nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
SCons/scons
309f0234d1d9cc76955818be47c5c722f577dac6
SCons/Debug.py
python
caller_trace
(back=0)
Trace caller stack and save info into global dicts, which are printed automatically at the end of SCons execution.
Trace caller stack and save info into global dicts, which are printed automatically at the end of SCons execution.
[ "Trace", "caller", "stack", "and", "save", "info", "into", "global", "dicts", "which", "are", "printed", "automatically", "at", "the", "end", "of", "SCons", "execution", "." ]
def caller_trace(back=0): """ Trace caller stack and save info into global dicts, which are printed automatically at the end of SCons execution. """ global caller_bases, caller_dicts import traceback tb = traceback.extract_stack(limit=3+back) tb.reverse() callee = tb[1][:3] caller_bases[callee] = caller_bases.get(callee, 0) + 1 for caller in tb[2:]: caller = callee + caller[:3] try: entry = caller_dicts[callee] except KeyError: caller_dicts[callee] = entry = {} entry[caller] = entry.get(caller, 0) + 1 callee = caller
[ "def", "caller_trace", "(", "back", "=", "0", ")", ":", "global", "caller_bases", ",", "caller_dicts", "import", "traceback", "tb", "=", "traceback", ".", "extract_stack", "(", "limit", "=", "3", "+", "back", ")", "tb", ".", "reverse", "(", ")", "callee"...
https://github.com/SCons/scons/blob/309f0234d1d9cc76955818be47c5c722f577dac6/SCons/Debug.py#L135-L153
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
contrib/od/setup_directory.py
python
ODError.__init__
(self, error)
[]
def __init__(self, error): self.message = (str(error), error.code())
[ "def", "__init__", "(", "self", ",", "error", ")", ":", "self", ".", "message", "=", "(", "str", "(", "error", ")", ",", "error", ".", "code", "(", ")", ")" ]
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/contrib/od/setup_directory.py#L422-L423
inventree/InvenTree
4a5e4a88ac3e91d64a21e8cab3708ecbc6e2bd8b
InvenTree/plugin/models.py
python
PluginConfig.__init__
(self, *args, **kwargs)
Override to set original state of the plugin-config instance
Override to set original state of the plugin-config instance
[ "Override", "to", "set", "original", "state", "of", "the", "plugin", "-", "config", "instance" ]
def __init__(self, *args, **kwargs): """ Override to set original state of the plugin-config instance """ super().__init__(*args, **kwargs) self.__org_active = self.active # append settings from registry self.plugin = plugin_registry.plugins.get(self.key, None) def get_plugin_meta(name): if self.plugin: return str(getattr(self.plugin, name, None)) return None self.meta = { key: get_plugin_meta(key) for key in ['slug', 'human_name', 'description', 'author', 'pub_date', 'version', 'website', 'license', 'package_path', 'settings_url', ] }
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "__org_active", "=", "self", ".", "active", "# append settings from ...
https://github.com/inventree/InvenTree/blob/4a5e4a88ac3e91d64a21e8cab3708ecbc6e2bd8b/InvenTree/plugin/models.py#L66-L86
francisck/DanderSpritz_docs
86bb7caca5a957147f120b18bb5c31f299914904
Python/Core/Lib/nntplib.py
python
NNTP.artcmd
(self, line, file=None)
return ( resp, nr, id, list)
Internal: process a HEAD, BODY or ARTICLE command.
Internal: process a HEAD, BODY or ARTICLE command.
[ "Internal", ":", "process", "a", "HEAD", "BODY", "or", "ARTICLE", "command", "." ]
def artcmd(self, line, file=None): """Internal: process a HEAD, BODY or ARTICLE command.""" resp, list = self.longcmd(line, file) resp, nr, id = self.statparse(resp) return ( resp, nr, id, list)
[ "def", "artcmd", "(", "self", ",", "line", ",", "file", "=", "None", ")", ":", "resp", ",", "list", "=", "self", ".", "longcmd", "(", "line", ",", "file", ")", "resp", ",", "nr", ",", "id", "=", "self", ".", "statparse", "(", "resp", ")", "retu...
https://github.com/francisck/DanderSpritz_docs/blob/86bb7caca5a957147f120b18bb5c31f299914904/Python/Core/Lib/nntplib.py#L375-L380
softlayer/softlayer-python
cdef7d63c66413197a9a97b0414de9f95887a82a
SoftLayer/CLI/globalip/cancel.py
python
cli
(env, identifier)
Cancel global IP.
Cancel global IP.
[ "Cancel", "global", "IP", "." ]
def cli(env, identifier): """Cancel global IP.""" mgr = SoftLayer.NetworkManager(env.client) global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier, name='global ip') if not (env.skip_confirmations or formatting.no_going_back(global_ip_id)): raise exceptions.CLIAbort('Aborted') mgr.cancel_global_ip(global_ip_id)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "global_ip_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_global_ip_ids", ",", "identifier", ",", "nam...
https://github.com/softlayer/softlayer-python/blob/cdef7d63c66413197a9a97b0414de9f95887a82a/SoftLayer/CLI/globalip/cancel.py#L16-L26
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/pkg_resources/__init__.py
python
ResourceManager.resource_exists
(self, package_or_requirement, resource_name)
return get_provider(package_or_requirement).has_resource(resource_name)
Does the named resource exist?
Does the named resource exist?
[ "Does", "the", "named", "resource", "exist?" ]
def resource_exists(self, package_or_requirement, resource_name): """Does the named resource exist?""" return get_provider(package_or_requirement).has_resource(resource_name)
[ "def", "resource_exists", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "has_resource", "(", "resource_name", ")" ]
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/pkg_resources/__init__.py#L1148-L1150
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Centos_6.4/paramiko/sftp.py
python
BaseSFTP._read_all
(self, n)
return out
[]
def _read_all(self, n): out = '' while n > 0: if isinstance(self.sock, socket.socket): # sometimes sftp is used directly over a socket instead of # through a paramiko channel. in this case, check periodically # if the socket is closed. (for some reason, recv() won't ever # return or raise an exception, but calling select on a closed # socket will.) while True: read, write, err = select.select([ self.sock ], [], [], 0.1) if len(read) > 0: x = self.sock.recv(n) break else: x = self.sock.recv(n) if len(x) == 0: raise EOFError() out += x n -= len(x) return out
[ "def", "_read_all", "(", "self", ",", "n", ")", ":", "out", "=", "''", "while", "n", ">", "0", ":", "if", "isinstance", "(", "self", ".", "sock", ",", "socket", ".", "socket", ")", ":", "# sometimes sftp is used directly over a socket instead of", "# through...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Centos_6.4/paramiko/sftp.py#L144-L165
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/Options.py
python
getMainArgs
()
return tuple(extra_args)
*tuple*, arguments following the optional arguments
*tuple*, arguments following the optional arguments
[ "*", "tuple", "*", "arguments", "following", "the", "optional", "arguments" ]
def getMainArgs(): """*tuple*, arguments following the optional arguments""" return tuple(extra_args)
[ "def", "getMainArgs", "(", ")", ":", "return", "tuple", "(", "extra_args", ")" ]
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/Options.py#L810-L812
MrH0wl/Cloudmare
65e5bc9888f9d362ab2abfb103ea6c1e869d67aa
thirdparty/dns/set.py
python
Set.difference
(self, other)
return obj
Return a new set which ``self`` - ``other``, i.e. the items in ``self`` which are not also in ``other``. Returns the same Set type as this set.
Return a new set which ``self`` - ``other``, i.e. the items in ``self`` which are not also in ``other``.
[ "Return", "a", "new", "set", "which", "self", "-", "other", "i", ".", "e", ".", "the", "items", "in", "self", "which", "are", "not", "also", "in", "other", "." ]
def difference(self, other): """Return a new set which ``self`` - ``other``, i.e. the items in ``self`` which are not also in ``other``. Returns the same Set type as this set. """ obj = self._clone() obj.difference_update(other) return obj
[ "def", "difference", "(", "self", ",", "other", ")", ":", "obj", "=", "self", ".", "_clone", "(", ")", "obj", ".", "difference_update", "(", "other", ")", "return", "obj" ]
https://github.com/MrH0wl/Cloudmare/blob/65e5bc9888f9d362ab2abfb103ea6c1e869d67aa/thirdparty/dns/set.py#L165-L174
shaneshixiang/rllabplusplus
4d55f96ec98e3fe025b7991945e3e6a54fd5449f
rllab/rllab_mujoco_py/glfw.py
python
set_monitor_callback
(cbfun)
Sets the monitor configuration callback. Wrapper for: GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun cbfun);
Sets the monitor configuration callback.
[ "Sets", "the", "monitor", "configuration", "callback", "." ]
def set_monitor_callback(cbfun): ''' Sets the monitor configuration callback. Wrapper for: GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun cbfun); ''' global _monitor_callback previous_callback = _monitor_callback if cbfun is None: cbfun = 0 c_cbfun = _GLFWmonitorfun(cbfun) _monitor_callback = (cbfun, c_cbfun) cbfun = c_cbfun _glfw.glfwSetMonitorCallback(cbfun) if previous_callback is not None and previous_callback[0] != 0: return previous_callback[0]
[ "def", "set_monitor_callback", "(", "cbfun", ")", ":", "global", "_monitor_callback", "previous_callback", "=", "_monitor_callback", "if", "cbfun", "is", "None", ":", "cbfun", "=", "0", "c_cbfun", "=", "_GLFWmonitorfun", "(", "cbfun", ")", "_monitor_callback", "="...
https://github.com/shaneshixiang/rllabplusplus/blob/4d55f96ec98e3fe025b7991945e3e6a54fd5449f/rllab/rllab_mujoco_py/glfw.py#L671-L687
oaubert/python-vlc
908ffdbd0844dc1849728c456e147788798c99da
generated/dev/vlc.py
python
Instance.media_player_new
(self, uri=None)
return p
Create a new MediaPlayer instance. @param uri: an optional URI to play in the player as a str, bytes or PathLike object.
Create a new MediaPlayer instance.
[ "Create", "a", "new", "MediaPlayer", "instance", "." ]
def media_player_new(self, uri=None): """Create a new MediaPlayer instance. @param uri: an optional URI to play in the player as a str, bytes or PathLike object. """ p = libvlc_media_player_new(self) if uri: p.set_media(self.media_new(uri)) p._instance = self return p
[ "def", "media_player_new", "(", "self", ",", "uri", "=", "None", ")", ":", "p", "=", "libvlc_media_player_new", "(", "self", ")", "if", "uri", ":", "p", ".", "set_media", "(", "self", ".", "media_new", "(", "uri", ")", ")", "p", ".", "_instance", "="...
https://github.com/oaubert/python-vlc/blob/908ffdbd0844dc1849728c456e147788798c99da/generated/dev/vlc.py#L2096-L2105
rspivak/slimit
3533eba9ad5b39f3a015ae6269670022ab310847
src/slimit/parser.py
python
Parser.p_case_clauses
(self, p)
case_clauses : case_clause | case_clauses case_clause
case_clauses : case_clause | case_clauses case_clause
[ "case_clauses", ":", "case_clause", "|", "case_clauses", "case_clause" ]
def p_case_clauses(self, p): """case_clauses : case_clause | case_clauses case_clause """ if len(p) == 2: p[0] = [p[1]] else: p[1].append(p[2]) p[0] = p[1]
[ "def", "p_case_clauses", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]", "else", ":", "p", "[", "1", "]", ".", "append", "(", "p", "[", "2", "]", ")", ...
https://github.com/rspivak/slimit/blob/3533eba9ad5b39f3a015ae6269670022ab310847/src/slimit/parser.py#L1109-L1117
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/encodings/punycode.py
python
insertion_unsort
(str, extended)
return result
3.2 Insertion unsort coding
3.2 Insertion unsort coding
[ "3", ".", "2", "Insertion", "unsort", "coding" ]
def insertion_unsort(str, extended): """3.2 Insertion unsort coding""" oldchar = 0x80 result = [] oldindex = -1 for c in extended: index = pos = -1 char = ord(c) curlen = selective_len(str, char) delta = (curlen+1) * (char - oldchar) while 1: index,pos = selective_find(str,c,index,pos) if index == -1: break delta += index - oldindex result.append(delta-1) oldindex = index delta = 0 oldchar = char return result
[ "def", "insertion_unsort", "(", "str", ",", "extended", ")", ":", "oldchar", "=", "0x80", "result", "=", "[", "]", "oldindex", "=", "-", "1", "for", "c", "in", "extended", ":", "index", "=", "pos", "=", "-", "1", "char", "=", "ord", "(", "c", ")"...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/encodings/punycode.py#L48-L68
Amulet-Team/Amulet-Core
a57aeaa4216806401ff35a2dba38782a35abc42e
amulet/level/formats/sponge_schem/interface.py
python
SpongeSchemInterface.decode
( self, cx: int, cz: int, data: SpongeSchemChunk )
return chunk, palette
Create an amulet.api.chunk.Chunk object from raw data given by the format :param cx: chunk x coordinate :param cz: chunk z coordinate :param data: Raw chunk data provided by the format. :return: Chunk object in version-specific format, along with the block_palette for that chunk.
Create an amulet.api.chunk.Chunk object from raw data given by the format :param cx: chunk x coordinate :param cz: chunk z coordinate :param data: Raw chunk data provided by the format. :return: Chunk object in version-specific format, along with the block_palette for that chunk.
[ "Create", "an", "amulet", ".", "api", ".", "chunk", ".", "Chunk", "object", "from", "raw", "data", "given", "by", "the", "format", ":", "param", "cx", ":", "chunk", "x", "coordinate", ":", "param", "cz", ":", "chunk", "z", "coordinate", ":", "param", ...
def decode( self, cx: int, cz: int, data: SpongeSchemChunk ) -> Tuple["Chunk", AnyNDArray]: """ Create an amulet.api.chunk.Chunk object from raw data given by the format :param cx: chunk x coordinate :param cz: chunk z coordinate :param data: Raw chunk data provided by the format. :return: Chunk object in version-specific format, along with the block_palette for that chunk. """ palette = numpy.empty(len(data.palette) + 1, dtype=object) palette[0] = Block(namespace="minecraft", base_name="air") palette[1:] = data.palette[:] chunk = Chunk(cx, cz) box = data.selection.create_moved_box((cx * 16, 0, cz * 16), subtract=True) chunk.blocks[box.slice] = data.blocks + 1 for b in data.block_entities: b = self._decode_block_entity( b, self._block_entity_id_type, self._block_entity_coord_type ) if b is not None: chunk.block_entities.insert(b) for e in data.entities: e = self._decode_entity( e, self._block_entity_id_type, self._block_entity_coord_type ) if e is not None: chunk.entities.append(e) return chunk, palette
[ "def", "decode", "(", "self", ",", "cx", ":", "int", ",", "cz", ":", "int", ",", "data", ":", "SpongeSchemChunk", ")", "->", "Tuple", "[", "\"Chunk\"", ",", "AnyNDArray", "]", ":", "palette", "=", "numpy", ".", "empty", "(", "len", "(", "data", "."...
https://github.com/Amulet-Team/Amulet-Core/blob/a57aeaa4216806401ff35a2dba38782a35abc42e/amulet/level/formats/sponge_schem/interface.py#L26-L56
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/xml/sax/xmlreader.py
python
InputSource.getEncoding
(self)
return self.__encoding
Get the character encoding of this InputSource.
Get the character encoding of this InputSource.
[ "Get", "the", "character", "encoding", "of", "this", "InputSource", "." ]
def getEncoding(self): "Get the character encoding of this InputSource." return self.__encoding
[ "def", "getEncoding", "(", "self", ")", ":", "return", "self", ".", "__encoding" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/xml/sax/xmlreader.py#L236-L238
TensorMSA/tensormsa
c36b565159cd934533636429add3c7d7263d622b
master/workflow/data/workflow_data_image.py
python
WorkFlowDataImage.set_preview_data
(self)
return None
:param type: :param conn: :return:
[]
def set_preview_data(self): """ :param type: :param conn: :return: """ return None
[ "def", "set_preview_data", "(", "self", ")", ":", "return", "None" ]
https://github.com/TensorMSA/tensormsa/blob/c36b565159cd934533636429add3c7d7263d622b/master/workflow/data/workflow_data_image.py#L23-L30
pandas-dev/pandas
5ba7d714014ae8feaccc0dd4a98890828cf2832d
pandas/core/dtypes/astype.py
python
astype_td64_unit_conversion
( values: np.ndarray, dtype: np.dtype, copy: bool )
return result
By pandas convention, converting to non-nano timedelta64 returns an int64-dtyped array with ints representing multiples of the desired timedelta unit. This is essentially division. Parameters ---------- values : np.ndarray[timedelta64[ns]] dtype : np.dtype timedelta64 with unit not-necessarily nano copy : bool Returns ------- np.ndarray
By pandas convention, converting to non-nano timedelta64 returns an int64-dtyped array with ints representing multiples of the desired timedelta unit. This is essentially division.
[ "By", "pandas", "convention", "converting", "to", "non", "-", "nano", "timedelta64", "returns", "an", "int64", "-", "dtyped", "array", "with", "ints", "representing", "multiples", "of", "the", "desired", "timedelta", "unit", ".", "This", "is", "essentially", "...
def astype_td64_unit_conversion( values: np.ndarray, dtype: np.dtype, copy: bool ) -> np.ndarray: """ By pandas convention, converting to non-nano timedelta64 returns an int64-dtyped array with ints representing multiples of the desired timedelta unit. This is essentially division. Parameters ---------- values : np.ndarray[timedelta64[ns]] dtype : np.dtype timedelta64 with unit not-necessarily nano copy : bool Returns ------- np.ndarray """ if is_dtype_equal(values.dtype, dtype): if copy: return values.copy() return values # otherwise we are converting to non-nano result = values.astype(dtype, copy=False) # avoid double-copying result = result.astype(np.float64) mask = isna(values) np.putmask(result, mask, np.nan) return result
[ "def", "astype_td64_unit_conversion", "(", "values", ":", "np", ".", "ndarray", ",", "dtype", ":", "np", ".", "dtype", ",", "copy", ":", "bool", ")", "->", "np", ".", "ndarray", ":", "if", "is_dtype_equal", "(", "values", ".", "dtype", ",", "dtype", ")...
https://github.com/pandas-dev/pandas/blob/5ba7d714014ae8feaccc0dd4a98890828cf2832d/pandas/core/dtypes/astype.py#L307-L337
openstack/rally
58b12c2e0bfa541bdb038be6e1679c5117b98484
rally/cli/cliutils.py
python
print_dict
(obj, fields=None, formatters=None, mixed_case_fields=False, normalize_field_names=False, property_label="Property", value_label="Value", table_label=None, print_header=True, print_border=True, wrap=0, out=sys.stdout)
Print dict as a table. :param obj: dict to print :param fields: `dict` of keys to print from d. Defaults to all keys :param formatters: `dict` of callables for field formatting :param mixed_case_fields: fields corresponding to object attributes that have mixed case names (e.g., 'serverId') :param normalize_field_names: If True, field names will be transformed, e.g. "Field Name" -> "field_name", otherwise they will be used unchanged. :param property_label: label of "property" column :param value_label: label of "value" column :param table_label: Label to use as header for the whole table. :param print_header: print table header. :param print_border: print table border. :param out: stream to write output to.
Print dict as a table.
[ "Print", "dict", "as", "a", "table", "." ]
def print_dict(obj, fields=None, formatters=None, mixed_case_fields=False, normalize_field_names=False, property_label="Property", value_label="Value", table_label=None, print_header=True, print_border=True, wrap=0, out=sys.stdout): """Print dict as a table. :param obj: dict to print :param fields: `dict` of keys to print from d. Defaults to all keys :param formatters: `dict` of callables for field formatting :param mixed_case_fields: fields corresponding to object attributes that have mixed case names (e.g., 'serverId') :param normalize_field_names: If True, field names will be transformed, e.g. "Field Name" -> "field_name", otherwise they will be used unchanged. :param property_label: label of "property" column :param value_label: label of "value" column :param table_label: Label to use as header for the whole table. :param print_header: print table header. :param print_border: print table border. :param out: stream to write output to. """ formatters = formatters or {} mixed_case_fields = mixed_case_fields or [] if not fields: if isinstance(obj, dict): fields = sorted(obj.keys()) else: fields = [name for name in dir(obj) if (not name.startswith("_") and not callable(getattr(obj, name)))] pt = prettytable.PrettyTable([property_label, value_label], caching=False) pt.align = "l" for field_name in fields: if field_name in formatters: data = formatters[field_name](obj) else: field = field_name if normalize_field_names: if field not in mixed_case_fields: field = field_name.lower() field = field.replace(" ", "_").replace("-", "_") if isinstance(obj, dict): data = obj.get(field, "") else: data = getattr(obj, field, "") # convert dict to str to check length if isinstance(data, (dict, list)): data = json.dumps(data) if wrap > 0: data = textwrap.fill(str(data), wrap) # if value has a newline, add in multiple rows # e.g. fault with stacktrace if (data and isinstance(data, str) and (r"\n" in data or "\r" in data)): # "\r" would break the table, so remove it. if "\r" in data: data = data.replace("\r", "") lines = data.strip().split(r"\n") col1 = field_name for line in lines: pt.add_row([col1, line]) col1 = "" else: if data is None: data = "-" pt.add_row([field_name, data]) table_body = pt.get_string(header=print_header, border=print_border) + "\n" table_header = "" if table_label: table_width = table_body.index("\n") table_header = make_table_header(table_label, table_width) table_header += "\n" if table_header: out.write(encodeutils.safe_encode(table_header).decode()) out.write(encodeutils.safe_encode(table_body).decode())
[ "def", "print_dict", "(", "obj", ",", "fields", "=", "None", ",", "formatters", "=", "None", ",", "mixed_case_fields", "=", "False", ",", "normalize_field_names", "=", "False", ",", "property_label", "=", "\"Property\"", ",", "value_label", "=", "\"Value\"", "...
https://github.com/openstack/rally/blob/58b12c2e0bfa541bdb038be6e1679c5117b98484/rally/cli/cliutils.py#L171-L253
pyglet/pyglet
2833c1df902ca81aeeffa786c12e7e87d402434b
pyglet/media/drivers/xaudio2/lib_xaudio2.py
python
load_xaudio2
(dll_name)
return xaudio2_lib, x3d_lib
This will attempt to load a version of XAudio2. Versions supported: 2.9, 2.8. While Windows 8 ships with 2.8 and Windows 10 ships with version 2.9, it is possible to install 2.9 on 8/8.1.
This will attempt to load a version of XAudio2. Versions supported: 2.9, 2.8. While Windows 8 ships with 2.8 and Windows 10 ships with version 2.9, it is possible to install 2.9 on 8/8.1.
[ "This", "will", "attempt", "to", "load", "a", "version", "of", "XAudio2", ".", "Versions", "supported", ":", "2", ".", "9", "2", ".", "8", ".", "While", "Windows", "8", "ships", "with", "2", ".", "8", "and", "Windows", "10", "ships", "with", "version...
def load_xaudio2(dll_name): """This will attempt to load a version of XAudio2. Versions supported: 2.9, 2.8. While Windows 8 ships with 2.8 and Windows 10 ships with version 2.9, it is possible to install 2.9 on 8/8.1. """ xaudio2 = dll_name # System32 and SysWOW64 folders are opposite perception in Windows x64. # System32 = x64 dll's | SysWOW64 = x86 dlls # By default ctypes only seems to look in system32 regardless of Python architecture, which has x64 dlls. if platform.architecture()[0] == '32bit': if platform.machine().endswith('64'): # Machine is 64 bit, Python is 32 bit. xaudio2 = os.path.join(os.environ['WINDIR'], 'SysWOW64', '{}.dll'.format(xaudio2)) xaudio2_lib = ctypes.windll.LoadLibrary(xaudio2) # Somehow x3d uses different calling structure than the rest of the DLL; Only affects 32 bit? Microsoft... x3d_lib = ctypes.cdll.LoadLibrary(xaudio2) return xaudio2_lib, x3d_lib
[ "def", "load_xaudio2", "(", "dll_name", ")", ":", "xaudio2", "=", "dll_name", "# System32 and SysWOW64 folders are opposite perception in Windows x64.", "# System32 = x64 dll's | SysWOW64 = x86 dlls", "# By default ctypes only seems to look in system32 regardless of Python architecture, which ...
https://github.com/pyglet/pyglet/blob/2833c1df902ca81aeeffa786c12e7e87d402434b/pyglet/media/drivers/xaudio2/lib_xaudio2.py#L12-L28
ChenRocks/UNITER
1dbfa62bb8ddb1f2b11d20775ce324c5e45a3ab4
data/nlvr2.py
python
Nlvr2PairedDataset.__getitem__
(self, i)
return tuple(outs), target
[[txt, img1], [txt, img2]]
[[txt, img1], [txt, img2]]
[ "[[", "txt", "img1", "]", "[", "txt", "img2", "]]" ]
def __getitem__(self, i): """ [[txt, img1], [txt, img2]] """ example = super().__getitem__(i) target = example['target'] outs = [] for i, img in enumerate(example['img_fname']): img_feat, img_pos_feat, num_bb = self._get_img_feat(img) # text input input_ids = copy.deepcopy(example['input_ids']) input_ids = [self.txt_db.cls_] + input_ids + [self.txt_db.sep] attn_masks = [1] * (len(input_ids) + num_bb) input_ids = torch.tensor(input_ids) attn_masks = torch.tensor(attn_masks) if self.use_img_type: img_type_ids = torch.tensor([i+1]*num_bb) else: img_type_ids = None outs.append((input_ids, img_feat, img_pos_feat, attn_masks, img_type_ids)) return tuple(outs), target
[ "def", "__getitem__", "(", "self", ",", "i", ")", ":", "example", "=", "super", "(", ")", ".", "__getitem__", "(", "i", ")", "target", "=", "example", "[", "'target'", "]", "outs", "=", "[", "]", "for", "i", ",", "img", "in", "enumerate", "(", "e...
https://github.com/ChenRocks/UNITER/blob/1dbfa62bb8ddb1f2b11d20775ce324c5e45a3ab4/data/nlvr2.py#L33-L58
PyMySQL/mysqlclient
2316313fc6777591494e870ba0c5da0d3dcd6dc6
MySQLdb/connections.py
python
Connection.literal
(self, o)
return s
If o is a single object, returns an SQL literal as a string. If o is a non-string sequence, the items of the sequence are converted and returned as a sequence. Non-standard. For internal use; do not use this in your applications.
If o is a single object, returns an SQL literal as a string. If o is a non-string sequence, the items of the sequence are converted and returned as a sequence.
[ "If", "o", "is", "a", "single", "object", "returns", "an", "SQL", "literal", "as", "a", "string", ".", "If", "o", "is", "a", "non", "-", "string", "sequence", "the", "items", "of", "the", "sequence", "are", "converted", "and", "returned", "as", "a", ...
def literal(self, o): """If o is a single object, returns an SQL literal as a string. If o is a non-string sequence, the items of the sequence are converted and returned as a sequence. Non-standard. For internal use; do not use this in your applications. """ if isinstance(o, str): s = self.string_literal(o.encode(self.encoding)) elif isinstance(o, bytearray): s = self._bytes_literal(o) elif isinstance(o, bytes): s = self._bytes_literal(o) elif isinstance(o, (tuple, list)): s = self._tuple_literal(o) else: s = self.escape(o, self.encoders) if isinstance(s, str): s = s.encode(self.encoding) assert isinstance(s, bytes) return s
[ "def", "literal", "(", "self", ",", "o", ")", ":", "if", "isinstance", "(", "o", ",", "str", ")", ":", "s", "=", "self", ".", "string_literal", "(", "o", ".", "encode", "(", "self", ".", "encoding", ")", ")", "elif", "isinstance", "(", "o", ",", ...
https://github.com/PyMySQL/mysqlclient/blob/2316313fc6777591494e870ba0c5da0d3dcd6dc6/MySQLdb/connections.py#L266-L287
python-discord/bot
26c5587ac13e5414361bb6e7ada42983b81014d2
bot/rules/burst_shared.py
python
apply
( last_message: Message, recent_messages: List[Message], config: Dict[str, int] )
return None
Detects repeated messages sent by multiple users.
Detects repeated messages sent by multiple users.
[ "Detects", "repeated", "messages", "sent", "by", "multiple", "users", "." ]
async def apply( last_message: Message, recent_messages: List[Message], config: Dict[str, int] ) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]: """Detects repeated messages sent by multiple users.""" total_recent = len(recent_messages) if total_recent > config['max']: return ( f"sent {total_recent} messages in {config['interval']}s", set(msg.author for msg in recent_messages), recent_messages ) return None
[ "async", "def", "apply", "(", "last_message", ":", "Message", ",", "recent_messages", ":", "List", "[", "Message", "]", ",", "config", ":", "Dict", "[", "str", ",", "int", "]", ")", "->", "Optional", "[", "Tuple", "[", "str", ",", "Iterable", "[", "M...
https://github.com/python-discord/bot/blob/26c5587ac13e5414361bb6e7ada42983b81014d2/bot/rules/burst_shared.py#L6-L18
HypoX64/DeepMosaics
b311aaac319439a0a1e8004b4a64c4222c55f38c
models/pix2pix_model.py
python
ResnetBlock.forward
(self, x)
return out
Forward function (with skip connections)
Forward function (with skip connections)
[ "Forward", "function", "(", "with", "skip", "connections", ")" ]
def forward(self, x): """Forward function (with skip connections)""" out = x + self.conv_block(x) # add skip connections return out
[ "def", "forward", "(", "self", ",", "x", ")", ":", "out", "=", "x", "+", "self", ".", "conv_block", "(", "x", ")", "# add skip connections", "return", "out" ]
https://github.com/HypoX64/DeepMosaics/blob/b311aaac319439a0a1e8004b4a64c4222c55f38c/models/pix2pix_model.py#L449-L452
PhoenixDL/rising
6de193375dcaac35605163c35cec259c9a2116d1
rising/transforms/format.py
python
MapToSeq.forward
(self, **data)
return tuple(data[_k] for _k in self.keys)
Convert input Args: data: input dict Returns: tuple: mapped data
Convert input
[ "Convert", "input" ]
def forward(self, **data) -> tuple: """ Convert input Args: data: input dict Returns: tuple: mapped data """ return tuple(data[_k] for _k in self.keys)
[ "def", "forward", "(", "self", ",", "*", "*", "data", ")", "->", "tuple", ":", "return", "tuple", "(", "data", "[", "_k", "]", "for", "_k", "in", "self", ".", "keys", ")" ]
https://github.com/PhoenixDL/rising/blob/6de193375dcaac35605163c35cec259c9a2116d1/rising/transforms/format.py#L27-L37
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/asn1crypto-0.24.0/asn1crypto/keys.py
python
PrivateKeyInfo.fingerprint
(self)
return self._fingerprint
Creates a fingerprint that can be compared with a public key to see if the two form a pair. This fingerprint is not compatible with fingerprints generated by any other software. :return: A byte string that is a sha256 hash of selected components (based on the key type)
Creates a fingerprint that can be compared with a public key to see if the two form a pair.
[ "Creates", "a", "fingerprint", "that", "can", "be", "compared", "with", "a", "public", "key", "to", "see", "if", "the", "two", "form", "a", "pair", "." ]
def fingerprint(self): """ Creates a fingerprint that can be compared with a public key to see if the two form a pair. This fingerprint is not compatible with fingerprints generated by any other software. :return: A byte string that is a sha256 hash of selected components (based on the key type) """ if self._fingerprint is None: params = self['private_key_algorithm']['parameters'] key = self['private_key'].parsed if self.algorithm == 'rsa': to_hash = '%d:%d' % ( key['modulus'].native, key['public_exponent'].native, ) elif self.algorithm == 'dsa': public_key = self.public_key to_hash = '%d:%d:%d:%d' % ( params['p'].native, params['q'].native, params['g'].native, public_key.native, ) elif self.algorithm == 'ec': public_key = key['public_key'].native if public_key is None: public_key = self.public_key.native if params.name == 'named': to_hash = '%s:' % params.chosen.native to_hash = to_hash.encode('utf-8') to_hash += public_key elif params.name == 'implicit_ca': to_hash = public_key elif params.name == 'specified': to_hash = '%s:' % params.chosen['field_id']['parameters'].native to_hash = to_hash.encode('utf-8') to_hash += b':' + params.chosen['curve']['a'].native to_hash += b':' + params.chosen['curve']['b'].native to_hash += public_key if isinstance(to_hash, str_cls): to_hash = to_hash.encode('utf-8') self._fingerprint = hashlib.sha256(to_hash).digest() return self._fingerprint
[ "def", "fingerprint", "(", "self", ")", ":", "if", "self", ".", "_fingerprint", "is", "None", ":", "params", "=", "self", "[", "'private_key_algorithm'", "]", "[", "'parameters'", "]", "key", "=", "self", "[", "'private_key'", "]", ".", "parsed", "if", "...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/asn1crypto-0.24.0/asn1crypto/keys.py#L826-L883
frenetic-lang/pyretic
30462692f3e9675158862755955b44f3a37ea21c
pyretic/core/language.py
python
CountBucket.clear_existing_rule_flag
(self, entry)
Clear the "existing rule" flag for the provided entry in self.matches. This method should only be called in the context of holding the bucket's in_update_cv since it updates the matches structure.
Clear the "existing rule" flag for the provided entry in self.matches. This method should only be called in the context of holding the bucket's in_update_cv since it updates the matches structure.
[ "Clear", "the", "existing", "rule", "flag", "for", "the", "provided", "entry", "in", "self", ".", "matches", ".", "This", "method", "should", "only", "be", "called", "in", "the", "context", "of", "holding", "the", "bucket", "s", "in_update_cv", "since", "i...
def clear_existing_rule_flag(self, entry): """Clear the "existing rule" flag for the provided entry in self.matches. This method should only be called in the context of holding the bucket's in_update_cv since it updates the matches structure. """ assert k in self.matches self.matches[k].existing_rule = False
[ "def", "clear_existing_rule_flag", "(", "self", ",", "entry", ")", ":", "assert", "k", "in", "self", ".", "matches", "self", ".", "matches", "[", "k", "]", ".", "existing_rule", "=", "False" ]
https://github.com/frenetic-lang/pyretic/blob/30462692f3e9675158862755955b44f3a37ea21c/pyretic/core/language.py#L1306-L1313
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/pandas/core/frame.py
python
DataFrame.from_items
(cls, items, columns=None, orient='columns')
Convert (key, value) pairs to DataFrame. The keys will be the axis index (usually the columns, but depends on the specified orientation). The values should be arrays or Series. Parameters ---------- items : sequence of (key, value) pairs Values should be arrays or Series. columns : sequence of column labels, optional Must be passed if orient='index'. orient : {'columns', 'index'}, default 'columns' The "orientation" of the data. If the keys of the input correspond to column labels, pass 'columns' (default). Otherwise if the keys correspond to the index, pass 'index'. Returns ------- frame : DataFrame
Convert (key, value) pairs to DataFrame. The keys will be the axis index (usually the columns, but depends on the specified orientation). The values should be arrays or Series.
[ "Convert", "(", "key", "value", ")", "pairs", "to", "DataFrame", ".", "The", "keys", "will", "be", "the", "axis", "index", "(", "usually", "the", "columns", "but", "depends", "on", "the", "specified", "orientation", ")", ".", "The", "values", "should", "...
def from_items(cls, items, columns=None, orient='columns'): """ Convert (key, value) pairs to DataFrame. The keys will be the axis index (usually the columns, but depends on the specified orientation). The values should be arrays or Series. Parameters ---------- items : sequence of (key, value) pairs Values should be arrays or Series. columns : sequence of column labels, optional Must be passed if orient='index'. orient : {'columns', 'index'}, default 'columns' The "orientation" of the data. If the keys of the input correspond to column labels, pass 'columns' (default). Otherwise if the keys correspond to the index, pass 'index'. Returns ------- frame : DataFrame """ keys, values = lzip(*items) if orient == 'columns': if columns is not None: columns = _ensure_index(columns) idict = dict(items) if len(idict) < len(items): if not columns.equals(_ensure_index(keys)): raise ValueError('With non-unique item names, passed ' 'columns must be identical') arrays = values else: arrays = [idict[k] for k in columns if k in idict] else: columns = _ensure_index(keys) arrays = values return cls._from_arrays(arrays, columns, None) elif orient == 'index': if columns is None: raise TypeError("Must pass columns with orient='index'") keys = _ensure_index(keys) arr = np.array(values, dtype=object).T data = [lib.maybe_convert_objects(v) for v in arr] return cls._from_arrays(data, columns, keys) else: # pragma: no cover raise ValueError("'orient' must be either 'columns' or 'index'")
[ "def", "from_items", "(", "cls", ",", "items", ",", "columns", "=", "None", ",", "orient", "=", "'columns'", ")", ":", "keys", ",", "values", "=", "lzip", "(", "*", "items", ")", "if", "orient", "==", "'columns'", ":", "if", "columns", "is", "not", ...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pandas/core/frame.py#L1116-L1167
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/cluster_complex.py
python
ClusterComplexFacet.upper_cluster
(self)
return [beta for beta in self.cluster() if sum(beta) > 0]
Return the part of the cluster that contains positive roots EXAMPLES:: sage: C = ClusterComplex(['A', 2]) sage: F = C((0, 1)) sage: F.upper_cluster() []
Return the part of the cluster that contains positive roots
[ "Return", "the", "part", "of", "the", "cluster", "that", "contains", "positive", "roots" ]
def upper_cluster(self): """ Return the part of the cluster that contains positive roots EXAMPLES:: sage: C = ClusterComplex(['A', 2]) sage: F = C((0, 1)) sage: F.upper_cluster() [] """ return [beta for beta in self.cluster() if sum(beta) > 0]
[ "def", "upper_cluster", "(", "self", ")", ":", "return", "[", "beta", "for", "beta", "in", "self", ".", "cluster", "(", ")", "if", "sum", "(", "beta", ")", ">", "0", "]" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/cluster_complex.py#L78-L89
Droidtown/ArticutAPI
ee415bb30c9722a85334d54d7015d5ad3870205f
ArticutAPI/WS_ArticutAPI.py
python
WS_Articut.getQuestionLIST
(self, parseResultDICT, indexWithPOS=True)
return self.POS.getQuestionLIST(parseResultDICT, indexWithPOS)
取出斷詞結果中含有 (CLAUSE_Q) 標籤的句子。 此處指的是 <CLAUSE_AnotAQ>: A-not-A 問句 <CLAUSE_YesNoQ>: 是非問句 <CLAUSE_WhoQ">: 「誰」問句 <CLAUSE_WhatQ>: 「物」問句 <CLAUSE_WhereQ>: 「何地」問句 <CLAUSE_WhenQ>: 「何時」問句 <CLAUSE_HowQ>: 「程度/過程」問句 <CLAUSE_WhyQ>: 「原因」問句 每個句子內若有 <CLAUSE_Q> 標籤,整個句子將會存進 list。
取出斷詞結果中含有 (CLAUSE_Q) 標籤的句子。 此處指的是 <CLAUSE_AnotAQ>: A-not-A 問句 <CLAUSE_YesNoQ>: 是非問句 <CLAUSE_WhoQ">: 「誰」問句 <CLAUSE_WhatQ>: 「物」問句 <CLAUSE_WhereQ>: 「何地」問句 <CLAUSE_WhenQ>: 「何時」問句 <CLAUSE_HowQ>: 「程度/過程」問句 <CLAUSE_WhyQ>: 「原因」問句 每個句子內若有 <CLAUSE_Q> 標籤,整個句子將會存進 list。
[ "取出斷詞結果中含有", "(", "CLAUSE_Q", ")", "標籤的句子。", "此處指的是", "<CLAUSE_AnotAQ", ">", ":", "A", "-", "not", "-", "A", "問句", "<CLAUSE_YesNoQ", ">", ":", "是非問句", "<CLAUSE_WhoQ", ">", ":", "「誰」問句", "<CLAUSE_WhatQ", ">", ":", "「物」問句", "<CLAUSE_WhereQ", ">", ":", "「何地」問...
def getQuestionLIST(self, parseResultDICT, indexWithPOS=True): ''' 取出斷詞結果中含有 (CLAUSE_Q) 標籤的句子。 此處指的是 <CLAUSE_AnotAQ>: A-not-A 問句 <CLAUSE_YesNoQ>: 是非問句 <CLAUSE_WhoQ">: 「誰」問句 <CLAUSE_WhatQ>: 「物」問句 <CLAUSE_WhereQ>: 「何地」問句 <CLAUSE_WhenQ>: 「何時」問句 <CLAUSE_HowQ>: 「程度/過程」問句 <CLAUSE_WhyQ>: 「原因」問句 每個句子內若有 <CLAUSE_Q> 標籤,整個句子將會存進 list。 ''' return self.POS.getQuestionLIST(parseResultDICT, indexWithPOS)
[ "def", "getQuestionLIST", "(", "self", ",", "parseResultDICT", ",", "indexWithPOS", "=", "True", ")", ":", "return", "self", ".", "POS", ".", "getQuestionLIST", "(", "parseResultDICT", ",", "indexWithPOS", ")" ]
https://github.com/Droidtown/ArticutAPI/blob/ee415bb30c9722a85334d54d7015d5ad3870205f/ArticutAPI/WS_ArticutAPI.py#L311-L325
altair-viz/altair
fb9e82eb378f68bad7a10c639f95e9a3991ac18d
altair/vegalite/v3/api.py
python
TopLevelMixin._set_resolve
(self, **kwargs)
return copy
Copy the chart and update the resolve property with kwargs
Copy the chart and update the resolve property with kwargs
[ "Copy", "the", "chart", "and", "update", "the", "resolve", "property", "with", "kwargs" ]
def _set_resolve(self, **kwargs): """Copy the chart and update the resolve property with kwargs""" if not hasattr(self, "resolve"): raise ValueError( "{} object has no attribute " "'resolve'".format(self.__class__) ) copy = self.copy(deep=["resolve"]) if copy.resolve is Undefined: copy.resolve = core.Resolve() for key, val in kwargs.items(): copy.resolve[key] = val return copy
[ "def", "_set_resolve", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"resolve\"", ")", ":", "raise", "ValueError", "(", "\"{} object has no attribute \"", "\"'resolve'\"", ".", "format", "(", "self", ".", "__clas...
https://github.com/altair-viz/altair/blob/fb9e82eb378f68bad7a10c639f95e9a3991ac18d/altair/vegalite/v3/api.py#L1515-L1526
shaneshixiang/rllabplusplus
4d55f96ec98e3fe025b7991945e3e6a54fd5449f
sandbox/rocky/tf/regressors/categorical_mlp_regressor.py
python
CategoricalMLPRegressor.__init__
( self, name, input_shape, output_dim, prob_network=None, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, optimizer=None, tr_optimizer=None, use_trust_region=True, step_size=0.01, normalize_inputs=True, no_initial_trust_region=True, )
:param input_shape: Shape of the input data. :param output_dim: Dimension of output. :param hidden_sizes: Number of hidden units of each layer of the mean network. :param hidden_nonlinearity: Non-linearity used for each layer of the mean network. :param optimizer: Optimizer for minimizing the negative log-likelihood. :param use_trust_region: Whether to use trust region constraint. :param step_size: KL divergence constraint for each iteration
:param input_shape: Shape of the input data. :param output_dim: Dimension of output. :param hidden_sizes: Number of hidden units of each layer of the mean network. :param hidden_nonlinearity: Non-linearity used for each layer of the mean network. :param optimizer: Optimizer for minimizing the negative log-likelihood. :param use_trust_region: Whether to use trust region constraint. :param step_size: KL divergence constraint for each iteration
[ ":", "param", "input_shape", ":", "Shape", "of", "the", "input", "data", ".", ":", "param", "output_dim", ":", "Dimension", "of", "output", ".", ":", "param", "hidden_sizes", ":", "Number", "of", "hidden", "units", "of", "each", "layer", "of", "the", "me...
def __init__( self, name, input_shape, output_dim, prob_network=None, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, optimizer=None, tr_optimizer=None, use_trust_region=True, step_size=0.01, normalize_inputs=True, no_initial_trust_region=True, ): """ :param input_shape: Shape of the input data. :param output_dim: Dimension of output. :param hidden_sizes: Number of hidden units of each layer of the mean network. :param hidden_nonlinearity: Non-linearity used for each layer of the mean network. :param optimizer: Optimizer for minimizing the negative log-likelihood. :param use_trust_region: Whether to use trust region constraint. :param step_size: KL divergence constraint for each iteration """ Serializable.quick_init(self, locals()) with tf.variable_scope(name): if optimizer is None: optimizer = LbfgsOptimizer(name="optimizer") if tr_optimizer is None: tr_optimizer = ConjugateGradientOptimizer() self.output_dim = output_dim self.optimizer = optimizer self.tr_optimizer = tr_optimizer if prob_network is None: prob_network = MLP( input_shape=input_shape, output_dim=output_dim, hidden_sizes=hidden_sizes, hidden_nonlinearity=hidden_nonlinearity, output_nonlinearity=tf.nn.softmax, name="prob_network" ) l_prob = prob_network.output_layer LayersPowered.__init__(self, [l_prob]) xs_var = prob_network.input_layer.input_var ys_var = tf.placeholder(dtype=tf.float32, shape=[None, output_dim], name="ys") old_prob_var = tf.placeholder(dtype=tf.float32, shape=[None, output_dim], name="old_prob") x_mean_var = tf.get_variable( name="x_mean", shape=(1,) + input_shape, initializer=tf.constant_initializer(0., dtype=tf.float32) ) x_std_var = tf.get_variable( name="x_std", shape=(1,) + input_shape, initializer=tf.constant_initializer(1., dtype=tf.float32) ) normalized_xs_var = (xs_var - x_mean_var) / x_std_var prob_var = L.get_output(l_prob, {prob_network.input_layer: normalized_xs_var}) old_info_vars = dict(prob=old_prob_var) info_vars = dict(prob=prob_var) dist = self._dist = Categorical(output_dim) mean_kl = tf.reduce_mean(dist.kl_sym(old_info_vars, info_vars)) loss = - tf.reduce_mean(dist.log_likelihood_sym(ys_var, info_vars)) predicted = tensor_utils.to_onehot_sym(tf.argmax(prob_var, axis=1), output_dim) self.prob_network = prob_network self.f_predict = tensor_utils.compile_function([xs_var], predicted) self.f_prob = tensor_utils.compile_function([xs_var], prob_var) self.l_prob = l_prob self.optimizer.update_opt(loss=loss, target=self, network_outputs=[prob_var], inputs=[xs_var, ys_var]) self.tr_optimizer.update_opt(loss=loss, target=self, network_outputs=[prob_var], inputs=[xs_var, ys_var, old_prob_var], leq_constraint=(mean_kl, step_size) ) self.use_trust_region = use_trust_region self.name = name self.normalize_inputs = normalize_inputs self.x_mean_var = x_mean_var self.x_std_var = x_std_var self.first_optimized = not no_initial_trust_region
[ "def", "__init__", "(", "self", ",", "name", ",", "input_shape", ",", "output_dim", ",", "prob_network", "=", "None", ",", "hidden_sizes", "=", "(", "32", ",", "32", ")", ",", "hidden_nonlinearity", "=", "tf", ".", "nn", ".", "tanh", ",", "optimizer", ...
https://github.com/shaneshixiang/rllabplusplus/blob/4d55f96ec98e3fe025b7991945e3e6a54fd5449f/sandbox/rocky/tf/regressors/categorical_mlp_regressor.py#L28-L125
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/core/strings.py
python
str_translate
(arr, table, deletechars=None)
return _na_map(f, arr)
Map all characters in the string through the given mapping table. Equivalent to standard :meth:`str.translate`. Note that the optional argument deletechars is only valid if you are using python 2. For python 3, character deletion should be specified via the table argument. Parameters ---------- table : dict (python 3), str or None (python 2) In python 3, table is a mapping of Unicode ordinals to Unicode ordinals, strings, or None. Unmapped characters are left untouched. Characters mapped to None are deleted. :meth:`str.maketrans` is a helper function for making translation tables. In python 2, table is either a string of length 256 or None. If the table argument is None, no translation is applied and the operation simply removes the characters in deletechars. :func:`string.maketrans` is a helper function for making translation tables. deletechars : str, optional (python 2) A string of characters to delete. This argument is only valid in python 2. Returns ------- translated : Series/Index of objects
Map all characters in the string through the given mapping table. Equivalent to standard :meth:`str.translate`. Note that the optional argument deletechars is only valid if you are using python 2. For python 3, character deletion should be specified via the table argument.
[ "Map", "all", "characters", "in", "the", "string", "through", "the", "given", "mapping", "table", ".", "Equivalent", "to", "standard", ":", "meth", ":", "str", ".", "translate", ".", "Note", "that", "the", "optional", "argument", "deletechars", "is", "only",...
def str_translate(arr, table, deletechars=None): """ Map all characters in the string through the given mapping table. Equivalent to standard :meth:`str.translate`. Note that the optional argument deletechars is only valid if you are using python 2. For python 3, character deletion should be specified via the table argument. Parameters ---------- table : dict (python 3), str or None (python 2) In python 3, table is a mapping of Unicode ordinals to Unicode ordinals, strings, or None. Unmapped characters are left untouched. Characters mapped to None are deleted. :meth:`str.maketrans` is a helper function for making translation tables. In python 2, table is either a string of length 256 or None. If the table argument is None, no translation is applied and the operation simply removes the characters in deletechars. :func:`string.maketrans` is a helper function for making translation tables. deletechars : str, optional (python 2) A string of characters to delete. This argument is only valid in python 2. Returns ------- translated : Series/Index of objects """ if deletechars is None: f = lambda x: x.translate(table) else: if compat.PY3: raise ValueError("deletechars is not a valid argument for " "str.translate in python 3. You should simply " "specify character deletions in the table " "argument") f = lambda x: x.translate(table, deletechars) return _na_map(f, arr)
[ "def", "str_translate", "(", "arr", ",", "table", ",", "deletechars", "=", "None", ")", ":", "if", "deletechars", "is", "None", ":", "f", "=", "lambda", "x", ":", "x", ".", "translate", "(", "table", ")", "else", ":", "if", "compat", ".", "PY3", ":...
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/core/strings.py#L1592-L1627
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/PIL/PsdImagePlugin.py
python
PsdImageFile._close__fp
(self)
[]
def _close__fp(self): try: if self.__fp != self.fp: self.__fp.close() except AttributeError: pass finally: self.__fp = None
[ "def", "_close__fp", "(", "self", ")", ":", "try", ":", "if", "self", ".", "__fp", "!=", "self", ".", "fp", ":", "self", ".", "__fp", ".", "close", "(", ")", "except", "AttributeError", ":", "pass", "finally", ":", "self", ".", "__fp", "=", "None" ...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/PIL/PsdImagePlugin.py#L168-L175
pyload/pyload
4410827ca7711f1a3cf91a0b11e967b81bbbcaa2
src/pyload/plugins/addons/UpdateManager.py
python
UpdateManager.update
(self)
Check for updates.
Check for updates.
[ "Check", "for", "updates", "." ]
def update(self): """ Check for updates. """ if self._update() != 2 or not self.config.get("autorestart"): return if not self.pyload.api.status_downloads(): self.pyload.api.restart() else: self.log_warning( self._("pyLoad restart scheduled"), self._( "Downloads are active, pyLoad restart postponed once the download is done" ), ) self.pyload.api.pause_server() self.do_restart = True
[ "def", "update", "(", "self", ")", ":", "if", "self", ".", "_update", "(", ")", "!=", "2", "or", "not", "self", ".", "config", ".", "get", "(", "\"autorestart\"", ")", ":", "return", "if", "not", "self", ".", "pyload", ".", "api", ".", "status_down...
https://github.com/pyload/pyload/blob/4410827ca7711f1a3cf91a0b11e967b81bbbcaa2/src/pyload/plugins/addons/UpdateManager.py#L163-L180
spotify/luigi
c3b66f4a5fa7eaa52f9a72eb6704b1049035c789
luigi/contrib/salesforce.py
python
SalesforceAPI.get_batch_results
(self, job_id, batch_id)
return self.get_batch_result_ids(job_id, batch_id)[0]
DEPRECATED: Use `get_batch_result_ids`
DEPRECATED: Use `get_batch_result_ids`
[ "DEPRECATED", ":", "Use", "get_batch_result_ids" ]
def get_batch_results(self, job_id, batch_id): """ DEPRECATED: Use `get_batch_result_ids` """ warnings.warn("get_batch_results is deprecated and only returns one batch result. Please use get_batch_result_ids") return self.get_batch_result_ids(job_id, batch_id)[0]
[ "def", "get_batch_results", "(", "self", ",", "job_id", ",", "batch_id", ")", ":", "warnings", ".", "warn", "(", "\"get_batch_results is deprecated and only returns one batch result. Please use get_batch_result_ids\"", ")", "return", "self", ".", "get_batch_result_ids", "(", ...
https://github.com/spotify/luigi/blob/c3b66f4a5fa7eaa52f9a72eb6704b1049035c789/luigi/contrib/salesforce.py#L509-L514
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/venv/lib/python3.7/site-packages/pip/_vendor/cachecontrol/heuristics.py
python
BaseHeuristic.update_headers
(self, response)
return {}
Update the response headers with any new headers. NOTE: This SHOULD always include some Warning header to signify that the response was cached by the client, not by way of the provided headers.
Update the response headers with any new headers.
[ "Update", "the", "response", "headers", "with", "any", "new", "headers", "." ]
def update_headers(self, response): """Update the response headers with any new headers. NOTE: This SHOULD always include some Warning header to signify that the response was cached by the client, not by way of the provided headers. """ return {}
[ "def", "update_headers", "(", "self", ",", "response", ")", ":", "return", "{", "}" ]
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/venv/lib/python3.7/site-packages/pip/_vendor/cachecontrol/heuristics.py#L33-L40
tmadl/semisup-learn
483698be0453f08e550a4c705fc7ad522708708c
methods/qns3vm.py
python
QN_S3VM_Dense.getPredictions
(self, X, real_valued=False)
Computes the predicted labels for a given set of patterns Keyword arguments: X -- The set of patterns real_valued -- If True, then the real prediction values are returned Returns: The predictions for the list X of patterns.
Computes the predicted labels for a given set of patterns
[ "Computes", "the", "predicted", "labels", "for", "a", "given", "set", "of", "patterns" ]
def getPredictions(self, X, real_valued=False): """ Computes the predicted labels for a given set of patterns Keyword arguments: X -- The set of patterns real_valued -- If True, then the real prediction values are returned Returns: The predictions for the list X of patterns. """ KNR = self.__kernel.computeKernelMatrix(X, self.__Xreg) KNU_bar = self.__kernel.computeKernelMatrix(X, self.__X_u_subset, symmetric=False) KNU_bar_horizontal_sum = (1.0 / len(self.__X_u_subset)) * KNU_bar.sum(axis=1) KNR = KNR - KNU_bar_horizontal_sum - self.__KU_barR_vertical_sum + self.__KU_barU_bar_sum preds = KNR * self.__c[0:self.__dim-1,:] + self.__c[self.__dim-1,:] if real_valued == True: return preds.flatten(1).tolist()[0] else: return np.sign(np.sign(preds)+0.1).flatten(1).tolist()[0]
[ "def", "getPredictions", "(", "self", ",", "X", ",", "real_valued", "=", "False", ")", ":", "KNR", "=", "self", ".", "__kernel", ".", "computeKernelMatrix", "(", "X", ",", "self", ".", "__Xreg", ")", "KNU_bar", "=", "self", ".", "__kernel", ".", "compu...
https://github.com/tmadl/semisup-learn/blob/483698be0453f08e550a4c705fc7ad522708708c/methods/qns3vm.py#L252-L271
machine-perception-robotics-group/attention_branch_network
ced1d97303792ac6d56442571d71bb0572b3efd8
models/cifar/resnext.py
python
resnext
(**kwargs)
return model
Constructs a ResNeXt.
Constructs a ResNeXt.
[ "Constructs", "a", "ResNeXt", "." ]
def resnext(**kwargs): """Constructs a ResNeXt. """ model = CifarResNeXt(**kwargs) return model
[ "def", "resnext", "(", "*", "*", "kwargs", ")", ":", "model", "=", "CifarResNeXt", "(", "*", "*", "kwargs", ")", "return", "model" ]
https://github.com/machine-perception-robotics-group/attention_branch_network/blob/ced1d97303792ac6d56442571d71bb0572b3efd8/models/cifar/resnext.py#L152-L156
Pyomo/pyomo
dbd4faee151084f343b893cc2b0c04cf2b76fd92
pyomo/contrib/pynumero/interfaces/nlp.py
python
ExtendedNLP.n_ineq_constraints
(self)
Returns number of inequality constraints
Returns number of inequality constraints
[ "Returns", "number", "of", "inequality", "constraints" ]
def n_ineq_constraints(self): """ Returns number of inequality constraints """ pass
[ "def", "n_ineq_constraints", "(", "self", ")", ":", "pass" ]
https://github.com/Pyomo/pyomo/blob/dbd4faee151084f343b893cc2b0c04cf2b76fd92/pyomo/contrib/pynumero/interfaces/nlp.py#L384-L388
linuxerwang/rkflashkit
c6b422afa372bf1d498fcddb6a6b95360021d2a6
src/rkflashkit/main.py
python
MainWindow.__reboot_device
(self, widget)
[]
def __reboot_device(self, widget): # Reboot device device_info, = self.__device_liststore.get( self.__device_selector.get_active_iter(), 1) if confirm(self, MESSAGE_REBOOT): op = None try: op = rktalk.RkOperation(self.__logger, device_info[0], device_info[1]) op.reboot() finally: if op: del op
[ "def", "__reboot_device", "(", "self", ",", "widget", ")", ":", "# Reboot device", "device_info", ",", "=", "self", ".", "__device_liststore", ".", "get", "(", "self", ".", "__device_selector", ".", "get_active_iter", "(", ")", ",", "1", ")", "if", "confirm"...
https://github.com/linuxerwang/rkflashkit/blob/c6b422afa372bf1d498fcddb6a6b95360021d2a6/src/rkflashkit/main.py#L357-L367
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/patches.py
python
Arc.__init__
(self, xy, width, height, angle=0.0, theta1=0.0, theta2=360.0, **kwargs)
The following args are supported: *xy* center of ellipse *width* length of horizontal axis *height* length of vertical axis *angle* rotation in degrees (anti-clockwise) *theta1* starting angle of the arc in degrees *theta2* ending angle of the arc in degrees If *theta1* and *theta2* are not provided, the arc will form a complete ellipse. Valid kwargs are: %(Patch)s
The following args are supported:
[ "The", "following", "args", "are", "supported", ":" ]
def __init__(self, xy, width, height, angle=0.0, theta1=0.0, theta2=360.0, **kwargs): """ The following args are supported: *xy* center of ellipse *width* length of horizontal axis *height* length of vertical axis *angle* rotation in degrees (anti-clockwise) *theta1* starting angle of the arc in degrees *theta2* ending angle of the arc in degrees If *theta1* and *theta2* are not provided, the arc will form a complete ellipse. Valid kwargs are: %(Patch)s """ fill = kwargs.setdefault('fill', False) if fill: raise ValueError("Arc objects can not be filled") Ellipse.__init__(self, xy, width, height, angle, **kwargs) self.theta1 = theta1 self.theta2 = theta2 self._path = Path.arc(self.theta1, self.theta2)
[ "def", "__init__", "(", "self", ",", "xy", ",", "width", ",", "height", ",", "angle", "=", "0.0", ",", "theta1", "=", "0.0", ",", "theta2", "=", "360.0", ",", "*", "*", "kwargs", ")", ":", "fill", "=", "kwargs", ".", "setdefault", "(", "'fill'", ...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/matplotlib/patches.py#L1321-L1360
RasaHQ/rasa
54823b68c1297849ba7ae841a4246193cd1223a1
rasa/shared/nlu/training_data/training_data.py
python
TrainingData.persist
( self, dir_name: Text, filename: Text = DEFAULT_TRAINING_DATA_OUTPUT_PATH )
return {"training_data": relpath(nlu_data_file, dir_name)}
Persists this training data to disk and returns necessary information to load it again.
Persists this training data to disk and returns necessary information to load it again.
[ "Persists", "this", "training", "data", "to", "disk", "and", "returns", "necessary", "information", "to", "load", "it", "again", "." ]
def persist( self, dir_name: Text, filename: Text = DEFAULT_TRAINING_DATA_OUTPUT_PATH ) -> Dict[Text, Any]: """Persists this training data to disk and returns necessary information to load it again.""" if not os.path.exists(dir_name): os.makedirs(dir_name) nlu_data_file = os.path.join(dir_name, filename) self.persist_nlu(nlu_data_file) self.persist_nlg(self.get_nlg_persist_filename(nlu_data_file)) return {"training_data": relpath(nlu_data_file, dir_name)}
[ "def", "persist", "(", "self", ",", "dir_name", ":", "Text", ",", "filename", ":", "Text", "=", "DEFAULT_TRAINING_DATA_OUTPUT_PATH", ")", "->", "Dict", "[", "Text", ",", "Any", "]", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "dir_name", "...
https://github.com/RasaHQ/rasa/blob/54823b68c1297849ba7ae841a4246193cd1223a1/rasa/shared/nlu/training_data/training_data.py#L431-L444
PaddlePaddle/PGL
e48545f2814523c777b8a9a9188bf5a7f00d6e52
docs/markdown2rst.py
python
RestRenderer.footnotes
(self, text)
Wrapper for all footnotes. :param text: contents of all footnotes.
Wrapper for all footnotes.
[ "Wrapper", "for", "all", "footnotes", "." ]
def footnotes(self, text): """Wrapper for all footnotes. :param text: contents of all footnotes. """ if text: return '\n\n' + text else: return ''
[ "def", "footnotes", "(", "self", ",", "text", ")", ":", "if", "text", ":", "return", "'\\n\\n'", "+", "text", "else", ":", "return", "''" ]
https://github.com/PaddlePaddle/PGL/blob/e48545f2814523c777b8a9a9188bf5a7f00d6e52/docs/markdown2rst.py#L483-L491
stevearc/pypicloud
046126f0b2a692b7bd382ae5cd3bf7af2f58103c
pypicloud/access/base.py
python
get_pwd_context
( preferred_hash: Optional[str] = None, rounds: Optional[int] = None )
return LazyCryptContext(schemes=schemes, default=schemes[0], **default_rounds)
Create a passlib context for hashing passwords
Create a passlib context for hashing passwords
[ "Create", "a", "passlib", "context", "for", "hashing", "passwords" ]
def get_pwd_context( preferred_hash: Optional[str] = None, rounds: Optional[int] = None ) -> LazyCryptContext: """Create a passlib context for hashing passwords""" if preferred_hash is None or preferred_hash == "sha": preferred_hash = "sha256_crypt" if sys_bits < 64 else "sha512_crypt" if preferred_hash == "pbkdf2": preferred_hash = "pbkdf2_sha256" if sys_bits < 64 else "pbkdf2_sha512" if preferred_hash not in SCHEMES: raise Exception( "Password hash %r is not in the list of supported schemes" % preferred_hash ) # Put the preferred hash at the beginning of the schemes list schemes = list(SCHEMES) schemes.remove(preferred_hash) schemes.insert(0, preferred_hash) # Override the default rounds of the preferred hash, if provided default_rounds = dict(DEFAULT_ROUNDS) if rounds is not None: default_rounds[preferred_hash + "__default_rounds"] = rounds return LazyCryptContext(schemes=schemes, default=schemes[0], **default_rounds)
[ "def", "get_pwd_context", "(", "preferred_hash", ":", "Optional", "[", "str", "]", "=", "None", ",", "rounds", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "LazyCryptContext", ":", "if", "preferred_hash", "is", "None", "or", "preferred_hash", ...
https://github.com/stevearc/pypicloud/blob/046126f0b2a692b7bd382ae5cd3bf7af2f58103c/pypicloud/access/base.py#L40-L64
CGCookie/retopoflow
3d8b3a47d1d661f99ab0aeb21d31370bf15de35e
addon_common/common/ui_styling.py
python
_print_trie
(self, full_trie=True)
[]
def _print_trie(self, full_trie=True): def p(node_cur, depth): for
[ "def", "_print_trie", "(", "self", ",", "full_trie", "=", "True", ")", ":", "def", "p", "(", "node_cur", ",", "depth", ")", ":", "for" ]
https://github.com/CGCookie/retopoflow/blob/3d8b3a47d1d661f99ab0aeb21d31370bf15de35e/addon_common/common/ui_styling.py#L671-L673
SymbiFlow/prjxray
5349556bc2c230801d6df0cf11bccb9cfd171639
prjxray/lms_solver.py
python
dump_solution_to_csv
(fp, all_tags, all_bits, X)
Dumps solution data to CSV. Parameters ---------- fp: An open file or stream all_tags: List of considered tags. all_bits: List of considered bits. X: Matrix with raw solution (floats).
Dumps solution data to CSV.
[ "Dumps", "solution", "data", "to", "CSV", "." ]
def dump_solution_to_csv(fp, all_tags, all_bits, X): """ Dumps solution data to CSV. Parameters ---------- fp: An open file or stream all_tags: List of considered tags. all_bits: List of considered bits. X: Matrix with raw solution (floats). """ # Bits line = "," for bit in all_bits: line += bit + "," fp.write(line[:-1] + "\n") # Tags + numbers for r, tag in enumerate(all_tags): line = tag + "," for c in range(X.shape[1]): line += "%+e," % X[r, c] fp.write(line[:-1] + "\n")
[ "def", "dump_solution_to_csv", "(", "fp", ",", "all_tags", ",", "all_bits", ",", "X", ")", ":", "# Bits", "line", "=", "\",\"", "for", "bit", "in", "all_bits", ":", "line", "+=", "bit", "+", "\",\"", "fp", ".", "write", "(", "line", "[", ":", "-", ...
https://github.com/SymbiFlow/prjxray/blob/5349556bc2c230801d6df0cf11bccb9cfd171639/prjxray/lms_solver.py#L268-L296
RasaHQ/rasa
54823b68c1297849ba7ae841a4246193cd1223a1
rasa/core/actions/action.py
python
Action.__str__
(self)
return f"{self.__class__.__name__}('{self.name()}')"
Returns text representation of form.
Returns text representation of form.
[ "Returns", "text", "representation", "of", "form", "." ]
def __str__(self) -> Text: """Returns text representation of form.""" return f"{self.__class__.__name__}('{self.name()}')"
[ "def", "__str__", "(", "self", ")", "->", "Text", ":", "return", "f\"{self.__class__.__name__}('{self.name()}')\"" ]
https://github.com/RasaHQ/rasa/blob/54823b68c1297849ba7ae841a4246193cd1223a1/rasa/core/actions/action.py#L250-L252
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/mpl_toolkits/axisartist/axis_artist.py
python
TickLabels.set_axis_direction
(self, label_direction)
Adjust the text angle and text alignment of ticklabels according to the matplotlib convention. The *label_direction* must be one of [left, right, bottom, top]. ===================== ========== ========= ========== ========== property left bottom right top ===================== ========== ========= ========== ========== ticklabels angle 90 0 -90 180 ticklabel va center baseline center baseline ticklabel ha right center right center ===================== ========== ========= ========== ========== Note that the text angles are actually relative to (90 + angle of the direction to the ticklabel), which gives 0 for bottom axis.
Adjust the text angle and text alignment of ticklabels according to the matplotlib convention.
[ "Adjust", "the", "text", "angle", "and", "text", "alignment", "of", "ticklabels", "according", "to", "the", "matplotlib", "convention", "." ]
def set_axis_direction(self, label_direction): """ Adjust the text angle and text alignment of ticklabels according to the matplotlib convention. The *label_direction* must be one of [left, right, bottom, top]. ===================== ========== ========= ========== ========== property left bottom right top ===================== ========== ========= ========== ========== ticklabels angle 90 0 -90 180 ticklabel va center baseline center baseline ticklabel ha right center right center ===================== ========== ========= ========== ========== Note that the text angles are actually relative to (90 + angle of the direction to the ticklabel), which gives 0 for bottom axis. """ if label_direction not in ["left", "right", "top", "bottom"]: raise ValueError('direction must be one of "left", "right", "top", "bottom"') self._axis_direction = label_direction self.set_default_alignment(label_direction) self.set_default_angle(label_direction)
[ "def", "set_axis_direction", "(", "self", ",", "label_direction", ")", ":", "if", "label_direction", "not", "in", "[", "\"left\"", ",", "\"right\"", ",", "\"top\"", ",", "\"bottom\"", "]", ":", "raise", "ValueError", "(", "'direction must be one of \"left\", \"right...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/mpl_toolkits/axisartist/axis_artist.py#L580-L608
ganeti/ganeti
d340a9ddd12f501bef57da421b5f9b969a4ba905
qa/qa_rapi.py
python
TestTags
(kind, name, tags)
Tests .../tags resources.
Tests .../tags resources.
[ "Tests", "...", "/", "tags", "resources", "." ]
def TestTags(kind, name, tags): """Tests .../tags resources. """ if kind == constants.TAG_CLUSTER: uri = "/2/tags" elif kind == constants.TAG_NODE: uri = "/2/nodes/%s/tags" % name elif kind == constants.TAG_INSTANCE: uri = "/2/instances/%s/tags" % name elif kind == constants.TAG_NODEGROUP: uri = "/2/groups/%s/tags" % name elif kind == constants.TAG_NETWORK: uri = "/2/networks/%s/tags" % name else: raise errors.ProgrammerError("Unknown tag kind") def _VerifyTags(data): AssertEqual(sorted(tags), sorted(_FilterTags(data))) queryargs = "&".join("tag=%s" % i for i in tags) # Add tags (job_id, ) = _DoTests([ ("%s?%s" % (uri, queryargs), _VerifyReturnsJob, "PUT", None), ]) _WaitForRapiJob(job_id) # Retrieve tags _DoTests([ (uri, _VerifyTags, "GET", None), ]) # Remove tags (job_id, ) = _DoTests([ ("%s?%s" % (uri, queryargs), _VerifyReturnsJob, "DELETE", None), ]) _WaitForRapiJob(job_id)
[ "def", "TestTags", "(", "kind", ",", "name", ",", "tags", ")", ":", "if", "kind", "==", "constants", ".", "TAG_CLUSTER", ":", "uri", "=", "\"/2/tags\"", "elif", "kind", "==", "constants", ".", "TAG_NODE", ":", "uri", "=", "\"/2/nodes/%s/tags\"", "%", "na...
https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/qa/qa_rapi.py#L753-L790
albermax/innvestigate
db8a58e6a6d54d1a25618fe653954166782e891c
src/innvestigate/utils/keras/graph.py
python
pre_softmax_tensors
(Xs: Tensor, should_find_softmax: bool = True)
return ret
Finds the tensors that were preceeding a potential softmax.
Finds the tensors that were preceeding a potential softmax.
[ "Finds", "the", "tensors", "that", "were", "preceeding", "a", "potential", "softmax", "." ]
def pre_softmax_tensors(Xs: Tensor, should_find_softmax: bool = True) -> List[Tensor]: """Finds the tensors that were preceeding a potential softmax.""" softmax_found = False Xs = iutils.to_list(Xs) ret = [] for x in Xs: layer, node_index, _tensor_index = x._keras_history if kchecks.contains_activation(layer, activation="softmax"): softmax_found = True if isinstance(layer, keras.layers.Activation): ret.append(layer.get_input_at(node_index)) else: layer_wo_act = copy_layer_wo_activation(layer) ret.append(layer_wo_act(layer.get_input_at(node_index))) if should_find_softmax and not softmax_found: raise Exception("No softmax found.") return ret
[ "def", "pre_softmax_tensors", "(", "Xs", ":", "Tensor", ",", "should_find_softmax", ":", "bool", "=", "True", ")", "->", "List", "[", "Tensor", "]", ":", "softmax_found", "=", "False", "Xs", "=", "iutils", ".", "to_list", "(", "Xs", ")", "ret", "=", "[...
https://github.com/albermax/innvestigate/blob/db8a58e6a6d54d1a25618fe653954166782e891c/src/innvestigate/utils/keras/graph.py#L356-L375
geekan/scrapy-examples
edb1cb116bd6def65a6ef01f953b58eb43e54305
tutorial/tutorial/pipelines.py
python
JsonWithEncodingPipeline.process_item
(self, item, spider)
return item
[]
def process_item(self, item, spider): line = json.dumps(dict(item), ensure_ascii=False) + "\n" self.file.write(line) return item
[ "def", "process_item", "(", "self", ",", "item", ",", "spider", ")", ":", "line", "=", "json", ".", "dumps", "(", "dict", "(", "item", ")", ",", "ensure_ascii", "=", "False", ")", "+", "\"\\n\"", "self", ".", "file", ".", "write", "(", "line", ")",...
https://github.com/geekan/scrapy-examples/blob/edb1cb116bd6def65a6ef01f953b58eb43e54305/tutorial/tutorial/pipelines.py#L53-L56
LGE-ARC-AdvancedAI/auptimizer
50f6e3b4e0cb9146ca90fd74b9b24ca97ae22617
src/aup/convert.py
python
add_main
(script)
return script + """\nif __name__ == "__main__": import sys from aup import BasicConfig, print_result if len(sys.argv) != 2: print("config file required") exit(1) config = BasicConfig().load(sys.argv[1]) aup_wrapper(config)\n"""
Adds a main function to the executable Python file.
Adds a main function to the executable Python file.
[ "Adds", "a", "main", "function", "to", "the", "executable", "Python", "file", "." ]
def add_main(script): """ Adds a main function to the executable Python file. """ if "__main__" in script: logging.critical("__main__ is already defined in the script. Make sure no duplicated __main__ blocks in output.") return script + """\nif __name__ == "__main__": import sys from aup import BasicConfig, print_result if len(sys.argv) != 2: print("config file required") exit(1) config = BasicConfig().load(sys.argv[1]) aup_wrapper(config)\n"""
[ "def", "add_main", "(", "script", ")", ":", "if", "\"__main__\"", "in", "script", ":", "logging", ".", "critical", "(", "\"__main__ is already defined in the script. Make sure no duplicated __main__ blocks in output.\"", ")", "return", "script", "+", "\"\"\"\\nif __name__ ==...
https://github.com/LGE-ARC-AdvancedAI/auptimizer/blob/50f6e3b4e0cb9146ca90fd74b9b24ca97ae22617/src/aup/convert.py#L86-L99
auth0/auth0-python
511b016ac9853c7f4ee66769be7ad315c5585735
auth0/v3/management/clients.py
python
Clients.rotate_secret
(self, id)
return self.client.post(url, data=data)
Rotate a client secret. The generated secret is NOT base64 encoded. Args: id (str): Client ID of the application. See: https://auth0.com/docs/api/management/v2#!/Clients/post_rotate_secret
Rotate a client secret. The generated secret is NOT base64 encoded.
[ "Rotate", "a", "client", "secret", ".", "The", "generated", "secret", "is", "NOT", "base64", "encoded", "." ]
def rotate_secret(self, id): """Rotate a client secret. The generated secret is NOT base64 encoded. Args: id (str): Client ID of the application. See: https://auth0.com/docs/api/management/v2#!/Clients/post_rotate_secret """ data = {'id': id} url = self._url('%s/rotate-secret' % id) return self.client.post(url, data=data)
[ "def", "rotate_secret", "(", "self", ",", "id", ")", ":", "data", "=", "{", "'id'", ":", "id", "}", "url", "=", "self", ".", "_url", "(", "'%s/rotate-secret'", "%", "id", ")", "return", "self", ".", "client", ".", "post", "(", "url", ",", "data", ...
https://github.com/auth0/auth0-python/blob/511b016ac9853c7f4ee66769be7ad315c5585735/auth0/v3/management/clients.py#L133-L145
hhyo/Archery
c9b057d37e47894ca8531e5cd10afdb064cd0122
sql/engines/inception.py
python
InceptionEngine.get_variables
(self, variables=None)
return self.query(sql=sql)
获取实例参数
获取实例参数
[ "获取实例参数" ]
def get_variables(self, variables=None): """获取实例参数""" if variables: sql = f"inception get variables '{variables[0]}';" else: sql = "inception get variables;" return self.query(sql=sql)
[ "def", "get_variables", "(", "self", ",", "variables", "=", "None", ")", ":", "if", "variables", ":", "sql", "=", "f\"inception get variables '{variables[0]}';\"", "else", ":", "sql", "=", "\"inception get variables;\"", "return", "self", ".", "query", "(", "sql",...
https://github.com/hhyo/Archery/blob/c9b057d37e47894ca8531e5cd10afdb064cd0122/sql/engines/inception.py#L233-L239
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/setuptools/_vendor/pyparsing.py
python
ParserElement.runTests
(self, tests, parseAll=True, comment='#', fullDump=True, printResults=True, failureTests=False)
return success, allResults
Execute the parse expression on a series of test strings, showing each test, the parsed results or where the parse failed. Quick and easy way to run a parse expression against a list of sample strings. Parameters: - tests - a list of separate test strings, or a multiline string of test strings - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests - comment - (default=C{'#'}) - expression for indicating embedded comments in the test string; pass None to disable comment filtering - fullDump - (default=C{True}) - dump results as list followed by results names in nested outline; if False, only dump nested list - printResults - (default=C{True}) prints test output to stdout - failureTests - (default=C{False}) indicates if these tests are expected to fail parsing Returns: a (success, results) tuple, where success indicates that all tests succeeded (or failed if C{failureTests} is True), and the results contain a list of lines of each test's output Example:: number_expr = pyparsing_common.number.copy() result = number_expr.runTests(''' # unsigned integer 100 # negative integer -100 # float with scientific notation 6.02e23 # integer with scientific notation 1e-12 ''') print("Success" if result[0] else "Failed!") result = number_expr.runTests(''' # stray character 100Z # missing leading digit before '.' -.100 # too many '.' 3.14.159 ''', failureTests=True) print("Success" if result[0] else "Failed!") prints:: # unsigned integer 100 [100] # negative integer -100 [-100] # float with scientific notation 6.02e23 [6.02e+23] # integer with scientific notation 1e-12 [1e-12] Success # stray character 100Z ^ FAIL: Expected end of text (at char 3), (line:1, col:4) # missing leading digit before '.' -.100 ^ FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1) # too many '.' 3.14.159 ^ FAIL: Expected end of text (at char 4), (line:1, col:5) Success Each test string must be on a single line. If you want to test a string that spans multiple lines, create a test like this:: expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines") (Note that this is a raw string literal, you must include the leading 'r'.)
Execute the parse expression on a series of test strings, showing each test, the parsed results or where the parse failed. Quick and easy way to run a parse expression against a list of sample strings. Parameters: - tests - a list of separate test strings, or a multiline string of test strings - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests - comment - (default=C{'#'}) - expression for indicating embedded comments in the test string; pass None to disable comment filtering - fullDump - (default=C{True}) - dump results as list followed by results names in nested outline; if False, only dump nested list - printResults - (default=C{True}) prints test output to stdout - failureTests - (default=C{False}) indicates if these tests are expected to fail parsing
[ "Execute", "the", "parse", "expression", "on", "a", "series", "of", "test", "strings", "showing", "each", "test", "the", "parsed", "results", "or", "where", "the", "parse", "failed", ".", "Quick", "and", "easy", "way", "to", "run", "a", "parse", "expressio...
def runTests(self, tests, parseAll=True, comment='#', fullDump=True, printResults=True, failureTests=False): """ Execute the parse expression on a series of test strings, showing each test, the parsed results or where the parse failed. Quick and easy way to run a parse expression against a list of sample strings. Parameters: - tests - a list of separate test strings, or a multiline string of test strings - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests - comment - (default=C{'#'}) - expression for indicating embedded comments in the test string; pass None to disable comment filtering - fullDump - (default=C{True}) - dump results as list followed by results names in nested outline; if False, only dump nested list - printResults - (default=C{True}) prints test output to stdout - failureTests - (default=C{False}) indicates if these tests are expected to fail parsing Returns: a (success, results) tuple, where success indicates that all tests succeeded (or failed if C{failureTests} is True), and the results contain a list of lines of each test's output Example:: number_expr = pyparsing_common.number.copy() result = number_expr.runTests(''' # unsigned integer 100 # negative integer -100 # float with scientific notation 6.02e23 # integer with scientific notation 1e-12 ''') print("Success" if result[0] else "Failed!") result = number_expr.runTests(''' # stray character 100Z # missing leading digit before '.' -.100 # too many '.' 3.14.159 ''', failureTests=True) print("Success" if result[0] else "Failed!") prints:: # unsigned integer 100 [100] # negative integer -100 [-100] # float with scientific notation 6.02e23 [6.02e+23] # integer with scientific notation 1e-12 [1e-12] Success # stray character 100Z ^ FAIL: Expected end of text (at char 3), (line:1, col:4) # missing leading digit before '.' -.100 ^ FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1) # too many '.' 3.14.159 ^ FAIL: Expected end of text (at char 4), (line:1, col:5) Success Each test string must be on a single line. If you want to test a string that spans multiple lines, create a test like this:: expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines") (Note that this is a raw string literal, you must include the leading 'r'.) """ if isinstance(tests, basestring): tests = list(map(str.strip, tests.rstrip().splitlines())) if isinstance(comment, basestring): comment = Literal(comment) allResults = [] comments = [] success = True for t in tests: if comment is not None and comment.matches(t, False) or comments and not t: comments.append(t) continue if not t: continue out = ['\n'.join(comments), t] comments = [] try: t = t.replace(r'\n','\n') result = self.parseString(t, parseAll=parseAll) out.append(result.dump(full=fullDump)) success = success and not failureTests except ParseBaseException as pe: fatal = "(FATAL)" if isinstance(pe, ParseFatalException) else "" if '\n' in t: out.append(line(pe.loc, t)) out.append(' '*(col(pe.loc,t)-1) + '^' + fatal) else: out.append(' '*pe.loc + '^' + fatal) out.append("FAIL: " + str(pe)) success = success and failureTests result = pe except Exception as exc: out.append("FAIL-EXCEPTION: " + str(exc)) success = success and failureTests result = exc if printResults: if fullDump: out.append('') print('\n'.join(out)) allResults.append((t, result)) return success, allResults
[ "def", "runTests", "(", "self", ",", "tests", ",", "parseAll", "=", "True", ",", "comment", "=", "'#'", ",", "fullDump", "=", "True", ",", "printResults", "=", "True", ",", "failureTests", "=", "False", ")", ":", "if", "isinstance", "(", "tests", ",", ...
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/setuptools/_vendor/pyparsing.py#L2232-L2361
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
research/object_detection/utils/visualization_utils.py
python
draw_side_by_side_evaluation_image
(eval_dict, category_index, max_boxes_to_draw=20, min_score_thresh=0.2, use_normalized_coordinates=True, keypoint_edges=None)
return images_with_detections_list
Creates a side-by-side image with detections and groundtruth. Bounding boxes (and instance masks, if available) are visualized on both subimages. Args: eval_dict: The evaluation dictionary returned by eval_util.result_dict_for_batched_example() or eval_util.result_dict_for_single_example(). category_index: A category index (dictionary) produced from a labelmap. max_boxes_to_draw: The maximum number of boxes to draw for detections. min_score_thresh: The minimum score threshold for showing detections. use_normalized_coordinates: Whether to assume boxes and keypoints are in normalized coordinates (as opposed to absolute coordinates). Default is True. keypoint_edges: A list of tuples with keypoint indices that specify which keypoints should be connected by an edge, e.g. [(0, 1), (2, 4)] draws edges from keypoint 0 to 1 and from keypoint 2 to 4. Returns: A list of [1, H, 2 * W, C] uint8 tensor. The subimage on the left corresponds to detections, while the subimage on the right corresponds to groundtruth.
Creates a side-by-side image with detections and groundtruth.
[ "Creates", "a", "side", "-", "by", "-", "side", "image", "with", "detections", "and", "groundtruth", "." ]
def draw_side_by_side_evaluation_image(eval_dict, category_index, max_boxes_to_draw=20, min_score_thresh=0.2, use_normalized_coordinates=True, keypoint_edges=None): """Creates a side-by-side image with detections and groundtruth. Bounding boxes (and instance masks, if available) are visualized on both subimages. Args: eval_dict: The evaluation dictionary returned by eval_util.result_dict_for_batched_example() or eval_util.result_dict_for_single_example(). category_index: A category index (dictionary) produced from a labelmap. max_boxes_to_draw: The maximum number of boxes to draw for detections. min_score_thresh: The minimum score threshold for showing detections. use_normalized_coordinates: Whether to assume boxes and keypoints are in normalized coordinates (as opposed to absolute coordinates). Default is True. keypoint_edges: A list of tuples with keypoint indices that specify which keypoints should be connected by an edge, e.g. [(0, 1), (2, 4)] draws edges from keypoint 0 to 1 and from keypoint 2 to 4. Returns: A list of [1, H, 2 * W, C] uint8 tensor. The subimage on the left corresponds to detections, while the subimage on the right corresponds to groundtruth. """ detection_fields = fields.DetectionResultFields() input_data_fields = fields.InputDataFields() images_with_detections_list = [] # Add the batch dimension if the eval_dict is for single example. if len(eval_dict[detection_fields.detection_classes].shape) == 1: for key in eval_dict: if (key != input_data_fields.original_image and key != input_data_fields.image_additional_channels): eval_dict[key] = tf.expand_dims(eval_dict[key], 0) num_gt_boxes = [-1] * eval_dict[input_data_fields.original_image].shape[0] if input_data_fields.num_groundtruth_boxes in eval_dict: num_gt_boxes = tf.cast(eval_dict[input_data_fields.num_groundtruth_boxes], tf.int32) for indx in range(eval_dict[input_data_fields.original_image].shape[0]): instance_masks = None if detection_fields.detection_masks in eval_dict: instance_masks = tf.cast( tf.expand_dims( eval_dict[detection_fields.detection_masks][indx], axis=0), tf.uint8) keypoints = None keypoint_scores = None if detection_fields.detection_keypoints in eval_dict: keypoints = tf.expand_dims( eval_dict[detection_fields.detection_keypoints][indx], axis=0) if detection_fields.detection_keypoint_scores in eval_dict: keypoint_scores = tf.expand_dims( eval_dict[detection_fields.detection_keypoint_scores][indx], axis=0) else: keypoint_scores = tf.expand_dims(tf.cast( keypoint_ops.set_keypoint_visibilities( eval_dict[detection_fields.detection_keypoints][indx]), dtype=tf.float32), axis=0) groundtruth_instance_masks = None if input_data_fields.groundtruth_instance_masks in eval_dict: groundtruth_instance_masks = tf.cast( tf.expand_dims( eval_dict[input_data_fields.groundtruth_instance_masks][indx], axis=0), tf.uint8) groundtruth_keypoints = None groundtruth_keypoint_scores = None gt_kpt_vis_fld = input_data_fields.groundtruth_keypoint_visibilities if input_data_fields.groundtruth_keypoints in eval_dict: groundtruth_keypoints = tf.expand_dims( eval_dict[input_data_fields.groundtruth_keypoints][indx], axis=0) if gt_kpt_vis_fld in eval_dict: groundtruth_keypoint_scores = tf.expand_dims( tf.cast(eval_dict[gt_kpt_vis_fld][indx], dtype=tf.float32), axis=0) else: groundtruth_keypoint_scores = tf.expand_dims(tf.cast( keypoint_ops.set_keypoint_visibilities( eval_dict[input_data_fields.groundtruth_keypoints][indx]), dtype=tf.float32), axis=0) images_with_detections = draw_bounding_boxes_on_image_tensors( tf.expand_dims( eval_dict[input_data_fields.original_image][indx], axis=0), tf.expand_dims( eval_dict[detection_fields.detection_boxes][indx], axis=0), tf.expand_dims( eval_dict[detection_fields.detection_classes][indx], axis=0), tf.expand_dims( eval_dict[detection_fields.detection_scores][indx], axis=0), category_index, original_image_spatial_shape=tf.expand_dims( eval_dict[input_data_fields.original_image_spatial_shape][indx], axis=0), true_image_shape=tf.expand_dims( eval_dict[input_data_fields.true_image_shape][indx], axis=0), instance_masks=instance_masks, keypoints=keypoints, keypoint_scores=keypoint_scores, keypoint_edges=keypoint_edges, max_boxes_to_draw=max_boxes_to_draw, min_score_thresh=min_score_thresh, use_normalized_coordinates=use_normalized_coordinates) num_gt_boxes_i = num_gt_boxes[indx] images_with_groundtruth = draw_bounding_boxes_on_image_tensors( tf.expand_dims( eval_dict[input_data_fields.original_image][indx], axis=0), tf.expand_dims( eval_dict[input_data_fields.groundtruth_boxes][indx] [:num_gt_boxes_i], axis=0), tf.expand_dims( eval_dict[input_data_fields.groundtruth_classes][indx] [:num_gt_boxes_i], axis=0), tf.expand_dims( tf.ones_like( eval_dict[input_data_fields.groundtruth_classes][indx] [:num_gt_boxes_i], dtype=tf.float32), axis=0), category_index, original_image_spatial_shape=tf.expand_dims( eval_dict[input_data_fields.original_image_spatial_shape][indx], axis=0), true_image_shape=tf.expand_dims( eval_dict[input_data_fields.true_image_shape][indx], axis=0), instance_masks=groundtruth_instance_masks, keypoints=groundtruth_keypoints, keypoint_scores=groundtruth_keypoint_scores, keypoint_edges=keypoint_edges, max_boxes_to_draw=None, min_score_thresh=0.0, use_normalized_coordinates=use_normalized_coordinates) images_to_visualize = tf.concat([images_with_detections, images_with_groundtruth], axis=2) if input_data_fields.image_additional_channels in eval_dict: images_with_additional_channels_groundtruth = ( draw_bounding_boxes_on_image_tensors( tf.expand_dims( eval_dict[input_data_fields.image_additional_channels][indx], axis=0), tf.expand_dims( eval_dict[input_data_fields.groundtruth_boxes][indx] [:num_gt_boxes_i], axis=0), tf.expand_dims( eval_dict[input_data_fields.groundtruth_classes][indx] [:num_gt_boxes_i], axis=0), tf.expand_dims( tf.ones_like( eval_dict[input_data_fields.groundtruth_classes][indx] [num_gt_boxes_i], dtype=tf.float32), axis=0), category_index, original_image_spatial_shape=tf.expand_dims( eval_dict[input_data_fields.original_image_spatial_shape] [indx], axis=0), true_image_shape=tf.expand_dims( eval_dict[input_data_fields.true_image_shape][indx], axis=0), instance_masks=groundtruth_instance_masks, keypoints=None, keypoint_edges=None, max_boxes_to_draw=None, min_score_thresh=0.0, use_normalized_coordinates=use_normalized_coordinates)) images_to_visualize = tf.concat( [images_to_visualize, images_with_additional_channels_groundtruth], axis=2) images_with_detections_list.append(images_to_visualize) return images_with_detections_list
[ "def", "draw_side_by_side_evaluation_image", "(", "eval_dict", ",", "category_index", ",", "max_boxes_to_draw", "=", "20", ",", "min_score_thresh", "=", "0.2", ",", "use_normalized_coordinates", "=", "True", ",", "keypoint_edges", "=", "None", ")", ":", "detection_fie...
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/research/object_detection/utils/visualization_utils.py#L625-L807
ryanlayer/samplot
34a3f37eb7042b30e074df4fb3937708b1164460
samplot/samplot.py
python
get_long_read_max_gap
(read_name, long_reads)
return max_gap
Finds the largest gap between alignments in LongRead alignments, plus lengths of the alignments Returns the integer max gap
Finds the largest gap between alignments in LongRead alignments, plus lengths of the alignments
[ "Finds", "the", "largest", "gap", "between", "alignments", "in", "LongRead", "alignments", "plus", "lengths", "of", "the", "alignments" ]
def get_long_read_max_gap(read_name, long_reads): """Finds the largest gap between alignments in LongRead alignments, plus lengths of the alignments Returns the integer max gap """ alignments = [] for long_read in long_reads[read_name]: for alignment in long_read.alignments: alignments.append(alignment) alignments.sort(key=lambda x: x.query_position) # find biggest gap max_gap = 0 for i in range(1, len(alignments)): curr_gap = abs(alignments[i].start - alignments[i - 1].end) max_gap = max(max_gap, curr_gap) return max_gap
[ "def", "get_long_read_max_gap", "(", "read_name", ",", "long_reads", ")", ":", "alignments", "=", "[", "]", "for", "long_read", "in", "long_reads", "[", "read_name", "]", ":", "for", "alignment", "in", "long_read", ".", "alignments", ":", "alignments", ".", ...
https://github.com/ryanlayer/samplot/blob/34a3f37eb7042b30e074df4fb3937708b1164460/samplot/samplot.py#L1669-L1686
pysmt/pysmt
ade4dc2a825727615033a96d31c71e9f53ce4764
pysmt/oracles.py
python
AtomsOracle.walk_ite
(self, formula, args, **kwargs)
[]
def walk_ite(self, formula, args, **kwargs): #pylint: disable=unused-argument if any(a is None for a in args): # Theory ITE return None else: return frozenset(x for a in args for x in a)
[ "def", "walk_ite", "(", "self", ",", "formula", ",", "args", ",", "*", "*", "kwargs", ")", ":", "#pylint: disable=unused-argument", "if", "any", "(", "a", "is", "None", "for", "a", "in", "args", ")", ":", "# Theory ITE", "return", "None", "else", ":", ...
https://github.com/pysmt/pysmt/blob/ade4dc2a825727615033a96d31c71e9f53ce4764/pysmt/oracles.py#L439-L445
PokemonGoF/PokemonGo-Bot
5e80f20760f32478a84a8f0ced7ca24cdf41fe03
pokemongo_bot/walkers/polyline_generator.py
python
PolylineObjectHandler.cached_polyline
(origin, destination, google_map_api_key=None)
return PolylineObjectHandler._cache
Google API has limits, so we can't generate new Polyline at every tick...
Google API has limits, so we can't generate new Polyline at every tick...
[ "Google", "API", "has", "limits", "so", "we", "can", "t", "generate", "new", "Polyline", "at", "every", "tick", "..." ]
def cached_polyline(origin, destination, google_map_api_key=None): ''' Google API has limits, so we can't generate new Polyline at every tick... ''' # Absolute offset between bot origin and PolyLine get_last_pos() (in meters) if PolylineObjectHandler._cache and PolylineObjectHandler._cache.get_last_pos() != (None, None): abs_offset = distance(origin, PolylineObjectHandler._cache.get_last_pos()) else: abs_offset = float("inf") is_old_cache = lambda : abs_offset > 8 # Consider cache old if we identified an offset more then 8 m new_dest_set = lambda : tuple(destination) != PolylineObjectHandler._cache.destination if PolylineObjectHandler._run and (not is_old_cache()): # bot used to have struggle with making a decision. PolylineObjectHandler._instability -= 1 if PolylineObjectHandler._instability <= 0: PolylineObjectHandler._instability = 0 PolylineObjectHandler._run = False pass # use current cache elif None == PolylineObjectHandler._cache or is_old_cache() or new_dest_set(): # no cache, old cache or new destination set by bot, so make new polyline PolylineObjectHandler._instability += 2 if 10 <= PolylineObjectHandler._instability: PolylineObjectHandler._run = True PolylineObjectHandler._instability = 20 # next N moves use same cache PolylineObjectHandler._cache = Polyline(origin, destination, google_map_api_key) else: # valid cache found PolylineObjectHandler._instability -= 1 PolylineObjectHandler._instability = max(PolylineObjectHandler._instability, 0) pass # use current cache return PolylineObjectHandler._cache
[ "def", "cached_polyline", "(", "origin", ",", "destination", ",", "google_map_api_key", "=", "None", ")", ":", "# Absolute offset between bot origin and PolyLine get_last_pos() (in meters)", "if", "PolylineObjectHandler", ".", "_cache", "and", "PolylineObjectHandler", ".", "_...
https://github.com/PokemonGoF/PokemonGo-Bot/blob/5e80f20760f32478a84a8f0ced7ca24cdf41fe03/pokemongo_bot/walkers/polyline_generator.py#L25-L58
openai/mujoco-py
f1312cceeeebbba17e78d5d77fbffa091eed9a3a
mujoco_py/mjrenderpool.py
python
MjRenderPool._worker_render
(worker_id, state, width, height, camera_name, randomize)
Main target function for the workers.
Main target function for the workers.
[ "Main", "target", "function", "for", "the", "workers", "." ]
def _worker_render(worker_id, state, width, height, camera_name, randomize): """ Main target function for the workers. """ s = _render_pool_storage forward = False if state is not None: s.sim.set_state(state) forward = True if randomize and s.modder is not None: s.modder.randomize() forward = True if forward: s.sim.forward() rgb_block = width * height * 3 rgb_offset = rgb_block * worker_id rgb = s.shared_rgbs_array[rgb_offset:rgb_offset + rgb_block] rgb = rgb.reshape(height, width, 3) depth_block = width * height depth_offset = depth_block * worker_id depth = s.shared_depths_array[depth_offset:depth_offset + depth_block] depth = depth.reshape(height, width) rgb[:], depth[:] = s.sim.render( width, height, camera_name=camera_name, depth=True, device_id=s.device_id)
[ "def", "_worker_render", "(", "worker_id", ",", "state", ",", "width", ",", "height", ",", "camera_name", ",", "randomize", ")", ":", "s", "=", "_render_pool_storage", "forward", "=", "False", "if", "state", "is", "not", "None", ":", "s", ".", "sim", "."...
https://github.com/openai/mujoco-py/blob/f1312cceeeebbba17e78d5d77fbffa091eed9a3a/mujoco_py/mjrenderpool.py#L140-L169
SFDO-Tooling/CumulusCI
825ae1f122b25dc41761c52a4ddfa1938d2a4b6e
cumulusci/tasks/datadictionary.py
python
GenerateDataDictionary._write_field_results
(self, file_handle)
Write to the given handle an output CSV containing the data dictionary for fields.
Write to the given handle an output CSV containing the data dictionary for fields.
[ "Write", "to", "the", "given", "handle", "an", "output", "CSV", "containing", "the", "data", "dictionary", "for", "fields", "." ]
def _write_field_results(self, file_handle): """Write to the given handle an output CSV containing the data dictionary for fields.""" writer = csv.writer(file_handle) writer.writerow( [ "Object Label", "Object API Name", "Field Label", "Field API Name", "Type", "Picklist Values", "Help Text", "Field Description", "Version Introduced", "Version Picklist Values Last Changed", "Version Help Text Last Changed", "Version Deleted", ] ) for _, field_versions in self.fields.items(): # field_version.version.version yields the LooseVersion of the package version for this field version. versions = sorted( field_versions, key=lambda field_version: field_version.version.version, reverse=True, ) first_version = versions[-1] last_version = versions[0] if last_version.sobject in self.omit_sobjects: continue # Locate the last versions where the valid values and the help text changed. valid_values_version = None for (index, version) in enumerate(versions[1:]): if version.valid_values != last_version.valid_values: valid_values_version = versions[index] break help_text_version = None for (index, version) in enumerate(versions[1:]): if version.help_text != last_version.help_text: help_text_version = versions[index] break # Locate the version, if any, where this field was deleted. package_versions = sorted( self.package_versions[last_version.version.package] ) if last_version.version.version != package_versions[-1]: deleted_version = package_versions[ package_versions.index(last_version.version.version) + 1 ] else: deleted_version = None # Find the sObject name, if possible, for this field. if last_version.sobject in self.sobjects: sobject_label = sorted( self.sobjects[last_version.sobject], key=lambda ver: ver.version.version, reverse=True, )[0].label else: sobject_label = last_version.sobject writer.writerow( [ sobject_label, last_version.sobject, last_version.label, last_version.api_name, last_version.type, last_version.valid_values, last_version.help_text, last_version.description, f"{first_version.version.package.package_name} {self._get_version_name(first_version.version)}", f"{first_version.version.package.package_name} {self._get_version_name(valid_values_version.version)}" if valid_values_version else "", f"{first_version.version.package.package_name} {self._get_version_name(help_text_version.version)}" if help_text_version else "", "" if deleted_version is None else f"{first_version.version.package.package_name} {deleted_version}", ] )
[ "def", "_write_field_results", "(", "self", ",", "file_handle", ")", ":", "writer", "=", "csv", ".", "writer", "(", "file_handle", ")", "writer", ".", "writerow", "(", "[", "\"Object Label\"", ",", "\"Object API Name\"", ",", "\"Field Label\"", ",", "\"Field API...
https://github.com/SFDO-Tooling/CumulusCI/blob/825ae1f122b25dc41761c52a4ddfa1938d2a4b6e/cumulusci/tasks/datadictionary.py#L646-L735
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/pip/utils/logging.py
python
IndentingFormatter.format
(self, record)
return formatted
Calls the standard formatter, but will indent all of the log messages by our current indentation level.
Calls the standard formatter, but will indent all of the log messages by our current indentation level.
[ "Calls", "the", "standard", "formatter", "but", "will", "indent", "all", "of", "the", "log", "messages", "by", "our", "current", "indentation", "level", "." ]
def format(self, record): """ Calls the standard formatter, but will indent all of the log messages by our current indentation level. """ formatted = logging.Formatter.format(self, record) formatted = "".join([ (" " * get_indentation()) + line for line in formatted.splitlines(True) ]) return formatted
[ "def", "format", "(", "self", ",", "record", ")", ":", "formatted", "=", "logging", ".", "Formatter", ".", "format", "(", "self", ",", "record", ")", "formatted", "=", "\"\"", ".", "join", "(", "[", "(", "\" \"", "*", "get_indentation", "(", ")", ")"...
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/pip/utils/logging.py#L47-L57
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pip/_vendor/urllib3/util/ssl_.py
python
create_urllib3_context
(ssl_version=None, cert_reqs=None, options=None, ciphers=None)
return context
All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from pip._vendor.urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext
All arguments have the same meaning as ``ssl_wrap_socket``.
[ "All", "arguments", "have", "the", "same", "meaning", "as", "ssl_wrap_socket", "." ]
def create_urllib3_context(ssl_version=None, cert_reqs=None, options=None, ciphers=None): """All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from pip._vendor.urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext """ context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23) context.set_ciphers(ciphers or DEFAULT_CIPHERS) # Setting the default here, as we may have no ssl module on import cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs if options is None: options = 0 # SSLv2 is easily broken and is considered harmful and dangerous options |= OP_NO_SSLv2 # SSLv3 has several problems and is now dangerous options |= OP_NO_SSLv3 # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ # (issue #309) options |= OP_NO_COMPRESSION context.options |= options context.verify_mode = cert_reqs if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2 # We do our own verification, including fingerprints and alternative # hostnames. So disable it here context.check_hostname = False return context
[ "def", "create_urllib3_context", "(", "ssl_version", "=", "None", ",", "cert_reqs", "=", "None", ",", "options", "=", "None", ",", "ciphers", "=", "None", ")", ":", "context", "=", "SSLContext", "(", "ssl_version", "or", "ssl", ".", "PROTOCOL_SSLv23", ")", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pip/_vendor/urllib3/util/ssl_.py#L229-L288
rwightman/pytorch-image-models
ccfeb06936549f19c453b7f1f27e8e632cfbe1c2
timm/models/vision_transformer.py
python
vit_small_patch32_224_in21k
(pretrained=False, **kwargs)
return model
ViT-Small (ViT-S/16) ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer. NOTE: this model has valid 21k classifier head and no representation (pre-logits) layer
ViT-Small (ViT-S/16) ImageNet-21k weights
[ "ViT", "-", "Small", "(", "ViT", "-", "S", "/", "16", ")", "ImageNet", "-", "21k", "weights" ]
def vit_small_patch32_224_in21k(pretrained=False, **kwargs): """ ViT-Small (ViT-S/16) ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer. NOTE: this model has valid 21k classifier head and no representation (pre-logits) layer """ model_kwargs = dict(patch_size=32, embed_dim=384, depth=12, num_heads=6, **kwargs) model = _create_vision_transformer('vit_small_patch32_224_in21k', pretrained=pretrained, **model_kwargs) return model
[ "def", "vit_small_patch32_224_in21k", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model_kwargs", "=", "dict", "(", "patch_size", "=", "32", ",", "embed_dim", "=", "384", ",", "depth", "=", "12", ",", "num_heads", "=", "6", ",", ...
https://github.com/rwightman/pytorch-image-models/blob/ccfeb06936549f19c453b7f1f27e8e632cfbe1c2/timm/models/vision_transformer.py#L730-L737
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/plugins/viewrendered3.py
python
ViewRenderedController3.set_md_stylesheet
(self)
Verify or create css stylesheet for Markdown node. If there is no custom css stylesheet specified by self.md_stylesheet, check if there is one at the standard location. If not, create a default stylesheet and write it to a file at that place. The default location is assumed to be at leo/plugins/viewrendered3. VARIABLE USED self.md_stylesheet -- The URL to the stylesheet. Need not include the "file:///", and must be an absolute path if it is a local file. Set by @string vr3-md-stylesheet.
Verify or create css stylesheet for Markdown node.
[ "Verify", "or", "create", "css", "stylesheet", "for", "Markdown", "node", "." ]
def set_md_stylesheet(self): """Verify or create css stylesheet for Markdown node. If there is no custom css stylesheet specified by self.md_stylesheet, check if there is one at the standard location. If not, create a default stylesheet and write it to a file at that place. The default location is assumed to be at leo/plugins/viewrendered3. VARIABLE USED self.md_stylesheet -- The URL to the stylesheet. Need not include the "file:///", and must be an absolute path if it is a local file. Set by @string vr3-md-stylesheet. """ # If no custom stylesheet specified, use standard one. if not self.md_stylesheet: # Look for the standard one vr_style_dir = g.os_path_join(g.app.leoDir, 'plugins', 'viewrendered3') style_path = g.os_path_join(vr_style_dir, MD_BASE_STYLESHEET_NAME) # If there is no stylesheet at the standard location, have Pygments # generate a default stylesheet there. # Note: "cmdline" is a function imported from pygments if not os.path.exists(style_path): args = [cmdline.__name__, '-S', 'default', '-f', 'html'] # pygments cmdline() writes to stdout; we have to redirect it to a file with ioOpen(style_path, 'w') as out: with redirect_stdout(out): cmdline.main(args) # Add some fine-tuning css with ioOpen(style_path, 'a') as out: out.write(MD_STYLESHEET_APPEND) self.md_stylesheet = 'file:///' + style_path
[ "def", "set_md_stylesheet", "(", "self", ")", ":", "# If no custom stylesheet specified, use standard one.", "if", "not", "self", ".", "md_stylesheet", ":", "# Look for the standard one", "vr_style_dir", "=", "g", ".", "os_path_join", "(", "g", ".", "app", ".", "leoDi...
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/plugins/viewrendered3.py#L1809-L1844
translate/translate
72816df696b5263abfe80ab59129b299b85ae749
translate/convert/ical2po.py
python
ical2po.convert_store
(self)
Convert a single source format file to a target format file.
Convert a single source format file to a target format file.
[ "Convert", "a", "single", "source", "format", "file", "to", "a", "target", "format", "file", "." ]
def convert_store(self): """Convert a single source format file to a target format file.""" self.extraction_msg = "extracted from %s" % self.source_store.filename for source_unit in self.source_store.units: self.target_store.addunit(self.convert_unit(source_unit))
[ "def", "convert_store", "(", "self", ")", ":", "self", ".", "extraction_msg", "=", "\"extracted from %s\"", "%", "self", ".", "source_store", ".", "filename", "for", "source_unit", "in", "self", ".", "source_store", ".", "units", ":", "self", ".", "target_stor...
https://github.com/translate/translate/blob/72816df696b5263abfe80ab59129b299b85ae749/translate/convert/ical2po.py#L66-L71
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/modular/modform_hecketriangle/abstract_ring.py
python
FormsRing_abstract.f_i
(self)
return self.extend_type("holo", ring=True)(y).reduce()
r""" Return a normalized modular form ``f_i`` with exactly one simple zero at ``i`` (up to the group action). It lies in a (holomorphic) extension of the graded ring of ``self``. In case ``has_reduce_hom`` is ``True`` it is given as an element of the corresponding space of homogeneous elements. The polynomial variable ``y`` exactly corresponds to ``f_i``. EXAMPLES:: sage: from sage.modular.modform_hecketriangle.graded_ring import QuasiMeromorphicModularFormsRing, ModularFormsRing, CuspFormsRing sage: MR = ModularFormsRing(n=7) sage: f_i = MR.f_i() sage: f_i in MR True sage: CuspFormsRing(n=7).f_i() == f_i True sage: f_i f_i sage: QuasiMeromorphicModularFormsRing(n=7).f_i() == QuasiMeromorphicModularFormsRing(n=7)(f_i) True sage: from sage.modular.modform_hecketriangle.space import ModularForms, CuspForms sage: MF = ModularForms(n=5, k=10/3) sage: f_i = MF.f_i() sage: f_i in MF True sage: ModularFormsRing(n=5, red_hom=True).f_i() == f_i True sage: CuspForms(n=5, k=12).f_i() == f_i True sage: MF.disp_prec(3) sage: f_i 1 - 13/(40*d)*q - 351/(64000*d^2)*q^2 + O(q^3) sage: from sage.modular.modform_hecketriangle.series_constructor import MFSeriesConstructor as MFC sage: MF = ModularForms(n=5) sage: d = MF.get_d() sage: q = MF.get_q() sage: ModularForms(n=5).f_i().q_expansion(prec=5) == MFC(group=5, prec=7).f_i_ZZ()(q/d).add_bigoh(5) True sage: ModularForms(n=infinity).f_i().q_expansion(prec=5) == MFC(group=infinity, prec=7).f_i_ZZ()(q/d).add_bigoh(5) True sage: ModularForms(n=5).f_i().q_expansion(fix_d=1, prec=5) == MFC(group=5, prec=7).f_i_ZZ().add_bigoh(5) True sage: ModularForms(n=infinity).f_i().q_expansion(fix_d=1, prec=5) == MFC(group=infinity, prec=7).f_i_ZZ().add_bigoh(5) True sage: ModularForms(n=infinity, k=2).f_i() 1 - 24*q + 24*q^2 - 96*q^3 + 24*q^4 + O(q^5) sage: ModularForms(k=6).f_i() == ModularForms(k=4).E6() True sage: ModularForms(k=6).f_i() 1 - 504*q - 16632*q^2 - 122976*q^3 - 532728*q^4 + O(q^5)
r""" Return a normalized modular form ``f_i`` with exactly one simple zero at ``i`` (up to the group action).
[ "r", "Return", "a", "normalized", "modular", "form", "f_i", "with", "exactly", "one", "simple", "zero", "at", "i", "(", "up", "to", "the", "group", "action", ")", "." ]
def f_i(self): r""" Return a normalized modular form ``f_i`` with exactly one simple zero at ``i`` (up to the group action). It lies in a (holomorphic) extension of the graded ring of ``self``. In case ``has_reduce_hom`` is ``True`` it is given as an element of the corresponding space of homogeneous elements. The polynomial variable ``y`` exactly corresponds to ``f_i``. EXAMPLES:: sage: from sage.modular.modform_hecketriangle.graded_ring import QuasiMeromorphicModularFormsRing, ModularFormsRing, CuspFormsRing sage: MR = ModularFormsRing(n=7) sage: f_i = MR.f_i() sage: f_i in MR True sage: CuspFormsRing(n=7).f_i() == f_i True sage: f_i f_i sage: QuasiMeromorphicModularFormsRing(n=7).f_i() == QuasiMeromorphicModularFormsRing(n=7)(f_i) True sage: from sage.modular.modform_hecketriangle.space import ModularForms, CuspForms sage: MF = ModularForms(n=5, k=10/3) sage: f_i = MF.f_i() sage: f_i in MF True sage: ModularFormsRing(n=5, red_hom=True).f_i() == f_i True sage: CuspForms(n=5, k=12).f_i() == f_i True sage: MF.disp_prec(3) sage: f_i 1 - 13/(40*d)*q - 351/(64000*d^2)*q^2 + O(q^3) sage: from sage.modular.modform_hecketriangle.series_constructor import MFSeriesConstructor as MFC sage: MF = ModularForms(n=5) sage: d = MF.get_d() sage: q = MF.get_q() sage: ModularForms(n=5).f_i().q_expansion(prec=5) == MFC(group=5, prec=7).f_i_ZZ()(q/d).add_bigoh(5) True sage: ModularForms(n=infinity).f_i().q_expansion(prec=5) == MFC(group=infinity, prec=7).f_i_ZZ()(q/d).add_bigoh(5) True sage: ModularForms(n=5).f_i().q_expansion(fix_d=1, prec=5) == MFC(group=5, prec=7).f_i_ZZ().add_bigoh(5) True sage: ModularForms(n=infinity).f_i().q_expansion(fix_d=1, prec=5) == MFC(group=infinity, prec=7).f_i_ZZ().add_bigoh(5) True sage: ModularForms(n=infinity, k=2).f_i() 1 - 24*q + 24*q^2 - 96*q^3 + 24*q^4 + O(q^5) sage: ModularForms(k=6).f_i() == ModularForms(k=4).E6() True sage: ModularForms(k=6).f_i() 1 - 504*q - 16632*q^2 - 122976*q^3 - 532728*q^4 + O(q^5) """ (x,y,z,d) = self._pol_ring.gens() return self.extend_type("holo", ring=True)(y).reduce()
[ "def", "f_i", "(", "self", ")", ":", "(", "x", ",", "y", ",", "z", ",", "d", ")", "=", "self", ".", "_pol_ring", ".", "gens", "(", ")", "return", "self", ".", "extend_type", "(", "\"holo\"", ",", "ring", "=", "True", ")", "(", "y", ")", ".", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/modular/modform_hecketriangle/abstract_ring.py#L1240-L1302
scanny/python-pptx
71d1ca0b2b3b9178d64cdab565e8503a25a54e0b
pptx/oxml/xmlchemy.py
python
RequiredAttribute._getter
(self)
return get_attr_value
Return a function object suitable for the "get" side of the attribute property descriptor.
Return a function object suitable for the "get" side of the attribute property descriptor.
[ "Return", "a", "function", "object", "suitable", "for", "the", "get", "side", "of", "the", "attribute", "property", "descriptor", "." ]
def _getter(self): """ Return a function object suitable for the "get" side of the attribute property descriptor. """ def get_attr_value(obj): attr_str_value = obj.get(self._clark_name) if attr_str_value is None: raise InvalidXmlError( "required '%s' attribute not present on element %s" % (self._attr_name, obj.tag) ) return self._simple_type.from_xml(attr_str_value) get_attr_value.__doc__ = self._docstring return get_attr_value
[ "def", "_getter", "(", "self", ")", ":", "def", "get_attr_value", "(", "obj", ")", ":", "attr_str_value", "=", "obj", ".", "get", "(", "self", ".", "_clark_name", ")", "if", "attr_str_value", "is", "None", ":", "raise", "InvalidXmlError", "(", "\"required ...
https://github.com/scanny/python-pptx/blob/71d1ca0b2b3b9178d64cdab565e8503a25a54e0b/pptx/oxml/xmlchemy.py#L231-L247
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/compiler/ast.py
python
UnaryAdd.__init__
(self, expr, lineno=None)
[]
def __init__(self, expr, lineno=None): self.expr = expr self.lineno = lineno
[ "def", "__init__", "(", "self", ",", "expr", ",", "lineno", "=", "None", ")", ":", "self", ".", "expr", "=", "expr", "self", ".", "lineno", "=", "lineno" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/compiler/ast.py#L1326-L1328
SolidCode/SolidPython
4715c827ad90db26ee37df57bc425e6f2de3cf8d
solid/utils.py
python
nut
(screw_type:str='m3')
return ret
[]
def nut(screw_type:str='m3') -> OpenSCADObject: dims = screw_dimensions[screw_type.lower()] outer_rad = dims['nut_outer_diam'] inner_rad = dims['screw_outer_diam'] ret = difference()( circle(outer_rad, segments=6), circle(inner_rad) ) return ret
[ "def", "nut", "(", "screw_type", ":", "str", "=", "'m3'", ")", "->", "OpenSCADObject", ":", "dims", "=", "screw_dimensions", "[", "screw_type", ".", "lower", "(", ")", "]", "outer_rad", "=", "dims", "[", "'nut_outer_diam'", "]", "inner_rad", "=", "dims", ...
https://github.com/SolidCode/SolidPython/blob/4715c827ad90db26ee37df57bc425e6f2de3cf8d/solid/utils.py#L667-L676
adisonhuang/pay-python
bc1b926cd5e6d42fcd945b6c7dc9c3c003aab571
all_pay/wx/__init__.py
python
WxPay.enterprise_pay
(self, **kwargs)
return self._verify_return_data(data)
使用企业对个人付款功能 详细规则参考 https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2 :param api_cert_path: 微信支付商户证书路径,此证书(apiclient_cert.pem)需要先到微信支付商户平台获取,下载后保存至服务器 :param api_key_path: 微信支付商户证书路径,此证书(apiclient_key.pem)需要先到微信支付商户平台获取,下载后保存至服务器 :param data: openid, check_name, re_user_name, amount, desc, spbill_create_ip openid: 用户openid check_name: 是否校验用户姓名 re_user_name: 如果 check_name 为True,则填写,否则不带此参数 amount: 金额: 企业付款金额,单位为分 desc: 企业付款描述信息 spbill_create_ip: 调用接口的机器Ip地址 :return: 企业转账结果
使用企业对个人付款功能 详细规则参考 https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
[ "使用企业对个人付款功能", "详细规则参考", "https", ":", "//", "pay", ".", "weixin", ".", "qq", ".", "com", "/", "wiki", "/", "doc", "/", "api", "/", "tools", "/", "mch_pay", ".", "php?chapter", "=", "14_2" ]
def enterprise_pay(self, **kwargs): """ 使用企业对个人付款功能 详细规则参考 https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2 :param api_cert_path: 微信支付商户证书路径,此证书(apiclient_cert.pem)需要先到微信支付商户平台获取,下载后保存至服务器 :param api_key_path: 微信支付商户证书路径,此证书(apiclient_key.pem)需要先到微信支付商户平台获取,下载后保存至服务器 :param data: openid, check_name, re_user_name, amount, desc, spbill_create_ip openid: 用户openid check_name: 是否校验用户姓名 re_user_name: 如果 check_name 为True,则填写,否则不带此参数 amount: 金额: 企业付款金额,单位为分 desc: 企业付款描述信息 spbill_create_ip: 调用接口的机器Ip地址 :return: 企业转账结果 """ if not self._api_cert_path or not self._api_key_path: raise PayError(message='miss parameter _api_cert_path or _api_key_path') url = '{url}/mmpaymkttransfers/promotion/transfers'.format(url=self.API_BASE_URL) kwargs.setdefault('mch_appid', self._appid) kwargs.setdefault('mchid', self._mch_id) kwargs.setdefault('nonce_str', nonce_str()) kwargs.setdefault('check_name', False) total_fee = kwargs.pop('total_fee', None) kwargs['amount'] = total_fee out_trade_no = kwargs.pop('out_trade_no', None) kwargs['partner_trade_no'] = out_trade_no kwargs.setdefault('partner_trade_no', u'{0}{1}{2}'.format( self._mch_id, time.strftime('%Y%m%d', time.localtime(time.time())), random_num(10) )) kwargs['check_name'] = 'FORCE_CHECK' if kwargs['check_name'] else 'NO_CHECK' kwargs.setdefault('sign', self._sign(kwargs)) data = self._fetch_with_ssl(url, kwargs, self._api_cert_path, self._api_key_path) return self._verify_return_data(data)
[ "def", "enterprise_pay", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "_api_cert_path", "or", "not", "self", ".", "_api_key_path", ":", "raise", "PayError", "(", "message", "=", "'miss parameter _api_cert_path or _api_key_path'", ")"...
https://github.com/adisonhuang/pay-python/blob/bc1b926cd5e6d42fcd945b6c7dc9c3c003aab571/all_pay/wx/__init__.py#L356-L390
wger-project/wger
3a17a2cf133d242d1f8c357faa53cf675a7b3223
wger/utils/helpers.py
python
next_weekday
(date, weekday)
return date + datetime.timedelta(days_ahead)
Helper function to find the next weekday after a given date, e.g. the first Monday after the 2013-12-05 See link for more details: * http://stackoverflow.com/questions/6558535/python-find-the-date-for-the-first-monday-after-a :param date: the start date :param weekday: weekday (0, Monday, 1 Tuesday, 2 Wednesday) :type date: datetime.date :type weekday int :return: datetime.date
Helper function to find the next weekday after a given date, e.g. the first Monday after the 2013-12-05
[ "Helper", "function", "to", "find", "the", "next", "weekday", "after", "a", "given", "date", "e", ".", "g", ".", "the", "first", "Monday", "after", "the", "2013", "-", "12", "-", "05" ]
def next_weekday(date, weekday): """ Helper function to find the next weekday after a given date, e.g. the first Monday after the 2013-12-05 See link for more details: * http://stackoverflow.com/questions/6558535/python-find-the-date-for-the-first-monday-after-a :param date: the start date :param weekday: weekday (0, Monday, 1 Tuesday, 2 Wednesday) :type date: datetime.date :type weekday int :return: datetime.date """ days_ahead = weekday - date.weekday() if days_ahead <= 0: days_ahead += 7 return date + datetime.timedelta(days_ahead)
[ "def", "next_weekday", "(", "date", ",", "weekday", ")", ":", "days_ahead", "=", "weekday", "-", "date", ".", "weekday", "(", ")", "if", "days_ahead", "<=", "0", ":", "days_ahead", "+=", "7", "return", "date", "+", "datetime", ".", "timedelta", "(", "d...
https://github.com/wger-project/wger/blob/3a17a2cf133d242d1f8c357faa53cf675a7b3223/wger/utils/helpers.py#L94-L111
Blockstream/satellite
ceb46a00e176c43a6b4170359f6948663a0616bb
blocksatcli/sdr.py
python
_monitor_demod_info
(info_pipe, monitor)
Monitor leandvb's demodulator information Continuously read the demodulator information printed by leandvb into the descriptor pointed by --fd-info, which is tied to an unnamed pipe file. Then, feed the information into the monitor object. Args: info_pipe : Pipe object pointing to the pipe file that is used as leandvb's --fd-info descriptor monitor : Object of the Monitor class used to handle receiver monitoring and logging
Monitor leandvb's demodulator information
[ "Monitor", "leandvb", "s", "demodulator", "information" ]
def _monitor_demod_info(info_pipe, monitor): """Monitor leandvb's demodulator information Continuously read the demodulator information printed by leandvb into the descriptor pointed by --fd-info, which is tied to an unnamed pipe file. Then, feed the information into the monitor object. Args: info_pipe : Pipe object pointing to the pipe file that is used as leandvb's --fd-info descriptor monitor : Object of the Monitor class used to handle receiver monitoring and logging """ assert (isinstance(info_pipe, util.Pipe)) # "Standard" status format accepted by the Monitor class status = {'lock': (False, None), 'level': None, 'snr': None, 'ber': None} while True: line = info_pipe.readline() if "FRAMELOCK" in line: status['lock'] = (line.split()[-1] == "1", None) for metric in rx_stat_map: if metric in line: val = float(line.split()[-1]) unit = rx_stat_map[metric]['unit'] key = rx_stat_map[metric]['key'] status[key] = (val, unit) # If unlocked, clear the status metrics that depend on receiver locking # (they will show garbage if unlocked). If locked, just make sure that # all the required metrics are filled in the status dictionary. ready = True for metric in rx_stat_map: key = rx_stat_map[metric]['key'] if status['lock'][0]: if key not in status or status[key] is None: ready = False else: if (key in status): del status[key] if (not ready): continue monitor.update(status)
[ "def", "_monitor_demod_info", "(", "info_pipe", ",", "monitor", ")", ":", "assert", "(", "isinstance", "(", "info_pipe", ",", "util", ".", "Pipe", ")", ")", "# \"Standard\" status format accepted by the Monitor class", "status", "=", "{", "'lock'", ":", "(", "Fals...
https://github.com/Blockstream/satellite/blob/ceb46a00e176c43a6b4170359f6948663a0616bb/blocksatcli/sdr.py#L90-L138
nlloyd/SubliminalCollaborator
5c619e17ddbe8acb9eea8996ec038169ddcd50a1
libs/twisted/trial/reporter.py
python
_AnsiColorizer.supported
(cls, stream=sys.stdout)
A class method that returns True if the current platform supports coloring terminal output using this method. Returns False otherwise.
A class method that returns True if the current platform supports coloring terminal output using this method. Returns False otherwise.
[ "A", "class", "method", "that", "returns", "True", "if", "the", "current", "platform", "supports", "coloring", "terminal", "output", "using", "this", "method", ".", "Returns", "False", "otherwise", "." ]
def supported(cls, stream=sys.stdout): """ A class method that returns True if the current platform supports coloring terminal output using this method. Returns False otherwise. """ if not stream.isatty(): return False # auto color only on TTYs try: import curses except ImportError: return False else: try: try: return curses.tigetnum("colors") > 2 except curses.error: curses.setupterm() return curses.tigetnum("colors") > 2 except: # guess false in case of error return False
[ "def", "supported", "(", "cls", ",", "stream", "=", "sys", ".", "stdout", ")", ":", "if", "not", "stream", ".", "isatty", "(", ")", ":", "return", "False", "# auto color only on TTYs", "try", ":", "import", "curses", "except", "ImportError", ":", "return",...
https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/trial/reporter.py#L834-L854
crossbario/crossbar
ed350b7ba1c8421f3640b9c2e94a21ed4cfdff64
crossbar/bridge/mqtt/wamp.py
python
WampMQTTServerFactory._get_payload_format
(self, topic)
Map a WAMP topic URI to MQTT payload format. :param topic: WAMP URI. :type topic: str :returns: Payload format metadata. :rtype: dict
Map a WAMP topic URI to MQTT payload format. :param topic: WAMP URI. :type topic: str
[ "Map", "a", "WAMP", "topic", "URI", "to", "MQTT", "payload", "format", ".", ":", "param", "topic", ":", "WAMP", "URI", ".", ":", "type", "topic", ":", "str" ]
def _get_payload_format(self, topic): """ Map a WAMP topic URI to MQTT payload format. :param topic: WAMP URI. :type topic: str :returns: Payload format metadata. :rtype: dict """ try: pmap = self._payload_mapping.longest_prefix_value(topic) except KeyError: return None else: return pmap
[ "def", "_get_payload_format", "(", "self", ",", "topic", ")", ":", "try", ":", "pmap", "=", "self", ".", "_payload_mapping", ".", "longest_prefix_value", "(", "topic", ")", "except", "KeyError", ":", "return", "None", "else", ":", "return", "pmap" ]
https://github.com/crossbario/crossbar/blob/ed350b7ba1c8421f3640b9c2e94a21ed4cfdff64/crossbar/bridge/mqtt/wamp.py#L500-L514
JulianEberius/SublimePythonIDE
d70e40abc0c9f347af3204c7b910e0d6bfd6e459
server/lib/python2/rope/base/prefs.py
python
Prefs.set
(self, key, value)
Set the value of `key` preference to `value`.
Set the value of `key` preference to `value`.
[ "Set", "the", "value", "of", "key", "preference", "to", "value", "." ]
def set(self, key, value): """Set the value of `key` preference to `value`.""" if key in self.callbacks: self.callbacks[key](value) else: self.prefs[key] = value
[ "def", "set", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "in", "self", ".", "callbacks", ":", "self", ".", "callbacks", "[", "key", "]", "(", "value", ")", "else", ":", "self", ".", "prefs", "[", "key", "]", "=", "value" ]
https://github.com/JulianEberius/SublimePythonIDE/blob/d70e40abc0c9f347af3204c7b910e0d6bfd6e459/server/lib/python2/rope/base/prefs.py#L7-L12
kamalgill/flask-appengine-template
11760f83faccbb0d0afe416fc58e67ecfb4643c2
src/lib/wtforms/fields/core.py
python
StringField.process_formdata
(self, valuelist)
[]
def process_formdata(self, valuelist): if valuelist: self.data = valuelist[0] else: self.data = ''
[ "def", "process_formdata", "(", "self", ",", "valuelist", ")", ":", "if", "valuelist", ":", "self", ".", "data", "=", "valuelist", "[", "0", "]", "else", ":", "self", ".", "data", "=", "''" ]
https://github.com/kamalgill/flask-appengine-template/blob/11760f83faccbb0d0afe416fc58e67ecfb4643c2/src/lib/wtforms/fields/core.py#L526-L530
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/log_analytics/log_analytics_client.py
python
LogAnalyticsClient.list_sources
(self, namespace_name, compartment_id, **kwargs)
Returns a list of sources, containing detailed information about them. You may limit the number of results, provide sorting order, and filter by information such as display name, description and entity type. :param str namespace_name: (required) The Logging Analytics namespace used for the request. :param str compartment_id: (required) The ID of the compartment in which to list resources. :param str entity_type: (optional) A filter to return only sources associated with entities of the specified type. The match is case-insensitive. :param str source_display_text: (optional) The source display text used for filtering. Only sources with the specified name or description will be returned. :param str is_system: (optional) The system value used for filtering. Only items with the specified system value will be returned. Valid values are built in, custom (for user defined items), or all (for all items, regardless of system value). Allowed values are: "ALL", "CUSTOM", "BUILT_IN" :param bool is_auto_associated: (optional) An auto-associate flag used for filtering. Only sources which are marked for automatic association will be returned. :param str sort_order: (optional) The sort order to use, either ascending (`ASC`) or descending (`DESC`). Allowed values are: "ASC", "DESC" :param str sort_by: (optional) The attribute used to sort the returned sources Allowed values are: "name", "timeUpdated", "associationCount", "sourceType" :param int limit: (optional) The maximum number of items to return. :param str page: (optional) The page token representing the page at which to start retrieving results. This is usually retrieved from a previous list call. :param str name: (optional) A filter to return only log analytics entities whose name matches the entire name given. The match is case-insensitive. :param str categories: (optional) A comma-separated list of categories used for filtering :param bool is_simplified: (optional) A flag specifying whether or not to return all source information, or a subset of the information about each source. A value of true will return only the source unique identifier and the source name. A value of false will return all source information (such as author, updated date, system flag, etc.) :param str opc_request_id: (optional) The client request ID for tracing. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.log_analytics.models.LogAnalyticsSourceCollection` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/loganalytics/list_sources.py.html>`__ to see an example of how to use list_sources API.
Returns a list of sources, containing detailed information about them. You may limit the number of results, provide sorting order, and filter by information such as display name, description and entity type.
[ "Returns", "a", "list", "of", "sources", "containing", "detailed", "information", "about", "them", ".", "You", "may", "limit", "the", "number", "of", "results", "provide", "sorting", "order", "and", "filter", "by", "information", "such", "as", "display", "name...
def list_sources(self, namespace_name, compartment_id, **kwargs): """ Returns a list of sources, containing detailed information about them. You may limit the number of results, provide sorting order, and filter by information such as display name, description and entity type. :param str namespace_name: (required) The Logging Analytics namespace used for the request. :param str compartment_id: (required) The ID of the compartment in which to list resources. :param str entity_type: (optional) A filter to return only sources associated with entities of the specified type. The match is case-insensitive. :param str source_display_text: (optional) The source display text used for filtering. Only sources with the specified name or description will be returned. :param str is_system: (optional) The system value used for filtering. Only items with the specified system value will be returned. Valid values are built in, custom (for user defined items), or all (for all items, regardless of system value). Allowed values are: "ALL", "CUSTOM", "BUILT_IN" :param bool is_auto_associated: (optional) An auto-associate flag used for filtering. Only sources which are marked for automatic association will be returned. :param str sort_order: (optional) The sort order to use, either ascending (`ASC`) or descending (`DESC`). Allowed values are: "ASC", "DESC" :param str sort_by: (optional) The attribute used to sort the returned sources Allowed values are: "name", "timeUpdated", "associationCount", "sourceType" :param int limit: (optional) The maximum number of items to return. :param str page: (optional) The page token representing the page at which to start retrieving results. This is usually retrieved from a previous list call. :param str name: (optional) A filter to return only log analytics entities whose name matches the entire name given. The match is case-insensitive. :param str categories: (optional) A comma-separated list of categories used for filtering :param bool is_simplified: (optional) A flag specifying whether or not to return all source information, or a subset of the information about each source. A value of true will return only the source unique identifier and the source name. A value of false will return all source information (such as author, updated date, system flag, etc.) :param str opc_request_id: (optional) The client request ID for tracing. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.log_analytics.models.LogAnalyticsSourceCollection` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/loganalytics/list_sources.py.html>`__ to see an example of how to use list_sources API. """ resource_path = "/namespaces/{namespaceName}/sources" method = "GET" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "entity_type", "source_display_text", "is_system", "is_auto_associated", "sort_order", "sort_by", "limit", "page", "name", "categories", "is_simplified", "opc_request_id" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "list_sources got unknown kwargs: {!r}".format(extra_kwargs)) path_params = { "namespaceName": namespace_name } path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing} for (k, v) in six.iteritems(path_params): if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0): raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k)) if 'is_system' in kwargs: is_system_allowed_values = ["ALL", "CUSTOM", "BUILT_IN"] if kwargs['is_system'] not in is_system_allowed_values: raise ValueError( "Invalid value for `is_system`, must be one of {0}".format(is_system_allowed_values) ) if 'sort_order' in kwargs: sort_order_allowed_values = ["ASC", "DESC"] if kwargs['sort_order'] not in sort_order_allowed_values: raise ValueError( "Invalid value for `sort_order`, must be one of {0}".format(sort_order_allowed_values) ) if 'sort_by' in kwargs: sort_by_allowed_values = ["name", "timeUpdated", "associationCount", "sourceType"] if kwargs['sort_by'] not in sort_by_allowed_values: raise ValueError( "Invalid value for `sort_by`, must be one of {0}".format(sort_by_allowed_values) ) query_params = { "entityType": kwargs.get("entity_type", missing), "sourceDisplayText": kwargs.get("source_display_text", missing), "isSystem": kwargs.get("is_system", missing), "isAutoAssociated": kwargs.get("is_auto_associated", missing), "sortOrder": kwargs.get("sort_order", missing), "sortBy": kwargs.get("sort_by", missing), "limit": kwargs.get("limit", missing), "page": kwargs.get("page", missing), "name": kwargs.get("name", missing), "categories": kwargs.get("categories", missing), "isSimplified": kwargs.get("is_simplified", missing), "compartmentId": compartment_id } query_params = {k: v for (k, v) in six.iteritems(query_params) if v is not missing and v is not None} header_params = { "accept": "application/json;charset=UTF-8", "content-type": "application/json", "opc-request-id": kwargs.get("opc_request_id", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, path_params=path_params, query_params=query_params, header_params=header_params, response_type="LogAnalyticsSourceCollection") else: return self.base_client.call_api( resource_path=resource_path, method=method, path_params=path_params, query_params=query_params, header_params=header_params, response_type="LogAnalyticsSourceCollection")
[ "def", "list_sources", "(", "self", ",", "namespace_name", ",", "compartment_id", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/namespaces/{namespaceName}/sources\"", "method", "=", "\"GET\"", "# Don't accept unknown kwargs", "expected_kwargs", "=", "[", ...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/log_analytics/log_analytics_client.py#L12755-L12933
deanishe/alfred-pwgen
7966df5c5e05f2fca5b9406fb2a6116f7030608a
src/workflow/update.py
python
Version.__gt__
(self, other)
return other.__lt__(self)
Implement comparison.
Implement comparison.
[ "Implement", "comparison", "." ]
def __gt__(self, other): """Implement comparison.""" if not isinstance(other, Version): raise ValueError('not a Version instance: {0!r}'.format(other)) return other.__lt__(self)
[ "def", "__gt__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Version", ")", ":", "raise", "ValueError", "(", "'not a Version instance: {0!r}'", ".", "format", "(", "other", ")", ")", "return", "other", ".", "__lt__",...
https://github.com/deanishe/alfred-pwgen/blob/7966df5c5e05f2fca5b9406fb2a6116f7030608a/src/workflow/update.py#L317-L321
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/_vendor/html5lib/treebuilders/base.py
python
TreeBuilder.getDocument
(self)
return self.document
Return the final tree
Return the final tree
[ "Return", "the", "final", "tree" ]
def getDocument(self): "Return the final tree" return self.document
[ "def", "getDocument", "(", "self", ")", ":", "return", "self", ".", "document" ]
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/_vendor/html5lib/treebuilders/base.py#L369-L371
metabrainz/picard
535bf8c7d9363ffc7abb3f69418ec11823c38118
picard/ui/options/plugins.py
python
PluginsOptionsPage.selected_item
(self)
[]
def selected_item(self): try: return self.ui.plugins.selectedItems()[COLUMN_NAME] except IndexError: return None
[ "def", "selected_item", "(", "self", ")", ":", "try", ":", "return", "self", ".", "ui", ".", "plugins", ".", "selectedItems", "(", ")", "[", "COLUMN_NAME", "]", "except", "IndexError", ":", "return", "None" ]
https://github.com/metabrainz/picard/blob/535bf8c7d9363ffc7abb3f69418ec11823c38118/picard/ui/options/plugins.py#L271-L275
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/boto-2.46.1/boto/dynamodb/table.py
python
Table.batch_get_item
(self, keys, attributes_to_get=None)
return TableBatchGenerator(self, keys, attributes_to_get)
Return a set of attributes for a multiple items from a single table using their primary keys. This abstraction removes the 100 Items per batch limitations as well as the "UnprocessedKeys" logic. :type keys: list :param keys: A list of scalar or tuple values. Each element in the list represents one Item to retrieve. If the schema for the table has both a HashKey and a RangeKey, each element in the list should be a tuple consisting of (hash_key, range_key). If the schema for the table contains only a HashKey, each element in the list should be a scalar value of the appropriate type for the table schema. NOTE: The maximum number of items that can be retrieved for a single operation is 100. Also, the number of items retrieved is constrained by a 1 MB size limit. :type attributes_to_get: list :param attributes_to_get: A list of attribute names. If supplied, only the specified attribute names will be returned. Otherwise, all attributes will be returned. :return: A TableBatchGenerator (generator) object which will iterate over all results :rtype: :class:`boto.dynamodb.table.TableBatchGenerator`
Return a set of attributes for a multiple items from a single table using their primary keys. This abstraction removes the 100 Items per batch limitations as well as the "UnprocessedKeys" logic.
[ "Return", "a", "set", "of", "attributes", "for", "a", "multiple", "items", "from", "a", "single", "table", "using", "their", "primary", "keys", ".", "This", "abstraction", "removes", "the", "100", "Items", "per", "batch", "limitations", "as", "well", "as", ...
def batch_get_item(self, keys, attributes_to_get=None): """ Return a set of attributes for a multiple items from a single table using their primary keys. This abstraction removes the 100 Items per batch limitations as well as the "UnprocessedKeys" logic. :type keys: list :param keys: A list of scalar or tuple values. Each element in the list represents one Item to retrieve. If the schema for the table has both a HashKey and a RangeKey, each element in the list should be a tuple consisting of (hash_key, range_key). If the schema for the table contains only a HashKey, each element in the list should be a scalar value of the appropriate type for the table schema. NOTE: The maximum number of items that can be retrieved for a single operation is 100. Also, the number of items retrieved is constrained by a 1 MB size limit. :type attributes_to_get: list :param attributes_to_get: A list of attribute names. If supplied, only the specified attribute names will be returned. Otherwise, all attributes will be returned. :return: A TableBatchGenerator (generator) object which will iterate over all results :rtype: :class:`boto.dynamodb.table.TableBatchGenerator` """ return TableBatchGenerator(self, keys, attributes_to_get)
[ "def", "batch_get_item", "(", "self", ",", "keys", ",", "attributes_to_get", "=", "None", ")", ":", "return", "TableBatchGenerator", "(", "self", ",", "keys", ",", "attributes_to_get", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/boto-2.46.1/boto/dynamodb/table.py#L520-L546
ganeti/ganeti
d340a9ddd12f501bef57da421b5f9b969a4ba905
lib/hooksmaster.py
python
HooksMaster.RunConfigUpdate
(self)
Run the special configuration update hook This is a special hook that runs only on the master after each top-level LI if the configuration has been updated.
Run the special configuration update hook
[ "Run", "the", "special", "configuration", "update", "hook" ]
def RunConfigUpdate(self): """Run the special configuration update hook This is a special hook that runs only on the master after each top-level LI if the configuration has been updated. """ phase = constants.HOOKS_PHASE_POST hpath = constants.HOOKS_NAME_CFGUPDATE nodes = [self.master_name] self._RunWrapper(nodes, hpath, phase, self.pre_env)
[ "def", "RunConfigUpdate", "(", "self", ")", ":", "phase", "=", "constants", ".", "HOOKS_PHASE_POST", "hpath", "=", "constants", ".", "HOOKS_NAME_CFGUPDATE", "nodes", "=", "[", "self", ".", "master_name", "]", "self", ".", "_RunWrapper", "(", "nodes", ",", "h...
https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/lib/hooksmaster.py#L262-L272
dj-stripe/dj-stripe
cf15b07c754525077098e2b906108425a1f657e0
djstripe/models/payment_methods.py
python
LegacySourceMixin.api_retrieve
(self, api_key=None, stripe_account=None)
[]
def api_retrieve(self, api_key=None, stripe_account=None): # OVERRIDING the parent version of this function # Cards & Banks Accounts must be manipulated through a customer or account. api_key = api_key or self.default_api_key if self.customer: return stripe.Customer.retrieve_source( self.customer.id, self.id, expand=self.expand_fields, stripe_account=stripe_account, api_key=api_key, ) # try to retrieve by account attribute if retrieval by customer fails. if self.account: return stripe.Account.retrieve_external_account( self.account.id, self.id, expand=self.expand_fields, stripe_account=stripe_account, api_key=api_key, )
[ "def", "api_retrieve", "(", "self", ",", "api_key", "=", "None", ",", "stripe_account", "=", "None", ")", ":", "# OVERRIDING the parent version of this function", "# Cards & Banks Accounts must be manipulated through a customer or account.", "api_key", "=", "api_key", "or", "...
https://github.com/dj-stripe/dj-stripe/blob/cf15b07c754525077098e2b906108425a1f657e0/djstripe/models/payment_methods.py#L288-L311
GoogleCloudPlatform/deploymentmanager-samples
9cc562d7d048a9890572587ca299816c0cd3bb38
examples/v2/ha-service/container_instance_template.py
python
GenerateConfig
(context)
return {'resources': [instance_template]}
Generates config.
Generates config.
[ "Generates", "config", "." ]
def GenerateConfig(context): """Generates config.""" image = ''.join(['https://www.googleapis.com/compute/v1/', 'projects/cos-cloud/global/images/', context.properties['containerImage']]) default_network = ''.join(['https://www.googleapis.com/compute/v1/projects/', context.env['project'], '/global/networks/default']) instance_template = { 'name': context.env['name'], 'type': 'compute.v1.instanceTemplate', 'properties': { 'properties': { 'metadata': { 'items': [{ 'key': 'google-container-manifest', 'value': GenerateManifest(context) }] }, 'machineType': 'f1-micro', 'disks': [{ 'deviceName': 'boot', 'boot': True, 'autoDelete': True, 'mode': 'READ_WRITE', 'type': 'PERSISTENT', 'initializeParams': {'sourceImage': image} }], 'networkInterfaces': [{ 'accessConfigs': [{ 'name': 'external-nat', 'type': 'ONE_TO_ONE_NAT' }], 'network': default_network }] } } } return {'resources': [instance_template]}
[ "def", "GenerateConfig", "(", "context", ")", ":", "image", "=", "''", ".", "join", "(", "[", "'https://www.googleapis.com/compute/v1/'", ",", "'projects/cos-cloud/global/images/'", ",", "context", ".", "properties", "[", "'containerImage'", "]", "]", ")", "default_...
https://github.com/GoogleCloudPlatform/deploymentmanager-samples/blob/9cc562d7d048a9890572587ca299816c0cd3bb38/examples/v2/ha-service/container_instance_template.py#L20-L61
vivisect/vivisect
37b0b655d8dedfcf322e86b0f144b096e48d547e
vivisect/__init__.py
python
VivWorkspace.getLocationByName
(self, name)
return self.getLocation(va)
Return a location object by the name of the location.
Return a location object by the name of the location.
[ "Return", "a", "location", "object", "by", "the", "name", "of", "the", "location", "." ]
def getLocationByName(self, name): """ Return a location object by the name of the location. """ va = self.vaByName(name) if va is None: raise InvalidLocation(0, "Unknown Name: %s" % name) return self.getLocation(va)
[ "def", "getLocationByName", "(", "self", ",", "name", ")", ":", "va", "=", "self", ".", "vaByName", "(", "name", ")", "if", "va", "is", "None", ":", "raise", "InvalidLocation", "(", "0", ",", "\"Unknown Name: %s\"", "%", "name", ")", "return", "self", ...
https://github.com/vivisect/vivisect/blob/37b0b655d8dedfcf322e86b0f144b096e48d547e/vivisect/__init__.py#L2518-L2526
SBCV/Blender-Addon-Photogrammetry-Importer
d964ef04cefde73320749cc346113e16be5bd73b
photogrammetry_importer/panels/screenshot_operators.py
python
ExportScreenshotImageOperator.poll
(cls, context)
return True
Return the availability status of the operator.
Return the availability status of the operator.
[ "Return", "the", "availability", "status", "of", "the", "operator", "." ]
def poll(cls, context): """Return the availability status of the operator.""" return True
[ "def", "poll", "(", "cls", ",", "context", ")", ":", "return", "True" ]
https://github.com/SBCV/Blender-Addon-Photogrammetry-Importer/blob/d964ef04cefde73320749cc346113e16be5bd73b/photogrammetry_importer/panels/screenshot_operators.py#L28-L30
hannes-brt/hebel
1e2c3a9309c2646103901b26a55be4e312dd5005
hebel/pycuda_ops/cudart.py
python
cudaCheckStatus
(status)
Raise CUDA exception. Raise an exception corresponding to the specified CUDA runtime error code. Parameters ---------- status : int CUDA runtime error code. See Also -------- cudaExceptions
Raise CUDA exception.
[ "Raise", "CUDA", "exception", "." ]
def cudaCheckStatus(status): """ Raise CUDA exception. Raise an exception corresponding to the specified CUDA runtime error code. Parameters ---------- status : int CUDA runtime error code. See Also -------- cudaExceptions """ if status != 0: try: raise cudaExceptions[status] except KeyError: raise cudaError
[ "def", "cudaCheckStatus", "(", "status", ")", ":", "if", "status", "!=", "0", ":", "try", ":", "raise", "cudaExceptions", "[", "status", "]", "except", "KeyError", ":", "raise", "cudaError" ]
https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cudart.py#L457-L479
bojone/bert4keras
347310ee0562139cc5de29ccc40dad9a41eb8595
examples/task_sequence_labeling_cws_crf.py
python
predict_to_file
(in_file, out_file)
预测结果到文件,便于用官方脚本评测 使用示例: predict_to_file('/root/icwb2-data/testing/pku_test.utf8', 'myresult.txt') 官方评测代码示例: data_dir="/root/icwb2-data" $data_dir/scripts/score $data_dir/gold/pku_training_words.utf8 $data_dir/gold/pku_test_gold.utf8 myresult.txt > myscore.txt (执行完毕后查看myscore.txt的内容末尾)
预测结果到文件,便于用官方脚本评测 使用示例: predict_to_file('/root/icwb2-data/testing/pku_test.utf8', 'myresult.txt') 官方评测代码示例: data_dir="/root/icwb2-data" $data_dir/scripts/score $data_dir/gold/pku_training_words.utf8 $data_dir/gold/pku_test_gold.utf8 myresult.txt > myscore.txt (执行完毕后查看myscore.txt的内容末尾)
[ "预测结果到文件,便于用官方脚本评测", "使用示例:", "predict_to_file", "(", "/", "root", "/", "icwb2", "-", "data", "/", "testing", "/", "pku_test", ".", "utf8", "myresult", ".", "txt", ")", "官方评测代码示例:", "data_dir", "=", "/", "root", "/", "icwb2", "-", "data", "$data_dir", "/",...
def predict_to_file(in_file, out_file): """预测结果到文件,便于用官方脚本评测 使用示例: predict_to_file('/root/icwb2-data/testing/pku_test.utf8', 'myresult.txt') 官方评测代码示例: data_dir="/root/icwb2-data" $data_dir/scripts/score $data_dir/gold/pku_training_words.utf8 $data_dir/gold/pku_test_gold.utf8 myresult.txt > myscore.txt (执行完毕后查看myscore.txt的内容末尾) """ fw = open(out_file, 'w', encoding='utf-8') with open(in_file, encoding='utf-8') as fr: for l in tqdm(fr): l = l.strip() if l: l = ' '.join(segmenter.tokenize(l)) fw.write(l + '\n') fw.close()
[ "def", "predict_to_file", "(", "in_file", ",", "out_file", ")", ":", "fw", "=", "open", "(", "out_file", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "with", "open", "(", "in_file", ",", "encoding", "=", "'utf-8'", ")", "as", "fr", ":", "for", "...
https://github.com/bojone/bert4keras/blob/347310ee0562139cc5de29ccc40dad9a41eb8595/examples/task_sequence_labeling_cws_crf.py#L171-L187
dagster-io/dagster
b27d569d5fcf1072543533a0c763815d96f90b8f
examples/docs_snippets/docs_snippets/concepts/io_management/subselection.py
python
op2
(dataframe)
Do stuff
Do stuff
[ "Do", "stuff" ]
def op2(dataframe): """Do stuff"""
[ "def", "op2", "(", "dataframe", ")", ":" ]
https://github.com/dagster-io/dagster/blob/b27d569d5fcf1072543533a0c763815d96f90b8f/examples/docs_snippets/docs_snippets/concepts/io_management/subselection.py#L39-L40
NVIDIA/Megatron-LM
9a8b89acd8f6ba096860170d0e30ddc0bc2bacd4
pretrain_t5.py
python
get_batch
(data_iterator)
return tokens_enc, tokens_dec, loss_mask, labels, \ enc_mask, dec_mask, enc_dec_mask
Build the batch.
Build the batch.
[ "Build", "the", "batch", "." ]
def get_batch(data_iterator): """Build the batch.""" keys = ['text_enc', 'text_dec', 'labels', 'loss_mask', 'enc_mask', 'dec_mask', 'enc_dec_mask'] datatype = torch.int64 # Broadcast data. if data_iterator is not None: data = next(data_iterator) else: data = None data_b = mpu.broadcast_data(keys, data, datatype) # Unpack. tokens_enc = data_b['text_enc'].long() tokens_dec = data_b['text_dec'].long() labels = data_b['labels'].long() loss_mask = data_b['loss_mask'].float() enc_mask = (data_b['enc_mask'] < 0.5) dec_mask = (data_b['dec_mask'] < 0.5) enc_dec_mask = (data_b['enc_dec_mask'] < 0.5) return tokens_enc, tokens_dec, loss_mask, labels, \ enc_mask, dec_mask, enc_dec_mask
[ "def", "get_batch", "(", "data_iterator", ")", ":", "keys", "=", "[", "'text_enc'", ",", "'text_dec'", ",", "'labels'", ",", "'loss_mask'", ",", "'enc_mask'", ",", "'dec_mask'", ",", "'enc_dec_mask'", "]", "datatype", "=", "torch", ".", "int64", "# Broadcast d...
https://github.com/NVIDIA/Megatron-LM/blob/9a8b89acd8f6ba096860170d0e30ddc0bc2bacd4/pretrain_t5.py#L84-L109
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-build/python-libs/gdata/build/lib/gdata/service.py
python
GDataService.SetOAuthInputParameters
(self, signature_method, consumer_key, consumer_secret=None, rsa_key=None, two_legged_oauth=False, requestor_id=None)
Sets parameters required for using OAuth authentication mechanism. NOTE: Though consumer_secret and rsa_key are optional, either of the two is required depending on the value of the signature_method. Args: signature_method: class which provides implementation for strategy class oauth.oauth.OAuthSignatureMethod. Signature method to be used for signing each request. Valid implementations are provided as the constants defined by gdata.auth.OAuthSignatureMethod. Currently they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and gdata.auth.OAuthSignatureMethod.HMAC_SHA1 consumer_key: string Domain identifying third_party web application. consumer_secret: string (optional) Secret generated during registration. Required only for HMAC_SHA1 signature method. rsa_key: string (optional) Private key required for RSA_SHA1 signature method. two_legged_oauth: boolean (optional) Enables two-legged OAuth process. requestor_id: string (optional) User email adress to make requests on their behalf. This parameter should only be set when two_legged_oauth is True.
Sets parameters required for using OAuth authentication mechanism.
[ "Sets", "parameters", "required", "for", "using", "OAuth", "authentication", "mechanism", "." ]
def SetOAuthInputParameters(self, signature_method, consumer_key, consumer_secret=None, rsa_key=None, two_legged_oauth=False, requestor_id=None): """Sets parameters required for using OAuth authentication mechanism. NOTE: Though consumer_secret and rsa_key are optional, either of the two is required depending on the value of the signature_method. Args: signature_method: class which provides implementation for strategy class oauth.oauth.OAuthSignatureMethod. Signature method to be used for signing each request. Valid implementations are provided as the constants defined by gdata.auth.OAuthSignatureMethod. Currently they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and gdata.auth.OAuthSignatureMethod.HMAC_SHA1 consumer_key: string Domain identifying third_party web application. consumer_secret: string (optional) Secret generated during registration. Required only for HMAC_SHA1 signature method. rsa_key: string (optional) Private key required for RSA_SHA1 signature method. two_legged_oauth: boolean (optional) Enables two-legged OAuth process. requestor_id: string (optional) User email adress to make requests on their behalf. This parameter should only be set when two_legged_oauth is True. """ self._oauth_input_params = gdata.auth.OAuthInputParams( signature_method, consumer_key, consumer_secret=consumer_secret, rsa_key=rsa_key, requestor_id=requestor_id) if two_legged_oauth: oauth_token = gdata.auth.OAuthToken( oauth_input_params=self._oauth_input_params) self.SetOAuthToken(oauth_token)
[ "def", "SetOAuthInputParameters", "(", "self", ",", "signature_method", ",", "consumer_key", ",", "consumer_secret", "=", "None", ",", "rsa_key", "=", "None", ",", "two_legged_oauth", "=", "False", ",", "requestor_id", "=", "None", ")", ":", "self", ".", "_oau...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/gdata/build/lib/gdata/service.py#L349-L380
encode/django-rest-framework
c5be86a6dbf3d21b00a296af5994fa075826bf0b
rest_framework/pagination.py
python
CursorPagination.decode_cursor
(self, request)
return Cursor(offset=offset, reverse=reverse, position=position)
Given a request with a cursor, return a `Cursor` instance.
Given a request with a cursor, return a `Cursor` instance.
[ "Given", "a", "request", "with", "a", "cursor", "return", "a", "Cursor", "instance", "." ]
def decode_cursor(self, request): """ Given a request with a cursor, return a `Cursor` instance. """ # Determine if we have a cursor, and if so then decode it. encoded = request.query_params.get(self.cursor_query_param) if encoded is None: return None try: querystring = b64decode(encoded.encode('ascii')).decode('ascii') tokens = parse.parse_qs(querystring, keep_blank_values=True) offset = tokens.get('o', ['0'])[0] offset = _positive_int(offset, cutoff=self.offset_cutoff) reverse = tokens.get('r', ['0'])[0] reverse = bool(int(reverse)) position = tokens.get('p', [None])[0] except (TypeError, ValueError): raise NotFound(self.invalid_cursor_message) return Cursor(offset=offset, reverse=reverse, position=position)
[ "def", "decode_cursor", "(", "self", ",", "request", ")", ":", "# Determine if we have a cursor, and if so then decode it.", "encoded", "=", "request", ".", "query_params", ".", "get", "(", "self", ".", "cursor_query_param", ")", "if", "encoded", "is", "None", ":", ...
https://github.com/encode/django-rest-framework/blob/c5be86a6dbf3d21b00a296af5994fa075826bf0b/rest_framework/pagination.py#L845-L868
jcmgray/quimb
a54b22c61534be8acbc9efe4da97fb5c7f12057d
quimb/tensor/tensor_2d_tebd.py
python
SimpleUpdate.gauges
(self)
return self._gauges
The dictionary of bond pair coordinates to Tensors describing the weights (``t = gauges[pair]; t.data``) and index (``t = gauges[pair]; t.inds[0]``) of all the gauges.
The dictionary of bond pair coordinates to Tensors describing the weights (``t = gauges[pair]; t.data``) and index (``t = gauges[pair]; t.inds[0]``) of all the gauges.
[ "The", "dictionary", "of", "bond", "pair", "coordinates", "to", "Tensors", "describing", "the", "weights", "(", "t", "=", "gauges", "[", "pair", "]", ";", "t", ".", "data", ")", "and", "index", "(", "t", "=", "gauges", "[", "pair", "]", ";", "t", "...
def gauges(self): """The dictionary of bond pair coordinates to Tensors describing the weights (``t = gauges[pair]; t.data``) and index (``t = gauges[pair]; t.inds[0]``) of all the gauges. """ return self._gauges
[ "def", "gauges", "(", "self", ")", ":", "return", "self", ".", "_gauges" ]
https://github.com/jcmgray/quimb/blob/a54b22c61534be8acbc9efe4da97fb5c7f12057d/quimb/tensor/tensor_2d_tebd.py#L542-L547
inejc/paragraph-vectors
33f6465208f738a5dac69810d709459cc99ed704
paragraphvec/models.py
python
DM.forward
(self, context_ids, doc_ids, target_noise_ids)
return torch.bmm( x.unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze()
Sparse computation of scores (unnormalized log probabilities) that should be passed to the negative sampling loss. Parameters ---------- context_ids: torch.Tensor of size (batch_size, num_context_words) Vocabulary indices of context words. doc_ids: torch.Tensor of size (batch_size,) Document indices of paragraphs. target_noise_ids: torch.Tensor of size (batch_size, num_noise_words + 1) Vocabulary indices of target and noise words. The first element in each row is the ground truth index (i.e. the target), other elements are indices of samples from the noise distribution. Returns ------- autograd.Variable of size (batch_size, num_noise_words + 1)
Sparse computation of scores (unnormalized log probabilities) that should be passed to the negative sampling loss.
[ "Sparse", "computation", "of", "scores", "(", "unnormalized", "log", "probabilities", ")", "that", "should", "be", "passed", "to", "the", "negative", "sampling", "loss", "." ]
def forward(self, context_ids, doc_ids, target_noise_ids): """Sparse computation of scores (unnormalized log probabilities) that should be passed to the negative sampling loss. Parameters ---------- context_ids: torch.Tensor of size (batch_size, num_context_words) Vocabulary indices of context words. doc_ids: torch.Tensor of size (batch_size,) Document indices of paragraphs. target_noise_ids: torch.Tensor of size (batch_size, num_noise_words + 1) Vocabulary indices of target and noise words. The first element in each row is the ground truth index (i.e. the target), other elements are indices of samples from the noise distribution. Returns ------- autograd.Variable of size (batch_size, num_noise_words + 1) """ # combine a paragraph vector with word vectors of # input (context) words x = torch.add( self._D[doc_ids, :], torch.sum(self._W[context_ids, :], dim=1)) # sparse computation of scores (unnormalized log probabilities) # for negative sampling return torch.bmm( x.unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze()
[ "def", "forward", "(", "self", ",", "context_ids", ",", "doc_ids", ",", "target_noise_ids", ")", ":", "# combine a paragraph vector with word vectors of", "# input (context) words", "x", "=", "torch", ".", "add", "(", "self", ".", "_D", "[", "doc_ids", ",", ":", ...
https://github.com/inejc/paragraph-vectors/blob/33f6465208f738a5dac69810d709459cc99ed704/paragraphvec/models.py#L31-L61
rlabbe/filterpy
a437893597957764fb6b415bfb5640bb117f5b99
filterpy/leastsq/least_squares.py
python
LeastSquaresFilter.errors
(self)
return error, std
Computes and returns the error and standard deviation of the filter at this time step. Returns ------- error : np.array size 1xorder+1 std : np.array size 1xorder+1
Computes and returns the error and standard deviation of the filter at this time step.
[ "Computes", "and", "returns", "the", "error", "and", "standard", "deviation", "of", "the", "filter", "at", "this", "time", "step", "." ]
def errors(self): """ Computes and returns the error and standard deviation of the filter at this time step. Returns ------- error : np.array size 1xorder+1 std : np.array size 1xorder+1 """ n = self.n dt = self.dt order = self._order sigma = self.sigma error = np.zeros(order + 1) std = np.zeros(order + 1) if n == 0: return (error, std) if order == 0: error[0] = sigma/sqrt(n) std[0] = sigma/sqrt(n) elif order == 1: if n > 1: error[0] = sigma * sqrt(2*(2*n-1) / (n*(n+1))) error[1] = sigma * sqrt(12. / (n*(n*n-1)*dt*dt)) std[0] = sigma * sqrt((2*(2*n-1)) / (n*(n+1))) std[1] = (sigma/dt) * sqrt(12. / (n*(n*n-1))) elif order == 2: dt2 = dt * dt if n >= 3: error[0] = sigma * sqrt(3*(3*n*n-3*n+2) / (n*(n+1)*(n+2))) error[1] = sigma * sqrt(12*(16*n*n-30*n+11) / (n*(n*n-1)*(n*n-4)*dt2)) error[2] = sigma * sqrt(720/(n*(n*n-1)*(n*n-4)*dt2*dt2)) std[0] = sigma * sqrt((3*(3*n*n - 3*n + 2)) / (n*(n+1)*(n+2))) std[1] = (sigma/dt) * sqrt((12*(16*n*n - 30*n + 11)) / (n*(n*n - 1)*(n*n - 4))) std[2] = (sigma/dt2) * sqrt(720 / (n*(n*n-1)*(n*n-4))) return error, std
[ "def", "errors", "(", "self", ")", ":", "n", "=", "self", ".", "n", "dt", "=", "self", ".", "dt", "order", "=", "self", ".", "_order", "sigma", "=", "self", ".", "sigma", "error", "=", "np", ".", "zeros", "(", "order", "+", "1", ")", "std", "...
https://github.com/rlabbe/filterpy/blob/a437893597957764fb6b415bfb5640bb117f5b99/filterpy/leastsq/least_squares.py#L157-L205
GoSecure/pyrdp
abd8b8762b6d7fd0e49d4a927b529f892b412743
pyrdp/parser/rdp/orders/secondary.py
python
CacheBitmapV1.__str__
(self)
return (f'<CacheBitmapV1 {self.width}x{self.height}x{self.bpp}' f' Cache={self.cacheId}:{self.cacheIndex}>')
[]
def __str__(self): return (f'<CacheBitmapV1 {self.width}x{self.height}x{self.bpp}' f' Cache={self.cacheId}:{self.cacheIndex}>')
[ "def", "__str__", "(", "self", ")", ":", "return", "(", "f'<CacheBitmapV1 {self.width}x{self.height}x{self.bpp}'", "f' Cache={self.cacheId}:{self.cacheIndex}>'", ")" ]
https://github.com/GoSecure/pyrdp/blob/abd8b8762b6d7fd0e49d4a927b529f892b412743/pyrdp/parser/rdp/orders/secondary.py#L116-L118
conorpp/btproxy
cd1c90688502852b55f139cc5202b487e7068c89
libbtproxy/utils.py
python
print_verbose
(*args)
[]
def print_verbose(*args): global print_lock if argparser.args.verbose: with print_lock: print(*args)
[ "def", "print_verbose", "(", "*", "args", ")", ":", "global", "print_lock", "if", "argparser", ".", "args", ".", "verbose", ":", "with", "print_lock", ":", "print", "(", "*", "args", ")" ]
https://github.com/conorpp/btproxy/blob/cd1c90688502852b55f139cc5202b487e7068c89/libbtproxy/utils.py#L27-L31
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/python27/1.0/lib/darwin/gevent/ssl.py
python
sslwrap_simple
(sock, keyfile=None, certfile=None)
return SSLSocket(sock, keyfile, certfile)
A replacement for the old socket.ssl function. Designed for compability with Python 2.5 and earlier. Will disappear in Python 3.0.
A replacement for the old socket.ssl function. Designed for compability with Python 2.5 and earlier. Will disappear in Python 3.0.
[ "A", "replacement", "for", "the", "old", "socket", ".", "ssl", "function", ".", "Designed", "for", "compability", "with", "Python", "2", ".", "5", "and", "earlier", ".", "Will", "disappear", "in", "Python", "3", ".", "0", "." ]
def sslwrap_simple(sock, keyfile=None, certfile=None): """A replacement for the old socket.ssl function. Designed for compability with Python 2.5 and earlier. Will disappear in Python 3.0.""" return SSLSocket(sock, keyfile, certfile)
[ "def", "sslwrap_simple", "(", "sock", ",", "keyfile", "=", "None", ",", "certfile", "=", "None", ")", ":", "return", "SSLSocket", "(", "sock", ",", "keyfile", ",", "certfile", ")" ]
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/python27/1.0/lib/darwin/gevent/ssl.py#L405-L409
hacktoolkit/django-htk
902f3780630f1308aa97a70b9b62a5682239ff2d
lib/stripe_lib/utils.py
python
_log_event_rollbar
(event, request=None, log_level='info', message=None)
Log the Stripe event `event` to Rollbar
Log the Stripe event `event` to Rollbar
[ "Log", "the", "Stripe", "event", "event", "to", "Rollbar" ]
def _log_event_rollbar(event, request=None, log_level='info', message=None): """Log the Stripe event `event` to Rollbar """ if message: message = '%s - Stripe Event: %s' % (message, get_event_type(event),) else: message = 'Stripe Event: %s' % get_event_type(event) extra_data = { 'event' : event, } rollbar.report_message(message, log_level, request, extra_data=extra_data)
[ "def", "_log_event_rollbar", "(", "event", ",", "request", "=", "None", ",", "log_level", "=", "'info'", ",", "message", "=", "None", ")", ":", "if", "message", ":", "message", "=", "'%s - Stripe Event: %s'", "%", "(", "message", ",", "get_event_type", "(", ...
https://github.com/hacktoolkit/django-htk/blob/902f3780630f1308aa97a70b9b62a5682239ff2d/lib/stripe_lib/utils.py#L266-L276