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
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/position.py
python
Position.open_order_buy_premium
(self)
return self._open_order_buy_premium
Gets the open_order_buy_premium of this Position. # noqa: E501 :return: The open_order_buy_premium of this Position. # noqa: E501 :rtype: float
Gets the open_order_buy_premium of this Position. # noqa: E501
[ "Gets", "the", "open_order_buy_premium", "of", "this", "Position", ".", "#", "noqa", ":", "E501" ]
def open_order_buy_premium(self): """Gets the open_order_buy_premium of this Position. # noqa: E501 :return: The open_order_buy_premium of this Position. # noqa: E501 :rtype: float """ return self._open_order_buy_premium
[ "def", "open_order_buy_premium", "(", "self", ")", ":", "return", "self", ".", "_open_order_buy_premium" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/position.py#L966-L973
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/aui.py
python
AuiTabContainer.SetActivePage
(*args)
return _aui.AuiTabContainer_SetActivePage(*args)
SetActivePage(self, Window page) -> bool SetActivePage(self, size_t page) -> bool
SetActivePage(self, Window page) -> bool SetActivePage(self, size_t page) -> bool
[ "SetActivePage", "(", "self", "Window", "page", ")", "-", ">", "bool", "SetActivePage", "(", "self", "size_t", "page", ")", "-", ">", "bool" ]
def SetActivePage(*args): """ SetActivePage(self, Window page) -> bool SetActivePage(self, size_t page) -> bool """ return _aui.AuiTabContainer_SetActivePage(*args)
[ "def", "SetActivePage", "(", "*", "args", ")", ":", "return", "_aui", ".", "AuiTabContainer_SetActivePage", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L1161-L1166
H-uru/Plasma
c2140ea046e82e9c199e257a7f2e7edb42602871
Scripts/Python/xAvatarCustomization.py
python
xAvatarCustomization.ISetWhatWearing
(self,avatar)
Gets whats being worn and sets the dialogs to show what we are wearing
Gets whats being worn and sets the dialogs to show what we are wearing
[ "Gets", "whats", "being", "worn", "and", "sets", "the", "dialogs", "to", "show", "what", "we", "are", "wearing" ]
def ISetWhatWearing(self,avatar): "Gets whats being worn and sets the dialogs to show what we are wearing" # assumes that WornList is already filled out global listboxDict for id, group in TheCloset.items(): listbox = listboxDict[id] acessoryListbox = listboxDict[id + kAccessoryLBOffset] # tell the listboxes to update themselves listbox.SetWhatWearing() listbox.UpdateScrollArrows() listbox.UpdateListbox() if id == kUpperBodyOptionsLB or id == kLwrBodyOptionsLB: # this is a texture listbox, so update our list of clothing items, and pick the currently worn one targetMesh = listbox.GetSelectedItem() texGroup = TextureGroup(group.clothingType,targetMesh.name) acessoryListbox.SetClothingList(texGroup.clothingItems) acessoryListbox.SetWhatWearing() acessoryListbox.UpdateScrollArrows() acessoryListbox.UpdateListbox() else: # standard accessory panel acessoryListbox.SetWhatWearing() acessoryListbox.UpdateScrollArrows() acessoryListbox.UpdateListbox()
[ "def", "ISetWhatWearing", "(", "self", ",", "avatar", ")", ":", "# assumes that WornList is already filled out", "global", "listboxDict", "for", "id", ",", "group", "in", "TheCloset", ".", "items", "(", ")", ":", "listbox", "=", "listboxDict", "[", "id", "]", ...
https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/xAvatarCustomization.py#L1523-L1547
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
build/android/gyp/util/build_utils.py
python
ExpandFileArgs
(args)
return new_args
Replaces file-arg placeholders in args. These placeholders have the form: @FileArg(filename:key1:key2:...:keyn) The value of such a placeholder is calculated by reading 'filename' as json. And then extracting the value at [key1][key2]...[keyn]. Note: This intentionally does not return the list of files that appear in such placeholders. An action that uses file-args *must* know the paths of those files prior to the parsing of the arguments (typically by explicitly listing them in the action's inputs in build files).
Replaces file-arg placeholders in args.
[ "Replaces", "file", "-", "arg", "placeholders", "in", "args", "." ]
def ExpandFileArgs(args): """Replaces file-arg placeholders in args. These placeholders have the form: @FileArg(filename:key1:key2:...:keyn) The value of such a placeholder is calculated by reading 'filename' as json. And then extracting the value at [key1][key2]...[keyn]. Note: This intentionally does not return the list of files that appear in such placeholders. An action that uses file-args *must* know the paths of those files prior to the parsing of the arguments (typically by explicitly listing them in the action's inputs in build files). """ new_args = list(args) file_jsons = dict() r = re.compile('@FileArg\((.*?)\)') for i, arg in enumerate(args): match = r.search(arg) if not match: continue if match.end() != len(arg): raise Exception('Unexpected characters after FileArg: ' + arg) lookup_path = match.group(1).split(':') file_path = lookup_path[0] if not file_path in file_jsons: file_jsons[file_path] = ReadJson(file_path) expansion = file_jsons[file_path] for k in lookup_path[1:]: expansion = expansion[k] new_args[i] = arg[:match.start()] + str(expansion) return new_args
[ "def", "ExpandFileArgs", "(", "args", ")", ":", "new_args", "=", "list", "(", "args", ")", "file_jsons", "=", "dict", "(", ")", "r", "=", "re", ".", "compile", "(", "'@FileArg\\((.*?)\\)'", ")", "for", "i", ",", "arg", "in", "enumerate", "(", "args", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/gyp/util/build_utils.py#L438-L474
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/grid.py
python
Grid.IsReadOnly
(*args, **kwargs)
return _grid.Grid_IsReadOnly(*args, **kwargs)
IsReadOnly(self, int row, int col) -> bool
IsReadOnly(self, int row, int col) -> bool
[ "IsReadOnly", "(", "self", "int", "row", "int", "col", ")", "-", ">", "bool" ]
def IsReadOnly(*args, **kwargs): """IsReadOnly(self, int row, int col) -> bool""" return _grid.Grid_IsReadOnly(*args, **kwargs)
[ "def", "IsReadOnly", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_IsReadOnly", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L2018-L2020
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/numbers.py
python
Integral.__rshift__
(self, other)
self >> other
self >> other
[ "self", ">>", "other" ]
def __rshift__(self, other): """self >> other""" raise NotImplementedError
[ "def", "__rshift__", "(", "self", ",", "other", ")", ":", "raise", "NotImplementedError" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/numbers.py#L330-L332
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plot_color_queue.py
python
ColorQueue._initialise_queue
(self)
Initialize the heap queue with the color_cache
Initialize the heap queue with the color_cache
[ "Initialize", "the", "heap", "queue", "with", "the", "color_cache" ]
def _initialise_queue(self): """Initialize the heap queue with the color_cache""" self._queue = [] for color, priority in self._color_cache.items(): heapq.heappush(self._queue, (priority, color))
[ "def", "_initialise_queue", "(", "self", ")", ":", "self", ".", "_queue", "=", "[", "]", "for", "color", ",", "priority", "in", "self", ".", "_color_cache", ".", "items", "(", ")", ":", "heapq", ".", "heappush", "(", "self", ".", "_queue", ",", "(", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/plot_widget/plotting_canvas/plot_color_queue.py#L44-L48
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/indexes/range.py
python
RangeIndex.is_unique
(self)
return True
return if the index has unique values
return if the index has unique values
[ "return", "if", "the", "index", "has", "unique", "values" ]
def is_unique(self): """ return if the index has unique values """ return True
[ "def", "is_unique", "(", "self", ")", ":", "return", "True" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/indexes/range.py#L253-L255
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/learn/python/learn/learn_io/graph_io.py
python
read_batch_features
(file_pattern, batch_size, features, reader, randomize_input=True, num_epochs=None, queue_capacity=10000, reader_num_threads=1, parser_num_threads=1, name=None)
return features
Adds operations to read, queue, batch and parse `Example` protos. Given file pattern (or list of files), will setup a queue for file names, read `Example` proto using provided `reader`, use batch queue to create batches of examples of size `batch_size` and parse example given `features` specification. All queue runners are added to the queue runners collection, and may be started via `start_queue_runners`. All ops are added to the default graph. Args: file_pattern: List of files or pattern of file paths containing `Example` records. See `tf.gfile.Glob` for pattern rules. batch_size: An int or scalar `Tensor` specifying the batch size to use. features: A `dict` mapping feature keys to `FixedLenFeature` or `VarLenFeature` values. reader: A function or class that returns an object with `read` method, (filename tensor) -> (example tensor). randomize_input: Whether the input should be randomized. num_epochs: Integer specifying the number of times to read through the dataset. If None, cycles through the dataset forever. NOTE - If specified, creates a variable that must be initialized, so call tf.initialize_local_variables() as shown in the tests. queue_capacity: Capacity for input queue. reader_num_threads: The number of threads to read examples. parser_num_threads: The number of threads to parse examples. records to read at once name: Name of resulting op. Returns: A dict of `Tensor` or `SparseTensor` objects for each in `features`. If `keep_keys` is `True`, returns tuple of string `Tensor` and above dict. Raises: ValueError: for invalid inputs.
Adds operations to read, queue, batch and parse `Example` protos.
[ "Adds", "operations", "to", "read", "queue", "batch", "and", "parse", "Example", "protos", "." ]
def read_batch_features(file_pattern, batch_size, features, reader, randomize_input=True, num_epochs=None, queue_capacity=10000, reader_num_threads=1, parser_num_threads=1, name=None): """Adds operations to read, queue, batch and parse `Example` protos. Given file pattern (or list of files), will setup a queue for file names, read `Example` proto using provided `reader`, use batch queue to create batches of examples of size `batch_size` and parse example given `features` specification. All queue runners are added to the queue runners collection, and may be started via `start_queue_runners`. All ops are added to the default graph. Args: file_pattern: List of files or pattern of file paths containing `Example` records. See `tf.gfile.Glob` for pattern rules. batch_size: An int or scalar `Tensor` specifying the batch size to use. features: A `dict` mapping feature keys to `FixedLenFeature` or `VarLenFeature` values. reader: A function or class that returns an object with `read` method, (filename tensor) -> (example tensor). randomize_input: Whether the input should be randomized. num_epochs: Integer specifying the number of times to read through the dataset. If None, cycles through the dataset forever. NOTE - If specified, creates a variable that must be initialized, so call tf.initialize_local_variables() as shown in the tests. queue_capacity: Capacity for input queue. reader_num_threads: The number of threads to read examples. parser_num_threads: The number of threads to parse examples. records to read at once name: Name of resulting op. Returns: A dict of `Tensor` or `SparseTensor` objects for each in `features`. If `keep_keys` is `True`, returns tuple of string `Tensor` and above dict. Raises: ValueError: for invalid inputs. """ _, features = read_keyed_batch_features( file_pattern, batch_size, features, reader, randomize_input=randomize_input, num_epochs=num_epochs, queue_capacity=queue_capacity, reader_num_threads=reader_num_threads, parser_num_threads=parser_num_threads, name=name) return features
[ "def", "read_batch_features", "(", "file_pattern", ",", "batch_size", ",", "features", ",", "reader", ",", "randomize_input", "=", "True", ",", "num_epochs", "=", "None", ",", "queue_capacity", "=", "10000", ",", "reader_num_threads", "=", "1", ",", "parser_num_...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/learn_io/graph_io.py#L355-L402
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py
python
JIRA.search_users
(self, user, startAt=0, maxResults=50, includeActive=True, includeInactive=False)
return self._fetch_pages(User, None, 'user/search', startAt, maxResults, params)
Get a list of user Resources that match the specified search string. :param user: a string to match usernames, name or email against. :param startAt: index of the first user to return. :param maxResults: maximum number of users to return. If maxResults evaluates as False, it will try to get all items in batches. :param includeActive: If true, then active users are included in the results. :param includeInactive: If true, then inactive users are included in the results.
Get a list of user Resources that match the specified search string.
[ "Get", "a", "list", "of", "user", "Resources", "that", "match", "the", "specified", "search", "string", "." ]
def search_users(self, user, startAt=0, maxResults=50, includeActive=True, includeInactive=False): """Get a list of user Resources that match the specified search string. :param user: a string to match usernames, name or email against. :param startAt: index of the first user to return. :param maxResults: maximum number of users to return. If maxResults evaluates as False, it will try to get all items in batches. :param includeActive: If true, then active users are included in the results. :param includeInactive: If true, then inactive users are included in the results. """ params = { 'username': user, 'includeActive': includeActive, 'includeInactive': includeInactive} return self._fetch_pages(User, None, 'user/search', startAt, maxResults, params)
[ "def", "search_users", "(", "self", ",", "user", ",", "startAt", "=", "0", ",", "maxResults", "=", "50", ",", "includeActive", "=", "True", ",", "includeInactive", "=", "False", ")", ":", "params", "=", "{", "'username'", ":", "user", ",", "'includeActiv...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py#L2283-L2297
google/angle
d5df233189cad620b8e0de653fe5e6cb778e209d
third_party/logdog/logdog/stream.py
python
StreamProtocolRegistry.create
(self, uri, **kwargs)
return client_cls._create(value, **kwargs)
Returns (StreamClient): A stream client for the specified URI. This uses the default StreamProtocolRegistry to instantiate a StreamClient for the specified URI. Args: uri (str): The streamserver URI. kwargs: keyword arguments to forward to the stream. See StreamClient.__init__. Raises: ValueError: if the supplied URI references an invalid or improperly configured streamserver.
Returns (StreamClient): A stream client for the specified URI.
[ "Returns", "(", "StreamClient", ")", ":", "A", "stream", "client", "for", "the", "specified", "URI", "." ]
def create(self, uri, **kwargs): """Returns (StreamClient): A stream client for the specified URI. This uses the default StreamProtocolRegistry to instantiate a StreamClient for the specified URI. Args: uri (str): The streamserver URI. kwargs: keyword arguments to forward to the stream. See StreamClient.__init__. Raises: ValueError: if the supplied URI references an invalid or improperly configured streamserver. """ uri = uri.split(':', 1) if len(uri) != 2: raise ValueError('Invalid stream server URI [%s]' % (uri,)) protocol, value = uri client_cls = self._registry.get(protocol) if not client_cls: raise ValueError('Unknown stream client protocol (%s)' % (protocol,)) return client_cls._create(value, **kwargs)
[ "def", "create", "(", "self", ",", "uri", ",", "*", "*", "kwargs", ")", ":", "uri", "=", "uri", ".", "split", "(", "':'", ",", "1", ")", "if", "len", "(", "uri", ")", "!=", "2", ":", "raise", "ValueError", "(", "'Invalid stream server URI [%s]'", "...
https://github.com/google/angle/blob/d5df233189cad620b8e0de653fe5e6cb778e209d/third_party/logdog/logdog/stream.py#L108-L131
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
tools/importers/common/converters.py
python
LookupTable.get_port_elements_and_memory_layout_for_input
(self, importer_node: ImporterNode, input_index=0)
return (port_elements, port_memory_layout)
Returns an (ell.nodes.PortElements, ell.nodes.PortMemoryLayout) for the corresponding input of the ImporterNode.
Returns an (ell.nodes.PortElements, ell.nodes.PortMemoryLayout) for the corresponding input of the ImporterNode.
[ "Returns", "an", "(", "ell", ".", "nodes", ".", "PortElements", "ell", ".", "nodes", ".", "PortMemoryLayout", ")", "for", "the", "corresponding", "input", "of", "the", "ImporterNode", "." ]
def get_port_elements_and_memory_layout_for_input(self, importer_node: ImporterNode, input_index=0) \ -> (ell.nodes.PortElements, ell.model.PortMemoryLayout): """ Returns an (ell.nodes.PortElements, ell.nodes.PortMemoryLayout) for the corresponding input of the ImporterNode. """ try: owning_ell_node = self.get_owning_node_for_output(importer_node.inputs[input_index]) owning_importer_node = self.ell_id_to_owning_importer_node[owning_ell_node.GetId()] padding = owning_importer_node.output_padding["size"] output_shape = owning_importer_node.output_shapes[0] port_elements = self.get_port_elements_for_input(importer_node, input_index) port_memory_layout = memory_shapes.get_ell_port_memory_layout(output_shape[0], output_shape[1], padding) except BaseException: raise Exception("Could not get PortMemoryElements or PortMemoryLayout for importer node {}, input {}" .format(importer_node.id, input_index)) return (port_elements, port_memory_layout)
[ "def", "get_port_elements_and_memory_layout_for_input", "(", "self", ",", "importer_node", ":", "ImporterNode", ",", "input_index", "=", "0", ")", "->", "(", "ell", ".", "nodes", ".", "PortElements", ",", "ell", ".", "model", ".", "PortMemoryLayout", ")", ":", ...
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/importers/common/converters.py#L246-L261
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/pytables.py
python
AppendableFrameTable.get_object
(cls, obj, transposed: bool)
return obj
these are written transposed
these are written transposed
[ "these", "are", "written", "transposed" ]
def get_object(cls, obj, transposed: bool): """ these are written transposed """ if transposed: obj = obj.T return obj
[ "def", "get_object", "(", "cls", ",", "obj", ",", "transposed", ":", "bool", ")", ":", "if", "transposed", ":", "obj", "=", "obj", ".", "T", "return", "obj" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/pytables.py#L4357-L4361
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/http/cookiejar.py
python
join_header_words
(lists)
return ", ".join(headers)
Do the inverse (almost) of the conversion done by split_header_words. Takes a list of lists of (key, value) pairs and produces a single header value. Attribute values are quoted if needed. >>> join_header_words([[("text/plain", None), ("charset", "iso-8859-1")]]) 'text/plain; charset="iso-8859-1"' >>> join_header_words([[("text/plain", None)], [("charset", "iso-8859-1")]]) 'text/plain, charset="iso-8859-1"'
Do the inverse (almost) of the conversion done by split_header_words.
[ "Do", "the", "inverse", "(", "almost", ")", "of", "the", "conversion", "done", "by", "split_header_words", "." ]
def join_header_words(lists): """Do the inverse (almost) of the conversion done by split_header_words. Takes a list of lists of (key, value) pairs and produces a single header value. Attribute values are quoted if needed. >>> join_header_words([[("text/plain", None), ("charset", "iso-8859-1")]]) 'text/plain; charset="iso-8859-1"' >>> join_header_words([[("text/plain", None)], [("charset", "iso-8859-1")]]) 'text/plain, charset="iso-8859-1"' """ headers = [] for pairs in lists: attr = [] for k, v in pairs: if v is not None: if not re.search(r"^\w+$", v): v = HEADER_JOIN_ESCAPE_RE.sub(r"\\\1", v) # escape " and \ v = '"%s"' % v k = "%s=%s" % (k, v) attr.append(k) if attr: headers.append("; ".join(attr)) return ", ".join(headers)
[ "def", "join_header_words", "(", "lists", ")", ":", "headers", "=", "[", "]", "for", "pairs", "in", "lists", ":", "attr", "=", "[", "]", "for", "k", ",", "v", "in", "pairs", ":", "if", "v", "is", "not", "None", ":", "if", "not", "re", ".", "sea...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/http/cookiejar.py#L426-L449
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/jinja2/ext.py
python
InternationalizationExtension._make_node
(self, singular, plural, variables, plural_expr, vars_referenced, num_called_num)
return nodes.Output([node])
Generates a useful node from the data provided.
Generates a useful node from the data provided.
[ "Generates", "a", "useful", "node", "from", "the", "data", "provided", "." ]
def _make_node(self, singular, plural, variables, plural_expr, vars_referenced, num_called_num): """Generates a useful node from the data provided.""" # no variables referenced? no need to escape for old style # gettext invocations only if there are vars. if not vars_referenced and not self.environment.newstyle_gettext: singular = singular.replace('%%', '%') if plural: plural = plural.replace('%%', '%') # singular only: if plural_expr is None: gettext = nodes.Name('gettext', 'load') node = nodes.Call(gettext, [nodes.Const(singular)], [], None, None) # singular and plural else: ngettext = nodes.Name('ngettext', 'load') node = nodes.Call(ngettext, [ nodes.Const(singular), nodes.Const(plural), plural_expr ], [], None, None) # in case newstyle gettext is used, the method is powerful # enough to handle the variable expansion and autoescape # handling itself if self.environment.newstyle_gettext: for key, value in variables.iteritems(): # the function adds that later anyways in case num was # called num, so just skip it. if num_called_num and key == 'num': continue node.kwargs.append(nodes.Keyword(key, value)) # otherwise do that here else: # mark the return value as safe if we are in an # environment with autoescaping turned on node = nodes.MarkSafeIfAutoescape(node) if variables: node = nodes.Mod(node, nodes.Dict([ nodes.Pair(nodes.Const(key), value) for key, value in variables.items() ])) return nodes.Output([node])
[ "def", "_make_node", "(", "self", ",", "singular", ",", "plural", ",", "variables", ",", "plural_expr", ",", "vars_referenced", ",", "num_called_num", ")", ":", "# no variables referenced? no need to escape for old style", "# gettext invocations only if there are vars.", "if...
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/jinja2/ext.py#L328-L374
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/profiler/parser/memory_usage_parser.py
python
MemoryUsageParser._parse_graph_memory
(self, graphs)
Parse memory usage based on subgraphs.
Parse memory usage based on subgraphs.
[ "Parse", "memory", "usage", "based", "on", "subgraphs", "." ]
def _parse_graph_memory(self, graphs): """Parse memory usage based on subgraphs.""" for graph_proto in graphs: graph_id = graph_proto.graph_id if graph_id is None: logger.info('Graph id is missing, skipped the graph.') continue graph_parser = GraphMemoryParser(graph_proto, self._points, self._framework) graph = graph_parser.parse_graph() if graph: self._graphs_dict[graph_id] = graph # update global memory usage data self._peak_mem = max(self._peak_mem, graph_parser.peak_mem) self._mem_summary['static_mem'] += graph_parser.static_mem self._mem_summary['allocations'] += graph_parser.allocations self._mem_summary['deallocations'] += graph_parser.deallocations
[ "def", "_parse_graph_memory", "(", "self", ",", "graphs", ")", ":", "for", "graph_proto", "in", "graphs", ":", "graph_id", "=", "graph_proto", ".", "graph_id", "if", "graph_id", "is", "None", ":", "logger", ".", "info", "(", "'Graph id is missing, skipped the gr...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/profiler/parser/memory_usage_parser.py#L113-L130
scanner-research/scanner
04a0c4b4196341995985acd729c0788aab823e1c
python/scannerpy/kernel.py
python
Kernel.execute
(self, stream_parameter: bytes)
r"""Runs the kernel on input elements and returns new output elements. Parameters ---------- stream_parameter An example stream parameter. Must be annotated with a stream parameter type. See :ref:`stream-parameters`. Returns ------- bytes The outputs for the operation.
r"""Runs the kernel on input elements and returns new output elements.
[ "r", "Runs", "the", "kernel", "on", "input", "elements", "and", "returns", "new", "output", "elements", "." ]
def execute(self, stream_parameter: bytes) -> bytes: r"""Runs the kernel on input elements and returns new output elements. Parameters ---------- stream_parameter An example stream parameter. Must be annotated with a stream parameter type. See :ref:`stream-parameters`. Returns ------- bytes The outputs for the operation. """ raise NotImplementedError
[ "def", "execute", "(", "self", ",", "stream_parameter", ":", "bytes", ")", "->", "bytes", ":", "raise", "NotImplementedError" ]
https://github.com/scanner-research/scanner/blob/04a0c4b4196341995985acd729c0788aab823e1c/python/scannerpy/kernel.py#L63-L78
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/check_ops.py
python
assert_rank_in_v2
(x, ranks, message=None, name=None)
return assert_rank_in(x=x, ranks=ranks, message=message, name=name)
Assert that `x` has a rank in `ranks`. This Op checks that the rank of `x` is in `ranks`. If `x` has a different rank, `message`, as well as the shape of `x` are printed, and `InvalidArgumentError` is raised. Args: x: `Tensor`. ranks: `Iterable` of scalar `Tensor` objects. message: A string to prefix to the default message. name: A name for this operation (optional). Defaults to "assert_rank_in". Returns: Op raising `InvalidArgumentError` unless rank of `x` is in `ranks`. If static checks determine `x` has matching rank, a `no_op` is returned. This can be used with `tf.control_dependencies` inside of `tf.function`s to block followup computation until the check has executed. @compatibility(eager) returns None @end_compatibility Raises: InvalidArgumentError: `x` does not have rank in `ranks`, but the rank cannot be statically determined. ValueError: If static checks determine `x` has mismatched rank.
Assert that `x` has a rank in `ranks`.
[ "Assert", "that", "x", "has", "a", "rank", "in", "ranks", "." ]
def assert_rank_in_v2(x, ranks, message=None, name=None): """Assert that `x` has a rank in `ranks`. This Op checks that the rank of `x` is in `ranks`. If `x` has a different rank, `message`, as well as the shape of `x` are printed, and `InvalidArgumentError` is raised. Args: x: `Tensor`. ranks: `Iterable` of scalar `Tensor` objects. message: A string to prefix to the default message. name: A name for this operation (optional). Defaults to "assert_rank_in". Returns: Op raising `InvalidArgumentError` unless rank of `x` is in `ranks`. If static checks determine `x` has matching rank, a `no_op` is returned. This can be used with `tf.control_dependencies` inside of `tf.function`s to block followup computation until the check has executed. @compatibility(eager) returns None @end_compatibility Raises: InvalidArgumentError: `x` does not have rank in `ranks`, but the rank cannot be statically determined. ValueError: If static checks determine `x` has mismatched rank. """ return assert_rank_in(x=x, ranks=ranks, message=message, name=name)
[ "def", "assert_rank_in_v2", "(", "x", ",", "ranks", ",", "message", "=", "None", ",", "name", "=", "None", ")", ":", "return", "assert_rank_in", "(", "x", "=", "x", ",", "ranks", "=", "ranks", ",", "message", "=", "message", ",", "name", "=", "name",...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/check_ops.py#L1324-L1352
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib-tk/Tkinter.py
python
Text.__init__
(self, master=None, cnf={}, **kw)
Construct a text widget with the parent MASTER. STANDARD OPTIONS background, borderwidth, cursor, exportselection, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, padx, pady, relief, selectbackground, selectborderwidth, selectforeground, setgrid, takefocus, xscrollcommand, yscrollcommand, WIDGET-SPECIFIC OPTIONS autoseparators, height, maxundo, spacing1, spacing2, spacing3, state, tabs, undo, width, wrap,
Construct a text widget with the parent MASTER.
[ "Construct", "a", "text", "widget", "with", "the", "parent", "MASTER", "." ]
def __init__(self, master=None, cnf={}, **kw): """Construct a text widget with the parent MASTER. STANDARD OPTIONS background, borderwidth, cursor, exportselection, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, padx, pady, relief, selectbackground, selectborderwidth, selectforeground, setgrid, takefocus, xscrollcommand, yscrollcommand, WIDGET-SPECIFIC OPTIONS autoseparators, height, maxundo, spacing1, spacing2, spacing3, state, tabs, undo, width, wrap, """ Widget.__init__(self, master, 'text', cnf, kw)
[ "def", "__init__", "(", "self", ",", "master", "=", "None", ",", "cnf", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "Widget", ".", "__init__", "(", "self", ",", "master", ",", "'text'", ",", "cnf", ",", "kw", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L2932-L2955
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/which/setup.py
python
_getBinDir
()
return bindir
Return the current Python's bindir.
Return the current Python's bindir.
[ "Return", "the", "current", "Python", "s", "bindir", "." ]
def _getBinDir(): """Return the current Python's bindir.""" if sys.platform.startswith("win"): bindir = sys.prefix else: bindir = os.path.join(sys.prefix, "bin") return bindir
[ "def", "_getBinDir", "(", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "bindir", "=", "sys", ".", "prefix", "else", ":", "bindir", "=", "os", ".", "path", ".", "join", "(", "sys", ".", "prefix", ",", "\"bin\"...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/which/setup.py#L19-L25
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/special_math_ops.py
python
bessel_i0
(x, name=None)
Computes the Bessel i0 function of `x` element-wise. Modified Bessel function of order 0. It is preferable to use the numerically stabler function `i0e(x)` instead. >>> tf.math.special.bessel_i0([-1., -0.5, 0.5, 1.]).numpy() array([1.26606588, 1.06348337, 1.06348337, 1.26606588], dtype=float32) Args: x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. @compatibility(scipy) Equivalent to scipy.special.i0 @end_compatibility
Computes the Bessel i0 function of `x` element-wise.
[ "Computes", "the", "Bessel", "i0", "function", "of", "x", "element", "-", "wise", "." ]
def bessel_i0(x, name=None): """Computes the Bessel i0 function of `x` element-wise. Modified Bessel function of order 0. It is preferable to use the numerically stabler function `i0e(x)` instead. >>> tf.math.special.bessel_i0([-1., -0.5, 0.5, 1.]).numpy() array([1.26606588, 1.06348337, 1.06348337, 1.26606588], dtype=float32) Args: x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`. @compatibility(scipy) Equivalent to scipy.special.i0 @end_compatibility """ with ops.name_scope(name, 'bessel_i0', [x]): return gen_special_math_ops.bessel_i0(x)
[ "def", "bessel_i0", "(", "x", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "'bessel_i0'", ",", "[", "x", "]", ")", ":", "return", "gen_special_math_ops", ".", "bessel_i0", "(", "x", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/special_math_ops.py#L255-L278
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
grc/core/generator/cpp_hier_block.py
python
get_hier_block_io
(flow_graph, direction, domain=None)
Get a list of io ports for this flow graph. Returns a list of dicts with: type, label, vlen, size, optional
Get a list of io ports for this flow graph.
[ "Get", "a", "list", "of", "io", "ports", "for", "this", "flow", "graph", "." ]
def get_hier_block_io(flow_graph, direction, domain=None): """ Get a list of io ports for this flow graph. Returns a list of dicts with: type, label, vlen, size, optional """ pads = flow_graph.get_pad_sources( ) if direction == 'inputs' else flow_graph.get_pad_sinks() for pad in pads: for port in (pad.sources if direction == 'inputs' else pad.sinks): if domain and port.domain != domain: continue yield port
[ "def", "get_hier_block_io", "(", "flow_graph", ",", "direction", ",", "domain", "=", "None", ")", ":", "pads", "=", "flow_graph", ".", "get_pad_sources", "(", ")", "if", "direction", "==", "'inputs'", "else", "flow_graph", ".", "get_pad_sinks", "(", ")", "fo...
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/generator/cpp_hier_block.py#L206-L219
mapeditor/tiled
b7abf3c9606aa53442bab8fc6a44a1b2797226e0
src/plugins/python/scripts/mappy.py
python
FMPColormap.pack
(self, cmap)
cmap -- T.qt.QImage.colorTable
cmap -- T.qt.QImage.colorTable
[ "cmap", "--", "T", ".", "qt", ".", "QImage", ".", "colorTable" ]
def pack(self, cmap): """cmap -- T.qt.QImage.colorTable""" yield fmpchunk(id='CMAP', len=len(list(cmap))).pack() for c in cmap: yield struct.pack('3B', (c.qRed,c.qGreen,c.qBlue))
[ "def", "pack", "(", "self", ",", "cmap", ")", ":", "yield", "fmpchunk", "(", "id", "=", "'CMAP'", ",", "len", "=", "len", "(", "list", "(", "cmap", ")", ")", ")", ".", "pack", "(", ")", "for", "c", "in", "cmap", ":", "yield", "struct", ".", "...
https://github.com/mapeditor/tiled/blob/b7abf3c9606aa53442bab8fc6a44a1b2797226e0/src/plugins/python/scripts/mappy.py#L248-L252
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/lib/io/file_io.py
python
atomic_write_string_to_file
(filename, contents, overwrite=True)
Writes to `filename` atomically. This means that when `filename` appears in the filesystem, it will contain all of `contents`. With write_string_to_file, it is possible for the file to appear in the filesystem with `contents` only partially written. Accomplished by writing to a temp file and then renaming it. Args: filename: string, pathname for a file contents: string, contents that need to be written to the file overwrite: boolean, if false it's an error for `filename` to be occupied by an existing file.
Writes to `filename` atomically.
[ "Writes", "to", "filename", "atomically", "." ]
def atomic_write_string_to_file(filename, contents, overwrite=True): """Writes to `filename` atomically. This means that when `filename` appears in the filesystem, it will contain all of `contents`. With write_string_to_file, it is possible for the file to appear in the filesystem with `contents` only partially written. Accomplished by writing to a temp file and then renaming it. Args: filename: string, pathname for a file contents: string, contents that need to be written to the file overwrite: boolean, if false it's an error for `filename` to be occupied by an existing file. """ if not has_atomic_move(filename): write_string_to_file(filename, contents) else: temp_pathname = filename + ".tmp" + uuid.uuid4().hex write_string_to_file(temp_pathname, contents) try: rename(temp_pathname, filename, overwrite) except errors.OpError: delete_file(temp_pathname) raise
[ "def", "atomic_write_string_to_file", "(", "filename", ",", "contents", ",", "overwrite", "=", "True", ")", ":", "if", "not", "has_atomic_move", "(", "filename", ")", ":", "write_string_to_file", "(", "filename", ",", "contents", ")", "else", ":", "temp_pathname...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/lib/io/file_io.py#L624-L648
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextCtrl.EndSymbolBullet
(*args, **kwargs)
return _richtext.RichTextCtrl_EndSymbolBullet(*args, **kwargs)
EndSymbolBullet(self) -> bool End symbol bullet
EndSymbolBullet(self) -> bool
[ "EndSymbolBullet", "(", "self", ")", "-", ">", "bool" ]
def EndSymbolBullet(*args, **kwargs): """ EndSymbolBullet(self) -> bool End symbol bullet """ return _richtext.RichTextCtrl_EndSymbolBullet(*args, **kwargs)
[ "def", "EndSymbolBullet", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_EndSymbolBullet", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L3540-L3546
gklz1982/caffe-yolov2
ebb27029db4ddc0d40e520634633b0fa9cdcc10d
scripts/cpp_lint.py
python
FileInfo.FullName
(self)
return os.path.abspath(self._filename).replace('\\', '/')
Make Windows paths like Unix.
Make Windows paths like Unix.
[ "Make", "Windows", "paths", "like", "Unix", "." ]
def FullName(self): """Make Windows paths like Unix.""" return os.path.abspath(self._filename).replace('\\', '/')
[ "def", "FullName", "(", "self", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "self", ".", "_filename", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")" ]
https://github.com/gklz1982/caffe-yolov2/blob/ebb27029db4ddc0d40e520634633b0fa9cdcc10d/scripts/cpp_lint.py#L881-L883
andrivet/ADVi3pp
31afb95333f2d830a5b762ea030a4a59ec27cb88
buildroot/share/scripts/createTemperatureLookupMarlin.py
python
Thermistor.voltage
(self, adc)
return adc * VSTEP
Convert ADC reading into a Voltage
Convert ADC reading into a Voltage
[ "Convert", "ADC", "reading", "into", "a", "Voltage" ]
def voltage(self, adc): "Convert ADC reading into a Voltage" return adc * VSTEP
[ "def", "voltage", "(", "self", ",", "adc", ")", ":", "return", "adc", "*", "VSTEP" ]
https://github.com/andrivet/ADVi3pp/blob/31afb95333f2d830a5b762ea030a4a59ec27cb88/buildroot/share/scripts/createTemperatureLookupMarlin.py#L67-L69
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
RichTextObject.AdjustAvailableSpace
(*args, **kwargs)
return _richtext.RichTextObject_AdjustAvailableSpace(*args, **kwargs)
AdjustAvailableSpace(DC dc, RichTextBuffer buffer, RichTextAttr parentAttr, RichTextAttr childAttr, Rect availableParentSpace, Rect availableContainerSpace) -> Rect
AdjustAvailableSpace(DC dc, RichTextBuffer buffer, RichTextAttr parentAttr, RichTextAttr childAttr, Rect availableParentSpace, Rect availableContainerSpace) -> Rect
[ "AdjustAvailableSpace", "(", "DC", "dc", "RichTextBuffer", "buffer", "RichTextAttr", "parentAttr", "RichTextAttr", "childAttr", "Rect", "availableParentSpace", "Rect", "availableContainerSpace", ")", "-", ">", "Rect" ]
def AdjustAvailableSpace(*args, **kwargs): """ AdjustAvailableSpace(DC dc, RichTextBuffer buffer, RichTextAttr parentAttr, RichTextAttr childAttr, Rect availableParentSpace, Rect availableContainerSpace) -> Rect """ return _richtext.RichTextObject_AdjustAvailableSpace(*args, **kwargs)
[ "def", "AdjustAvailableSpace", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextObject_AdjustAvailableSpace", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L1442-L1448
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/max.py
python
max.is_atom_log_log_convex
(self)
return True
Is the atom log-log convex?
Is the atom log-log convex?
[ "Is", "the", "atom", "log", "-", "log", "convex?" ]
def is_atom_log_log_convex(self) -> bool: """Is the atom log-log convex? """ return True
[ "def", "is_atom_log_log_convex", "(", "self", ")", "->", "bool", ":", "return", "True" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/max.py#L84-L87
musescore/MuseScore
a817fea23e3c2be30847b7fde5b01746222c252e
thirdparty/freetype/src/tools/glnames.py
python
dump_encoding
( file, encoding_name, encoding_list )
dump a given encoding
dump a given encoding
[ "dump", "a", "given", "encoding" ]
def dump_encoding( file, encoding_name, encoding_list ): """dump a given encoding""" write = file.write write( " /* the following are indices into the SID name table */\n" ) write( " static const unsigned short " + encoding_name + "[" + repr( len( encoding_list ) ) + "] =\n" ) write( " {\n" ) line = " " comma = "" col = 0 for value in encoding_list: line += comma line += "%3d" % value comma = "," col += 1 if col == 16: col = 0 comma = ",\n " write( line + "\n };\n\n\n" )
[ "def", "dump_encoding", "(", "file", ",", "encoding_name", ",", "encoding_list", ")", ":", "write", "=", "file", ".", "write", "write", "(", "\" /* the following are indices into the SID name table */\\n\"", ")", "write", "(", "\" static const unsigned short \"", "+", ...
https://github.com/musescore/MuseScore/blob/a817fea23e3c2be30847b7fde5b01746222c252e/thirdparty/freetype/src/tools/glnames.py#L5186-L5207
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/target.py
python
set_hsa_kernel
(fn)
Ensure `fn` is usable as a SPIR kernel. - Fix calling convention - Add metadata
Ensure `fn` is usable as a SPIR kernel. - Fix calling convention - Add metadata
[ "Ensure", "fn", "is", "usable", "as", "a", "SPIR", "kernel", ".", "-", "Fix", "calling", "convention", "-", "Add", "metadata" ]
def set_hsa_kernel(fn): """ Ensure `fn` is usable as a SPIR kernel. - Fix calling convention - Add metadata """ mod = fn.module # Set nounwind # fn.add_attribute(lc.ATTR_NO_UNWIND) # Set SPIR kernel calling convention fn.calling_convention = CC_SPIR_KERNEL # Mark kernels ocl_kernels = mod.get_or_insert_named_metadata("opencl.kernels") ocl_kernels.add(lc.MetaData.get(mod, [fn, gen_arg_addrspace_md(fn), gen_arg_access_qual_md(fn), gen_arg_type(fn), gen_arg_type_qual(fn), gen_arg_base_type(fn)])) # SPIR version 2.0 make_constant = lambda x: lc.Constant.int(lc.Type.int(), x) spir_version_constant = [make_constant(x) for x in SPIR_VERSION] spir_version = mod.get_or_insert_named_metadata("opencl.spir.version") if not spir_version.operands: spir_version.add(lc.MetaData.get(mod, spir_version_constant)) ocl_version = mod.get_or_insert_named_metadata("opencl.ocl.version") if not ocl_version.operands: ocl_version.add(lc.MetaData.get(mod, spir_version_constant))
[ "def", "set_hsa_kernel", "(", "fn", ")", ":", "mod", "=", "fn", ".", "module", "# Set nounwind", "# fn.add_attribute(lc.ATTR_NO_UNWIND)", "# Set SPIR kernel calling convention", "fn", ".", "calling_convention", "=", "CC_SPIR_KERNEL", "# Mark kernels", "ocl_kernels", "=", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/target.py#L203-L236
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/operator.py
python
sub
(a, b)
return a - b
Same as a - b.
Same as a - b.
[ "Same", "as", "a", "-", "b", "." ]
def sub(a, b): "Same as a - b." return a - b
[ "def", "sub", "(", "a", ",", "b", ")", ":", "return", "a", "-", "b" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/operator.py#L132-L134
potassco/clingo
e0c91d8f95cc28de1c480a871f9c97c30de83d40
libpyclingo/clingo/ast.py
python
Transformer._dispatch
(self, ast: Union[None, AST, ASTSequence], *args: Any, **kwargs: Any)
Visit and transform an (optional) AST or a sequence of ASTs.
Visit and transform an (optional) AST or a sequence of ASTs.
[ "Visit", "and", "transform", "an", "(", "optional", ")", "AST", "or", "a", "sequence", "of", "ASTs", "." ]
def _dispatch(self, ast: Union[None, AST, ASTSequence], *args: Any, **kwargs: Any) -> Union[None, AST, MutableSequence[AST]]: ''' Visit and transform an (optional) AST or a sequence of ASTs. ''' if ast is None: return ast if isinstance(ast, AST): return self.visit(ast, *args, **kwargs) # type: ignore if isinstance(ast, abc.Sequence): return self.visit_sequence(ast, *args, **kwargs) raise TypeError('unexpected type')
[ "def", "_dispatch", "(", "self", ",", "ast", ":", "Union", "[", "None", ",", "AST", ",", "ASTSequence", "]", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Union", "[", "None", ",", "AST", ",", "MutableSequence", "...
https://github.com/potassco/clingo/blob/e0c91d8f95cc28de1c480a871f9c97c30de83d40/libpyclingo/clingo/ast.py#L1175-L1188
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/pytables.py
python
AppendableTable.write_data_chunk
( self, rows: np.ndarray, indexes: list[np.ndarray], mask: np.ndarray | None, values: list[np.ndarray], )
Parameters ---------- rows : an empty memory space where we are putting the chunk indexes : an array of the indexes mask : an array of the masks values : an array of the values
Parameters ---------- rows : an empty memory space where we are putting the chunk indexes : an array of the indexes mask : an array of the masks values : an array of the values
[ "Parameters", "----------", "rows", ":", "an", "empty", "memory", "space", "where", "we", "are", "putting", "the", "chunk", "indexes", ":", "an", "array", "of", "the", "indexes", "mask", ":", "an", "array", "of", "the", "masks", "values", ":", "an", "arr...
def write_data_chunk( self, rows: np.ndarray, indexes: list[np.ndarray], mask: np.ndarray | None, values: list[np.ndarray], ): """ Parameters ---------- rows : an empty memory space where we are putting the chunk indexes : an array of the indexes mask : an array of the masks values : an array of the values """ # 0 len for v in values: if not np.prod(v.shape): return nrows = indexes[0].shape[0] if nrows != len(rows): rows = np.empty(nrows, dtype=self.dtype) names = self.dtype.names nindexes = len(indexes) # indexes for i, idx in enumerate(indexes): rows[names[i]] = idx # values for i, v in enumerate(values): rows[names[i + nindexes]] = v # mask if mask is not None: m = ~mask.ravel().astype(bool, copy=False) if not m.all(): rows = rows[m] if len(rows): self.table.append(rows) self.table.flush()
[ "def", "write_data_chunk", "(", "self", ",", "rows", ":", "np", ".", "ndarray", ",", "indexes", ":", "list", "[", "np", ".", "ndarray", "]", ",", "mask", ":", "np", ".", "ndarray", "|", "None", ",", "values", ":", "list", "[", "np", ".", "ndarray",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/pytables.py#L4392-L4434
isl-org/Open3D
79aec3ddde6a571ce2f28e4096477e52ec465244
docs/make_docs.py
python
PyAPIDocsBuilder._try_import_module
(self, full_module_name)
Returns the module object for the given module path
Returns the module object for the given module path
[ "Returns", "the", "module", "object", "for", "the", "given", "module", "path" ]
def _try_import_module(self, full_module_name): """Returns the module object for the given module path""" import open3d # make sure the root module is loaded if open3d._build_config['BUILD_TENSORFLOW_OPS']: import open3d.ml.tf if open3d._build_config['BUILD_PYTORCH_OPS']: import open3d.ml.torch try: # Try to import directly. This will work for pure python submodules module = importlib.import_module(full_module_name) return module except ImportError: # Traverse the module hierarchy of the root module. # This code path is necessary for modules for which we manually # define a specific module path (e.g. the modules defined with # pybind). current_module = open3d for sub_module_name in full_module_name.split(".")[1:]: current_module = getattr(current_module, sub_module_name) return current_module
[ "def", "_try_import_module", "(", "self", ",", "full_module_name", ")", ":", "import", "open3d", "# make sure the root module is loaded", "if", "open3d", ".", "_build_config", "[", "'BUILD_TENSORFLOW_OPS'", "]", ":", "import", "open3d", ".", "ml", ".", "tf", "if", ...
https://github.com/isl-org/Open3D/blob/79aec3ddde6a571ce2f28e4096477e52ec465244/docs/make_docs.py#L116-L136
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/robotsim.py
python
RobotModel.setVelocity
(self, dq)
return _robotsim.RobotModel_setVelocity(self, dq)
setVelocity(RobotModel self, doubleVector dq) Sets the current velocity of the robot model. Like the configuration, this is also essentially a temporary variable.
setVelocity(RobotModel self, doubleVector dq)
[ "setVelocity", "(", "RobotModel", "self", "doubleVector", "dq", ")" ]
def setVelocity(self, dq): """ setVelocity(RobotModel self, doubleVector dq) Sets the current velocity of the robot model. Like the configuration, this is also essentially a temporary variable. """ return _robotsim.RobotModel_setVelocity(self, dq)
[ "def", "setVelocity", "(", "self", ",", "dq", ")", ":", "return", "_robotsim", ".", "RobotModel_setVelocity", "(", "self", ",", "dq", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L4674-L4684
freeorion/freeorion
c266a40eccd3a99a17de8fe57c36ef6ba3771665
default/python/AI/universe/system_network.py
python
get_shortest_distance
(system_1: SystemId, system_2: SystemId)
return _get_shortest_distance(*_min_max(system_1, system_2))
Return the distance between the systems where objects are located.
Return the distance between the systems where objects are located.
[ "Return", "the", "distance", "between", "the", "systems", "where", "objects", "are", "located", "." ]
def get_shortest_distance(system_1: SystemId, system_2: SystemId) -> float: """ Return the distance between the systems where objects are located. """ return _get_shortest_distance(*_min_max(system_1, system_2))
[ "def", "get_shortest_distance", "(", "system_1", ":", "SystemId", ",", "system_2", ":", "SystemId", ")", "->", "float", ":", "return", "_get_shortest_distance", "(", "*", "_min_max", "(", "system_1", ",", "system_2", ")", ")" ]
https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/universe/system_network.py#L59-L63
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
build/android/gyp/apkbuilder.py
python
_ExpandPaths
(paths)
return ret
Converts src:dst into tuples and enumerates files within directories. Args: paths: Paths in the form "src_path:dest_path" Returns: A list of (src_path, dest_path) tuples sorted by dest_path (for stable ordering within output .apk).
Converts src:dst into tuples and enumerates files within directories.
[ "Converts", "src", ":", "dst", "into", "tuples", "and", "enumerates", "files", "within", "directories", "." ]
def _ExpandPaths(paths): """Converts src:dst into tuples and enumerates files within directories. Args: paths: Paths in the form "src_path:dest_path" Returns: A list of (src_path, dest_path) tuples sorted by dest_path (for stable ordering within output .apk). """ ret = [] for path in paths: src_path, dest_path = _SplitAssetPath(path) if os.path.isdir(src_path): for f in build_utils.FindInDirectory(src_path, '*'): ret.append((f, os.path.join(dest_path, f[len(src_path) + 1:]))) else: ret.append((src_path, dest_path)) ret.sort(key=lambda t:t[1]) return ret
[ "def", "_ExpandPaths", "(", "paths", ")", ":", "ret", "=", "[", "]", "for", "path", "in", "paths", ":", "src_path", ",", "dest_path", "=", "_SplitAssetPath", "(", "path", ")", "if", "os", ".", "path", ".", "isdir", "(", "src_path", ")", ":", "for", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/gyp/apkbuilder.py#L107-L126
msitt/blpapi-python
bebcf43668c9e5f5467b1f685f9baebbfc45bc87
src/blpapi/session.py
python
Session.__dispatchEvent
(sessionRef, eventHandle)
event dispatcher
event dispatcher
[ "event", "dispatcher" ]
def __dispatchEvent(sessionRef, eventHandle): # pragma: no cover """ event dispatcher """ try: session = sessionRef() if session is not None: event = Event(eventHandle, session) session.__handler(event, session) except: print("Exception in event handler:", file=sys.stderr) traceback.print_exc(file=sys.stderr) os._exit(1)
[ "def", "__dispatchEvent", "(", "sessionRef", ",", "eventHandle", ")", ":", "# pragma: no cover", "try", ":", "session", "=", "sessionRef", "(", ")", "if", "session", "is", "not", "None", ":", "event", "=", "Event", "(", "eventHandle", ",", "session", ")", ...
https://github.com/msitt/blpapi-python/blob/bebcf43668c9e5f5467b1f685f9baebbfc45bc87/src/blpapi/session.py#L102-L112
gklz1982/caffe-yolov2
ebb27029db4ddc0d40e520634633b0fa9cdcc10d
scripts/cpp_lint.py
python
GetHeaderGuardCPPVariable
(filename)
return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_'
Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file.
Returns the CPP variable that should be used as a header guard.
[ "Returns", "the", "CPP", "variable", "that", "should", "be", "used", "as", "a", "header", "guard", "." ]
def GetHeaderGuardCPPVariable(filename): """Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file. """ # Restores original filename in case that cpplint is invoked from Emacs's # flymake. filename = re.sub(r'_flymake\.h$', '.h', filename) filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) fileinfo = FileInfo(filename) file_path_from_root = fileinfo.RepositoryName() if _root: file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root) return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_'
[ "def", "GetHeaderGuardCPPVariable", "(", "filename", ")", ":", "# Restores original filename in case that cpplint is invoked from Emacs's", "# flymake.", "filename", "=", "re", ".", "sub", "(", "r'_flymake\\.h$'", ",", "'.h'", ",", "filename", ")", "filename", "=", "re", ...
https://github.com/gklz1982/caffe-yolov2/blob/ebb27029db4ddc0d40e520634633b0fa9cdcc10d/scripts/cpp_lint.py#L1384-L1405
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
scripts/mk_genfile_common.py
python
mk_z3consts_py_internal
(api_files, output_dir)
return z3consts_output_path
Generate ``z3consts.py`` from the list of API header files in ``api_files`` and write the output file into the ``output_dir`` directory Returns the path to the generated file.
Generate ``z3consts.py`` from the list of API header files in ``api_files`` and write the output file into the ``output_dir`` directory
[ "Generate", "z3consts", ".", "py", "from", "the", "list", "of", "API", "header", "files", "in", "api_files", "and", "write", "the", "output", "file", "into", "the", "output_dir", "directory" ]
def mk_z3consts_py_internal(api_files, output_dir): """ Generate ``z3consts.py`` from the list of API header files in ``api_files`` and write the output file into the ``output_dir`` directory Returns the path to the generated file. """ assert os.path.isdir(output_dir) assert isinstance(api_files, list) blank_pat = re.compile("^ *\r?$") comment_pat = re.compile("^ *//.*$") typedef_pat = re.compile("typedef enum *") typedef2_pat = re.compile("typedef enum { *") openbrace_pat = re.compile("{ *") closebrace_pat = re.compile("}.*;") z3consts = open(os.path.join(output_dir, 'z3', 'z3consts.py'), 'w') z3consts_output_path = z3consts.name z3consts.write('# Automatically generated file\n\n') for api_file in api_files: api = open(api_file, 'r') SEARCHING = 0 FOUND_ENUM = 1 IN_ENUM = 2 mode = SEARCHING decls = {} idx = 0 linenum = 1 for line in api: m1 = blank_pat.match(line) m2 = comment_pat.match(line) if m1 or m2: # skip blank lines and comments linenum = linenum + 1 elif mode == SEARCHING: m = typedef_pat.match(line) if m: mode = FOUND_ENUM m = typedef2_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 elif mode == FOUND_ENUM: m = openbrace_pat.match(line) if m: mode = IN_ENUM decls = {} idx = 0 else: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: assert mode == IN_ENUM words = re.split('[^\-a-zA-Z0-9_]+', line) m = closebrace_pat.match(line) if m: name = words[1] z3consts.write('# enum %s\n' % name) # Iterate over key-value pairs ordered by value for k, v in sorted(decls.items(), key=lambda pair: pair[1]): z3consts.write('%s = %s\n' % (k, v)) z3consts.write('\n') mode = SEARCHING elif len(words) <= 2: assert False, "Invalid %s, line: %s" % (api_file, linenum) else: if words[2] != '': if len(words[2]) > 1 and words[2][1] == 'x': idx = int(words[2], 16) else: idx = int(words[2]) decls[words[1]] = idx idx = idx + 1 linenum = linenum + 1 api.close() z3consts.close() return z3consts_output_path
[ "def", "mk_z3consts_py_internal", "(", "api_files", ",", "output_dir", ")", ":", "assert", "os", ".", "path", ".", "isdir", "(", "output_dir", ")", "assert", "isinstance", "(", "api_files", ",", "list", ")", "blank_pat", "=", "re", ".", "compile", "(", "\"...
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/scripts/mk_genfile_common.py#L84-L165
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/model/subrobot.py
python
SubRobotModel.__init__
(self, robot : Union[RobotModel,'SubRobotModel'], links : Sequence[Union[int,str]])
Args: robot (RobotModel or SubRobotModel): the robot to base this on. links (list of ints or strs): the links to use in this sub-robot.
Args: robot (RobotModel or SubRobotModel): the robot to base this on. links (list of ints or strs): the links to use in this sub-robot.
[ "Args", ":", "robot", "(", "RobotModel", "or", "SubRobotModel", ")", ":", "the", "robot", "to", "base", "this", "on", ".", "links", "(", "list", "of", "ints", "or", "strs", ")", ":", "the", "links", "to", "use", "in", "this", "sub", "-", "robot", "...
def __init__(self, robot : Union[RobotModel,'SubRobotModel'], links : Sequence[Union[int,str]]): """ Args: robot (RobotModel or SubRobotModel): the robot to base this on. links (list of ints or strs): the links to use in this sub-robot. """ assert isinstance(robot,(RobotModel,SubRobotModel)),"SubRobotModel constructor must be given a RobotModel or SubRobotModel as first argument" self._robot = robot self._links = links[:] #type : List[int] self._drivers = None #type : List[RobotModelDriver] self.index = robot.index self.world = robot.world if isinstance(robot,SubRobotModel): warnings.warn("Taking sub-robot of sub-robot... not tested yet") self._robot = robot._robot for i,l in enumerate(self._links): if isinstance(l,int): self._links[i] = robot._links[l] for i,l in enumerate(self._links): if isinstance(l,str): self._links[i] = robot.link(l).getIndex() self._inv_links = dict((l,i) for (i,l) in enumerate(self._links))
[ "def", "__init__", "(", "self", ",", "robot", ":", "Union", "[", "RobotModel", ",", "'SubRobotModel'", "]", ",", "links", ":", "Sequence", "[", "Union", "[", "int", ",", "str", "]", "]", ")", ":", "assert", "isinstance", "(", "robot", ",", "(", "Robo...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/subrobot.py#L28-L49
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
Grid.DeselectCell
(*args, **kwargs)
return _grid.Grid_DeselectCell(*args, **kwargs)
DeselectCell(self, int row, int col)
DeselectCell(self, int row, int col)
[ "DeselectCell", "(", "self", "int", "row", "int", "col", ")" ]
def DeselectCell(*args, **kwargs): """DeselectCell(self, int row, int col)""" return _grid.Grid_DeselectCell(*args, **kwargs)
[ "def", "DeselectCell", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_DeselectCell", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L2085-L2087
zeakey/DeepSkeleton
dc70170f8fd2ec8ca1157484ce66129981104486
python/caffe/pycaffe.py
python
_Net_set_input_arrays
(self, data, labels)
return self._set_input_arrays(data, labels)
Set input arrays of the in-memory MemoryDataLayer. (Note: this is only for networks declared with the memory data layer.)
Set input arrays of the in-memory MemoryDataLayer. (Note: this is only for networks declared with the memory data layer.)
[ "Set", "input", "arrays", "of", "the", "in", "-", "memory", "MemoryDataLayer", ".", "(", "Note", ":", "this", "is", "only", "for", "networks", "declared", "with", "the", "memory", "data", "layer", ".", ")" ]
def _Net_set_input_arrays(self, data, labels): """ Set input arrays of the in-memory MemoryDataLayer. (Note: this is only for networks declared with the memory data layer.) """ if labels.ndim == 1: labels = np.ascontiguousarray(labels[:, np.newaxis, np.newaxis, np.newaxis]) return self._set_input_arrays(data, labels)
[ "def", "_Net_set_input_arrays", "(", "self", ",", "data", ",", "labels", ")", ":", "if", "labels", ".", "ndim", "==", "1", ":", "labels", "=", "np", ".", "ascontiguousarray", "(", "labels", "[", ":", ",", "np", ".", "newaxis", ",", "np", ".", "newaxi...
https://github.com/zeakey/DeepSkeleton/blob/dc70170f8fd2ec8ca1157484ce66129981104486/python/caffe/pycaffe.py#L236-L244
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/SocketServer.py
python
ForkingMixIn.collect_children
(self)
Internal routine to wait for children that have exited.
Internal routine to wait for children that have exited.
[ "Internal", "routine", "to", "wait", "for", "children", "that", "have", "exited", "." ]
def collect_children(self): """Internal routine to wait for children that have exited.""" if self.active_children is None: return # If we're above the max number of children, wait and reap them until # we go back below threshold. Note that we use waitpid(-1) below to be # able to collect children in size(<defunct children>) syscalls instead # of size(<children>): the downside is that this might reap children # which we didn't spawn, which is why we only resort to this when we're # above max_children. while len(self.active_children) >= self.max_children: try: pid, _ = os.waitpid(-1, 0) self.active_children.discard(pid) except OSError as e: if e.errno == errno.ECHILD: # we don't have any children, we're done self.active_children.clear() elif e.errno != errno.EINTR: break # Now reap all defunct children. for pid in self.active_children.copy(): try: pid, _ = os.waitpid(pid, os.WNOHANG) # if the child hasn't exited yet, pid will be 0 and ignored by # discard() below self.active_children.discard(pid) except OSError as e: if e.errno == errno.ECHILD: # someone else reaped it self.active_children.discard(pid)
[ "def", "collect_children", "(", "self", ")", ":", "if", "self", ".", "active_children", "is", "None", ":", "return", "# If we're above the max number of children, wait and reap them until", "# we go back below threshold. Note that we use waitpid(-1) below to be", "# able to collect c...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/SocketServer.py#L518-L550
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/s3/resumable_download_handler.py
python
ResumableDownloadHandler._attempt_resumable_download
(self, key, fp, headers, cb, num_cb, torrent, version_id, hash_algs)
Attempts a resumable download. Raises ResumableDownloadException if any problems occur.
Attempts a resumable download.
[ "Attempts", "a", "resumable", "download", "." ]
def _attempt_resumable_download(self, key, fp, headers, cb, num_cb, torrent, version_id, hash_algs): """ Attempts a resumable download. Raises ResumableDownloadException if any problems occur. """ cur_file_size = get_cur_file_size(fp, position_to_eof=True) if (cur_file_size and self.etag_value_for_current_download and self.etag_value_for_current_download == key.etag.strip('"\'')): # Try to resume existing transfer. if cur_file_size > key.size: raise ResumableDownloadException( '%s is larger (%d) than %s (%d).\nDeleting tracker file, so ' 'if you re-try this download it will start from scratch' % (fp.name, cur_file_size, str(storage_uri_for_key(key)), key.size), ResumableTransferDisposition.ABORT) elif cur_file_size == key.size: if key.bucket.connection.debug >= 1: print('Download complete.') return if key.bucket.connection.debug >= 1: print('Resuming download.') headers = headers.copy() headers['Range'] = 'bytes=%d-%d' % (cur_file_size, key.size - 1) cb = ByteTranslatingCallbackHandler(cb, cur_file_size).call self.download_start_point = cur_file_size else: if key.bucket.connection.debug >= 1: print('Starting new resumable download.') self._save_tracker_info(key) self.download_start_point = 0 # Truncate the file, in case a new resumable download is being # started atop an existing file. fp.truncate(0) # Disable AWSAuthConnection-level retry behavior, since that would # cause downloads to restart from scratch. if isinstance(key, GSKey): key.get_file(fp, headers, cb, num_cb, torrent, version_id, override_num_retries=0, hash_algs=hash_algs) else: key.get_file(fp, headers, cb, num_cb, torrent, version_id, override_num_retries=0) fp.flush()
[ "def", "_attempt_resumable_download", "(", "self", ",", "key", ",", "fp", ",", "headers", ",", "cb", ",", "num_cb", ",", "torrent", ",", "version_id", ",", "hash_algs", ")", ":", "cur_file_size", "=", "get_cur_file_size", "(", "fp", ",", "position_to_eof", "...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/s3/resumable_download_handler.py#L175-L221
google/filament
d21f092645b8e1e312307cbf89f1484891347c63
third_party/benchmark/tools/gbench/report.py
python
partition_benchmarks
(json1, json2)
return partitions
While preserving the ordering, find benchmarks with the same names in both of the inputs, and group them. (i.e. partition/filter into groups with common name)
While preserving the ordering, find benchmarks with the same names in both of the inputs, and group them. (i.e. partition/filter into groups with common name)
[ "While", "preserving", "the", "ordering", "find", "benchmarks", "with", "the", "same", "names", "in", "both", "of", "the", "inputs", "and", "group", "them", ".", "(", "i", ".", "e", ".", "partition", "/", "filter", "into", "groups", "with", "common", "na...
def partition_benchmarks(json1, json2): """ While preserving the ordering, find benchmarks with the same names in both of the inputs, and group them. (i.e. partition/filter into groups with common name) """ json1_unique_names = get_unique_benchmark_names(json1) json2_unique_names = get_unique_benchmark_names(json2) names = intersect(json1_unique_names, json2_unique_names) partitions = [] for name in names: # Pick the time unit from the first entry of the lhs benchmark. time_unit = (x['time_unit'] for x in json1['benchmarks'] if x['name'] == name).next() # Filter by name and time unit. lhs = [x for x in json1['benchmarks'] if x['name'] == name and x['time_unit'] == time_unit] rhs = [x for x in json2['benchmarks'] if x['name'] == name and x['time_unit'] == time_unit] partitions.append([lhs, rhs]) return partitions
[ "def", "partition_benchmarks", "(", "json1", ",", "json2", ")", ":", "json1_unique_names", "=", "get_unique_benchmark_names", "(", "json1", ")", "json2_unique_names", "=", "get_unique_benchmark_names", "(", "json2", ")", "names", "=", "intersect", "(", "json1_unique_n...
https://github.com/google/filament/blob/d21f092645b8e1e312307cbf89f1484891347c63/third_party/benchmark/tools/gbench/report.py#L116-L136
h2oai/deepwater
80e345c582e6ef912a31f42707a2f31c01b064da
docs/sphinxext/docscrape.py
python
dedent_lines
(lines)
return textwrap.dedent("\n".join(lines)).split("\n")
Deindent a list of lines maximally
Deindent a list of lines maximally
[ "Deindent", "a", "list", "of", "lines", "maximally" ]
def dedent_lines(lines): """Deindent a list of lines maximally""" return textwrap.dedent("\n".join(lines)).split("\n")
[ "def", "dedent_lines", "(", "lines", ")", ":", "return", "textwrap", ".", "dedent", "(", "\"\\n\"", ".", "join", "(", "lines", ")", ")", ".", "split", "(", "\"\\n\"", ")" ]
https://github.com/h2oai/deepwater/blob/80e345c582e6ef912a31f42707a2f31c01b064da/docs/sphinxext/docscrape.py#L400-L402
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/response.py
python
StreamingBody.set_socket_timeout
(self, timeout)
Set the timeout seconds on the socket.
Set the timeout seconds on the socket.
[ "Set", "the", "timeout", "seconds", "on", "the", "socket", "." ]
def set_socket_timeout(self, timeout): """Set the timeout seconds on the socket.""" # The problem we're trying to solve is to prevent .read() calls from # hanging. This can happen in rare cases. What we'd like to ideally # do is set a timeout on the .read() call so that callers can retry # the request. # Unfortunately, this isn't currently possible in requests. # See: https://github.com/kennethreitz/requests/issues/1803 # So what we're going to do is reach into the guts of the stream and # grab the socket object, which we can set the timeout on. We're # putting in a check here so in case this interface goes away, we'll # know. try: # To further complicate things, the way to grab the # underlying socket object from an HTTPResponse is different # in py2 and py3. So this code has been pushed to botocore.compat. set_socket_timeout(self._raw_stream, timeout) except AttributeError: logger.error("Cannot access the socket object of " "a streaming response. It's possible " "the interface has changed.", exc_info=True) raise
[ "def", "set_socket_timeout", "(", "self", ",", "timeout", ")", ":", "# The problem we're trying to solve is to prevent .read() calls from", "# hanging. This can happen in rare cases. What we'd like to ideally", "# do is set a timeout on the .read() call so that callers can retry", "# the req...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/response.py#L49-L70
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
RichTextCtrl.MoveLeft
(*args, **kwargs)
return _richtext.RichTextCtrl_MoveLeft(*args, **kwargs)
MoveLeft(self, int noPositions=1, int flags=0) -> bool Move left
MoveLeft(self, int noPositions=1, int flags=0) -> bool
[ "MoveLeft", "(", "self", "int", "noPositions", "=", "1", "int", "flags", "=", "0", ")", "-", ">", "bool" ]
def MoveLeft(*args, **kwargs): """ MoveLeft(self, int noPositions=1, int flags=0) -> bool Move left """ return _richtext.RichTextCtrl_MoveLeft(*args, **kwargs)
[ "def", "MoveLeft", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_MoveLeft", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L3728-L3734
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBThread.GetStopReason
(self)
return _lldb.SBThread_GetStopReason(self)
GetStopReason(SBThread self) -> lldb::StopReason
GetStopReason(SBThread self) -> lldb::StopReason
[ "GetStopReason", "(", "SBThread", "self", ")", "-", ">", "lldb", "::", "StopReason" ]
def GetStopReason(self): """GetStopReason(SBThread self) -> lldb::StopReason""" return _lldb.SBThread_GetStopReason(self)
[ "def", "GetStopReason", "(", "self", ")", ":", "return", "_lldb", ".", "SBThread_GetStopReason", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L11516-L11518
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/cherrypy/wsgiserver/wsgiserver2.py
python
HTTPConnection.close
(self)
Close the socket underlying this connection.
Close the socket underlying this connection.
[ "Close", "the", "socket", "underlying", "this", "connection", "." ]
def close(self): """Close the socket underlying this connection.""" self.rfile.close() if not self.linger: # Python's socket module does NOT call close on the kernel socket # when you call socket.close(). We do so manually here because we # want this server to send a FIN TCP segment immediately. Note this # must be called *before* calling socket.close(), because the latter # drops its reference to the kernel socket. if hasattr(self.socket, '_sock'): self.socket._sock.close() self.socket.close() else: # On the other hand, sometimes we want to hang around for a bit # to make sure the client has a chance to read our entire # response. Skipping the close() calls here delays the FIN # packet until the socket object is garbage-collected later. # Someday, perhaps, we'll do the full lingering_close that # Apache does, but not today. pass
[ "def", "close", "(", "self", ")", ":", "self", ".", "rfile", ".", "close", "(", ")", "if", "not", "self", ".", "linger", ":", "# Python's socket module does NOT call close on the kernel socket", "# when you call socket.close(). We do so manually here because we", "# want th...
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/wsgiserver/wsgiserver2.py#L1358-L1378
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
tools/harness-thci/OpenThread.py
python
OpenThreadTHCI._connect
(self)
Connect to the device.
Connect to the device.
[ "Connect", "to", "the", "device", "." ]
def _connect(self): """ Connect to the device. """
[ "def", "_connect", "(", "self", ")", ":" ]
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-thci/OpenThread.py#L232-L235
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/training/queue_runner.py
python
QueueRunner._init_from_args
(self, queue=None, enqueue_ops=None, close_op=None, cancel_op=None)
Create a QueueRunner from arguments. Args: queue: A `Queue`. enqueue_ops: List of enqueue ops to run in threads later. close_op: Op to close the queue. Pending enqueue ops are preserved. cancel_op: Op to close the queue and cancel pending enqueue ops. Raises: ValueError: If `queue` or `enqueue_ops` are not provided when not restoring from `queue_runner_def`.
Create a QueueRunner from arguments.
[ "Create", "a", "QueueRunner", "from", "arguments", "." ]
def _init_from_args(self, queue=None, enqueue_ops=None, close_op=None, cancel_op=None): """Create a QueueRunner from arguments. Args: queue: A `Queue`. enqueue_ops: List of enqueue ops to run in threads later. close_op: Op to close the queue. Pending enqueue ops are preserved. cancel_op: Op to close the queue and cancel pending enqueue ops. Raises: ValueError: If `queue` or `enqueue_ops` are not provided when not restoring from `queue_runner_def`. """ if not queue or not enqueue_ops: raise ValueError("Must provide queue and enqueue_ops.") self._queue = queue self._enqueue_ops = enqueue_ops self._close_op = close_op self._cancel_op = cancel_op # Close when no more will be produced, but pending enqueues should be # preserved. if not self._close_op: self._close_op = self._queue.close() # Close and cancel pending enqueues since there was an error and we want # to unblock everything so we can cleanly exit. if not self._cancel_op: self._cancel_op = self._queue.close(cancel_pending_enqueues=True)
[ "def", "_init_from_args", "(", "self", ",", "queue", "=", "None", ",", "enqueue_ops", "=", "None", ",", "close_op", "=", "None", ",", "cancel_op", "=", "None", ")", ":", "if", "not", "queue", "or", "not", "enqueue_ops", ":", "raise", "ValueError", "(", ...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/training/queue_runner.py#L86-L113
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/urllib3/util/timeout.py
python
Timeout.from_float
(cls, timeout)
return Timeout(read=timeout, connect=timeout)
Create a new Timeout from a legacy timeout value. The timeout value used by httplib.py sets the same timeout on the connect(), and recv() socket requests. This creates a :class:`Timeout` object that sets the individual timeouts to the ``timeout`` value passed to this function. :param timeout: The legacy timeout value. :type timeout: integer, float, sentinel default object, or None :return: Timeout object :rtype: :class:`Timeout`
Create a new Timeout from a legacy timeout value.
[ "Create", "a", "new", "Timeout", "from", "a", "legacy", "timeout", "value", "." ]
def from_float(cls, timeout): """ Create a new Timeout from a legacy timeout value. The timeout value used by httplib.py sets the same timeout on the connect(), and recv() socket requests. This creates a :class:`Timeout` object that sets the individual timeouts to the ``timeout`` value passed to this function. :param timeout: The legacy timeout value. :type timeout: integer, float, sentinel default object, or None :return: Timeout object :rtype: :class:`Timeout` """ return Timeout(read=timeout, connect=timeout)
[ "def", "from_float", "(", "cls", ",", "timeout", ")", ":", "return", "Timeout", "(", "read", "=", "timeout", ",", "connect", "=", "timeout", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/urllib3/util/timeout.py#L141-L154
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
tools/harness-automation/autothreadharness/pdu_controller.py
python
ApcPduController.close
(self)
Close telnet connection
Close telnet connection
[ "Close", "telnet", "connection" ]
def close(self): """Close telnet connection""" logger.info('closing telnet') if self.tn: self.tn.close()
[ "def", "close", "(", "self", ")", ":", "logger", ".", "info", "(", "'closing telnet'", ")", "if", "self", ".", "tn", ":", "self", ".", "tn", ".", "close", "(", ")" ]
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-automation/autothreadharness/pdu_controller.py#L112-L116
goldeneye-source/ges-code
2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d
thirdparty/protobuf-2.3.0/python/google/protobuf/text_format.py
python
_Tokenizer.TryConsume
(self, token)
return False
Tries to consume a given piece of text. Args: token: Text to consume. Returns: True iff the text was consumed.
Tries to consume a given piece of text.
[ "Tries", "to", "consume", "a", "given", "piece", "of", "text", "." ]
def TryConsume(self, token): """Tries to consume a given piece of text. Args: token: Text to consume. Returns: True iff the text was consumed. """ if self.token == token: self.NextToken() return True return False
[ "def", "TryConsume", "(", "self", ",", "token", ")", ":", "if", "self", ".", "token", "==", "token", ":", "self", ".", "NextToken", "(", ")", "return", "True", "return", "False" ]
https://github.com/goldeneye-source/ges-code/blob/2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d/thirdparty/protobuf-2.3.0/python/google/protobuf/text_format.py#L358-L370
nsnam/ns-3-dev-git
efdb2e21f45c0a87a60b47c547b68fa140a7b686
src/flow-monitor/examples/flowmon-parse-results.py
python
Simulation.__init__
(self, simulation_el)
! The initializer. @param self The object pointer. @param simulation_el The element.
! The initializer.
[ "!", "The", "initializer", "." ]
def __init__(self, simulation_el): '''! The initializer. @param self The object pointer. @param simulation_el The element. ''' self.flows = [] FlowClassifier_el, = simulation_el.findall("Ipv4FlowClassifier") flow_map = {} for flow_el in simulation_el.findall("FlowStats/Flow"): flow = Flow(flow_el) flow_map[flow.flowId] = flow self.flows.append(flow) for flow_cls in FlowClassifier_el.findall("Flow"): flowId = int(flow_cls.get('flowId')) flow_map[flowId].fiveTuple = FiveTuple(flow_cls) for probe_elem in simulation_el.findall("FlowProbes/FlowProbe"): probeId = int(probe_elem.get('index')) for stats in probe_elem.findall("FlowStats"): flowId = int(stats.get('flowId')) s = ProbeFlowStats() s.packets = int(stats.get('packets')) s.bytes = float(stats.get('bytes')) s.probeId = probeId if s.packets > 0: s.delayFromFirstProbe = parse_time_ns(stats.get('delayFromFirstProbeSum')) / float(s.packets) else: s.delayFromFirstProbe = 0 flow_map[flowId].probe_stats_unsorted.append(s)
[ "def", "__init__", "(", "self", ",", "simulation_el", ")", ":", "self", ".", "flows", "=", "[", "]", "FlowClassifier_el", ",", "=", "simulation_el", ".", "findall", "(", "\"Ipv4FlowClassifier\"", ")", "flow_map", "=", "{", "}", "for", "flow_el", "in", "sim...
https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/src/flow-monitor/examples/flowmon-parse-results.py#L160-L188
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py
python
ExamplePeakFunction.setFwhm
(self, new_fwhm)
Called by an external entity, probably a GUI, in response to a user guessing the height.
Called by an external entity, probably a GUI, in response to a user guessing the height.
[ "Called", "by", "an", "external", "entity", "probably", "a", "GUI", "in", "response", "to", "a", "user", "guessing", "the", "height", "." ]
def setFwhm(self, new_fwhm): """ Called by an external entity, probably a GUI, in response to a user guessing the height. """ sigma = new_fwhm/(2.0*math.sqrt(2.0*math.log(2.0))) self.setParameter("Sigma", sigma)
[ "def", "setFwhm", "(", "self", ",", "new_fwhm", ")", ":", "sigma", "=", "new_fwhm", "/", "(", "2.0", "*", "math", ".", "sqrt", "(", "2.0", "*", "math", ".", "log", "(", "2.0", ")", ")", ")", "self", ".", "setParameter", "(", "\"Sigma\"", ",", "si...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py#L177-L183
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/bandwidth.py
python
BandwidthLimitedStream.read
(self, amount)
return self._fileobj.read(amount)
Read a specified amount Reads will only be throttled if bandwidth limiting is enabled.
Read a specified amount
[ "Read", "a", "specified", "amount" ]
def read(self, amount): """Read a specified amount Reads will only be throttled if bandwidth limiting is enabled. """ if not self._bandwidth_limiting_enabled: return self._fileobj.read(amount) # We do not want to be calling consume on every read as the read # amounts can be small causing the lock of the leaky bucket to # introduce noticeable overhead. So instead we keep track of # how many bytes we have seen and only call consume once we pass a # certain threshold. self._bytes_seen += amount if self._bytes_seen < self._bytes_threshold: return self._fileobj.read(amount) self._consume_through_leaky_bucket() return self._fileobj.read(amount)
[ "def", "read", "(", "self", ",", "amount", ")", ":", "if", "not", "self", ".", "_bandwidth_limiting_enabled", ":", "return", "self", ".", "_fileobj", ".", "read", "(", "amount", ")", "# We do not want to be calling consume on every read as the read", "# amounts can be...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/bandwidth.py#L138-L156
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/seq2seq/python/ops/beam_search_decoder.py
python
BeamSearchDecoder.initialize
(self, name=None)
return (finished, start_inputs, initial_state)
Initialize the decoder. Args: name: Name scope for any created operations. Returns: `(finished, start_inputs, initial_state)`.
Initialize the decoder.
[ "Initialize", "the", "decoder", "." ]
def initialize(self, name=None): """Initialize the decoder. Args: name: Name scope for any created operations. Returns: `(finished, start_inputs, initial_state)`. """ finished, start_inputs = self._finished, self._start_inputs initial_state = BeamSearchDecoderState( cell_state=self._initial_cell_state, log_probs=array_ops.zeros( [self._batch_size, self._beam_width], dtype=nest.flatten(self._initial_cell_state)[0].dtype), finished=finished, lengths=array_ops.zeros( [self._batch_size, self._beam_width], dtype=dtypes.int64)) return (finished, start_inputs, initial_state)
[ "def", "initialize", "(", "self", ",", "name", "=", "None", ")", ":", "finished", ",", "start_inputs", "=", "self", ".", "_finished", ",", "self", ".", "_start_inputs", "initial_state", "=", "BeamSearchDecoderState", "(", "cell_state", "=", "self", ".", "_in...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/seq2seq/python/ops/beam_search_decoder.py#L289-L309
grpc/grpc
27bc6fe7797e43298dc931b96dc57322d0852a9f
src/python/grpcio/grpc/framework/interfaces/face/face.py
python
ResponseReceiver.response
(self, response)
Receives a response from the service-side of the RPC. Args: response: A response object emitted from the service-side of the RPC.
Receives a response from the service-side of the RPC.
[ "Receives", "a", "response", "from", "the", "service", "-", "side", "of", "the", "RPC", "." ]
def response(self, response): """Receives a response from the service-side of the RPC. Args: response: A response object emitted from the service-side of the RPC. """ raise NotImplementedError()
[ "def", "response", "(", "self", ",", "response", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/framework/interfaces/face/face.py#L332-L338
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
isIdeographic
(ch)
return ret
This function is DEPRECATED. Use xmlIsIdeographicQ instead
This function is DEPRECATED. Use xmlIsIdeographicQ instead
[ "This", "function", "is", "DEPRECATED", ".", "Use", "xmlIsIdeographicQ", "instead" ]
def isIdeographic(ch): """This function is DEPRECATED. Use xmlIsIdeographicQ instead """ ret = libxml2mod.xmlIsIdeographic(ch) return ret
[ "def", "isIdeographic", "(", "ch", ")", ":", "ret", "=", "libxml2mod", ".", "xmlIsIdeographic", "(", "ch", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L274-L277
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/util/nest.py
python
is_nested_or_composite
(seq)
return _is_nested_or_composite(seq)
Returns true if its input is a nested structure or a composite. Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) for the definition of a nested structure. Args: seq: the value to test. Returns: True if the input is a nested structure or a composite.
Returns true if its input is a nested structure or a composite.
[ "Returns", "true", "if", "its", "input", "is", "a", "nested", "structure", "or", "a", "composite", "." ]
def is_nested_or_composite(seq): """Returns true if its input is a nested structure or a composite. Refer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest) for the definition of a nested structure. Args: seq: the value to test. Returns: True if the input is a nested structure or a composite. """ return _is_nested_or_composite(seq)
[ "def", "is_nested_or_composite", "(", "seq", ")", ":", "return", "_is_nested_or_composite", "(", "seq", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/util/nest.py#L328-L340
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/lib/scimath.py
python
_tocomplex
(arr)
Convert its input `arr` to a complex array. The input is returned as a complex array of the smallest type that will fit the original data: types like single, byte, short, etc. become csingle, while others become cdouble. A copy of the input is always made. Parameters ---------- arr : array Returns ------- array An array with the same input data as the input but in complex form. Examples -------- First, consider an input of type short: >>> a = np.array([1,2,3],np.short) >>> ac = np.lib.scimath._tocomplex(a); ac array([ 1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) >>> ac.dtype dtype('complex64') If the input is of type double, the output is correspondingly of the complex double type as well: >>> b = np.array([1,2,3],np.double) >>> bc = np.lib.scimath._tocomplex(b); bc array([ 1.+0.j, 2.+0.j, 3.+0.j]) >>> bc.dtype dtype('complex128') Note that even if the input was complex to begin with, a copy is still made, since the astype() method always copies: >>> c = np.array([1,2,3],np.csingle) >>> cc = np.lib.scimath._tocomplex(c); cc array([ 1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) >>> c *= 2; c array([ 2.+0.j, 4.+0.j, 6.+0.j], dtype=complex64) >>> cc array([ 1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64)
Convert its input `arr` to a complex array.
[ "Convert", "its", "input", "arr", "to", "a", "complex", "array", "." ]
def _tocomplex(arr): """Convert its input `arr` to a complex array. The input is returned as a complex array of the smallest type that will fit the original data: types like single, byte, short, etc. become csingle, while others become cdouble. A copy of the input is always made. Parameters ---------- arr : array Returns ------- array An array with the same input data as the input but in complex form. Examples -------- First, consider an input of type short: >>> a = np.array([1,2,3],np.short) >>> ac = np.lib.scimath._tocomplex(a); ac array([ 1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) >>> ac.dtype dtype('complex64') If the input is of type double, the output is correspondingly of the complex double type as well: >>> b = np.array([1,2,3],np.double) >>> bc = np.lib.scimath._tocomplex(b); bc array([ 1.+0.j, 2.+0.j, 3.+0.j]) >>> bc.dtype dtype('complex128') Note that even if the input was complex to begin with, a copy is still made, since the astype() method always copies: >>> c = np.array([1,2,3],np.csingle) >>> cc = np.lib.scimath._tocomplex(c); cc array([ 1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) >>> c *= 2; c array([ 2.+0.j, 4.+0.j, 6.+0.j], dtype=complex64) >>> cc array([ 1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) """ if issubclass(arr.dtype.type, (nt.single, nt.byte, nt.short, nt.ubyte, nt.ushort, nt.csingle)): return arr.astype(nt.csingle) else: return arr.astype(nt.cdouble)
[ "def", "_tocomplex", "(", "arr", ")", ":", "if", "issubclass", "(", "arr", ".", "dtype", ".", "type", ",", "(", "nt", ".", "single", ",", "nt", ".", "byte", ",", "nt", ".", "short", ",", "nt", ".", "ubyte", ",", "nt", ".", "ushort", ",", "nt", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/lib/scimath.py#L36-L96
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/tlslite/tlslite/utils/RSAKey.py
python
RSAKey.generate
(bits)
Generate a new key with the specified bit length. @rtype: L{tlslite.utils.RSAKey.RSAKey}
Generate a new key with the specified bit length.
[ "Generate", "a", "new", "key", "with", "the", "specified", "bit", "length", "." ]
def generate(bits): """Generate a new key with the specified bit length. @rtype: L{tlslite.utils.RSAKey.RSAKey} """ raise NotImplementedError()
[ "def", "generate", "(", "bits", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/tlslite/tlslite/utils/RSAKey.py#L226-L231
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/crywaflib/default_settings.py
python
load_user_settings
(ctx)
return (user_settings, new_options)
Apply all loaded options if they are different that the default value, and no cmd line value is presented
Apply all loaded options if they are different that the default value, and no cmd line value is presented
[ "Apply", "all", "loaded", "options", "if", "they", "are", "different", "that", "the", "default", "value", "and", "no", "cmd", "line", "value", "is", "presented" ]
def load_user_settings(ctx): """ Apply all loaded options if they are different that the default value, and no cmd line value is presented """ global user_settings _load_default_settings_file(ctx) write_user_settings = False user_settings = ConfigParser.ConfigParser() user_setting_file = ctx.get_user_settings_node().abspath() new_options = {} # Load existing user settings if not os.path.exists( user_setting_file ): write_user_settings = True # No file, hence we need to write it else: user_settings.read( [user_setting_file] ) # Load settings and check for newly set ones for section_name, settings_list in ctx.default_settings.items(): # Add not already present sections if not user_settings.has_section(section_name): user_settings.add_section(section_name) write_user_settings = True # Iterate over all options in this group for settings in settings_list: option_name = settings['attribute'] default_value = settings.get('default_value', '') # Load the value from user settings if it is already present if user_settings.has_option(section_name, option_name): value = user_settings.get(section_name, settings['attribute']) LOADED_OPTIONS[ option_name ] = value else: # Add info about newly added option if not new_options.has_key(section_name): new_options[section_name] = [] new_options[section_name].append(option_name) # Load value for current option and stringify it value = settings.get('default_value', '') if getattr(ctx.options, option_name) != value: value = getattr(ctx.options, option_name) if not isinstance(value, str): value = str(value) if ATTRIBUTE_CALLBACKS.get(option_name, None): value = ATTRIBUTE_CALLBACKS[option_name](ctx, section_name, settings['attribute'], value) (isValid, warning, error) = ctx.verify_settings_option(option_name, value) # Add option if isValid: user_settings.set( section_name, settings['attribute'], str(value) ) LOADED_OPTIONS[ option_name ] = value write_user_settings = True # Check for settings provided by the cmd line long_form = settings['long_form'] short_form = settings.get('short_form', None) # Settings on cmdline should have priority, do a sub string match to batch both --option=<SomeThing> and --option <Something> bOptionSetOnCmdLine = False for arg in sys.argv: if long_form in arg: bOptionSetOnCmdLine = True value = getattr(ctx.options, option_name) break for arg in sys.argv: if short_form and short_form in arg: bOptionSetOnCmdLine = True value = getattr(ctx.options, option_name) break # Remember option for internal processing if bOptionSetOnCmdLine: LOADED_OPTIONS[ option_name ] = value elif user_settings.has_option(section_name, option_name): # Load all settings not coming form the cmd line from the config file setattr(ctx.options, option_name, user_settings.get(section_name, option_name)) # Ensure that the user_settings file only contains valid options that are part of the default list if not write_user_settings: for section in user_settings.sections(): # Check for "section" in default list else remove if section not in ctx.default_settings: Logs.warn("[user_settings.options]: Removing section: \"[%s]\" as it is not part of the supported settings found in default_settings.options" % (section)) user_settings.remove_section(section) write_user_settings = True continue # Check for "option" in default list else remove for option in user_settings.options(section): found_match = False for option_desc in ctx.default_settings[section]: # loop over all option descriptions :( if option_desc['attribute'] == option: found_match = True break if not found_match: Logs.warn("[user_settings.options]: Removing entry: \"%s=%s\" from section: \"[%s]\" as it is not part of the supported settings found in default_settings.options" % (option, user_settings.get(section, option), section)) user_settings.remove_option(section, option) write_user_settings = True # Write user settings if write_user_settings: ctx.save_user_settings(user_settings) # Verify IB registry settings after loading all options _validate_incredibuild_registry_settings(ctx) _validate_auto_detect_compiler(ctx) return (user_settings, new_options)
[ "def", "load_user_settings", "(", "ctx", ")", ":", "global", "user_settings", "_load_default_settings_file", "(", "ctx", ")", "write_user_settings", "=", "False", "user_settings", "=", "ConfigParser", ".", "ConfigParser", "(", ")", "user_setting_file", "=", "ctx", "...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/crywaflib/default_settings.py#L521-L634
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/tools/graph_transforms/__init__.py
python
TransformGraph
(input_graph_def, inputs, outputs, transforms)
return output_graph_def
Python wrapper for the Graph Transform Tool. Gives access to all graph transforms available through the command line tool. See documentation at https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/graph_transforms/README.md for full details of the options available. Args: input_graph_def: GraphDef object containing a model to be transformed. inputs: List of node names for the model inputs. outputs: List of node names for the model outputs. transforms: List of strings containing transform names and parameters. Returns: New GraphDef with transforms applied.
Python wrapper for the Graph Transform Tool.
[ "Python", "wrapper", "for", "the", "Graph", "Transform", "Tool", "." ]
def TransformGraph(input_graph_def, inputs, outputs, transforms): """Python wrapper for the Graph Transform Tool. Gives access to all graph transforms available through the command line tool. See documentation at https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/graph_transforms/README.md for full details of the options available. Args: input_graph_def: GraphDef object containing a model to be transformed. inputs: List of node names for the model inputs. outputs: List of node names for the model outputs. transforms: List of strings containing transform names and parameters. Returns: New GraphDef with transforms applied. """ input_graph_def_string = input_graph_def.SerializeToString() inputs_string = compat.as_bytes(",".join(inputs)) outputs_string = compat.as_bytes(",".join(outputs)) transforms_string = compat.as_bytes(" ".join(transforms)) with errors.raise_exception_on_not_ok_status() as status: output_graph_def_string = TransformGraphWithStringInputs( input_graph_def_string, inputs_string, outputs_string, transforms_string, status) output_graph_def = graph_pb2.GraphDef() output_graph_def.ParseFromString(output_graph_def_string) return output_graph_def
[ "def", "TransformGraph", "(", "input_graph_def", ",", "inputs", ",", "outputs", ",", "transforms", ")", ":", "input_graph_def_string", "=", "input_graph_def", ".", "SerializeToString", "(", ")", "inputs_string", "=", "compat", ".", "as_bytes", "(", "\",\"", ".", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/tools/graph_transforms/__init__.py#L27-L54
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
clang/bindings/python/clang/cindex.py
python
Cursor.get_tokens
(self)
return TokenGroup.get_tokens(self._tu, self.extent)
Obtain Token instances formulating that compose this Cursor. This is a generator for Token instances. It returns all tokens which occupy the extent this cursor occupies.
Obtain Token instances formulating that compose this Cursor.
[ "Obtain", "Token", "instances", "formulating", "that", "compose", "this", "Cursor", "." ]
def get_tokens(self): """Obtain Token instances formulating that compose this Cursor. This is a generator for Token instances. It returns all tokens which occupy the extent this cursor occupies. """ return TokenGroup.get_tokens(self._tu, self.extent)
[ "def", "get_tokens", "(", "self", ")", ":", "return", "TokenGroup", ".", "get_tokens", "(", "self", ".", "_tu", ",", "self", ".", "extent", ")" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/clang/bindings/python/clang/cindex.py#L1855-L1861
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/google/protobuf-py/google/protobuf/service.py
python
RpcController.SetFailed
(self, reason)
Sets a failure reason. Causes Failed() to return true on the client side. "reason" will be incorporated into the message returned by ErrorText(). If you find you need to return machine-readable information about failures, you should incorporate it into your response protocol buffer and should NOT call SetFailed().
Sets a failure reason.
[ "Sets", "a", "failure", "reason", "." ]
def SetFailed(self, reason): """Sets a failure reason. Causes Failed() to return true on the client side. "reason" will be incorporated into the message returned by ErrorText(). If you find you need to return machine-readable information about failures, you should incorporate it into your response protocol buffer and should NOT call SetFailed(). """ raise NotImplementedError
[ "def", "SetFailed", "(", "self", ",", "reason", ")", ":", "raise", "NotImplementedError" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/google/protobuf-py/google/protobuf/service.py#L166-L175
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/dimension.py
python
LayoutDimension.exact
(cls, amount)
return cls(min=amount, max=amount, preferred=amount)
Return a :class:`.LayoutDimension` with an exact size. (min, max and preferred set to ``amount``).
Return a :class:`.LayoutDimension` with an exact size. (min, max and preferred set to ``amount``).
[ "Return", "a", ":", "class", ":", ".", "LayoutDimension", "with", "an", "exact", "size", ".", "(", "min", "max", "and", "preferred", "set", "to", "amount", ")", "." ]
def exact(cls, amount): """ Return a :class:`.LayoutDimension` with an exact size. (min, max and preferred set to ``amount``). """ return cls(min=amount, max=amount, preferred=amount)
[ "def", "exact", "(", "cls", ",", "amount", ")", ":", "return", "cls", "(", "min", "=", "amount", ",", "max", "=", "amount", ",", "preferred", "=", "amount", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/dimension.py#L58-L63
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
Grid.SetSelectionMode
(*args, **kwargs)
return _grid.Grid_SetSelectionMode(*args, **kwargs)
SetSelectionMode(self, WXGRIDSELECTIONMODES selmode)
SetSelectionMode(self, WXGRIDSELECTIONMODES selmode)
[ "SetSelectionMode", "(", "self", "WXGRIDSELECTIONMODES", "selmode", ")" ]
def SetSelectionMode(*args, **kwargs): """SetSelectionMode(self, WXGRIDSELECTIONMODES selmode)""" return _grid.Grid_SetSelectionMode(*args, **kwargs)
[ "def", "SetSelectionMode", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_SetSelectionMode", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1223-L1225
google/skia
82d65d0487bd72f5f7332d002429ec2dc61d2463
infra/bots/recipes.py
python
parse
(repo_root, recipes_cfg_path)
Parse is a lightweight a recipes.cfg file parser. Args: repo_root (str) - native path to the root of the repo we're trying to run recipes for. recipes_cfg_path (str) - native path to the recipes.cfg file to process. Returns (as tuple): engine_dep (EngineDep|None): The recipe_engine dependency, or None, if the current repo IS the recipe_engine. recipes_path (str) - native path to where the recipes live inside of the current repo (i.e. the folder containing `recipes/` and/or `recipe_modules`)
Parse is a lightweight a recipes.cfg file parser.
[ "Parse", "is", "a", "lightweight", "a", "recipes", ".", "cfg", "file", "parser", "." ]
def parse(repo_root, recipes_cfg_path): """Parse is a lightweight a recipes.cfg file parser. Args: repo_root (str) - native path to the root of the repo we're trying to run recipes for. recipes_cfg_path (str) - native path to the recipes.cfg file to process. Returns (as tuple): engine_dep (EngineDep|None): The recipe_engine dependency, or None, if the current repo IS the recipe_engine. recipes_path (str) - native path to where the recipes live inside of the current repo (i.e. the folder containing `recipes/` and/or `recipe_modules`) """ with open(recipes_cfg_path, 'r') as fh: pb = json.load(fh) try: if pb['api_version'] != 2: raise MalformedRecipesCfg('unknown version %d' % pb['api_version'], recipes_cfg_path) # If we're running ./recipes.py from the recipe_engine repo itself, then # return None to signal that there's no EngineDep. repo_name = pb.get('repo_name') if not repo_name: repo_name = pb['project_id'] if repo_name == 'recipe_engine': return None, pb.get('recipes_path', '') engine = pb['deps']['recipe_engine'] if 'url' not in engine: raise MalformedRecipesCfg( 'Required field "url" in dependency "recipe_engine" not found', recipes_cfg_path) engine.setdefault('revision', '') engine.setdefault('branch', 'refs/heads/main') recipes_path = pb.get('recipes_path', '') # TODO(iannucci): only support absolute refs if not engine['branch'].startswith('refs/'): engine['branch'] = 'refs/heads/' + engine['branch'] recipes_path = os.path.join(repo_root, recipes_path.replace('/', os.path.sep)) return EngineDep(**engine), recipes_path except KeyError as ex: raise MalformedRecipesCfg(str(ex), recipes_cfg_path)
[ "def", "parse", "(", "repo_root", ",", "recipes_cfg_path", ")", ":", "with", "open", "(", "recipes_cfg_path", ",", "'r'", ")", "as", "fh", ":", "pb", "=", "json", ".", "load", "(", "fh", ")", "try", ":", "if", "pb", "[", "'api_version'", "]", "!=", ...
https://github.com/google/skia/blob/82d65d0487bd72f5f7332d002429ec2dc61d2463/infra/bots/recipes.py#L59-L109
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/symbol/numpy_extension/random.py
python
uniform_n
(low=0.0, high=1.0, batch_shape=None, dtype=None, ctx=None)
r"""Draw samples from a uniform distribution. Samples are uniformly distributed over the half-open interval ``[low, high)`` (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by `uniform`. Parameters ---------- low : float, ndarray, optional Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0. high : float, ndarray, optional Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0. shape : int or tuple of ints, optional Batch shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k * broadcast(low, high).size`` samples are drawn. If size is ``None`` (default), a scalar tensor containing a single value is returned if ``low`` and ``high`` are both scalars. Otherwise, ``np.broadcast(low, high).size`` samples are drawn. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' ctx : Context, optional Device context of output. Default is current context. Returns ------- out : ndarray Drawn samples from the parameterized uniform distribution. See Also -------- randint : Discrete uniform distribution, yielding integers. rand : Convenience function that accepts dimensions as input, e.g., ``rand(2,2)`` would generate a 2-by-2 array of floats, uniformly distributed over ``[0, 1)``. Notes ----- The probability density function of the uniform distribution is .. math:: p(x) = \frac{1}{b - a} anywhere within the interval ``[a, b)``, and zero elsewhere. When ``high`` == ``low``, values of ``low`` will be returned. If ``high`` < ``low``, the results are officially undefined and may eventually raise an error, i.e. do not rely on this function to behave when passed arguments satisfying that inequality condition.
r"""Draw samples from a uniform distribution.
[ "r", "Draw", "samples", "from", "a", "uniform", "distribution", "." ]
def uniform_n(low=0.0, high=1.0, batch_shape=None, dtype=None, ctx=None): r"""Draw samples from a uniform distribution. Samples are uniformly distributed over the half-open interval ``[low, high)`` (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by `uniform`. Parameters ---------- low : float, ndarray, optional Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0. high : float, ndarray, optional Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0. shape : int or tuple of ints, optional Batch shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k * broadcast(low, high).size`` samples are drawn. If size is ``None`` (default), a scalar tensor containing a single value is returned if ``low`` and ``high`` are both scalars. Otherwise, ``np.broadcast(low, high).size`` samples are drawn. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' ctx : Context, optional Device context of output. Default is current context. Returns ------- out : ndarray Drawn samples from the parameterized uniform distribution. See Also -------- randint : Discrete uniform distribution, yielding integers. rand : Convenience function that accepts dimensions as input, e.g., ``rand(2,2)`` would generate a 2-by-2 array of floats, uniformly distributed over ``[0, 1)``. Notes ----- The probability density function of the uniform distribution is .. math:: p(x) = \frac{1}{b - a} anywhere within the interval ``[a, b)``, and zero elsewhere. When ``high`` == ``low``, values of ``low`` will be returned. If ``high`` < ``low``, the results are officially undefined and may eventually raise an error, i.e. do not rely on this function to behave when passed arguments satisfying that inequality condition. """ from ..numpy import _Symbol as np_symbol input_type = (isinstance(low, np_symbol), isinstance(high, np_symbol)) if dtype is None: dtype = 'float32' if ctx is None: ctx = current_context() if batch_shape == (): batch_shape = None else: if isinstance(batch_shape, int): batch_shape = (batch_shape,) batch_shape = (-2,) + batch_shape if input_type == (True, True): return _npi.uniform(low, high, low=None, high=None, size=batch_shape, ctx=ctx, dtype=dtype) elif input_type == (False, True): return _npi.uniform(high, low=low, high=None, size=batch_shape, ctx=ctx, dtype=dtype) elif input_type == (True, False): return _npi.uniform(low, low=None, high=high, size=batch_shape, ctx=ctx, dtype=dtype) else: return _npi.uniform(low=low, high=high, size=batch_shape, ctx=ctx, dtype=dtype)
[ "def", "uniform_n", "(", "low", "=", "0.0", ",", "high", "=", "1.0", ",", "batch_shape", "=", "None", ",", "dtype", "=", "None", ",", "ctx", "=", "None", ")", ":", "from", ".", ".", "numpy", "import", "_Symbol", "as", "np_symbol", "input_type", "=", ...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/numpy_extension/random.py#L104-L181
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
xmlTextReader.NewFd
(self, fd, URL, encoding, options)
return ret
Setup an xmltextReader to parse an XML from a file descriptor. NOTE that the file descriptor will not be closed when the reader is closed or reset. The parsing flags @options are a combination of xmlParserOption. This reuses the existing @reader xmlTextReader.
Setup an xmltextReader to parse an XML from a file descriptor. NOTE that the file descriptor will not be closed when the reader is closed or reset. The parsing flags
[ "Setup", "an", "xmltextReader", "to", "parse", "an", "XML", "from", "a", "file", "descriptor", ".", "NOTE", "that", "the", "file", "descriptor", "will", "not", "be", "closed", "when", "the", "reader", "is", "closed", "or", "reset", ".", "The", "parsing", ...
def NewFd(self, fd, URL, encoding, options): """Setup an xmltextReader to parse an XML from a file descriptor. NOTE that the file descriptor will not be closed when the reader is closed or reset. The parsing flags @options are a combination of xmlParserOption. This reuses the existing @reader xmlTextReader. """ ret = libxml2mod.xmlReaderNewFd(self._o, fd, URL, encoding, options) return ret
[ "def", "NewFd", "(", "self", ",", "fd", ",", "URL", ",", "encoding", ",", "options", ")", ":", "ret", "=", "libxml2mod", ".", "xmlReaderNewFd", "(", "self", ".", "_o", ",", "fd", ",", "URL", ",", "encoding", ",", "options", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L5954-L5961
zdevito/ATen
4aa3e1de29ed58457e530f84217e53db0998476c
aten/src/ATen/nn_parse.py
python
remove_unused_args
(args, thnn_args)
return args
Returns the subset of args whose name appears in thnn_args
Returns the subset of args whose name appears in thnn_args
[ "Returns", "the", "subset", "of", "args", "whose", "name", "appears", "in", "thnn_args" ]
def remove_unused_args(args, thnn_args): """Returns the subset of args whose name appears in thnn_args""" def clean_name(name): name = name[:name.index('[')] if '[' in name else name if name.endswith('_'): name = name[:-1] return name uses = set([clean_name(arg['name']) for arg in thnn_args]) uses.add('output_mask') args = [arg for arg in args if arg['name'] in uses] for arg in args: if 'default' in arg: del arg['default'] return args
[ "def", "remove_unused_args", "(", "args", ",", "thnn_args", ")", ":", "def", "clean_name", "(", "name", ")", ":", "name", "=", "name", "[", ":", "name", ".", "index", "(", "'['", ")", "]", "if", "'['", "in", "name", "else", "name", "if", "name", "....
https://github.com/zdevito/ATen/blob/4aa3e1de29ed58457e530f84217e53db0998476c/aten/src/ATen/nn_parse.py#L196-L209
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-blocks/python/blocks/qa_repack_bits_bb.py
python
qa_repack_bits_bb.test_002_three_msb
(self)
8 -> 3
8 -> 3
[ "8", "-", ">", "3" ]
def test_002_three_msb(self): """ 8 -> 3 """ src_data = [0b11111101, 0b11111111, 0b11111111] expected_data = [0b111, ] + [0b111, ] + [0b011, ] + [0b111, ] * 5 k = 8 l = 3 src = blocks.vector_source_b(src_data, False, 1) repack = blocks.repack_bits_bb(k, l, "", False, gr.GR_MSB_FIRST) sink = blocks.vector_sink_b() self.tb.connect(src, repack, sink) self.tb.run() self.assertEqual(sink.data(), expected_data)
[ "def", "test_002_three_msb", "(", "self", ")", ":", "src_data", "=", "[", "0b11111101", ",", "0b11111111", ",", "0b11111111", "]", "expected_data", "=", "[", "0b111", ",", "]", "+", "[", "0b111", ",", "]", "+", "[", "0b011", ",", "]", "+", "[", "0b11...
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-blocks/python/blocks/qa_repack_bits_bb.py#L79-L90
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
example/image-classification/symbols/resnet-v1.py
python
residual_unit
(data, num_filter, stride, dim_match, name, bottle_neck=True, bn_mom=0.9, workspace=256, memonger=False)
Return ResNet Unit symbol for building ResNet Parameters ---------- data : str Input data num_filter : int Number of output channels bnf : int Bottle neck channels factor with regard to num_filter stride : tuple Stride used in convolution dim_match : Boolean True means channel number between input and output is the same, otherwise means differ name : str Base name of the operators workspace : int Workspace used in convolution operator
Return ResNet Unit symbol for building ResNet Parameters ---------- data : str Input data num_filter : int Number of output channels bnf : int Bottle neck channels factor with regard to num_filter stride : tuple Stride used in convolution dim_match : Boolean True means channel number between input and output is the same, otherwise means differ name : str Base name of the operators workspace : int Workspace used in convolution operator
[ "Return", "ResNet", "Unit", "symbol", "for", "building", "ResNet", "Parameters", "----------", "data", ":", "str", "Input", "data", "num_filter", ":", "int", "Number", "of", "output", "channels", "bnf", ":", "int", "Bottle", "neck", "channels", "factor", "with...
def residual_unit(data, num_filter, stride, dim_match, name, bottle_neck=True, bn_mom=0.9, workspace=256, memonger=False): """Return ResNet Unit symbol for building ResNet Parameters ---------- data : str Input data num_filter : int Number of output channels bnf : int Bottle neck channels factor with regard to num_filter stride : tuple Stride used in convolution dim_match : Boolean True means channel number between input and output is the same, otherwise means differ name : str Base name of the operators workspace : int Workspace used in convolution operator """ if bottle_neck: conv1 = mx.sym.Convolution(data=data, num_filter=int(num_filter*0.25), kernel=(1,1), stride=stride, pad=(0,0), no_bias=True, workspace=workspace, name=name + '_conv1') bn1 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn1') act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1') conv2 = mx.sym.Convolution(data=act1, num_filter=int(num_filter*0.25), kernel=(3,3), stride=(1,1), pad=(1,1), no_bias=True, workspace=workspace, name=name + '_conv2') bn2 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn2') act2 = mx.sym.Activation(data=bn2, act_type='relu', name=name + '_relu2') conv3 = mx.sym.Convolution(data=act2, num_filter=num_filter, kernel=(1,1), stride=(1,1), pad=(0,0), no_bias=True, workspace=workspace, name=name + '_conv3') bn3 = mx.sym.BatchNorm(data=conv3, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn3') if dim_match: shortcut = data else: conv1sc = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True, workspace=workspace, name=name+'_conv1sc') shortcut = mx.sym.BatchNorm(data=conv1sc, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_sc') if memonger: shortcut._set_attr(mirror_stage='True') return mx.sym.Activation(data=bn3 + shortcut, act_type='relu', name=name + '_relu3') else: conv1 = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(3,3), stride=stride, pad=(1,1), no_bias=True, workspace=workspace, name=name + '_conv1') bn1 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn1') act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1') conv2 = mx.sym.Convolution(data=act1, num_filter=num_filter, kernel=(3,3), stride=(1,1), pad=(1,1), no_bias=True, workspace=workspace, name=name + '_conv2') bn2 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn2') if dim_match: shortcut = data else: conv1sc = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True, workspace=workspace, name=name+'_conv1sc') shortcut = mx.sym.BatchNorm(data=conv1sc, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_sc') if memonger: shortcut._set_attr(mirror_stage='True') return mx.sym.Activation(data=bn2 + shortcut, act_type='relu', name=name + '_relu3')
[ "def", "residual_unit", "(", "data", ",", "num_filter", ",", "stride", ",", "dim_match", ",", "name", ",", "bottle_neck", "=", "True", ",", "bn_mom", "=", "0.9", ",", "workspace", "=", "256", ",", "memonger", "=", "False", ")", ":", "if", "bottle_neck", ...
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/image-classification/symbols/resnet-v1.py#L29-L87
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/stc.py
python
StyledTextCtrl.StyleSetSpec
(*args, **kwargs)
return _stc.StyledTextCtrl_StyleSetSpec(*args, **kwargs)
StyleSetSpec(self, int styleNum, String spec) Extract style settings from a spec-string which is composed of one or more of the following comma separated elements:: bold turns on bold italic turns on italics fore:[name or #RRGGBB] sets the foreground colour back:[name or #RRGGBB] sets the background colour face:[facename] sets the font face name to use size:[num] sets the font size in points eol turns on eol filling underline turns on underlining
StyleSetSpec(self, int styleNum, String spec)
[ "StyleSetSpec", "(", "self", "int", "styleNum", "String", "spec", ")" ]
def StyleSetSpec(*args, **kwargs): """ StyleSetSpec(self, int styleNum, String spec) Extract style settings from a spec-string which is composed of one or more of the following comma separated elements:: bold turns on bold italic turns on italics fore:[name or #RRGGBB] sets the foreground colour back:[name or #RRGGBB] sets the background colour face:[facename] sets the font face name to use size:[num] sets the font size in points eol turns on eol filling underline turns on underlining """ return _stc.StyledTextCtrl_StyleSetSpec(*args, **kwargs)
[ "def", "StyleSetSpec", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_StyleSetSpec", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L6523-L6540
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/slim/python/slim/nets/resnet_v2.py
python
resnet_v2_101
(inputs, num_classes=None, global_pool=True, is_training=None, output_stride=None, reuse=None, scope='resnet_v2_101')
return resnet_v2( inputs, blocks, num_classes, is_training, global_pool, output_stride, include_root_block=True, reuse=reuse, scope=scope)
ResNet-101 model of [1]. See resnet_v2() for arg and return description.
ResNet-101 model of [1]. See resnet_v2() for arg and return description.
[ "ResNet", "-", "101", "model", "of", "[", "1", "]", ".", "See", "resnet_v2", "()", "for", "arg", "and", "return", "description", "." ]
def resnet_v2_101(inputs, num_classes=None, global_pool=True, is_training=None, output_stride=None, reuse=None, scope='resnet_v2_101'): """ResNet-101 model of [1]. See resnet_v2() for arg and return description.""" blocks = [ resnet_v2_block('block1', base_depth=64, num_units=3, stride=2), resnet_v2_block('block2', base_depth=128, num_units=4, stride=2), resnet_v2_block('block3', base_depth=256, num_units=23, stride=2), resnet_v2_block('block4', base_depth=512, num_units=3, stride=1), ] return resnet_v2( inputs, blocks, num_classes, is_training, global_pool, output_stride, include_root_block=True, reuse=reuse, scope=scope)
[ "def", "resnet_v2_101", "(", "inputs", ",", "num_classes", "=", "None", ",", "global_pool", "=", "True", ",", "is_training", "=", "None", ",", "output_stride", "=", "None", ",", "reuse", "=", "None", ",", "scope", "=", "'resnet_v2_101'", ")", ":", "blocks"...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/slim/python/slim/nets/resnet_v2.py#L295-L318
ZhouWeikuan/DouDiZhu
0d84ff6c0bc54dba6ae37955de9ae9307513dc99
code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py
python
Token.location
(self)
return conf.lib.clang_getTokenLocation(self._tu, self)
The SourceLocation this Token occurs at.
The SourceLocation this Token occurs at.
[ "The", "SourceLocation", "this", "Token", "occurs", "at", "." ]
def location(self): """The SourceLocation this Token occurs at.""" return conf.lib.clang_getTokenLocation(self._tu, self)
[ "def", "location", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getTokenLocation", "(", "self", ".", "_tu", ",", "self", ")" ]
https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L2681-L2683
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozpack/chrome/flags.py
python
Flags.__str__
(self)
return ' '.join(str(self[k]) for k in self)
Serialize the set of flags.
Serialize the set of flags.
[ "Serialize", "the", "set", "of", "flags", "." ]
def __str__(self): ''' Serialize the set of flags. ''' return ' '.join(str(self[k]) for k in self)
[ "def", "__str__", "(", "self", ")", ":", "return", "' '", ".", "join", "(", "str", "(", "self", "[", "k", "]", ")", "for", "k", "in", "self", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozpack/chrome/flags.py#L236-L240
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/random_ops.py
python
random_uniform
(shape, minval=0, maxval=None, dtype=dtypes.float32, seed=None, name=None)
Outputs random values from a uniform distribution. The generated values follow a uniform distribution in the range `[minval, maxval)`. The lower bound `minval` is included in the range, while the upper bound `maxval` is excluded. For floats, the default range is `[0, 1)`. For ints, at least `maxval` must be specified explicitly. In the integer case, the random integers are slightly biased unless `maxval - minval` is an exact power of two. The bias is small for values of `maxval - minval` significantly smaller than the range of the output (either `2**32` or `2**64`). Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. minval: A 0-D Tensor or Python value of type `dtype`. The lower bound on the range of random values to generate. Defaults to 0. maxval: A 0-D Tensor or Python value of type `dtype`. The upper bound on the range of random values to generate. Defaults to 1 if `dtype` is floating point. dtype: The type of the output: `float32`, `float64`, `int32`, or `int64`. seed: A Python integer. Used to create a random seed for the distribution. See [`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed) for behavior. name: A name for the operation (optional). Returns: A tensor of the specified shape filled with random uniform values. Raises: ValueError: If `dtype` is integral and `maxval` is not specified.
Outputs random values from a uniform distribution.
[ "Outputs", "random", "values", "from", "a", "uniform", "distribution", "." ]
def random_uniform(shape, minval=0, maxval=None, dtype=dtypes.float32, seed=None, name=None): """Outputs random values from a uniform distribution. The generated values follow a uniform distribution in the range `[minval, maxval)`. The lower bound `minval` is included in the range, while the upper bound `maxval` is excluded. For floats, the default range is `[0, 1)`. For ints, at least `maxval` must be specified explicitly. In the integer case, the random integers are slightly biased unless `maxval - minval` is an exact power of two. The bias is small for values of `maxval - minval` significantly smaller than the range of the output (either `2**32` or `2**64`). Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. minval: A 0-D Tensor or Python value of type `dtype`. The lower bound on the range of random values to generate. Defaults to 0. maxval: A 0-D Tensor or Python value of type `dtype`. The upper bound on the range of random values to generate. Defaults to 1 if `dtype` is floating point. dtype: The type of the output: `float32`, `float64`, `int32`, or `int64`. seed: A Python integer. Used to create a random seed for the distribution. See [`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed) for behavior. name: A name for the operation (optional). Returns: A tensor of the specified shape filled with random uniform values. Raises: ValueError: If `dtype` is integral and `maxval` is not specified. """ dtype = dtypes.as_dtype(dtype) if maxval is None: if dtype.is_integer: raise ValueError("Must specify maxval for integer dtype %r" % dtype) maxval = 1 with ops.op_scope([shape, minval, maxval], name, "random_uniform") as name: shape = _ShapeTensor(shape) minval = ops.convert_to_tensor(minval, dtype=dtype, name="min") maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max") seed1, seed2 = random_seed.get_seed(seed) if dtype.is_integer: return gen_random_ops._random_uniform_int(shape, minval, maxval, seed=seed1, seed2=seed2, name=name) else: rnd = gen_random_ops._random_uniform(shape, dtype, seed=seed1, seed2=seed2) return math_ops.add(rnd * (maxval - minval), minval, name=name)
[ "def", "random_uniform", "(", "shape", ",", "minval", "=", "0", ",", "maxval", "=", "None", ",", "dtype", "=", "dtypes", ".", "float32", ",", "seed", "=", "None", ",", "name", "=", "None", ")", ":", "dtype", "=", "dtypes", ".", "as_dtype", "(", "dt...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/random_ops.py#L188-L250
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
SystemSettings.SetScreenType
(*args, **kwargs)
return _misc_.SystemSettings_SetScreenType(*args, **kwargs)
SetScreenType(int screen)
SetScreenType(int screen)
[ "SetScreenType", "(", "int", "screen", ")" ]
def SetScreenType(*args, **kwargs): """SetScreenType(int screen)""" return _misc_.SystemSettings_SetScreenType(*args, **kwargs)
[ "def", "SetScreenType", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "SystemSettings_SetScreenType", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L183-L185
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/gluon/probability/distributions/utils.py
python
erfinv
()
return compute
Unified erfinv interface for both scalar and tensor
Unified erfinv interface for both scalar and tensor
[ "Unified", "erfinv", "interface", "for", "both", "scalar", "and", "tensor" ]
def erfinv(): """Unified erfinv interface for both scalar and tensor """ def compute(value): if isinstance(value, Number): if sc is not None: return sc.erfinv(value) else: raise ValueError('Numbers are not supported as input if scipy is not installed') return npx.erfinv(value) return compute
[ "def", "erfinv", "(", ")", ":", "def", "compute", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Number", ")", ":", "if", "sc", "is", "not", "None", ":", "return", "sc", ".", "erfinv", "(", "value", ")", "else", ":", "raise", "Va...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/probability/distributions/utils.py#L89-L99
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/common.py
python
InvertRelativePath
(path, toplevel_dir=None)
return RelativePath(toplevel_dir, os.path.join(toplevel_dir, path))
Given a path like foo/bar that is relative to toplevel_dir, return the inverse relative path back to the toplevel_dir. E.g. os.path.normpath(os.path.join(path, InvertRelativePath(path))) should always produce the empty string, unless the path contains symlinks.
Given a path like foo/bar that is relative to toplevel_dir, return the inverse relative path back to the toplevel_dir.
[ "Given", "a", "path", "like", "foo", "/", "bar", "that", "is", "relative", "to", "toplevel_dir", "return", "the", "inverse", "relative", "path", "back", "to", "the", "toplevel_dir", "." ]
def InvertRelativePath(path, toplevel_dir=None): """Given a path like foo/bar that is relative to toplevel_dir, return the inverse relative path back to the toplevel_dir. E.g. os.path.normpath(os.path.join(path, InvertRelativePath(path))) should always produce the empty string, unless the path contains symlinks. """ if not path: return path toplevel_dir = '.' if toplevel_dir is None else toplevel_dir return RelativePath(toplevel_dir, os.path.join(toplevel_dir, path))
[ "def", "InvertRelativePath", "(", "path", ",", "toplevel_dir", "=", "None", ")", ":", "if", "not", "path", ":", "return", "path", "toplevel_dir", "=", "'.'", "if", "toplevel_dir", "is", "None", "else", "toplevel_dir", "return", "RelativePath", "(", "toplevel_d...
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/common.py#L171-L181
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/urllib.py
python
quote_plus
(s, safe='')
return quote(s, safe)
Quote the query fragment of a URL; replacing ' ' with '+
Quote the query fragment of a URL; replacing ' ' with '+
[ "Quote", "the", "query", "fragment", "of", "a", "URL", ";", "replacing", "with", "+" ]
def quote_plus(s, safe=''): """Quote the query fragment of a URL; replacing ' ' with '+'""" if ' ' in s: s = quote(s, safe + ' ') return s.replace(' ', '+') return quote(s, safe)
[ "def", "quote_plus", "(", "s", ",", "safe", "=", "''", ")", ":", "if", "' '", "in", "s", ":", "s", "=", "quote", "(", "s", ",", "safe", "+", "' '", ")", "return", "s", ".", "replace", "(", "' '", ",", "'+'", ")", "return", "quote", "(", "s", ...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/urllib.py#L1284-L1289
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/distributions/python/ops/shape.py
python
_DistributionShape.get_shape
(self, x, name="get_shape")
Returns `Tensor`'s shape partitioned into `sample`, `batch`, `event`. Args: x: `Tensor`. name: Python `str`. The name to give this op. Returns: sample_shape: `Tensor` (1D, `int32`). batch_shape: `Tensor` (1D, `int32`). event_shape: `Tensor` (1D, `int32`).
Returns `Tensor`'s shape partitioned into `sample`, `batch`, `event`.
[ "Returns", "Tensor", "s", "shape", "partitioned", "into", "sample", "batch", "event", "." ]
def get_shape(self, x, name="get_shape"): """Returns `Tensor`'s shape partitioned into `sample`, `batch`, `event`. Args: x: `Tensor`. name: Python `str`. The name to give this op. Returns: sample_shape: `Tensor` (1D, `int32`). batch_shape: `Tensor` (1D, `int32`). event_shape: `Tensor` (1D, `int32`). """ with self._name_scope(name, values=[x]): x = ops.convert_to_tensor(x, name="x") def slice_shape(start_sum, size, name): """Closure to slice out shape.""" start_sum = start_sum if start_sum else [ array_ops.zeros([], dtype=dtypes.int32, name="zero")] if (x.get_shape().ndims is not None and self._is_all_constant_helper(size, *start_sum)): start = sum(tensor_util.constant_value(s) for s in start_sum) stop = start + tensor_util.constant_value(size) slice_ = x.get_shape()[start:stop].as_list() if all(s is not None for s in slice_): return ops.convert_to_tensor(slice_, dtype=dtypes.int32, name=name) return array_ops.slice(array_ops.shape(x), [sum(start_sum)], [size]) sample_ndims = self.get_sample_ndims(x, name=name) return (slice_shape([], sample_ndims, name="sample_shape"), slice_shape([sample_ndims], self.batch_ndims, name="batch_shape"), slice_shape([sample_ndims, self.batch_ndims], self.event_ndims, name="event_shape"))
[ "def", "get_shape", "(", "self", ",", "x", ",", "name", "=", "\"get_shape\"", ")", ":", "with", "self", ".", "_name_scope", "(", "name", ",", "values", "=", "[", "x", "]", ")", ":", "x", "=", "ops", ".", "convert_to_tensor", "(", "x", ",", "name", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/distributions/python/ops/shape.py#L325-L357
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/v8/third_party/jinja2/filters.py
python
do_urlize
(eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None)
return rv
Converts URLs in plain text into clickable links. If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls "nofollow": .. sourcecode:: jinja {{ mytext|urlize(40, true) }} links are shortened to 40 chars and defined with rel="nofollow" If *target* is specified, the ``target`` attribute will be added to the ``<a>`` tag: .. sourcecode:: jinja {{ mytext|urlize(40, target='_blank') }} .. versionchanged:: 2.8+ The *target* parameter was added.
Converts URLs in plain text into clickable links.
[ "Converts", "URLs", "in", "plain", "text", "into", "clickable", "links", "." ]
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None): """Converts URLs in plain text into clickable links. If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls "nofollow": .. sourcecode:: jinja {{ mytext|urlize(40, true) }} links are shortened to 40 chars and defined with rel="nofollow" If *target* is specified, the ``target`` attribute will be added to the ``<a>`` tag: .. sourcecode:: jinja {{ mytext|urlize(40, target='_blank') }} .. versionchanged:: 2.8+ The *target* parameter was added. """ policies = eval_ctx.environment.policies rel = set((rel or '').split() or []) if nofollow: rel.add('nofollow') rel.update((policies['urlize.rel'] or '').split()) if target is None: target = policies['urlize.target'] rel = ' '.join(sorted(rel)) or None rv = urlize(value, trim_url_limit, rel=rel, target=target) if eval_ctx.autoescape: rv = Markup(rv) return rv
[ "def", "do_urlize", "(", "eval_ctx", ",", "value", ",", "trim_url_limit", "=", "None", ",", "nofollow", "=", "False", ",", "target", "=", "None", ",", "rel", "=", "None", ")", ":", "policies", "=", "eval_ctx", ".", "environment", ".", "policies", "rel", ...
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/third_party/jinja2/filters.py#L499-L533
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/calltip.py
python
get_entity
(expression)
Return the object corresponding to expression evaluated in a namespace spanning sys.modules and __main.dict__.
Return the object corresponding to expression evaluated in a namespace spanning sys.modules and __main.dict__.
[ "Return", "the", "object", "corresponding", "to", "expression", "evaluated", "in", "a", "namespace", "spanning", "sys", ".", "modules", "and", "__main", ".", "dict__", "." ]
def get_entity(expression): """Return the object corresponding to expression evaluated in a namespace spanning sys.modules and __main.dict__. """ if expression: namespace = {**sys.modules, **__main__.__dict__} try: return eval(expression, namespace) # Only protect user code. except BaseException: # An uncaught exception closes idle, and eval can raise any # exception, especially if user classes are involved. return None
[ "def", "get_entity", "(", "expression", ")", ":", "if", "expression", ":", "namespace", "=", "{", "*", "*", "sys", ".", "modules", ",", "*", "*", "__main__", ".", "__dict__", "}", "try", ":", "return", "eval", "(", "expression", ",", "namespace", ")", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/calltip.py#L101-L112
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/tasks.py
python
Task.__init__
(self, transfer_coordinator, main_kwargs=None, pending_main_kwargs=None, done_callbacks=None, is_final=False)
:type transfer_coordinator: s3transfer.futures.TransferCoordinator :param transfer_coordinator: The context associated to the TransferFuture for which this Task is associated with. :type main_kwargs: dict :param main_kwargs: The keyword args that can be immediately supplied to the _main() method of the task :type pending_main_kwargs: dict :param pending_main_kwargs: The keyword args that are depended upon by the result from a dependent future(s). The result returned by the future(s) will be used as the value for the keyword argument when _main() is called. The values for each key can be: * a single future - Once completed, its value will be the result of that single future * a list of futures - Once all of the futures complete, the value used will be a list of each completed future result value in order of when they were originally supplied. :type done_callbacks: list of callbacks :param done_callbacks: A list of callbacks to call once the task is done completing. Each callback will be called with no arguments and will be called no matter if the task succeeds or an exception is raised. :type is_final: boolean :param is_final: True, to indicate that this task is the final task for the TransferFuture request. By setting this value to True, it will set the result of the entire TransferFuture to the result returned by this task's main() method.
:type transfer_coordinator: s3transfer.futures.TransferCoordinator :param transfer_coordinator: The context associated to the TransferFuture for which this Task is associated with.
[ ":", "type", "transfer_coordinator", ":", "s3transfer", ".", "futures", ".", "TransferCoordinator", ":", "param", "transfer_coordinator", ":", "The", "context", "associated", "to", "the", "TransferFuture", "for", "which", "this", "Task", "is", "associated", "with", ...
def __init__(self, transfer_coordinator, main_kwargs=None, pending_main_kwargs=None, done_callbacks=None, is_final=False): """ :type transfer_coordinator: s3transfer.futures.TransferCoordinator :param transfer_coordinator: The context associated to the TransferFuture for which this Task is associated with. :type main_kwargs: dict :param main_kwargs: The keyword args that can be immediately supplied to the _main() method of the task :type pending_main_kwargs: dict :param pending_main_kwargs: The keyword args that are depended upon by the result from a dependent future(s). The result returned by the future(s) will be used as the value for the keyword argument when _main() is called. The values for each key can be: * a single future - Once completed, its value will be the result of that single future * a list of futures - Once all of the futures complete, the value used will be a list of each completed future result value in order of when they were originally supplied. :type done_callbacks: list of callbacks :param done_callbacks: A list of callbacks to call once the task is done completing. Each callback will be called with no arguments and will be called no matter if the task succeeds or an exception is raised. :type is_final: boolean :param is_final: True, to indicate that this task is the final task for the TransferFuture request. By setting this value to True, it will set the result of the entire TransferFuture to the result returned by this task's main() method. """ self._transfer_coordinator = transfer_coordinator self._main_kwargs = main_kwargs if self._main_kwargs is None: self._main_kwargs = {} self._pending_main_kwargs = pending_main_kwargs if pending_main_kwargs is None: self._pending_main_kwargs = {} self._done_callbacks = done_callbacks if self._done_callbacks is None: self._done_callbacks = [] self._is_final = is_final
[ "def", "__init__", "(", "self", ",", "transfer_coordinator", ",", "main_kwargs", "=", "None", ",", "pending_main_kwargs", "=", "None", ",", "done_callbacks", "=", "None", ",", "is_final", "=", "False", ")", ":", "self", ".", "_transfer_coordinator", "=", "tran...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/s3transfer/tasks.py#L28-L77
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/aui.py
python
AuiPaneInfo.IsDestroyOnClose
(*args, **kwargs)
return _aui.AuiPaneInfo_IsDestroyOnClose(*args, **kwargs)
IsDestroyOnClose(self) -> bool
IsDestroyOnClose(self) -> bool
[ "IsDestroyOnClose", "(", "self", ")", "-", ">", "bool" ]
def IsDestroyOnClose(*args, **kwargs): """IsDestroyOnClose(self) -> bool""" return _aui.AuiPaneInfo_IsDestroyOnClose(*args, **kwargs)
[ "def", "IsDestroyOnClose", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiPaneInfo_IsDestroyOnClose", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L293-L295
carla-simulator/carla
8854804f4d7748e14d937ec763a2912823a7e5f5
PythonAPI/examples/rss/rss_visualization.py
python
RssUnstructuredSceneVisualizer._world_to_sensor
(cords, camera_transform)
return sensor_cords
Transforms world coordinates to sensor.
Transforms world coordinates to sensor.
[ "Transforms", "world", "coordinates", "to", "sensor", "." ]
def _world_to_sensor(cords, camera_transform): """ Transforms world coordinates to sensor. """ sensor_world_matrix = get_matrix(camera_transform) world_sensor_matrix = np.linalg.inv(sensor_world_matrix) sensor_cords = np.dot(world_sensor_matrix, cords) return sensor_cords
[ "def", "_world_to_sensor", "(", "cords", ",", "camera_transform", ")", ":", "sensor_world_matrix", "=", "get_matrix", "(", "camera_transform", ")", "world_sensor_matrix", "=", "np", ".", "linalg", ".", "inv", "(", "sensor_world_matrix", ")", "sensor_cords", "=", "...
https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/PythonAPI/examples/rss/rss_visualization.py#L414-L421
HKUST-Aerial-Robotics/Fast-Planner
2ddd7793eecd573dbb5b47e2c985aa06606df3cf
uav_simulator/Utils/multi_map_server/quadrotor_msgs/src/quadrotor_msgs/msg/_AuxCommand.py
python
AuxCommand.__init__
(self, *args, **kwds)
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: current_yaw,kf_correction,angle_corrections,enable_motors,use_external_yaw :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields.
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments.
[ "Constructor", ".", "Any", "message", "fields", "that", "are", "implicitly", "/", "explicitly", "set", "to", "None", "will", "be", "assigned", "a", "default", "value", ".", "The", "recommend", "use", "is", "keyword", "arguments", "as", "this", "is", "more", ...
def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: current_yaw,kf_correction,angle_corrections,enable_motors,use_external_yaw :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(AuxCommand, self).__init__(*args, **kwds) #message fields cannot be None, assign default values for those that are if self.current_yaw is None: self.current_yaw = 0. if self.kf_correction is None: self.kf_correction = 0. if self.angle_corrections is None: self.angle_corrections = [0.,0.] if self.enable_motors is None: self.enable_motors = False if self.use_external_yaw is None: self.use_external_yaw = False else: self.current_yaw = 0. self.kf_correction = 0. self.angle_corrections = [0.,0.] self.enable_motors = False self.use_external_yaw = False
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "if", "args", "or", "kwds", ":", "super", "(", "AuxCommand", ",", "self", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwds", ")", "#message fields cannot...
https://github.com/HKUST-Aerial-Robotics/Fast-Planner/blob/2ddd7793eecd573dbb5b47e2c985aa06606df3cf/uav_simulator/Utils/multi_map_server/quadrotor_msgs/src/quadrotor_msgs/msg/_AuxCommand.py#L22-L54
GXYM/DRRG
9e074fa9052de8d131f55ca1f6ae6673c1bfeca4
dataset/icdar15/Evaluation_Protocol/rrc_evaluation_funcs.py
python
decode_utf8
(raw)
Returns a Unicode object on success, or None on failure
Returns a Unicode object on success, or None on failure
[ "Returns", "a", "Unicode", "object", "on", "success", "or", "None", "on", "failure" ]
def decode_utf8(raw): """ Returns a Unicode object on success, or None on failure """ try: raw = codecs.decode(raw,'utf-8', 'replace') #extracts BOM if exists raw = raw.encode('utf8') if raw.startswith(codecs.BOM_UTF8): raw = raw.replace(codecs.BOM_UTF8, '', 1) return raw.decode('utf-8') except: return None
[ "def", "decode_utf8", "(", "raw", ")", ":", "try", ":", "raw", "=", "codecs", ".", "decode", "(", "raw", ",", "'utf-8'", ",", "'replace'", ")", "#extracts BOM if exists", "raw", "=", "raw", ".", "encode", "(", "'utf8'", ")", "if", "raw", ".", "startswi...
https://github.com/GXYM/DRRG/blob/9e074fa9052de8d131f55ca1f6ae6673c1bfeca4/dataset/icdar15/Evaluation_Protocol/rrc_evaluation_funcs.py#L77-L89
crosslife/OpenBird
9e0198a1a2295f03fa1e8676e216e22c9c7d380b
cocos2d/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
Cursor.kind
(self)
return CursorKind.from_id(self._kind_id)
Return the kind of this cursor.
Return the kind of this cursor.
[ "Return", "the", "kind", "of", "this", "cursor", "." ]
def kind(self): """Return the kind of this cursor.""" return CursorKind.from_id(self._kind_id)
[ "def", "kind", "(", "self", ")", ":", "return", "CursorKind", ".", "from_id", "(", "self", ".", "_kind_id", ")" ]
https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L1098-L1100
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/selectors.py
python
_BaseSelectorImpl._fileobj_lookup
(self, fileobj)
Return a file descriptor from a file object. This wraps _fileobj_to_fd() to do an exhaustive search in case the object is invalid but we still have it in our map. This is used by unregister() so we can unregister an object that was previously registered even if it is closed. It is also used by _SelectorMapping.
Return a file descriptor from a file object.
[ "Return", "a", "file", "descriptor", "from", "a", "file", "object", "." ]
def _fileobj_lookup(self, fileobj): """Return a file descriptor from a file object. This wraps _fileobj_to_fd() to do an exhaustive search in case the object is invalid but we still have it in our map. This is used by unregister() so we can unregister an object that was previously registered even if it is closed. It is also used by _SelectorMapping. """ try: return _fileobj_to_fd(fileobj) except ValueError: # Do an exhaustive search. for key in self._fd_to_key.values(): if key.fileobj is fileobj: return key.fd # Raise ValueError after all. raise
[ "def", "_fileobj_lookup", "(", "self", ",", "fileobj", ")", ":", "try", ":", "return", "_fileobj_to_fd", "(", "fileobj", ")", "except", "ValueError", ":", "# Do an exhaustive search.", "for", "key", "in", "self", ".", "_fd_to_key", ".", "values", "(", ")", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/selectors.py#L215-L232
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py
python
ZerosLikeOutsideLoop
(op, index)
Create zeros_like for the specified output of an op.
Create zeros_like for the specified output of an op.
[ "Create", "zeros_like", "for", "the", "specified", "output", "of", "an", "op", "." ]
def ZerosLikeOutsideLoop(op, index): """Create zeros_like for the specified output of an op.""" val = op.outputs[index] if not IsSwitch(op): return array_ops.zeros_like(val) else: op_ctxt = op._get_control_flow_context() pred = op_ctxt.pred branch = op_ctxt.branch switch_val = switch(op.inputs[0], pred)[1 - branch] zeros_shape = array_ops.shape(switch_val) return array_ops.zeros(zeros_shape, dtype=val.dtype)
[ "def", "ZerosLikeOutsideLoop", "(", "op", ",", "index", ")", ":", "val", "=", "op", ".", "outputs", "[", "index", "]", "if", "not", "IsSwitch", "(", "op", ")", ":", "return", "array_ops", ".", "zeros_like", "(", "val", ")", "else", ":", "op_ctxt", "=...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L1053-L1064
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
scripts/authors.py
python
update_count
(c, lang, counts)
Add the counts from to the total count Input: c[dict]: Local counts with authors as keys, returned from 'target' function lang[str]: The language key that the 'c' count dict is associated counts[dict of dict]: The global count by author, then language
Add the counts from to the total count
[ "Add", "the", "counts", "from", "to", "the", "total", "count" ]
def update_count(c, lang, counts): """ Add the counts from to the total count Input: c[dict]: Local counts with authors as keys, returned from 'target' function lang[str]: The language key that the 'c' count dict is associated counts[dict of dict]: The global count by author, then language """ for key, value in c.items(): counts[key][lang] += value
[ "def", "update_count", "(", "c", ",", "lang", ",", "counts", ")", ":", "for", "key", ",", "value", "in", "c", ".", "items", "(", ")", ":", "counts", "[", "key", "]", "[", "lang", "]", "+=", "value" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/scripts/authors.py#L46-L56
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBData.SetDataFromUInt64Array
(self, *args)
return _lldb.SBData_SetDataFromUInt64Array(self, *args)
SetDataFromUInt64Array(self, uint64_t array) -> bool
SetDataFromUInt64Array(self, uint64_t array) -> bool
[ "SetDataFromUInt64Array", "(", "self", "uint64_t", "array", ")", "-", ">", "bool" ]
def SetDataFromUInt64Array(self, *args): """SetDataFromUInt64Array(self, uint64_t array) -> bool""" return _lldb.SBData_SetDataFromUInt64Array(self, *args)
[ "def", "SetDataFromUInt64Array", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBData_SetDataFromUInt64Array", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L2800-L2802