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
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/hypertreelist.py
python
HyperTreeList.GetAGWWindowStyleFlag
(self)
return agwStyle
Returns the :class:`HyperTreeList` window style flag. :see: :meth:`~HyperTreeList.SetAGWWindowStyleFlag` for a list of valid window styles.
Returns the :class:`HyperTreeList` window style flag.
[ "Returns", "the", ":", "class", ":", "HyperTreeList", "window", "style", "flag", "." ]
def GetAGWWindowStyleFlag(self): """ Returns the :class:`HyperTreeList` window style flag. :see: :meth:`~HyperTreeList.SetAGWWindowStyleFlag` for a list of valid window styles. """ agwStyle = self._agwStyle if self._main_win: agwStyle |= self._main_win.GetAGWWindowStyleFlag() return agwStyle
[ "def", "GetAGWWindowStyleFlag", "(", "self", ")", ":", "agwStyle", "=", "self", ".", "_agwStyle", "if", "self", ".", "_main_win", ":", "agwStyle", "|=", "self", ".", "_main_win", ".", "GetAGWWindowStyleFlag", "(", ")", "return", "agwStyle" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hypertreelist.py#L4323-L4334
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/debug/cli/profile_analyzer_cli.py
python
ProfileAnalyzer._get_list_profile_lines
( self, device_name, device_index, device_count, profile_datum_list, sort_by, sort_reverse, time_unit, device_name_filter=None, node_name_filter=None, op_type_filter=None, screen_cols=80)
return debugger_cli_common.rich_text_lines_from_rich_line_list(output)
Get `RichTextLines` object for list_profile command for a given device. Args: device_name: (string) Device name. device_index: (int) Device index. device_count: (int) Number of devices. profile_datum_list: List of `ProfileDatum` objects. sort_by: (string) Identifier of column to sort. Sort identifier must match value of SORT_OPS_BY_OP_NAME, SORT_OPS_BY_OP_TYPE, SORT_OPS_BY_EXEC_TIME, SORT_OPS_BY_MEMORY or SORT_OPS_BY_LINE. sort_reverse: (bool) Whether to sort in descending instead of default (ascending) order. time_unit: time unit, must be in cli_shared.TIME_UNITS. device_name_filter: Regular expression to filter by device name. node_name_filter: Regular expression to filter by node name. op_type_filter: Regular expression to filter by op type. screen_cols: (int) Number of columns available on the screen (i.e., available screen width). Returns: `RichTextLines` object containing a table that displays profiling information for each op.
Get `RichTextLines` object for list_profile command for a given device.
[ "Get", "RichTextLines", "object", "for", "list_profile", "command", "for", "a", "given", "device", "." ]
def _get_list_profile_lines( self, device_name, device_index, device_count, profile_datum_list, sort_by, sort_reverse, time_unit, device_name_filter=None, node_name_filter=None, op_type_filter=None, screen_cols=80): """Get `RichTextLines` object for list_profile command for a given device. Args: device_name: (string) Device name. device_index: (int) Device index. device_count: (int) Number of devices. profile_datum_list: List of `ProfileDatum` objects. sort_by: (string) Identifier of column to sort. Sort identifier must match value of SORT_OPS_BY_OP_NAME, SORT_OPS_BY_OP_TYPE, SORT_OPS_BY_EXEC_TIME, SORT_OPS_BY_MEMORY or SORT_OPS_BY_LINE. sort_reverse: (bool) Whether to sort in descending instead of default (ascending) order. time_unit: time unit, must be in cli_shared.TIME_UNITS. device_name_filter: Regular expression to filter by device name. node_name_filter: Regular expression to filter by node name. op_type_filter: Regular expression to filter by op type. screen_cols: (int) Number of columns available on the screen (i.e., available screen width). Returns: `RichTextLines` object containing a table that displays profiling information for each op. """ profile_data = ProfileDataTableView(profile_datum_list, time_unit=time_unit) # Calculate total time early to calculate column widths. total_op_time = sum(datum.op_time for datum in profile_datum_list) total_exec_time = sum(datum.node_exec_stats.all_end_rel_micros for datum in profile_datum_list) device_total_row = [ "Device Total", "", cli_shared.time_to_readable_str(total_op_time, force_time_unit=time_unit), cli_shared.time_to_readable_str(total_exec_time, force_time_unit=time_unit)] # Calculate column widths. column_widths = [ len(column_name) for column_name in profile_data.column_names()] for col in range(len(device_total_row)): column_widths[col] = max(column_widths[col], len(device_total_row[col])) for col in range(len(column_widths)): for row in range(profile_data.row_count()): column_widths[col] = max( column_widths[col], len(profile_data.value( row, col, device_name_filter=device_name_filter, node_name_filter=node_name_filter, op_type_filter=op_type_filter))) column_widths[col] += 2 # add margin between columns # Add device name. output = [RL("-" * screen_cols)] device_row = "Device %d of %d: %s" % ( device_index + 1, device_count, device_name) output.append(RL(device_row)) output.append(RL()) # Add headers. base_command = "list_profile" row = RL() for col in range(profile_data.column_count()): column_name = profile_data.column_names()[col] sort_id = profile_data.column_sort_id(col) command = "%s -s %s" % (base_command, sort_id) if sort_by == sort_id and not sort_reverse: command += " -r" head_menu_item = debugger_cli_common.MenuItem(None, command) row += RL(column_name, font_attr=[head_menu_item, "bold"]) row += RL(" " * (column_widths[col] - len(column_name))) output.append(row) # Add data rows. for row in range(profile_data.row_count()): new_row = RL() for col in range(profile_data.column_count()): new_cell = profile_data.value( row, col, device_name_filter=device_name_filter, node_name_filter=node_name_filter, op_type_filter=op_type_filter) new_row += new_cell new_row += RL(" " * (column_widths[col] - len(new_cell))) output.append(new_row) # Add stat totals. row_str = "" for width, row in zip(column_widths, device_total_row): row_str += ("{:<%d}" % width).format(row) output.append(RL()) output.append(RL(row_str)) return debugger_cli_common.rich_text_lines_from_rich_line_list(output)
[ "def", "_get_list_profile_lines", "(", "self", ",", "device_name", ",", "device_index", ",", "device_count", ",", "profile_datum_list", ",", "sort_by", ",", "sort_reverse", ",", "time_unit", ",", "device_name_filter", "=", "None", ",", "node_name_filter", "=", "None", ",", "op_type_filter", "=", "None", ",", "screen_cols", "=", "80", ")", ":", "profile_data", "=", "ProfileDataTableView", "(", "profile_datum_list", ",", "time_unit", "=", "time_unit", ")", "# Calculate total time early to calculate column widths.", "total_op_time", "=", "sum", "(", "datum", ".", "op_time", "for", "datum", "in", "profile_datum_list", ")", "total_exec_time", "=", "sum", "(", "datum", ".", "node_exec_stats", ".", "all_end_rel_micros", "for", "datum", "in", "profile_datum_list", ")", "device_total_row", "=", "[", "\"Device Total\"", ",", "\"\"", ",", "cli_shared", ".", "time_to_readable_str", "(", "total_op_time", ",", "force_time_unit", "=", "time_unit", ")", ",", "cli_shared", ".", "time_to_readable_str", "(", "total_exec_time", ",", "force_time_unit", "=", "time_unit", ")", "]", "# Calculate column widths.", "column_widths", "=", "[", "len", "(", "column_name", ")", "for", "column_name", "in", "profile_data", ".", "column_names", "(", ")", "]", "for", "col", "in", "range", "(", "len", "(", "device_total_row", ")", ")", ":", "column_widths", "[", "col", "]", "=", "max", "(", "column_widths", "[", "col", "]", ",", "len", "(", "device_total_row", "[", "col", "]", ")", ")", "for", "col", "in", "range", "(", "len", "(", "column_widths", ")", ")", ":", "for", "row", "in", "range", "(", "profile_data", ".", "row_count", "(", ")", ")", ":", "column_widths", "[", "col", "]", "=", "max", "(", "column_widths", "[", "col", "]", ",", "len", "(", "profile_data", ".", "value", "(", "row", ",", "col", ",", "device_name_filter", "=", "device_name_filter", ",", "node_name_filter", "=", "node_name_filter", ",", "op_type_filter", "=", "op_type_filter", ")", ")", ")", "column_widths", "[", "col", "]", "+=", "2", "# add margin between columns", "# Add device name.", "output", "=", "[", "RL", "(", "\"-\"", "*", "screen_cols", ")", "]", "device_row", "=", "\"Device %d of %d: %s\"", "%", "(", "device_index", "+", "1", ",", "device_count", ",", "device_name", ")", "output", ".", "append", "(", "RL", "(", "device_row", ")", ")", "output", ".", "append", "(", "RL", "(", ")", ")", "# Add headers.", "base_command", "=", "\"list_profile\"", "row", "=", "RL", "(", ")", "for", "col", "in", "range", "(", "profile_data", ".", "column_count", "(", ")", ")", ":", "column_name", "=", "profile_data", ".", "column_names", "(", ")", "[", "col", "]", "sort_id", "=", "profile_data", ".", "column_sort_id", "(", "col", ")", "command", "=", "\"%s -s %s\"", "%", "(", "base_command", ",", "sort_id", ")", "if", "sort_by", "==", "sort_id", "and", "not", "sort_reverse", ":", "command", "+=", "\" -r\"", "head_menu_item", "=", "debugger_cli_common", ".", "MenuItem", "(", "None", ",", "command", ")", "row", "+=", "RL", "(", "column_name", ",", "font_attr", "=", "[", "head_menu_item", ",", "\"bold\"", "]", ")", "row", "+=", "RL", "(", "\" \"", "*", "(", "column_widths", "[", "col", "]", "-", "len", "(", "column_name", ")", ")", ")", "output", ".", "append", "(", "row", ")", "# Add data rows.", "for", "row", "in", "range", "(", "profile_data", ".", "row_count", "(", ")", ")", ":", "new_row", "=", "RL", "(", ")", "for", "col", "in", "range", "(", "profile_data", ".", "column_count", "(", ")", ")", ":", "new_cell", "=", "profile_data", ".", "value", "(", "row", ",", "col", ",", "device_name_filter", "=", "device_name_filter", ",", "node_name_filter", "=", "node_name_filter", ",", "op_type_filter", "=", "op_type_filter", ")", "new_row", "+=", "new_cell", "new_row", "+=", "RL", "(", "\" \"", "*", "(", "column_widths", "[", "col", "]", "-", "len", "(", "new_cell", ")", ")", ")", "output", ".", "append", "(", "new_row", ")", "# Add stat totals.", "row_str", "=", "\"\"", "for", "width", ",", "row", "in", "zip", "(", "column_widths", ",", "device_total_row", ")", ":", "row_str", "+=", "(", "\"{:<%d}\"", "%", "width", ")", ".", "format", "(", "row", ")", "output", ".", "append", "(", "RL", "(", ")", ")", "output", ".", "append", "(", "RL", "(", "row_str", ")", ")", "return", "debugger_cli_common", ".", "rich_text_lines_from_rich_line_list", "(", "output", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/cli/profile_analyzer_cli.py#L472-L571
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/ipaddress.py
python
_BaseNetwork.address_exclude
(self, other)
Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') list(addr1.address_exclude(addr2)) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') list(addr1.address_exclude(addr2)) = [ip_network('2001:db8::1/128'), ip_network('2001:db8::2/127'), ip_network('2001:db8::4/126'), ip_network('2001:db8::8/125'), ... ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self.
Remove an address from a larger block.
[ "Remove", "an", "address", "from", "a", "larger", "block", "." ]
def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') list(addr1.address_exclude(addr2)) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') list(addr1.address_exclude(addr2)) = [ip_network('2001:db8::1/128'), ip_network('2001:db8::2/127'), ip_network('2001:db8::4/126'), ip_network('2001:db8::8/125'), ... ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self. """ if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError("%s is not a network object" % other) if not other.subnet_of(self): raise ValueError('%s not contained in %s' % (other, self)) if other == self: return # Make sure we're comparing the network of other. other = other.__class__('%s/%s' % (other.network_address, other.prefixlen)) s1, s2 = self.subnets() while s1 != other and s2 != other: if other.subnet_of(s1): yield s2 s1, s2 = s1.subnets() elif other.subnet_of(s2): yield s1 s1, s2 = s2.subnets() else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) if s1 == other: yield s2 elif s2 == other: yield s1 else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other))
[ "def", "address_exclude", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "_version", "==", "other", ".", "_version", ":", "raise", "TypeError", "(", "\"%s and %s are not of the same version\"", "%", "(", "self", ",", "other", ")", ")", "if", "not", "isinstance", "(", "other", ",", "_BaseNetwork", ")", ":", "raise", "TypeError", "(", "\"%s is not a network object\"", "%", "other", ")", "if", "not", "other", ".", "subnet_of", "(", "self", ")", ":", "raise", "ValueError", "(", "'%s not contained in %s'", "%", "(", "other", ",", "self", ")", ")", "if", "other", "==", "self", ":", "return", "# Make sure we're comparing the network of other.", "other", "=", "other", ".", "__class__", "(", "'%s/%s'", "%", "(", "other", ".", "network_address", ",", "other", ".", "prefixlen", ")", ")", "s1", ",", "s2", "=", "self", ".", "subnets", "(", ")", "while", "s1", "!=", "other", "and", "s2", "!=", "other", ":", "if", "other", ".", "subnet_of", "(", "s1", ")", ":", "yield", "s2", "s1", ",", "s2", "=", "s1", ".", "subnets", "(", ")", "elif", "other", ".", "subnet_of", "(", "s2", ")", ":", "yield", "s1", "s1", ",", "s2", "=", "s2", ".", "subnets", "(", ")", "else", ":", "# If we got here, there's a bug somewhere.", "raise", "AssertionError", "(", "'Error performing exclusion: '", "'s1: %s s2: %s other: %s'", "%", "(", "s1", ",", "s2", ",", "other", ")", ")", "if", "s1", "==", "other", ":", "yield", "s2", "elif", "s2", "==", "other", ":", "yield", "s1", "else", ":", "# If we got here, there's a bug somewhere.", "raise", "AssertionError", "(", "'Error performing exclusion: '", "'s1: %s s2: %s other: %s'", "%", "(", "s1", ",", "s2", ",", "other", ")", ")" ]
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/ipaddress.py#L863-L936
apache/impala
8ddac48f3428c86f2cbd037ced89cfb903298b12
shell/impala_shell.py
python
ImpalaShell.do_version
(self, args)
Prints the Impala build version
Prints the Impala build version
[ "Prints", "the", "Impala", "build", "version" ]
def do_version(self, args): """Prints the Impala build version""" print("Shell version: %s" % VERSION_STRING, file=sys.stderr) print("Server version: %s" % self.server_version, file=sys.stderr)
[ "def", "do_version", "(", "self", ",", "args", ")", ":", "print", "(", "\"Shell version: %s\"", "%", "VERSION_STRING", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "\"Server version: %s\"", "%", "self", ".", "server_version", ",", "file", "=", "sys", ".", "stderr", ")" ]
https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/shell/impala_shell.py#L1692-L1695
stan-dev/math
5fd79f89933269a4ca4d8dd1fde2a36d53d4768c
lib/boost_1.75.0/tools/build/src/util/__init__.py
python
value_to_jam
(value, methods=False)
return exported_name
Makes a token to refer to a Python value inside Jam language code. The token is merely a string that can be passed around in Jam code and eventually passed back. For example, we might want to pass PropertySet instance to a tag function and it might eventually call back to virtual_target.add_suffix_and_prefix, passing the same instance. For values that are classes, we'll also make class methods callable from Jam. Note that this is necessary to make a bit more of existing Jamfiles work. This trick should not be used to much, or else the performance benefits of Python port will be eaten.
Makes a token to refer to a Python value inside Jam language code.
[ "Makes", "a", "token", "to", "refer", "to", "a", "Python", "value", "inside", "Jam", "language", "code", "." ]
def value_to_jam(value, methods=False): """Makes a token to refer to a Python value inside Jam language code. The token is merely a string that can be passed around in Jam code and eventually passed back. For example, we might want to pass PropertySet instance to a tag function and it might eventually call back to virtual_target.add_suffix_and_prefix, passing the same instance. For values that are classes, we'll also make class methods callable from Jam. Note that this is necessary to make a bit more of existing Jamfiles work. This trick should not be used to much, or else the performance benefits of Python port will be eaten. """ global __value_id r = __python_to_jam.get(value, None) if r: return r exported_name = '###_' + str(__value_id) __value_id = __value_id + 1 __python_to_jam[value] = exported_name __jam_to_python[exported_name] = value if methods and type(value) == types.InstanceType: for field_name in dir(value): field = getattr(value, field_name) if callable(field) and not field_name.startswith("__"): bjam.import_rule("", exported_name + "." + field_name, field) return exported_name
[ "def", "value_to_jam", "(", "value", ",", "methods", "=", "False", ")", ":", "global", "__value_id", "r", "=", "__python_to_jam", ".", "get", "(", "value", ",", "None", ")", "if", "r", ":", "return", "r", "exported_name", "=", "'###_'", "+", "str", "(", "__value_id", ")", "__value_id", "=", "__value_id", "+", "1", "__python_to_jam", "[", "value", "]", "=", "exported_name", "__jam_to_python", "[", "exported_name", "]", "=", "value", "if", "methods", "and", "type", "(", "value", ")", "==", "types", ".", "InstanceType", ":", "for", "field_name", "in", "dir", "(", "value", ")", ":", "field", "=", "getattr", "(", "value", ",", "field_name", ")", "if", "callable", "(", "field", ")", "and", "not", "field_name", ".", "startswith", "(", "\"__\"", ")", ":", "bjam", ".", "import_rule", "(", "\"\"", ",", "exported_name", "+", "\".\"", "+", "field_name", ",", "field", ")", "return", "exported_name" ]
https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/util/__init__.py#L228-L261
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/style.py
python
Styler.format
(self, formatter, subset=None, na_rep: Optional[str] = None)
return self
Format the text display value of cells. Parameters ---------- formatter : str, callable, dict or None If ``formatter`` is None, the default formatter is used subset : IndexSlice An argument to ``DataFrame.loc`` that restricts which elements ``formatter`` is applied to. na_rep : str, optional Representation for missing values. If ``na_rep`` is None, no special formatting is applied .. versionadded:: 1.0.0 Returns ------- self : Styler Notes ----- ``formatter`` is either an ``a`` or a dict ``{column name: a}`` where ``a`` is one of - str: this will be wrapped in: ``a.format(x)`` - callable: called with the value of an individual cell The default display value for numeric values is the "general" (``g``) format with ``pd.options.display.precision`` precision. Examples -------- >>> df = pd.DataFrame(np.random.randn(4, 2), columns=['a', 'b']) >>> df.style.format("{:.2%}") >>> df['c'] = ['a', 'b', 'c', 'd'] >>> df.style.format({'c': str.upper})
Format the text display value of cells.
[ "Format", "the", "text", "display", "value", "of", "cells", "." ]
def format(self, formatter, subset=None, na_rep: Optional[str] = None): """ Format the text display value of cells. Parameters ---------- formatter : str, callable, dict or None If ``formatter`` is None, the default formatter is used subset : IndexSlice An argument to ``DataFrame.loc`` that restricts which elements ``formatter`` is applied to. na_rep : str, optional Representation for missing values. If ``na_rep`` is None, no special formatting is applied .. versionadded:: 1.0.0 Returns ------- self : Styler Notes ----- ``formatter`` is either an ``a`` or a dict ``{column name: a}`` where ``a`` is one of - str: this will be wrapped in: ``a.format(x)`` - callable: called with the value of an individual cell The default display value for numeric values is the "general" (``g``) format with ``pd.options.display.precision`` precision. Examples -------- >>> df = pd.DataFrame(np.random.randn(4, 2), columns=['a', 'b']) >>> df.style.format("{:.2%}") >>> df['c'] = ['a', 'b', 'c', 'd'] >>> df.style.format({'c': str.upper}) """ if formatter is None: assert self._display_funcs.default_factory is not None formatter = self._display_funcs.default_factory() if subset is None: row_locs = range(len(self.data)) col_locs = range(len(self.data.columns)) else: subset = _non_reducing_slice(subset) if len(subset) == 1: subset = subset, self.data.columns sub_df = self.data.loc[subset] row_locs = self.data.index.get_indexer_for(sub_df.index) col_locs = self.data.columns.get_indexer_for(sub_df.columns) if is_dict_like(formatter): for col, col_formatter in formatter.items(): # formatter must be callable, so '{}' are converted to lambdas col_formatter = _maybe_wrap_formatter(col_formatter, na_rep) col_num = self.data.columns.get_indexer_for([col])[0] for row_num in row_locs: self._display_funcs[(row_num, col_num)] = col_formatter else: # single scalar to format all cells with formatter = _maybe_wrap_formatter(formatter, na_rep) locs = product(*(row_locs, col_locs)) for i, j in locs: self._display_funcs[(i, j)] = formatter return self
[ "def", "format", "(", "self", ",", "formatter", ",", "subset", "=", "None", ",", "na_rep", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "if", "formatter", "is", "None", ":", "assert", "self", ".", "_display_funcs", ".", "default_factory", "is", "not", "None", "formatter", "=", "self", ".", "_display_funcs", ".", "default_factory", "(", ")", "if", "subset", "is", "None", ":", "row_locs", "=", "range", "(", "len", "(", "self", ".", "data", ")", ")", "col_locs", "=", "range", "(", "len", "(", "self", ".", "data", ".", "columns", ")", ")", "else", ":", "subset", "=", "_non_reducing_slice", "(", "subset", ")", "if", "len", "(", "subset", ")", "==", "1", ":", "subset", "=", "subset", ",", "self", ".", "data", ".", "columns", "sub_df", "=", "self", ".", "data", ".", "loc", "[", "subset", "]", "row_locs", "=", "self", ".", "data", ".", "index", ".", "get_indexer_for", "(", "sub_df", ".", "index", ")", "col_locs", "=", "self", ".", "data", ".", "columns", ".", "get_indexer_for", "(", "sub_df", ".", "columns", ")", "if", "is_dict_like", "(", "formatter", ")", ":", "for", "col", ",", "col_formatter", "in", "formatter", ".", "items", "(", ")", ":", "# formatter must be callable, so '{}' are converted to lambdas", "col_formatter", "=", "_maybe_wrap_formatter", "(", "col_formatter", ",", "na_rep", ")", "col_num", "=", "self", ".", "data", ".", "columns", ".", "get_indexer_for", "(", "[", "col", "]", ")", "[", "0", "]", "for", "row_num", "in", "row_locs", ":", "self", ".", "_display_funcs", "[", "(", "row_num", ",", "col_num", ")", "]", "=", "col_formatter", "else", ":", "# single scalar to format all cells with", "formatter", "=", "_maybe_wrap_formatter", "(", "formatter", ",", "na_rep", ")", "locs", "=", "product", "(", "*", "(", "row_locs", ",", "col_locs", ")", ")", "for", "i", ",", "j", "in", "locs", ":", "self", ".", "_display_funcs", "[", "(", "i", ",", "j", ")", "]", "=", "formatter", "return", "self" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/formats/style.py#L426-L497
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/programs/scripts/metadata/Music/musicbrainzngs/musicbrainz.py
python
get_recording_by_id
(id, includes=[], release_status=[], release_type=[])
return _do_mb_query("recording", id, includes, params)
Get the recording with the MusicBrainz `id` as a dict with a 'recording' key. *Available includes*: {includes}
Get the recording with the MusicBrainz `id` as a dict with a 'recording' key.
[ "Get", "the", "recording", "with", "the", "MusicBrainz", "id", "as", "a", "dict", "with", "a", "recording", "key", "." ]
def get_recording_by_id(id, includes=[], release_status=[], release_type=[]): """Get the recording with the MusicBrainz `id` as a dict with a 'recording' key. *Available includes*: {includes}""" params = _check_filter_and_make_params("recording", includes, release_status, release_type) return _do_mb_query("recording", id, includes, params)
[ "def", "get_recording_by_id", "(", "id", ",", "includes", "=", "[", "]", ",", "release_status", "=", "[", "]", ",", "release_type", "=", "[", "]", ")", ":", "params", "=", "_check_filter_and_make_params", "(", "\"recording\"", ",", "includes", ",", "release_status", ",", "release_type", ")", "return", "_do_mb_query", "(", "\"recording\"", ",", "id", ",", "includes", ",", "params", ")" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/metadata/Music/musicbrainzngs/musicbrainz.py#L843-L850
gemrb/gemrb
730206eed8d1dd358ca5e69a62f9e099aa22ffc6
gemrb/GUIScripts/LUSpellSelection.py
python
RowIndex
()
Determines which factor to use in scrolling of spells It depends on if it is character generation where you have 4 rows of 6 spells (24), or it is sorcs level up window where there is 4 rows of 5 spells and 5th row of 4 spell, but you may also use 25th slot there and it is 5 rows of 5 with 25 spells seen at once.
Determines which factor to use in scrolling of spells
[ "Determines", "which", "factor", "to", "use", "in", "scrolling", "of", "spells" ]
def RowIndex (): """Determines which factor to use in scrolling of spells It depends on if it is character generation where you have 4 rows of 6 spells (24), or it is sorcs level up window where there is 4 rows of 5 spells and 5th row of 4 spell, but you may also use 25th slot there and it is 5 rows of 5 with 25 spells seen at once. """ SpellTopIndex = GemRB.GetVar ("SpellTopIndex") if chargen: return ( SpellTopIndex + 1 ) * 6 - 6 elif IWD2: # 30 during level-up return ( SpellTopIndex + 1 ) * 6 - 6 elif EnhanceGUI: return ( SpellTopIndex + 1 ) * 5 - 5 else: return SpellTopIndex
[ "def", "RowIndex", "(", ")", ":", "SpellTopIndex", "=", "GemRB", ".", "GetVar", "(", "\"SpellTopIndex\"", ")", "if", "chargen", ":", "return", "(", "SpellTopIndex", "+", "1", ")", "*", "6", "-", "6", "elif", "IWD2", ":", "# 30 during level-up", "return", "(", "SpellTopIndex", "+", "1", ")", "*", "6", "-", "6", "elif", "EnhanceGUI", ":", "return", "(", "SpellTopIndex", "+", "1", ")", "*", "5", "-", "5", "else", ":", "return", "SpellTopIndex" ]
https://github.com/gemrb/gemrb/blob/730206eed8d1dd358ca5e69a62f9e099aa22ffc6/gemrb/GUIScripts/LUSpellSelection.py#L683-L699
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
ToolBarToolBase.CanBeToggled
(*args, **kwargs)
return _controls_.ToolBarToolBase_CanBeToggled(*args, **kwargs)
CanBeToggled(self) -> bool
CanBeToggled(self) -> bool
[ "CanBeToggled", "(", "self", ")", "-", ">", "bool" ]
def CanBeToggled(*args, **kwargs): """CanBeToggled(self) -> bool""" return _controls_.ToolBarToolBase_CanBeToggled(*args, **kwargs)
[ "def", "CanBeToggled", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ToolBarToolBase_CanBeToggled", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L3485-L3487
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/sparsemax/python/ops/sparsemax_loss.py
python
sparsemax_loss
(logits, sparsemax, labels, name=None)
Computes sparsemax loss function [1]. [1]: https://arxiv.org/abs/1602.02068 Args: logits: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. sparsemax: A `Tensor`. Must have the same type as `logits`. labels: A `Tensor`. Must have the same type as `logits`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `logits`.
Computes sparsemax loss function [1].
[ "Computes", "sparsemax", "loss", "function", "[", "1", "]", "." ]
def sparsemax_loss(logits, sparsemax, labels, name=None): """Computes sparsemax loss function [1]. [1]: https://arxiv.org/abs/1602.02068 Args: logits: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. sparsemax: A `Tensor`. Must have the same type as `logits`. labels: A `Tensor`. Must have the same type as `logits`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `logits`. """ with ops.name_scope(name, "sparsemax_loss", [logits, sparsemax, labels]) as name: logits = ops.convert_to_tensor(logits, name="logits") sparsemax = ops.convert_to_tensor(sparsemax, name="sparsemax") labels = ops.convert_to_tensor(labels, name="labels") # In the paper, they call the logits z. # A constant can be substracted from logits to make the algorithm # more numerically stable in theory. However, there are really no major # source numerical instability in this algorithm. z = logits # sum over support # Use a conditional where instead of a multiplication to support z = -inf. # If z = -inf, and there is no support (sparsemax = 0), a multiplication # would cause 0 * -inf = nan, which is not correct in this case. sum_s = array_ops.where( math_ops.logical_or(sparsemax > 0, math_ops.is_nan(sparsemax)), sparsemax * (z - 0.5 * sparsemax), array_ops.zeros_like(sparsemax)) # - z_k + ||q||^2 q_part = labels * (0.5 * labels - z) # Fix the case where labels = 0 and z = -inf, where q_part would # otherwise be 0 * -inf = nan. But since the lables = 0, no cost for # z = -inf should be consideredself. # The code below also coveres the case where z = inf. Howeverm in this # caose the sparsemax will be nan, which means the sum_s will also be nan, # therefor this case doesn't need addtional special treatment. q_part_safe = array_ops.where( math_ops.logical_and(math_ops.equal(labels, 0), math_ops.is_inf(z)), array_ops.zeros_like(z), q_part) return math_ops.reduce_sum(sum_s + q_part_safe, axis=1)
[ "def", "sparsemax_loss", "(", "logits", ",", "sparsemax", ",", "labels", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"sparsemax_loss\"", ",", "[", "logits", ",", "sparsemax", ",", "labels", "]", ")", "as", "name", ":", "logits", "=", "ops", ".", "convert_to_tensor", "(", "logits", ",", "name", "=", "\"logits\"", ")", "sparsemax", "=", "ops", ".", "convert_to_tensor", "(", "sparsemax", ",", "name", "=", "\"sparsemax\"", ")", "labels", "=", "ops", ".", "convert_to_tensor", "(", "labels", ",", "name", "=", "\"labels\"", ")", "# In the paper, they call the logits z.", "# A constant can be substracted from logits to make the algorithm", "# more numerically stable in theory. However, there are really no major", "# source numerical instability in this algorithm.", "z", "=", "logits", "# sum over support", "# Use a conditional where instead of a multiplication to support z = -inf.", "# If z = -inf, and there is no support (sparsemax = 0), a multiplication", "# would cause 0 * -inf = nan, which is not correct in this case.", "sum_s", "=", "array_ops", ".", "where", "(", "math_ops", ".", "logical_or", "(", "sparsemax", ">", "0", ",", "math_ops", ".", "is_nan", "(", "sparsemax", ")", ")", ",", "sparsemax", "*", "(", "z", "-", "0.5", "*", "sparsemax", ")", ",", "array_ops", ".", "zeros_like", "(", "sparsemax", ")", ")", "# - z_k + ||q||^2", "q_part", "=", "labels", "*", "(", "0.5", "*", "labels", "-", "z", ")", "# Fix the case where labels = 0 and z = -inf, where q_part would", "# otherwise be 0 * -inf = nan. But since the lables = 0, no cost for", "# z = -inf should be consideredself.", "# The code below also coveres the case where z = inf. Howeverm in this", "# caose the sparsemax will be nan, which means the sum_s will also be nan,", "# therefor this case doesn't need addtional special treatment.", "q_part_safe", "=", "array_ops", ".", "where", "(", "math_ops", ".", "logical_and", "(", "math_ops", ".", "equal", "(", "labels", ",", "0", ")", ",", "math_ops", ".", "is_inf", "(", "z", ")", ")", ",", "array_ops", ".", "zeros_like", "(", "z", ")", ",", "q_part", ")", "return", "math_ops", ".", "reduce_sum", "(", "sum_s", "+", "q_part_safe", ",", "axis", "=", "1", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/sparsemax/python/ops/sparsemax_loss.py#L28-L76
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/summary/event_multiplexer.py
python
EventMultiplexer.AddRun
(self, path, name=None)
return self
Add a run to the multiplexer. If the name is not specified, it is the same as the path. If a run by that name exists, and we are already watching the right path, do nothing. If we are watching a different path, replace the event accumulator. If `Reload` has been called, it will `Reload` the newly created accumulators. Args: path: Path to the event files (or event directory) for given run. name: Name of the run to add. If not provided, is set to path. Returns: The `EventMultiplexer`.
Add a run to the multiplexer.
[ "Add", "a", "run", "to", "the", "multiplexer", "." ]
def AddRun(self, path, name=None): """Add a run to the multiplexer. If the name is not specified, it is the same as the path. If a run by that name exists, and we are already watching the right path, do nothing. If we are watching a different path, replace the event accumulator. If `Reload` has been called, it will `Reload` the newly created accumulators. Args: path: Path to the event files (or event directory) for given run. name: Name of the run to add. If not provided, is set to path. Returns: The `EventMultiplexer`. """ if name is None or name is '': name = path accumulator = None with self._accumulators_mutex: if name not in self._accumulators or self._paths[name] != path: if name in self._paths and self._paths[name] != path: # TODO(danmane) - Make it impossible to overwrite an old path with # a new path (just give the new path a distinct name) logging.warning('Conflict for name %s: old path %s, new path %s', name, self._paths[name], path) logging.info('Constructing EventAccumulator for %s', path) accumulator = event_accumulator.EventAccumulator( path, size_guidance=self._size_guidance, purge_orphaned_data=self.purge_orphaned_data) self._accumulators[name] = accumulator self._paths[name] = path if accumulator: if self._reload_called: accumulator.Reload() return self
[ "def", "AddRun", "(", "self", ",", "path", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", "or", "name", "is", "''", ":", "name", "=", "path", "accumulator", "=", "None", "with", "self", ".", "_accumulators_mutex", ":", "if", "name", "not", "in", "self", ".", "_accumulators", "or", "self", ".", "_paths", "[", "name", "]", "!=", "path", ":", "if", "name", "in", "self", ".", "_paths", "and", "self", ".", "_paths", "[", "name", "]", "!=", "path", ":", "# TODO(danmane) - Make it impossible to overwrite an old path with", "# a new path (just give the new path a distinct name)", "logging", ".", "warning", "(", "'Conflict for name %s: old path %s, new path %s'", ",", "name", ",", "self", ".", "_paths", "[", "name", "]", ",", "path", ")", "logging", ".", "info", "(", "'Constructing EventAccumulator for %s'", ",", "path", ")", "accumulator", "=", "event_accumulator", ".", "EventAccumulator", "(", "path", ",", "size_guidance", "=", "self", ".", "_size_guidance", ",", "purge_orphaned_data", "=", "self", ".", "purge_orphaned_data", ")", "self", ".", "_accumulators", "[", "name", "]", "=", "accumulator", "self", ".", "_paths", "[", "name", "]", "=", "path", "if", "accumulator", ":", "if", "self", ".", "_reload_called", ":", "accumulator", ".", "Reload", "(", ")", "return", "self" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/summary/event_multiplexer.py#L106-L145
LisaAnne/lisa-caffe-public
49b8643ddef23a4f6120017968de30c45e693f59
python/caffe/io.py
python
arraylist_to_blobprotovecor_str
(arraylist)
return vec.SerializeToString()
Converts a list of arrays to a serialized blobprotovec, which could be then passed to a network for processing.
Converts a list of arrays to a serialized blobprotovec, which could be then passed to a network for processing.
[ "Converts", "a", "list", "of", "arrays", "to", "a", "serialized", "blobprotovec", "which", "could", "be", "then", "passed", "to", "a", "network", "for", "processing", "." ]
def arraylist_to_blobprotovecor_str(arraylist): """Converts a list of arrays to a serialized blobprotovec, which could be then passed to a network for processing. """ vec = caffe_pb2.BlobProtoVector() vec.blobs.extend([array_to_blobproto(arr) for arr in arraylist]) return vec.SerializeToString()
[ "def", "arraylist_to_blobprotovecor_str", "(", "arraylist", ")", ":", "vec", "=", "caffe_pb2", ".", "BlobProtoVector", "(", ")", "vec", ".", "blobs", ".", "extend", "(", "[", "array_to_blobproto", "(", "arr", ")", "for", "arr", "in", "arraylist", "]", ")", "return", "vec", ".", "SerializeToString", "(", ")" ]
https://github.com/LisaAnne/lisa-caffe-public/blob/49b8643ddef23a4f6120017968de30c45e693f59/python/caffe/io.py#L45-L51
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBUnixSignals.GetNumSignals
(self)
return _lldb.SBUnixSignals_GetNumSignals(self)
GetNumSignals(SBUnixSignals self) -> int32_t
GetNumSignals(SBUnixSignals self) -> int32_t
[ "GetNumSignals", "(", "SBUnixSignals", "self", ")", "-", ">", "int32_t" ]
def GetNumSignals(self): """GetNumSignals(SBUnixSignals self) -> int32_t""" return _lldb.SBUnixSignals_GetNumSignals(self)
[ "def", "GetNumSignals", "(", "self", ")", ":", "return", "_lldb", ".", "SBUnixSignals_GetNumSignals", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L15366-L15368
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/computation/eval.py
python
_convert_expression
(expr)
return s
Convert an object to an expression. This function converts an object to an expression (a unicode string) and checks to make sure it isn't empty after conversion. This is used to convert operators to their string representation for recursive calls to :func:`~pandas.eval`. Parameters ---------- expr : object The object to be converted to a string. Returns ------- str The string representation of an object. Raises ------ ValueError * If the expression is empty.
Convert an object to an expression.
[ "Convert", "an", "object", "to", "an", "expression", "." ]
def _convert_expression(expr) -> str: """ Convert an object to an expression. This function converts an object to an expression (a unicode string) and checks to make sure it isn't empty after conversion. This is used to convert operators to their string representation for recursive calls to :func:`~pandas.eval`. Parameters ---------- expr : object The object to be converted to a string. Returns ------- str The string representation of an object. Raises ------ ValueError * If the expression is empty. """ s = pprint_thing(expr) _check_expression(s) return s
[ "def", "_convert_expression", "(", "expr", ")", "->", "str", ":", "s", "=", "pprint_thing", "(", "expr", ")", "_check_expression", "(", "s", ")", "return", "s" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/computation/eval.py#L120-L146
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/compiler/pycodegen.py
python
compile
(source, filename, mode, flags=None, dont_inherit=None)
return gen.code
Replacement for builtin compile() function
Replacement for builtin compile() function
[ "Replacement", "for", "builtin", "compile", "()", "function" ]
def compile(source, filename, mode, flags=None, dont_inherit=None): """Replacement for builtin compile() function""" if flags is not None or dont_inherit is not None: raise RuntimeError, "not implemented yet" if mode == "single": gen = Interactive(source, filename) elif mode == "exec": gen = Module(source, filename) elif mode == "eval": gen = Expression(source, filename) else: raise ValueError("compile() 3rd arg must be 'exec' or " "'eval' or 'single'") gen.compile() return gen.code
[ "def", "compile", "(", "source", ",", "filename", ",", "mode", ",", "flags", "=", "None", ",", "dont_inherit", "=", "None", ")", ":", "if", "flags", "is", "not", "None", "or", "dont_inherit", "is", "not", "None", ":", "raise", "RuntimeError", ",", "\"not implemented yet\"", "if", "mode", "==", "\"single\"", ":", "gen", "=", "Interactive", "(", "source", ",", "filename", ")", "elif", "mode", "==", "\"exec\"", ":", "gen", "=", "Module", "(", "source", ",", "filename", ")", "elif", "mode", "==", "\"eval\"", ":", "gen", "=", "Expression", "(", "source", ",", "filename", ")", "else", ":", "raise", "ValueError", "(", "\"compile() 3rd arg must be 'exec' or \"", "\"'eval' or 'single'\"", ")", "gen", ".", "compile", "(", ")", "return", "gen", ".", "code" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/compiler/pycodegen.py#L51-L66
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Tools/bgen/bgen/bgenType.py
python
Type.mkvalueArgs
(self, name)
return name
Return an argument for use with Py_BuildValue(). Example: int.mkvalueArgs("spam") returns the string "spam".
Return an argument for use with Py_BuildValue().
[ "Return", "an", "argument", "for", "use", "with", "Py_BuildValue", "()", "." ]
def mkvalueArgs(self, name): """Return an argument for use with Py_BuildValue(). Example: int.mkvalueArgs("spam") returns the string "spam". """ return name
[ "def", "mkvalueArgs", "(", "self", ",", "name", ")", ":", "return", "name" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Tools/bgen/bgen/bgenType.py#L131-L136
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/core/ultratb.py
python
with_patch_inspect
(f)
return wrapped
decorator for monkeypatching inspect.findsource
decorator for monkeypatching inspect.findsource
[ "decorator", "for", "monkeypatching", "inspect", ".", "findsource" ]
def with_patch_inspect(f): """decorator for monkeypatching inspect.findsource""" def wrapped(*args, **kwargs): save_findsource = inspect.findsource save_getargs = inspect.getargs inspect.findsource = findsource inspect.getargs = getargs try: return f(*args, **kwargs) finally: inspect.findsource = save_findsource inspect.getargs = save_getargs return wrapped
[ "def", "with_patch_inspect", "(", "f", ")", ":", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "save_findsource", "=", "inspect", ".", "findsource", "save_getargs", "=", "inspect", ".", "getargs", "inspect", ".", "findsource", "=", "findsource", "inspect", ".", "getargs", "=", "getargs", "try", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "inspect", ".", "findsource", "=", "save_findsource", "inspect", ".", "getargs", "=", "save_getargs", "return", "wrapped" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/ultratb.py#L304-L318
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
StaticText_GetClassDefaultAttributes
(*args, **kwargs)
return _controls_.StaticText_GetClassDefaultAttributes(*args, **kwargs)
StaticText_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this.
StaticText_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
[ "StaticText_GetClassDefaultAttributes", "(", "int", "variant", "=", "WINDOW_VARIANT_NORMAL", ")", "-", ">", "VisualAttributes" ]
def StaticText_GetClassDefaultAttributes(*args, **kwargs): """ StaticText_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.StaticText_GetClassDefaultAttributes(*args, **kwargs)
[ "def", "StaticText_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "StaticText_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L1048-L1063
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/dataview.py
python
DataViewModelNotifier.ItemChanged
(*args, **kwargs)
return _dataview.DataViewModelNotifier_ItemChanged(*args, **kwargs)
ItemChanged(self, DataViewItem item) -> bool Override this to be informed that an item's value has changed.
ItemChanged(self, DataViewItem item) -> bool
[ "ItemChanged", "(", "self", "DataViewItem", "item", ")", "-", ">", "bool" ]
def ItemChanged(*args, **kwargs): """ ItemChanged(self, DataViewItem item) -> bool Override this to be informed that an item's value has changed. """ return _dataview.DataViewModelNotifier_ItemChanged(*args, **kwargs)
[ "def", "ItemChanged", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewModelNotifier_ItemChanged", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L208-L214
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/stats/morestats.py
python
mood
(x, y, axis=0)
return z, pval
Perform Mood's test for equal scale parameters. Mood's two-sample test for scale parameters is a non-parametric test for the null hypothesis that two samples are drawn from the same distribution with the same scale parameter. Parameters ---------- x, y : array_like Arrays of sample data. axis : int, optional The axis along which the samples are tested. `x` and `y` can be of different length along `axis`. If `axis` is None, `x` and `y` are flattened and the test is done on all values in the flattened arrays. Returns ------- z : scalar or ndarray The z-score for the hypothesis test. For 1-D inputs a scalar is returned. p-value : scalar ndarray The p-value for the hypothesis test. See Also -------- fligner : A non-parametric test for the equality of k variances ansari : A non-parametric test for the equality of 2 variances bartlett : A parametric test for equality of k variances in normal samples levene : A parametric test for equality of k variances Notes ----- The data are assumed to be drawn from probability distributions ``f(x)`` and ``f(x/s) / s`` respectively, for some probability density function f. The null hypothesis is that ``s == 1``. For multi-dimensional arrays, if the inputs are of shapes ``(n0, n1, n2, n3)`` and ``(n0, m1, n2, n3)``, then if ``axis=1``, the resulting z and p values will have shape ``(n0, n2, n3)``. Note that ``n1`` and ``m1`` don't have to be equal, but the other dimensions do. Examples -------- >>> from scipy import stats >>> np.random.seed(1234) >>> x2 = np.random.randn(2, 45, 6, 7) >>> x1 = np.random.randn(2, 30, 6, 7) >>> z, p = stats.mood(x1, x2, axis=1) >>> p.shape (2, 6, 7) Find the number of points where the difference in scale is not significant: >>> (p > 0.1).sum() 74 Perform the test with different scales: >>> x1 = np.random.randn(2, 30) >>> x2 = np.random.randn(2, 35) * 10.0 >>> stats.mood(x1, x2, axis=1) (array([-5.7178125 , -5.25342163]), array([ 1.07904114e-08, 1.49299218e-07]))
Perform Mood's test for equal scale parameters.
[ "Perform", "Mood", "s", "test", "for", "equal", "scale", "parameters", "." ]
def mood(x, y, axis=0): """ Perform Mood's test for equal scale parameters. Mood's two-sample test for scale parameters is a non-parametric test for the null hypothesis that two samples are drawn from the same distribution with the same scale parameter. Parameters ---------- x, y : array_like Arrays of sample data. axis : int, optional The axis along which the samples are tested. `x` and `y` can be of different length along `axis`. If `axis` is None, `x` and `y` are flattened and the test is done on all values in the flattened arrays. Returns ------- z : scalar or ndarray The z-score for the hypothesis test. For 1-D inputs a scalar is returned. p-value : scalar ndarray The p-value for the hypothesis test. See Also -------- fligner : A non-parametric test for the equality of k variances ansari : A non-parametric test for the equality of 2 variances bartlett : A parametric test for equality of k variances in normal samples levene : A parametric test for equality of k variances Notes ----- The data are assumed to be drawn from probability distributions ``f(x)`` and ``f(x/s) / s`` respectively, for some probability density function f. The null hypothesis is that ``s == 1``. For multi-dimensional arrays, if the inputs are of shapes ``(n0, n1, n2, n3)`` and ``(n0, m1, n2, n3)``, then if ``axis=1``, the resulting z and p values will have shape ``(n0, n2, n3)``. Note that ``n1`` and ``m1`` don't have to be equal, but the other dimensions do. Examples -------- >>> from scipy import stats >>> np.random.seed(1234) >>> x2 = np.random.randn(2, 45, 6, 7) >>> x1 = np.random.randn(2, 30, 6, 7) >>> z, p = stats.mood(x1, x2, axis=1) >>> p.shape (2, 6, 7) Find the number of points where the difference in scale is not significant: >>> (p > 0.1).sum() 74 Perform the test with different scales: >>> x1 = np.random.randn(2, 30) >>> x2 = np.random.randn(2, 35) * 10.0 >>> stats.mood(x1, x2, axis=1) (array([-5.7178125 , -5.25342163]), array([ 1.07904114e-08, 1.49299218e-07])) """ x = np.asarray(x, dtype=float) y = np.asarray(y, dtype=float) if axis is None: x = x.flatten() y = y.flatten() axis = 0 # Determine shape of the result arrays res_shape = tuple([x.shape[ax] for ax in range(len(x.shape)) if ax != axis]) if not (res_shape == tuple([y.shape[ax] for ax in range(len(y.shape)) if ax != axis])): raise ValueError("Dimensions of x and y on all axes except `axis` " "should match") n = x.shape[axis] m = y.shape[axis] N = m + n if N < 3: raise ValueError("Not enough observations.") xy = np.concatenate((x, y), axis=axis) if axis != 0: xy = np.rollaxis(xy, axis) xy = xy.reshape(xy.shape[0], -1) # Generalized to the n-dimensional case by adding the axis argument, and # using for loops, since rankdata is not vectorized. For improving # performance consider vectorizing rankdata function. all_ranks = np.zeros_like(xy) for j in range(xy.shape[1]): all_ranks[:, j] = stats.rankdata(xy[:, j]) Ri = all_ranks[:n] M = np.sum((Ri - (N + 1.0) / 2)**2, axis=0) # Approx stat. mnM = n * (N * N - 1.0) / 12 varM = m * n * (N + 1.0) * (N + 2) * (N - 2) / 180 z = (M - mnM) / sqrt(varM) # sf for right tail, cdf for left tail. Factor 2 for two-sidedness z_pos = z > 0 pval = np.zeros_like(z) pval[z_pos] = 2 * distributions.norm.sf(z[z_pos]) pval[~z_pos] = 2 * distributions.norm.cdf(z[~z_pos]) if res_shape == (): # Return scalars, not 0-D arrays z = z[0] pval = pval[0] else: z.shape = res_shape pval.shape = res_shape return z, pval
[ "def", "mood", "(", "x", ",", "y", ",", "axis", "=", "0", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ",", "dtype", "=", "float", ")", "y", "=", "np", ".", "asarray", "(", "y", ",", "dtype", "=", "float", ")", "if", "axis", "is", "None", ":", "x", "=", "x", ".", "flatten", "(", ")", "y", "=", "y", ".", "flatten", "(", ")", "axis", "=", "0", "# Determine shape of the result arrays", "res_shape", "=", "tuple", "(", "[", "x", ".", "shape", "[", "ax", "]", "for", "ax", "in", "range", "(", "len", "(", "x", ".", "shape", ")", ")", "if", "ax", "!=", "axis", "]", ")", "if", "not", "(", "res_shape", "==", "tuple", "(", "[", "y", ".", "shape", "[", "ax", "]", "for", "ax", "in", "range", "(", "len", "(", "y", ".", "shape", ")", ")", "if", "ax", "!=", "axis", "]", ")", ")", ":", "raise", "ValueError", "(", "\"Dimensions of x and y on all axes except `axis` \"", "\"should match\"", ")", "n", "=", "x", ".", "shape", "[", "axis", "]", "m", "=", "y", ".", "shape", "[", "axis", "]", "N", "=", "m", "+", "n", "if", "N", "<", "3", ":", "raise", "ValueError", "(", "\"Not enough observations.\"", ")", "xy", "=", "np", ".", "concatenate", "(", "(", "x", ",", "y", ")", ",", "axis", "=", "axis", ")", "if", "axis", "!=", "0", ":", "xy", "=", "np", ".", "rollaxis", "(", "xy", ",", "axis", ")", "xy", "=", "xy", ".", "reshape", "(", "xy", ".", "shape", "[", "0", "]", ",", "-", "1", ")", "# Generalized to the n-dimensional case by adding the axis argument, and", "# using for loops, since rankdata is not vectorized. For improving", "# performance consider vectorizing rankdata function.", "all_ranks", "=", "np", ".", "zeros_like", "(", "xy", ")", "for", "j", "in", "range", "(", "xy", ".", "shape", "[", "1", "]", ")", ":", "all_ranks", "[", ":", ",", "j", "]", "=", "stats", ".", "rankdata", "(", "xy", "[", ":", ",", "j", "]", ")", "Ri", "=", "all_ranks", "[", ":", "n", "]", "M", "=", "np", ".", "sum", "(", "(", "Ri", "-", "(", "N", "+", "1.0", ")", "/", "2", ")", "**", "2", ",", "axis", "=", "0", ")", "# Approx stat.", "mnM", "=", "n", "*", "(", "N", "*", "N", "-", "1.0", ")", "/", "12", "varM", "=", "m", "*", "n", "*", "(", "N", "+", "1.0", ")", "*", "(", "N", "+", "2", ")", "*", "(", "N", "-", "2", ")", "/", "180", "z", "=", "(", "M", "-", "mnM", ")", "/", "sqrt", "(", "varM", ")", "# sf for right tail, cdf for left tail. Factor 2 for two-sidedness", "z_pos", "=", "z", ">", "0", "pval", "=", "np", ".", "zeros_like", "(", "z", ")", "pval", "[", "z_pos", "]", "=", "2", "*", "distributions", ".", "norm", ".", "sf", "(", "z", "[", "z_pos", "]", ")", "pval", "[", "~", "z_pos", "]", "=", "2", "*", "distributions", ".", "norm", ".", "cdf", "(", "z", "[", "~", "z_pos", "]", ")", "if", "res_shape", "==", "(", ")", ":", "# Return scalars, not 0-D arrays", "z", "=", "z", "[", "0", "]", "pval", "=", "pval", "[", "0", "]", "else", ":", "z", ".", "shape", "=", "res_shape", "pval", ".", "shape", "=", "res_shape", "return", "z", ",", "pval" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/stats/morestats.py#L2581-L2703
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/core/fromnumeric.py
python
shape
(a)
return result
Return the shape of an array. Parameters ---------- a : array_like Input array. Returns ------- shape : tuple of ints The elements of the shape tuple give the lengths of the corresponding array dimensions. See Also -------- alen ndarray.shape : Equivalent array method. Examples -------- >>> np.shape(np.eye(3)) (3, 3) >>> np.shape([[1, 2]]) (1, 2) >>> np.shape([0]) (1,) >>> np.shape(0) () >>> a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')]) >>> np.shape(a) (2,) >>> a.shape (2,)
Return the shape of an array.
[ "Return", "the", "shape", "of", "an", "array", "." ]
def shape(a): """ Return the shape of an array. Parameters ---------- a : array_like Input array. Returns ------- shape : tuple of ints The elements of the shape tuple give the lengths of the corresponding array dimensions. See Also -------- alen ndarray.shape : Equivalent array method. Examples -------- >>> np.shape(np.eye(3)) (3, 3) >>> np.shape([[1, 2]]) (1, 2) >>> np.shape([0]) (1,) >>> np.shape(0) () >>> a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')]) >>> np.shape(a) (2,) >>> a.shape (2,) """ try: result = a.shape except AttributeError: result = asarray(a).shape return result
[ "def", "shape", "(", "a", ")", ":", "try", ":", "result", "=", "a", ".", "shape", "except", "AttributeError", ":", "result", "=", "asarray", "(", "a", ")", ".", "shape", "return", "result" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/core/fromnumeric.py#L1786-L1828
WeitaoVan/L-GM-loss
598582f0631bac876b3eeb8d6c4cd1d780269e03
examples/pycaffe/layers/pascal_multilabel_datalayers.py
python
PascalMultilabelDataLayerSync.reshape
(self, bottom, top)
There is no need to reshape the data, since the input is of fixed size (rows and columns)
There is no need to reshape the data, since the input is of fixed size (rows and columns)
[ "There", "is", "no", "need", "to", "reshape", "the", "data", "since", "the", "input", "is", "of", "fixed", "size", "(", "rows", "and", "columns", ")" ]
def reshape(self, bottom, top): """ There is no need to reshape the data, since the input is of fixed size (rows and columns) """ pass
[ "def", "reshape", "(", "self", ",", "bottom", ",", "top", ")", ":", "pass" ]
https://github.com/WeitaoVan/L-GM-loss/blob/598582f0631bac876b3eeb8d6c4cd1d780269e03/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L67-L72
facebook/folly
744a0a698074d1b013813065fe60f545aa2c9b94
build/fbcode_builder/getdeps/subcmd.py
python
SubCmd.run
(self, args)
return 0
perform the command
perform the command
[ "perform", "the", "command" ]
def run(self, args): """perform the command""" return 0
[ "def", "run", "(", "self", ",", "args", ")", ":", "return", "0" ]
https://github.com/facebook/folly/blob/744a0a698074d1b013813065fe60f545aa2c9b94/build/fbcode_builder/getdeps/subcmd.py#L11-L13
NERSC/timemory
431912b360ff50d1a160d7826e2eea04fbd1037f
timemory/trace/tracer.py
python
Tracer.__enter__
(self, *args, **kwargs)
Context manager start function
Context manager start function
[ "Context", "manager", "start", "function" ]
def __enter__(self, *args, **kwargs): """Context manager start function""" self.start()
[ "def", "__enter__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "start", "(", ")" ]
https://github.com/NERSC/timemory/blob/431912b360ff50d1a160d7826e2eea04fbd1037f/timemory/trace/tracer.py#L253-L256
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
PostEvent
(*args, **kwargs)
return _core_.PostEvent(*args, **kwargs)
PostEvent(EvtHandler dest, Event event) Send an event to a window or other wx.EvtHandler to be processed later.
PostEvent(EvtHandler dest, Event event)
[ "PostEvent", "(", "EvtHandler", "dest", "Event", "event", ")" ]
def PostEvent(*args, **kwargs): """ PostEvent(EvtHandler dest, Event event) Send an event to a window or other wx.EvtHandler to be processed later. """ return _core_.PostEvent(*args, **kwargs)
[ "def", "PostEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "PostEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L8403-L8410
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/distutils/dir_util.py
python
_build_cmdtuple
(path, cmdtuples)
Helper for remove_tree().
Helper for remove_tree().
[ "Helper", "for", "remove_tree", "()", "." ]
def _build_cmdtuple(path, cmdtuples): """Helper for remove_tree().""" for f in os.listdir(path): real_f = os.path.join(path,f) if os.path.isdir(real_f) and not os.path.islink(real_f): _build_cmdtuple(real_f, cmdtuples) else: cmdtuples.append((os.remove, real_f)) cmdtuples.append((os.rmdir, path))
[ "def", "_build_cmdtuple", "(", "path", ",", "cmdtuples", ")", ":", "for", "f", "in", "os", ".", "listdir", "(", "path", ")", ":", "real_f", "=", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", "if", "os", ".", "path", ".", "isdir", "(", "real_f", ")", "and", "not", "os", ".", "path", ".", "islink", "(", "real_f", ")", ":", "_build_cmdtuple", "(", "real_f", ",", "cmdtuples", ")", "else", ":", "cmdtuples", ".", "append", "(", "(", "os", ".", "remove", ",", "real_f", ")", ")", "cmdtuples", ".", "append", "(", "(", "os", ".", "rmdir", ",", "path", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/dir_util.py#L168-L176
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/glcanvas.py
python
GLCanvas.GetPalette
(*args, **kwargs)
return _glcanvas.GLCanvas_GetPalette(*args, **kwargs)
GetPalette(self) -> Palette
GetPalette(self) -> Palette
[ "GetPalette", "(", "self", ")", "-", ">", "Palette" ]
def GetPalette(*args, **kwargs): """GetPalette(self) -> Palette""" return _glcanvas.GLCanvas_GetPalette(*args, **kwargs)
[ "def", "GetPalette", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_glcanvas", ".", "GLCanvas_GetPalette", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/glcanvas.py#L146-L148
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Validation/RecoTrack/python/plotting/ntupleDataFormat.py
python
TrackingVertex.nSourceTrackingParticles
(self)
return self._tree.simvtx_sourceSimIdx[self._index].size()
Returns the number of source TrackingParticles.
Returns the number of source TrackingParticles.
[ "Returns", "the", "number", "of", "source", "TrackingParticles", "." ]
def nSourceTrackingParticles(self): """Returns the number of source TrackingParticles.""" self._checkIsValid() return self._tree.simvtx_sourceSimIdx[self._index].size()
[ "def", "nSourceTrackingParticles", "(", "self", ")", ":", "self", ".", "_checkIsValid", "(", ")", "return", "self", ".", "_tree", ".", "simvtx_sourceSimIdx", "[", "self", ".", "_index", "]", ".", "size", "(", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTrack/python/plotting/ntupleDataFormat.py#L1144-L1147
h2oai/datatable
753197c3f76041dd6468e0f6a9708af92d80f6aa
docs/_ext/xcontributors.py
python
UserRepository._compute_version_strings
(self, maxsize, newname, oldname)
self._data.sorted_versions = [<version>] # list of strings self._data.doc_versions = {<docname>: <version>}
self._data.sorted_versions = [<version>] # list of strings self._data.doc_versions = {<docname>: <version>}
[ "self", ".", "_data", ".", "sorted_versions", "=", "[", "<version", ">", "]", "#", "list", "of", "strings", "self", ".", "_data", ".", "doc_versions", "=", "{", "<docname", ">", ":", "<version", ">", "}" ]
def _compute_version_strings(self, maxsize, newname, oldname): """ self._data.sorted_versions = [<version>] # list of strings self._data.doc_versions = {<docname>: <version>} """ env = self._env assert env and isinstance(env.xchangelog, list) v2_set = set() for info in env.xchangelog: version_tuple = info["version"] v2 = version_tuple[:2] v2_set.add(v2) short_versions = sorted(v2_set, reverse=True) sorted_versions = [] v2_to_vstr = {} for i, v2 in enumerate(short_versions): if v2[0] == 999: vstr = newname elif len(short_versions) > maxsize and i >= maxsize - 1: vstr = oldname else: vstr = "%d.%d" % v2 v2_to_vstr[v2] = vstr if i < maxsize: sorted_versions.append(vstr) doc_versions = {} for info in env.xchangelog: docname = info["doc"] version_tuple = info["version"] vstr = v2_to_vstr[version_tuple[:2]] doc_versions[docname] = vstr self._data.sorted_versions = sorted_versions self._data.doc_versions = doc_versions
[ "def", "_compute_version_strings", "(", "self", ",", "maxsize", ",", "newname", ",", "oldname", ")", ":", "env", "=", "self", ".", "_env", "assert", "env", "and", "isinstance", "(", "env", ".", "xchangelog", ",", "list", ")", "v2_set", "=", "set", "(", ")", "for", "info", "in", "env", ".", "xchangelog", ":", "version_tuple", "=", "info", "[", "\"version\"", "]", "v2", "=", "version_tuple", "[", ":", "2", "]", "v2_set", ".", "add", "(", "v2", ")", "short_versions", "=", "sorted", "(", "v2_set", ",", "reverse", "=", "True", ")", "sorted_versions", "=", "[", "]", "v2_to_vstr", "=", "{", "}", "for", "i", ",", "v2", "in", "enumerate", "(", "short_versions", ")", ":", "if", "v2", "[", "0", "]", "==", "999", ":", "vstr", "=", "newname", "elif", "len", "(", "short_versions", ")", ">", "maxsize", "and", "i", ">=", "maxsize", "-", "1", ":", "vstr", "=", "oldname", "else", ":", "vstr", "=", "\"%d.%d\"", "%", "v2", "v2_to_vstr", "[", "v2", "]", "=", "vstr", "if", "i", "<", "maxsize", ":", "sorted_versions", ".", "append", "(", "vstr", ")", "doc_versions", "=", "{", "}", "for", "info", "in", "env", ".", "xchangelog", ":", "docname", "=", "info", "[", "\"doc\"", "]", "version_tuple", "=", "info", "[", "\"version\"", "]", "vstr", "=", "v2_to_vstr", "[", "version_tuple", "[", ":", "2", "]", "]", "doc_versions", "[", "docname", "]", "=", "vstr", "self", ".", "_data", ".", "sorted_versions", "=", "sorted_versions", "self", ".", "_data", ".", "doc_versions", "=", "doc_versions" ]
https://github.com/h2oai/datatable/blob/753197c3f76041dd6468e0f6a9708af92d80f6aa/docs/_ext/xcontributors.py#L61-L96
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/linesearch.py
python
_nonmonotone_line_search_cruz
(f, x_k, d, prev_fs, eta, gamma=1e-4, tau_min=0.1, tau_max=0.5)
return alpha, xp, fp, Fp
Nonmonotone backtracking line search as described in [1]_ Parameters ---------- f : callable Function returning a tuple ``(f, F)`` where ``f`` is the value of a merit function and ``F`` the residual. x_k : ndarray Initial position d : ndarray Search direction prev_fs : float List of previous merit function values. Should have ``len(prev_fs) <= M`` where ``M`` is the nonmonotonicity window parameter. eta : float Allowed merit function increase, see [1]_ gamma, tau_min, tau_max : float, optional Search parameters, see [1]_ Returns ------- alpha : float Step length xp : ndarray Next position fp : float Merit function value at next position Fp : ndarray Residual at next position References ---------- [1] "Spectral residual method without gradient information for solving large-scale nonlinear systems of equations." W. La Cruz, J.M. Martinez, M. Raydan. Math. Comp. **75**, 1429 (2006).
Nonmonotone backtracking line search as described in [1]_
[ "Nonmonotone", "backtracking", "line", "search", "as", "described", "in", "[", "1", "]", "_" ]
def _nonmonotone_line_search_cruz(f, x_k, d, prev_fs, eta, gamma=1e-4, tau_min=0.1, tau_max=0.5): """ Nonmonotone backtracking line search as described in [1]_ Parameters ---------- f : callable Function returning a tuple ``(f, F)`` where ``f`` is the value of a merit function and ``F`` the residual. x_k : ndarray Initial position d : ndarray Search direction prev_fs : float List of previous merit function values. Should have ``len(prev_fs) <= M`` where ``M`` is the nonmonotonicity window parameter. eta : float Allowed merit function increase, see [1]_ gamma, tau_min, tau_max : float, optional Search parameters, see [1]_ Returns ------- alpha : float Step length xp : ndarray Next position fp : float Merit function value at next position Fp : ndarray Residual at next position References ---------- [1] "Spectral residual method without gradient information for solving large-scale nonlinear systems of equations." W. La Cruz, J.M. Martinez, M. Raydan. Math. Comp. **75**, 1429 (2006). """ f_k = prev_fs[-1] f_bar = max(prev_fs) alpha_p = 1 alpha_m = 1 alpha = 1 while True: xp = x_k + alpha_p * d fp, Fp = f(xp) if fp <= f_bar + eta - gamma * alpha_p**2 * f_k: alpha = alpha_p break alpha_tp = alpha_p**2 * f_k / (fp + (2*alpha_p - 1)*f_k) xp = x_k - alpha_m * d fp, Fp = f(xp) if fp <= f_bar + eta - gamma * alpha_m**2 * f_k: alpha = -alpha_m break alpha_tm = alpha_m**2 * f_k / (fp + (2*alpha_m - 1)*f_k) alpha_p = np.clip(alpha_tp, tau_min * alpha_p, tau_max * alpha_p) alpha_m = np.clip(alpha_tm, tau_min * alpha_m, tau_max * alpha_m) return alpha, xp, fp, Fp
[ "def", "_nonmonotone_line_search_cruz", "(", "f", ",", "x_k", ",", "d", ",", "prev_fs", ",", "eta", ",", "gamma", "=", "1e-4", ",", "tau_min", "=", "0.1", ",", "tau_max", "=", "0.5", ")", ":", "f_k", "=", "prev_fs", "[", "-", "1", "]", "f_bar", "=", "max", "(", "prev_fs", ")", "alpha_p", "=", "1", "alpha_m", "=", "1", "alpha", "=", "1", "while", "True", ":", "xp", "=", "x_k", "+", "alpha_p", "*", "d", "fp", ",", "Fp", "=", "f", "(", "xp", ")", "if", "fp", "<=", "f_bar", "+", "eta", "-", "gamma", "*", "alpha_p", "**", "2", "*", "f_k", ":", "alpha", "=", "alpha_p", "break", "alpha_tp", "=", "alpha_p", "**", "2", "*", "f_k", "/", "(", "fp", "+", "(", "2", "*", "alpha_p", "-", "1", ")", "*", "f_k", ")", "xp", "=", "x_k", "-", "alpha_m", "*", "d", "fp", ",", "Fp", "=", "f", "(", "xp", ")", "if", "fp", "<=", "f_bar", "+", "eta", "-", "gamma", "*", "alpha_m", "**", "2", "*", "f_k", ":", "alpha", "=", "-", "alpha_m", "break", "alpha_tm", "=", "alpha_m", "**", "2", "*", "f_k", "/", "(", "fp", "+", "(", "2", "*", "alpha_m", "-", "1", ")", "*", "f_k", ")", "alpha_p", "=", "np", ".", "clip", "(", "alpha_tp", ",", "tau_min", "*", "alpha_p", ",", "tau_max", "*", "alpha_p", ")", "alpha_m", "=", "np", ".", "clip", "(", "alpha_tm", ",", "tau_min", "*", "alpha_m", ",", "tau_max", "*", "alpha_m", ")", "return", "alpha", ",", "xp", ",", "fp", ",", "Fp" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/linesearch.py#L729-L798
rodeofx/OpenWalter
6116fbe3f04f1146c854afbfbdbe944feaee647e
walter/maya/scripts/walterPanel/walterMayaTraverser.py
python
WalterMayaImplementation.getLayersAssignationPlug
(self, nodeName)
return dependNode.findPlug("layersAssignation", False)
Return MPlug node.layersAssignation.
Return MPlug node.layersAssignation.
[ "Return", "MPlug", "node", ".", "layersAssignation", "." ]
def getLayersAssignationPlug(self, nodeName): """Return MPlug node.layersAssignation.""" # Walter Standin dependNode = self.getDependNode(nodeName) if not dependNode: return # Get walterStandin.layersAssignation return dependNode.findPlug("layersAssignation", False)
[ "def", "getLayersAssignationPlug", "(", "self", ",", "nodeName", ")", ":", "# Walter Standin", "dependNode", "=", "self", ".", "getDependNode", "(", "nodeName", ")", "if", "not", "dependNode", ":", "return", "# Get walterStandin.layersAssignation", "return", "dependNode", ".", "findPlug", "(", "\"layersAssignation\"", ",", "False", ")" ]
https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/maya/scripts/walterPanel/walterMayaTraverser.py#L791-L800
tensorflow/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
deepmath/premises/model_definition_cnn.py
python
Model.axiom_embedding
(self, axioms)
return self.make_embedding(axioms)
Compute the embedding for each of the axioms.
Compute the embedding for each of the axioms.
[ "Compute", "the", "embedding", "for", "each", "of", "the", "axioms", "." ]
def axiom_embedding(self, axioms): """Compute the embedding for each of the axioms.""" return self.make_embedding(axioms)
[ "def", "axiom_embedding", "(", "self", ",", "axioms", ")", ":", "return", "self", ".", "make_embedding", "(", "axioms", ")" ]
https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/premises/model_definition_cnn.py#L60-L62
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/makeutil.py
python
Makefile.create_rule
(self, targets=[])
return rule
Create a new rule in the makefile for the given targets. Returns the corresponding Rule instance.
Create a new rule in the makefile for the given targets. Returns the corresponding Rule instance.
[ "Create", "a", "new", "rule", "in", "the", "makefile", "for", "the", "given", "targets", ".", "Returns", "the", "corresponding", "Rule", "instance", "." ]
def create_rule(self, targets=[]): ''' Create a new rule in the makefile for the given targets. Returns the corresponding Rule instance. ''' rule = Rule(targets) self._statements.append(rule) return rule
[ "def", "create_rule", "(", "self", ",", "targets", "=", "[", "]", ")", ":", "rule", "=", "Rule", "(", "targets", ")", "self", ".", "_statements", ".", "append", "(", "rule", ")", "return", "rule" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/makeutil.py#L21-L28
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/isotonic.py
python
IsotonicRegression._build_y
(self, X, y, sample_weight, trim_duplicates=True)
Build the y_ IsotonicRegression.
Build the y_ IsotonicRegression.
[ "Build", "the", "y_", "IsotonicRegression", "." ]
def _build_y(self, X, y, sample_weight, trim_duplicates=True): """Build the y_ IsotonicRegression.""" check_consistent_length(X, y, sample_weight) X, y = [check_array(x, ensure_2d=False) for x in [X, y]] y = as_float_array(y) self._check_fit_data(X, y, sample_weight) # Determine increasing if auto-determination requested if self.increasing == 'auto': self.increasing_ = check_increasing(X, y) else: self.increasing_ = self.increasing # If sample_weights is passed, removed zero-weight values and clean # order if sample_weight is not None: sample_weight = check_array(sample_weight, ensure_2d=False) mask = sample_weight > 0 X, y, sample_weight = X[mask], y[mask], sample_weight[mask] else: sample_weight = np.ones(len(y)) order = np.lexsort((y, X)) X, y, sample_weight = [astype(array[order], np.float64, copy=False) for array in [X, y, sample_weight]] unique_X, unique_y, unique_sample_weight = _make_unique( X, y, sample_weight) # Store _X_ and _y_ to maintain backward compat during the deprecation # period of X_ and y_ self._X_ = X = unique_X self._y_ = y = isotonic_regression(unique_y, unique_sample_weight, self.y_min, self.y_max, increasing=self.increasing_) # Handle the left and right bounds on X self.X_min_, self.X_max_ = np.min(X), np.max(X) if trim_duplicates: # Remove unnecessary points for faster prediction keep_data = np.ones((len(y),), dtype=bool) # Aside from the 1st and last point, remove points whose y values # are equal to both the point before and the point after it. keep_data[1:-1] = np.logical_or( np.not_equal(y[1:-1], y[:-2]), np.not_equal(y[1:-1], y[2:]) ) return X[keep_data], y[keep_data] else: # The ability to turn off trim_duplicates is only used to it make # easier to unit test that removing duplicates in y does not have # any impact the resulting interpolation function (besides # prediction speed). return X, y
[ "def", "_build_y", "(", "self", ",", "X", ",", "y", ",", "sample_weight", ",", "trim_duplicates", "=", "True", ")", ":", "check_consistent_length", "(", "X", ",", "y", ",", "sample_weight", ")", "X", ",", "y", "=", "[", "check_array", "(", "x", ",", "ensure_2d", "=", "False", ")", "for", "x", "in", "[", "X", ",", "y", "]", "]", "y", "=", "as_float_array", "(", "y", ")", "self", ".", "_check_fit_data", "(", "X", ",", "y", ",", "sample_weight", ")", "# Determine increasing if auto-determination requested", "if", "self", ".", "increasing", "==", "'auto'", ":", "self", ".", "increasing_", "=", "check_increasing", "(", "X", ",", "y", ")", "else", ":", "self", ".", "increasing_", "=", "self", ".", "increasing", "# If sample_weights is passed, removed zero-weight values and clean", "# order", "if", "sample_weight", "is", "not", "None", ":", "sample_weight", "=", "check_array", "(", "sample_weight", ",", "ensure_2d", "=", "False", ")", "mask", "=", "sample_weight", ">", "0", "X", ",", "y", ",", "sample_weight", "=", "X", "[", "mask", "]", ",", "y", "[", "mask", "]", ",", "sample_weight", "[", "mask", "]", "else", ":", "sample_weight", "=", "np", ".", "ones", "(", "len", "(", "y", ")", ")", "order", "=", "np", ".", "lexsort", "(", "(", "y", ",", "X", ")", ")", "X", ",", "y", ",", "sample_weight", "=", "[", "astype", "(", "array", "[", "order", "]", ",", "np", ".", "float64", ",", "copy", "=", "False", ")", "for", "array", "in", "[", "X", ",", "y", ",", "sample_weight", "]", "]", "unique_X", ",", "unique_y", ",", "unique_sample_weight", "=", "_make_unique", "(", "X", ",", "y", ",", "sample_weight", ")", "# Store _X_ and _y_ to maintain backward compat during the deprecation", "# period of X_ and y_", "self", ".", "_X_", "=", "X", "=", "unique_X", "self", ".", "_y_", "=", "y", "=", "isotonic_regression", "(", "unique_y", ",", "unique_sample_weight", ",", "self", ".", "y_min", ",", "self", ".", "y_max", ",", "increasing", "=", "self", ".", "increasing_", ")", "# Handle the left and right bounds on X", "self", ".", "X_min_", ",", "self", ".", "X_max_", "=", "np", ".", "min", "(", "X", ")", ",", "np", ".", "max", "(", "X", ")", "if", "trim_duplicates", ":", "# Remove unnecessary points for faster prediction", "keep_data", "=", "np", ".", "ones", "(", "(", "len", "(", "y", ")", ",", ")", ",", "dtype", "=", "bool", ")", "# Aside from the 1st and last point, remove points whose y values", "# are equal to both the point before and the point after it.", "keep_data", "[", "1", ":", "-", "1", "]", "=", "np", ".", "logical_or", "(", "np", ".", "not_equal", "(", "y", "[", "1", ":", "-", "1", "]", ",", "y", "[", ":", "-", "2", "]", ")", ",", "np", ".", "not_equal", "(", "y", "[", "1", ":", "-", "1", "]", ",", "y", "[", "2", ":", "]", ")", ")", "return", "X", "[", "keep_data", "]", ",", "y", "[", "keep_data", "]", "else", ":", "# The ability to turn off trim_duplicates is only used to it make", "# easier to unit test that removing duplicates in y does not have", "# any impact the resulting interpolation function (besides", "# prediction speed).", "return", "X", ",", "y" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/isotonic.py#L270-L324
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_grad/grad_implementations.py
python
bprop_tuple_getitem
(data, idx, out, dout)
return F.tuple_setitem(C.zeros_like(data), idx, dout), C.zeros_like(idx)
Backpropagator for primitive `tuple_getitem`.
Backpropagator for primitive `tuple_getitem`.
[ "Backpropagator", "for", "primitive", "tuple_getitem", "." ]
def bprop_tuple_getitem(data, idx, out, dout): """Backpropagator for primitive `tuple_getitem`.""" return F.tuple_setitem(C.zeros_like(data), idx, dout), C.zeros_like(idx)
[ "def", "bprop_tuple_getitem", "(", "data", ",", "idx", ",", "out", ",", "dout", ")", ":", "return", "F", ".", "tuple_setitem", "(", "C", ".", "zeros_like", "(", "data", ")", ",", "idx", ",", "dout", ")", ",", "C", ".", "zeros_like", "(", "idx", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_grad/grad_implementations.py#L137-L139
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py
python
TarFile.utime
(self, tarinfo, targetpath)
Set modification time of targetpath according to tarinfo.
Set modification time of targetpath according to tarinfo.
[ "Set", "modification", "time", "of", "targetpath", "according", "to", "tarinfo", "." ]
def utime(self, tarinfo, targetpath): """Set modification time of targetpath according to tarinfo. """ if not hasattr(os, 'utime'): return try: os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime)) except OSError: raise ExtractError("could not change modification time")
[ "def", "utime", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "if", "not", "hasattr", "(", "os", ",", "'utime'", ")", ":", "return", "try", ":", "os", ".", "utime", "(", "targetpath", ",", "(", "tarinfo", ".", "mtime", ",", "tarinfo", ".", "mtime", ")", ")", "except", "OSError", ":", "raise", "ExtractError", "(", "\"could not change modification time\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py#L2257-L2265
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/util.py
python
get_logger
()
return _logger
Returns logger used by multiprocessing
Returns logger used by multiprocessing
[ "Returns", "logger", "used", "by", "multiprocessing" ]
def get_logger(): ''' Returns logger used by multiprocessing ''' global _logger import logging logging._acquireLock() try: if not _logger: _logger = logging.getLogger(LOGGER_NAME) _logger.propagate = 0 # XXX multiprocessing should cleanup before logging if hasattr(atexit, 'unregister'): atexit.unregister(_exit_function) atexit.register(_exit_function) else: atexit._exithandlers.remove((_exit_function, (), {})) atexit._exithandlers.append((_exit_function, (), {})) finally: logging._releaseLock() return _logger
[ "def", "get_logger", "(", ")", ":", "global", "_logger", "import", "logging", "logging", ".", "_acquireLock", "(", ")", "try", ":", "if", "not", "_logger", ":", "_logger", "=", "logging", ".", "getLogger", "(", "LOGGER_NAME", ")", "_logger", ".", "propagate", "=", "0", "# XXX multiprocessing should cleanup before logging", "if", "hasattr", "(", "atexit", ",", "'unregister'", ")", ":", "atexit", ".", "unregister", "(", "_exit_function", ")", "atexit", ".", "register", "(", "_exit_function", ")", "else", ":", "atexit", ".", "_exithandlers", ".", "remove", "(", "(", "_exit_function", ",", "(", ")", ",", "{", "}", ")", ")", "atexit", ".", "_exithandlers", ".", "append", "(", "(", "_exit_function", ",", "(", ")", ",", "{", "}", ")", ")", "finally", ":", "logging", ".", "_releaseLock", "(", ")", "return", "_logger" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/util.py#L60-L85
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/operator_pd_cholesky.py
python
OperatorPDCholesky.get_shape
(self)
return self._chol.get_shape()
`TensorShape` giving static shape.
`TensorShape` giving static shape.
[ "TensorShape", "giving", "static", "shape", "." ]
def get_shape(self): """`TensorShape` giving static shape.""" return self._chol.get_shape()
[ "def", "get_shape", "(", "self", ")", ":", "return", "self", ".", "_chol", ".", "get_shape", "(", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/operator_pd_cholesky.py#L160-L162
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Utilities/Templates/Modules/Scripted/TemplateKey.py
python
TemplateKeyWidget.exit
(self)
Called each time the user opens a different module.
Called each time the user opens a different module.
[ "Called", "each", "time", "the", "user", "opens", "a", "different", "module", "." ]
def exit(self): """ Called each time the user opens a different module. """ # Do not react to parameter node changes (GUI wlil be updated when the user enters into the module) self.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)
[ "def", "exit", "(", "self", ")", ":", "# Do not react to parameter node changes (GUI wlil be updated when the user enters into the module)", "self", ".", "removeObserver", "(", "self", ".", "_parameterNode", ",", "vtk", ".", "vtkCommand", ".", "ModifiedEvent", ",", "self", ".", "updateGUIFromParameterNode", ")" ]
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Utilities/Templates/Modules/Scripted/TemplateKey.py#L159-L164
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/util/_cloudpickle/_cloudpickle_py27.py
python
CloudPickler.save_function_tuple
(self, func)
Pickles an actual func object. A func comprises: code, globals, defaults, closure, and dict. We extract and save these, injecting reducing functions at certain points to recreate the func object. Keep in mind that some of these pieces can contain a ref to the func itself. Thus, a naive save on these pieces could trigger an infinite loop of save's. To get around that, we first create a skeleton func object using just the code (this is safe, since this won't contain a ref to the func), and memoize it as soon as it's created. The other stuff can then be filled in later.
Pickles an actual func object.
[ "Pickles", "an", "actual", "func", "object", "." ]
def save_function_tuple(self, func): """ Pickles an actual func object. A func comprises: code, globals, defaults, closure, and dict. We extract and save these, injecting reducing functions at certain points to recreate the func object. Keep in mind that some of these pieces can contain a ref to the func itself. Thus, a naive save on these pieces could trigger an infinite loop of save's. To get around that, we first create a skeleton func object using just the code (this is safe, since this won't contain a ref to the func), and memoize it as soon as it's created. The other stuff can then be filled in later. """ if is_tornado_coroutine(func): self.save_reduce(_rebuild_tornado_coroutine, (func.__wrapped__,), obj=func) return save = self.save write = self.write ( code, f_globals, defaults, closure_values, dct, base_globals, ) = self.extract_func_data(func) save(_fill_function) # skeleton function updater write(pickle.MARK) # beginning of tuple that _fill_function expects self._save_subimports( code, itertools.chain(f_globals.values(), closure_values or ()), ) # create a skeleton function object and memoize it save(_make_skel_func) save( ( code, len(closure_values) if closure_values is not None else -1, base_globals, ) ) write(pickle.REDUCE) self.memoize(func) # save the rest of the func data needed by _fill_function save(f_globals) save(defaults) save(dct) save(func.__module__) save(closure_values) write(pickle.TUPLE) write(pickle.REDUCE)
[ "def", "save_function_tuple", "(", "self", ",", "func", ")", ":", "if", "is_tornado_coroutine", "(", "func", ")", ":", "self", ".", "save_reduce", "(", "_rebuild_tornado_coroutine", ",", "(", "func", ".", "__wrapped__", ",", ")", ",", "obj", "=", "func", ")", "return", "save", "=", "self", ".", "save", "write", "=", "self", ".", "write", "(", "code", ",", "f_globals", ",", "defaults", ",", "closure_values", ",", "dct", ",", "base_globals", ",", ")", "=", "self", ".", "extract_func_data", "(", "func", ")", "save", "(", "_fill_function", ")", "# skeleton function updater", "write", "(", "pickle", ".", "MARK", ")", "# beginning of tuple that _fill_function expects", "self", ".", "_save_subimports", "(", "code", ",", "itertools", ".", "chain", "(", "f_globals", ".", "values", "(", ")", ",", "closure_values", "or", "(", ")", ")", ",", ")", "# create a skeleton function object and memoize it", "save", "(", "_make_skel_func", ")", "save", "(", "(", "code", ",", "len", "(", "closure_values", ")", "if", "closure_values", "is", "not", "None", "else", "-", "1", ",", "base_globals", ",", ")", ")", "write", "(", "pickle", ".", "REDUCE", ")", "self", ".", "memoize", "(", "func", ")", "# save the rest of the func data needed by _fill_function", "save", "(", "f_globals", ")", "save", "(", "defaults", ")", "save", "(", "dct", ")", "save", "(", "func", ".", "__module__", ")", "save", "(", "closure_values", ")", "write", "(", "pickle", ".", "TUPLE", ")", "write", "(", "pickle", ".", "REDUCE", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/util/_cloudpickle/_cloudpickle_py27.py#L530-L584
qt/qt
0a2f2382541424726168804be2c90b91381608c6
src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/generator/msvs.py
python
_GetLibraries
(config, spec)
return [re.sub('^(\-l)', '', lib) for lib in libraries]
Returns the list of libraries for this configuration. Arguments: config: The dictionnary that defines the special processing to be done for this configuration. spec: The target dictionary containing the properties of the target. Returns: The list of directory paths.
Returns the list of libraries for this configuration.
[ "Returns", "the", "list", "of", "libraries", "for", "this", "configuration", "." ]
def _GetLibraries(config, spec): """Returns the list of libraries for this configuration. Arguments: config: The dictionnary that defines the special processing to be done for this configuration. spec: The target dictionary containing the properties of the target. Returns: The list of directory paths. """ libraries = spec.get('libraries', []) # Strip out -l, as it is not used on windows (but is needed so we can pass # in libraries that are assumed to be in the default library path). return [re.sub('^(\-l)', '', lib) for lib in libraries]
[ "def", "_GetLibraries", "(", "config", ",", "spec", ")", ":", "libraries", "=", "spec", ".", "get", "(", "'libraries'", ",", "[", "]", ")", "# Strip out -l, as it is not used on windows (but is needed so we can pass", "# in libraries that are assumed to be in the default library path).", "return", "[", "re", ".", "sub", "(", "'^(\\-l)'", ",", "''", ",", "lib", ")", "for", "lib", "in", "libraries", "]" ]
https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/generator/msvs.py#L944-L957
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/motionplanning.py
python
get_plan_json_string
()
return _motionplanning.get_plan_json_string()
r""" get_plan_json_string() -> std::string Saves planner values to a JSON string.
r""" get_plan_json_string() -> std::string
[ "r", "get_plan_json_string", "()", "-", ">", "std", "::", "string" ]
def get_plan_json_string() -> "std::string": r""" get_plan_json_string() -> std::string Saves planner values to a JSON string. """ return _motionplanning.get_plan_json_string()
[ "def", "get_plan_json_string", "(", ")", "->", "\"std::string\"", ":", "return", "_motionplanning", ".", "get_plan_json_string", "(", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/motionplanning.py#L360-L368
psmoveservice/PSMoveService
22bbe20e9de53f3f3581137bce7b88e2587a27e7
misc/python/pypsmove/transformations.py
python
orthogonalization_matrix
(lengths, angles)
return numpy.array([ [ a*sinb*math.sqrt(1.0-co*co), 0.0, 0.0, 0.0], [-a*sinb*co, b*sina, 0.0, 0.0], [ a*cosb, b*cosa, c, 0.0], [ 0.0, 0.0, 0.0, 1.0]])
Return orthogonalization matrix for crystallographic cell coordinates. Angles are expected in degrees. The de-orthogonalization matrix is the inverse. >>> O = orthogonalization_matrix([10, 10, 10], [90, 90, 90]) >>> numpy.allclose(O[:3, :3], numpy.identity(3, float) * 10) True >>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7]) >>> numpy.allclose(numpy.sum(O), 43.063229) True
Return orthogonalization matrix for crystallographic cell coordinates.
[ "Return", "orthogonalization", "matrix", "for", "crystallographic", "cell", "coordinates", "." ]
def orthogonalization_matrix(lengths, angles): """Return orthogonalization matrix for crystallographic cell coordinates. Angles are expected in degrees. The de-orthogonalization matrix is the inverse. >>> O = orthogonalization_matrix([10, 10, 10], [90, 90, 90]) >>> numpy.allclose(O[:3, :3], numpy.identity(3, float) * 10) True >>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7]) >>> numpy.allclose(numpy.sum(O), 43.063229) True """ a, b, c = lengths angles = numpy.radians(angles) sina, sinb, _ = numpy.sin(angles) cosa, cosb, cosg = numpy.cos(angles) co = (cosa * cosb - cosg) / (sina * sinb) return numpy.array([ [ a*sinb*math.sqrt(1.0-co*co), 0.0, 0.0, 0.0], [-a*sinb*co, b*sina, 0.0, 0.0], [ a*cosb, b*cosa, c, 0.0], [ 0.0, 0.0, 0.0, 1.0]])
[ "def", "orthogonalization_matrix", "(", "lengths", ",", "angles", ")", ":", "a", ",", "b", ",", "c", "=", "lengths", "angles", "=", "numpy", ".", "radians", "(", "angles", ")", "sina", ",", "sinb", ",", "_", "=", "numpy", ".", "sin", "(", "angles", ")", "cosa", ",", "cosb", ",", "cosg", "=", "numpy", ".", "cos", "(", "angles", ")", "co", "=", "(", "cosa", "*", "cosb", "-", "cosg", ")", "/", "(", "sina", "*", "sinb", ")", "return", "numpy", ".", "array", "(", "[", "[", "a", "*", "sinb", "*", "math", ".", "sqrt", "(", "1.0", "-", "co", "*", "co", ")", ",", "0.0", ",", "0.0", ",", "0.0", "]", ",", "[", "-", "a", "*", "sinb", "*", "co", ",", "b", "*", "sina", ",", "0.0", ",", "0.0", "]", ",", "[", "a", "*", "cosb", ",", "b", "*", "cosa", ",", "c", ",", "0.0", "]", ",", "[", "0.0", ",", "0.0", ",", "0.0", ",", "1.0", "]", "]", ")" ]
https://github.com/psmoveservice/PSMoveService/blob/22bbe20e9de53f3f3581137bce7b88e2587a27e7/misc/python/pypsmove/transformations.py#L862-L886
dmlc/nnvm
dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38
python/nnvm/symbol.py
python
Symbol.list_input_names
(self, option='all')
return [_base.py_str(sarr[i]) for i in range(size.value)]
List all the inputs in the symbol. Parameters ---------- option : {'all', 'read_only', 'aux_state'}, optional The listing option - 'all' will list all the arguments. - 'read_only' lists arguments that are readed by the graph. - 'aux_state' lists arguments that are mutated by the graph as state. Returns ------- args : list of string List of all the arguments.
List all the inputs in the symbol.
[ "List", "all", "the", "inputs", "in", "the", "symbol", "." ]
def list_input_names(self, option='all'): """List all the inputs in the symbol. Parameters ---------- option : {'all', 'read_only', 'aux_state'}, optional The listing option - 'all' will list all the arguments. - 'read_only' lists arguments that are readed by the graph. - 'aux_state' lists arguments that are mutated by the graph as state. Returns ------- args : list of string List of all the arguments. """ size = _ctypes.c_uint() sarr = _ctypes.POINTER(_ctypes.c_char_p)() _check_call(_LIB.NNSymbolListInputNames( self.handle, self._get_list_copt(option), _ctypes.byref(size), _ctypes.byref(sarr))) return [_base.py_str(sarr[i]) for i in range(size.value)]
[ "def", "list_input_names", "(", "self", ",", "option", "=", "'all'", ")", ":", "size", "=", "_ctypes", ".", "c_uint", "(", ")", "sarr", "=", "_ctypes", ".", "POINTER", "(", "_ctypes", ".", "c_char_p", ")", "(", ")", "_check_call", "(", "_LIB", ".", "NNSymbolListInputNames", "(", "self", ".", "handle", ",", "self", ".", "_get_list_copt", "(", "option", ")", ",", "_ctypes", ".", "byref", "(", "size", ")", ",", "_ctypes", ".", "byref", "(", "sarr", ")", ")", ")", "return", "[", "_base", ".", "py_str", "(", "sarr", "[", "i", "]", ")", "for", "i", "in", "range", "(", "size", ".", "value", ")", "]" ]
https://github.com/dmlc/nnvm/blob/dab5ce8ab6adbf4edd8bd2fa89f1a99f343b6e38/python/nnvm/symbol.py#L256-L276
plumonito/dtslam
5994bb9cf7a11981b830370db206bceb654c085d
3rdparty/eigen-3.2.2/debug/gdb/printers.py
python
EigenMatrixPrinter.__init__
(self, variety, val)
Extract all the necessary information
Extract all the necessary information
[ "Extract", "all", "the", "necessary", "information" ]
def __init__(self, variety, val): "Extract all the necessary information" # Save the variety (presumably "Matrix" or "Array") for later usage self.variety = variety # The gdb extension does not support value template arguments - need to extract them by hand type = val.type if type.code == gdb.TYPE_CODE_REF: type = type.target() self.type = type.unqualified().strip_typedefs() tag = self.type.tag regex = re.compile('\<.*\>') m = regex.findall(tag)[0][1:-1] template_params = m.split(',') template_params = map(lambda x:x.replace(" ", ""), template_params) if template_params[1] == '-0x00000000000000001' or template_params[1] == '-0x000000001' or template_params[1] == '-1': self.rows = val['m_storage']['m_rows'] else: self.rows = int(template_params[1]) if template_params[2] == '-0x00000000000000001' or template_params[2] == '-0x000000001' or template_params[2] == '-1': self.cols = val['m_storage']['m_cols'] else: self.cols = int(template_params[2]) self.options = 0 # default value if len(template_params) > 3: self.options = template_params[3]; self.rowMajor = (int(self.options) & 0x1) self.innerType = self.type.template_argument(0) self.val = val # Fixed size matrices have a struct as their storage, so we need to walk through this self.data = self.val['m_storage']['m_data'] if self.data.type.code == gdb.TYPE_CODE_STRUCT: self.data = self.data['array'] self.data = self.data.cast(self.innerType.pointer())
[ "def", "__init__", "(", "self", ",", "variety", ",", "val", ")", ":", "# Save the variety (presumably \"Matrix\" or \"Array\") for later usage", "self", ".", "variety", "=", "variety", "# The gdb extension does not support value template arguments - need to extract them by hand", "type", "=", "val", ".", "type", "if", "type", ".", "code", "==", "gdb", ".", "TYPE_CODE_REF", ":", "type", "=", "type", ".", "target", "(", ")", "self", ".", "type", "=", "type", ".", "unqualified", "(", ")", ".", "strip_typedefs", "(", ")", "tag", "=", "self", ".", "type", ".", "tag", "regex", "=", "re", ".", "compile", "(", "'\\<.*\\>'", ")", "m", "=", "regex", ".", "findall", "(", "tag", ")", "[", "0", "]", "[", "1", ":", "-", "1", "]", "template_params", "=", "m", ".", "split", "(", "','", ")", "template_params", "=", "map", "(", "lambda", "x", ":", "x", ".", "replace", "(", "\" \"", ",", "\"\"", ")", ",", "template_params", ")", "if", "template_params", "[", "1", "]", "==", "'-0x00000000000000001'", "or", "template_params", "[", "1", "]", "==", "'-0x000000001'", "or", "template_params", "[", "1", "]", "==", "'-1'", ":", "self", ".", "rows", "=", "val", "[", "'m_storage'", "]", "[", "'m_rows'", "]", "else", ":", "self", ".", "rows", "=", "int", "(", "template_params", "[", "1", "]", ")", "if", "template_params", "[", "2", "]", "==", "'-0x00000000000000001'", "or", "template_params", "[", "2", "]", "==", "'-0x000000001'", "or", "template_params", "[", "2", "]", "==", "'-1'", ":", "self", ".", "cols", "=", "val", "[", "'m_storage'", "]", "[", "'m_cols'", "]", "else", ":", "self", ".", "cols", "=", "int", "(", "template_params", "[", "2", "]", ")", "self", ".", "options", "=", "0", "# default value", "if", "len", "(", "template_params", ")", ">", "3", ":", "self", ".", "options", "=", "template_params", "[", "3", "]", "self", ".", "rowMajor", "=", "(", "int", "(", "self", ".", "options", ")", "&", "0x1", ")", "self", ".", "innerType", "=", "self", ".", "type", ".", "template_argument", "(", "0", ")", "self", ".", "val", "=", "val", "# Fixed size matrices have a struct as their storage, so we need to walk through this", "self", ".", "data", "=", "self", ".", "val", "[", "'m_storage'", "]", "[", "'m_data'", "]", "if", "self", ".", "data", ".", "type", ".", "code", "==", "gdb", ".", "TYPE_CODE_STRUCT", ":", "self", ".", "data", "=", "self", ".", "data", "[", "'array'", "]", "self", ".", "data", "=", "self", ".", "data", ".", "cast", "(", "self", ".", "innerType", ".", "pointer", "(", ")", ")" ]
https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/eigen-3.2.2/debug/gdb/printers.py#L37-L78
PaddlePaddle/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
tools/external_converter_v2/parser/graph_io.py
python
NodeProtoIO.add_attr
(self, value_name, data, data_type_str)
set tensor data: value_name : var name data : real data data_type_str : data type desc ("string" "int" "float" "bool" "tensor" "shape" "list_value")
set tensor data: value_name : var name data : real data data_type_str : data type desc ("string" "int" "float" "bool" "tensor" "shape" "list_value")
[ "set", "tensor", "data", ":", "value_name", ":", "var", "name", "data", ":", "real", "data", "data_type_str", ":", "data", "type", "desc", "(", "string", "int", "float", "bool", "tensor", "shape", "list_value", ")" ]
def add_attr(self, value_name, data, data_type_str): """ set tensor data: value_name : var name data : real data data_type_str : data type desc ("string" "int" "float" "bool" "tensor" "shape" "list_value") """ self.node_proto.attr[value_name].CopyFrom(self.attr_warpper(data, data_type_str))
[ "def", "add_attr", "(", "self", ",", "value_name", ",", "data", ",", "data_type_str", ")", ":", "self", ".", "node_proto", ".", "attr", "[", "value_name", "]", ".", "CopyFrom", "(", "self", ".", "attr_warpper", "(", "data", ",", "data_type_str", ")", ")" ]
https://github.com/PaddlePaddle/Anakin/blob/5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730/tools/external_converter_v2/parser/graph_io.py#L230-L244
google/mozc
7329757e1ad30e327c1ae823a8302c79482d6b9c
src/build_tools/versioning_files.py
python
_GetSha1Digest
(file_path)
return sha.digest()
Returns the sha1 hash of the file.
Returns the sha1 hash of the file.
[ "Returns", "the", "sha1", "hash", "of", "the", "file", "." ]
def _GetSha1Digest(file_path): """Returns the sha1 hash of the file.""" sha = hashlib.sha1() with open(file_path, 'rb') as f: data = f.read() sha.update(data) return sha.digest()
[ "def", "_GetSha1Digest", "(", "file_path", ")", ":", "sha", "=", "hashlib", ".", "sha1", "(", ")", "with", "open", "(", "file_path", ",", "'rb'", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", ")", "sha", ".", "update", "(", "data", ")", "return", "sha", ".", "digest", "(", ")" ]
https://github.com/google/mozc/blob/7329757e1ad30e327c1ae823a8302c79482d6b9c/src/build_tools/versioning_files.py#L62-L68
ros-planning/moveit2
dd240ef6fd8b9932a7a53964140f2952786187a9
moveit_commander/src/moveit_commander/move_group.py
python
MoveGroupCommander.get_active_joints
(self)
return self._g.get_active_joints()
Get the active joints of this group
Get the active joints of this group
[ "Get", "the", "active", "joints", "of", "this", "group" ]
def get_active_joints(self): """ Get the active joints of this group """ return self._g.get_active_joints()
[ "def", "get_active_joints", "(", "self", ")", ":", "return", "self", ".", "_g", ".", "get_active_joints", "(", ")" ]
https://github.com/ros-planning/moveit2/blob/dd240ef6fd8b9932a7a53964140f2952786187a9/moveit_commander/src/moveit_commander/move_group.py#L78-L80
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/Tool/mwcc.py
python
set_vars
(env)
return 1
Set MWCW_VERSION, MWCW_VERSIONS, and some codewarrior environment vars MWCW_VERSIONS is set to a list of objects representing installed versions MWCW_VERSION is set to the version object that will be used for building. MWCW_VERSION can be set to a string during Environment construction to influence which version is chosen, otherwise the latest one from MWCW_VERSIONS is used. Returns true if at least one version is found, false otherwise
Set MWCW_VERSION, MWCW_VERSIONS, and some codewarrior environment vars
[ "Set", "MWCW_VERSION", "MWCW_VERSIONS", "and", "some", "codewarrior", "environment", "vars" ]
def set_vars(env): """Set MWCW_VERSION, MWCW_VERSIONS, and some codewarrior environment vars MWCW_VERSIONS is set to a list of objects representing installed versions MWCW_VERSION is set to the version object that will be used for building. MWCW_VERSION can be set to a string during Environment construction to influence which version is chosen, otherwise the latest one from MWCW_VERSIONS is used. Returns true if at least one version is found, false otherwise """ desired = env.get('MWCW_VERSION', '') # return right away if the variables are already set if isinstance(desired, MWVersion): return 1 elif desired is None: return 0 versions = find_versions() version = None if desired: for v in versions: if str(v) == desired: version = v elif versions: version = versions[-1] env['MWCW_VERSIONS'] = versions env['MWCW_VERSION'] = version if version is None: return 0 env.PrependENVPath('PATH', version.clpath) env.PrependENVPath('PATH', version.dllpath) ENV = env['ENV'] ENV['CWFolder'] = version.path ENV['LM_LICENSE_FILE'] = version.license plus = lambda x: '+%s' % x ENV['MWCIncludes'] = os.pathsep.join(map(plus, version.includes)) ENV['MWLibraries'] = os.pathsep.join(map(plus, version.libs)) return 1
[ "def", "set_vars", "(", "env", ")", ":", "desired", "=", "env", ".", "get", "(", "'MWCW_VERSION'", ",", "''", ")", "# return right away if the variables are already set", "if", "isinstance", "(", "desired", ",", "MWVersion", ")", ":", "return", "1", "elif", "desired", "is", "None", ":", "return", "0", "versions", "=", "find_versions", "(", ")", "version", "=", "None", "if", "desired", ":", "for", "v", "in", "versions", ":", "if", "str", "(", "v", ")", "==", "desired", ":", "version", "=", "v", "elif", "versions", ":", "version", "=", "versions", "[", "-", "1", "]", "env", "[", "'MWCW_VERSIONS'", "]", "=", "versions", "env", "[", "'MWCW_VERSION'", "]", "=", "version", "if", "version", "is", "None", ":", "return", "0", "env", ".", "PrependENVPath", "(", "'PATH'", ",", "version", ".", "clpath", ")", "env", ".", "PrependENVPath", "(", "'PATH'", ",", "version", ".", "dllpath", ")", "ENV", "=", "env", "[", "'ENV'", "]", "ENV", "[", "'CWFolder'", "]", "=", "version", ".", "path", "ENV", "[", "'LM_LICENSE_FILE'", "]", "=", "version", ".", "license", "plus", "=", "lambda", "x", ":", "'+%s'", "%", "x", "ENV", "[", "'MWCIncludes'", "]", "=", "os", ".", "pathsep", ".", "join", "(", "map", "(", "plus", ",", "version", ".", "includes", ")", ")", "ENV", "[", "'MWLibraries'", "]", "=", "os", ".", "pathsep", ".", "join", "(", "map", "(", "plus", ",", "version", ".", "libs", ")", ")", "return", "1" ]
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Tool/mwcc.py#L40-L84
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
cnx/strategy/tickPosition.py
python
Position.entryActive
(self)
return self.__entryOrder is not None and self.__entryOrder.isActive()
Returns True if the entry order is active.
Returns True if the entry order is active.
[ "Returns", "True", "if", "the", "entry", "order", "is", "active", "." ]
def entryActive(self): """Returns True if the entry order is active.""" return self.__entryOrder is not None and self.__entryOrder.isActive()
[ "def", "entryActive", "(", "self", ")", ":", "return", "self", ".", "__entryOrder", "is", "not", "None", "and", "self", ".", "__entryOrder", ".", "isActive", "(", ")" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/cnx/strategy/tickPosition.py#L219-L221
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/history.py
python
HistoryManager.writeout_cache
(self, conn=None)
Write any entries in the cache to the database.
Write any entries in the cache to the database.
[ "Write", "any", "entries", "in", "the", "cache", "to", "the", "database", "." ]
def writeout_cache(self, conn=None): """Write any entries in the cache to the database.""" if conn is None: conn = self.db with self.db_input_cache_lock: try: self._writeout_input_cache(conn) except sqlite3.IntegrityError: self.new_session(conn) print("ERROR! Session/line number was not unique in", "database. History logging moved to new session", self.session_number) try: # Try writing to the new session. If this fails, don't # recurse self._writeout_input_cache(conn) except sqlite3.IntegrityError: pass finally: self.db_input_cache = [] with self.db_output_cache_lock: try: self._writeout_output_cache(conn) except sqlite3.IntegrityError: print("!! Session/line number for output was not unique", "in database. Output will not be stored.") finally: self.db_output_cache = []
[ "def", "writeout_cache", "(", "self", ",", "conn", "=", "None", ")", ":", "if", "conn", "is", "None", ":", "conn", "=", "self", ".", "db", "with", "self", ".", "db_input_cache_lock", ":", "try", ":", "self", ".", "_writeout_input_cache", "(", "conn", ")", "except", "sqlite3", ".", "IntegrityError", ":", "self", ".", "new_session", "(", "conn", ")", "print", "(", "\"ERROR! Session/line number was not unique in\"", ",", "\"database. History logging moved to new session\"", ",", "self", ".", "session_number", ")", "try", ":", "# Try writing to the new session. If this fails, don't", "# recurse", "self", ".", "_writeout_input_cache", "(", "conn", ")", "except", "sqlite3", ".", "IntegrityError", ":", "pass", "finally", ":", "self", ".", "db_input_cache", "=", "[", "]", "with", "self", ".", "db_output_cache_lock", ":", "try", ":", "self", ".", "_writeout_output_cache", "(", "conn", ")", "except", "sqlite3", ".", "IntegrityError", ":", "print", "(", "\"!! Session/line number for output was not unique\"", ",", "\"in database. Output will not be stored.\"", ")", "finally", ":", "self", ".", "db_output_cache", "=", "[", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/history.py#L773-L802
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/framework/python/ops/variables.py
python
get_or_create_global_step
(graph=None)
return globalstep
Returns and create (if necessary) the global step variable. Args: graph: The graph in which to create the global step. If missing, use default graph. Returns: the tensor representing the global step variable.
Returns and create (if necessary) the global step variable.
[ "Returns", "and", "create", "(", "if", "necessary", ")", "the", "global", "step", "variable", "." ]
def get_or_create_global_step(graph=None): """Returns and create (if necessary) the global step variable. Args: graph: The graph in which to create the global step. If missing, use default graph. Returns: the tensor representing the global step variable. """ graph = ops.get_default_graph() if graph is None else graph globalstep = get_global_step(graph) if globalstep is None: globalstep = create_global_step(graph) return globalstep
[ "def", "get_or_create_global_step", "(", "graph", "=", "None", ")", ":", "graph", "=", "ops", ".", "get_default_graph", "(", ")", "if", "graph", "is", "None", "else", "graph", "globalstep", "=", "get_global_step", "(", "graph", ")", "if", "globalstep", "is", "None", ":", "globalstep", "=", "create_global_step", "(", "graph", ")", "return", "globalstep" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/framework/python/ops/variables.py#L160-L174
Samsung/veles
95ed733c2e49bc011ad98ccf2416ecec23fbf352
veles/external/daemon/daemon.py
python
DaemonContext.__init__
( self, chroot_directory=None, working_directory='/', umask=0, uid=None, gid=None, prevent_core=True, detach_process=None, files_preserve=None, pidfile=None, stdin=None, stdout=None, stderr=None, signal_map=None, )
Set up a new instance.
Set up a new instance.
[ "Set", "up", "a", "new", "instance", "." ]
def __init__( self, chroot_directory=None, working_directory='/', umask=0, uid=None, gid=None, prevent_core=True, detach_process=None, files_preserve=None, pidfile=None, stdin=None, stdout=None, stderr=None, signal_map=None, ): """ Set up a new instance. """ self.chroot_directory = chroot_directory self.working_directory = working_directory self.umask = umask self.prevent_core = prevent_core self.files_preserve = files_preserve self.pidfile = pidfile self.stdin = stdin self.stdout = stdout self.stderr = stderr if uid is None: uid = os.getuid() elif isinstance(uid, str): try: uid = int(uid) except ValueError: uid = getpwnam(uid).pw_uid self.uid = uid if gid is None: gid = os.getgid() elif isinstance(gid, str): try: gid = int(gid) except ValueError: gid = getgrnam(gid).gr_gid self.gid = gid if detach_process is None: detach_process = is_detach_process_context_required() self.detach_process = detach_process if signal_map is None: signal_map = make_default_signal_map() self.signal_map = signal_map self._is_open = False
[ "def", "__init__", "(", "self", ",", "chroot_directory", "=", "None", ",", "working_directory", "=", "'/'", ",", "umask", "=", "0", ",", "uid", "=", "None", ",", "gid", "=", "None", ",", "prevent_core", "=", "True", ",", "detach_process", "=", "None", ",", "files_preserve", "=", "None", ",", "pidfile", "=", "None", ",", "stdin", "=", "None", ",", "stdout", "=", "None", ",", "stderr", "=", "None", ",", "signal_map", "=", "None", ",", ")", ":", "self", ".", "chroot_directory", "=", "chroot_directory", "self", ".", "working_directory", "=", "working_directory", "self", ".", "umask", "=", "umask", "self", ".", "prevent_core", "=", "prevent_core", "self", ".", "files_preserve", "=", "files_preserve", "self", ".", "pidfile", "=", "pidfile", "self", ".", "stdin", "=", "stdin", "self", ".", "stdout", "=", "stdout", "self", ".", "stderr", "=", "stderr", "if", "uid", "is", "None", ":", "uid", "=", "os", ".", "getuid", "(", ")", "elif", "isinstance", "(", "uid", ",", "str", ")", ":", "try", ":", "uid", "=", "int", "(", "uid", ")", "except", "ValueError", ":", "uid", "=", "getpwnam", "(", "uid", ")", ".", "pw_uid", "self", ".", "uid", "=", "uid", "if", "gid", "is", "None", ":", "gid", "=", "os", ".", "getgid", "(", ")", "elif", "isinstance", "(", "gid", ",", "str", ")", ":", "try", ":", "gid", "=", "int", "(", "gid", ")", "except", "ValueError", ":", "gid", "=", "getgrnam", "(", "gid", ")", ".", "gr_gid", "self", ".", "gid", "=", "gid", "if", "detach_process", "is", "None", ":", "detach_process", "=", "is_detach_process_context_required", "(", ")", "self", ".", "detach_process", "=", "detach_process", "if", "signal_map", "is", "None", ":", "signal_map", "=", "make_default_signal_map", "(", ")", "self", ".", "signal_map", "=", "signal_map", "self", ".", "_is_open", "=", "False" ]
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/daemon/daemon.py#L210-L262
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/mailbox.py
python
MHMessage.add_sequence
(self, sequence)
Add sequence to list of sequences including the message.
Add sequence to list of sequences including the message.
[ "Add", "sequence", "to", "list", "of", "sequences", "including", "the", "message", "." ]
def add_sequence(self, sequence): """Add sequence to list of sequences including the message.""" if isinstance(sequence, str): if not sequence in self._sequences: self._sequences.append(sequence) else: raise TypeError('sequence type must be str: %s' % type(sequence))
[ "def", "add_sequence", "(", "self", ",", "sequence", ")", ":", "if", "isinstance", "(", "sequence", ",", "str", ")", ":", "if", "not", "sequence", "in", "self", ".", "_sequences", ":", "self", ".", "_sequences", ".", "append", "(", "sequence", ")", "else", ":", "raise", "TypeError", "(", "'sequence type must be str: %s'", "%", "type", "(", "sequence", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/mailbox.py#L1767-L1773
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/logging/handlers.py
python
HTTPHandler.emit
(self, record)
Emit a record. Send the record to the Web server as an URL-encoded dictionary
Emit a record.
[ "Emit", "a", "record", "." ]
def emit(self, record): """ Emit a record. Send the record to the Web server as an URL-encoded dictionary """ try: import httplib, urllib host = self.host h = httplib.HTTP(host) url = self.url data = urllib.urlencode(self.mapLogRecord(record)) if self.method == "GET": if (string.find(url, '?') >= 0): sep = '&' else: sep = '?' url = url + "%c%s" % (sep, data) h.putrequest(self.method, url) # support multiple hosts on one IP address... # need to strip optional :port from host, if present i = string.find(host, ":") if i >= 0: host = host[:i] h.putheader("Host", host) if self.method == "POST": h.putheader("Content-type", "application/x-www-form-urlencoded") h.putheader("Content-length", str(len(data))) h.endheaders() if self.method == "POST": h.send(data) h.getreply() #can't do anything with the result except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)
[ "def", "emit", "(", "self", ",", "record", ")", ":", "try", ":", "import", "httplib", ",", "urllib", "host", "=", "self", ".", "host", "h", "=", "httplib", ".", "HTTP", "(", "host", ")", "url", "=", "self", ".", "url", "data", "=", "urllib", ".", "urlencode", "(", "self", ".", "mapLogRecord", "(", "record", ")", ")", "if", "self", ".", "method", "==", "\"GET\"", ":", "if", "(", "string", ".", "find", "(", "url", ",", "'?'", ")", ">=", "0", ")", ":", "sep", "=", "'&'", "else", ":", "sep", "=", "'?'", "url", "=", "url", "+", "\"%c%s\"", "%", "(", "sep", ",", "data", ")", "h", ".", "putrequest", "(", "self", ".", "method", ",", "url", ")", "# support multiple hosts on one IP address...", "# need to strip optional :port from host, if present", "i", "=", "string", ".", "find", "(", "host", ",", "\":\"", ")", "if", "i", ">=", "0", ":", "host", "=", "host", "[", ":", "i", "]", "h", ".", "putheader", "(", "\"Host\"", ",", "host", ")", "if", "self", ".", "method", "==", "\"POST\"", ":", "h", ".", "putheader", "(", "\"Content-type\"", ",", "\"application/x-www-form-urlencoded\"", ")", "h", ".", "putheader", "(", "\"Content-length\"", ",", "str", "(", "len", "(", "data", ")", ")", ")", "h", ".", "endheaders", "(", ")", "if", "self", ".", "method", "==", "\"POST\"", ":", "h", ".", "send", "(", "data", ")", "h", ".", "getreply", "(", ")", "#can't do anything with the result", "except", "(", "KeyboardInterrupt", ",", "SystemExit", ")", ":", "raise", "except", ":", "self", ".", "handleError", "(", "record", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/logging/handlers.py#L1007-L1043
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/internals/array_manager.py
python
BaseArrayManager.make_empty
(self: T, axes=None)
return type(self)(arrays, axes)
Return an empty ArrayManager with the items axis of len 0 (no columns)
Return an empty ArrayManager with the items axis of len 0 (no columns)
[ "Return", "an", "empty", "ArrayManager", "with", "the", "items", "axis", "of", "len", "0", "(", "no", "columns", ")" ]
def make_empty(self: T, axes=None) -> T: """Return an empty ArrayManager with the items axis of len 0 (no columns)""" if axes is None: axes = [self.axes[1:], Index([])] arrays: list[np.ndarray | ExtensionArray] = [] return type(self)(arrays, axes)
[ "def", "make_empty", "(", "self", ":", "T", ",", "axes", "=", "None", ")", "->", "T", ":", "if", "axes", "is", "None", ":", "axes", "=", "[", "self", ".", "axes", "[", "1", ":", "]", ",", "Index", "(", "[", "]", ")", "]", "arrays", ":", "list", "[", "np", ".", "ndarray", "|", "ExtensionArray", "]", "=", "[", "]", "return", "type", "(", "self", ")", "(", "arrays", ",", "axes", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/internals/array_manager.py#L133-L139
pristineio/webrtc-mirror
7a5bcdffaab90a05bc1146b2b1ea71c004e54d71
tools_webrtc/valgrind/gdb_helper.py
python
AddressTable.ResolveAll
(self)
Carry out all lookup requests.
Carry out all lookup requests.
[ "Carry", "out", "all", "lookup", "requests", "." ]
def ResolveAll(self): ''' Carry out all lookup requests. ''' self._translation = {} for binary in self._binaries.keys(): if binary != '' and binary in self._load_addresses: load_address = self._load_addresses[binary] addr = ResolveAddressesWithinABinary( binary, load_address, self._binaries[binary]) self._translation[binary] = addr self._all_resolved = True
[ "def", "ResolveAll", "(", "self", ")", ":", "self", ".", "_translation", "=", "{", "}", "for", "binary", "in", "self", ".", "_binaries", ".", "keys", "(", ")", ":", "if", "binary", "!=", "''", "and", "binary", "in", "self", ".", "_load_addresses", ":", "load_address", "=", "self", ".", "_load_addresses", "[", "binary", "]", "addr", "=", "ResolveAddressesWithinABinary", "(", "binary", ",", "load_address", ",", "self", ".", "_binaries", "[", "binary", "]", ")", "self", ".", "_translation", "[", "binary", "]", "=", "addr", "self", ".", "_all_resolved", "=", "True" ]
https://github.com/pristineio/webrtc-mirror/blob/7a5bcdffaab90a05bc1146b2b1ea71c004e54d71/tools_webrtc/valgrind/gdb_helper.py#L72-L81
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/applications/workbench/workbench/plotting/plotscriptgenerator/legend.py
python
generate_title_font_commands
(legend, legend_object_var)
return title_commands
Generate commands for setting properties for the legend title font.
Generate commands for setting properties for the legend title font.
[ "Generate", "commands", "for", "setting", "properties", "for", "the", "legend", "title", "font", "." ]
def generate_title_font_commands(legend, legend_object_var): """ Generate commands for setting properties for the legend title font. """ title_commands = [] kwargs = LegendProperties.from_legend(legend) _remove_kwargs_if_default(kwargs) if 'title_font' in kwargs: title_commands.append(legend_object_var + ".get_title().set_fontname('" + kwargs['title_font'] + "')") if 'title_color' in kwargs: title_commands.append(legend_object_var + ".get_title().set_color('" + kwargs['title_color'] + "')") if 'title_size' in kwargs: title_commands.append(legend_object_var + ".get_title().set_fontsize('" + str(kwargs['title_size']) + "')") return title_commands
[ "def", "generate_title_font_commands", "(", "legend", ",", "legend_object_var", ")", ":", "title_commands", "=", "[", "]", "kwargs", "=", "LegendProperties", ".", "from_legend", "(", "legend", ")", "_remove_kwargs_if_default", "(", "kwargs", ")", "if", "'title_font'", "in", "kwargs", ":", "title_commands", ".", "append", "(", "legend_object_var", "+", "\".get_title().set_fontname('\"", "+", "kwargs", "[", "'title_font'", "]", "+", "\"')\"", ")", "if", "'title_color'", "in", "kwargs", ":", "title_commands", ".", "append", "(", "legend_object_var", "+", "\".get_title().set_color('\"", "+", "kwargs", "[", "'title_color'", "]", "+", "\"')\"", ")", "if", "'title_size'", "in", "kwargs", ":", "title_commands", ".", "append", "(", "legend_object_var", "+", "\".get_title().set_fontsize('\"", "+", "str", "(", "kwargs", "[", "'title_size'", "]", ")", "+", "\"')\"", ")", "return", "title_commands" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/applications/workbench/workbench/plotting/plotscriptgenerator/legend.py#L70-L85
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
python/artm/score_tracker.py
python
SparsityPhiScoreTracker.__init__
(self, score)
:Properties: * Note: every field is a list of info about score on all synchronizations. * value - values of Phi sparsity. * zero_tokens - number of zero rows in Phi. * total_tokens - number of all rows in Phi. * Note: every field has a version with prefix 'last_', means retrieving only\ info about the last synchronization.
:Properties: * Note: every field is a list of info about score on all synchronizations. * value - values of Phi sparsity. * zero_tokens - number of zero rows in Phi. * total_tokens - number of all rows in Phi. * Note: every field has a version with prefix 'last_', means retrieving only\ info about the last synchronization.
[ ":", "Properties", ":", "*", "Note", ":", "every", "field", "is", "a", "list", "of", "info", "about", "score", "on", "all", "synchronizations", ".", "*", "value", "-", "values", "of", "Phi", "sparsity", ".", "*", "zero_tokens", "-", "number", "of", "zero", "rows", "in", "Phi", ".", "*", "total_tokens", "-", "number", "of", "all", "rows", "in", "Phi", ".", "*", "Note", ":", "every", "field", "has", "a", "version", "with", "prefix", "last_", "means", "retrieving", "only", "\\", "info", "about", "the", "last", "synchronization", "." ]
def __init__(self, score): """ :Properties: * Note: every field is a list of info about score on all synchronizations. * value - values of Phi sparsity. * zero_tokens - number of zero rows in Phi. * total_tokens - number of all rows in Phi. * Note: every field has a version with prefix 'last_', means retrieving only\ info about the last synchronization. """ BaseScoreTracker.__init__(self, score)
[ "def", "__init__", "(", "self", ",", "score", ")", ":", "BaseScoreTracker", ".", "__init__", "(", "self", ",", "score", ")" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/python/artm/score_tracker.py#L101-L111
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
scripts/cpp_lint.py
python
FilesBelongToSameModule
(filename_cc, filename_h)
return files_belong_to_same_module, common_path
Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the .cc file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file.
Check if these two filenames belong to the same module.
[ "Check", "if", "these", "two", "filenames", "belong", "to", "the", "same", "module", "." ]
def FilesBelongToSameModule(filename_cc, filename_h): """Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the .cc file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file. """ if not filename_cc.endswith('.cc'): return (False, '') filename_cc = filename_cc[:-len('.cc')] if filename_cc.endswith('_unittest'): filename_cc = filename_cc[:-len('_unittest')] elif filename_cc.endswith('_test'): filename_cc = filename_cc[:-len('_test')] filename_cc = filename_cc.replace('/public/', '/') filename_cc = filename_cc.replace('/internal/', '/') if not filename_h.endswith('.h'): return (False, '') filename_h = filename_h[:-len('.h')] if filename_h.endswith('-inl'): filename_h = filename_h[:-len('-inl')] filename_h = filename_h.replace('/public/', '/') filename_h = filename_h.replace('/internal/', '/') files_belong_to_same_module = filename_cc.endswith(filename_h) common_path = '' if files_belong_to_same_module: common_path = filename_cc[:-len(filename_h)] return files_belong_to_same_module, common_path
[ "def", "FilesBelongToSameModule", "(", "filename_cc", ",", "filename_h", ")", ":", "if", "not", "filename_cc", ".", "endswith", "(", "'.cc'", ")", ":", "return", "(", "False", ",", "''", ")", "filename_cc", "=", "filename_cc", "[", ":", "-", "len", "(", "'.cc'", ")", "]", "if", "filename_cc", ".", "endswith", "(", "'_unittest'", ")", ":", "filename_cc", "=", "filename_cc", "[", ":", "-", "len", "(", "'_unittest'", ")", "]", "elif", "filename_cc", ".", "endswith", "(", "'_test'", ")", ":", "filename_cc", "=", "filename_cc", "[", ":", "-", "len", "(", "'_test'", ")", "]", "filename_cc", "=", "filename_cc", ".", "replace", "(", "'/public/'", ",", "'/'", ")", "filename_cc", "=", "filename_cc", ".", "replace", "(", "'/internal/'", ",", "'/'", ")", "if", "not", "filename_h", ".", "endswith", "(", "'.h'", ")", ":", "return", "(", "False", ",", "''", ")", "filename_h", "=", "filename_h", "[", ":", "-", "len", "(", "'.h'", ")", "]", "if", "filename_h", ".", "endswith", "(", "'-inl'", ")", ":", "filename_h", "=", "filename_h", "[", ":", "-", "len", "(", "'-inl'", ")", "]", "filename_h", "=", "filename_h", ".", "replace", "(", "'/public/'", ",", "'/'", ")", "filename_h", "=", "filename_h", ".", "replace", "(", "'/internal/'", ",", "'/'", ")", "files_belong_to_same_module", "=", "filename_cc", ".", "endswith", "(", "filename_h", ")", "common_path", "=", "''", "if", "files_belong_to_same_module", ":", "common_path", "=", "filename_cc", "[", ":", "-", "len", "(", "filename_h", ")", "]", "return", "files_belong_to_same_module", ",", "common_path" ]
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/scripts/cpp_lint.py#L4403-L4455
trailofbits/sienna-locomotive
09bc1a0bea7d7a33089422c62e0d3c715ecb7ce0
sl2/harness/instrument.py
python
kill
()
Ends a sequence of fuzzing runs.
Ends a sequence of fuzzing runs.
[ "Ends", "a", "sequence", "of", "fuzzing", "runs", "." ]
def kill(): """ Ends a sequence of fuzzing runs. """ global can_fuzz can_fuzz = False
[ "def", "kill", "(", ")", ":", "global", "can_fuzz", "can_fuzz", "=", "False" ]
https://github.com/trailofbits/sienna-locomotive/blob/09bc1a0bea7d7a33089422c62e0d3c715ecb7ce0/sl2/harness/instrument.py#L470-L475
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/aui.py
python
AuiManager.DetachPane
(*args, **kwargs)
return _aui.AuiManager_DetachPane(*args, **kwargs)
DetachPane(self, Window window) -> bool
DetachPane(self, Window window) -> bool
[ "DetachPane", "(", "self", "Window", "window", ")", "-", ">", "bool" ]
def DetachPane(*args, **kwargs): """DetachPane(self, Window window) -> bool""" return _aui.AuiManager_DetachPane(*args, **kwargs)
[ "def", "DetachPane", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiManager_DetachPane", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L655-L657
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
grc/core/utils/extract_docs.py
python
docstring_from_make
(key, imports, make)
return doc_strings
Extract the documentation from the python __doc__ strings By importing it and checking a truncated make Args: key: the block key imports: a list of import statements (string) to execute make: block constructor template Returns: a list of tuples (block_name, doc string)
Extract the documentation from the python __doc__ strings By importing it and checking a truncated make
[ "Extract", "the", "documentation", "from", "the", "python", "__doc__", "strings", "By", "importing", "it", "and", "checking", "a", "truncated", "make" ]
def docstring_from_make(key, imports, make): """ Extract the documentation from the python __doc__ strings By importing it and checking a truncated make Args: key: the block key imports: a list of import statements (string) to execute make: block constructor template Returns: a list of tuples (block_name, doc string) """ try: blk_cls = make.partition('(')[0].strip() if '$' in blk_cls: raise ValueError('Not an identifier') ns = dict() exec(imports.strip(), ns) blk = eval(blk_cls, ns) doc_strings = {key: blk.__doc__} except (ImportError, AttributeError, SyntaxError, ValueError): doc_strings = docstring_guess_from_key(key) return doc_strings
[ "def", "docstring_from_make", "(", "key", ",", "imports", ",", "make", ")", ":", "try", ":", "blk_cls", "=", "make", ".", "partition", "(", "'('", ")", "[", "0", "]", ".", "strip", "(", ")", "if", "'$'", "in", "blk_cls", ":", "raise", "ValueError", "(", "'Not an identifier'", ")", "ns", "=", "dict", "(", ")", "exec", "(", "imports", ".", "strip", "(", ")", ",", "ns", ")", "blk", "=", "eval", "(", "blk_cls", ",", "ns", ")", "doc_strings", "=", "{", "key", ":", "blk", ".", "__doc__", "}", "except", "(", "ImportError", ",", "AttributeError", ",", "SyntaxError", ",", "ValueError", ")", ":", "doc_strings", "=", "docstring_guess_from_key", "(", "key", ")", "return", "doc_strings" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/utils/extract_docs.py#L69-L95
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/gyp/copy_ex.py
python
DoRenaming
(options, deps)
Copy and rename files given in options.renaming_sources and update deps.
Copy and rename files given in options.renaming_sources and update deps.
[ "Copy", "and", "rename", "files", "given", "in", "options", ".", "renaming_sources", "and", "update", "deps", "." ]
def DoRenaming(options, deps): """Copy and rename files given in options.renaming_sources and update deps.""" src_files = list(itertools.chain.from_iterable( build_utils.ParseGnList(f) for f in options.renaming_sources)) dest_files = list(itertools.chain.from_iterable( build_utils.ParseGnList(f) for f in options.renaming_destinations)) if (len(src_files) != len(dest_files)): print('Renaming source and destination files not match.') sys.exit(-1) for src, dest in zip(src_files, dest_files): if os.path.isdir(src): print('renaming diretory is not supported.') sys.exit(-1) else: CopyFile(src, os.path.join(options.dest, dest), deps)
[ "def", "DoRenaming", "(", "options", ",", "deps", ")", ":", "src_files", "=", "list", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "build_utils", ".", "ParseGnList", "(", "f", ")", "for", "f", "in", "options", ".", "renaming_sources", ")", ")", "dest_files", "=", "list", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "build_utils", ".", "ParseGnList", "(", "f", ")", "for", "f", "in", "options", ".", "renaming_destinations", ")", ")", "if", "(", "len", "(", "src_files", ")", "!=", "len", "(", "dest_files", ")", ")", ":", "print", "(", "'Renaming source and destination files not match.'", ")", "sys", ".", "exit", "(", "-", "1", ")", "for", "src", ",", "dest", "in", "zip", "(", "src_files", ",", "dest_files", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "src", ")", ":", "print", "(", "'renaming diretory is not supported.'", ")", "sys", ".", "exit", "(", "-", "1", ")", "else", ":", "CopyFile", "(", "src", ",", "os", ".", "path", ".", "join", "(", "options", ".", "dest", ",", "dest", ")", ",", "deps", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/copy_ex.py#L63-L82
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/remote.py
python
RequestState.__init__
(self, remote_host=None, remote_address=None, server_host=None, server_port=None)
Constructor. Args: remote_host: Assigned to property. remote_address: Assigned to property. server_host: Assigned to property. server_port: Assigned to property.
Constructor.
[ "Constructor", "." ]
def __init__(self, remote_host=None, remote_address=None, server_host=None, server_port=None): """Constructor. Args: remote_host: Assigned to property. remote_address: Assigned to property. server_host: Assigned to property. server_port: Assigned to property. """ self.__remote_host = remote_host self.__remote_address = remote_address self.__server_host = server_host self.__server_port = server_port
[ "def", "__init__", "(", "self", ",", "remote_host", "=", "None", ",", "remote_address", "=", "None", ",", "server_host", "=", "None", ",", "server_port", "=", "None", ")", ":", "self", ".", "__remote_host", "=", "remote_host", "self", ".", "__remote_address", "=", "remote_address", "self", ".", "__server_host", "=", "server_host", "self", ".", "__server_port", "=", "server_port" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/remote.py#L717-L733
Tarsnap/tarsnap-gui
60a1d7816747ac71a4573673df8ee1b81ef1cb99
util/generate_loading_gif.py
python
draw_frame
(framenum)
return image
Draw a frame of the animation.
Draw a frame of the animation.
[ "Draw", "a", "frame", "of", "the", "animation", "." ]
def draw_frame(framenum): """ Draw a frame of the animation. """ # Create new image and drawing surface. image = PIL.Image.new('LA', (SIZE, SIZE), (1, 255)) draw = PIL.ImageDraw.Draw(image) # Draw the dots. for i in range(VISUAL_DOTS): pos = ((framenum - i) % TOTAL_DOTS) # The Qt background is (239,239,239) so this fades from 0 # to 240 (but stops at 180). gray = round(240/4*i) draw_dot(draw, pos, (gray, 0)) return image
[ "def", "draw_frame", "(", "framenum", ")", ":", "# Create new image and drawing surface.", "image", "=", "PIL", ".", "Image", ".", "new", "(", "'LA'", ",", "(", "SIZE", ",", "SIZE", ")", ",", "(", "1", ",", "255", ")", ")", "draw", "=", "PIL", ".", "ImageDraw", ".", "Draw", "(", "image", ")", "# Draw the dots.", "for", "i", "in", "range", "(", "VISUAL_DOTS", ")", ":", "pos", "=", "(", "(", "framenum", "-", "i", ")", "%", "TOTAL_DOTS", ")", "# The Qt background is (239,239,239) so this fades from 0", "# to 240 (but stops at 180).", "gray", "=", "round", "(", "240", "/", "4", "*", "i", ")", "draw_dot", "(", "draw", ",", "pos", ",", "(", "gray", ",", "0", ")", ")", "return", "image" ]
https://github.com/Tarsnap/tarsnap-gui/blob/60a1d7816747ac71a4573673df8ee1b81ef1cb99/util/generate_loading_gif.py#L39-L54
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Modules/Scripted/DICOMPlugins/DICOMImageSequencePlugin.py
python
DICOMImageSequencePluginClass.examineFiles
(self,files)
return loadables
Returns a list of DICOMLoadable instances corresponding to ways of interpreting the files parameter.
Returns a list of DICOMLoadable instances corresponding to ways of interpreting the files parameter.
[ "Returns", "a", "list", "of", "DICOMLoadable", "instances", "corresponding", "to", "ways", "of", "interpreting", "the", "files", "parameter", "." ]
def examineFiles(self,files): """ Returns a list of DICOMLoadable instances corresponding to ways of interpreting the files parameter. """ self.detailedLogging = slicer.util.settingsValue('DICOM/detailedLogging', False, converter=slicer.util.toBool) supportedSOPClassUIDs = [ '1.2.840.10008.5.1.4.1.1.12.1', # X-Ray Angiographic Image Storage '1.2.840.10008.5.1.4.1.1.12.2', # X-Ray Fluoroscopy Image Storage '1.2.840.10008.5.1.4.1.1.3.1', # Ultrasound Multiframe Image Storage '1.2.840.10008.5.1.4.1.1.6.1', # Ultrasound Image Storage '1.2.840.10008.5.1.4.1.1.7', # Secondary Capture Image Storage (only accepted for modalities that typically acquire 2D image sequences) '1.2.840.10008.5.1.4.1.1.4', # MR Image Storage (will be only accepted if cine-MRI) ] # Modalities that typically acquire 2D image sequences: suppportedSecondaryCaptureModalities = ['US', 'XA', 'RF', 'ES'] # Each instance will be a loadable, that will result in one sequence browser node # and usually one sequence (except simultaneous biplane acquisition, which will # result in two sequences). # Each pedal press on the XA/RF acquisition device creates a new instance number, # but if the device has two imaging planes (biplane) then two sequences # will be acquired, which have the same instance number. These two sequences # are synchronized in time, therefore they have to be assigned to the same # browser node. instanceNumberToLoadableIndex = {} loadables = [] canBeCineMri = True cineMriTriggerTimes = set() cineMriImageOrientations = set() cineMriInstanceNumberToFilenameIndex = {} for filePath in files: # Quick check of SOP class UID without parsing the file... try: sopClassUID = slicer.dicomDatabase.fileValue(filePath, self.tags['sopClassUID']) if not (sopClassUID in supportedSOPClassUIDs): # Unsupported class continue # Only accept MRI if it looks like cine-MRI if sopClassUID != '1.2.840.10008.5.1.4.1.1.4': # MR Image Storage (will be only accepted if cine-MRI) canBeCineMri = False if not canBeCineMri and sopClassUID == '1.2.840.10008.5.1.4.1.1.4': # MR Image Storage continue except Exception as e: # Quick check could not be completed (probably Slicer DICOM database is not initialized). # No problem, we'll try to parse the file and check the SOP class UID then. pass instanceNumber = slicer.dicomDatabase.fileValue(filePath, self.tags['instanceNumber']) if canBeCineMri and sopClassUID == '1.2.840.10008.5.1.4.1.1.4': # MR Image Storage if not instanceNumber: # no instance number, probably not cine-MRI canBeCineMri = False if self.detailedLogging: logging.debug("No instance number attribute found, the series will not be considered as a cine MRI") continue cineMriInstanceNumberToFilenameIndex[int(instanceNumber)] = filePath cineMriTriggerTimes.add(slicer.dicomDatabase.fileValue(filePath, self.tags['triggerTime'])) cineMriImageOrientations.add(slicer.dicomDatabase.fileValue(filePath, self.tags['orientation'])) else: modality = slicer.dicomDatabase.fileValue(filePath, self.tags['modality']) if sopClassUID == '1.2.840.10008.5.1.4.1.1.7': # Secondary Capture Image Storage if modality not in suppportedSecondaryCaptureModalities: # practice of dumping secondary capture images into the same series # is only prevalent in US and XA/RF modalities continue if not (instanceNumber in instanceNumberToLoadableIndex.keys()): # new instance number seriesNumber = slicer.dicomDatabase.fileValue(filePath, self.tags['seriesNumber']) seriesDescription = slicer.dicomDatabase.fileValue(filePath, self.tags['seriesDescription']) photometricInterpretation = slicer.dicomDatabase.fileValue(filePath, self.tags['photometricInterpretation']) name = '' if seriesNumber: name = f'{seriesNumber}:' if modality: name = f'{name} {modality}' if seriesDescription: name = f'{name} {seriesDescription}' if instanceNumber: name = f'{name} [{instanceNumber}]' loadable = DICOMLoadable() loadable.singleSequence = False # put each instance in a separate sequence loadable.files = [filePath] loadable.name = name.strip() # remove leading and trailing spaces, if any loadable.warning = "Image spacing may need to be calibrated for accurate size measurements." loadable.tooltip = f"{modality} image sequence" loadable.selected = True # Confidence is slightly larger than default scalar volume plugin's (0.5) # but still leaving room for more specialized plugins. loadable.confidence = 0.7 loadable.grayscale = ('MONOCHROME' in photometricInterpretation) # Add to loadables list loadables.append(loadable) instanceNumberToLoadableIndex[instanceNumber] = len(loadables)-1 else: # existing instance number, add this file loadableIndex = instanceNumberToLoadableIndex[instanceNumber] loadables[loadableIndex].files.append(filePath) loadable.tooltip = f"{modality} image sequence ({len(loadables[loadableIndex].files)} planes)" if canBeCineMri and len(cineMriInstanceNumberToFilenameIndex) > 1: # Get description from first ds = dicom.read_file(cineMriInstanceNumberToFilenameIndex[next(iter(cineMriInstanceNumberToFilenameIndex))], stop_before_pixels=True) name = '' if hasattr(ds, 'SeriesNumber') and ds.SeriesNumber: name = f'{ds.SeriesNumber}:' if hasattr(ds, 'Modality') and ds.Modality: name = f'{name} {ds.Modality}' if hasattr(ds, 'SeriesDescription') and ds.SeriesDescription: name = f'{name} {ds.SeriesDescription}' loadable = DICOMLoadable() loadable.singleSequence = True # put all instances in a single sequence loadable.instanceNumbers = sorted(cineMriInstanceNumberToFilenameIndex) loadable.files = [cineMriInstanceNumberToFilenameIndex[instanceNumber] for instanceNumber in loadable.instanceNumbers] loadable.name = name.strip() # remove leading and trailing spaces, if any loadable.tooltip = f"{ds.Modality} image sequence" loadable.selected = True if len(cineMriTriggerTimes)>3: if self.detailedLogging: logging.debug("Several different trigger times found ("+repr(cineMriTriggerTimes)+") - assuming this series is a cine MRI") # This is likely a cardiac cine acquisition. if len(cineMriImageOrientations) > 1: if self.detailedLogging: logging.debug("Several different image orientations found ("+repr(cineMriImageOrientations)+") - assuming this series is a rotational cine MRI") # Multivolume importer sets confidence=0.9-1.0, so we need to set a bit higher confidence to be selected by default loadable.confidence = 1.05 else: if self.detailedLogging: logging.debug("All image orientations are the same ("+repr(cineMriImageOrientations)+") - probably the MultiVolume plugin should load this") # Multivolume importer sets confidence=0.9-1.0, so we need to set a bit lower confidence to allow multivolume selected by default loadable.confidence = 0.85 else: # This may be a 3D acquisition,so set lower confidence than scalar volume's default (0.5) if self.detailedLogging: logging.debug("Only one or few different trigger times found ("+repr(cineMriTriggerTimes)+") - assuming this series is not a cine MRI") loadable.confidence = 0.4 loadable.grayscale = ('MONOCHROME' in ds.PhotometricInterpretation) # Add to loadables list loadables.append(loadable) return loadables
[ "def", "examineFiles", "(", "self", ",", "files", ")", ":", "self", ".", "detailedLogging", "=", "slicer", ".", "util", ".", "settingsValue", "(", "'DICOM/detailedLogging'", ",", "False", ",", "converter", "=", "slicer", ".", "util", ".", "toBool", ")", "supportedSOPClassUIDs", "=", "[", "'1.2.840.10008.5.1.4.1.1.12.1'", ",", "# X-Ray Angiographic Image Storage", "'1.2.840.10008.5.1.4.1.1.12.2'", ",", "# X-Ray Fluoroscopy Image Storage", "'1.2.840.10008.5.1.4.1.1.3.1'", ",", "# Ultrasound Multiframe Image Storage", "'1.2.840.10008.5.1.4.1.1.6.1'", ",", "# Ultrasound Image Storage", "'1.2.840.10008.5.1.4.1.1.7'", ",", "# Secondary Capture Image Storage (only accepted for modalities that typically acquire 2D image sequences)", "'1.2.840.10008.5.1.4.1.1.4'", ",", "# MR Image Storage (will be only accepted if cine-MRI)", "]", "# Modalities that typically acquire 2D image sequences:", "suppportedSecondaryCaptureModalities", "=", "[", "'US'", ",", "'XA'", ",", "'RF'", ",", "'ES'", "]", "# Each instance will be a loadable, that will result in one sequence browser node", "# and usually one sequence (except simultaneous biplane acquisition, which will", "# result in two sequences).", "# Each pedal press on the XA/RF acquisition device creates a new instance number,", "# but if the device has two imaging planes (biplane) then two sequences", "# will be acquired, which have the same instance number. These two sequences", "# are synchronized in time, therefore they have to be assigned to the same", "# browser node.", "instanceNumberToLoadableIndex", "=", "{", "}", "loadables", "=", "[", "]", "canBeCineMri", "=", "True", "cineMriTriggerTimes", "=", "set", "(", ")", "cineMriImageOrientations", "=", "set", "(", ")", "cineMriInstanceNumberToFilenameIndex", "=", "{", "}", "for", "filePath", "in", "files", ":", "# Quick check of SOP class UID without parsing the file...", "try", ":", "sopClassUID", "=", "slicer", ".", "dicomDatabase", ".", "fileValue", "(", "filePath", ",", "self", ".", "tags", "[", "'sopClassUID'", "]", ")", "if", "not", "(", "sopClassUID", "in", "supportedSOPClassUIDs", ")", ":", "# Unsupported class", "continue", "# Only accept MRI if it looks like cine-MRI", "if", "sopClassUID", "!=", "'1.2.840.10008.5.1.4.1.1.4'", ":", "# MR Image Storage (will be only accepted if cine-MRI)", "canBeCineMri", "=", "False", "if", "not", "canBeCineMri", "and", "sopClassUID", "==", "'1.2.840.10008.5.1.4.1.1.4'", ":", "# MR Image Storage", "continue", "except", "Exception", "as", "e", ":", "# Quick check could not be completed (probably Slicer DICOM database is not initialized).", "# No problem, we'll try to parse the file and check the SOP class UID then.", "pass", "instanceNumber", "=", "slicer", ".", "dicomDatabase", ".", "fileValue", "(", "filePath", ",", "self", ".", "tags", "[", "'instanceNumber'", "]", ")", "if", "canBeCineMri", "and", "sopClassUID", "==", "'1.2.840.10008.5.1.4.1.1.4'", ":", "# MR Image Storage", "if", "not", "instanceNumber", ":", "# no instance number, probably not cine-MRI", "canBeCineMri", "=", "False", "if", "self", ".", "detailedLogging", ":", "logging", ".", "debug", "(", "\"No instance number attribute found, the series will not be considered as a cine MRI\"", ")", "continue", "cineMriInstanceNumberToFilenameIndex", "[", "int", "(", "instanceNumber", ")", "]", "=", "filePath", "cineMriTriggerTimes", ".", "add", "(", "slicer", ".", "dicomDatabase", ".", "fileValue", "(", "filePath", ",", "self", ".", "tags", "[", "'triggerTime'", "]", ")", ")", "cineMriImageOrientations", ".", "add", "(", "slicer", ".", "dicomDatabase", ".", "fileValue", "(", "filePath", ",", "self", ".", "tags", "[", "'orientation'", "]", ")", ")", "else", ":", "modality", "=", "slicer", ".", "dicomDatabase", ".", "fileValue", "(", "filePath", ",", "self", ".", "tags", "[", "'modality'", "]", ")", "if", "sopClassUID", "==", "'1.2.840.10008.5.1.4.1.1.7'", ":", "# Secondary Capture Image Storage", "if", "modality", "not", "in", "suppportedSecondaryCaptureModalities", ":", "# practice of dumping secondary capture images into the same series", "# is only prevalent in US and XA/RF modalities", "continue", "if", "not", "(", "instanceNumber", "in", "instanceNumberToLoadableIndex", ".", "keys", "(", ")", ")", ":", "# new instance number", "seriesNumber", "=", "slicer", ".", "dicomDatabase", ".", "fileValue", "(", "filePath", ",", "self", ".", "tags", "[", "'seriesNumber'", "]", ")", "seriesDescription", "=", "slicer", ".", "dicomDatabase", ".", "fileValue", "(", "filePath", ",", "self", ".", "tags", "[", "'seriesDescription'", "]", ")", "photometricInterpretation", "=", "slicer", ".", "dicomDatabase", ".", "fileValue", "(", "filePath", ",", "self", ".", "tags", "[", "'photometricInterpretation'", "]", ")", "name", "=", "''", "if", "seriesNumber", ":", "name", "=", "f'{seriesNumber}:'", "if", "modality", ":", "name", "=", "f'{name} {modality}'", "if", "seriesDescription", ":", "name", "=", "f'{name} {seriesDescription}'", "if", "instanceNumber", ":", "name", "=", "f'{name} [{instanceNumber}]'", "loadable", "=", "DICOMLoadable", "(", ")", "loadable", ".", "singleSequence", "=", "False", "# put each instance in a separate sequence", "loadable", ".", "files", "=", "[", "filePath", "]", "loadable", ".", "name", "=", "name", ".", "strip", "(", ")", "# remove leading and trailing spaces, if any", "loadable", ".", "warning", "=", "\"Image spacing may need to be calibrated for accurate size measurements.\"", "loadable", ".", "tooltip", "=", "f\"{modality} image sequence\"", "loadable", ".", "selected", "=", "True", "# Confidence is slightly larger than default scalar volume plugin's (0.5)", "# but still leaving room for more specialized plugins.", "loadable", ".", "confidence", "=", "0.7", "loadable", ".", "grayscale", "=", "(", "'MONOCHROME'", "in", "photometricInterpretation", ")", "# Add to loadables list", "loadables", ".", "append", "(", "loadable", ")", "instanceNumberToLoadableIndex", "[", "instanceNumber", "]", "=", "len", "(", "loadables", ")", "-", "1", "else", ":", "# existing instance number, add this file", "loadableIndex", "=", "instanceNumberToLoadableIndex", "[", "instanceNumber", "]", "loadables", "[", "loadableIndex", "]", ".", "files", ".", "append", "(", "filePath", ")", "loadable", ".", "tooltip", "=", "f\"{modality} image sequence ({len(loadables[loadableIndex].files)} planes)\"", "if", "canBeCineMri", "and", "len", "(", "cineMriInstanceNumberToFilenameIndex", ")", ">", "1", ":", "# Get description from first", "ds", "=", "dicom", ".", "read_file", "(", "cineMriInstanceNumberToFilenameIndex", "[", "next", "(", "iter", "(", "cineMriInstanceNumberToFilenameIndex", ")", ")", "]", ",", "stop_before_pixels", "=", "True", ")", "name", "=", "''", "if", "hasattr", "(", "ds", ",", "'SeriesNumber'", ")", "and", "ds", ".", "SeriesNumber", ":", "name", "=", "f'{ds.SeriesNumber}:'", "if", "hasattr", "(", "ds", ",", "'Modality'", ")", "and", "ds", ".", "Modality", ":", "name", "=", "f'{name} {ds.Modality}'", "if", "hasattr", "(", "ds", ",", "'SeriesDescription'", ")", "and", "ds", ".", "SeriesDescription", ":", "name", "=", "f'{name} {ds.SeriesDescription}'", "loadable", "=", "DICOMLoadable", "(", ")", "loadable", ".", "singleSequence", "=", "True", "# put all instances in a single sequence", "loadable", ".", "instanceNumbers", "=", "sorted", "(", "cineMriInstanceNumberToFilenameIndex", ")", "loadable", ".", "files", "=", "[", "cineMriInstanceNumberToFilenameIndex", "[", "instanceNumber", "]", "for", "instanceNumber", "in", "loadable", ".", "instanceNumbers", "]", "loadable", ".", "name", "=", "name", ".", "strip", "(", ")", "# remove leading and trailing spaces, if any", "loadable", ".", "tooltip", "=", "f\"{ds.Modality} image sequence\"", "loadable", ".", "selected", "=", "True", "if", "len", "(", "cineMriTriggerTimes", ")", ">", "3", ":", "if", "self", ".", "detailedLogging", ":", "logging", ".", "debug", "(", "\"Several different trigger times found (\"", "+", "repr", "(", "cineMriTriggerTimes", ")", "+", "\") - assuming this series is a cine MRI\"", ")", "# This is likely a cardiac cine acquisition.", "if", "len", "(", "cineMriImageOrientations", ")", ">", "1", ":", "if", "self", ".", "detailedLogging", ":", "logging", ".", "debug", "(", "\"Several different image orientations found (\"", "+", "repr", "(", "cineMriImageOrientations", ")", "+", "\") - assuming this series is a rotational cine MRI\"", ")", "# Multivolume importer sets confidence=0.9-1.0, so we need to set a bit higher confidence to be selected by default", "loadable", ".", "confidence", "=", "1.05", "else", ":", "if", "self", ".", "detailedLogging", ":", "logging", ".", "debug", "(", "\"All image orientations are the same (\"", "+", "repr", "(", "cineMriImageOrientations", ")", "+", "\") - probably the MultiVolume plugin should load this\"", ")", "# Multivolume importer sets confidence=0.9-1.0, so we need to set a bit lower confidence to allow multivolume selected by default", "loadable", ".", "confidence", "=", "0.85", "else", ":", "# This may be a 3D acquisition,so set lower confidence than scalar volume's default (0.5)", "if", "self", ".", "detailedLogging", ":", "logging", ".", "debug", "(", "\"Only one or few different trigger times found (\"", "+", "repr", "(", "cineMriTriggerTimes", ")", "+", "\") - assuming this series is not a cine MRI\"", ")", "loadable", ".", "confidence", "=", "0.4", "loadable", ".", "grayscale", "=", "(", "'MONOCHROME'", "in", "ds", ".", "PhotometricInterpretation", ")", "# Add to loadables list", "loadables", ".", "append", "(", "loadable", ")", "return", "loadables" ]
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Modules/Scripted/DICOMPlugins/DICOMImageSequencePlugin.py#L60-L214
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/generic.py
python
NDFrame._check_label_or_level_ambiguity
(self, key, axis: int = 0)
Check whether `key` is ambiguous. By ambiguous, we mean that it matches both a level of the input `axis` and a label of the other axis. Parameters ---------- key : str or object Label or level name. axis : int, default 0 Axis that levels are associated with (0 for index, 1 for columns). Raises ------ ValueError: `key` is ambiguous
Check whether `key` is ambiguous.
[ "Check", "whether", "key", "is", "ambiguous", "." ]
def _check_label_or_level_ambiguity(self, key, axis: int = 0) -> None: """ Check whether `key` is ambiguous. By ambiguous, we mean that it matches both a level of the input `axis` and a label of the other axis. Parameters ---------- key : str or object Label or level name. axis : int, default 0 Axis that levels are associated with (0 for index, 1 for columns). Raises ------ ValueError: `key` is ambiguous """ axis = self._get_axis_number(axis) other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis) if ( key is not None and is_hashable(key) and key in self.axes[axis].names and any(key in self.axes[ax] for ax in other_axes) ): # Build an informative and grammatical warning level_article, level_type = ( ("an", "index") if axis == 0 else ("a", "column") ) label_article, label_type = ( ("a", "column") if axis == 0 else ("an", "index") ) msg = ( f"'{key}' is both {level_article} {level_type} level and " f"{label_article} {label_type} label, which is ambiguous." ) raise ValueError(msg)
[ "def", "_check_label_or_level_ambiguity", "(", "self", ",", "key", ",", "axis", ":", "int", "=", "0", ")", "->", "None", ":", "axis", "=", "self", ".", "_get_axis_number", "(", "axis", ")", "other_axes", "=", "(", "ax", "for", "ax", "in", "range", "(", "self", ".", "_AXIS_LEN", ")", "if", "ax", "!=", "axis", ")", "if", "(", "key", "is", "not", "None", "and", "is_hashable", "(", "key", ")", "and", "key", "in", "self", ".", "axes", "[", "axis", "]", ".", "names", "and", "any", "(", "key", "in", "self", ".", "axes", "[", "ax", "]", "for", "ax", "in", "other_axes", ")", ")", ":", "# Build an informative and grammatical warning", "level_article", ",", "level_type", "=", "(", "(", "\"an\"", ",", "\"index\"", ")", "if", "axis", "==", "0", "else", "(", "\"a\"", ",", "\"column\"", ")", ")", "label_article", ",", "label_type", "=", "(", "(", "\"a\"", ",", "\"column\"", ")", "if", "axis", "==", "0", "else", "(", "\"an\"", ",", "\"index\"", ")", ")", "msg", "=", "(", "f\"'{key}' is both {level_article} {level_type} level and \"", "f\"{label_article} {label_type} label, which is ambiguous.\"", ")", "raise", "ValueError", "(", "msg", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/generic.py#L1692-L1733
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributions/distribution.py
python
Distribution.cdf
(self, value)
Returns the cumulative density/mass function evaluated at `value`. Args: value (Tensor):
Returns the cumulative density/mass function evaluated at `value`.
[ "Returns", "the", "cumulative", "density", "/", "mass", "function", "evaluated", "at", "value", "." ]
def cdf(self, value): """ Returns the cumulative density/mass function evaluated at `value`. Args: value (Tensor): """ raise NotImplementedError
[ "def", "cdf", "(", "self", ",", "value", ")", ":", "raise", "NotImplementedError" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributions/distribution.py#L172-L180
albarji/proxTV
69062fe54335976e83fe9269a09d795ae37470ba
prox_tv/__init__.py
python
tvp_2d
(x, w_col, w_row, p_col, p_row, n_threads=1, max_iters=0)
return y
r"""2D proximal operator for any :math:`\ell_p` norm. Specifically, this optimizes the following program: .. math:: \mathrm{min}_y \frac{1}{2}\|x-y\|^2 + w^r \|D_\mathrm{row}(y)\|_{p_1} + w^c \|D_\mathrm{col}(y) \|_{p_2}, where :math:`\mathrm D_{row}` and :math:`\mathrm D_{col}` take the differences accross rows and columns respectively. Parameters ---------- y : numpy array The matrix signal we are approximating. p_col : float Column norm. p_row : float Row norm. w_col : float Column penalty. w_row : float Row penalty. Returns ------- numpy array The solution of the optimization problem.
r"""2D proximal operator for any :math:`\ell_p` norm.
[ "r", "2D", "proximal", "operator", "for", "any", ":", "math", ":", "\\", "ell_p", "norm", "." ]
def tvp_2d(x, w_col, w_row, p_col, p_row, n_threads=1, max_iters=0): r"""2D proximal operator for any :math:`\ell_p` norm. Specifically, this optimizes the following program: .. math:: \mathrm{min}_y \frac{1}{2}\|x-y\|^2 + w^r \|D_\mathrm{row}(y)\|_{p_1} + w^c \|D_\mathrm{col}(y) \|_{p_2}, where :math:`\mathrm D_{row}` and :math:`\mathrm D_{col}` take the differences accross rows and columns respectively. Parameters ---------- y : numpy array The matrix signal we are approximating. p_col : float Column norm. p_row : float Row norm. w_col : float Column penalty. w_row : float Row penalty. Returns ------- numpy array The solution of the optimization problem. """ assert w_col >= 0 assert w_row >= 0 assert p_col >= 1 assert p_row >= 1 info = np.zeros(_N_INFO) x = np.asfortranarray(x, dtype='float64') w_col = force_float_scalar(w_col) w_row = force_float_scalar(w_row) p_col = force_float_scalar(p_col) p_row = force_float_scalar(p_row) y = np.zeros(np.shape(x), order='F') _call(lib.DR2_TV, x.shape[0], x.shape[1], x, w_col, w_row, p_col, p_row, y, n_threads, max_iters, info) return y
[ "def", "tvp_2d", "(", "x", ",", "w_col", ",", "w_row", ",", "p_col", ",", "p_row", ",", "n_threads", "=", "1", ",", "max_iters", "=", "0", ")", ":", "assert", "w_col", ">=", "0", "assert", "w_row", ">=", "0", "assert", "p_col", ">=", "1", "assert", "p_row", ">=", "1", "info", "=", "np", ".", "zeros", "(", "_N_INFO", ")", "x", "=", "np", ".", "asfortranarray", "(", "x", ",", "dtype", "=", "'float64'", ")", "w_col", "=", "force_float_scalar", "(", "w_col", ")", "w_row", "=", "force_float_scalar", "(", "w_row", ")", "p_col", "=", "force_float_scalar", "(", "p_col", ")", "p_row", "=", "force_float_scalar", "(", "p_row", ")", "y", "=", "np", ".", "zeros", "(", "np", ".", "shape", "(", "x", ")", ",", "order", "=", "'F'", ")", "_call", "(", "lib", ".", "DR2_TV", ",", "x", ".", "shape", "[", "0", "]", ",", "x", ".", "shape", "[", "1", "]", ",", "x", ",", "w_col", ",", "w_row", ",", "p_col", ",", "p_row", ",", "y", ",", "n_threads", ",", "max_iters", ",", "info", ")", "return", "y" ]
https://github.com/albarji/proxTV/blob/69062fe54335976e83fe9269a09d795ae37470ba/prox_tv/__init__.py#L484-L530
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/v8/third_party/jinja2/environment.py
python
_environment_sanity_check
(environment)
return environment
Perform a sanity check on the environment.
Perform a sanity check on the environment.
[ "Perform", "a", "sanity", "check", "on", "the", "environment", "." ]
def _environment_sanity_check(environment): """Perform a sanity check on the environment.""" assert issubclass(environment.undefined, Undefined), 'undefined must ' \ 'be a subclass of undefined because filters depend on it.' assert environment.block_start_string != \ environment.variable_start_string != \ environment.comment_start_string, 'block, variable and comment ' \ 'start strings must be different' assert environment.newline_sequence in ('\r', '\r\n', '\n'), \ 'newline_sequence set to unknown line ending string.' return environment
[ "def", "_environment_sanity_check", "(", "environment", ")", ":", "assert", "issubclass", "(", "environment", ".", "undefined", ",", "Undefined", ")", ",", "'undefined must '", "'be a subclass of undefined because filters depend on it.'", "assert", "environment", ".", "block_start_string", "!=", "environment", ".", "variable_start_string", "!=", "environment", ".", "comment_start_string", ",", "'block, variable and comment '", "'start strings must be different'", "assert", "environment", ".", "newline_sequence", "in", "(", "'\\r'", ",", "'\\r\\n'", ",", "'\\n'", ")", ",", "'newline_sequence set to unknown line ending string.'", "return", "environment" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/third_party/jinja2/environment.py#L100-L110
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/cygprofile/cygprofile_utils.py
python
WarningCollector.WriteEnd
(self, message)
Once all warnings have been printed, use this to print the number of elided warnings.
Once all warnings have been printed, use this to print the number of elided warnings.
[ "Once", "all", "warnings", "have", "been", "printed", "use", "this", "to", "print", "the", "number", "of", "elided", "warnings", "." ]
def WriteEnd(self, message): """Once all warnings have been printed, use this to print the number of elided warnings.""" if self._warnings > self._max_warnings: logging.log(self._level, '%d more warnings for: %s' % ( self._warnings - self._max_warnings, message))
[ "def", "WriteEnd", "(", "self", ",", "message", ")", ":", "if", "self", ".", "_warnings", ">", "self", ".", "_max_warnings", ":", "logging", ".", "log", "(", "self", ".", "_level", ",", "'%d more warnings for: %s'", "%", "(", "self", ".", "_warnings", "-", "self", ".", "_max_warnings", ",", "message", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/cygprofile/cygprofile_utils.py#L26-L31
rootm0s/Protectors
5b3f4d11687a5955caf9c3af30666c4bfc2c19ab
OWASP-ZSC/module/readline_windows/pyreadline/rlmain.py
python
BaseReadline.get_begidx
(self)
return self.mode.begidx
Get the beginning index of the readline tab-completion scope.
Get the beginning index of the readline tab-completion scope.
[ "Get", "the", "beginning", "index", "of", "the", "readline", "tab", "-", "completion", "scope", "." ]
def get_begidx(self): '''Get the beginning index of the readline tab-completion scope.''' return self.mode.begidx
[ "def", "get_begidx", "(", "self", ")", ":", "return", "self", ".", "mode", ".", "begidx" ]
https://github.com/rootm0s/Protectors/blob/5b3f4d11687a5955caf9c3af30666c4bfc2c19ab/OWASP-ZSC/module/readline_windows/pyreadline/rlmain.py#L198-L200
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/Eigen/debug/gdb/printers.py
python
EigenMatrixPrinter.__init__
(self, variety, val)
Extract all the necessary information
Extract all the necessary information
[ "Extract", "all", "the", "necessary", "information" ]
def __init__(self, variety, val): "Extract all the necessary information" # Save the variety (presumably "Matrix" or "Array") for later usage self.variety = variety # The gdb extension does not support value template arguments - need to extract them by hand type = val.type if type.code == gdb.TYPE_CODE_REF: type = type.target() self.type = type.unqualified().strip_typedefs() tag = self.type.tag regex = re.compile('\<.*\>') m = regex.findall(tag)[0][1:-1] template_params = m.split(',') template_params = [x.replace(" ", "") for x in template_params] if template_params[1] == '-0x00000000000000001' or template_params[1] == '-0x000000001' or template_params[1] == '-1': self.rows = val['m_storage']['m_rows'] else: self.rows = int(template_params[1]) if template_params[2] == '-0x00000000000000001' or template_params[2] == '-0x000000001' or template_params[2] == '-1': self.cols = val['m_storage']['m_cols'] else: self.cols = int(template_params[2]) self.options = 0 # default value if len(template_params) > 3: self.options = template_params[3]; self.rowMajor = (int(self.options) & 0x1) self.innerType = self.type.template_argument(0) self.val = val # Fixed size matrices have a struct as their storage, so we need to walk through this self.data = self.val['m_storage']['m_data'] if self.data.type.code == gdb.TYPE_CODE_STRUCT: self.data = self.data['array'] self.data = self.data.cast(self.innerType.pointer())
[ "def", "__init__", "(", "self", ",", "variety", ",", "val", ")", ":", "# Save the variety (presumably \"Matrix\" or \"Array\") for later usage", "self", ".", "variety", "=", "variety", "# The gdb extension does not support value template arguments - need to extract them by hand", "type", "=", "val", ".", "type", "if", "type", ".", "code", "==", "gdb", ".", "TYPE_CODE_REF", ":", "type", "=", "type", ".", "target", "(", ")", "self", ".", "type", "=", "type", ".", "unqualified", "(", ")", ".", "strip_typedefs", "(", ")", "tag", "=", "self", ".", "type", ".", "tag", "regex", "=", "re", ".", "compile", "(", "'\\<.*\\>'", ")", "m", "=", "regex", ".", "findall", "(", "tag", ")", "[", "0", "]", "[", "1", ":", "-", "1", "]", "template_params", "=", "m", ".", "split", "(", "','", ")", "template_params", "=", "[", "x", ".", "replace", "(", "\" \"", ",", "\"\"", ")", "for", "x", "in", "template_params", "]", "if", "template_params", "[", "1", "]", "==", "'-0x00000000000000001'", "or", "template_params", "[", "1", "]", "==", "'-0x000000001'", "or", "template_params", "[", "1", "]", "==", "'-1'", ":", "self", ".", "rows", "=", "val", "[", "'m_storage'", "]", "[", "'m_rows'", "]", "else", ":", "self", ".", "rows", "=", "int", "(", "template_params", "[", "1", "]", ")", "if", "template_params", "[", "2", "]", "==", "'-0x00000000000000001'", "or", "template_params", "[", "2", "]", "==", "'-0x000000001'", "or", "template_params", "[", "2", "]", "==", "'-1'", ":", "self", ".", "cols", "=", "val", "[", "'m_storage'", "]", "[", "'m_cols'", "]", "else", ":", "self", ".", "cols", "=", "int", "(", "template_params", "[", "2", "]", ")", "self", ".", "options", "=", "0", "# default value", "if", "len", "(", "template_params", ")", ">", "3", ":", "self", ".", "options", "=", "template_params", "[", "3", "]", "self", ".", "rowMajor", "=", "(", "int", "(", "self", ".", "options", ")", "&", "0x1", ")", "self", ".", "innerType", "=", "self", ".", "type", ".", "template_argument", "(", "0", ")", "self", ".", "val", "=", "val", "# Fixed size matrices have a struct as their storage, so we need to walk through this", "self", ".", "data", "=", "self", ".", "val", "[", "'m_storage'", "]", "[", "'m_data'", "]", "if", "self", ".", "data", ".", "type", ".", "code", "==", "gdb", ".", "TYPE_CODE_STRUCT", ":", "self", ".", "data", "=", "self", ".", "data", "[", "'array'", "]", "self", ".", "data", "=", "self", ".", "data", ".", "cast", "(", "self", ".", "innerType", ".", "pointer", "(", ")", ")" ]
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/algorithms/src/LocalizationAndMapping/registration_localization/fast_gicp/thirdparty/Eigen/debug/gdb/printers.py#L74-L115
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py
python
_sqrt_nearest
(n, a)
return a
Closest integer to the square root of the positive integer n. a is an initial approximation to the square root. Any positive integer will do for a, but the closer a is to the square root of n the faster convergence will be.
Closest integer to the square root of the positive integer n. a is an initial approximation to the square root. Any positive integer will do for a, but the closer a is to the square root of n the faster convergence will be.
[ "Closest", "integer", "to", "the", "square", "root", "of", "the", "positive", "integer", "n", ".", "a", "is", "an", "initial", "approximation", "to", "the", "square", "root", ".", "Any", "positive", "integer", "will", "do", "for", "a", "but", "the", "closer", "a", "is", "to", "the", "square", "root", "of", "n", "the", "faster", "convergence", "will", "be", "." ]
def _sqrt_nearest(n, a): """Closest integer to the square root of the positive integer n. a is an initial approximation to the square root. Any positive integer will do for a, but the closer a is to the square root of n the faster convergence will be. """ if n <= 0 or a <= 0: raise ValueError("Both arguments to _sqrt_nearest should be positive.") b=0 while a != b: b, a = a, a--n//a>>1 return a
[ "def", "_sqrt_nearest", "(", "n", ",", "a", ")", ":", "if", "n", "<=", "0", "or", "a", "<=", "0", ":", "raise", "ValueError", "(", "\"Both arguments to _sqrt_nearest should be positive.\"", ")", "b", "=", "0", "while", "a", "!=", "b", ":", "b", ",", "a", "=", "a", ",", "a", "-", "-", "n", "//", "a", ">>", "1", "return", "a" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py#L5695-L5708
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/ConfigSet.py
python
ConfigSet.get_merged_dict
(self)
return merged_table
Computes the merged dictionary from the fusion of self and all its parent :rtype: a ConfigSet object
Computes the merged dictionary from the fusion of self and all its parent
[ "Computes", "the", "merged", "dictionary", "from", "the", "fusion", "of", "self", "and", "all", "its", "parent" ]
def get_merged_dict(self): """ Computes the merged dictionary from the fusion of self and all its parent :rtype: a ConfigSet object """ table_list = [] env = self while 1: table_list.insert(0, env.table) try: env = env.parent except AttributeError: break merged_table = {} for table in table_list: merged_table.update(table) return merged_table
[ "def", "get_merged_dict", "(", "self", ")", ":", "table_list", "=", "[", "]", "env", "=", "self", "while", "1", ":", "table_list", ".", "insert", "(", "0", ",", "env", ".", "table", ")", "try", ":", "env", "=", "env", ".", "parent", "except", "AttributeError", ":", "break", "merged_table", "=", "{", "}", "for", "table", "in", "table_list", ":", "merged_table", ".", "update", "(", "table", ")", "return", "merged_table" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/ConfigSet.py#L261-L278
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/pubsub/core/kwargs/topicmgrimpl.py
python
getRootTopicSpec
()
return argsDocs, reqdArgs
If using kwargs protocol, then root topic takes no args.
If using kwargs protocol, then root topic takes no args.
[ "If", "using", "kwargs", "protocol", "then", "root", "topic", "takes", "no", "args", "." ]
def getRootTopicSpec(): """If using kwargs protocol, then root topic takes no args.""" argsDocs = {} reqdArgs = () return argsDocs, reqdArgs
[ "def", "getRootTopicSpec", "(", ")", ":", "argsDocs", "=", "{", "}", "reqdArgs", "=", "(", ")", "return", "argsDocs", ",", "reqdArgs" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pubsub/core/kwargs/topicmgrimpl.py#L8-L12
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/generator/msvs.py
python
_FixPaths
(paths)
return [_FixPath(i) for i in paths]
Fix each of the paths of the list.
Fix each of the paths of the list.
[ "Fix", "each", "of", "the", "paths", "of", "the", "list", "." ]
def _FixPaths(paths): """Fix each of the paths of the list.""" return [_FixPath(i) for i in paths]
[ "def", "_FixPaths", "(", "paths", ")", ":", "return", "[", "_FixPath", "(", "i", ")", "for", "i", "in", "paths", "]" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/generator/msvs.py#L177-L179
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
StyledTextCtrl.TextWidth
(*args, **kwargs)
return _stc.StyledTextCtrl_TextWidth(*args, **kwargs)
TextWidth(self, int style, String text) -> int Measure the pixel width of some text in a particular style. NUL terminated text argument. Does not handle tab or control characters.
TextWidth(self, int style, String text) -> int
[ "TextWidth", "(", "self", "int", "style", "String", "text", ")", "-", ">", "int" ]
def TextWidth(*args, **kwargs): """ TextWidth(self, int style, String text) -> int Measure the pixel width of some text in a particular style. NUL terminated text argument. Does not handle tab or control characters. """ return _stc.StyledTextCtrl_TextWidth(*args, **kwargs)
[ "def", "TextWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_TextWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L4199-L4207
LLNL/lbann
26083e6c86050302ce33148aea70f62e61cacb92
python/lbann/launcher/batch_script.py
python
BatchScript.write
(self, overwrite=False)
Write script to file. The working directory is created if needed. Args: overwrite (bool): Whether to overwrite script file if it already exists (default: false).
Write script to file.
[ "Write", "script", "to", "file", "." ]
def write(self, overwrite=False): """Write script to file. The working directory is created if needed. Args: overwrite (bool): Whether to overwrite script file if it already exists (default: false). """ # Create directories if needed os.makedirs(self.work_dir, exist_ok=True) os.makedirs(os.path.dirname(self.script_file), exist_ok=True) # Check if script file already exists if not overwrite and os.path.isfile(self.script_file): raise RuntimeError('Attempted to write batch script to {}, ' 'but it already exists' .format(self.script_file)) # Write script to file with open(self.script_file, 'w') as f: for line in self.header: f.write('{}\n'.format(line)) f.write('\n') for line in self.body: f.write('{}\n'.format(line)) # Make script file executable os.chmod(self.script_file, 0o755)
[ "def", "write", "(", "self", ",", "overwrite", "=", "False", ")", ":", "# Create directories if needed", "os", ".", "makedirs", "(", "self", ".", "work_dir", ",", "exist_ok", "=", "True", ")", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "self", ".", "script_file", ")", ",", "exist_ok", "=", "True", ")", "# Check if script file already exists", "if", "not", "overwrite", "and", "os", ".", "path", ".", "isfile", "(", "self", ".", "script_file", ")", ":", "raise", "RuntimeError", "(", "'Attempted to write batch script to {}, '", "'but it already exists'", ".", "format", "(", "self", ".", "script_file", ")", ")", "# Write script to file", "with", "open", "(", "self", ".", "script_file", ",", "'w'", ")", "as", "f", ":", "for", "line", "in", "self", ".", "header", ":", "f", ".", "write", "(", "'{}\\n'", ".", "format", "(", "line", ")", ")", "f", ".", "write", "(", "'\\n'", ")", "for", "line", "in", "self", ".", "body", ":", "f", ".", "write", "(", "'{}\\n'", ".", "format", "(", "line", ")", ")", "# Make script file executable", "os", ".", "chmod", "(", "self", ".", "script_file", ",", "0o755", ")" ]
https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/python/lbann/launcher/batch_script.py#L108-L138
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/sets.py
python
Set.discard
(self, element)
Remove an element from a set if it is a member. If the element is not a member, do nothing.
Remove an element from a set if it is a member.
[ "Remove", "an", "element", "from", "a", "set", "if", "it", "is", "a", "member", "." ]
def discard(self, element): """Remove an element from a set if it is a member. If the element is not a member, do nothing. """ try: self.remove(element) except KeyError: pass
[ "def", "discard", "(", "self", ",", "element", ")", ":", "try", ":", "self", ".", "remove", "(", "element", ")", "except", "KeyError", ":", "pass" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/sets.py#L525-L533
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/polynomial.py
python
polydiv
(c1, c2)
Divide one polynomial by another. Returns the quotient-with-remainder of two polynomials `c1` / `c2`. The arguments are sequences of coefficients, from lowest order term to highest, e.g., [1,2,3] represents ``1 + 2*x + 3*x**2``. Parameters ---------- c1, c2 : array_like 1-D arrays of polynomial coefficients ordered from low to high. Returns ------- [quo, rem] : ndarrays Of coefficient series representing the quotient and remainder. See Also -------- polyadd, polysub, polymul, polypow Examples -------- >>> import numpy.polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> P.polydiv(c1,c2) (array([ 3.]), array([-8., -4.])) >>> P.polydiv(c2,c1) (array([ 0.33333333]), array([ 2.66666667, 1.33333333]))
Divide one polynomial by another.
[ "Divide", "one", "polynomial", "by", "another", "." ]
def polydiv(c1, c2): """ Divide one polynomial by another. Returns the quotient-with-remainder of two polynomials `c1` / `c2`. The arguments are sequences of coefficients, from lowest order term to highest, e.g., [1,2,3] represents ``1 + 2*x + 3*x**2``. Parameters ---------- c1, c2 : array_like 1-D arrays of polynomial coefficients ordered from low to high. Returns ------- [quo, rem] : ndarrays Of coefficient series representing the quotient and remainder. See Also -------- polyadd, polysub, polymul, polypow Examples -------- >>> import numpy.polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> P.polydiv(c1,c2) (array([ 3.]), array([-8., -4.])) >>> P.polydiv(c2,c1) (array([ 0.33333333]), array([ 2.66666667, 1.33333333])) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if c2[-1] == 0 : raise ZeroDivisionError() len1 = len(c1) len2 = len(c2) if len2 == 1 : return c1/c2[-1], c1[:1]*0 elif len1 < len2 : return c1[:1]*0, c1 else : dlen = len1 - len2 scl = c2[-1] c2 = c2[:-1]/scl i = dlen j = len1 - 1 while i >= 0 : c1[i:j] -= c2*c1[j] i -= 1 j -= 1 return c1[j+1:]/scl, pu.trimseq(c1[:j+1])
[ "def", "polydiv", "(", "c1", ",", "c2", ")", ":", "# c1, c2 are trimmed copies", "[", "c1", ",", "c2", "]", "=", "pu", ".", "as_series", "(", "[", "c1", ",", "c2", "]", ")", "if", "c2", "[", "-", "1", "]", "==", "0", ":", "raise", "ZeroDivisionError", "(", ")", "len1", "=", "len", "(", "c1", ")", "len2", "=", "len", "(", "c2", ")", "if", "len2", "==", "1", ":", "return", "c1", "/", "c2", "[", "-", "1", "]", ",", "c1", "[", ":", "1", "]", "*", "0", "elif", "len1", "<", "len2", ":", "return", "c1", "[", ":", "1", "]", "*", "0", ",", "c1", "else", ":", "dlen", "=", "len1", "-", "len2", "scl", "=", "c2", "[", "-", "1", "]", "c2", "=", "c2", "[", ":", "-", "1", "]", "/", "scl", "i", "=", "dlen", "j", "=", "len1", "-", "1", "while", "i", ">=", "0", ":", "c1", "[", "i", ":", "j", "]", "-=", "c2", "*", "c1", "[", "j", "]", "i", "-=", "1", "j", "-=", "1", "return", "c1", "[", "j", "+", "1", ":", "]", "/", "scl", ",", "pu", ".", "trimseq", "(", "c1", "[", ":", "j", "+", "1", "]", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/polynomial.py#L367-L421
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/msgpack/__init__.py
python
pack
(o, stream, **kwargs)
Pack object `o` and write it to `stream` See :class:`Packer` for options.
Pack object `o` and write it to `stream`
[ "Pack", "object", "o", "and", "write", "it", "to", "stream" ]
def pack(o, stream, **kwargs): """ Pack object `o` and write it to `stream` See :class:`Packer` for options. """ packer = Packer(**kwargs) stream.write(packer.pack(o))
[ "def", "pack", "(", "o", ",", "stream", ",", "*", "*", "kwargs", ")", ":", "packer", "=", "Packer", "(", "*", "*", "kwargs", ")", "stream", ".", "write", "(", "packer", ".", "pack", "(", "o", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/msgpack/__init__.py#L19-L26
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/osx_cocoa/gizmos.py
python
DynamicSashWindow.GetVScrollBar
(*args, **kwargs)
return _gizmos.DynamicSashWindow_GetVScrollBar(*args, **kwargs)
GetVScrollBar(self, Window child) -> ScrollBar
GetVScrollBar(self, Window child) -> ScrollBar
[ "GetVScrollBar", "(", "self", "Window", "child", ")", "-", ">", "ScrollBar" ]
def GetVScrollBar(*args, **kwargs): """GetVScrollBar(self, Window child) -> ScrollBar""" return _gizmos.DynamicSashWindow_GetVScrollBar(*args, **kwargs)
[ "def", "GetVScrollBar", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gizmos", ".", "DynamicSashWindow_GetVScrollBar", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_cocoa/gizmos.py#L115-L117
ArduPilot/ardupilot
6e684b3496122b8158ac412b609d00004b7ac306
Tools/scripts/apj_tool.py
python
embedded_defaults.find
(self)
find defaults in firmware
find defaults in firmware
[ "find", "defaults", "in", "firmware" ]
def find(self): '''find defaults in firmware''' # these are the magic headers from AP_Param.cpp magic_str = "PARMDEF".encode('ascii') param_magic = [ 0x55, 0x37, 0xf4, 0xa0, 0x38, 0x5d, 0x48, 0x5b ] def u_ord(c): return ord(c) if sys.version_info.major < 3 else c while True: i = self.firmware[self.offset:].find(magic_str) if i == -1: print("No param area found") return None matched = True for j in range(len(param_magic)): if u_ord(self.firmware[self.offset+i+j+8]) != param_magic[j]: matched = False break if not matched: self.offset += i+8 continue self.offset += i self.max_len, self.length = struct.unpack("<HH", self.firmware[self.offset+16:self.offset+20]) return True
[ "def", "find", "(", "self", ")", ":", "# these are the magic headers from AP_Param.cpp", "magic_str", "=", "\"PARMDEF\"", ".", "encode", "(", "'ascii'", ")", "param_magic", "=", "[", "0x55", ",", "0x37", ",", "0xf4", ",", "0xa0", ",", "0x38", ",", "0x5d", ",", "0x48", ",", "0x5b", "]", "def", "u_ord", "(", "c", ")", ":", "return", "ord", "(", "c", ")", "if", "sys", ".", "version_info", ".", "major", "<", "3", "else", "c", "while", "True", ":", "i", "=", "self", ".", "firmware", "[", "self", ".", "offset", ":", "]", ".", "find", "(", "magic_str", ")", "if", "i", "==", "-", "1", ":", "print", "(", "\"No param area found\"", ")", "return", "None", "matched", "=", "True", "for", "j", "in", "range", "(", "len", "(", "param_magic", ")", ")", ":", "if", "u_ord", "(", "self", ".", "firmware", "[", "self", ".", "offset", "+", "i", "+", "j", "+", "8", "]", ")", "!=", "param_magic", "[", "j", "]", ":", "matched", "=", "False", "break", "if", "not", "matched", ":", "self", ".", "offset", "+=", "i", "+", "8", "continue", "self", ".", "offset", "+=", "i", "self", ".", "max_len", ",", "self", ".", "length", "=", "struct", ".", "unpack", "(", "\"<HH\"", ",", "self", ".", "firmware", "[", "self", ".", "offset", "+", "16", ":", "self", ".", "offset", "+", "20", "]", ")", "return", "True" ]
https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/Tools/scripts/apj_tool.py#L105-L128
bakwc/JamSpell
ab5ade201df3e52d99c3a1d38ec422cf4ded1795
evaluate/context_spell_prototype.py
python
edits2
(word)
return (e2 for e1 in edits1(word) for e2 in edits1(e1))
All edits that are two edits away from `word`.
All edits that are two edits away from `word`.
[ "All", "edits", "that", "are", "two", "edits", "away", "from", "word", "." ]
def edits2(word): "All edits that are two edits away from `word`." return (e2 for e1 in edits1(word) for e2 in edits1(e1))
[ "def", "edits2", "(", "word", ")", ":", "return", "(", "e2", "for", "e1", "in", "edits1", "(", "word", ")", "for", "e2", "in", "edits1", "(", "e1", ")", ")" ]
https://github.com/bakwc/JamSpell/blob/ab5ade201df3e52d99c3a1d38ec422cf4ded1795/evaluate/context_spell_prototype.py#L64-L66
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/programs/scripts/internetcontent/nv_python_libs/common/common_api.py
python
Common.initializeMythDB
(self)
Import the MythTV database bindings return nothing
Import the MythTV database bindings return nothing
[ "Import", "the", "MythTV", "database", "bindings", "return", "nothing" ]
def initializeMythDB(self): ''' Import the MythTV database bindings return nothing ''' try: from MythTV import MythDB, MythLog, MythError try: '''Create an instance of each: MythDB ''' MythLog._setlevel('none') # Some non option -M cannot have any logging on stdout self.mythdb = MythDB() except MythError as e: sys.stderr.write('\n! Error - %s\n' % e.args[0]) filename = os.path.expanduser("~")+'/.mythtv/config.xml' if not os.path.isfile(filename): sys.stderr.write('\n! Error - A correctly configured (%s) file must exist\n' % filename) else: sys.stderr.write('\n! Error - Check that (%s) is correctly configured\n' % filename) sys.exit(1) except Exception as e: sys.stderr.write("\n! Error - Creating an instance caused an error for one of: MythDB. error(%s)\n" % e) sys.exit(1) except Exception as e: sys.stderr.write("\n! Error - MythTV python bindings could not be imported. error(%s)\n" % e) sys.exit(1)
[ "def", "initializeMythDB", "(", "self", ")", ":", "try", ":", "from", "MythTV", "import", "MythDB", ",", "MythLog", ",", "MythError", "try", ":", "'''Create an instance of each: MythDB\n '''", "MythLog", ".", "_setlevel", "(", "'none'", ")", "# Some non option -M cannot have any logging on stdout", "self", ".", "mythdb", "=", "MythDB", "(", ")", "except", "MythError", "as", "e", ":", "sys", ".", "stderr", ".", "write", "(", "'\\n! Error - %s\\n'", "%", "e", ".", "args", "[", "0", "]", ")", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", "+", "'/.mythtv/config.xml'", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'\\n! Error - A correctly configured (%s) file must exist\\n'", "%", "filename", ")", "else", ":", "sys", ".", "stderr", ".", "write", "(", "'\\n! Error - Check that (%s) is correctly configured\\n'", "%", "filename", ")", "sys", ".", "exit", "(", "1", ")", "except", "Exception", "as", "e", ":", "sys", ".", "stderr", ".", "write", "(", "\"\\n! Error - Creating an instance caused an error for one of: MythDB. error(%s)\\n\"", "%", "e", ")", "sys", ".", "exit", "(", "1", ")", "except", "Exception", "as", "e", ":", "sys", ".", "stderr", ".", "write", "(", "\"\\n! Error - MythTV python bindings could not be imported. error(%s)\\n\"", "%", "e", ")", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/common/common_api.py#L925-L949
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/sandbox.py
python
override_temp
(replacement)
Monkey-patch tempfile.tempdir with replacement, ensuring it exists
Monkey-patch tempfile.tempdir with replacement, ensuring it exists
[ "Monkey", "-", "patch", "tempfile", ".", "tempdir", "with", "replacement", "ensuring", "it", "exists" ]
def override_temp(replacement): """ Monkey-patch tempfile.tempdir with replacement, ensuring it exists """ os.makedirs(replacement, exist_ok=True) saved = tempfile.tempdir tempfile.tempdir = replacement try: yield finally: tempfile.tempdir = saved
[ "def", "override_temp", "(", "replacement", ")", ":", "os", ".", "makedirs", "(", "replacement", ",", "exist_ok", "=", "True", ")", "saved", "=", "tempfile", ".", "tempdir", "tempfile", ".", "tempdir", "=", "replacement", "try", ":", "yield", "finally", ":", "tempfile", ".", "tempdir", "=", "saved" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/sandbox.py#L70-L83
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/osx_cocoa/gizmos.py
python
TreeListCtrl.GetFirstExpandedItem
(*args, **kwargs)
return _gizmos.TreeListCtrl_GetFirstExpandedItem(*args, **kwargs)
GetFirstExpandedItem(self) -> TreeItemId
GetFirstExpandedItem(self) -> TreeItemId
[ "GetFirstExpandedItem", "(", "self", ")", "-", ">", "TreeItemId" ]
def GetFirstExpandedItem(*args, **kwargs): """GetFirstExpandedItem(self) -> TreeItemId""" return _gizmos.TreeListCtrl_GetFirstExpandedItem(*args, **kwargs)
[ "def", "GetFirstExpandedItem", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gizmos", ".", "TreeListCtrl_GetFirstExpandedItem", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_cocoa/gizmos.py#L802-L804
wy1iu/LargeMargin_Softmax_Loss
c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec
python/caffe/pycaffe.py
python
_Net_params
(self)
return self._params_dict
An OrderedDict (bottom to top, i.e., input to output) of network parameters indexed by name; each is a list of multiple blobs (e.g., weights and biases)
An OrderedDict (bottom to top, i.e., input to output) of network parameters indexed by name; each is a list of multiple blobs (e.g., weights and biases)
[ "An", "OrderedDict", "(", "bottom", "to", "top", "i", ".", "e", ".", "input", "to", "output", ")", "of", "network", "parameters", "indexed", "by", "name", ";", "each", "is", "a", "list", "of", "multiple", "blobs", "(", "e", ".", "g", ".", "weights", "and", "biases", ")" ]
def _Net_params(self): """ An OrderedDict (bottom to top, i.e., input to output) of network parameters indexed by name; each is a list of multiple blobs (e.g., weights and biases) """ if not hasattr(self, '_params_dict'): self._params_dict = OrderedDict([(name, lr.blobs) for name, lr in zip( self._layer_names, self.layers) if len(lr.blobs) > 0]) return self._params_dict
[ "def", "_Net_params", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_params_dict'", ")", ":", "self", ".", "_params_dict", "=", "OrderedDict", "(", "[", "(", "name", ",", "lr", ".", "blobs", ")", "for", "name", ",", "lr", "in", "zip", "(", "self", ".", "_layer_names", ",", "self", ".", "layers", ")", "if", "len", "(", "lr", ".", "blobs", ")", ">", "0", "]", ")", "return", "self", ".", "_params_dict" ]
https://github.com/wy1iu/LargeMargin_Softmax_Loss/blob/c3e9f20e4f16e2b4daf7d358a614366b9b39a6ec/python/caffe/pycaffe.py#L48-L59
tensorflow/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
deepmath/guidance/clause_loom.py
python
weave_fast_clauses
(clauses, embed, apply_, not_, or_, and_=None, shuffle=True, seed=None)
return tuple(clause_loom.output_tensor(ts) for ts in or_.output_type_shapes)
Weave serialized FastClauses using TensorLoom. Computes embeddings for a list of FastClause protos, which can either represent a single negated conjecture (if and_ is specified) or a batch of clauses (if and_ is None). In the description of the LoomOps below, vocab_id must be VOCAB_ID. Args: clauses: 1-D `string` tensor of serialized `FastClause` protos. embed: LoomOp to embed vocabulary ids: vocab_id -> embedding. apply_: LoomOp for curried function application: embedding -> embedding -> embedding. not_: LoomOp for negation: embedding -> embedding. or_: LoomOp for or: embedding -> embedding -> embedding. and_: LooOp for and (embedding -> embedding -> embedding) or None if clauses is a batch of individual clauses. shuffle: Whether to randomly shuffle ands and ors. seed: Optional seed for random number generation. Returns: The final embeddings of each clause, or of the whole conjunction if and_ is given.
Weave serialized FastClauses using TensorLoom.
[ "Weave", "serialized", "FastClauses", "using", "TensorLoom", "." ]
def weave_fast_clauses(clauses, embed, apply_, not_, or_, and_=None, shuffle=True, seed=None): """Weave serialized FastClauses using TensorLoom. Computes embeddings for a list of FastClause protos, which can either represent a single negated conjecture (if and_ is specified) or a batch of clauses (if and_ is None). In the description of the LoomOps below, vocab_id must be VOCAB_ID. Args: clauses: 1-D `string` tensor of serialized `FastClause` protos. embed: LoomOp to embed vocabulary ids: vocab_id -> embedding. apply_: LoomOp for curried function application: embedding -> embedding -> embedding. not_: LoomOp for negation: embedding -> embedding. or_: LoomOp for or: embedding -> embedding -> embedding. and_: LooOp for and (embedding -> embedding -> embedding) or None if clauses is a batch of individual clauses. shuffle: Whether to randomly shuffle ands and ors. seed: Optional seed for random number generation. Returns: The final embeddings of each clause, or of the whole conjunction if and_ is given. """ def weaver_op(**kwds): seed1, seed2 = tf.get_seed(seed) return gen_clause_ops.fast_clause_weaver( clauses=clauses, shuffle=shuffle, seed=seed1, seed2=seed2, conjunction=and_ is not None, **kwds) ops = {'embed': embed, 'apply': apply_, 'not': not_, 'or': or_} if and_ is not None: ops['and'] = and_ clause_loom = loom.Loom(named_ops=ops, weaver_op=weaver_op) return tuple(clause_loom.output_tensor(ts) for ts in or_.output_type_shapes)
[ "def", "weave_fast_clauses", "(", "clauses", ",", "embed", ",", "apply_", ",", "not_", ",", "or_", ",", "and_", "=", "None", ",", "shuffle", "=", "True", ",", "seed", "=", "None", ")", ":", "def", "weaver_op", "(", "*", "*", "kwds", ")", ":", "seed1", ",", "seed2", "=", "tf", ".", "get_seed", "(", "seed", ")", "return", "gen_clause_ops", ".", "fast_clause_weaver", "(", "clauses", "=", "clauses", ",", "shuffle", "=", "shuffle", ",", "seed", "=", "seed1", ",", "seed2", "=", "seed2", ",", "conjunction", "=", "and_", "is", "not", "None", ",", "*", "*", "kwds", ")", "ops", "=", "{", "'embed'", ":", "embed", ",", "'apply'", ":", "apply_", ",", "'not'", ":", "not_", ",", "'or'", ":", "or_", "}", "if", "and_", "is", "not", "None", ":", "ops", "[", "'and'", "]", "=", "and_", "clause_loom", "=", "loom", ".", "Loom", "(", "named_ops", "=", "ops", ",", "weaver_op", "=", "weaver_op", ")", "return", "tuple", "(", "clause_loom", ".", "output_tensor", "(", "ts", ")", "for", "ts", "in", "or_", ".", "output_type_shapes", ")" ]
https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/guidance/clause_loom.py#L84-L131
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/sparse/linalg/_norm.py
python
norm
(x, ord=None, axis=None)
Norm of a sparse matrix This function is able to return one of seven different matrix norms, depending on the value of the ``ord`` parameter. Parameters ---------- x : a sparse matrix Input sparse matrix. ord : {non-zero int, inf, -inf, 'fro'}, optional Order of the norm (see table under ``Notes``). inf means numpy's `inf` object. axis : {int, 2-tuple of ints, None}, optional If `axis` is an integer, it specifies the axis of `x` along which to compute the vector norms. If `axis` is a 2-tuple, it specifies the axes that hold 2-D matrices, and the matrix norms of these matrices are computed. If `axis` is None then either a vector norm (when `x` is 1-D) or a matrix norm (when `x` is 2-D) is returned. Returns ------- n : float or ndarray Notes ----- Some of the ord are not implemented because some associated functions like, _multi_svd_norm, are not yet available for sparse matrix. This docstring is modified based on numpy.linalg.norm. https://github.com/numpy/numpy/blob/master/numpy/linalg/linalg.py The following norms can be calculated: ===== ============================ ord norm for sparse matrices ===== ============================ None Frobenius norm 'fro' Frobenius norm inf max(sum(abs(x), axis=1)) -inf min(sum(abs(x), axis=1)) 0 abs(x).sum(axis=axis) 1 max(sum(abs(x), axis=0)) -1 min(sum(abs(x), axis=0)) 2 Not implemented -2 Not implemented other Not implemented ===== ============================ The Frobenius norm is given by [1]_: :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}` References ---------- .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*, Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15 Examples -------- >>> from scipy.sparse import * >>> import numpy as np >>> from scipy.sparse.linalg import norm >>> a = np.arange(9) - 4 >>> a array([-4, -3, -2, -1, 0, 1, 2, 3, 4]) >>> b = a.reshape((3, 3)) >>> b array([[-4, -3, -2], [-1, 0, 1], [ 2, 3, 4]]) >>> b = csr_matrix(b) >>> norm(b) 7.745966692414834 >>> norm(b, 'fro') 7.745966692414834 >>> norm(b, np.inf) 9 >>> norm(b, -np.inf) 2 >>> norm(b, 1) 7 >>> norm(b, -1) 6
Norm of a sparse matrix
[ "Norm", "of", "a", "sparse", "matrix" ]
def norm(x, ord=None, axis=None): """ Norm of a sparse matrix This function is able to return one of seven different matrix norms, depending on the value of the ``ord`` parameter. Parameters ---------- x : a sparse matrix Input sparse matrix. ord : {non-zero int, inf, -inf, 'fro'}, optional Order of the norm (see table under ``Notes``). inf means numpy's `inf` object. axis : {int, 2-tuple of ints, None}, optional If `axis` is an integer, it specifies the axis of `x` along which to compute the vector norms. If `axis` is a 2-tuple, it specifies the axes that hold 2-D matrices, and the matrix norms of these matrices are computed. If `axis` is None then either a vector norm (when `x` is 1-D) or a matrix norm (when `x` is 2-D) is returned. Returns ------- n : float or ndarray Notes ----- Some of the ord are not implemented because some associated functions like, _multi_svd_norm, are not yet available for sparse matrix. This docstring is modified based on numpy.linalg.norm. https://github.com/numpy/numpy/blob/master/numpy/linalg/linalg.py The following norms can be calculated: ===== ============================ ord norm for sparse matrices ===== ============================ None Frobenius norm 'fro' Frobenius norm inf max(sum(abs(x), axis=1)) -inf min(sum(abs(x), axis=1)) 0 abs(x).sum(axis=axis) 1 max(sum(abs(x), axis=0)) -1 min(sum(abs(x), axis=0)) 2 Not implemented -2 Not implemented other Not implemented ===== ============================ The Frobenius norm is given by [1]_: :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}` References ---------- .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*, Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15 Examples -------- >>> from scipy.sparse import * >>> import numpy as np >>> from scipy.sparse.linalg import norm >>> a = np.arange(9) - 4 >>> a array([-4, -3, -2, -1, 0, 1, 2, 3, 4]) >>> b = a.reshape((3, 3)) >>> b array([[-4, -3, -2], [-1, 0, 1], [ 2, 3, 4]]) >>> b = csr_matrix(b) >>> norm(b) 7.745966692414834 >>> norm(b, 'fro') 7.745966692414834 >>> norm(b, np.inf) 9 >>> norm(b, -np.inf) 2 >>> norm(b, 1) 7 >>> norm(b, -1) 6 """ if not issparse(x): raise TypeError("input is not sparse. use numpy.linalg.norm") # Check the default case first and handle it immediately. if axis is None and ord in (None, 'fro', 'f'): return _sparse_frobenius_norm(x) # Some norms require functions that are not implemented for all types. x = x.tocsr() if axis is None: axis = (0, 1) elif not isinstance(axis, tuple): msg = "'axis' must be None, an integer or a tuple of integers" try: int_axis = int(axis) except TypeError: raise TypeError(msg) if axis != int_axis: raise TypeError(msg) axis = (int_axis,) nd = 2 if len(axis) == 2: row_axis, col_axis = axis if not (-nd <= row_axis < nd and -nd <= col_axis < nd): raise ValueError('Invalid axis %r for an array with shape %r' % (axis, x.shape)) if row_axis % nd == col_axis % nd: raise ValueError('Duplicate axes given.') if ord == 2: raise NotImplementedError #return _multi_svd_norm(x, row_axis, col_axis, amax) elif ord == -2: raise NotImplementedError #return _multi_svd_norm(x, row_axis, col_axis, amin) elif ord == 1: return abs(x).sum(axis=row_axis).max(axis=col_axis)[0,0] elif ord == Inf: return abs(x).sum(axis=col_axis).max(axis=row_axis)[0,0] elif ord == -1: return abs(x).sum(axis=row_axis).min(axis=col_axis)[0,0] elif ord == -Inf: return abs(x).sum(axis=col_axis).min(axis=row_axis)[0,0] elif ord in (None, 'f', 'fro'): # The axis order does not matter for this norm. return _sparse_frobenius_norm(x) else: raise ValueError("Invalid norm order for matrices.") elif len(axis) == 1: a, = axis if not (-nd <= a < nd): raise ValueError('Invalid axis %r for an array with shape %r' % (axis, x.shape)) if ord == Inf: M = abs(x).max(axis=a) elif ord == -Inf: M = abs(x).min(axis=a) elif ord == 0: # Zero norm M = (x != 0).sum(axis=a) elif ord == 1: # special case for speedup M = abs(x).sum(axis=a) elif ord in (2, None): M = sqrt(abs(x).power(2).sum(axis=a)) else: try: ord + 1 except TypeError: raise ValueError('Invalid norm order for vectors.') M = np.power(abs(x).power(ord).sum(axis=a), 1 / ord) return M.A.ravel() else: raise ValueError("Improper number of dimensions to norm.")
[ "def", "norm", "(", "x", ",", "ord", "=", "None", ",", "axis", "=", "None", ")", ":", "if", "not", "issparse", "(", "x", ")", ":", "raise", "TypeError", "(", "\"input is not sparse. use numpy.linalg.norm\"", ")", "# Check the default case first and handle it immediately.", "if", "axis", "is", "None", "and", "ord", "in", "(", "None", ",", "'fro'", ",", "'f'", ")", ":", "return", "_sparse_frobenius_norm", "(", "x", ")", "# Some norms require functions that are not implemented for all types.", "x", "=", "x", ".", "tocsr", "(", ")", "if", "axis", "is", "None", ":", "axis", "=", "(", "0", ",", "1", ")", "elif", "not", "isinstance", "(", "axis", ",", "tuple", ")", ":", "msg", "=", "\"'axis' must be None, an integer or a tuple of integers\"", "try", ":", "int_axis", "=", "int", "(", "axis", ")", "except", "TypeError", ":", "raise", "TypeError", "(", "msg", ")", "if", "axis", "!=", "int_axis", ":", "raise", "TypeError", "(", "msg", ")", "axis", "=", "(", "int_axis", ",", ")", "nd", "=", "2", "if", "len", "(", "axis", ")", "==", "2", ":", "row_axis", ",", "col_axis", "=", "axis", "if", "not", "(", "-", "nd", "<=", "row_axis", "<", "nd", "and", "-", "nd", "<=", "col_axis", "<", "nd", ")", ":", "raise", "ValueError", "(", "'Invalid axis %r for an array with shape %r'", "%", "(", "axis", ",", "x", ".", "shape", ")", ")", "if", "row_axis", "%", "nd", "==", "col_axis", "%", "nd", ":", "raise", "ValueError", "(", "'Duplicate axes given.'", ")", "if", "ord", "==", "2", ":", "raise", "NotImplementedError", "#return _multi_svd_norm(x, row_axis, col_axis, amax)", "elif", "ord", "==", "-", "2", ":", "raise", "NotImplementedError", "#return _multi_svd_norm(x, row_axis, col_axis, amin)", "elif", "ord", "==", "1", ":", "return", "abs", "(", "x", ")", ".", "sum", "(", "axis", "=", "row_axis", ")", ".", "max", "(", "axis", "=", "col_axis", ")", "[", "0", ",", "0", "]", "elif", "ord", "==", "Inf", ":", "return", "abs", "(", "x", ")", ".", "sum", "(", "axis", "=", "col_axis", ")", ".", "max", "(", "axis", "=", "row_axis", ")", "[", "0", ",", "0", "]", "elif", "ord", "==", "-", "1", ":", "return", "abs", "(", "x", ")", ".", "sum", "(", "axis", "=", "row_axis", ")", ".", "min", "(", "axis", "=", "col_axis", ")", "[", "0", ",", "0", "]", "elif", "ord", "==", "-", "Inf", ":", "return", "abs", "(", "x", ")", ".", "sum", "(", "axis", "=", "col_axis", ")", ".", "min", "(", "axis", "=", "row_axis", ")", "[", "0", ",", "0", "]", "elif", "ord", "in", "(", "None", ",", "'f'", ",", "'fro'", ")", ":", "# The axis order does not matter for this norm.", "return", "_sparse_frobenius_norm", "(", "x", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid norm order for matrices.\"", ")", "elif", "len", "(", "axis", ")", "==", "1", ":", "a", ",", "=", "axis", "if", "not", "(", "-", "nd", "<=", "a", "<", "nd", ")", ":", "raise", "ValueError", "(", "'Invalid axis %r for an array with shape %r'", "%", "(", "axis", ",", "x", ".", "shape", ")", ")", "if", "ord", "==", "Inf", ":", "M", "=", "abs", "(", "x", ")", ".", "max", "(", "axis", "=", "a", ")", "elif", "ord", "==", "-", "Inf", ":", "M", "=", "abs", "(", "x", ")", ".", "min", "(", "axis", "=", "a", ")", "elif", "ord", "==", "0", ":", "# Zero norm", "M", "=", "(", "x", "!=", "0", ")", ".", "sum", "(", "axis", "=", "a", ")", "elif", "ord", "==", "1", ":", "# special case for speedup", "M", "=", "abs", "(", "x", ")", ".", "sum", "(", "axis", "=", "a", ")", "elif", "ord", "in", "(", "2", ",", "None", ")", ":", "M", "=", "sqrt", "(", "abs", "(", "x", ")", ".", "power", "(", "2", ")", ".", "sum", "(", "axis", "=", "a", ")", ")", "else", ":", "try", ":", "ord", "+", "1", "except", "TypeError", ":", "raise", "ValueError", "(", "'Invalid norm order for vectors.'", ")", "M", "=", "np", ".", "power", "(", "abs", "(", "x", ")", ".", "power", "(", "ord", ")", ".", "sum", "(", "axis", "=", "a", ")", ",", "1", "/", "ord", ")", "return", "M", ".", "A", ".", "ravel", "(", ")", "else", ":", "raise", "ValueError", "(", "\"Improper number of dimensions to norm.\"", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/sparse/linalg/_norm.py#L22-L184
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
FontData.SetAllowSymbols
(*args, **kwargs)
return _windows_.FontData_SetAllowSymbols(*args, **kwargs)
SetAllowSymbols(self, bool allowSymbols) Under MS Windows, determines whether symbol fonts can be selected. Has no effect on other platforms. The default value is true.
SetAllowSymbols(self, bool allowSymbols)
[ "SetAllowSymbols", "(", "self", "bool", "allowSymbols", ")" ]
def SetAllowSymbols(*args, **kwargs): """ SetAllowSymbols(self, bool allowSymbols) Under MS Windows, determines whether symbol fonts can be selected. Has no effect on other platforms. The default value is true. """ return _windows_.FontData_SetAllowSymbols(*args, **kwargs)
[ "def", "SetAllowSymbols", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "FontData_SetAllowSymbols", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L3519-L3526
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/syntax.py
python
Import.__init__
(self, file_name, line, column)
Construct an Imports section.
Construct an Imports section.
[ "Construct", "an", "Imports", "section", "." ]
def __init__(self, file_name, line, column): # type: (str, int, int) -> None """Construct an Imports section.""" self.imports = [] # type: List[str] # These are not part of the IDL syntax but are produced by the parser. # List of imports with structs. self.resolved_imports = [] # type: List[str] # All imports directly or indirectly included self.dependencies = [] # type: List[str] super(Import, self).__init__(file_name, line, column)
[ "def", "__init__", "(", "self", ",", "file_name", ",", "line", ",", "column", ")", ":", "# type: (str, int, int) -> None", "self", ".", "imports", "=", "[", "]", "# type: List[str]", "# These are not part of the IDL syntax but are produced by the parser.", "# List of imports with structs.", "self", ".", "resolved_imports", "=", "[", "]", "# type: List[str]", "# All imports directly or indirectly included", "self", ".", "dependencies", "=", "[", "]", "# type: List[str]", "super", "(", "Import", ",", "self", ")", ".", "__init__", "(", "file_name", ",", "line", ",", "column", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/syntax.py#L338-L349
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/distutils/command/config.py
python
config.try_run
(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c")
return ok
Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Return true on success, false otherwise.
Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Return true on success, false otherwise.
[ "Try", "to", "compile", "link", "to", "an", "executable", "and", "run", "a", "program", "built", "from", "body", "and", "headers", ".", "Return", "true", "on", "success", "false", "otherwise", "." ]
def try_run(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c"): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Return true on success, false otherwise. """ from distutils.ccompiler import CompileError, LinkError self._check_compiler() try: src, obj, exe = self._link(body, headers, include_dirs, libraries, library_dirs, lang) self.spawn([exe]) ok = True except (CompileError, LinkError, DistutilsExecError): ok = False log.info(ok and "success!" or "failure.") self._clean() return ok
[ "def", "try_run", "(", "self", ",", "body", ",", "headers", "=", "None", ",", "include_dirs", "=", "None", ",", "libraries", "=", "None", ",", "library_dirs", "=", "None", ",", "lang", "=", "\"c\"", ")", ":", "from", "distutils", ".", "ccompiler", "import", "CompileError", ",", "LinkError", "self", ".", "_check_compiler", "(", ")", "try", ":", "src", ",", "obj", ",", "exe", "=", "self", ".", "_link", "(", "body", ",", "headers", ",", "include_dirs", ",", "libraries", ",", "library_dirs", ",", "lang", ")", "self", ".", "spawn", "(", "[", "exe", "]", ")", "ok", "=", "True", "except", "(", "CompileError", ",", "LinkError", ",", "DistutilsExecError", ")", ":", "ok", "=", "False", "log", ".", "info", "(", "ok", "and", "\"success!\"", "or", "\"failure.\"", ")", "self", ".", "_clean", "(", ")", "return", "ok" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/distutils/command/config.py#L255-L273
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ftplib.py
python
FTP.pwd
(self)
return parse257(resp)
Return current working directory.
Return current working directory.
[ "Return", "current", "working", "directory", "." ]
def pwd(self): '''Return current working directory.''' resp = self.sendcmd('PWD') return parse257(resp)
[ "def", "pwd", "(", "self", ")", ":", "resp", "=", "self", ".", "sendcmd", "(", "'PWD'", ")", "return", "parse257", "(", "resp", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ftplib.py#L575-L578
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/serve/snippets/util/sparse_tree.py
python
_GeneralRemoveAbstractPath
(parts, store)
Remove path parts from store, when store's top-layer is not repeated. I believe that removing a whole subtree is just an artifact of programmer laziness, not part of its design. Used with user-accessible 'template' stuff. Does no 'required'ness checking; use with care. Returns true if deletion deleted /something/ (doesn't check the whole abstract_path). It will delete a whole subtree if that subtree has no other children (ie is {}), and so on, up. If there is only the abstract_path in the tree, will leave an empty tree {}. This expects the tree to be 'newstyle', as all sparse trees currently are. Args: parts: the path elements to remove. store: store to remove path from. Returns: Whether we found (and removed) anything.
Remove path parts from store, when store's top-layer is not repeated.
[ "Remove", "path", "parts", "from", "store", "when", "store", "s", "top", "-", "layer", "is", "not", "repeated", "." ]
def _GeneralRemoveAbstractPath(parts, store): """Remove path parts from store, when store's top-layer is not repeated. I believe that removing a whole subtree is just an artifact of programmer laziness, not part of its design. Used with user-accessible 'template' stuff. Does no 'required'ness checking; use with care. Returns true if deletion deleted /something/ (doesn't check the whole abstract_path). It will delete a whole subtree if that subtree has no other children (ie is {}), and so on, up. If there is only the abstract_path in the tree, will leave an empty tree {}. This expects the tree to be 'newstyle', as all sparse trees currently are. Args: parts: the path elements to remove. store: store to remove path from. Returns: Whether we found (and removed) anything. """ # down to parent + child assert isinstance(store, dict) key, rest = parts[0], parts[1:] if not rest: # it doesn't matter if what's below is repeated, that just makes it more # convenient to destroy them all. if key in store: del store[key] # This deleted 'field' has siblings; the parent should live parent_should_live = bool(store) return parent_should_live else: key_should_live = True substore = store.get(key, None) assert not key.isdigit() if not isinstance(substore, dict): # Path wasn't in the sparse tree; don't delete anything further up. key_should_live = True elif substore.keys()[0].isdigit(): key_should_live = _RemoveAbstractPathFromRepeatedPartOfSparse( rest, substore) else: key_should_live = _GeneralRemoveAbstractPath(rest, substore) if not key_should_live: del store[key] return bool(store) else: return True
[ "def", "_GeneralRemoveAbstractPath", "(", "parts", ",", "store", ")", ":", "# down to parent + child", "assert", "isinstance", "(", "store", ",", "dict", ")", "key", ",", "rest", "=", "parts", "[", "0", "]", ",", "parts", "[", "1", ":", "]", "if", "not", "rest", ":", "# it doesn't matter if what's below is repeated, that just makes it more", "# convenient to destroy them all.", "if", "key", "in", "store", ":", "del", "store", "[", "key", "]", "# This deleted 'field' has siblings; the parent should live", "parent_should_live", "=", "bool", "(", "store", ")", "return", "parent_should_live", "else", ":", "key_should_live", "=", "True", "substore", "=", "store", ".", "get", "(", "key", ",", "None", ")", "assert", "not", "key", ".", "isdigit", "(", ")", "if", "not", "isinstance", "(", "substore", ",", "dict", ")", ":", "# Path wasn't in the sparse tree; don't delete anything further up.", "key_should_live", "=", "True", "elif", "substore", ".", "keys", "(", ")", "[", "0", "]", ".", "isdigit", "(", ")", ":", "key_should_live", "=", "_RemoveAbstractPathFromRepeatedPartOfSparse", "(", "rest", ",", "substore", ")", "else", ":", "key_should_live", "=", "_GeneralRemoveAbstractPath", "(", "rest", ",", "substore", ")", "if", "not", "key_should_live", ":", "del", "store", "[", "key", "]", "return", "bool", "(", "store", ")", "else", ":", "return", "True" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/snippets/util/sparse_tree.py#L167-L217
google/skia
82d65d0487bd72f5f7332d002429ec2dc61d2463
tools/copyright/fileparser.py
python
CParser.CreateCopyrightBlock
(self, year, holder)
return self.COPYRIGHT_BLOCK_FORMAT % (year, holder)
Returns a copyright block suitable for this language, with the given attributes. @param year year in which to hold copyright (defaults to DEFAULT_YEAR) @param holder holder of copyright (defaults to DEFAULT_HOLDER)
Returns a copyright block suitable for this language, with the given attributes.
[ "Returns", "a", "copyright", "block", "suitable", "for", "this", "language", "with", "the", "given", "attributes", "." ]
def CreateCopyrightBlock(self, year, holder): """Returns a copyright block suitable for this language, with the given attributes. @param year year in which to hold copyright (defaults to DEFAULT_YEAR) @param holder holder of copyright (defaults to DEFAULT_HOLDER) """ if not year: year = self.DEFAULT_YEAR if not holder: holder = self.DEFAULT_HOLDER return self.COPYRIGHT_BLOCK_FORMAT % (year, holder)
[ "def", "CreateCopyrightBlock", "(", "self", ",", "year", ",", "holder", ")", ":", "if", "not", "year", ":", "year", "=", "self", ".", "DEFAULT_YEAR", "if", "not", "holder", ":", "holder", "=", "self", ".", "DEFAULT_HOLDER", "return", "self", ".", "COPYRIGHT_BLOCK_FORMAT", "%", "(", "year", ",", "holder", ")" ]
https://github.com/google/skia/blob/82d65d0487bd72f5f7332d002429ec2dc61d2463/tools/copyright/fileparser.py#L81-L92
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/sparse/spfuncs.py
python
count_blocks
(A,blocksize)
For a given blocksize=(r,c) count the number of occupied blocks in a sparse matrix A
For a given blocksize=(r,c) count the number of occupied blocks in a sparse matrix A
[ "For", "a", "given", "blocksize", "=", "(", "r", "c", ")", "count", "the", "number", "of", "occupied", "blocks", "in", "a", "sparse", "matrix", "A" ]
def count_blocks(A,blocksize): """For a given blocksize=(r,c) count the number of occupied blocks in a sparse matrix A """ r,c = blocksize if r < 1 or c < 1: raise ValueError('r and c must be positive') if isspmatrix_csr(A): M,N = A.shape return csr_count_blocks(M,N,r,c,A.indptr,A.indices) elif isspmatrix_csc(A): return count_blocks(A.T,(c,r)) else: return count_blocks(csr_matrix(A),blocksize)
[ "def", "count_blocks", "(", "A", ",", "blocksize", ")", ":", "r", ",", "c", "=", "blocksize", "if", "r", "<", "1", "or", "c", "<", "1", ":", "raise", "ValueError", "(", "'r and c must be positive'", ")", "if", "isspmatrix_csr", "(", "A", ")", ":", "M", ",", "N", "=", "A", ".", "shape", "return", "csr_count_blocks", "(", "M", ",", "N", ",", "r", ",", "c", ",", "A", ".", "indptr", ",", "A", ".", "indices", ")", "elif", "isspmatrix_csc", "(", "A", ")", ":", "return", "count_blocks", "(", "A", ".", "T", ",", "(", "c", ",", "r", ")", ")", "else", ":", "return", "count_blocks", "(", "csr_matrix", "(", "A", ")", ",", "blocksize", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/sparse/spfuncs.py#L86-L100
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/mailbox.py
python
Mailbox.popitem
(self)
Delete an arbitrary (key, message) pair and return it.
Delete an arbitrary (key, message) pair and return it.
[ "Delete", "an", "arbitrary", "(", "key", "message", ")", "pair", "and", "return", "it", "." ]
def popitem(self): """Delete an arbitrary (key, message) pair and return it.""" for key in self.iterkeys(): return (key, self.pop(key)) # This is only run once. else: raise KeyError('No messages in mailbox')
[ "def", "popitem", "(", "self", ")", ":", "for", "key", "in", "self", ".", "iterkeys", "(", ")", ":", "return", "(", "key", ",", "self", ".", "pop", "(", "key", ")", ")", "# This is only run once.", "else", ":", "raise", "KeyError", "(", "'No messages in mailbox'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/mailbox.py#L156-L161