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
GrammaTech/gtirb
415dd72e1e3c475004d013723c16cdcb29c0826e
python/gtirb/block.py
python
Block._add_to_uuid_cache
(self, cache: typing.Dict[UUID, Node])
Update the UUID cache when this node is added.
Update the UUID cache when this node is added.
[ "Update", "the", "UUID", "cache", "when", "this", "node", "is", "added", "." ]
def _add_to_uuid_cache(self, cache: typing.Dict[UUID, Node]) -> None: """Update the UUID cache when this node is added.""" cache[self.uuid] = self
[ "def", "_add_to_uuid_cache", "(", "self", ",", "cache", ":", "typing", ".", "Dict", "[", "UUID", ",", "Node", "]", ")", "->", "None", ":", "cache", "[", "self", ".", "uuid", "]", "=", "self" ]
https://github.com/GrammaTech/gtirb/blob/415dd72e1e3c475004d013723c16cdcb29c0826e/python/gtirb/block.py#L29-L32
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/convert_to_constants.py
python
_Convertible.converted_self
(self)
A copy of this Convertible to be modified during conversion. Returns: Implementations should return the copied instance, which in turn should be contained in converted_enclosing_graph(). This instance is the one that will be modified during conversion. Its main use will be in the implementations of convert_variable_to_constant().
A copy of this Convertible to be modified during conversion.
[ "A", "copy", "of", "this", "Convertible", "to", "be", "modified", "during", "conversion", "." ]
def converted_self(self): """A copy of this Convertible to be modified during conversion. Returns: Implementations should return the copied instance, which in turn should be contained in converted_enclosing_graph(). This instance is the one that will be modified during conversion. Its main use will be in the implementations of convert_variable_to_constant(). """ raise NotImplementedError
[ "def", "converted_self", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/convert_to_constants.py#L89-L98
RegrowthStudios/SoACode-Public
c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe
utils/git-hooks/cpplint/cpplint.py
python
ProcessLine
(filename, file_extension, clean_lines, line, include_state, function_state, class_state, error, extra_check_functions=[])
Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. class_state: A _ClassState instance which maintains information about the current stack of nested class declarations being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error
Processes a single line in the file.
[ "Processes", "a", "single", "line", "in", "the", "file", "." ]
def ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, class_state, error, extra_check_functions=[]): """Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. class_state: A _ClassState instance which maintains information about the current stack of nested class declarations being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[line], line, error) CheckForFunctionLengths(filename, clean_lines, line, function_state, error) CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) CheckStyle(filename, clean_lines, line, file_extension, class_state, error) CheckLanguage(filename, clean_lines, line, file_extension, include_state, error) CheckForNonStandardConstructs(filename, clean_lines, line, class_state, error) CheckPosixThreading(filename, clean_lines, line, error) CheckInvalidIncrement(filename, clean_lines, line, error) CheckMakePairUsesDeduction(filename, clean_lines, line, error) for check_fn in extra_check_functions: check_fn(filename, clean_lines, line, error)
[ "def", "ProcessLine", "(", "filename", ",", "file_extension", ",", "clean_lines", ",", "line", ",", "include_state", ",", "function_state", ",", "class_state", ",", "error", ",", "extra_check_functions", "=", "[", "]", ")", ":", "raw_lines", "=", "clean_lines", ...
https://github.com/RegrowthStudios/SoACode-Public/blob/c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe/utils/git-hooks/cpplint/cpplint.py#L3140-L3174
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
deprecated/demo/tutorial_7/multi_uavs_path_planning/px4_mavros_run_uav2.py
python
Px4Controller.__init__
(self)
ros subscribers
ros subscribers
[ "ros", "subscribers" ]
def __init__(self): self.imu = None self.gps = None self.local_pose = None self.current_state = None self.current_heading = None self.takeoff_height = 10 self.local_enu_position = None self.cur_target_pose = None self.global_target = None self.received_new_task = False self.arm_state = False self.offboard_state = False self.received_imu = False self.frame = "BODY" self.state = None ''' ros subscribers ''' self.local_pose_sub = rospy.Subscriber("/uav2/mavros/local_position/pose", PoseStamped, self.local_pose_callback) self.mavros_sub = rospy.Subscriber("/uav2/mavros/state", State, self.mavros_state_callback) self.gps_sub = rospy.Subscriber("/uav2/mavros/global_position/global", NavSatFix, self.gps_callback) self.imu_sub = rospy.Subscriber("/uav2/mavros/imu/data", Imu, self.imu_callback) self.set_target_position_sub = rospy.Subscriber("/uav2/gi/set_pose/position", PoseStamped, self.set_target_position_callback) self.set_target_yaw_sub = rospy.Subscriber("/uav2/gi/set_pose/orientation", Float32, self.set_target_yaw_callback) self.custom_activity_sub = rospy.Subscriber("/uav2/gi/set_activity/type", String, self.custom_activity_callback) ''' ros publishers ''' self.local_target_pub = rospy.Publisher('/uav2/mavros/setpoint_raw/local', PositionTarget, queue_size=10) ''' ros services ''' self.armService = rospy.ServiceProxy('/uav2/mavros/cmd/arming', CommandBool) self.flightModeService = rospy.ServiceProxy('/uav2/mavros/set_mode', SetMode) print("Px4 Controller Initialized!")
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "imu", "=", "None", "self", ".", "gps", "=", "None", "self", ".", "local_pose", "=", "None", "self", ".", "current_state", "=", "None", "self", ".", "current_heading", "=", "None", "self", ".", "...
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/demo/tutorial_7/multi_uavs_path_planning/px4_mavros_run_uav2.py#L15-L61
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozpack/mozjar.py
python
Deflater._compressed_size
(self)
return self.uncompressed_size
Return the real compressed size of the data written to the Deflater. If the Deflater is set not to compress, the uncompressed size is returned. Otherwise, the actual compressed size is returned, whether or not it is a win over the uncompressed size.
Return the real compressed size of the data written to the Deflater. If the Deflater is set not to compress, the uncompressed size is returned. Otherwise, the actual compressed size is returned, whether or not it is a win over the uncompressed size.
[ "Return", "the", "real", "compressed", "size", "of", "the", "data", "written", "to", "the", "Deflater", ".", "If", "the", "Deflater", "is", "set", "not", "to", "compress", "the", "uncompressed", "size", "is", "returned", ".", "Otherwise", "the", "actual", ...
def _compressed_size(self): ''' Return the real compressed size of the data written to the Deflater. If the Deflater is set not to compress, the uncompressed size is returned. Otherwise, the actual compressed size is returned, whether or not it is a win over the uncompressed size. ''' if self.compress: self._flush() return self._deflated.tell() return self.uncompressed_size
[ "def", "_compressed_size", "(", "self", ")", ":", "if", "self", ".", "compress", ":", "self", ".", "_flush", "(", ")", "return", "self", ".", "_deflated", ".", "tell", "(", ")", "return", "self", ".", "uncompressed_size" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozpack/mozjar.py#L701-L711
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
Grid.GetDefaultEditor
(*args, **kwargs)
return _grid.Grid_GetDefaultEditor(*args, **kwargs)
GetDefaultEditor(self) -> GridCellEditor
GetDefaultEditor(self) -> GridCellEditor
[ "GetDefaultEditor", "(", "self", ")", "-", ">", "GridCellEditor" ]
def GetDefaultEditor(*args, **kwargs): """GetDefaultEditor(self) -> GridCellEditor""" return _grid.Grid_GetDefaultEditor(*args, **kwargs)
[ "def", "GetDefaultEditor", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_GetDefaultEditor", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L2002-L2004
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/cephadm/box/util.py
python
Target.main
(self)
A target will be setup by first calling this main function where the parser is initialized.
A target will be setup by first calling this main function where the parser is initialized.
[ "A", "target", "will", "be", "setup", "by", "first", "calling", "this", "main", "function", "where", "the", "parser", "is", "initialized", "." ]
def main(self): """ A target will be setup by first calling this main function where the parser is initialized. """ args = self.parser.parse_args(self.argv) Config.add_args(vars(args)) function = getattr(self, args.action) function()
[ "def", "main", "(", "self", ")", ":", "args", "=", "self", ".", "parser", ".", "parse_args", "(", "self", ".", "argv", ")", "Config", ".", "add_args", "(", "vars", "(", "args", ")", ")", "function", "=", "getattr", "(", "self", ",", "args", ".", ...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/cephadm/box/util.py#L43-L51
vnpy/vnpy
f50f2535ed39dd33272e0985ed40c7078e4c19f6
vnpy/trader/gateway.py
python
BaseGateway.on_log
(self, log: LogData)
Log event push.
Log event push.
[ "Log", "event", "push", "." ]
def on_log(self, log: LogData) -> None: """ Log event push. """ self.on_event(EVENT_LOG, log)
[ "def", "on_log", "(", "self", ",", "log", ":", "LogData", ")", "->", "None", ":", "self", ".", "on_event", "(", "EVENT_LOG", ",", "log", ")" ]
https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/trader/gateway.py#L144-L148
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/containers.py
python
RepeatedCompositeFieldContainer.remove
(self, elem)
Removes an item from the list. Similar to list.remove().
Removes an item from the list. Similar to list.remove().
[ "Removes", "an", "item", "from", "the", "list", ".", "Similar", "to", "list", ".", "remove", "()", "." ]
def remove(self, elem): """Removes an item from the list. Similar to list.remove().""" self._values.remove(elem) self._message_listener.Modified()
[ "def", "remove", "(", "self", ",", "elem", ")", ":", "self", ".", "_values", ".", "remove", "(", "elem", ")", "self", ".", "_message_listener", ".", "Modified", "(", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/containers.py#L399-L402
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/sumolib/__init__.py
python
TeeFile.flush
(self)
flushes all file contents to disc
flushes all file contents to disc
[ "flushes", "all", "file", "contents", "to", "disc" ]
def flush(self): """flushes all file contents to disc""" for fp in self.files: fp.flush() if isinstance(fp, int) or hasattr(fp, "fileno"): try: os.fsync(fp) except OSError: pass
[ "def", "flush", "(", "self", ")", ":", "for", "fp", "in", "self", ".", "files", ":", "fp", ".", "flush", "(", ")", "if", "isinstance", "(", "fp", ",", "int", ")", "or", "hasattr", "(", "fp", ",", "\"fileno\"", ")", ":", "try", ":", "os", ".", ...
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/sumolib/__init__.py#L206-L214
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Engineering/gui/engineering_diffraction/tabs/common/vanadium_corrections.py
python
_calculate_vanadium_integral
(van_ws, run_no)
return ws_integ
Calculate the integral of the normalised vanadium workspace :param van_ws: Chosen vanadium run workspace :return: Integrated workspace
Calculate the integral of the normalised vanadium workspace :param van_ws: Chosen vanadium run workspace :return: Integrated workspace
[ "Calculate", "the", "integral", "of", "the", "normalised", "vanadium", "workspace", ":", "param", "van_ws", ":", "Chosen", "vanadium", "run", "workspace", ":", "return", ":", "Integrated", "workspace" ]
def _calculate_vanadium_integral(van_ws, run_no): # -> Workspace """ Calculate the integral of the normalised vanadium workspace :param van_ws: Chosen vanadium run workspace :return: Integrated workspace """ ws = NormaliseByCurrent(InputWorkspace=van_ws, OutputWorkspace=str(run_no) + "_" + INTEGRATED_WORKSPACE_NAME) # create new name ws here # sensitivity correction for van ws_integ = Integration(InputWorkspace=ws, OutputWorkspace=ws) ws_integ /= van_ws.blocksize() return ws_integ
[ "def", "_calculate_vanadium_integral", "(", "van_ws", ",", "run_no", ")", ":", "# -> Workspace", "ws", "=", "NormaliseByCurrent", "(", "InputWorkspace", "=", "van_ws", ",", "OutputWorkspace", "=", "str", "(", "run_no", ")", "+", "\"_\"", "+", "INTEGRATED_WORKSPACE...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Engineering/gui/engineering_diffraction/tabs/common/vanadium_corrections.py#L76-L86
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/syntax/synxml.py
python
EditraXml.LoadFromDisk
(self)
Load the object from from disk @precondition: path has been set @return: bool @todo: set error state on failed loads
Load the object from from disk @precondition: path has been set @return: bool @todo: set error state on failed loads
[ "Load", "the", "object", "from", "from", "disk", "@precondition", ":", "path", "has", "been", "set", "@return", ":", "bool", "@todo", ":", "set", "error", "state", "on", "failed", "loads" ]
def LoadFromDisk(self): """Load the object from from disk @precondition: path has been set @return: bool @todo: set error state on failed loads """ assert self.path is not None, "Must SetPath before calling Load" try: sax.parse(self.path, self) except (sax.SAXException, OSError, IOError, UnicodeDecodeError): self._ok = False return False else: self._ok = True return True
[ "def", "LoadFromDisk", "(", "self", ")", ":", "assert", "self", ".", "path", "is", "not", "None", ",", "\"Must SetPath before calling Load\"", "try", ":", "sax", ".", "parse", "(", "self", ".", "path", ",", "self", ")", "except", "(", "sax", ".", "SAXExc...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/synxml.py#L188-L203
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/training/checkpoint_management.py
python
remove_checkpoint
(checkpoint_prefix, checkpoint_format_version=saver_pb2.SaverDef.V2, meta_graph_suffix="meta")
Removes a checkpoint given by `checkpoint_prefix`. Args: checkpoint_prefix: The prefix of a V1 or V2 checkpoint. Typically the result of `Saver.save()` or that of `tf.train.latest_checkpoint()`, regardless of sharded/non-sharded or V1/V2. checkpoint_format_version: `SaverDef.CheckpointFormatVersion`, defaults to `SaverDef.V2`. meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'.
Removes a checkpoint given by `checkpoint_prefix`.
[ "Removes", "a", "checkpoint", "given", "by", "checkpoint_prefix", "." ]
def remove_checkpoint(checkpoint_prefix, checkpoint_format_version=saver_pb2.SaverDef.V2, meta_graph_suffix="meta"): """Removes a checkpoint given by `checkpoint_prefix`. Args: checkpoint_prefix: The prefix of a V1 or V2 checkpoint. Typically the result of `Saver.save()` or that of `tf.train.latest_checkpoint()`, regardless of sharded/non-sharded or V1/V2. checkpoint_format_version: `SaverDef.CheckpointFormatVersion`, defaults to `SaverDef.V2`. meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'. """ _delete_file_if_exists( meta_graph_filename(checkpoint_prefix, meta_graph_suffix)) if checkpoint_format_version == saver_pb2.SaverDef.V2: # V2 has a metadata file and some data files. _delete_file_if_exists(checkpoint_prefix + ".index") _delete_file_if_exists(checkpoint_prefix + ".data-?????-of-?????") else: # V1, Legacy. Exact match on the data file. _delete_file_if_exists(checkpoint_prefix)
[ "def", "remove_checkpoint", "(", "checkpoint_prefix", ",", "checkpoint_format_version", "=", "saver_pb2", ".", "SaverDef", ".", "V2", ",", "meta_graph_suffix", "=", "\"meta\"", ")", ":", "_delete_file_if_exists", "(", "meta_graph_filename", "(", "checkpoint_prefix", ","...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/checkpoint_management.py#L460-L481
bingwin/MicroChat
81d9a71a212c1cbca5bba497ec42659a7d25dccf
mars/lint/cpplint.py
python
NestingState.InnermostClass
(self)
return None
Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise.
Get class info on the top of the stack.
[ "Get", "class", "info", "on", "the", "top", "of", "the", "stack", "." ]
def InnermostClass(self): """Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise. """ for i in range(len(self.stack), 0, -1): classinfo = self.stack[i - 1] if isinstance(classinfo, _ClassInfo): return classinfo return None
[ "def", "InnermostClass", "(", "self", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "stack", ")", ",", "0", ",", "-", "1", ")", ":", "classinfo", "=", "self", ".", "stack", "[", "i", "-", "1", "]", "if", "isinstance", "(", ...
https://github.com/bingwin/MicroChat/blob/81d9a71a212c1cbca5bba497ec42659a7d25dccf/mars/lint/cpplint.py#L2544-L2554
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/mongosymb.py
python
PathResolver.url_to_filename
(url: str)
return url.split('/')[-1]
Convert URL to local filename. :param url: download URL :return: full name for local file
Convert URL to local filename.
[ "Convert", "URL", "to", "local", "filename", "." ]
def url_to_filename(url: str) -> str: """ Convert URL to local filename. :param url: download URL :return: full name for local file """ return url.split('/')[-1]
[ "def", "url_to_filename", "(", "url", ":", "str", ")", "->", "str", ":", "return", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/mongosymb.py#L261-L268
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/engine/validators.py
python
check_textfiledataset
(method)
return new_method
A wrapper that wraps a parameter checker around the original Dataset(TextFileDataset).
A wrapper that wraps a parameter checker around the original Dataset(TextFileDataset).
[ "A", "wrapper", "that", "wraps", "a", "parameter", "checker", "around", "the", "original", "Dataset", "(", "TextFileDataset", ")", "." ]
def check_textfiledataset(method): """A wrapper that wraps a parameter checker around the original Dataset(TextFileDataset).""" @wraps(method) def new_method(self, *args, **kwargs): _, param_dict = parse_user_args(method, *args, **kwargs) nreq_param_int = ['num_samples', 'num_parallel_workers', 'num_shards', 'shard_id'] dataset_files = param_dict.get('dataset_files') type_check(dataset_files, (str, list), "dataset files") validate_dataset_param_value(nreq_param_int, param_dict, int) check_sampler_shuffle_shard_options(param_dict) cache = param_dict.get('cache') check_cache_option(cache) return method(self, *args, **kwargs) return new_method
[ "def", "check_textfiledataset", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "new_method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_", ",", "param_dict", "=", "parse_user_args", "(", "method", ",", "*", ...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/validators.py#L1464-L1483
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/psutil/psutil/_pslinux.py
python
_get_cputimes_ntuple
()
return (namedtuple('cputimes', ' '.join(fields)), rindex)
Return a (nt, rindex) tuple depending on the CPU times available on this Linux kernel version which may be: user, nice, system, idle, iowait, irq, softirq [steal, [guest, [guest_nice]]]
Return a (nt, rindex) tuple depending on the CPU times available on this Linux kernel version which may be: user, nice, system, idle, iowait, irq, softirq [steal, [guest, [guest_nice]]]
[ "Return", "a", "(", "nt", "rindex", ")", "tuple", "depending", "on", "the", "CPU", "times", "available", "on", "this", "Linux", "kernel", "version", "which", "may", "be", ":", "user", "nice", "system", "idle", "iowait", "irq", "softirq", "[", "steal", "[...
def _get_cputimes_ntuple(): """ Return a (nt, rindex) tuple depending on the CPU times available on this Linux kernel version which may be: user, nice, system, idle, iowait, irq, softirq [steal, [guest, [guest_nice]]] """ f = open('/proc/stat', 'r') try: values = f.readline().split()[1:] finally: f.close() fields = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq'] rindex = 8 vlen = len(values) if vlen >= 8: # Linux >= 2.6.11 fields.append('steal') rindex += 1 if vlen >= 9: # Linux >= 2.6.24 fields.append('guest') rindex += 1 if vlen >= 10: # Linux >= 3.2.0 fields.append('guest_nice') rindex += 1 return (namedtuple('cputimes', ' '.join(fields)), rindex)
[ "def", "_get_cputimes_ntuple", "(", ")", ":", "f", "=", "open", "(", "'/proc/stat'", ",", "'r'", ")", "try", ":", "values", "=", "f", ".", "readline", "(", ")", ".", "split", "(", ")", "[", "1", ":", "]", "finally", ":", "f", ".", "close", "(", ...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/psutil/psutil/_pslinux.py#L214-L239
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/saver.py
python
BaseSaverBuilder._AddRestoreOps
(self, filename_tensor, saveables, restore_sequentially, reshape, preferred_shard=-1, name="restore_all")
return control_flow_ops.group(*assign_ops, name=name)
Add operations to restore saveables. Args: filename_tensor: Tensor for the path of the file to load. saveables: A list of SaveableObject objects. restore_sequentially: True if we want to restore variables sequentially within a shard. reshape: True if we want to reshape loaded tensors to the shape of the corresponding variable. preferred_shard: Shard to open first when loading a sharded file. name: Name for the returned op. Returns: An Operation that restores the variables.
Add operations to restore saveables.
[ "Add", "operations", "to", "restore", "saveables", "." ]
def _AddRestoreOps(self, filename_tensor, saveables, restore_sequentially, reshape, preferred_shard=-1, name="restore_all"): """Add operations to restore saveables. Args: filename_tensor: Tensor for the path of the file to load. saveables: A list of SaveableObject objects. restore_sequentially: True if we want to restore variables sequentially within a shard. reshape: True if we want to reshape loaded tensors to the shape of the corresponding variable. preferred_shard: Shard to open first when loading a sharded file. name: Name for the returned op. Returns: An Operation that restores the variables. """ all_tensors = self.bulk_restore(filename_tensor, saveables, preferred_shard, restore_sequentially) assign_ops = [] idx = 0 # Load and optionally reshape on the CPU, as string tensors are not # available on the GPU. # TODO(touts): Re-enable restore on GPU when we can support annotating # string tensors as "HostMemory" inputs. for saveable in saveables: shapes = None if reshape: # Compute the shapes, let the restore op decide if and how to do # the reshape. shapes = [] for spec in saveable.specs: v = spec.tensor shape = v.get_shape() if not shape.is_fully_defined(): shape = array_ops.shape(v) shapes.append(shape) saveable_tensors = all_tensors[idx:idx + len(saveable.specs)] idx += len(saveable.specs) assign_ops.append(saveable.restore(saveable_tensors, shapes)) # Create a Noop that has control dependencies from all the updates. return control_flow_ops.group(*assign_ops, name=name)
[ "def", "_AddRestoreOps", "(", "self", ",", "filename_tensor", ",", "saveables", ",", "restore_sequentially", ",", "reshape", ",", "preferred_shard", "=", "-", "1", ",", "name", "=", "\"restore_all\"", ")", ":", "all_tensors", "=", "self", ".", "bulk_restore", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/saver.py#L305-L353
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/install.py
python
scons_copytree
(src, dst, symlinks=False)
Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an CopytreeError is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. XXX Consider this example code rather than the ultimate tool.
Recursively copy a directory tree using copy2().
[ "Recursively", "copy", "a", "directory", "tree", "using", "copy2", "()", "." ]
def scons_copytree(src, dst, symlinks=False): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an CopytreeError is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. XXX Consider this example code rather than the ultimate tool. """ names = os.listdir(src) # garyo@genarts.com fix: check for dir before making dirs. if not os.path.exists(dst): os.makedirs(dst) errors = [] for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): scons_copytree(srcname, dstname, symlinks) else: shutil.copy2(srcname, dstname) # XXX What about devices, sockets etc.? except (IOError, os.error), why: errors.append((srcname, dstname, str(why))) # catch the CopytreeError from the recursive copytree so that we can # continue with other files except CopytreeError, err: errors.extend(err.args[0]) try: shutil.copystat(src, dst) except SCons.Util.WinError: # can't copy file access times on Windows pass except OSError, why: errors.extend((src, dst, str(why))) if errors: raise CopytreeError, errors
[ "def", "scons_copytree", "(", "src", ",", "dst", ",", "symlinks", "=", "False", ")", ":", "names", "=", "os", ".", "listdir", "(", "src", ")", "# garyo@genarts.com fix: check for dir before making dirs.", "if", "not", "os", ".", "path", ".", "exists", "(", "...
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/install.py#L55-L100
jackaudio/jack2
21b293dbc37d42446141a08922cdec0d2550c6a0
waflib/Tools/gxx.py
python
gxx_modifier_cygwin
(conf)
Configuration flags for executing g++ on Cygwin
Configuration flags for executing g++ on Cygwin
[ "Configuration", "flags", "for", "executing", "g", "++", "on", "Cygwin" ]
def gxx_modifier_cygwin(conf): """Configuration flags for executing g++ on Cygwin""" gxx_modifier_win32(conf) v = conf.env v.cxxshlib_PATTERN = 'cyg%s.dll' v.append_value('LINKFLAGS_cxxshlib', ['-Wl,--enable-auto-image-base']) v.CXXFLAGS_cxxshlib = []
[ "def", "gxx_modifier_cygwin", "(", "conf", ")", ":", "gxx_modifier_win32", "(", "conf", ")", "v", "=", "conf", ".", "env", "v", ".", "cxxshlib_PATTERN", "=", "'cyg%s.dll'", "v", ".", "append_value", "(", "'LINKFLAGS_cxxshlib'", ",", "[", "'-Wl,--enable-auto-imag...
https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Tools/gxx.py#L82-L88
acbull/Unbiased_LambdaMart
7c39abe5caa18ca07df2d23c2db392916d92956c
Unbias_LightGBM/python-package/lightgbm/basic.py
python
Dataset.get_init_score
(self)
return self.init_score
Get the initial score of the Dataset. Returns ------- init_score : numpy array Init score of Booster.
Get the initial score of the Dataset.
[ "Get", "the", "initial", "score", "of", "the", "Dataset", "." ]
def get_init_score(self): """Get the initial score of the Dataset. Returns ------- init_score : numpy array Init score of Booster. """ if self.init_score is None: self.init_score = self.get_field('init_score') return self.init_score
[ "def", "get_init_score", "(", "self", ")", ":", "if", "self", ".", "init_score", "is", "None", ":", "self", ".", "init_score", "=", "self", ".", "get_field", "(", "'init_score'", ")", "return", "self", ".", "init_score" ]
https://github.com/acbull/Unbiased_LambdaMart/blob/7c39abe5caa18ca07df2d23c2db392916d92956c/Unbias_LightGBM/python-package/lightgbm/basic.py#L1175-L1185
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/emxccompiler.py
python
get_versions
()
return (gcc_version, ld_version)
Try to find out the versions of gcc and ld. If not possible it returns None for it.
Try to find out the versions of gcc and ld. If not possible it returns None for it.
[ "Try", "to", "find", "out", "the", "versions", "of", "gcc", "and", "ld", ".", "If", "not", "possible", "it", "returns", "None", "for", "it", "." ]
def get_versions(): """ Try to find out the versions of gcc and ld. If not possible it returns None for it. """ from distutils.version import StrictVersion from distutils.spawn import find_executable import re gcc_exe = find_executable('gcc') if gcc_exe: out = os.popen(gcc_exe + ' -dumpversion','r') try: out_string = out.read() finally: out.close() result = re.search('(\d+\.\d+\.\d+)',out_string) if result: gcc_version = StrictVersion(result.group(1)) else: gcc_version = None else: gcc_version = None # EMX ld has no way of reporting version number, and we use GCC # anyway - so we can link OMF DLLs ld_version = None return (gcc_version, ld_version)
[ "def", "get_versions", "(", ")", ":", "from", "distutils", ".", "version", "import", "StrictVersion", "from", "distutils", ".", "spawn", "import", "find_executable", "import", "re", "gcc_exe", "=", "find_executable", "(", "'gcc'", ")", "if", "gcc_exe", ":", "o...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/emxccompiler.py#L294-L319
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/s3a_hadoop.py
python
install_prereq
(client)
Install pre requisites for RHEL and CentOS TBD: Ubuntu
Install pre requisites for RHEL and CentOS TBD: Ubuntu
[ "Install", "pre", "requisites", "for", "RHEL", "and", "CentOS", "TBD", ":", "Ubuntu" ]
def install_prereq(client): """ Install pre requisites for RHEL and CentOS TBD: Ubuntu """ if client.os.name == 'rhel' or client.os.name == 'centos': client.run( args=[ 'sudo', 'yum', 'install', '-y', 'protobuf-c.x86_64', 'java', 'java-1.8.0-openjdk-devel', 'dnsmasq' ] )
[ "def", "install_prereq", "(", "client", ")", ":", "if", "client", ".", "os", ".", "name", "==", "'rhel'", "or", "client", ".", "os", ".", "name", "==", "'centos'", ":", "client", ".", "run", "(", "args", "=", "[", "'sudo'", ",", "'yum'", ",", "'ins...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/s3a_hadoop.py#L106-L123
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/pydoc.py
python
HTMLDoc.namelink
(self, name, *dicts)
return name
Make a link for an identifier, given name-to-URL mappings.
Make a link for an identifier, given name-to-URL mappings.
[ "Make", "a", "link", "for", "an", "identifier", "given", "name", "-", "to", "-", "URL", "mappings", "." ]
def namelink(self, name, *dicts): """Make a link for an identifier, given name-to-URL mappings.""" for dict in dicts: if name in dict: return '<a href="%s">%s</a>' % (dict[name], name) return name
[ "def", "namelink", "(", "self", ",", "name", ",", "*", "dicts", ")", ":", "for", "dict", "in", "dicts", ":", "if", "name", "in", "dict", ":", "return", "'<a href=\"%s\">%s</a>'", "%", "(", "dict", "[", "name", "]", ",", "name", ")", "return", "name" ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pydoc.py#L549-L554
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/cookies.py
python
RequestsCookieJar.list_paths
(self)
return paths
Utility method to list all the paths in the jar.
Utility method to list all the paths in the jar.
[ "Utility", "method", "to", "list", "all", "the", "paths", "in", "the", "jar", "." ]
def list_paths(self): """Utility method to list all the paths in the jar.""" paths = [] for cookie in iter(self): if cookie.path not in paths: paths.append(cookie.path) return paths
[ "def", "list_paths", "(", "self", ")", ":", "paths", "=", "[", "]", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "path", "not", "in", "paths", ":", "paths", ".", "append", "(", "cookie", ".", "path", ")", "return", "...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/cookies.py#L247-L253
baidu/AnyQ
d94d450d2aaa5f7ed73424b10aa4539835b97527
tools/simnet/preprocess/operation_unit.py
python
BaseOperation.operate
(self, prev_op_out)
run
run
[ "run" ]
def operate(self, prev_op_out): """ run """ raise NotImplementedError("operate method must be implemented.")
[ "def", "operate", "(", "self", ",", "prev_op_out", ")", ":", "raise", "NotImplementedError", "(", "\"operate method must be implemented.\"", ")" ]
https://github.com/baidu/AnyQ/blob/d94d450d2aaa5f7ed73424b10aa4539835b97527/tools/simnet/preprocess/operation_unit.py#L45-L49
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/shapedbutton.py
python
SButton.OnLeftDown
(self, event)
Handles the ``wx.EVT_LEFT_DOWN`` event for :class:`SButton`. :param `event`: a :class:`MouseEvent` event to be processed.
Handles the ``wx.EVT_LEFT_DOWN`` event for :class:`SButton`.
[ "Handles", "the", "wx", ".", "EVT_LEFT_DOWN", "event", "for", ":", "class", ":", "SButton", "." ]
def OnLeftDown(self, event): """ Handles the ``wx.EVT_LEFT_DOWN`` event for :class:`SButton`. :param `event`: a :class:`MouseEvent` event to be processed. """ if not self.IsEnabled(): return x, y = (event.GetX(), event.GetY()) if self.IsOutside(x,y): return self._isup = False if not self.HasCapture(): self.CaptureMouse() self.SetFocus() self.Refresh() event.Skip()
[ "def", "OnLeftDown", "(", "self", ",", "event", ")", ":", "if", "not", "self", ".", "IsEnabled", "(", ")", ":", "return", "x", ",", "y", "=", "(", "event", ".", "GetX", "(", ")", ",", "event", ".", "GetY", "(", ")", ")", "if", "self", ".", "I...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/shapedbutton.py#L750-L773
wujian16/Cornell-MOE
df299d1be882d2af9796d7a68b3f9505cac7a53e
moe/optimal_learning/python/cpp_wrappers/optimization.py
python
NullOptimizer.__init__
(self, domain, optimizable, optimizer_parameters, num_random_samples=None)
Construct a NullOptimizer. :param domain: the domain that this optimizer operates over :type domain: interfaces.domain_interface.DomainInterface subclass :param optimizable: object representing the objective function being optimized :type optimizable: interfaces.optimization_interface.OptimizableInterface subclass :param optimizer_parameters: None :type optimizer_parameters: None :params num_random_samples: number of random samples to use if performing 'dumb' search :type num_random_sampes: int >= 0
Construct a NullOptimizer.
[ "Construct", "a", "NullOptimizer", "." ]
def __init__(self, domain, optimizable, optimizer_parameters, num_random_samples=None): """Construct a NullOptimizer. :param domain: the domain that this optimizer operates over :type domain: interfaces.domain_interface.DomainInterface subclass :param optimizable: object representing the objective function being optimized :type optimizable: interfaces.optimization_interface.OptimizableInterface subclass :param optimizer_parameters: None :type optimizer_parameters: None :params num_random_samples: number of random samples to use if performing 'dumb' search :type num_random_sampes: int >= 0 """ self.domain = domain self.objective_function = optimizable self.optimizer_type = C_GP.OptimizerTypes.null self.optimizer_parameters = _CppOptimizerParameters( domain_type=domain._domain_type, objective_type=optimizable.objective_type, optimizer_type=self.optimizer_type, num_random_samples=num_random_samples, optimizer_parameters=None, )
[ "def", "__init__", "(", "self", ",", "domain", ",", "optimizable", ",", "optimizer_parameters", ",", "num_random_samples", "=", "None", ")", ":", "self", ".", "domain", "=", "domain", "self", ".", "objective_function", "=", "optimizable", "self", ".", "optimiz...
https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/cpp_wrappers/optimization.py#L375-L397
protocolbuffers/protobuf
b5ab0b7a18b7336c60130f4ddb2d97c51792f896
python/google/protobuf/text_format.py
python
_Printer.__init__
( self, out, indent=0, as_utf8=False, as_one_line=False, use_short_repeated_primitives=False, pointy_brackets=False, use_index_order=False, float_format=None, double_format=None, use_field_number=False, descriptor_pool=None, message_formatter=None, print_unknown_fields=False, force_colon=False)
Initialize the Printer. Double values can be formatted compactly with 15 digits of precision (which is the most that IEEE 754 "double" can guarantee) using double_format='.15g'. To ensure that converting to text and back to a proto will result in an identical value, double_format='.17g' should be used. Args: out: To record the text format result. indent: The initial indent level for pretty print. as_utf8: Return unescaped Unicode for non-ASCII characters. In Python 3 actual Unicode characters may appear as is in strings. In Python 2 the return value will be valid UTF-8 rather than ASCII. as_one_line: Don't introduce newlines between fields. use_short_repeated_primitives: Use short repeated format for primitives. pointy_brackets: If True, use angle brackets instead of curly braces for nesting. use_index_order: If True, print fields of a proto message using the order defined in source code instead of the field number. By default, use the field number order. float_format: If set, use this to specify float field formatting (per the "Format Specification Mini-Language"); otherwise, shortest float that has same value in wire will be printed. Also affect double field if double_format is not set but float_format is set. double_format: If set, use this to specify double field formatting (per the "Format Specification Mini-Language"); if it is not set but float_format is set, use float_format. Otherwise, str() is used. use_field_number: If True, print field numbers instead of names. descriptor_pool: A DescriptorPool used to resolve Any types. message_formatter: A function(message, indent, as_one_line): unicode|None to custom format selected sub-messages (usually based on message type). Use to pretty print parts of the protobuf for easier diffing. print_unknown_fields: If True, unknown fields will be printed. force_colon: If set, a colon will be added after the field name even if the field is a proto message.
Initialize the Printer.
[ "Initialize", "the", "Printer", "." ]
def __init__( self, out, indent=0, as_utf8=False, as_one_line=False, use_short_repeated_primitives=False, pointy_brackets=False, use_index_order=False, float_format=None, double_format=None, use_field_number=False, descriptor_pool=None, message_formatter=None, print_unknown_fields=False, force_colon=False): """Initialize the Printer. Double values can be formatted compactly with 15 digits of precision (which is the most that IEEE 754 "double" can guarantee) using double_format='.15g'. To ensure that converting to text and back to a proto will result in an identical value, double_format='.17g' should be used. Args: out: To record the text format result. indent: The initial indent level for pretty print. as_utf8: Return unescaped Unicode for non-ASCII characters. In Python 3 actual Unicode characters may appear as is in strings. In Python 2 the return value will be valid UTF-8 rather than ASCII. as_one_line: Don't introduce newlines between fields. use_short_repeated_primitives: Use short repeated format for primitives. pointy_brackets: If True, use angle brackets instead of curly braces for nesting. use_index_order: If True, print fields of a proto message using the order defined in source code instead of the field number. By default, use the field number order. float_format: If set, use this to specify float field formatting (per the "Format Specification Mini-Language"); otherwise, shortest float that has same value in wire will be printed. Also affect double field if double_format is not set but float_format is set. double_format: If set, use this to specify double field formatting (per the "Format Specification Mini-Language"); if it is not set but float_format is set, use float_format. Otherwise, str() is used. use_field_number: If True, print field numbers instead of names. descriptor_pool: A DescriptorPool used to resolve Any types. message_formatter: A function(message, indent, as_one_line): unicode|None to custom format selected sub-messages (usually based on message type). Use to pretty print parts of the protobuf for easier diffing. print_unknown_fields: If True, unknown fields will be printed. force_colon: If set, a colon will be added after the field name even if the field is a proto message. """ self.out = out self.indent = indent self.as_utf8 = as_utf8 self.as_one_line = as_one_line self.use_short_repeated_primitives = use_short_repeated_primitives self.pointy_brackets = pointy_brackets self.use_index_order = use_index_order self.float_format = float_format if double_format is not None: self.double_format = double_format else: self.double_format = float_format self.use_field_number = use_field_number self.descriptor_pool = descriptor_pool self.message_formatter = message_formatter self.print_unknown_fields = print_unknown_fields self.force_colon = force_colon
[ "def", "__init__", "(", "self", ",", "out", ",", "indent", "=", "0", ",", "as_utf8", "=", "False", ",", "as_one_line", "=", "False", ",", "use_short_repeated_primitives", "=", "False", ",", "pointy_brackets", "=", "False", ",", "use_index_order", "=", "False...
https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/text_format.py#L323-L391
MVIG-SJTU/RMPE
5188c230ec800c12be7369c3619615bc9b020aa4
tools/extra/extract_seconds.py
python
get_start_time
(line_iterable, year)
return start_datetime
Find start time from group of lines
Find start time from group of lines
[ "Find", "start", "time", "from", "group", "of", "lines" ]
def get_start_time(line_iterable, year): """Find start time from group of lines """ start_datetime = None for line in line_iterable: line = line.strip() if line.find('Solving') != -1: start_datetime = extract_datetime_from_line(line, year) break return start_datetime
[ "def", "get_start_time", "(", "line_iterable", ",", "year", ")", ":", "start_datetime", "=", "None", "for", "line", "in", "line_iterable", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ".", "find", "(", "'Solving'", ")", "!=", "-", "1...
https://github.com/MVIG-SJTU/RMPE/blob/5188c230ec800c12be7369c3619615bc9b020aa4/tools/extra/extract_seconds.py#L31-L41
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/lite/tutorials/dataset.py
python
read32
(bytestream)
return np.frombuffer(bytestream.read(4), dtype=dt)[0]
Read 4 bytes from bytestream as an unsigned 32-bit integer.
Read 4 bytes from bytestream as an unsigned 32-bit integer.
[ "Read", "4", "bytes", "from", "bytestream", "as", "an", "unsigned", "32", "-", "bit", "integer", "." ]
def read32(bytestream): """Read 4 bytes from bytestream as an unsigned 32-bit integer.""" dt = np.dtype(np.uint32).newbyteorder('>') return np.frombuffer(bytestream.read(4), dtype=dt)[0]
[ "def", "read32", "(", "bytestream", ")", ":", "dt", "=", "np", ".", "dtype", "(", "np", ".", "uint32", ")", ".", "newbyteorder", "(", "'>'", ")", "return", "np", ".", "frombuffer", "(", "bytestream", ".", "read", "(", "4", ")", ",", "dtype", "=", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/tutorials/dataset.py#L31-L34
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextBuffer.__init__
(self, *args, **kwargs)
__init__(self) -> RichTextBuffer This is a kind of box, used to represent the whole buffer.
__init__(self) -> RichTextBuffer
[ "__init__", "(", "self", ")", "-", ">", "RichTextBuffer" ]
def __init__(self, *args, **kwargs): """ __init__(self) -> RichTextBuffer This is a kind of box, used to represent the whole buffer. """ _richtext.RichTextBuffer_swiginit(self,_richtext.new_RichTextBuffer(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_richtext", ".", "RichTextBuffer_swiginit", "(", "self", ",", "_richtext", ".", "new_RichTextBuffer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2200-L2206
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/ma/mrecords.py
python
_mrreconstruct
(subtype, baseclass, baseshape, basetype,)
return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype,)
Build a new MaskedArray from the information stored in a pickle.
Build a new MaskedArray from the information stored in a pickle.
[ "Build", "a", "new", "MaskedArray", "from", "the", "information", "stored", "in", "a", "pickle", "." ]
def _mrreconstruct(subtype, baseclass, baseshape, basetype,): """ Build a new MaskedArray from the information stored in a pickle. """ _data = ndarray.__new__(baseclass, baseshape, basetype).view(subtype) _mask = ndarray.__new__(ndarray, baseshape, 'b1') return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype,)
[ "def", "_mrreconstruct", "(", "subtype", ",", "baseclass", ",", "baseshape", ",", "basetype", ",", ")", ":", "_data", "=", "ndarray", ".", "__new__", "(", "baseclass", ",", "baseshape", ",", "basetype", ")", ".", "view", "(", "subtype", ")", "_mask", "="...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/ma/mrecords.py#L489-L496
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/ccompiler.py
python
CCompiler._compile
(self, obj, src, ext, cc_args, extra_postargs, pp_opts)
Compile 'src' to product 'obj'.
Compile 'src' to product 'obj'.
[ "Compile", "src", "to", "product", "obj", "." ]
def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): """Compile 'src' to product 'obj'.""" # A concrete compiler class that does not override compile() # should implement _compile(). pass
[ "def", "_compile", "(", "self", ",", "obj", ",", "src", ",", "ext", ",", "cc_args", ",", "extra_postargs", ",", "pp_opts", ")", ":", "# A concrete compiler class that does not override compile()", "# should implement _compile().", "pass" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/ccompiler.py#L579-L584
tensorflow/io
92b44e180674a8af0e12e405530f7343e3e693e4
tensorflow_io/python/ops/hdf5_io_tensor_ops.py
python
BaseHDF5GraphIOTensor.dtype
(self)
return self._dtype
Returns the `dtype` of elements in the tensor.
Returns the `dtype` of elements in the tensor.
[ "Returns", "the", "dtype", "of", "elements", "in", "the", "tensor", "." ]
def dtype(self): """Returns the `dtype` of elements in the tensor.""" return self._dtype
[ "def", "dtype", "(", "self", ")", ":", "return", "self", ".", "_dtype" ]
https://github.com/tensorflow/io/blob/92b44e180674a8af0e12e405530f7343e3e693e4/tensorflow_io/python/ops/hdf5_io_tensor_ops.py#L47-L49
eProsima/Fast-DDS
6639a84b7855e8fda66a4afb541326ef22f8c727
tools/fastdds/shm/clean.py
python
Clean.__shm_dir
(self)
return shm_path
Calculate the shm directory. returns Path: The path to the platform specific the SHM directory
Calculate the shm directory.
[ "Calculate", "the", "shm", "directory", "." ]
def __shm_dir(self): """ Calculate the shm directory. returns Path: The path to the platform specific the SHM directory """ # Windows if os.name == 'nt': shm_path = Path('c:\\programdata\\eprosima\\' 'fastrtps_interprocess\\').resolve() elif os.name == 'posix': # MAC if platform.mac_ver()[0] != '': shm_path = Path('/private/tmp/boost_interprocess/').resolve() # Linux else: shm_path = Path('/dev/shm/').resolve() else: raise RuntimeError(f'{os.name} not supported') return shm_path
[ "def", "__shm_dir", "(", "self", ")", ":", "# Windows", "if", "os", ".", "name", "==", "'nt'", ":", "shm_path", "=", "Path", "(", "'c:\\\\programdata\\\\eprosima\\\\'", "'fastrtps_interprocess\\\\'", ")", ".", "resolve", "(", ")", "elif", "os", ".", "name", ...
https://github.com/eProsima/Fast-DDS/blob/6639a84b7855e8fda66a4afb541326ef22f8c727/tools/fastdds/shm/clean.py#L55-L77
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/dtypes/common.py
python
_is_dtype_type
(arr_or_dtype, condition)
return condition(tipo)
Return a boolean if the condition is satisfied for the arr_or_dtype. Parameters ---------- arr_or_dtype : array-like The array-like or dtype object whose dtype we want to extract. condition : callable[Union[np.dtype, ExtensionDtypeType]] Returns ------- bool : if the condition is satisifed for the arr_or_dtype
Return a boolean if the condition is satisfied for the arr_or_dtype.
[ "Return", "a", "boolean", "if", "the", "condition", "is", "satisfied", "for", "the", "arr_or_dtype", "." ]
def _is_dtype_type(arr_or_dtype, condition): """ Return a boolean if the condition is satisfied for the arr_or_dtype. Parameters ---------- arr_or_dtype : array-like The array-like or dtype object whose dtype we want to extract. condition : callable[Union[np.dtype, ExtensionDtypeType]] Returns ------- bool : if the condition is satisifed for the arr_or_dtype """ if arr_or_dtype is None: return condition(type(None)) # fastpath if isinstance(arr_or_dtype, np.dtype): return condition(arr_or_dtype.type) elif isinstance(arr_or_dtype, type): if issubclass(arr_or_dtype, (PandasExtensionDtype, ExtensionDtype)): arr_or_dtype = arr_or_dtype.type return condition(np.dtype(arr_or_dtype).type) elif arr_or_dtype is None: return condition(type(None)) # if we have an array-like if hasattr(arr_or_dtype, 'dtype'): arr_or_dtype = arr_or_dtype.dtype # we are not possibly a dtype elif is_list_like(arr_or_dtype): return condition(type(None)) try: tipo = pandas_dtype(arr_or_dtype).type except (TypeError, ValueError, UnicodeEncodeError): if is_scalar(arr_or_dtype): return condition(type(None)) return False return condition(tipo)
[ "def", "_is_dtype_type", "(", "arr_or_dtype", ",", "condition", ")", ":", "if", "arr_or_dtype", "is", "None", ":", "return", "condition", "(", "type", "(", "None", ")", ")", "# fastpath", "if", "isinstance", "(", "arr_or_dtype", ",", "np", ".", "dtype", ")...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/dtypes/common.py#L1845-L1889
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/variables.py
python
_has_cycle
(op, state)
return False
Detect cycles in the dependencies of `initial_value`.
Detect cycles in the dependencies of `initial_value`.
[ "Detect", "cycles", "in", "the", "dependencies", "of", "initial_value", "." ]
def _has_cycle(op, state): """Detect cycles in the dependencies of `initial_value`.""" op_state = state.get(op.name, _UNKNOWN) if op_state == _STARTED: return True elif op_state == _FINISHED: return False state[op.name] = _STARTED for i in itertools.chain((i.op for i in op.inputs), op.control_inputs): if _has_cycle(i, state): return True state[op.name] = _FINISHED return False
[ "def", "_has_cycle", "(", "op", ",", "state", ")", ":", "op_state", "=", "state", ".", "get", "(", "op", ".", "name", ",", "_UNKNOWN", ")", "if", "op_state", "==", "_STARTED", ":", "return", "True", "elif", "op_state", "==", "_FINISHED", ":", "return",...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/variables.py#L2717-L2730
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/seq2seq/python/ops/beam_search_decoder.py
python
BeamSearchDecoder.finalize
(self, outputs, final_state, sequence_lengths)
return outputs, final_state
Finalize and return the predicted_ids. Args: outputs: An instance of BeamSearchDecoderOutput. final_state: An instance of BeamSearchDecoderState. Passed through to the output. sequence_lengths: An `int32` tensor shaped `[batch_size, beam_width]`. The sequence lengths determined for each beam during decode. Returns: outputs: An instance of FinalBeamSearchDecoderOutput where the predicted_ids are the result of calling _gather_tree. final_state: The same input instance of BeamSearchDecoderState.
Finalize and return the predicted_ids.
[ "Finalize", "and", "return", "the", "predicted_ids", "." ]
def finalize(self, outputs, final_state, sequence_lengths): """Finalize and return the predicted_ids. Args: outputs: An instance of BeamSearchDecoderOutput. final_state: An instance of BeamSearchDecoderState. Passed through to the output. sequence_lengths: An `int32` tensor shaped `[batch_size, beam_width]`. The sequence lengths determined for each beam during decode. Returns: outputs: An instance of FinalBeamSearchDecoderOutput where the predicted_ids are the result of calling _gather_tree. final_state: The same input instance of BeamSearchDecoderState. """ predicted_ids = beam_search_ops.gather_tree( outputs.predicted_ids, outputs.parent_ids, sequence_length=sequence_lengths) outputs = FinalBeamSearchDecoderOutput( beam_search_decoder_output=outputs, predicted_ids=predicted_ids) return outputs, final_state
[ "def", "finalize", "(", "self", ",", "outputs", ",", "final_state", ",", "sequence_lengths", ")", ":", "predicted_ids", "=", "beam_search_ops", ".", "gather_tree", "(", "outputs", ".", "predicted_ids", ",", "outputs", ".", "parent_ids", ",", "sequence_length", "...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/seq2seq/python/ops/beam_search_decoder.py#L263-L283
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/learn/python/learn/utils/gc.py
python
union
(lf, rf)
return keep
Creates a filter that keeps the union of two filters. Args: lf: first filter rf: second filter Returns: A filter function that keeps the n largest paths.
Creates a filter that keeps the union of two filters.
[ "Creates", "a", "filter", "that", "keeps", "the", "union", "of", "two", "filters", "." ]
def union(lf, rf): """Creates a filter that keeps the union of two filters. Args: lf: first filter rf: second filter Returns: A filter function that keeps the n largest paths. """ def keep(paths): l = set(lf(paths)) r = set(rf(paths)) return sorted(list(l|r)) return keep
[ "def", "union", "(", "lf", ",", "rf", ")", ":", "def", "keep", "(", "paths", ")", ":", "l", "=", "set", "(", "lf", "(", "paths", ")", ")", "r", "=", "set", "(", "rf", "(", "paths", ")", ")", "return", "sorted", "(", "list", "(", "l", "|", ...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/utils/gc.py#L148-L162
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/esptool/serial/tools/list_ports_common.py
python
numsplit
(text)
return result
\ Convert string into a list of texts and numbers in order to support a natural sorting.
\ Convert string into a list of texts and numbers in order to support a natural sorting.
[ "\\", "Convert", "string", "into", "a", "list", "of", "texts", "and", "numbers", "in", "order", "to", "support", "a", "natural", "sorting", "." ]
def numsplit(text): """\ Convert string into a list of texts and numbers in order to support a natural sorting. """ result = [] for group in re.split(r'(\d+)', text): if group: try: group = int(group) except ValueError: pass result.append(group) return result
[ "def", "numsplit", "(", "text", ")", ":", "result", "=", "[", "]", "for", "group", "in", "re", ".", "split", "(", "r'(\\d+)'", ",", "text", ")", ":", "if", "group", ":", "try", ":", "group", "=", "int", "(", "group", ")", "except", "ValueError", ...
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/serial/tools/list_ports_common.py#L15-L28
arx/ArxLibertatis
0313c51625f3f55016cdad43d2c7f7296d27949c
scripts/cpplint.py
python
FileInfo.RepositoryName
(self)
return fullname
FullName after removing the local path to the repository. If we have a real absolute path name here we can try to do something smart: detecting the root of the checkout and truncating /path/to/checkout from the name so that we get header guards that don't include things like "C:\Documents and Settings\..." or "/home/username/..." in them and thus people on different computers who have checked the source out to different locations won't see bogus errors.
FullName after removing the local path to the repository.
[ "FullName", "after", "removing", "the", "local", "path", "to", "the", "repository", "." ]
def RepositoryName(self): """FullName after removing the local path to the repository. If we have a real absolute path name here we can try to do something smart: detecting the root of the checkout and truncating /path/to/checkout from the name so that we get header guards that don't include things like "C:\Documents and Settings\..." or "/home/username/..." in them and thus people on different computers who have checked the source out to different locations won't see bogus errors. """ fullname = self.FullName() if os.path.exists(fullname): project_dir = os.path.dirname(fullname) if os.path.exists(os.path.join(project_dir, ".svn")): # If there's a .svn file in the current directory, we recursively look # up the directory tree for the top of the SVN checkout root_dir = project_dir one_up_dir = os.path.dirname(root_dir) while os.path.exists(os.path.join(one_up_dir, ".svn")): root_dir = os.path.dirname(root_dir) one_up_dir = os.path.dirname(one_up_dir) prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by # searching up from the current path. root_dir = os.path.dirname(fullname) while (root_dir != os.path.dirname(root_dir) and os.path.basename(root_dir) != "src" and not os.path.exists(os.path.join(root_dir, ".git")) and not os.path.exists(os.path.join(root_dir, ".hg")) and not os.path.exists(os.path.join(root_dir, ".svn"))): root_dir = os.path.dirname(root_dir) if (os.path.basename(root_dir) == "src" or os.path.exists(os.path.join(root_dir, ".git")) or os.path.exists(os.path.join(root_dir, ".hg")) or os.path.exists(os.path.join(root_dir, ".svn"))): prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Don't know what to do; header guard warnings may be wrong... return fullname
[ "def", "RepositoryName", "(", "self", ")", ":", "fullname", "=", "self", ".", "FullName", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "fullname", ")", ":", "project_dir", "=", "os", ".", "path", ".", "dirname", "(", "fullname", ")", "if", ...
https://github.com/arx/ArxLibertatis/blob/0313c51625f3f55016cdad43d2c7f7296d27949c/scripts/cpplint.py#L729-L774
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/cookielib.py
python
CookiePolicy.domain_return_ok
(self, domain, request)
return True
Return false if cookies should not be returned, given cookie domain.
Return false if cookies should not be returned, given cookie domain.
[ "Return", "false", "if", "cookies", "should", "not", "be", "returned", "given", "cookie", "domain", "." ]
def domain_return_ok(self, domain, request): """Return false if cookies should not be returned, given cookie domain. """ return True
[ "def", "domain_return_ok", "(", "self", ",", "domain", ",", "request", ")", ":", "return", "True" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/cookielib.py#L827-L830
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/ragged/row_partition.py
python
RowPartition.static_check
(self)
Checks if the object is internally consistent. Raises: ValueError if inconsistent.
Checks if the object is internally consistent.
[ "Checks", "if", "the", "object", "is", "internally", "consistent", "." ]
def static_check(self): """Checks if the object is internally consistent. Raises: ValueError if inconsistent. """ my_dtype = self.dtype if self._uniform_row_length is not None: if self._uniform_row_length.dtype != my_dtype: raise ValueError("_uniform_row_length.dtype=" + str(self._uniform_row_length.dtype) + ", not " + str(my_dtype)) if self._row_lengths is not None and self._row_lengths.dtype != my_dtype: raise ValueError("_row_lengths.dtype=" + str(self._row_lengths.dtype) + ", not " + str(my_dtype)) if self._value_rowids is not None and self._value_rowids.dtype != my_dtype: raise ValueError("_value_rowids.dtype=" + str(self._value_rowids.dtype) + ", not " + str(my_dtype)) if self._nrows is not None and self._nrows.dtype != my_dtype: raise ValueError("_nrows.dtype=" + str(self._nrows.dtype) + ", not " + str(my_dtype))
[ "def", "static_check", "(", "self", ")", ":", "my_dtype", "=", "self", ".", "dtype", "if", "self", ".", "_uniform_row_length", "is", "not", "None", ":", "if", "self", ".", "_uniform_row_length", ".", "dtype", "!=", "my_dtype", ":", "raise", "ValueError", "...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ragged/row_partition.py#L959-L982
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/signal/ltisys.py
python
_cast_to_array_dtype
(in1, in2)
return in1
Cast array to dtype of other array, while avoiding ComplexWarning. Those can be raised when casting complex to real.
Cast array to dtype of other array, while avoiding ComplexWarning.
[ "Cast", "array", "to", "dtype", "of", "other", "array", "while", "avoiding", "ComplexWarning", "." ]
def _cast_to_array_dtype(in1, in2): """Cast array to dtype of other array, while avoiding ComplexWarning. Those can be raised when casting complex to real. """ if numpy.issubdtype(in2.dtype, numpy.float): # dtype to cast to is not complex, so use .real in1 = in1.real.astype(in2.dtype) else: in1 = in1.astype(in2.dtype) return in1
[ "def", "_cast_to_array_dtype", "(", "in1", ",", "in2", ")", ":", "if", "numpy", ".", "issubdtype", "(", "in2", ".", "dtype", ",", "numpy", ".", "float", ")", ":", "# dtype to cast to is not complex, so use .real", "in1", "=", "in1", ".", "real", ".", "astype...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/signal/ltisys.py#L1856-L1867
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/rnn/python/ops/rnn_cell.py
python
IntersectionRNNCell.call
(self, inputs, state)
return new_y, new_state
Run one step of the Intersection RNN. Args: inputs: input Tensor, 2D, batch x input size. state: state Tensor, 2D, batch x num units. Returns: new_y: batch x num units, Tensor representing the output of the +RNN after reading `inputs` when previous state was `state`. new_state: batch x num units, Tensor representing the state of the +RNN after reading `inputs` when previous state was `state`. Raises: ValueError: If input size cannot be inferred from `inputs` via static shape inference. ValueError: If input size != output size (these must be equal when using the Intersection RNN).
Run one step of the Intersection RNN.
[ "Run", "one", "step", "of", "the", "Intersection", "RNN", "." ]
def call(self, inputs, state): """Run one step of the Intersection RNN. Args: inputs: input Tensor, 2D, batch x input size. state: state Tensor, 2D, batch x num units. Returns: new_y: batch x num units, Tensor representing the output of the +RNN after reading `inputs` when previous state was `state`. new_state: batch x num units, Tensor representing the state of the +RNN after reading `inputs` when previous state was `state`. Raises: ValueError: If input size cannot be inferred from `inputs` via static shape inference. ValueError: If input size != output size (these must be equal when using the Intersection RNN). """ sigmoid = math_ops.sigmoid tanh = math_ops.tanh input_size = inputs.get_shape().with_rank(2)[1] if input_size.value is None: raise ValueError("Could not infer input size from inputs.get_shape()[-1]") with vs.variable_scope(vs.get_variable_scope(), initializer=self._initializer): # read-in projections (should be used for first layer in deep +RNN # to transform size of inputs from I --> N) if input_size.value != self._num_units: if self._num_input_proj: with vs.variable_scope("in_projection"): inputs = _linear(inputs, self._num_units, True) else: raise ValueError("Must have input size == output size for " "Intersection RNN. To fix, num_in_proj should " "be set to num_units at cell init.") n_dim = i_dim = self._num_units cell_inputs = array_ops.concat([inputs, state], 1) rnn_matrix = _linear(cell_inputs, 2*n_dim + 2*i_dim, True) gh_act = rnn_matrix[:, :n_dim] # b x n h_act = rnn_matrix[:, n_dim:2*n_dim] # b x n gy_act = rnn_matrix[:, 2*n_dim:2*n_dim+i_dim] # b x i y_act = rnn_matrix[:, 2*n_dim+i_dim:2*n_dim+2*i_dim] # b x i h = tanh(h_act) y = self._y_activation(y_act) gh = sigmoid(gh_act + self._forget_bias) gy = sigmoid(gy_act + self._forget_bias) new_state = gh * state + (1.0 - gh) * h # passed thru time new_y = gy * inputs + (1.0 - gy) * y # passed thru depth return new_y, new_state
[ "def", "call", "(", "self", ",", "inputs", ",", "state", ")", ":", "sigmoid", "=", "math_ops", ".", "sigmoid", "tanh", "=", "math_ops", ".", "tanh", "input_size", "=", "inputs", ".", "get_shape", "(", ")", ".", "with_rank", "(", "2", ")", "[", "1", ...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/rnn/python/ops/rnn_cell.py#L1649-L1705
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/tpu/tensor_tracer.py
python
TensorTracer.report_proto
(self)
Getter for tensor_tracer.proto object for summary and full_tensor_summary modes. Returns: A tensor_tracer.proto object. Raises: ValueError if called before tracing happens, or when trace mode is not summary or full_tensor_summary.
Getter for tensor_tracer.proto object for summary and full_tensor_summary modes.
[ "Getter", "for", "tensor_tracer", ".", "proto", "object", "for", "summary", "and", "full_tensor_summary", "modes", "." ]
def report_proto(self): """Getter for tensor_tracer.proto object for summary and full_tensor_summary modes. Returns: A tensor_tracer.proto object. Raises: ValueError if called before tracing happens, or when trace mode is not summary or full_tensor_summary. """ if self._report_proto: return self._report_proto else: raise ValueError('Call to report_proto must be done after tracing.' 'Report proto only exists for ' 'trace_mode=[summary|full_tensor_summary]')
[ "def", "report_proto", "(", "self", ")", ":", "if", "self", ".", "_report_proto", ":", "return", "self", ".", "_report_proto", "else", ":", "raise", "ValueError", "(", "'Call to report_proto must be done after tracing.'", "'Report proto only exists for '", "'trace_mode=[s...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/tpu/tensor_tracer.py#L570-L584
mingchen/protobuf-ios
0958df34558cd54cb7b6e6ca5c8855bf3d475046
compiler/python/google/protobuf/internal/decoder.py
python
Decoder.Position
(self)
return self._stream.Position()
Returns the 0-indexed position in |s|.
Returns the 0-indexed position in |s|.
[ "Returns", "the", "0", "-", "indexed", "position", "in", "|s|", "." ]
def Position(self): """Returns the 0-indexed position in |s|.""" return self._stream.Position()
[ "def", "Position", "(", "self", ")", ":", "return", "self", ".", "_stream", ".", "Position", "(", ")" ]
https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/google/protobuf/internal/decoder.py#L68-L70
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py
python
ExportSampleLogsToCSVFile._writeAscynLogFile
(self, logtimeslist, logvaluelist, localtimediff, timetol)
return
Logs are recorded upon the change of the data time tolerance : two log entries within time tolerance will be recorded as one @param logtimeslist: @param logvaluelist: @param localtimediff: @param timetol: tolerance of time (in second) @return:
Logs are recorded upon the change of the data time tolerance : two log entries within time tolerance will be recorded as one
[ "Logs", "are", "recorded", "upon", "the", "change", "of", "the", "data", "time", "tolerance", ":", "two", "log", "entries", "within", "time", "tolerance", "will", "be", "recorded", "as", "one" ]
def _writeAscynLogFile(self, logtimeslist, logvaluelist, localtimediff, timetol): """ Logs are recorded upon the change of the data time tolerance : two log entries within time tolerance will be recorded as one @param logtimeslist: @param logvaluelist: @param localtimediff: @param timetol: tolerance of time (in second) @return: """ # Check input if logtimeslist.__class__.__name__ != "list": raise NotImplementedError("Input log times is not list") if logvaluelist.__class__.__name__ != "list": raise NotImplementedError("Input log value is not list") wbuf = "" currtimeindexes = [] for dummy_i in range(len(logtimeslist)): currtimeindexes.append(0) nextlogindexes = [] continuewrite = True linecount = 0 maxcount, mintime, maxtime = self._getLogsInfo(logtimeslist) self._maxtimestamp = maxcount self._maxtime = maxtime self._starttime = mintime self._localtimediff = localtimediff while continuewrite: self._findNextTimeStamps(logtimeslist, currtimeindexes, timetol, nextlogindexes) self.log().debug("Next time stamp log indexes: %s" % (str(nextlogindexes))) if len(nextlogindexes) == 0: # No new indexes that can be found continuewrite = False else: # templine = self._writeNewLine(logtimeslist, logvaluelist, currtimeindexes, nextlogindexes) self.log().debug("Write new line %d: %s" % (linecount, templine)) self._progressTimeIndexes(currtimeindexes, nextlogindexes) wbuf += templine + "\n" linecount += 1 # ENDIF if linecount > maxcount: raise NotImplementedError("Logic error.") # ENDWHILE # Remove last "\n" if wbuf[-1] == "\n": wbuf = wbuf[:-1] try: if self._append is True: log_file = open(self._outputfilename, 'a') else: log_file = open(self._outputfilename, "w") log_file.write(wbuf) log_file.close() except IOError: raise NotImplementedError("Unable to write file %s. Check permission." % (self._outputfilename)) return
[ "def", "_writeAscynLogFile", "(", "self", ",", "logtimeslist", ",", "logvaluelist", ",", "localtimediff", ",", "timetol", ")", ":", "# Check input", "if", "logtimeslist", ".", "__class__", ".", "__name__", "!=", "\"list\"", ":", "raise", "NotImplementedError", "("...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py#L225-L288
google/mysql-protobuf
467cda676afaa49e762c5c9164a43f6ad31a1fbf
protobuf/python/mox.py
python
MockObject.__init__
(self, class_to_mock)
Initialize a mock object. This determines the methods and properties of the class and stores them. Args: # class_to_mock: class to be mocked class_to_mock: class
Initialize a mock object.
[ "Initialize", "a", "mock", "object", "." ]
def __init__(self, class_to_mock): """Initialize a mock object. This determines the methods and properties of the class and stores them. Args: # class_to_mock: class to be mocked class_to_mock: class """ # This is used to hack around the mixin/inheritance of MockAnything, which # is not a proper object (it can be anything. :-) MockAnything.__dict__['__init__'](self) # Get a list of all the public and special methods we should mock. self._known_methods = set() self._known_vars = set() self._class_to_mock = class_to_mock for method in dir(class_to_mock): if callable(getattr(class_to_mock, method)): self._known_methods.add(method) else: self._known_vars.add(method)
[ "def", "__init__", "(", "self", ",", "class_to_mock", ")", ":", "# This is used to hack around the mixin/inheritance of MockAnything, which", "# is not a proper object (it can be anything. :-)", "MockAnything", ".", "__dict__", "[", "'__init__'", "]", "(", "self", ")", "# Get a...
https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/mox.py#L362-L384
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/customtreectrl.py
python
CustomTreeCtrl.IsItemHyperText
(self, item)
return item.IsHyperText()
Returns whether an item is hypertext or not. :param `item`: an instance of :class:`GenericTreeItem`. :return: ``True`` if the item is hypertext-like, ``False`` otherwise.
Returns whether an item is hypertext or not.
[ "Returns", "whether", "an", "item", "is", "hypertext", "or", "not", "." ]
def IsItemHyperText(self, item): """ Returns whether an item is hypertext or not. :param `item`: an instance of :class:`GenericTreeItem`. :return: ``True`` if the item is hypertext-like, ``False`` otherwise. """ return item.IsHyperText()
[ "def", "IsItemHyperText", "(", "self", ",", "item", ")", ":", "return", "item", ".", "IsHyperText", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L3657-L3666
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
docs/examples/use_cases/pytorch/single_stage_detector/src/coco.py
python
COCO.__init__
(self, annotation_file=None)
Constructor of Microsoft COCO helper class for reading and visualizing annotations. :param annotation_file (str): location of annotation file :param image_folder (str): location to the folder that hosts images. :return:
Constructor of Microsoft COCO helper class for reading and visualizing annotations. :param annotation_file (str): location of annotation file :param image_folder (str): location to the folder that hosts images. :return:
[ "Constructor", "of", "Microsoft", "COCO", "helper", "class", "for", "reading", "and", "visualizing", "annotations", ".", ":", "param", "annotation_file", "(", "str", ")", ":", "location", "of", "annotation", "file", ":", "param", "image_folder", "(", "str", ")...
def __init__(self, annotation_file=None): """ Constructor of Microsoft COCO helper class for reading and visualizing annotations. :param annotation_file (str): location of annotation file :param image_folder (str): location to the folder that hosts images. :return: """ # load dataset self.dataset,self.anns,self.cats,self.imgs = dict(),dict(),dict(),dict() self.imgToAnns, self.catToImgs = defaultdict(list), defaultdict(list) if not annotation_file == None: print('loading annotations into memory...') tic = time.time() dataset = json.load(open(annotation_file, 'r')) assert type(dataset)==dict, 'annotation file format {} not supported'.format(type(dataset)) print('Done (t={:0.2f}s)'.format(time.time()- tic)) self.dataset = dataset self.createIndex()
[ "def", "__init__", "(", "self", ",", "annotation_file", "=", "None", ")", ":", "# load dataset", "self", ".", "dataset", ",", "self", ".", "anns", ",", "self", ".", "cats", ",", "self", ".", "imgs", "=", "dict", "(", ")", ",", "dict", "(", ")", ","...
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/docs/examples/use_cases/pytorch/single_stage_detector/src/coco.py#L71-L88
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/interface.py
python
CommandLineInterface.reset
(self, reset_current_buffer=False)
Reset everything, for reading the next input. :param reset_current_buffer: XXX: not used anymore. The reason for having this option in the past was when this CommandLineInterface is run multiple times, that we could reset the buffer content from the previous run. This is now handled in the AcceptAction.
Reset everything, for reading the next input.
[ "Reset", "everything", "for", "reading", "the", "next", "input", "." ]
def reset(self, reset_current_buffer=False): """ Reset everything, for reading the next input. :param reset_current_buffer: XXX: not used anymore. The reason for having this option in the past was when this CommandLineInterface is run multiple times, that we could reset the buffer content from the previous run. This is now handled in the AcceptAction. """ # Notice that we don't reset the buffers. (This happens just before # returning, and when we have multiple buffers, we clearly want the # content in the other buffers to remain unchanged between several # calls of `run`. (And the same is true for the focus stack.) self._exit_flag = False self._abort_flag = False self._return_value = None self.renderer.reset() self.input_processor.reset() self.layout.reset() self.vi_state.reset() # Search new search state. (Does also remember what has to be # highlighted.) self.search_state = SearchState(ignore_case=Condition(lambda: self.is_ignoring_case)) # Trigger reset event. self.on_reset.fire()
[ "def", "reset", "(", "self", ",", "reset_current_buffer", "=", "False", ")", ":", "# Notice that we don't reset the buffers. (This happens just before", "# returning, and when we have multiple buffers, we clearly want the", "# content in the other buffers to remain unchanged between several"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/interface.py#L274-L303
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_proof.py
python
ProofChecker.match_schema
(self,decl,proof)
return goal_subgoals(prob.schema,decl,proof.lineno)
attempt to match a definition or property decl to a schema - decl is an ivy_ast.Definition or ivy_ast.Property - proof is an ivy_ast.SchemaInstantiation Returns a match or None
attempt to match a definition or property decl to a schema
[ "attempt", "to", "match", "a", "definition", "or", "property", "decl", "to", "a", "schema" ]
def match_schema(self,decl,proof): """ attempt to match a definition or property decl to a schema - decl is an ivy_ast.Definition or ivy_ast.Property - proof is an ivy_ast.SchemaInstantiation Returns a match or None """ prob, pmatch = self.setup_matching(decl,proof) apply_match_to_problem(pmatch,prob,apply_match_alt) if isinstance(prob.pat,ia.Tuple): for idx in range(len(prob.pat.args)): fomatch = fo_match(prob.pat.args[idx],prob.inst.args[idx],prob.freesyms,prob.constants) if fomatch is not None: apply_match_to_problem(fomatch,prob,apply_match) somatch = match(prob.pat.args[idx],prob.inst.args[idx],prob.freesyms,prob.constants) if somatch is None: raise NoMatch(proof,"goal does not match the given schema") apply_match_to_problem(somatch,prob,apply_match_alt) else: fomatch = fo_match(prob.pat,prob.inst,prob.freesyms,prob.constants) if fomatch is not None: apply_match_to_problem(fomatch,prob,apply_match) somatch = match(prob.pat,prob.inst,prob.freesyms,prob.constants) if somatch is None: raise NoMatch(proof,"goal does not match the given schema") apply_match_to_problem(somatch,prob,apply_match_alt) detect_nonce_symbols(prob) # schema = apply_match_goal(pmatch,schema,apply_match_alt) # schema = apply_match_goal(fomatch,schema,apply_match) # schema = apply_match_goal(somatch,schema,apply_match_alt) # tmatch = apply_match_match(fomatch,pmatch,apply_match) # tmatch = apply_match_match(somatch,tmatch,apply_match_alt) # schema = apply_match_goal(tmatch,schema,apply_match_alt) return goal_subgoals(prob.schema,decl,proof.lineno)
[ "def", "match_schema", "(", "self", ",", "decl", ",", "proof", ")", ":", "prob", ",", "pmatch", "=", "self", ".", "setup_matching", "(", "decl", ",", "proof", ")", "apply_match_to_problem", "(", "pmatch", ",", "prob", ",", "apply_match_alt", ")", "if", "...
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_proof.py#L400-L435
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
third_party/ply/example/ansic/cparse.py
python
p_logical_or_expression_2
(t)
logical_or_expression : logical_or_expression LOR logical_and_expression
logical_or_expression : logical_or_expression LOR logical_and_expression
[ "logical_or_expression", ":", "logical_or_expression", "LOR", "logical_and_expression" ]
def p_logical_or_expression_2(t): 'logical_or_expression : logical_or_expression LOR logical_and_expression' pass
[ "def", "p_logical_or_expression_2", "(", "t", ")", ":", "pass" ]
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/ansic/cparse.py#L621-L623
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/graphics.py
python
GraphicsContext.PopState
(self)
Restore the most recently saved state which was saved with PushState.
Restore the most recently saved state which was saved with PushState.
[ "Restore", "the", "most", "recently", "saved", "state", "which", "was", "saved", "with", "PushState", "." ]
def PopState(self): """ Restore the most recently saved state which was saved with PushState. """ self._context.restore()
[ "def", "PopState", "(", "self", ")", ":", "self", ".", "_context", ".", "restore", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/graphics.py#L1140-L1145
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/traitlets/py3/traitlets/traitlets.py
python
Container.from_string_list
(self, s_list)
return self.klass( [item_from_string(s, index=idx) for idx, s in enumerate(s_list)] )
Return the value from a list of config strings This is where we parse CLI configuration
Return the value from a list of config strings
[ "Return", "the", "value", "from", "a", "list", "of", "config", "strings" ]
def from_string_list(self, s_list): """Return the value from a list of config strings This is where we parse CLI configuration """ if len(s_list) == 1: # check for deprecated --Class.trait="['a', 'b', 'c']" r = s_list[0] if r == "None" and self.allow_none: return None if len(r) >= 2 and any( r.startswith(start) and r.endswith(end) for start, end in self._literal_from_string_pairs ): if self.this_class: clsname = self.this_class.__name__ + "." else: clsname = "" warn( "--{0}={1} for containers is deprecated in traitlets 5.0. " "You can pass `--{0} item` ... multiple times to add items to a list.".format( clsname + self.name, r ), FutureWarning, ) return self.klass(literal_eval(r)) sig = inspect.signature(self.item_from_string) if "index" in sig.parameters: item_from_string = self.item_from_string else: # backward-compat: allow item_from_string to ignore index arg item_from_string = lambda s, index=None: self.item_from_string(s) return self.klass( [item_from_string(s, index=idx) for idx, s in enumerate(s_list)] )
[ "def", "from_string_list", "(", "self", ",", "s_list", ")", ":", "if", "len", "(", "s_list", ")", "==", "1", ":", "# check for deprecated --Class.trait=\"['a', 'b', 'c']\"", "r", "=", "s_list", "[", "0", "]", "if", "r", "==", "\"None\"", "and", "self", ".", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py3/traitlets/traitlets.py#L2543-L2578
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Spreadsheet/App/Spreadsheet_legacy.py
python
open
(filename)
return doc
called when freecad opens a csv file
called when freecad opens a csv file
[ "called", "when", "freecad", "opens", "a", "csv", "file" ]
def open(filename): "called when freecad opens a csv file" import os docname = os.path.splitext(os.path.basename(filename))[0] doc = FreeCAD.newDocument(docname) FreeCAD.ActiveDocument = doc read(filename) doc.recompute() return doc
[ "def", "open", "(", "filename", ")", ":", "import", "os", "docname", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "filename", ")", ")", "[", "0", "]", "doc", "=", "FreeCAD", ".", "newDocument", "(", "docnam...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Spreadsheet/App/Spreadsheet_legacy.py#L1038-L1046
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/fitting_context.py
python
FittingContext.all_latest_fits
(self)
Returns the latest fits with unique fit output names for all fitting modes. Override in a child class.
Returns the latest fits with unique fit output names for all fitting modes. Override in a child class.
[ "Returns", "the", "latest", "fits", "with", "unique", "fit", "output", "names", "for", "all", "fitting", "modes", ".", "Override", "in", "a", "child", "class", "." ]
def all_latest_fits(self) -> None: """Returns the latest fits with unique fit output names for all fitting modes. Override in a child class.""" raise NotImplementedError("This needs to be overridden by a child class.")
[ "def", "all_latest_fits", "(", "self", ")", "->", "None", ":", "raise", "NotImplementedError", "(", "\"This needs to be overridden by a child class.\"", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/fitting_context.py#L349-L351
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/plugins/hcprt/hcprt.py
python
PrtVehicles.control_berth_position_enter
(self, id_veh, id_berth, id_edge_sumo=None, position=None, laneindex=2, )
Stop vehicle with id_veh at stopline of berth with id_berth Memorize berth for later use.
Stop vehicle with id_veh at stopline of berth with id_berth Memorize berth for later use.
[ "Stop", "vehicle", "with", "id_veh", "at", "stopline", "of", "berth", "with", "id_berth", "Memorize", "berth", "for", "later", "use", "." ]
def control_berth_position_enter(self, id_veh, id_berth, id_edge_sumo=None, position=None, laneindex=2, ): """Stop vehicle with id_veh at stopline of berth with id_berth Memorize berth for later use. """ id_veh_sumo = self.get_id_sumo(id_veh) p = traci.vehicle.getLanePosition(id_veh_sumo) print 'control_berth_position_enter', id_veh_sumo, p, '->', position, 'id_berth', id_berth # here it can happen that vehicle has been programmed to stop in front # of first berth to wait for allocation # print ' getStopState',traci.vehicle.getStopState(id_veh_sumo) # print ' getNextStops',traci.vehicle.getNextStops(id_veh_sumo) print ' isStopped', traci.vehicle.isStopped(id_veh_sumo) # if len(traci.vehicle.getNextStops(id_veh_sumo))>0: # already resumed # if traci.vehicle.isStopped(id_veh_sumo): # traci.vehicle.resume(id_veh_sumo) self.states[id_veh] = VEHICLESTATES['forewarding_enter'] self.ids_berth[id_veh] = id_berth traci.vehicle.setStop(id_veh_sumo, id_edge_sumo, pos=position, flags=0, laneIndex=laneindex, ) # force vehicle to stay on lane traci.vehicle.changeLane(id_veh_sumo, laneindex, 60.0)
[ "def", "control_berth_position_enter", "(", "self", ",", "id_veh", ",", "id_berth", ",", "id_edge_sumo", "=", "None", ",", "position", "=", "None", ",", "laneindex", "=", "2", ",", ")", ":", "id_veh_sumo", "=", "self", ".", "get_id_sumo", "(", "id_veh", ")...
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/plugins/hcprt/hcprt.py#L5912-L5944
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/idl/idl/bson.py
python
list_valid_types
()
return [a for a in _BSON_TYPE_INFORMATION.iterkeys()]
Return a list of supported bson types.
Return a list of supported bson types.
[ "Return", "a", "list", "of", "supported", "bson", "types", "." ]
def list_valid_types(): # type: () -> List[unicode] """Return a list of supported bson types.""" return [a for a in _BSON_TYPE_INFORMATION.iterkeys()]
[ "def", "list_valid_types", "(", ")", ":", "# type: () -> List[unicode]", "return", "[", "a", "for", "a", "in", "_BSON_TYPE_INFORMATION", ".", "iterkeys", "(", ")", "]" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/bson.py#L141-L144
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/mailbox.py
python
MMDF._generate_toc
(self)
Generate key-to-(start, stop) table of contents.
Generate key-to-(start, stop) table of contents.
[ "Generate", "key", "-", "to", "-", "(", "start", "stop", ")", "table", "of", "contents", "." ]
def _generate_toc(self): """Generate key-to-(start, stop) table of contents.""" starts, stops = [], [] self._file.seek(0) next_pos = 0 while True: line_pos = next_pos line = self._file.readline() next_pos = self._file.tell() if line.startswith('\001\001\001\001' + os.linesep): starts.append(next_pos) while True: line_pos = next_pos line = self._file.readline() next_pos = self._file.tell() if line == '\001\001\001\001' + os.linesep: stops.append(line_pos - len(os.linesep)) break elif line == '': stops.append(line_pos) break elif line == '': break self._toc = dict(enumerate(zip(starts, stops))) self._next_key = len(self._toc) self._file.seek(0, 2) self._file_length = self._file.tell()
[ "def", "_generate_toc", "(", "self", ")", ":", "starts", ",", "stops", "=", "[", "]", ",", "[", "]", "self", ".", "_file", ".", "seek", "(", "0", ")", "next_pos", "=", "0", "while", "True", ":", "line_pos", "=", "next_pos", "line", "=", "self", "...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/mailbox.py#L779-L805
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/aui.py
python
AuiNotebookEvent.GetDragSource
(*args, **kwargs)
return _aui.AuiNotebookEvent_GetDragSource(*args, **kwargs)
GetDragSource(self) -> AuiNotebook
GetDragSource(self) -> AuiNotebook
[ "GetDragSource", "(", "self", ")", "-", ">", "AuiNotebook" ]
def GetDragSource(*args, **kwargs): """GetDragSource(self) -> AuiNotebook""" return _aui.AuiNotebookEvent_GetDragSource(*args, **kwargs)
[ "def", "GetDragSource", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiNotebookEvent_GetDragSource", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L1088-L1090
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/applications/workbench/workbench/plugins/workspacewidget.py
python
WorkspaceWidget._do_slice_viewer
(self, names)
Show the sliceviewer window for the given workspaces :param names: A list of workspace names
Show the sliceviewer window for the given workspaces
[ "Show", "the", "sliceviewer", "window", "for", "the", "given", "workspaces" ]
def _do_slice_viewer(self, names): """ Show the sliceviewer window for the given workspaces :param names: A list of workspace names """ parent, flags = get_window_config() for ws in self._ads.retrieveWorkspaces(names, unrollGroups=True): try: presenter = SliceViewer(ws=ws, conf=CONF, parent=parent, window_flags=flags) presenter.view.show() except Exception as exception: logger.warning("Could not open slice viewer for workspace '{}'." "".format(ws.name())) logger.warning("{}: {}".format(type(exception).__name__, exception))
[ "def", "_do_slice_viewer", "(", "self", ",", "names", ")", ":", "parent", ",", "flags", "=", "get_window_config", "(", ")", "for", "ws", "in", "self", ".", "_ads", ".", "retrieveWorkspaces", "(", "names", ",", "unrollGroups", "=", "True", ")", ":", "try"...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/applications/workbench/workbench/plugins/workspacewidget.py#L247-L261
freeorion/freeorion
c266a40eccd3a99a17de8fe57c36ef6ba3771665
default/python/AI/savegame_codec/_encoder.py
python
_encode_object
(obj)
return _encode_dict(value)
Get a string representation of state of an object which is not handled by a specialized encoder.
Get a string representation of state of an object which is not handled by a specialized encoder.
[ "Get", "a", "string", "representation", "of", "state", "of", "an", "object", "which", "is", "not", "handled", "by", "a", "specialized", "encoder", "." ]
def _encode_object(obj): """Get a string representation of state of an object which is not handled by a specialized encoder.""" try: class_name = "%s.%s" % (obj.__class__.__module__, obj.__class__.__name__) if class_name not in trusted_classes: raise CanNotSaveGameException("Class %s is not trusted" % class_name) except AttributeError: # obj does not have a class or class has no module raise CanNotSaveGameException("Encountered unsupported object %s (%s)" % (obj, type(obj))) # if possible, use getstate method to query the state, otherwise use the object's __dict__ try: getstate = obj.__getstate__ except AttributeError: value = obj.__dict__ else: # only call now to avoid catching exceptions raised during the getstate call value = getstate() # encode information about class value.update({"__class__": obj.__class__.__name__, "__module__": obj.__class__.__module__}) return _encode_dict(value)
[ "def", "_encode_object", "(", "obj", ")", ":", "try", ":", "class_name", "=", "\"%s.%s\"", "%", "(", "obj", ".", "__class__", ".", "__module__", ",", "obj", ".", "__class__", ".", "__name__", ")", "if", "class_name", "not", "in", "trusted_classes", ":", ...
https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/savegame_codec/_encoder.py#L109-L130
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cgi.py
python
print_form
(form)
Dump the contents of a form as HTML.
Dump the contents of a form as HTML.
[ "Dump", "the", "contents", "of", "a", "form", "as", "HTML", "." ]
def print_form(form): """Dump the contents of a form as HTML.""" keys = form.keys() keys.sort() print print "<H3>Form Contents:</H3>" if not keys: print "<P>No form fields." print "<DL>" for key in keys: print "<DT>" + escape(key) + ":", value = form[key] print "<i>" + escape(repr(type(value))) + "</i>" print "<DD>" + escape(repr(value)) print "</DL>" print
[ "def", "print_form", "(", "form", ")", ":", "keys", "=", "form", ".", "keys", "(", ")", "keys", ".", "sort", "(", ")", "print", "print", "\"<H3>Form Contents:</H3>\"", "if", "not", "keys", ":", "print", "\"<P>No form fields.\"", "print", "\"<DL>\"", "for", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cgi.py#L947-L962
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
StyledTextCtrl.GetIndicatorCurrent
(*args, **kwargs)
return _stc.StyledTextCtrl_GetIndicatorCurrent(*args, **kwargs)
GetIndicatorCurrent(self) -> int Get the current indicator
GetIndicatorCurrent(self) -> int
[ "GetIndicatorCurrent", "(", "self", ")", "-", ">", "int" ]
def GetIndicatorCurrent(*args, **kwargs): """ GetIndicatorCurrent(self) -> int Get the current indicator """ return _stc.StyledTextCtrl_GetIndicatorCurrent(*args, **kwargs)
[ "def", "GetIndicatorCurrent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetIndicatorCurrent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L5655-L5661
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/trace.py
python
find_lines
(code, strs)
return linenos
Return lineno dict for all code objects reachable from code.
Return lineno dict for all code objects reachable from code.
[ "Return", "lineno", "dict", "for", "all", "code", "objects", "reachable", "from", "code", "." ]
def find_lines(code, strs): """Return lineno dict for all code objects reachable from code.""" # get all of the lineno information from the code of this scope level linenos = find_lines_from_code(code, strs) # and check the constants for references to other code objects for c in code.co_consts: if inspect.iscode(c): # find another code object, so recurse into it linenos.update(find_lines(c, strs)) return linenos
[ "def", "find_lines", "(", "code", ",", "strs", ")", ":", "# get all of the lineno information from the code of this scope level", "linenos", "=", "find_lines_from_code", "(", "code", ",", "strs", ")", "# and check the constants for references to other code objects", "for", "c",...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/trace.py#L403-L413
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py
python
Misc.pack_propagate
(self, flag=_noarg_)
Set or get the status for propagation of geometry information. A boolean argument specifies whether the geometry information of the slaves will determine the size of this widget. If no argument is given the current setting will be returned.
Set or get the status for propagation of geometry information.
[ "Set", "or", "get", "the", "status", "for", "propagation", "of", "geometry", "information", "." ]
def pack_propagate(self, flag=_noarg_): """Set or get the status for propagation of geometry information. A boolean argument specifies whether the geometry information of the slaves will determine the size of this widget. If no argument is given the current setting will be returned. """ if flag is Misc._noarg_: return self._getboolean(self.tk.call( 'pack', 'propagate', self._w)) else: self.tk.call('pack', 'propagate', self._w, flag)
[ "def", "pack_propagate", "(", "self", ",", "flag", "=", "_noarg_", ")", ":", "if", "flag", "is", "Misc", ".", "_noarg_", ":", "return", "self", ".", "_getboolean", "(", "self", ".", "tk", ".", "call", "(", "'pack'", ",", "'propagate'", ",", "self", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L1508-L1519
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/quantization/keras/graph_transformations/model_transformer.py
python
ModelTransformer._get_leaf_layers
(self, match_layer)
return leaf_layers
Return leaf layers from this sub-graph tree.
Return leaf layers from this sub-graph tree.
[ "Return", "leaf", "layers", "from", "this", "sub", "-", "graph", "tree", "." ]
def _get_leaf_layers(self, match_layer): """Return leaf layers from this sub-graph tree.""" if not match_layer.input_layers: return [match_layer.layer] # If 2 different layers point to the same input, or if a layer uses the # same input multiple times, the input layer can be repeated. But it # preserves a bit of structure. leaf_layers = [] for inp in match_layer.input_layers: leaf_layers.extend(self._get_leaf_layers(inp)) return leaf_layers
[ "def", "_get_leaf_layers", "(", "self", ",", "match_layer", ")", ":", "if", "not", "match_layer", ".", "input_layers", ":", "return", "[", "match_layer", ".", "layer", "]", "# If 2 different layers point to the same input, or if a layer uses the", "# same input multiple tim...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/quantization/keras/graph_transformations/model_transformer.py#L237-L251
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
PseudoDC.GetLen
(*args, **kwargs)
return _gdi_.PseudoDC_GetLen(*args, **kwargs)
GetLen(self) -> int Returns the number of operations in the recorded list.
GetLen(self) -> int
[ "GetLen", "(", "self", ")", "-", ">", "int" ]
def GetLen(*args, **kwargs): """ GetLen(self) -> int Returns the number of operations in the recorded list. """ return _gdi_.PseudoDC_GetLen(*args, **kwargs)
[ "def", "GetLen", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "PseudoDC_GetLen", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L7586-L7592
happynear/caffe-windows
967eedf25009e334b7f6f933bb5e17aaaff5bef6
scripts/cpp_lint.py
python
CheckCheck
(filename, clean_lines, linenum, error)
Checks the use of CHECK and EXPECT macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks the use of CHECK and EXPECT macros.
[ "Checks", "the", "use", "of", "CHECK", "and", "EXPECT", "macros", "." ]
def CheckCheck(filename, clean_lines, linenum, error): """Checks the use of CHECK and EXPECT macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Decide the set of replacement macros that should be suggested lines = clean_lines.elided check_macro = None start_pos = -1 for macro in _CHECK_MACROS: i = lines[linenum].find(macro) if i >= 0: check_macro = macro # Find opening parenthesis. Do a regular expression match here # to make sure that we are matching the expected CHECK macro, as # opposed to some other macro that happens to contain the CHECK # substring. matched = Match(r'^(.*\b' + check_macro + r'\s*)\(', lines[linenum]) if not matched: continue start_pos = len(matched.group(1)) break if not check_macro or start_pos < 0: # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT' return # Find end of the boolean expression by matching parentheses (last_line, end_line, end_pos) = CloseExpression( clean_lines, linenum, start_pos) if end_pos < 0: return if linenum == end_line: expression = lines[linenum][start_pos + 1:end_pos - 1] else: expression = lines[linenum][start_pos + 1:] for i in xrange(linenum + 1, end_line): expression += lines[i] expression += last_line[0:end_pos - 1] # Parse expression so that we can take parentheses into account. # This avoids false positives for inputs like "CHECK((a < 4) == b)", # which is not replaceable by CHECK_LE. lhs = '' rhs = '' operator = None while expression: matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||' r'==|!=|>=|>|<=|<|\()(.*)$', expression) if matched: token = matched.group(1) if token == '(': # Parenthesized operand expression = matched.group(2) (end, _) = FindEndOfExpressionInLine(expression, 0, 1, '(', ')') if end < 0: return # Unmatched parenthesis lhs += '(' + expression[0:end] expression = expression[end:] elif token in ('&&', '||'): # Logical and/or operators. This means the expression # contains more than one term, for example: # CHECK(42 < a && a < b); # # These are not replaceable with CHECK_LE, so bail out early. return elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'): # Non-relational operator lhs += token expression = matched.group(2) else: # Relational operator operator = token rhs = matched.group(2) break else: # Unparenthesized operand. Instead of appending to lhs one character # at a time, we do another regular expression match to consume several # characters at once if possible. Trivial benchmark shows that this # is more efficient when the operands are longer than a single # character, which is generally the case. matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression) if not matched: matched = Match(r'^(\s*\S)(.*)$', expression) if not matched: break lhs += matched.group(1) expression = matched.group(2) # Only apply checks if we got all parts of the boolean expression if not (lhs and operator and rhs): return # Check that rhs do not contain logical operators. We already know # that lhs is fine since the loop above parses out && and ||. if rhs.find('&&') > -1 or rhs.find('||') > -1: return # At least one of the operands must be a constant literal. This is # to avoid suggesting replacements for unprintable things like # CHECK(variable != iterator) # # The following pattern matches decimal, hex integers, strings, and # characters (in that order). lhs = lhs.strip() rhs = rhs.strip() match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$' if Match(match_constant, lhs) or Match(match_constant, rhs): # Note: since we know both lhs and rhs, we can provide a more # descriptive error message like: # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42) # Instead of: # Consider using CHECK_EQ instead of CHECK(a == b) # # We are still keeping the less descriptive message because if lhs # or rhs gets long, the error message might become unreadable. error(filename, linenum, 'readability/check', 2, 'Consider using %s instead of %s(a %s b)' % ( _CHECK_REPLACEMENT[check_macro][operator], check_macro, operator))
[ "def", "CheckCheck", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "# Decide the set of replacement macros that should be suggested", "lines", "=", "clean_lines", ".", "elided", "check_macro", "=", "None", "start_pos", "=", "-", "1", "...
https://github.com/happynear/caffe-windows/blob/967eedf25009e334b7f6f933bb5e17aaaff5bef6/scripts/cpp_lint.py#L3282-L3406
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/robotsim.py
python
TerrainModel.setFriction
(self, friction)
return _robotsim.TerrainModel_setFriction(self, friction)
setFriction(TerrainModel self, double friction) Changes the friction coefficient for this terrain.
setFriction(TerrainModel self, double friction)
[ "setFriction", "(", "TerrainModel", "self", "double", "friction", ")" ]
def setFriction(self, friction): """ setFriction(TerrainModel self, double friction) Changes the friction coefficient for this terrain. """ return _robotsim.TerrainModel_setFriction(self, friction)
[ "def", "setFriction", "(", "self", ",", "friction", ")", ":", "return", "_robotsim", ".", "TerrainModel_setFriction", "(", "self", ",", "friction", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L5662-L5671
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/stc.py
python
StyledTextCtrl.GetPrintColourMode
(*args, **kwargs)
return _stc.StyledTextCtrl_GetPrintColourMode(*args, **kwargs)
GetPrintColourMode(self) -> int Returns the print colour mode.
GetPrintColourMode(self) -> int
[ "GetPrintColourMode", "(", "self", ")", "-", ">", "int" ]
def GetPrintColourMode(*args, **kwargs): """ GetPrintColourMode(self) -> int Returns the print colour mode. """ return _stc.StyledTextCtrl_GetPrintColourMode(*args, **kwargs)
[ "def", "GetPrintColourMode", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetPrintColourMode", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L3488-L3494
tensorflow/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
deepmath/deephol/utilities/sexpression_graphs.py
python
theorem_sexpression
(theorem: proof_assistant_pb2.Theorem)
Converts theorem object to an S-expression.
Converts theorem object to an S-expression.
[ "Converts", "theorem", "object", "to", "an", "S", "-", "expression", "." ]
def theorem_sexpression(theorem: proof_assistant_pb2.Theorem) -> Text: """Converts theorem object to an S-expression.""" if theorem.tag == proof_assistant_pb2.Theorem.GOAL: return '(g (%s) %s)' % (' '.join(theorem.hypotheses), theorem.conclusion) if theorem.tag == proof_assistant_pb2.Theorem.THEOREM: return '(h (%s) %s)' % (' '.join(theorem.hypotheses), theorem.conclusion) if theorem.tag == proof_assistant_pb2.Theorem.DEFINITION: if theorem.hypotheses: raise ValueError('Detected definition with hypotheses.') return '(d (%s) %s)' % (' '.join( theorem.definition.constants), theorem.conclusion) if theorem.tag == proof_assistant_pb2.Theorem.TYPE_DEFINITION: if theorem.hypotheses: raise ValueError('Detected type definition with hypotheses.') return '(t %s %s)' % (theorem.type_definition.type_name, theorem.conclusion) raise ValueError('Unknown theorem tag.')
[ "def", "theorem_sexpression", "(", "theorem", ":", "proof_assistant_pb2", ".", "Theorem", ")", "->", "Text", ":", "if", "theorem", ".", "tag", "==", "proof_assistant_pb2", ".", "Theorem", ".", "GOAL", ":", "return", "'(g (%s) %s)'", "%", "(", "' '", ".", "jo...
https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/deephol/utilities/sexpression_graphs.py#L23-L38
facebook/hhvm
cd8d20db628e93583fffa0194aaca937af9b2692
hphp/tools/gdb/hhbc.py
python
HHBC.decode_named_local
(pc)
return info
Decode the NLA immediate at `pc', returning a dict with 'value' and 'size' keys.
Decode the NLA immediate at `pc', returning a dict with 'value' and 'size' keys.
[ "Decode", "the", "NLA", "immediate", "at", "pc", "returning", "a", "dict", "with", "value", "and", "size", "keys", "." ]
def decode_named_local(pc): """Decode the NLA immediate at `pc', returning a dict with 'value' and 'size' keys.""" info = {} name = HHBC.decode_iva(pc) size = name['size'] locId = HHBC.decode_iva(pc + size) size += locId['size'] info['size'] = size info['value'] = '%s (name: %s)' % ( str(locId['value'].cast(T('int32_t'))), str(name['value'].cast(T('int32_t')) - 1) ) return info
[ "def", "decode_named_local", "(", "pc", ")", ":", "info", "=", "{", "}", "name", "=", "HHBC", ".", "decode_iva", "(", "pc", ")", "size", "=", "name", "[", "'size'", "]", "locId", "=", "HHBC", ".", "decode_iva", "(", "pc", "+", "size", ")", "size", ...
https://github.com/facebook/hhvm/blob/cd8d20db628e93583fffa0194aaca937af9b2692/hphp/tools/gdb/hhbc.py#L147-L161
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/esptool/serial/rfc2217.py
python
PortManager.rfc2217_send_subnegotiation
(self, option, value=b'')
Subnegotiation of RFC 2217 parameters.
Subnegotiation of RFC 2217 parameters.
[ "Subnegotiation", "of", "RFC", "2217", "parameters", "." ]
def rfc2217_send_subnegotiation(self, option, value=b''): """Subnegotiation of RFC 2217 parameters.""" value = value.replace(IAC, IAC_DOUBLED) self.connection.write(IAC + SB + COM_PORT_OPTION + option + value + IAC + SE)
[ "def", "rfc2217_send_subnegotiation", "(", "self", ",", "option", ",", "value", "=", "b''", ")", ":", "value", "=", "value", ".", "replace", "(", "IAC", ",", "IAC_DOUBLED", ")", "self", ".", "connection", ".", "write", "(", "IAC", "+", "SB", "+", "COM_...
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/serial/rfc2217.py#L997-L1000
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/python_gflags/gflags.py
python
FlagValues.__str__
(self)
return self.GetHelp()
Generates a help string for all known flags.
Generates a help string for all known flags.
[ "Generates", "a", "help", "string", "for", "all", "known", "flags", "." ]
def __str__(self): """Generates a help string for all known flags.""" return self.GetHelp()
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "GetHelp", "(", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/python_gflags/gflags.py#L1355-L1357
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
ErrNotify
(*args)
return _snap.ErrNotify(*args)
ErrNotify(char const * NotifyCStr) Parameters: NotifyCStr: char const *
ErrNotify(char const * NotifyCStr)
[ "ErrNotify", "(", "char", "const", "*", "NotifyCStr", ")" ]
def ErrNotify(*args): """ ErrNotify(char const * NotifyCStr) Parameters: NotifyCStr: char const * """ return _snap.ErrNotify(*args)
[ "def", "ErrNotify", "(", "*", "args", ")", ":", "return", "_snap", ".", "ErrNotify", "(", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L198-L206
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py
python
NDFrame.at_time
( self: FrameOrSeries, time, asof: bool_t = False, axis=None )
return self._take_with_is_copy(indexer, axis=axis)
Select values at particular time of day (e.g. 9:30AM). Parameters ---------- time : datetime.time or str axis : {0 or 'index', 1 or 'columns'}, default 0 .. versionadded:: 0.24.0 Returns ------- Series or DataFrame Raises ------ TypeError If the index is not a :class:`DatetimeIndex` See Also -------- between_time : Select values between particular times of the day. first : Select initial periods of time series based on a date offset. last : Select final periods of time series based on a date offset. DatetimeIndex.indexer_at_time : Get just the index locations for values at particular time of the day. Examples -------- >>> i = pd.date_range('2018-04-09', periods=4, freq='12H') >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i) >>> ts A 2018-04-09 00:00:00 1 2018-04-09 12:00:00 2 2018-04-10 00:00:00 3 2018-04-10 12:00:00 4 >>> ts.at_time('12:00') A 2018-04-09 12:00:00 2 2018-04-10 12:00:00 4
Select values at particular time of day (e.g. 9:30AM).
[ "Select", "values", "at", "particular", "time", "of", "day", "(", "e", ".", "g", ".", "9", ":", "30AM", ")", "." ]
def at_time( self: FrameOrSeries, time, asof: bool_t = False, axis=None ) -> FrameOrSeries: """ Select values at particular time of day (e.g. 9:30AM). Parameters ---------- time : datetime.time or str axis : {0 or 'index', 1 or 'columns'}, default 0 .. versionadded:: 0.24.0 Returns ------- Series or DataFrame Raises ------ TypeError If the index is not a :class:`DatetimeIndex` See Also -------- between_time : Select values between particular times of the day. first : Select initial periods of time series based on a date offset. last : Select final periods of time series based on a date offset. DatetimeIndex.indexer_at_time : Get just the index locations for values at particular time of the day. Examples -------- >>> i = pd.date_range('2018-04-09', periods=4, freq='12H') >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i) >>> ts A 2018-04-09 00:00:00 1 2018-04-09 12:00:00 2 2018-04-10 00:00:00 3 2018-04-10 12:00:00 4 >>> ts.at_time('12:00') A 2018-04-09 12:00:00 2 2018-04-10 12:00:00 4 """ if axis is None: axis = self._stat_axis_number axis = self._get_axis_number(axis) index = self._get_axis(axis) try: indexer = index.indexer_at_time(time, asof=asof) except AttributeError: raise TypeError("Index must be DatetimeIndex") return self._take_with_is_copy(indexer, axis=axis)
[ "def", "at_time", "(", "self", ":", "FrameOrSeries", ",", "time", ",", "asof", ":", "bool_t", "=", "False", ",", "axis", "=", "None", ")", "->", "FrameOrSeries", ":", "if", "axis", "is", "None", ":", "axis", "=", "self", ".", "_stat_axis_number", "axis...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py#L7684-L7740
flameshot-org/flameshot
bcb4041e0e433e6ac0d65e87bd50c194459f5684
scripts/upload_services/transferwee.py
python
upload
(files: List[str], message: str = '', sender: str = None, recipients: List[str] = [])
return _finalize_upload(transfer_id, s)['shortened_url']
Given a list of files upload them and return the corresponding URL. Also accepts optional parameters: - `message': message used as a description of the transfer - `sender': email address used to receive an ACK if the upload is successfull. For every download by the recipients an email will be also sent - `recipients': list of email addresses of recipients. When the upload succeed every recipients will receive an email with a link If both sender and recipient parameters are passed the email upload will be used. Otherwise, the link upload will be used. Return the short URL of the transfer on success.
Given a list of files upload them and return the corresponding URL.
[ "Given", "a", "list", "of", "files", "upload", "them", "and", "return", "the", "corresponding", "URL", "." ]
def upload(files: List[str], message: str = '', sender: str = None, recipients: List[str] = []) -> str: """Given a list of files upload them and return the corresponding URL. Also accepts optional parameters: - `message': message used as a description of the transfer - `sender': email address used to receive an ACK if the upload is successfull. For every download by the recipients an email will be also sent - `recipients': list of email addresses of recipients. When the upload succeed every recipients will receive an email with a link If both sender and recipient parameters are passed the email upload will be used. Otherwise, the link upload will be used. Return the short URL of the transfer on success. """ # Check that all files exists for f in files: if not os.path.exists(f): raise FileNotFoundError(f) # Check that there are no duplicates filenames # (despite possible different dirname()) filenames = [os.path.basename(f) for f in files] if len(files) != len(set(filenames)): raise FileExistsError('Duplicate filenames') transfer_id = None s = _prepare_session() if sender and recipients: # email upload transfer_id = \ _prepare_email_upload(files, message, sender, recipients, s)['id'] _verify_email_upload(transfer_id, s) else: # link upload transfer_id = _prepare_link_upload(files, message, s)['id'] for f in files: file_id = _prepare_file_upload(transfer_id, f, s)['id'] _upload_chunks(transfer_id, file_id, f, s) return _finalize_upload(transfer_id, s)['shortened_url']
[ "def", "upload", "(", "files", ":", "List", "[", "str", "]", ",", "message", ":", "str", "=", "''", ",", "sender", ":", "str", "=", "None", ",", "recipients", ":", "List", "[", "str", "]", "=", "[", "]", ")", "->", "str", ":", "# Check that all f...
https://github.com/flameshot-org/flameshot/blob/bcb4041e0e433e6ac0d65e87bd50c194459f5684/scripts/upload_services/transferwee.py#L296-L340
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/google/protobuf/internal/encoder.py
python
StringEncoder
(field_number, is_repeated, is_packed)
Returns an encoder for a string field.
Returns an encoder for a string field.
[ "Returns", "an", "encoder", "for", "a", "string", "field", "." ]
def StringEncoder(field_number, is_repeated, is_packed): """Returns an encoder for a string field.""" tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) local_EncodeVarint = _EncodeVarint local_len = len assert not is_packed if is_repeated: def EncodeRepeatedField(write, value): for element in value: encoded = element.encode('utf-8') write(tag) local_EncodeVarint(write, local_len(encoded)) write(encoded) return EncodeRepeatedField else: def EncodeField(write, value): encoded = value.encode('utf-8') write(tag) local_EncodeVarint(write, local_len(encoded)) return write(encoded) return EncodeField
[ "def", "StringEncoder", "(", "field_number", ",", "is_repeated", ",", "is_packed", ")", ":", "tag", "=", "TagBytes", "(", "field_number", ",", "wire_format", ".", "WIRETYPE_LENGTH_DELIMITED", ")", "local_EncodeVarint", "=", "_EncodeVarint", "local_len", "=", "len", ...
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/internal/encoder.py#L652-L673
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/urllib/parse.py
python
splitattr
(url)
return words[0], words[1:]
splitattr('/path;attr1=value1;attr2=value2;...') -> '/path', ['attr1=value1', 'attr2=value2', ...].
splitattr('/path;attr1=value1;attr2=value2;...') -> '/path', ['attr1=value1', 'attr2=value2', ...].
[ "splitattr", "(", "/", "path", ";", "attr1", "=", "value1", ";", "attr2", "=", "value2", ";", "...", ")", "-", ">", "/", "path", "[", "attr1", "=", "value1", "attr2", "=", "value2", "...", "]", "." ]
def splitattr(url): """splitattr('/path;attr1=value1;attr2=value2;...') -> '/path', ['attr1=value1', 'attr2=value2', ...].""" words = url.split(';') return words[0], words[1:]
[ "def", "splitattr", "(", "url", ")", ":", "words", "=", "url", ".", "split", "(", "';'", ")", "return", "words", "[", "0", "]", ",", "words", "[", "1", ":", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/urllib/parse.py#L1068-L1072
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
GridTableMessage.GetCommandInt
(*args, **kwargs)
return _grid.GridTableMessage_GetCommandInt(*args, **kwargs)
GetCommandInt(self) -> int
GetCommandInt(self) -> int
[ "GetCommandInt", "(", "self", ")", "-", ">", "int" ]
def GetCommandInt(*args, **kwargs): """GetCommandInt(self) -> int""" return _grid.GridTableMessage_GetCommandInt(*args, **kwargs)
[ "def", "GetCommandInt", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridTableMessage_GetCommandInt", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1095-L1097
lhmRyan/deep-supervised-hashing-DSH
631901f82e2ab031fbac33f914a5b08ef8e21d57
python/caffe/coord_map.py
python
coord_map
(fn)
Define the coordinate mapping by its - axis - scale: output coord[i * scale] <- input_coord[i] - shift: output coord[i] <- output_coord[i + shift] s.t. the identity mapping, as for pointwise layers like ReLu, is defined by (None, 1, 0) since it is independent of axis and does not transform coords.
Define the coordinate mapping by its - axis - scale: output coord[i * scale] <- input_coord[i] - shift: output coord[i] <- output_coord[i + shift] s.t. the identity mapping, as for pointwise layers like ReLu, is defined by (None, 1, 0) since it is independent of axis and does not transform coords.
[ "Define", "the", "coordinate", "mapping", "by", "its", "-", "axis", "-", "scale", ":", "output", "coord", "[", "i", "*", "scale", "]", "<", "-", "input_coord", "[", "i", "]", "-", "shift", ":", "output", "coord", "[", "i", "]", "<", "-", "output_co...
def coord_map(fn): """ Define the coordinate mapping by its - axis - scale: output coord[i * scale] <- input_coord[i] - shift: output coord[i] <- output_coord[i + shift] s.t. the identity mapping, as for pointwise layers like ReLu, is defined by (None, 1, 0) since it is independent of axis and does not transform coords. """ if fn.type_name in ['Convolution', 'Pooling', 'Im2col']: axis, stride, ks, pad = conv_params(fn) return axis, 1 / stride, (pad - (ks - 1) / 2) / stride elif fn.type_name == 'Deconvolution': axis, stride, ks, pad = conv_params(fn) return axis, stride, (ks - 1) / 2 - pad elif fn.type_name in PASS_THROUGH_LAYERS: return None, 1, 0 elif fn.type_name == 'Crop': axis, offset = crop_params(fn) axis -= 1 # -1 for last non-coordinate dim. return axis, 1, - offset else: raise UndefinedMapException
[ "def", "coord_map", "(", "fn", ")", ":", "if", "fn", ".", "type_name", "in", "[", "'Convolution'", ",", "'Pooling'", ",", "'Im2col'", "]", ":", "axis", ",", "stride", ",", "ks", ",", "pad", "=", "conv_params", "(", "fn", ")", "return", "axis", ",", ...
https://github.com/lhmRyan/deep-supervised-hashing-DSH/blob/631901f82e2ab031fbac33f914a5b08ef8e21d57/python/caffe/coord_map.py#L57-L79
Kitware/VTK
5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8
Wrapping/Python/vtkmodules/numpy_interface/dataset_adapter.py
python
CompositeDataSet.GetPointData
(self)
return self._PointData()
Returns the point data as a DataSetAttributes instance.
Returns the point data as a DataSetAttributes instance.
[ "Returns", "the", "point", "data", "as", "a", "DataSetAttributes", "instance", "." ]
def GetPointData(self): "Returns the point data as a DataSetAttributes instance." if self._PointData is None or self._PointData() is None: pdata = self.GetAttributes(ArrayAssociation.POINT) self._PointData = weakref.ref(pdata) return self._PointData()
[ "def", "GetPointData", "(", "self", ")", ":", "if", "self", ".", "_PointData", "is", "None", "or", "self", ".", "_PointData", "(", ")", "is", "None", ":", "pdata", "=", "self", ".", "GetAttributes", "(", "ArrayAssociation", ".", "POINT", ")", "self", "...
https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Wrapping/Python/vtkmodules/numpy_interface/dataset_adapter.py#L968-L973
OkCupid/okws
1c337392c676ccb4e9a4c92d11d5d2fada6427d2
py/okws/pubast.py
python
iter_fields
(node)
Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*.
Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*.
[ "Yield", "a", "tuple", "of", "(", "fieldname", "value", ")", "for", "each", "field", "in", "node", ".", "_fields", "that", "is", "present", "on", "*", "node", "*", "." ]
def iter_fields(node): """ Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*. """ for field in node._fields: try: yield field, getattr(node, field) except AttributeError: pass
[ "def", "iter_fields", "(", "node", ")", ":", "for", "field", "in", "node", ".", "_fields", ":", "try", ":", "yield", "field", ",", "getattr", "(", "node", ",", "field", ")", "except", "AttributeError", ":", "pass" ]
https://github.com/OkCupid/okws/blob/1c337392c676ccb4e9a4c92d11d5d2fada6427d2/py/okws/pubast.py#L61-L70
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/fancy-sequence.py
python
Fancy2.multAll
(self, m)
:type m: int :rtype: None
:type m: int :rtype: None
[ ":", "type", "m", ":", "int", ":", "rtype", ":", "None" ]
def multAll(self, m): """ :type m: int :rtype: None """ self.__op = [(self.__op[0]*m) % MOD, (self.__op[1]*m) % MOD]
[ "def", "multAll", "(", "self", ",", "m", ")", ":", "self", ".", "__op", "=", "[", "(", "self", ".", "__op", "[", "0", "]", "*", "m", ")", "%", "MOD", ",", "(", "self", ".", "__op", "[", "1", "]", "*", "m", ")", "%", "MOD", "]" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/fancy-sequence.py#L70-L75
syoyo/tinygltf
e7f1ff5c59d3ca2489923beb239bdf93d863498f
deps/cpplint.py
python
CheckRedundantVirtual
(filename, clean_lines, linenum, error)
Check if line contains a redundant "virtual" function-specifier. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Check if line contains a redundant "virtual" function-specifier.
[ "Check", "if", "line", "contains", "a", "redundant", "virtual", "function", "-", "specifier", "." ]
def CheckRedundantVirtual(filename, clean_lines, linenum, error): """Check if line contains a redundant "virtual" function-specifier. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Look for "virtual" on current line. line = clean_lines.elided[linenum] virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line) if not virtual: return # Ignore "virtual" keywords that are near access-specifiers. These # are only used in class base-specifier and do not apply to member # functions. if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or Match(r'^\s+(public|protected|private)\b', virtual.group(3))): return # Ignore the "virtual" keyword from virtual base classes. Usually # there is a column on the same line in these cases (virtual base # classes are rare in google3 because multiple inheritance is rare). if Match(r'^.*[^:]:[^:].*$', line): return # Look for the next opening parenthesis. This is the start of the # parameter list (possibly on the next line shortly after virtual). # TODO(unknown): doesn't work if there are virtual functions with # decltype() or other things that use parentheses, but csearch suggests # that this is rare. end_col = -1 end_line = -1 start_col = len(virtual.group(2)) for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())): line = clean_lines.elided[start_line][start_col:] parameter_list = Match(r'^([^(]*)\(', line) if parameter_list: # Match parentheses to find the end of the parameter list (_, end_line, end_col) = CloseExpression( clean_lines, start_line, start_col + len(parameter_list.group(1))) break start_col = 0 if end_col < 0: return # Couldn't find end of parameter list, give up # Look for "override" or "final" after the parameter list # (possibly on the next few lines). for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())): line = clean_lines.elided[i][end_col:] match = Search(r'\b(override|final)\b', line) if match: error(filename, linenum, 'readability/inheritance', 4, ('"virtual" is redundant since function is ' 'already declared as "%s"' % match.group(1))) # Set end_col to check whole lines after we are done with the # first line. end_col = 0 if Search(r'[^\w]\s*$', line): break
[ "def", "CheckRedundantVirtual", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "# Look for \"virtual\" on current line.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "virtual", "=", "Match", "(", "r'^(.*)(\\bvirtual\...
https://github.com/syoyo/tinygltf/blob/e7f1ff5c59d3ca2489923beb239bdf93d863498f/deps/cpplint.py#L5747-L5808
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/vcs/git.py
python
Git.resolve_revision
(self, dest, url, rev_options)
return rev_options
Resolve a revision to a new RevOptions object with the SHA1 of the branch, tag, or ref if found. Args: rev_options: a RevOptions object.
Resolve a revision to a new RevOptions object with the SHA1 of the branch, tag, or ref if found.
[ "Resolve", "a", "revision", "to", "a", "new", "RevOptions", "object", "with", "the", "SHA1", "of", "the", "branch", "tag", "or", "ref", "if", "found", "." ]
def resolve_revision(self, dest, url, rev_options): """ Resolve a revision to a new RevOptions object with the SHA1 of the branch, tag, or ref if found. Args: rev_options: a RevOptions object. """ rev = rev_options.arg_rev sha, is_branch = self.get_revision_sha(dest, rev) if sha is not None: rev_options = rev_options.make_new(sha) rev_options.branch_name = rev if is_branch else None return rev_options # Do not show a warning for the common case of something that has # the form of a Git commit hash. if not looks_like_hash(rev): logger.warning( "Did not find branch or tag '%s', assuming revision or ref.", rev, ) if not rev.startswith('refs/'): return rev_options # If it looks like a ref, we have to fetch it explicitly. self.run_command( ['fetch', '-q', url] + rev_options.to_args(), cwd=dest, ) # Change the revision to the SHA of the ref we fetched sha = self.get_revision(dest, rev='FETCH_HEAD') rev_options = rev_options.make_new(sha) return rev_options
[ "def", "resolve_revision", "(", "self", ",", "dest", ",", "url", ",", "rev_options", ")", ":", "rev", "=", "rev_options", ".", "arg_rev", "sha", ",", "is_branch", "=", "self", ".", "get_revision_sha", "(", "dest", ",", "rev", ")", "if", "sha", "is", "n...
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/_internal/vcs/git.py#L148-L185
happynear/caffe-windows
967eedf25009e334b7f6f933bb5e17aaaff5bef6
scripts/cpp_lint.py
python
_NestingState.InnermostClass
(self)
return None
Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise.
Get class info on the top of the stack.
[ "Get", "class", "info", "on", "the", "top", "of", "the", "stack", "." ]
def InnermostClass(self): """Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise. """ for i in range(len(self.stack), 0, -1): classinfo = self.stack[i - 1] if isinstance(classinfo, _ClassInfo): return classinfo return None
[ "def", "InnermostClass", "(", "self", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "stack", ")", ",", "0", ",", "-", "1", ")", ":", "classinfo", "=", "self", ".", "stack", "[", "i", "-", "1", "]", "if", "isinstance", "(", ...
https://github.com/happynear/caffe-windows/blob/967eedf25009e334b7f6f933bb5e17aaaff5bef6/scripts/cpp_lint.py#L2164-L2174
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gnm.py
python
CastToNetwork
(*args)
return _gnm.CastToNetwork(*args)
r"""CastToNetwork(MajorObject base) -> Network
r"""CastToNetwork(MajorObject base) -> Network
[ "r", "CastToNetwork", "(", "MajorObject", "base", ")", "-", ">", "Network" ]
def CastToNetwork(*args): r"""CastToNetwork(MajorObject base) -> Network""" return _gnm.CastToNetwork(*args)
[ "def", "CastToNetwork", "(", "*", "args", ")", ":", "return", "_gnm", ".", "CastToNetwork", "(", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gnm.py#L91-L93
aimerykong/Low-Rank-Bilinear-Pooling
487eb2c857fd9c95357a5166b0c15ad0fe135b28
caffe-20160312/scripts/cpp_lint.py
python
ResetNolintSuppressions
()
Resets the set of NOLINT suppressions to empty.
Resets the set of NOLINT suppressions to empty.
[ "Resets", "the", "set", "of", "NOLINT", "suppressions", "to", "empty", "." ]
def ResetNolintSuppressions(): "Resets the set of NOLINT suppressions to empty." _error_suppressions.clear()
[ "def", "ResetNolintSuppressions", "(", ")", ":", "_error_suppressions", ".", "clear", "(", ")" ]
https://github.com/aimerykong/Low-Rank-Bilinear-Pooling/blob/487eb2c857fd9c95357a5166b0c15ad0fe135b28/caffe-20160312/scripts/cpp_lint.py#L495-L497
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Window.ScreenToClient
(*args, **kwargs)
return _core_.Window_ScreenToClient(*args, **kwargs)
ScreenToClient(self, Point pt) -> Point Converts from screen to client window coordinates.
ScreenToClient(self, Point pt) -> Point
[ "ScreenToClient", "(", "self", "Point", "pt", ")", "-", ">", "Point" ]
def ScreenToClient(*args, **kwargs): """ ScreenToClient(self, Point pt) -> Point Converts from screen to client window coordinates. """ return _core_.Window_ScreenToClient(*args, **kwargs)
[ "def", "ScreenToClient", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_ScreenToClient", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L11072-L11078
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py
python
_AddFieldPaths
(node, prefix, field_mask)
Adds the field paths descended from node to field_mask.
Adds the field paths descended from node to field_mask.
[ "Adds", "the", "field", "paths", "descended", "from", "node", "to", "field_mask", "." ]
def _AddFieldPaths(node, prefix, field_mask): """Adds the field paths descended from node to field_mask.""" if not node: field_mask.paths.append(prefix) return for name in sorted(node): if prefix: child_path = prefix + '.' + name else: child_path = name _AddFieldPaths(node[name], child_path, field_mask)
[ "def", "_AddFieldPaths", "(", "node", ",", "prefix", ",", "field_mask", ")", ":", "if", "not", "node", ":", "field_mask", ".", "paths", ".", "append", "(", "prefix", ")", "return", "for", "name", "in", "sorted", "(", "node", ")", ":", "if", "prefix", ...
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L674-L684
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/bindings/python/llvm/disassembler.py
python
Disassembler.get_instruction
(self, source, pc=0)
return (result, out_str.value)
Obtain the next instruction from an input source. The input source should be a str or bytearray or something that represents a sequence of bytes. This function will start reading bytes from the beginning of the source. The pc argument specifies the address that the first byte is at. This returns a 2-tuple of: long number of bytes read. 0 if no instruction was read. str representation of instruction. This will be the assembly that represents the instruction.
Obtain the next instruction from an input source.
[ "Obtain", "the", "next", "instruction", "from", "an", "input", "source", "." ]
def get_instruction(self, source, pc=0): """Obtain the next instruction from an input source. The input source should be a str or bytearray or something that represents a sequence of bytes. This function will start reading bytes from the beginning of the source. The pc argument specifies the address that the first byte is at. This returns a 2-tuple of: long number of bytes read. 0 if no instruction was read. str representation of instruction. This will be the assembly that represents the instruction. """ buf = cast(c_char_p(source), POINTER(c_ubyte)) out_str = cast((c_byte * 255)(), c_char_p) result = lib.LLVMDisasmInstruction(self, buf, c_uint64(len(source)), c_uint64(pc), out_str, 255) return (result, out_str.value)
[ "def", "get_instruction", "(", "self", ",", "source", ",", "pc", "=", "0", ")", ":", "buf", "=", "cast", "(", "c_char_p", "(", "source", ")", ",", "POINTER", "(", "c_ubyte", ")", ")", "out_str", "=", "cast", "(", "(", "c_byte", "*", "255", ")", "...
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/bindings/python/llvm/disassembler.py#L84-L107
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
PseudoDC.DrawBitmap
(*args, **kwargs)
return _gdi_.PseudoDC_DrawBitmap(*args, **kwargs)
DrawBitmap(self, Bitmap bmp, int x, int y, bool useMask=False) Draw a bitmap on the device context at the specified point. If *transparent* is true and the bitmap has a transparency mask, (or alpha channel on the platforms that support it) then the bitmap will be drawn transparently.
DrawBitmap(self, Bitmap bmp, int x, int y, bool useMask=False)
[ "DrawBitmap", "(", "self", "Bitmap", "bmp", "int", "x", "int", "y", "bool", "useMask", "=", "False", ")" ]
def DrawBitmap(*args, **kwargs): """ DrawBitmap(self, Bitmap bmp, int x, int y, bool useMask=False) Draw a bitmap on the device context at the specified point. If *transparent* is true and the bitmap has a transparency mask, (or alpha channel on the platforms that support it) then the bitmap will be drawn transparently. """ return _gdi_.PseudoDC_DrawBitmap(*args, **kwargs)
[ "def", "DrawBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "PseudoDC_DrawBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L8063-L8072
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/joblib/joblib/numpy_pickle_utils.py
python
_ensure_native_byte_order
(array)
return array
Use the byte order of the host while preserving values Does nothing if array already uses the system byte order.
Use the byte order of the host while preserving values
[ "Use", "the", "byte", "order", "of", "the", "host", "while", "preserving", "values" ]
def _ensure_native_byte_order(array): """Use the byte order of the host while preserving values Does nothing if array already uses the system byte order. """ if _is_numpy_array_byte_order_mismatch(array): array = array.byteswap().newbyteorder('=') return array
[ "def", "_ensure_native_byte_order", "(", "array", ")", ":", "if", "_is_numpy_array_byte_order_mismatch", "(", "array", ")", ":", "array", "=", "array", ".", "byteswap", "(", ")", ".", "newbyteorder", "(", "'='", ")", "return", "array" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/joblib/joblib/numpy_pickle_utils.py#L66-L73
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/visitor.py
python
NodeVisitor.visit
(self, node, *args, **kwargs)
return self.generic_visit(node, *args, **kwargs)
Visit a node.
Visit a node.
[ "Visit", "a", "node", "." ]
def visit(self, node, *args, **kwargs): """Visit a node.""" f = self.get_visitor(node) if f is not None: return f(node, *args, **kwargs) return self.generic_visit(node, *args, **kwargs)
[ "def", "visit", "(", "self", ",", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "f", "=", "self", ".", "get_visitor", "(", "node", ")", "if", "f", "is", "not", "None", ":", "return", "f", "(", "node", ",", "*", "args", ",", "*"...
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/visitor.py#L34-L39
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
MakeDisabledBitmap
(original)
return wx.BitmapFromImage(img.ConvertToGreyscale())
Creates a disabled-looking bitmap starting from the input one. :param `original`: an instance of :class:`Bitmap` to be greyed-out.
Creates a disabled-looking bitmap starting from the input one.
[ "Creates", "a", "disabled", "-", "looking", "bitmap", "starting", "from", "the", "input", "one", "." ]
def MakeDisabledBitmap(original): """ Creates a disabled-looking bitmap starting from the input one. :param `original`: an instance of :class:`Bitmap` to be greyed-out. """ img = original.ConvertToImage() return wx.BitmapFromImage(img.ConvertToGreyscale())
[ "def", "MakeDisabledBitmap", "(", "original", ")", ":", "img", "=", "original", ".", "ConvertToImage", "(", ")", "return", "wx", ".", "BitmapFromImage", "(", "img", ".", "ConvertToGreyscale", "(", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L613-L621