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
tipam/pi3d
1f1c822dc3ac58344ad2d5468978d62e51710df4
pi3d/shape/MergeShape.py
python
MergeShape.cluster
(self, bufr, elevmap, xpos, zpos, w, d, count, options, minscl, maxscl, bufnum=0, billboard=False)
generates a random cluster on an ElevationMap. Arguments: *bufr* Buffer object to merge. *elevmap* ElevationMap object to merge onto. *xpos, zpos* x and z location of centre of cluster. These are locations RELATIVE to the origin of the MergeShape *w, d* x and z direction size of the cluster. *count* Number of objects to generate. *options* Deprecated. *minscl* The minimum scale value for random selection. *maxscl* The maximum scale value for random selection. *billboard* If True then all Buffers are set rotated 180 degrees so that they turn to face Camera location when billboard() called
generates a random cluster on an ElevationMap.
[ "generates", "a", "random", "cluster", "on", "an", "ElevationMap", "." ]
def cluster(self, bufr, elevmap, xpos, zpos, w, d, count, options, minscl, maxscl, bufnum=0, billboard=False): """generates a random cluster on an ElevationMap. Arguments: *bufr* Buffer object to merge. *elevmap* ElevationMap object to merge onto. *xpos, zpos* x and z location of centre of cluster. These are locations RELATIVE to the origin of the MergeShape *w, d* x and z direction size of the cluster. *count* Number of objects to generate. *options* Deprecated. *minscl* The minimum scale value for random selection. *maxscl* The maximum scale value for random selection. *billboard* If True then all Buffers are set rotated 180 degrees so that they turn to face Camera location when billboard() called """ #create a cluster of shapes on an elevation map blist = [] for _ in range(count): x = xpos + random.random() * w - w * 0.5 z = zpos + random.random() * d - d * 0.5 rh = random.random() * (maxscl - minscl) + minscl if billboard: rt = 180.0 else: rt = random.random() * 360.0 y = elevmap.calcHeight(self.unif[0] + x, self.unif[2] + z) + rh * 2 blist.append([bufr, x, y, z, 0.0, rt, 0.0, rh, rh, rh, bufnum]) self.merge(blist)
[ "def", "cluster", "(", "self", ",", "bufr", ",", "elevmap", ",", "xpos", ",", "zpos", ",", "w", ",", "d", ",", "count", ",", "options", ",", "minscl", ",", "maxscl", ",", "bufnum", "=", "0", ",", "billboard", "=", "False", ")", ":", "#create a clus...
https://github.com/tipam/pi3d/blob/1f1c822dc3ac58344ad2d5468978d62e51710df4/pi3d/shape/MergeShape.py#L179-L216
pypa/setuptools
9f37366aab9cd8f6baa23e6a77cfdb8daf97757e
setuptools/_vendor/more_itertools/more.py
python
map_reduce
(iterable, keyfunc, valuefunc=None, reducefunc=None)
return ret
Return a dictionary that maps the items in *iterable* to categories defined by *keyfunc*, transforms them with *valuefunc*, and then summarizes them by category with *reducefunc*. *valuefunc* defaults to the identity function if it is unspecified. If *reducefunc* is unspecified, no summarization takes place: >>> keyfunc = lambda x: x.upper() >>> result = map_reduce('abbccc', keyfunc) >>> sorted(result.items()) [('A', ['a']), ('B', ['b', 'b']), ('C', ['c', 'c', 'c'])] Specifying *valuefunc* transforms the categorized items: >>> keyfunc = lambda x: x.upper() >>> valuefunc = lambda x: 1 >>> result = map_reduce('abbccc', keyfunc, valuefunc) >>> sorted(result.items()) [('A', [1]), ('B', [1, 1]), ('C', [1, 1, 1])] Specifying *reducefunc* summarizes the categorized items: >>> keyfunc = lambda x: x.upper() >>> valuefunc = lambda x: 1 >>> reducefunc = sum >>> result = map_reduce('abbccc', keyfunc, valuefunc, reducefunc) >>> sorted(result.items()) [('A', 1), ('B', 2), ('C', 3)] You may want to filter the input iterable before applying the map/reduce procedure: >>> all_items = range(30) >>> items = [x for x in all_items if 10 <= x <= 20] # Filter >>> keyfunc = lambda x: x % 2 # Evens map to 0; odds to 1 >>> categories = map_reduce(items, keyfunc=keyfunc) >>> sorted(categories.items()) [(0, [10, 12, 14, 16, 18, 20]), (1, [11, 13, 15, 17, 19])] >>> summaries = map_reduce(items, keyfunc=keyfunc, reducefunc=sum) >>> sorted(summaries.items()) [(0, 90), (1, 75)] Note that all items in the iterable are gathered into a list before the summarization step, which may require significant storage. The returned object is a :obj:`collections.defaultdict` with the ``default_factory`` set to ``None``, such that it behaves like a normal dictionary.
Return a dictionary that maps the items in *iterable* to categories defined by *keyfunc*, transforms them with *valuefunc*, and then summarizes them by category with *reducefunc*.
[ "Return", "a", "dictionary", "that", "maps", "the", "items", "in", "*", "iterable", "*", "to", "categories", "defined", "by", "*", "keyfunc", "*", "transforms", "them", "with", "*", "valuefunc", "*", "and", "then", "summarizes", "them", "by", "category", "...
def map_reduce(iterable, keyfunc, valuefunc=None, reducefunc=None): """Return a dictionary that maps the items in *iterable* to categories defined by *keyfunc*, transforms them with *valuefunc*, and then summarizes them by category with *reducefunc*. *valuefunc* defaults to the identity function if it is unspecified. If *reducefunc* is unspecified, no summarization takes place: >>> keyfunc = lambda x: x.upper() >>> result = map_reduce('abbccc', keyfunc) >>> sorted(result.items()) [('A', ['a']), ('B', ['b', 'b']), ('C', ['c', 'c', 'c'])] Specifying *valuefunc* transforms the categorized items: >>> keyfunc = lambda x: x.upper() >>> valuefunc = lambda x: 1 >>> result = map_reduce('abbccc', keyfunc, valuefunc) >>> sorted(result.items()) [('A', [1]), ('B', [1, 1]), ('C', [1, 1, 1])] Specifying *reducefunc* summarizes the categorized items: >>> keyfunc = lambda x: x.upper() >>> valuefunc = lambda x: 1 >>> reducefunc = sum >>> result = map_reduce('abbccc', keyfunc, valuefunc, reducefunc) >>> sorted(result.items()) [('A', 1), ('B', 2), ('C', 3)] You may want to filter the input iterable before applying the map/reduce procedure: >>> all_items = range(30) >>> items = [x for x in all_items if 10 <= x <= 20] # Filter >>> keyfunc = lambda x: x % 2 # Evens map to 0; odds to 1 >>> categories = map_reduce(items, keyfunc=keyfunc) >>> sorted(categories.items()) [(0, [10, 12, 14, 16, 18, 20]), (1, [11, 13, 15, 17, 19])] >>> summaries = map_reduce(items, keyfunc=keyfunc, reducefunc=sum) >>> sorted(summaries.items()) [(0, 90), (1, 75)] Note that all items in the iterable are gathered into a list before the summarization step, which may require significant storage. The returned object is a :obj:`collections.defaultdict` with the ``default_factory`` set to ``None``, such that it behaves like a normal dictionary. """ valuefunc = (lambda x: x) if (valuefunc is None) else valuefunc ret = defaultdict(list) for item in iterable: key = keyfunc(item) value = valuefunc(item) ret[key].append(value) if reducefunc is not None: for key, value_list in ret.items(): ret[key] = reducefunc(value_list) ret.default_factory = None return ret
[ "def", "map_reduce", "(", "iterable", ",", "keyfunc", ",", "valuefunc", "=", "None", ",", "reducefunc", "=", "None", ")", ":", "valuefunc", "=", "(", "lambda", "x", ":", "x", ")", "if", "(", "valuefunc", "is", "None", ")", "else", "valuefunc", "ret", ...
https://github.com/pypa/setuptools/blob/9f37366aab9cd8f6baa23e6a77cfdb8daf97757e/setuptools/_vendor/more_itertools/more.py#L2825-L2889
w3h/isf
6faf0a3df185465ec17369c90ccc16e2a03a1870
lib/thirdparty/katnip/controllers/client/ssh.py
python
ClientSshController.post_test
(self)
Log output of process, check if crashed
Log output of process, check if crashed
[ "Log", "output", "of", "process", "check", "if", "crashed" ]
def post_test(self): ''' Log output of process, check if crashed ''' self._stdout.channel.settimeout(3) self._stderr.channel.settimeout(3) self.logger.debug('reading stdout...') try: self.report.add('stdout', self._stdout.read()) self.logger.debug('getting process return code...') return_code = self._stdout.channel.recv_exit_status() self.logger.debug('return code: %d', return_code) self.report.add('return_code', return_code) except socket.timeout: self.report.add('stdout', 'Timeout reading stdout.)') return_code = -2 self.report.add('return_code', return_code) self.logger.debug('return code: %d', return_code) self.logger.debug('reading stderr...') try: self.report.add('stderr', self._stderr.read()) except socket.timeout: self.report.add('stderr', 'Timeout reading stderr.)') self.report.add('failed', return_code < 0) self._stop_process() self._ssh.close() super(ClientSshController, self).post_test()
[ "def", "post_test", "(", "self", ")", ":", "self", ".", "_stdout", ".", "channel", ".", "settimeout", "(", "3", ")", "self", ".", "_stderr", ".", "channel", ".", "settimeout", "(", "3", ")", "self", ".", "logger", ".", "debug", "(", "'reading stdout......
https://github.com/w3h/isf/blob/6faf0a3df185465ec17369c90ccc16e2a03a1870/lib/thirdparty/katnip/controllers/client/ssh.py#L69-L95
lutris/lutris
66675a4d5537f6b2a2ba2b6df0b3cdf8924c823a
lutris/command.py
python
MonitoredCommand.on_stdout_output
(self, stdout, condition)
return True
Called by the stdout monitor to dispatch output to log handlers
Called by the stdout monitor to dispatch output to log handlers
[ "Called", "by", "the", "stdout", "monitor", "to", "dispatch", "output", "to", "log", "handlers" ]
def on_stdout_output(self, stdout, condition): """Called by the stdout monitor to dispatch output to log handlers""" if condition == GLib.IO_HUP: self.stdout_monitor = None return False if not self.is_running: return False try: line = stdout.read(262144).decode("utf-8", errors="ignore") except ValueError: # file_desc might be closed return True if "winemenubuilder.exe" in line: return True for log_handler in self.log_handlers: log_handler(line) return True
[ "def", "on_stdout_output", "(", "self", ",", "stdout", ",", "condition", ")", ":", "if", "condition", "==", "GLib", ".", "IO_HUP", ":", "self", ".", "stdout_monitor", "=", "None", "return", "False", "if", "not", "self", ".", "is_running", ":", "return", ...
https://github.com/lutris/lutris/blob/66675a4d5537f6b2a2ba2b6df0b3cdf8924c823a/lutris/command.py#L200-L216
pypa/setuptools
9f37366aab9cd8f6baa23e6a77cfdb8daf97757e
setuptools/dist.py
python
Distribution.get_command_class
(self, command)
Pluggable version of get_command_class()
Pluggable version of get_command_class()
[ "Pluggable", "version", "of", "get_command_class", "()" ]
def get_command_class(self, command): """Pluggable version of get_command_class()""" if command in self.cmdclass: return self.cmdclass[command] eps = pkg_resources.iter_entry_points('distutils.commands', command) for ep in eps: ep.require(installer=self.fetch_build_egg) self.cmdclass[command] = cmdclass = ep.load() return cmdclass else: return _Distribution.get_command_class(self, command)
[ "def", "get_command_class", "(", "self", ",", "command", ")", ":", "if", "command", "in", "self", ".", "cmdclass", ":", "return", "self", ".", "cmdclass", "[", "command", "]", "eps", "=", "pkg_resources", ".", "iter_entry_points", "(", "'distutils.commands'", ...
https://github.com/pypa/setuptools/blob/9f37366aab9cd8f6baa23e6a77cfdb8daf97757e/setuptools/dist.py#L885-L896
w3h/isf
6faf0a3df185465ec17369c90ccc16e2a03a1870
lib/thirdparty/kitty/model/high_level/base.py
python
BaseModel.get_sequence
(self)
return self._sequence[:]
:rtype: [Connection] :return: Sequence of current case
:rtype: [Connection] :return: Sequence of current case
[ ":", "rtype", ":", "[", "Connection", "]", ":", "return", ":", "Sequence", "of", "current", "case" ]
def get_sequence(self): ''' :rtype: [Connection] :return: Sequence of current case ''' self._get_ready() assert self._sequence return self._sequence[:]
[ "def", "get_sequence", "(", "self", ")", ":", "self", ".", "_get_ready", "(", ")", "assert", "self", ".", "_sequence", "return", "self", ".", "_sequence", "[", ":", "]" ]
https://github.com/w3h/isf/blob/6faf0a3df185465ec17369c90ccc16e2a03a1870/lib/thirdparty/kitty/model/high_level/base.py#L149-L156
Alexander-H-Liu/End-to-end-ASR-Pytorch
1103d144423e8e692f1d18cd9db27a96cb49fb9d
bin/train_lm.py
python
Solver.__init__
(self, config, paras, mode)
[]
def __init__(self, config, paras, mode): super().__init__(config, paras, mode) # Logger settings self.best_loss = 10
[ "def", "__init__", "(", "self", ",", "config", ",", "paras", ",", "mode", ")", ":", "super", "(", ")", ".", "__init__", "(", "config", ",", "paras", ",", "mode", ")", "# Logger settings", "self", ".", "best_loss", "=", "10" ]
https://github.com/Alexander-H-Liu/End-to-end-ASR-Pytorch/blob/1103d144423e8e692f1d18cd9db27a96cb49fb9d/bin/train_lm.py#L13-L16
RDFLib/rdflib
c0bd5eaaa983461445b9469d731be4ae0e0cfc54
rdflib/plugins/parsers/ntriples.py
python
W3CNTriplesParser.parsestring
(self, s: Union[bytes, bytearray, str], **kwargs)
Parse s as an N-Triples string.
Parse s as an N-Triples string.
[ "Parse", "s", "as", "an", "N", "-", "Triples", "string", "." ]
def parsestring(self, s: Union[bytes, bytearray, str], **kwargs): """Parse s as an N-Triples string.""" if not isinstance(s, (str, bytes, bytearray)): raise ParseError("Item to parse must be a string instance.") f: Union[codecs.StreamReader, StringIO] if isinstance(s, (bytes, bytearray)): f = codecs.getreader("utf-8")(BytesIO(s)) else: f = StringIO(s) self.parse(f, **kwargs)
[ "def", "parsestring", "(", "self", ",", "s", ":", "Union", "[", "bytes", ",", "bytearray", ",", "str", "]", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "s", ",", "(", "str", ",", "bytes", ",", "bytearray", ")", ")", ":", ...
https://github.com/RDFLib/rdflib/blob/c0bd5eaaa983461445b9469d731be4ae0e0cfc54/rdflib/plugins/parsers/ntriples.py#L175-L184
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/qtconsole/rich_jupyter_widget.py
python
RichJupyterWidget._handle_display_data
(self, msg)
Overridden to handle rich data types, like SVG.
Overridden to handle rich data types, like SVG.
[ "Overridden", "to", "handle", "rich", "data", "types", "like", "SVG", "." ]
def _handle_display_data(self, msg): """Overridden to handle rich data types, like SVG.""" self.log.debug("display_data: %s", msg.get('content', '')) if self.include_output(msg): self.flush_clearoutput() data = msg['content']['data'] metadata = msg['content']['metadata'] # Try to use the svg or html representations. # FIXME: Is this the right ordering of things to try? self.log.debug("display: %s", msg.get('content', '')) if 'image/svg+xml' in data: svg = data['image/svg+xml'] self._append_svg(svg, True) elif 'image/png' in data: # PNG data is base64 encoded as it passes over the network # in a JSON structure so we decode it. png = b64decode(data['image/png'].encode('ascii')) self._append_png(png, True, metadata=metadata.get('image/png', None)) elif 'image/jpeg' in data and self._jpg_supported: jpg = b64decode(data['image/jpeg'].encode('ascii')) self._append_jpg(jpg, True, metadata=metadata.get('image/jpeg', None)) elif 'text/latex' in data and latex_to_png: try: self._append_latex(data['text/latex'], True) except LatexError: return super(RichJupyterWidget, self)._handle_display_data(msg) else: # Default back to the plain text representation. return super(RichJupyterWidget, self)._handle_display_data(msg)
[ "def", "_handle_display_data", "(", "self", ",", "msg", ")", ":", "self", ".", "log", ".", "debug", "(", "\"display_data: %s\"", ",", "msg", ".", "get", "(", "'content'", ",", "''", ")", ")", "if", "self", ".", "include_output", "(", "msg", ")", ":", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/qtconsole/rich_jupyter_widget.py#L155-L183
beeware/ouroboros
a29123c6fab6a807caffbb7587cf548e0c370296
ouroboros/inspect.py
python
classify_class_attrs
(cls)
return result
Return list of attribute-descriptor tuples. For each name in dir(cls), the return list contains a 4-tuple with these elements: 0. The name (a string). 1. The kind of attribute this is, one of these strings: 'class method' created via classmethod() 'static method' created via staticmethod() 'property' created via property() 'method' any other flavor of method or descriptor 'data' not a method 2. The class which defined this attribute (a class). 3. The object as obtained by calling getattr; if this fails, or if the resulting object does not live anywhere in the class' mro (including metaclasses) then the object is looked up in the defining class's dict (found by walking the mro). If one of the items in dir(cls) is stored in the metaclass it will now be discovered and not have None be listed as the class in which it was defined. Any items whose home class cannot be discovered are skipped.
Return list of attribute-descriptor tuples.
[ "Return", "list", "of", "attribute", "-", "descriptor", "tuples", "." ]
def classify_class_attrs(cls): """Return list of attribute-descriptor tuples. For each name in dir(cls), the return list contains a 4-tuple with these elements: 0. The name (a string). 1. The kind of attribute this is, one of these strings: 'class method' created via classmethod() 'static method' created via staticmethod() 'property' created via property() 'method' any other flavor of method or descriptor 'data' not a method 2. The class which defined this attribute (a class). 3. The object as obtained by calling getattr; if this fails, or if the resulting object does not live anywhere in the class' mro (including metaclasses) then the object is looked up in the defining class's dict (found by walking the mro). If one of the items in dir(cls) is stored in the metaclass it will now be discovered and not have None be listed as the class in which it was defined. Any items whose home class cannot be discovered are skipped. """ mro = getmro(cls) metamro = getmro(type(cls)) # for attributes stored in the metaclass metamro = tuple([cls for cls in metamro if cls not in (type, object)]) class_bases = (cls,) + mro all_bases = class_bases + metamro names = dir(cls) # :dd any DynamicClassAttributes to the list of names; # this may result in duplicate entries if, for example, a virtual # attribute with the same name as a DynamicClassAttribute exists. for base in mro: for k, v in base.__dict__.items(): if isinstance(v, types.DynamicClassAttribute): names.append(k) result = [] processed = set() for name in names: # Get the object associated with the name, and where it was defined. # Normal objects will be looked up with both getattr and directly in # its class' dict (in case getattr fails [bug #1785], and also to look # for a docstring). # For DynamicClassAttributes on the second pass we only look in the # class's dict. # # Getting an obj from the __dict__ sometimes reveals more than # using getattr. Static and class methods are dramatic examples. homecls = None get_obj = None dict_obj = None if name not in processed: try: if name == '__dict__': raise Exception("__dict__ is special, don't want the proxy") get_obj = getattr(cls, name) except Exception as exc: pass else: homecls = getattr(get_obj, "__objclass__", homecls) if homecls not in class_bases: # if the resulting object does not live somewhere in the # mro, drop it and search the mro manually homecls = None last_cls = None # first look in the classes for srch_cls in class_bases: srch_obj = getattr(srch_cls, name, None) if srch_obj is get_obj: last_cls = srch_cls # then check the metaclasses for srch_cls in metamro: try: srch_obj = srch_cls.__getattr__(cls, name) except AttributeError: continue if srch_obj is get_obj: last_cls = srch_cls if last_cls is not None: homecls = last_cls for base in all_bases: if name in base.__dict__: dict_obj = base.__dict__[name] if homecls not in metamro: homecls = base break if homecls is None: # unable to locate the attribute anywhere, most likely due to # buggy custom __dir__; discard and move on continue obj = get_obj if get_obj is not None else dict_obj # Classify the object or its descriptor. if isinstance(dict_obj, staticmethod): kind = "static method" obj = dict_obj elif isinstance(dict_obj, classmethod): kind = "class method" obj = dict_obj elif isinstance(dict_obj, property): kind = "property" obj = dict_obj elif isroutine(obj): kind = "method" else: kind = "data" result.append(Attribute(name, kind, homecls, obj)) processed.add(name) return result
[ "def", "classify_class_attrs", "(", "cls", ")", ":", "mro", "=", "getmro", "(", "cls", ")", "metamro", "=", "getmro", "(", "type", "(", "cls", ")", ")", "# for attributes stored in the metaclass", "metamro", "=", "tuple", "(", "[", "cls", "for", "cls", "in...
https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/inspect.py#L310-L422
lzrobots/DeepEmbeddingModel_ZSL
2d950282c1555054c0cd7d9a758f2815e4ef52d5
kNN_cosine.py
python
createDataSet
()
return group, labels
[]
def createDataSet(): # create a matrix: each row as a sample group = array([[1.0, 0.9], [1.0, 1.0], [0.1, 0.2], [0.0, 0.1]]) labels = ['A', 'A', 'B', 'B'] # four samples and two classes return group, labels
[ "def", "createDataSet", "(", ")", ":", "# create a matrix: each row as a sample ", "group", "=", "array", "(", "[", "[", "1.0", ",", "0.9", "]", ",", "[", "1.0", ",", "1.0", "]", ",", "[", "0.1", ",", "0.2", "]", ",", "[", "0.0", ",", "0.1", "]", ...
https://github.com/lzrobots/DeepEmbeddingModel_ZSL/blob/2d950282c1555054c0cd7d9a758f2815e4ef52d5/kNN_cosine.py#L19-L23
pyvista/pyvista
012dbb95a9aae406c3cd4cd94fc8c477f871e426
pyvista/utilities/reader.py
python
PVDReader.active_readers
(self)
return self._active_readers
Return the active readers. Returns ------- list[pyvista.BaseReader]
Return the active readers.
[ "Return", "the", "active", "readers", "." ]
def active_readers(self): """Return the active readers. Returns ------- list[pyvista.BaseReader] """ return self._active_readers
[ "def", "active_readers", "(", "self", ")", ":", "return", "self", ".", "_active_readers" ]
https://github.com/pyvista/pyvista/blob/012dbb95a9aae406c3cd4cd94fc8c477f871e426/pyvista/utilities/reader.py#L1056-L1064
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/_vendor/requests/models.py
python
Response.iter_content
(self, chunk_size=1, decode_unicode=False)
return chunks
Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. chunk_size must be of type int or None. A value of None will function differently depending on the value of `stream`. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk. If decode_unicode is True, content will be decoded using the best available encoding based on the response.
Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place.
[ "Iterates", "over", "the", "response", "data", ".", "When", "stream", "=", "True", "is", "set", "on", "the", "request", "this", "avoids", "reading", "the", "content", "at", "once", "into", "memory", "for", "large", "responses", ".", "The", "chunk", "size",...
def iter_content(self, chunk_size=1, decode_unicode=False): """Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. chunk_size must be of type int or None. A value of None will function differently depending on the value of `stream`. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk. If decode_unicode is True, content will be decoded using the best available encoding based on the response. """ def generate(): # Special case for urllib3. if hasattr(self.raw, 'stream'): try: for chunk in self.raw.stream(chunk_size, decode_content=True): yield chunk except ProtocolError as e: raise ChunkedEncodingError(e) except DecodeError as e: raise ContentDecodingError(e) except ReadTimeoutError as e: raise ConnectionError(e) else: # Standard file-like object. while True: chunk = self.raw.read(chunk_size) if not chunk: break yield chunk self._content_consumed = True if self._content_consumed and isinstance(self._content, bool): raise StreamConsumedError() elif chunk_size is not None and not isinstance(chunk_size, int): raise TypeError("chunk_size must be an int, it is instead a %s." % type(chunk_size)) # simulate reading small chunks of the content reused_chunks = iter_slices(self._content, chunk_size) stream_chunks = generate() chunks = reused_chunks if self._content_consumed else stream_chunks if decode_unicode: chunks = stream_decode_response_unicode(chunks, self) return chunks
[ "def", "iter_content", "(", "self", ",", "chunk_size", "=", "1", ",", "decode_unicode", "=", "False", ")", ":", "def", "generate", "(", ")", ":", "# Special case for urllib3.", "if", "hasattr", "(", "self", ".", "raw", ",", "'stream'", ")", ":", "try", "...
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/_vendor/requests/models.py#L655-L708
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
lib-python/2.7/sgmllib.py
python
SGMLParser.convert_entityref
(self, name)
Convert entity references. As an alternative to overriding this method; one can tailor the results by setting up the self.entitydefs mapping appropriately.
Convert entity references.
[ "Convert", "entity", "references", "." ]
def convert_entityref(self, name): """Convert entity references. As an alternative to overriding this method; one can tailor the results by setting up the self.entitydefs mapping appropriately. """ table = self.entitydefs if name in table: return table[name] else: return
[ "def", "convert_entityref", "(", "self", ",", "name", ")", ":", "table", "=", "self", ".", "entitydefs", "if", "name", "in", "table", ":", "return", "table", "[", "name", "]", "else", ":", "return" ]
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/sgmllib.py#L418-L428
USEPA/WNTR
2f92bab5736da6ef3591fc4b0229ec1ac6cd6fcc
wntr/network/model.py
python
LinkRegistry.psv_names
(self)
return self._psvs
A list of all psv names
A list of all psv names
[ "A", "list", "of", "all", "psv", "names" ]
def psv_names(self): """A list of all psv names""" return self._psvs
[ "def", "psv_names", "(", "self", ")", ":", "return", "self", ".", "_psvs" ]
https://github.com/USEPA/WNTR/blob/2f92bab5736da6ef3591fc4b0229ec1ac6cd6fcc/wntr/network/model.py#L2439-L2441
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/settings.py
python
disable_debug_log
()
[]
def disable_debug_log(): LOGGING['root']['handlers'].remove('debug_file')
[ "def", "disable_debug_log", "(", ")", ":", "LOGGING", "[", "'root'", "]", "[", "'handlers'", "]", ".", "remove", "(", "'debug_file'", ")" ]
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/settings.py#L438-L439
deepmind/spriteworld
ace9e186ee9a819e8f4de070bd11cf27e2265b63
spriteworld/factor_distributions.py
python
Discrete.__init__
(self, key, candidates, probs=None)
Construct discrete distribution. Args: key: String. Factor name. candidates: Iterable. Discrete values to sample from. probs: None or iterable of floats summing to 1. Candidate sampling probabilities. If None, candidates are sampled uniformly.
Construct discrete distribution.
[ "Construct", "discrete", "distribution", "." ]
def __init__(self, key, candidates, probs=None): """Construct discrete distribution. Args: key: String. Factor name. candidates: Iterable. Discrete values to sample from. probs: None or iterable of floats summing to 1. Candidate sampling probabilities. If None, candidates are sampled uniformly. """ self.candidates = candidates self.key = key self.probs = probs
[ "def", "__init__", "(", "self", ",", "key", ",", "candidates", ",", "probs", "=", "None", ")", ":", "self", ".", "candidates", "=", "candidates", "self", ".", "key", "=", "key", "self", ".", "probs", "=", "probs" ]
https://github.com/deepmind/spriteworld/blob/ace9e186ee9a819e8f4de070bd11cf27e2265b63/spriteworld/factor_distributions.py#L126-L137
ping/instagram_private_api
0fda0369ac02bc03d56f5f3f99bc9de2cc25ffaa
instagram_private_api/endpoints/tags.py
python
TagsEndpointsMixin.tag_follow
(self, tag)
return self._call_api(endpoint, params=self.authenticated_params)
Follow a tag :param tag: :return:
Follow a tag
[ "Follow", "a", "tag" ]
def tag_follow(self, tag): """ Follow a tag :param tag: :return: """ endpoint = 'tags/follow/{hashtag!s}/'.format( hashtag=compat_urllib_parse.quote(tag.encode('utf-8'))) return self._call_api(endpoint, params=self.authenticated_params)
[ "def", "tag_follow", "(", "self", ",", "tag", ")", ":", "endpoint", "=", "'tags/follow/{hashtag!s}/'", ".", "format", "(", "hashtag", "=", "compat_urllib_parse", ".", "quote", "(", "tag", ".", "encode", "(", "'utf-8'", ")", ")", ")", "return", "self", ".",...
https://github.com/ping/instagram_private_api/blob/0fda0369ac02bc03d56f5f3f99bc9de2cc25ffaa/instagram_private_api/endpoints/tags.py#L77-L86
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/ne1_ui/prefs/Preferences.py
python
Preferences.change_dnaStyleAxisShape
(self, shape)
Changes DNA Style strands shape. @param shape: The shape mode: - 0 = none (hidden) - 1 = wide tube - 2 = narrow tube @type shape: int
Changes DNA Style strands shape.
[ "Changes", "DNA", "Style", "strands", "shape", "." ]
def change_dnaStyleAxisShape(self, shape): """ Changes DNA Style strands shape. @param shape: The shape mode: - 0 = none (hidden) - 1 = wide tube - 2 = narrow tube @type shape: int """ env.prefs[dnaStyleAxisShape_prefs_key] = shape
[ "def", "change_dnaStyleAxisShape", "(", "self", ",", "shape", ")", ":", "env", ".", "prefs", "[", "dnaStyleAxisShape_prefs_key", "]", "=", "shape" ]
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/ne1_ui/prefs/Preferences.py#L2434-L2445
mattupstate/flask-principal
0b5cd06b464ae8b60939857784bda86c03dda1eb
flask_principal.py
python
Permission.difference
(self, other)
return p
Create a new permission consisting of requirements in this permission and not in the other.
Create a new permission consisting of requirements in this permission and not in the other.
[ "Create", "a", "new", "permission", "consisting", "of", "requirements", "in", "this", "permission", "and", "not", "in", "the", "other", "." ]
def difference(self, other): """Create a new permission consisting of requirements in this permission and not in the other. """ p = Permission(*self.needs.difference(other.needs)) p.excludes.update(self.excludes.difference(other.excludes)) return p
[ "def", "difference", "(", "self", ",", "other", ")", ":", "p", "=", "Permission", "(", "*", "self", ".", "needs", ".", "difference", "(", "other", ".", "needs", ")", ")", "p", ".", "excludes", ".", "update", "(", "self", ".", "excludes", ".", "diff...
https://github.com/mattupstate/flask-principal/blob/0b5cd06b464ae8b60939857784bda86c03dda1eb/flask_principal.py#L309-L316
jesse-ai/jesse
28759547138fbc76dff12741204833e39c93b083
jesse/modes/optimize_mode/Optimize.py
python
Optimizer.generate_initial_population
(self)
generates the initial population
generates the initial population
[ "generates", "the", "initial", "population" ]
def generate_initial_population(self) -> None: """ generates the initial population """ length = int(self.population_size / self.cpu_cores) progressbar = Progressbar(length) for i in range(length): people = [] with Manager() as manager: dna_bucket = manager.list([]) workers = [] try: for _ in range(self.cpu_cores): dna = ''.join(choices(self.charset, k=self.solution_len)) w = Process( target=get_and_add_fitness_to_the_bucket, args=( dna_bucket, jh.get_config('env.optimization'), router.formatted_routes, router.formatted_extra_routes, self.strategy_hp, dna, self.training_candles, self.testing_candles, self.optimal_total ) ) w.start() workers.append(w) # join workers for w in workers: w.join() if w.exitcode > 0: logger.error(f'a process exited with exitcode: {w.exitcode}') except exceptions.Termination: self._handle_termination(manager, workers) for d in dna_bucket: people.append({ 'dna': d[0], 'fitness': d[1], 'training_log': d[2], 'testing_log': d[3] }) # update dashboard self.update_progressbar(progressbar) # general_info streams general_info = { 'started_at': jh.timestamp_to_arrow(self.start_time).humanize(), 'index': f'{(i + 1) * self.cpu_cores}/{self.population_size}', 'errors_info_count': f'{len(store.logs.errors)}/{len(store.logs.info)}', 'trading_route': f'{router.routes[0].exchange}, {router.routes[0].symbol}, {router.routes[0].timeframe}, {router.routes[0].strategy_name}', 'average_execution_seconds': self.average_execution_seconds } if jh.is_debugging(): general_info['population_size'] = self.population_size general_info['iterations'] = self.iterations general_info['solution_length'] = self.solution_len sync_publish('general_info', general_info) for p in people: self.population.append(p) sync_publish('progressbar', { 'current': 100, 'estimated_remaining_seconds': 0 }) # sort the population self.population = list(sorted(self.population, key=lambda x: x['fitness'], reverse=True))
[ "def", "generate_initial_population", "(", "self", ")", "->", "None", ":", "length", "=", "int", "(", "self", ".", "population_size", "/", "self", ".", "cpu_cores", ")", "progressbar", "=", "Progressbar", "(", "length", ")", "for", "i", "in", "range", "(",...
https://github.com/jesse-ai/jesse/blob/28759547138fbc76dff12741204833e39c93b083/jesse/modes/optimize_mode/Optimize.py#L110-L178
landlab/landlab
a5dd80b8ebfd03d1ba87ef6c4368c409485f222c
landlab/components/lithology/lithology.py
python
Lithology.z_top
(self)
return thick - self._layers.z
Thickness from the surface to the top of each layer in Lithology. Thickness from the topographic surface to the top of each layer as an array of shape `(number_of_layers, number_of_nodes)`. Examples -------- >>> from landlab import RasterModelGrid >>> from landlab.components import Lithology >>> mg = RasterModelGrid((3, 3)) >>> z = mg.add_zeros("topographic__elevation", at="node") >>> thicknesses = [1, 2, 4, 1] >>> ids = [1, 2, 1, 2] >>> attrs = {'K_sp': {1: 0.001, ... 2: 0.0001}} >>> lith = Lithology(mg, thicknesses, ids, attrs) >>> lith.z_top array([[ 7., 7., 7., 7., 7., 7., 7., 7., 7.], [ 3., 3., 3., 3., 3., 3., 3., 3., 3.], [ 1., 1., 1., 1., 1., 1., 1., 1., 1.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
Thickness from the surface to the top of each layer in Lithology.
[ "Thickness", "from", "the", "surface", "to", "the", "top", "of", "each", "layer", "in", "Lithology", "." ]
def z_top(self): """Thickness from the surface to the top of each layer in Lithology. Thickness from the topographic surface to the top of each layer as an array of shape `(number_of_layers, number_of_nodes)`. Examples -------- >>> from landlab import RasterModelGrid >>> from landlab.components import Lithology >>> mg = RasterModelGrid((3, 3)) >>> z = mg.add_zeros("topographic__elevation", at="node") >>> thicknesses = [1, 2, 4, 1] >>> ids = [1, 2, 1, 2] >>> attrs = {'K_sp': {1: 0.001, ... 2: 0.0001}} >>> lith = Lithology(mg, thicknesses, ids, attrs) >>> lith.z_top array([[ 7., 7., 7., 7., 7., 7., 7., 7., 7.], [ 3., 3., 3., 3., 3., 3., 3., 3., 3.], [ 1., 1., 1., 1., 1., 1., 1., 1., 1.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0.]]) """ thick = np.broadcast_to(self._layers.thickness, self._layers.z.shape) return thick - self._layers.z
[ "def", "z_top", "(", "self", ")", ":", "thick", "=", "np", ".", "broadcast_to", "(", "self", ".", "_layers", ".", "thickness", ",", "self", ".", "_layers", ".", "z", ".", "shape", ")", "return", "thick", "-", "self", ".", "_layers", ".", "z" ]
https://github.com/landlab/landlab/blob/a5dd80b8ebfd03d1ba87ef6c4368c409485f222c/landlab/components/lithology/lithology.py#L471-L495
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/ftplib.py
python
FTP.delete
(self, filename)
Delete a file.
Delete a file.
[ "Delete", "a", "file", "." ]
def delete(self, filename): '''Delete a file.''' resp = self.sendcmd('DELE ' + filename) if resp[:3] in {'250', '200'}: return resp else: raise error_reply(resp)
[ "def", "delete", "(", "self", ",", "filename", ")", ":", "resp", "=", "self", ".", "sendcmd", "(", "'DELE '", "+", "filename", ")", "if", "resp", "[", ":", "3", "]", "in", "{", "'250'", ",", "'200'", "}", ":", "return", "resp", "else", ":", "rais...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/ftplib.py#L595-L601
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-35/skeinforge_application/skeinforge_utilities/skeinforge_profile.py
python
getReadProfileRepository
()
return settings.getReadRepository( ProfileRepository() )
Get the read profile repository.
Get the read profile repository.
[ "Get", "the", "read", "profile", "repository", "." ]
def getReadProfileRepository(): "Get the read profile repository." return settings.getReadRepository( ProfileRepository() )
[ "def", "getReadProfileRepository", "(", ")", ":", "return", "settings", ".", "getReadRepository", "(", "ProfileRepository", "(", ")", ")" ]
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/skeinforge_application/skeinforge_utilities/skeinforge_profile.py#L116-L118
cmbruns/pyopenvr
ac4847a8a05cda0d4bcf7c4f243008b2a191c7a5
src/samples/pyqt5/track_hmd_qt.py
python
MainWindow.update_page
(self)
[]
def update_page(self): try: openvr.VRCompositor().waitGetPoses(self.poses, None) except: return vrsys = openvr.VRSystem() poses = {} hmd_index = openvr.k_unTrackedDeviceIndex_Hmd beacon_indices = [] controller_indices = [] for i in range(len(self.poses)): device_class = vrsys.getTrackedDeviceClass(i) if device_class == openvr.TrackedDeviceClass_Invalid: continue elif device_class == openvr.TrackedDeviceClass_Controller: controller_indices.append(i) elif device_class == openvr.TrackedDeviceClass_TrackingReference: beacon_indices.append(i) model_name = vrsys.getStringTrackedDeviceProperty(i, openvr.Prop_RenderModelName_String) pose = self.poses[i] poses[i] = dict( model_name=model_name, device_is_connected=pose.bDeviceIsConnected, valid=pose.bPoseIsValid, tracking_result=pose.eTrackingResult, d2a=pose.mDeviceToAbsoluteTracking, velocity=pose.vVelocity, # m/s angular_velocity=pose.vAngularVelocity # radians/s? ) template = jinja_env.get_template('status.html') html = template.render(poses=poses, hmd_index=hmd_index, controller_indices=controller_indices, beacon_indices=beacon_indices) self.webview.setHtml(html) self.update()
[ "def", "update_page", "(", "self", ")", ":", "try", ":", "openvr", ".", "VRCompositor", "(", ")", ".", "waitGetPoses", "(", "self", ".", "poses", ",", "None", ")", "except", ":", "return", "vrsys", "=", "openvr", ".", "VRSystem", "(", ")", "poses", "...
https://github.com/cmbruns/pyopenvr/blob/ac4847a8a05cda0d4bcf7c4f243008b2a191c7a5/src/samples/pyqt5/track_hmd_qt.py#L78-L118
wildfoundry/dataplicity-agent
896d6f7d160c987656a158f036024d2858981ccb
dataplicity/m2m/wsclient.py
python
WSClient.on_ready
(self)
Called when WS is opened.
Called when WS is opened.
[ "Called", "when", "WS", "is", "opened", "." ]
def on_ready(self): """Called when WS is opened.""" log.debug("websocket opened") if self.identity is None: self.send(PacketType.request_join) else: self.send(PacketType.request_identify, uuid=self.identity)
[ "def", "on_ready", "(", "self", ")", ":", "log", ".", "debug", "(", "\"websocket opened\"", ")", "if", "self", ".", "identity", "is", "None", ":", "self", ".", "send", "(", "PacketType", ".", "request_join", ")", "else", ":", "self", ".", "send", "(", ...
https://github.com/wildfoundry/dataplicity-agent/blob/896d6f7d160c987656a158f036024d2858981ccb/dataplicity/m2m/wsclient.py#L312-L318
intrig-unicamp/mininet-wifi
3c8a8f63bd4aa043aa9c1ad16f304dec2916f5ba
mn_wifi/sumo/traci/_simulation.py
python
SimulationDomain.getArrivedIDList
(self)
return self._getUniversal(tc.VAR_ARRIVED_VEHICLES_IDS)
getArrivedIDList() -> list(string) Returns a list of ids of vehicles which arrived (have reached their destination and are removed from the road network) in this time step.
getArrivedIDList() -> list(string) Returns a list of ids of vehicles which arrived (have reached their destination and are removed from the road network) in this time step.
[ "getArrivedIDList", "()", "-", ">", "list", "(", "string", ")", "Returns", "a", "list", "of", "ids", "of", "vehicles", "which", "arrived", "(", "have", "reached", "their", "destination", "and", "are", "removed", "from", "the", "road", "network", ")", "in",...
def getArrivedIDList(self): """getArrivedIDList() -> list(string) Returns a list of ids of vehicles which arrived (have reached their destination and are removed from the road network) in this time step. """ return self._getUniversal(tc.VAR_ARRIVED_VEHICLES_IDS)
[ "def", "getArrivedIDList", "(", "self", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "VAR_ARRIVED_VEHICLES_IDS", ")" ]
https://github.com/intrig-unicamp/mininet-wifi/blob/3c8a8f63bd4aa043aa9c1ad16f304dec2916f5ba/mn_wifi/sumo/traci/_simulation.py#L138-L143
filerock/FileRock-Client
37214f701666e76e723595f8f9ed238a42f6eb06
filerockclient/serversession/server_session.py
python
ServerSession.__init__
(self, cfg, warebox, storage_cache, startup_synchronization, filesystem_watcher, linker, metadata_db, hashes_db, internal_facade, ui_controller, lockfile_fd, auto_start, input_queue, scheduler)
@param cfg: Instance of filerockclient.config.ConfigManager. @param warebox: Instance of filerockclient.warebox.Warebox. @param storage_cache: Instance of filerockclient.databases.storage_cache. StorageCache. @param startup_synchronization: Instance of filerockclient.serversession. startup_synchronization. @param filesystem_watcher: Instance of any class in the filerockclient. filesystem_watcher package. @param linker: Instance of filerockclient.linker.Linker. @param metadata_db: Instance of filerockclient.databases.metadata. MetadataDB. @param hashes_db: Instance of filerockclient.databases.hashes.HashesDB. @param internal_facade: Instance of filerockclient.internal_facade. InternalFacade. @param ui_controller: Instance of filerockclient.ui.ui_controller. UIController. @param lockfile_fd: File descriptor of the lock file which ensures there is only one instance of FileRock Client running. Child processes have to close it to avoid stale locks. @param auto_start: Boolean flag telling whether ServerSession should connect to the server when started. @param input_queue: Instance of filerockclient.util.multi_queue. MultiQueue. It is expected to have the following queues: usercommand: Commands sent by the user sessioncommand: ServerSession internal use commands systemcommand: Commands sent by other client components servermessage: Messages sent by the server. operation: PathnameOperation objects to handle @param scheduler: Instance of filerockclient.util.scheduler.Scheduler.
[]
def __init__(self, cfg, warebox, storage_cache, startup_synchronization, filesystem_watcher, linker, metadata_db, hashes_db, internal_facade, ui_controller, lockfile_fd, auto_start, input_queue, scheduler): """ @param cfg: Instance of filerockclient.config.ConfigManager. @param warebox: Instance of filerockclient.warebox.Warebox. @param storage_cache: Instance of filerockclient.databases.storage_cache. StorageCache. @param startup_synchronization: Instance of filerockclient.serversession. startup_synchronization. @param filesystem_watcher: Instance of any class in the filerockclient. filesystem_watcher package. @param linker: Instance of filerockclient.linker.Linker. @param metadata_db: Instance of filerockclient.databases.metadata. MetadataDB. @param hashes_db: Instance of filerockclient.databases.hashes.HashesDB. @param internal_facade: Instance of filerockclient.internal_facade. InternalFacade. @param ui_controller: Instance of filerockclient.ui.ui_controller. UIController. @param lockfile_fd: File descriptor of the lock file which ensures there is only one instance of FileRock Client running. Child processes have to close it to avoid stale locks. @param auto_start: Boolean flag telling whether ServerSession should connect to the server when started. @param input_queue: Instance of filerockclient.util.multi_queue. MultiQueue. It is expected to have the following queues: usercommand: Commands sent by the user sessioncommand: ServerSession internal use commands systemcommand: Commands sent by other client components servermessage: Messages sent by the server. operation: PathnameOperation objects to handle @param scheduler: Instance of filerockclient.util.scheduler.Scheduler. """ threading.Thread.__init__(self, name=self.__class__.__name__) self.logger = logging.getLogger("FR.%s" % self.__class__.__name__) self._input_queue = input_queue self.warebox = warebox self.startup_synchronization = startup_synchronization self.filesystem_watcher = filesystem_watcher self._internal_facade = internal_facade self._ui_controller = ui_controller self.metadataDB = metadata_db self.hashesDB = hashes_db self.auto_start = auto_start self._scheduler = scheduler self.storage_cache = storage_cache self.linker = linker self.warebox = warebox self.cfg = cfg self._lockfile_fd = lockfile_fd self._started = False self.must_die = threading.Event() # TODO: this flag exists due to auto-disconnection. It will be removed # and replaced by a CONNECTFORCE command as soon as ServerSession will # stop going automatically to DisconnectedState. self.disconnect_other_client = False self.operation_responses = {} self._pathname2id = {} self.output_message_queue = Queue.Queue() self.input_keepalive_queue = Queue.Queue() self.current_state = None self.reconnection_time = 1 self.num_connection_attempts = 0 self.max_connection_attempts = MAX_CONNECTION_ATTEMPTS self._basis_lock = threading.Lock() self.server_basis = None self.session_id = None self.storage_ip_address = None self.refused_declare_count = 0 self._current_basis = None self.id = 0 self._sync_operations = [] self.keepalive_timer = ConnectionLifeKeeper( self._input_queue, self.input_keepalive_queue, self.output_message_queue, True) self.transaction = Transaction() self.transaction_manager = TransactionManager( self.transaction, self.storage_cache) StateRegister.setup(self) self.client_id = None self.username = None self.priv_key = None self.host = None self.port = None self.server_certificate = None self.storage_hostname = None self.refused_declare_max = None self.refused_declare_waiting_time = None self.commit_threshold_seconds = None self.commit_threshold_operations = None self.commit_threshold_bytes = None self.transaction_cache = None self.integrity_manager = None self.cryptoAdapter = None self.temp_dir = None self.connection_reader = None self.connection_writer = None self.sock = None self.listening_operations = False self.reload_config_info()
[ "def", "__init__", "(", "self", ",", "cfg", ",", "warebox", ",", "storage_cache", ",", "startup_synchronization", ",", "filesystem_watcher", ",", "linker", ",", "metadata_db", ",", "hashes_db", ",", "internal_facade", ",", "ui_controller", ",", "lockfile_fd", ",",...
https://github.com/filerock/FileRock-Client/blob/37214f701666e76e723595f8f9ed238a42f6eb06/filerockclient/serversession/server_session.py#L100-L223
jina-ai/jina
c77a492fcd5adba0fc3de5347bea83dd4e7d8087
jina/flow/base.py
python
Flow.host
(self)
Return the local address of the gateway .. # noqa: DAR201
Return the local address of the gateway .. # noqa: DAR201
[ "Return", "the", "local", "address", "of", "the", "gateway", "..", "#", "noqa", ":", "DAR201" ]
def host(self) -> str: """Return the local address of the gateway .. # noqa: DAR201 """ if GATEWAY_NAME in self._pod_nodes: return self._pod_nodes[GATEWAY_NAME].host else: return self._common_kwargs.get('host', __default_host__)
[ "def", "host", "(", "self", ")", "->", "str", ":", "if", "GATEWAY_NAME", "in", "self", ".", "_pod_nodes", ":", "return", "self", ".", "_pod_nodes", "[", "GATEWAY_NAME", "]", ".", "host", "else", ":", "return", "self", ".", "_common_kwargs", ".", "get", ...
https://github.com/jina-ai/jina/blob/c77a492fcd5adba0fc3de5347bea83dd4e7d8087/jina/flow/base.py#L1436-L1443
simonw/sqlite-utils
e0c476bc380744680c8b7675c24fb0e9f5ec6dcd
sqlite_utils/db.py
python
Table.guess_foreign_table
(self, column: str)
For a given column, suggest another table that might be referenced by this column should it be used as a foreign key. For example, a column called ``tag_id`` or ``tag`` or ``tags`` might suggest a ``tag`` table, if one exists. If no candidates can be found, raises a ``NoObviousTable`` exception.
For a given column, suggest another table that might be referenced by this column should it be used as a foreign key.
[ "For", "a", "given", "column", "suggest", "another", "table", "that", "might", "be", "referenced", "by", "this", "column", "should", "it", "be", "used", "as", "a", "foreign", "key", "." ]
def guess_foreign_table(self, column: str) -> str: """ For a given column, suggest another table that might be referenced by this column should it be used as a foreign key. For example, a column called ``tag_id`` or ``tag`` or ``tags`` might suggest a ``tag`` table, if one exists. If no candidates can be found, raises a ``NoObviousTable`` exception. """ column = column.lower() possibilities = [column] if column.endswith("_id"): column_without_id = column[:-3] possibilities.append(column_without_id) if not column_without_id.endswith("s"): possibilities.append(column_without_id + "s") elif not column.endswith("s"): possibilities.append(column + "s") existing_tables = {t.lower(): t for t in self.db.table_names()} for table in possibilities: if table in existing_tables: return existing_tables[table] # If we get here there's no obvious candidate - raise an error raise NoObviousTable( "No obvious foreign key table for column '{}' - tried {}".format( column, repr(possibilities) ) )
[ "def", "guess_foreign_table", "(", "self", ",", "column", ":", "str", ")", "->", "str", ":", "column", "=", "column", ".", "lower", "(", ")", "possibilities", "=", "[", "column", "]", "if", "column", ".", "endswith", "(", "\"_id\"", ")", ":", "column_w...
https://github.com/simonw/sqlite-utils/blob/e0c476bc380744680c8b7675c24fb0e9f5ec6dcd/sqlite_utils/db.py#L1662-L1690
PythonCharmers/python-future
80523f383fbba1c6de0551e19d0277e73e69573c
src/future/backports/urllib/parse.py
python
splitvalue
(attr)
return attr, None
splitvalue('attr=value') --> 'attr', 'value'.
splitvalue('attr=value') --> 'attr', 'value'.
[ "splitvalue", "(", "attr", "=", "value", ")", "--", ">", "attr", "value", "." ]
def splitvalue(attr): """splitvalue('attr=value') --> 'attr', 'value'.""" global _valueprog if _valueprog is None: import re _valueprog = re.compile('^([^=]*)=(.*)$') match = _valueprog.match(attr) if match: return match.group(1, 2) return attr, None
[ "def", "splitvalue", "(", "attr", ")", ":", "global", "_valueprog", "if", "_valueprog", "is", "None", ":", "import", "re", "_valueprog", "=", "re", ".", "compile", "(", "'^([^=]*)=(.*)$'", ")", "match", "=", "_valueprog", ".", "match", "(", "attr", ")", ...
https://github.com/PythonCharmers/python-future/blob/80523f383fbba1c6de0551e19d0277e73e69573c/src/future/backports/urllib/parse.py#L982-L991
ladybug-tools/honeybee-legacy
bd62af4862fe022801fb87dbc8794fdf1dff73a9
src/Honeybee_SplitFloor2ThermalZones.py
python
AdjGraph.find_most_ccw_cycle
(self)
return LOC
[]
def find_most_ccw_cycle(self): #def helper_most_ccw(lok): #Input adjacency graph #Output loc: listof (listof (listof pts in closed cycle)) LOC = [] keylst = self.get_sorted_keylst() for i in xrange(len(keylst)): key = keylst[i] root_node = self.adj_graph[key] if not root_node.is_out_edge: continue #Identify the next node on outer edge #b/c outer edge vertexes are placed first in adj graph #worst complexity <= O(n) for i in xrange(root_node.num_neighbor()): adj_key = root_node.adj_lst[i] neighbor = self.adj_graph[adj_key] if neighbor.is_out_edge: next_node = neighbor break #Now we recursively check most ccw n_adj_lst = next_node.adj_lst cycle = [root_node] try: cycle = self.recurse_ccw(root_node,next_node,n_adj_lst,cycle,0) except: pass #print '-------\n-----FINISHED CYCLE\n', cycle, '---\---\n' LOC.append(cycle) #print '-' return LOC
[ "def", "find_most_ccw_cycle", "(", "self", ")", ":", "#def helper_most_ccw(lok):", "#Input adjacency graph", "#Output loc: listof (listof (listof pts in closed cycle))", "LOC", "=", "[", "]", "keylst", "=", "self", ".", "get_sorted_keylst", "(", ")", "for", "i", "in", "...
https://github.com/ladybug-tools/honeybee-legacy/blob/bd62af4862fe022801fb87dbc8794fdf1dff73a9/src/Honeybee_SplitFloor2ThermalZones.py#L377-L410
WenRichard/KBQA-BERT
6e7079ede8979b1179600564ed9ecc58c7a4f877
bert/modeling.py
python
BertConfig.__init__
(self, vocab_size, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, initializer_range=0.02)
Constructs BertConfig. Args: vocab_size: Vocabulary size of `inputs_ids` in `BertModel`. hidden_size: Size of the encoder layers and the pooler layer. num_hidden_layers: Number of hidden layers in the Transformer encoder. num_attention_heads: Number of attention heads for each attention layer in the Transformer encoder. intermediate_size: The size of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. hidden_act: The non-linear activation function (function or string) in the encoder and pooler. hidden_dropout_prob: The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_probs_dropout_prob: The dropout ratio for the attention probabilities. max_position_embeddings: The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). type_vocab_size: The vocabulary size of the `token_type_ids` passed into `BertModel`. initializer_range: The stdev of the truncated_normal_initializer for initializing all weight matrices.
Constructs BertConfig.
[ "Constructs", "BertConfig", "." ]
def __init__(self, vocab_size, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, initializer_range=0.02): """Constructs BertConfig. Args: vocab_size: Vocabulary size of `inputs_ids` in `BertModel`. hidden_size: Size of the encoder layers and the pooler layer. num_hidden_layers: Number of hidden layers in the Transformer encoder. num_attention_heads: Number of attention heads for each attention layer in the Transformer encoder. intermediate_size: The size of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. hidden_act: The non-linear activation function (function or string) in the encoder and pooler. hidden_dropout_prob: The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_probs_dropout_prob: The dropout ratio for the attention probabilities. max_position_embeddings: The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). type_vocab_size: The vocabulary size of the `token_type_ids` passed into `BertModel`. initializer_range: The stdev of the truncated_normal_initializer for initializing all weight matrices. """ self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_act = hidden_act self.intermediate_size = intermediate_size self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.initializer_range = initializer_range
[ "def", "__init__", "(", "self", ",", "vocab_size", ",", "hidden_size", "=", "768", ",", "num_hidden_layers", "=", "12", ",", "num_attention_heads", "=", "12", ",", "intermediate_size", "=", "3072", ",", "hidden_act", "=", "\"gelu\"", ",", "hidden_dropout_prob", ...
https://github.com/WenRichard/KBQA-BERT/blob/6e7079ede8979b1179600564ed9ecc58c7a4f877/bert/modeling.py#L33-L79
maas/maas
db2f89970c640758a51247c59bf1ec6f60cf4ab5
src/maascli/actions/boot_resources_create.py
python
BootResourcesCreateAction.put_upload
(self, upload_uri, data, insecure=False)
Send PUT method to upload data.
Send PUT method to upload data.
[ "Send", "PUT", "method", "to", "upload", "data", "." ]
def put_upload(self, upload_uri, data, insecure=False): """Send PUT method to upload data.""" headers = { "Content-Type": "application/octet-stream", "Content-Length": "%s" % len(data), } if self.credentials is not None: self.sign(upload_uri, headers, self.credentials) # httplib2 expects the body to be file-like if its binary data data = BytesIO(data) response, content = http_request( upload_uri, "PUT", body=data, headers=headers, insecure=insecure ) if response.status != 200: utils.print_response_content(response, content) raise CommandError(2)
[ "def", "put_upload", "(", "self", ",", "upload_uri", ",", "data", ",", "insecure", "=", "False", ")", ":", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/octet-stream\"", ",", "\"Content-Length\"", ":", "\"%s\"", "%", "len", "(", "data", ")", "...
https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/maascli/actions/boot_resources_create.py#L148-L163
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /scripts/toolbox.py
python
check_wplazyseoplugin
(sites)
return wplazyseoplugin
[]
def check_wplazyseoplugin(sites) : wplazyseoplugin = [] for site in sites : try : if urllib2.urlopen(site+'wp-content/plugins/lazy-seo/lazyseo.php').getcode() == 200 : wplazyseoplugin.append(site) except : pass return wplazyseoplugin
[ "def", "check_wplazyseoplugin", "(", "sites", ")", ":", "wplazyseoplugin", "=", "[", "]", "for", "site", "in", "sites", ":", "try", ":", "if", "urllib2", ".", "urlopen", "(", "site", "+", "'wp-content/plugins/lazy-seo/lazyseo.php'", ")", ".", "getcode", "(", ...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /scripts/toolbox.py#L1456-L1465
spack/spack
675210bd8bd1c5d32ad1cc83d898fb43b569ed74
lib/spack/spack/package.py
python
PackageBase._run_default_install_time_test_callbacks
(self)
Tries to call all the methods that are listed in the attribute ``install_time_test_callbacks`` if ``self.run_tests is True``. If ``install_time_test_callbacks is None`` returns immediately.
Tries to call all the methods that are listed in the attribute ``install_time_test_callbacks`` if ``self.run_tests is True``.
[ "Tries", "to", "call", "all", "the", "methods", "that", "are", "listed", "in", "the", "attribute", "install_time_test_callbacks", "if", "self", ".", "run_tests", "is", "True", "." ]
def _run_default_install_time_test_callbacks(self): """Tries to call all the methods that are listed in the attribute ``install_time_test_callbacks`` if ``self.run_tests is True``. If ``install_time_test_callbacks is None`` returns immediately. """ if self.install_time_test_callbacks is None: return for name in self.install_time_test_callbacks: try: fn = getattr(self, name) except AttributeError: msg = 'RUN-TESTS: method not implemented [{0}]' tty.warn(msg.format(name)) else: tty.msg('RUN-TESTS: install-time tests [{0}]'.format(name)) fn()
[ "def", "_run_default_install_time_test_callbacks", "(", "self", ")", ":", "if", "self", ".", "install_time_test_callbacks", "is", "None", ":", "return", "for", "name", "in", "self", ".", "install_time_test_callbacks", ":", "try", ":", "fn", "=", "getattr", "(", ...
https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/spack/package.py#L2591-L2608
firebase/firebase-admin-python
7cfb798ca78f706d08a46c3c48028895787d0ea4
firebase_admin/_user_mgt.py
python
UserRecord.provider_id
(self)
return 'firebase'
Returns the provider ID of this user. Returns: string: A constant provider ID value.
Returns the provider ID of this user.
[ "Returns", "the", "provider", "ID", "of", "this", "user", "." ]
def provider_id(self): """Returns the provider ID of this user. Returns: string: A constant provider ID value. """ return 'firebase'
[ "def", "provider_id", "(", "self", ")", ":", "return", "'firebase'" ]
https://github.com/firebase/firebase-admin-python/blob/7cfb798ca78f706d08a46c3c48028895787d0ea4/firebase_admin/_user_mgt.py#L184-L190
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cpdp/v20190820/models.py
python
ApplyOutwardOrderResult.__init__
(self)
r""" :param Data: 汇出指令申请数据 :type Data: :class:`tencentcloud.cpdp.v20190820.models.ApplyOutwardOrderData` :param Code: 错误码 :type Code: str
r""" :param Data: 汇出指令申请数据 :type Data: :class:`tencentcloud.cpdp.v20190820.models.ApplyOutwardOrderData` :param Code: 错误码 :type Code: str
[ "r", ":", "param", "Data", ":", "汇出指令申请数据", ":", "type", "Data", ":", ":", "class", ":", "tencentcloud", ".", "cpdp", ".", "v20190820", ".", "models", ".", "ApplyOutwardOrderData", ":", "param", "Code", ":", "错误码", ":", "type", "Code", ":", "str" ]
def __init__(self): r""" :param Data: 汇出指令申请数据 :type Data: :class:`tencentcloud.cpdp.v20190820.models.ApplyOutwardOrderData` :param Code: 错误码 :type Code: str """ self.Data = None self.Code = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "Data", "=", "None", "self", ".", "Code", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cpdp/v20190820/models.py#L1284-L1292
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/pandas/core/base.py
python
SelectionMixin._shallow_copy
(self, obj=None, obj_type=None, **kwargs)
return obj_type(obj, **kwargs)
return a new object with the replacement attributes
return a new object with the replacement attributes
[ "return", "a", "new", "object", "with", "the", "replacement", "attributes" ]
def _shallow_copy(self, obj=None, obj_type=None, **kwargs): """ return a new object with the replacement attributes """ if obj is None: obj = self._selected_obj.copy() if obj_type is None: obj_type = self._constructor if isinstance(obj, obj_type): obj = obj.obj for attr in self._attributes: if attr not in kwargs: kwargs[attr] = getattr(self, attr) return obj_type(obj, **kwargs)
[ "def", "_shallow_copy", "(", "self", ",", "obj", "=", "None", ",", "obj_type", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "obj", "is", "None", ":", "obj", "=", "self", ".", "_selected_obj", ".", "copy", "(", ")", "if", "obj_type", "is", ...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pandas/core/base.py#L622-L633
rowliny/DiffHelper
ab3a96f58f9579d0023aed9ebd785f4edf26f8af
Tool/SitePackages/joblib/memory.py
python
MemorizedFunc.call_and_shelve
(self, *args, **kwargs)
return MemorizedResult(self.store_backend, self.func, args_id, metadata=metadata, verbose=self._verbose - 1, timestamp=self.timestamp)
Call wrapped function, cache result and return a reference. This method returns a reference to the cached result instead of the result itself. The reference object is small and pickeable, allowing to send or store it easily. Call .get() on reference object to get result. Returns ------- cached_result: MemorizedResult or NotMemorizedResult reference to the value returned by the wrapped function. The class "NotMemorizedResult" is used when there is no cache activated (e.g. location=None in Memory).
Call wrapped function, cache result and return a reference.
[ "Call", "wrapped", "function", "cache", "result", "and", "return", "a", "reference", "." ]
def call_and_shelve(self, *args, **kwargs): """Call wrapped function, cache result and return a reference. This method returns a reference to the cached result instead of the result itself. The reference object is small and pickeable, allowing to send or store it easily. Call .get() on reference object to get result. Returns ------- cached_result: MemorizedResult or NotMemorizedResult reference to the value returned by the wrapped function. The class "NotMemorizedResult" is used when there is no cache activated (e.g. location=None in Memory). """ _, args_id, metadata = self._cached_call(args, kwargs, shelving=True) return MemorizedResult(self.store_backend, self.func, args_id, metadata=metadata, verbose=self._verbose - 1, timestamp=self.timestamp)
[ "def", "call_and_shelve", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_", ",", "args_id", ",", "metadata", "=", "self", ".", "_cached_call", "(", "args", ",", "kwargs", ",", "shelving", "=", "True", ")", "return", "MemorizedResul...
https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/joblib/memory.py#L573-L591
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/distlib/database.py
python
DistributionPath.get_distribution
(self, name)
return result
Looks for a named distribution on the path. This function only returns the first result found, as no more than one value is expected. If nothing is found, ``None`` is returned. :rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution` or ``None``
Looks for a named distribution on the path.
[ "Looks", "for", "a", "named", "distribution", "on", "the", "path", "." ]
def get_distribution(self, name): """ Looks for a named distribution on the path. This function only returns the first result found, as no more than one value is expected. If nothing is found, ``None`` is returned. :rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution` or ``None`` """ result = None name = name.lower() if not self._cache_enabled: for dist in self._yield_distributions(): if dist.key == name: result = dist break else: self._generate_cache() if name in self._cache.name: result = self._cache.name[name][0] elif self._include_egg and name in self._cache_egg.name: result = self._cache_egg.name[name][0] return result
[ "def", "get_distribution", "(", "self", ",", "name", ")", ":", "result", "=", "None", "name", "=", "name", ".", "lower", "(", ")", "if", "not", "self", ".", "_cache_enabled", ":", "for", "dist", "in", "self", ".", "_yield_distributions", "(", ")", ":",...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/distlib/database.py#L219-L243
gaphor/gaphor
dfe8df33ef3b884afdadf7c91fc7740f8d3c2e88
gaphor/UML/actions/flowconnect.py
python
FlowForkDecisionNodeConnect.decombine_nodes
(self)
Decombine join/fork or decision/merge nodes.
Decombine join/fork or decision/merge nodes.
[ "Decombine", "join", "/", "fork", "or", "decision", "/", "merge", "nodes", "." ]
def decombine_nodes(self): """Decombine join/fork or decision/merge nodes.""" element = self.element if element.combined: join_node = element.subject cflow = join_node.outgoing[0] # combining flow fork_node = cflow.target assert fork_node is element.combined join_node_cls = self.join_node_cls assert isinstance(join_node, join_node_cls) fork_node_cls = self.fork_node_cls assert isinstance(fork_node, fork_node_cls) if len(join_node.incoming) < 2 or len(fork_node.outgoing) < 2: # Move all outgoing edges to the first node (the join node): for f in list(fork_node.outgoing): f.source = join_node cflow.unlink() fork_node.unlink() # swap subject to fork node if outgoing > 1 if len(join_node.outgoing) > 1: assert len(join_node.incoming) < 2 UML.recipes.swap_element(join_node, fork_node_cls) del element.combined
[ "def", "decombine_nodes", "(", "self", ")", ":", "element", "=", "self", ".", "element", "if", "element", ".", "combined", ":", "join_node", "=", "element", ".", "subject", "cflow", "=", "join_node", ".", "outgoing", "[", "0", "]", "# combining flow", "for...
https://github.com/gaphor/gaphor/blob/dfe8df33ef3b884afdadf7c91fc7740f8d3c2e88/gaphor/UML/actions/flowconnect.py#L161-L185
sametmax/Django--an-app-at-a-time
99eddf12ead76e6dfbeb09ce0bae61e282e22f8a
ignore_this_directory/django/template/defaulttags.py
python
do_with
(parser, token)
return WithNode(None, None, nodelist, extra_context=extra_context)
Add one or more values to the context (inside of this block) for caching and easy access. For example:: {% with total=person.some_sql_method %} {{ total }} object{{ total|pluralize }} {% endwith %} Multiple values can be added to the context:: {% with foo=1 bar=2 %} ... {% endwith %} The legacy format of ``{% with person.some_sql_method as total %}`` is still accepted.
Add one or more values to the context (inside of this block) for caching and easy access.
[ "Add", "one", "or", "more", "values", "to", "the", "context", "(", "inside", "of", "this", "block", ")", "for", "caching", "and", "easy", "access", "." ]
def do_with(parser, token): """ Add one or more values to the context (inside of this block) for caching and easy access. For example:: {% with total=person.some_sql_method %} {{ total }} object{{ total|pluralize }} {% endwith %} Multiple values can be added to the context:: {% with foo=1 bar=2 %} ... {% endwith %} The legacy format of ``{% with person.some_sql_method as total %}`` is still accepted. """ bits = token.split_contents() remaining_bits = bits[1:] extra_context = token_kwargs(remaining_bits, parser, support_legacy=True) if not extra_context: raise TemplateSyntaxError("%r expected at least one variable " "assignment" % bits[0]) if remaining_bits: raise TemplateSyntaxError("%r received an invalid token: %r" % (bits[0], remaining_bits[0])) nodelist = parser.parse(('endwith',)) parser.delete_first_token() return WithNode(None, None, nodelist, extra_context=extra_context)
[ "def", "do_with", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "remaining_bits", "=", "bits", "[", "1", ":", "]", "extra_context", "=", "token_kwargs", "(", "remaining_bits", ",", "parser", ",", "support_leg...
https://github.com/sametmax/Django--an-app-at-a-time/blob/99eddf12ead76e6dfbeb09ce0bae61e282e22f8a/ignore_this_directory/django/template/defaulttags.py#L1443-L1474
aboul3la/Sublist3r
729d649ec5370730172bf6f5314aafd68c874124
sublist3r.py
python
YahooEnum.get_page
(self, num)
return num + 10
[]
def get_page(self, num): return num + 10
[ "def", "get_page", "(", "self", ",", "num", ")", ":", "return", "num", "+", "10" ]
https://github.com/aboul3la/Sublist3r/blob/729d649ec5370730172bf6f5314aafd68c874124/sublist3r.py#L361-L362
PixarAnimationStudios/OpenTimelineIO
990a54ccbe6488180a93753370fc87902b982962
src/opentimelineview/track_widgets.py
python
TrackNameItem._set_labels
(self)
return
[]
def _set_labels(self): return
[ "def", "_set_labels", "(", "self", ")", ":", "return" ]
https://github.com/PixarAnimationStudios/OpenTimelineIO/blob/990a54ccbe6488180a93753370fc87902b982962/src/opentimelineview/track_widgets.py#L300-L301
IntelAI/nauta
bbedb114a755cf1f43b834a58fc15fb6e3a4b291
applications/cli/util/system.py
python
ExternalCliCommand.__init__
(self, cmd: List[str], env: dict = None, cwd: str = None, timeout: int = None)
:param cmd: List of strings which define a command that will be executed, e.g. ['git', 'clone'] :param env: Dictionary containing environment variables that will be used during command execution :param cwd: Path to working directory :param timeout: Timeout in seconds
:param cmd: List of strings which define a command that will be executed, e.g. ['git', 'clone'] :param env: Dictionary containing environment variables that will be used during command execution :param cwd: Path to working directory :param timeout: Timeout in seconds
[ ":", "param", "cmd", ":", "List", "of", "strings", "which", "define", "a", "command", "that", "will", "be", "executed", "e", ".", "g", ".", "[", "git", "clone", "]", ":", "param", "env", ":", "Dictionary", "containing", "environment", "variables", "that"...
def __init__(self, cmd: List[str], env: dict = None, cwd: str = None, timeout: int = None): """ :param cmd: List of strings which define a command that will be executed, e.g. ['git', 'clone'] :param env: Dictionary containing environment variables that will be used during command execution :param cwd: Path to working directory :param timeout: Timeout in seconds """ self.cmd = cmd self.env = env self.cwd = cwd self.timeout = timeout
[ "def", "__init__", "(", "self", ",", "cmd", ":", "List", "[", "str", "]", ",", "env", ":", "dict", "=", "None", ",", "cwd", ":", "str", "=", "None", ",", "timeout", ":", "int", "=", "None", ")", ":", "self", ".", "cmd", "=", "cmd", "self", "....
https://github.com/IntelAI/nauta/blob/bbedb114a755cf1f43b834a58fc15fb6e3a4b291/applications/cli/util/system.py#L81-L91
shellphish/ictf-framework
c0384f12060cf47442a52f516c6e78bd722f208a
database/support/mysql-connector-python-2.1.3/lib/mysql/connector/fabric/connection.py
python
Fabric.execute
(self, group, command, *args, **kwargs)
return inst.execute(group, command, *args, **kwargs)
Execute a Fabric command from given group This method will execute the given Fabric command from the given group using the given arguments. It returns an instance of FabricSet. Raises ValueError when group.command is not valid and raises InterfaceError when an error occurs while executing. Returns FabricSet.
Execute a Fabric command from given group
[ "Execute", "a", "Fabric", "command", "from", "given", "group" ]
def execute(self, group, command, *args, **kwargs): """Execute a Fabric command from given group This method will execute the given Fabric command from the given group using the given arguments. It returns an instance of FabricSet. Raises ValueError when group.command is not valid and raises InterfaceError when an error occurs while executing. Returns FabricSet. """ inst = self.get_instance() return inst.execute(group, command, *args, **kwargs)
[ "def", "execute", "(", "self", ",", "group", ",", "command", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "inst", "=", "self", ".", "get_instance", "(", ")", "return", "inst", ".", "execute", "(", "group", ",", "command", ",", "*", "args", ...
https://github.com/shellphish/ictf-framework/blob/c0384f12060cf47442a52f516c6e78bd722f208a/database/support/mysql-connector-python-2.1.3/lib/mysql/connector/fabric/connection.py#L1005-L1017
deepinsight/insightface
c0b25f998a649f662c7136eb389abcacd7900e9d
detection/scrfd/mmdet/models/losses/varifocal_loss.py
python
varifocal_loss
(pred, target, weight=None, alpha=0.75, gamma=2.0, iou_weighted=True, reduction='mean', avg_factor=None)
return loss
`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: pred (torch.Tensor): The prediction with shape (N, C), C is the number of classes target (torch.Tensor): The learning target of the iou-aware classification score with shape (N, C), C is the number of classes. weight (torch.Tensor, optional): The weight of loss for each prediction. Defaults to None. alpha (float, optional): A balance factor for the negative part of Varifocal Loss, which is different from the alpha of Focal Loss. Defaults to 0.75. gamma (float, optional): The gamma for calculating the modulating factor. Defaults to 2.0. iou_weighted (bool, optional): Whether to weight the loss of the positive example with the iou target. Defaults to True. reduction (str, optional): The method used to reduce the loss into a scalar. Defaults to 'mean'. Options are "none", "mean" and "sum". avg_factor (int, optional): Average factor that is used to average the loss. Defaults to None.
`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_
[ "Varifocal", "Loss", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "2008", ".", "13367", ">", "_" ]
def varifocal_loss(pred, target, weight=None, alpha=0.75, gamma=2.0, iou_weighted=True, reduction='mean', avg_factor=None): """`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_ Args: pred (torch.Tensor): The prediction with shape (N, C), C is the number of classes target (torch.Tensor): The learning target of the iou-aware classification score with shape (N, C), C is the number of classes. weight (torch.Tensor, optional): The weight of loss for each prediction. Defaults to None. alpha (float, optional): A balance factor for the negative part of Varifocal Loss, which is different from the alpha of Focal Loss. Defaults to 0.75. gamma (float, optional): The gamma for calculating the modulating factor. Defaults to 2.0. iou_weighted (bool, optional): Whether to weight the loss of the positive example with the iou target. Defaults to True. reduction (str, optional): The method used to reduce the loss into a scalar. Defaults to 'mean'. Options are "none", "mean" and "sum". avg_factor (int, optional): Average factor that is used to average the loss. Defaults to None. """ # pred and target should be of the same size assert pred.size() == target.size() pred_sigmoid = pred.sigmoid() target = target.type_as(pred) if iou_weighted: focal_weight = target * (target > 0.0).float() + \ alpha * (pred_sigmoid - target).abs().pow(gamma) * \ (target <= 0.0).float() else: focal_weight = (target > 0.0).float() + \ alpha * (pred_sigmoid - target).abs().pow(gamma) * \ (target <= 0.0).float() loss = F.binary_cross_entropy_with_logits( pred, target, reduction='none') * focal_weight loss = weight_reduce_loss(loss, weight, reduction, avg_factor) return loss
[ "def", "varifocal_loss", "(", "pred", ",", "target", ",", "weight", "=", "None", ",", "alpha", "=", "0.75", ",", "gamma", "=", "2.0", ",", "iou_weighted", "=", "True", ",", "reduction", "=", "'mean'", ",", "avg_factor", "=", "None", ")", ":", "# pred a...
https://github.com/deepinsight/insightface/blob/c0b25f998a649f662c7136eb389abcacd7900e9d/detection/scrfd/mmdet/models/losses/varifocal_loss.py#L8-L53
ioflo/ioflo
177ac656d7c4ff801aebb0d8b401db365a5248ce
ioflo/aio/proto/stacking.py
python
GramStack.__init__
(self, **kwa)
Setup Stack instance Inherited Parameters: stamper is relative time stamper for this stack version is version tuple or string for this stack puid is previous uid for devices managed by this stack local is local device if any for this stack uid is uid of local device shared with stack if local not given name is name of local device shared with stack if local not given ha is host address of local device shared with stack if local not given kind is kind of local device shared with stack if local not given handler is interface handler/server/listeniner/client/driver if any rxbs is bytearray buffer to hold input data stream if any rxPkts is deque of duples to hold received packet and source ha if any rxMsgs is deque to hold received msgs if any txPkts is deque of duples to hold packet to be transmitted and destination ha if any txMsgs is deque to hold messages to be transmitted if any stats is odict of stack statistics if any Parameters: Inherited Attributes: .stamper is relative time stamper for this stack .version is version tuple or string for this stack .puid is previous uid for devices managed by this stack .local is local device for this stack .handler is interface handler/server/listeniner/client/driver if any .rxbs is bytearray buffer to hold input data stream .rxPkts is deque of duples to hold received packet and source ha if any .rxMsgs is deque of duples to hold received msgs and remotes .txPkts is deque of duples to hold packet to be transmitted and destination ha if any .txMsgs is deque of duples to hold messages to be transmitted .stats is odict of stack statistics .statTimer is relative timer for statistics .aha is normalized accepting (listening) host address for .handler if applicable Attributes: Inherited Properties: .uid is local device unique id as stack uid .name is local device name as stack name .ha is local device ha as stack ha .kind is local device kind as stack kind Properties:
Setup Stack instance
[ "Setup", "Stack", "instance" ]
def __init__(self, **kwa): """ Setup Stack instance Inherited Parameters: stamper is relative time stamper for this stack version is version tuple or string for this stack puid is previous uid for devices managed by this stack local is local device if any for this stack uid is uid of local device shared with stack if local not given name is name of local device shared with stack if local not given ha is host address of local device shared with stack if local not given kind is kind of local device shared with stack if local not given handler is interface handler/server/listeniner/client/driver if any rxbs is bytearray buffer to hold input data stream if any rxPkts is deque of duples to hold received packet and source ha if any rxMsgs is deque to hold received msgs if any txPkts is deque of duples to hold packet to be transmitted and destination ha if any txMsgs is deque to hold messages to be transmitted if any stats is odict of stack statistics if any Parameters: Inherited Attributes: .stamper is relative time stamper for this stack .version is version tuple or string for this stack .puid is previous uid for devices managed by this stack .local is local device for this stack .handler is interface handler/server/listeniner/client/driver if any .rxbs is bytearray buffer to hold input data stream .rxPkts is deque of duples to hold received packet and source ha if any .rxMsgs is deque of duples to hold received msgs and remotes .txPkts is deque of duples to hold packet to be transmitted and destination ha if any .txMsgs is deque of duples to hold messages to be transmitted .stats is odict of stack statistics .statTimer is relative timer for statistics .aha is normalized accepting (listening) host address for .handler if applicable Attributes: Inherited Properties: .uid is local device unique id as stack uid .name is local device name as stack name .ha is local device ha as stack ha .kind is local device kind as stack kind Properties: """ super(GramStack, self).__init__(**kwa)
[ "def", "__init__", "(", "self", ",", "*", "*", "kwa", ")", ":", "super", "(", "GramStack", ",", "self", ")", ".", "__init__", "(", "*", "*", "kwa", ")" ]
https://github.com/ioflo/ioflo/blob/177ac656d7c4ff801aebb0d8b401db365a5248ce/ioflo/aio/proto/stacking.py#L1775-L1826
nlplab/brat
44ecd825810167eed2a5d8ad875d832218e734e8
standalone.py
python
BratHTTPRequestHandler.list_directory
(self, path)
Override SimpleHTTPRequestHandler.list_directory()
Override SimpleHTTPRequestHandler.list_directory()
[ "Override", "SimpleHTTPRequestHandler", ".", "list_directory", "()" ]
def list_directory(self, path): """Override SimpleHTTPRequestHandler.list_directory()""" # TODO: permissions for directory listings self.send_error(403)
[ "def", "list_directory", "(", "self", ",", "path", ")", ":", "# TODO: permissions for directory listings", "self", ".", "send_error", "(", "403", ")" ]
https://github.com/nlplab/brat/blob/44ecd825810167eed2a5d8ad875d832218e734e8/standalone.py#L220-L223
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/plugin.py
python
Plugins.get_plugin
(self, name: str)
return self.plugins[name]
[]
def get_plugin(self, name: str) -> 'BasePlugin': if name not in self.plugins: self.load_plugin(name) return self.plugins[name]
[ "def", "get_plugin", "(", "self", ",", "name", ":", "str", ")", "->", "'BasePlugin'", ":", "if", "name", "not", "in", "self", ".", "plugins", ":", "self", ".", "load_plugin", "(", "name", ")", "return", "self", ".", "plugins", "[", "name", "]" ]
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/plugin.py#L205-L208
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/distutils/command/build_py.py
python
build_py.find_modules
(self)
return modules
Finds individually-specified Python modules, ie. those listed by module name in 'self.py_modules'. Returns a list of tuples (package, module_base, filename): 'package' is a tuple of the path through package-space to the module; 'module_base' is the bare (no packages, no dots) module name, and 'filename' is the path to the ".py" file (relative to the distribution root) that implements the module.
Finds individually-specified Python modules, ie. those listed by module name in 'self.py_modules'. Returns a list of tuples (package, module_base, filename): 'package' is a tuple of the path through package-space to the module; 'module_base' is the bare (no packages, no dots) module name, and 'filename' is the path to the ".py" file (relative to the distribution root) that implements the module.
[ "Finds", "individually", "-", "specified", "Python", "modules", "ie", ".", "those", "listed", "by", "module", "name", "in", "self", ".", "py_modules", ".", "Returns", "a", "list", "of", "tuples", "(", "package", "module_base", "filename", ")", ":", "package"...
def find_modules(self): """Finds individually-specified Python modules, ie. those listed by module name in 'self.py_modules'. Returns a list of tuples (package, module_base, filename): 'package' is a tuple of the path through package-space to the module; 'module_base' is the bare (no packages, no dots) module name, and 'filename' is the path to the ".py" file (relative to the distribution root) that implements the module. """ # Map package names to tuples of useful info about the package: # (package_dir, checked) # package_dir - the directory where we'll find source files for # this package # checked - true if we have checked that the package directory # is valid (exists, contains __init__.py, ... ?) packages = {} # List of (package, module, filename) tuples to return modules = [] # We treat modules-in-packages almost the same as toplevel modules, # just the "package" for a toplevel is empty (either an empty # string or empty list, depending on context). Differences: # - don't check for __init__.py in directory for empty package for module in self.py_modules: path = module.split('.') package = '.'.join(path[0:-1]) module_base = path[-1] try: (package_dir, checked) = packages[package] except KeyError: package_dir = self.get_package_dir(package) checked = 0 if not checked: init_py = self.check_package(package, package_dir) packages[package] = (package_dir, 1) if init_py: modules.append((package, "__init__", init_py)) # XXX perhaps we should also check for just .pyc files # (so greedy closed-source bastards can distribute Python # modules too) module_file = os.path.join(package_dir, module_base + ".py") if not self.check_module(module, module_file): continue modules.append((package, module_base, module_file)) return modules
[ "def", "find_modules", "(", "self", ")", ":", "# Map package names to tuples of useful info about the package:", "# (package_dir, checked)", "# package_dir - the directory where we'll find source files for", "# this package", "# checked - true if we have checked that the package directory",...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/distutils/command/build_py.py#L232-L282
wakatime/legacy-python-cli
9b64548b16ab5ef16603d9a6c2620a16d0df8d46
wakatime/packages/py27/OpenSSL/crypto.py
python
X509Name.__init__
(self, name)
Create a new X509Name, copying the given X509Name instance. :param name: The name to copy. :type name: :py:class:`X509Name`
Create a new X509Name, copying the given X509Name instance.
[ "Create", "a", "new", "X509Name", "copying", "the", "given", "X509Name", "instance", "." ]
def __init__(self, name): """ Create a new X509Name, copying the given X509Name instance. :param name: The name to copy. :type name: :py:class:`X509Name` """ name = _lib.X509_NAME_dup(name._name) self._name = _ffi.gc(name, _lib.X509_NAME_free)
[ "def", "__init__", "(", "self", ",", "name", ")", ":", "name", "=", "_lib", ".", "X509_NAME_dup", "(", "name", ".", "_name", ")", "self", ".", "_name", "=", "_ffi", ".", "gc", "(", "name", ",", "_lib", ".", "X509_NAME_free", ")" ]
https://github.com/wakatime/legacy-python-cli/blob/9b64548b16ab5ef16603d9a6c2620a16d0df8d46/wakatime/packages/py27/OpenSSL/crypto.py#L533-L541
wucng/TensorExpand
4ea58f64f5c5082b278229b799c9f679536510b7
TensorExpand/Object detection/RetinaNet/keras-retinanet/keras_retinanet/preprocessing/generator.py
python
Generator.preprocess_group
(self, image_group, annotations_group)
return image_group, annotations_group
[]
def preprocess_group(self, image_group, annotations_group): for index, (image, annotations) in enumerate(zip(image_group, annotations_group)): # preprocess a single group entry image, annotations = self.preprocess_group_entry(image, annotations) # copy processed data back to group image_group[index] = image annotations_group[index] = annotations return image_group, annotations_group
[ "def", "preprocess_group", "(", "self", ",", "image_group", ",", "annotations_group", ")", ":", "for", "index", ",", "(", "image", ",", "annotations", ")", "in", "enumerate", "(", "zip", "(", "image_group", ",", "annotations_group", ")", ")", ":", "# preproc...
https://github.com/wucng/TensorExpand/blob/4ea58f64f5c5082b278229b799c9f679536510b7/TensorExpand/Object detection/RetinaNet/keras-retinanet/keras_retinanet/preprocessing/generator.py#L147-L156
csujedihy/lc-all-solutions
b9fd938a7b3c164f28096361993600e338c399c3
444.sequence-reconstruction/sequence-reconstruction.py
python
Solution.sequenceReconstruction
(self, org, seqs)
return False
:type org: List[int] :type seqs: List[List[int]] :rtype: bool
:type org: List[int] :type seqs: List[List[int]] :rtype: bool
[ ":", "type", "org", ":", "List", "[", "int", "]", ":", "type", "seqs", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "bool" ]
def sequenceReconstruction(self, org, seqs): """ :type org: List[int] :type seqs: List[List[int]] :rtype: bool """ n = len(org) graph = collections.defaultdict(list) visited = {} incomings = collections.defaultdict(int) nodes = set() for seq in seqs: nodes |= set(seq) if len(seq) > 0: incomings[seq[0]] += 0 for i in range(0, len(seq) - 1): start, end = seq[i], seq[i + 1] graph[start].append(end) incomings[end] += 1 count = 0 for node in incomings: if incomings[node] == 0: count += 1 if count == 2: return False order = [] visited = collections.defaultdict(int) queue = [q for q in incomings if incomings[q] == 0] while len(queue) == 1: top = queue.pop() order.append(top) for nbr in graph[top]: incomings[nbr] -= 1 if incomings[nbr] == 0: queue.append(nbr) if len(queue) > 1: return False if order == org and len(order) == len(nodes): return True return False
[ "def", "sequenceReconstruction", "(", "self", ",", "org", ",", "seqs", ")", ":", "n", "=", "len", "(", "org", ")", "graph", "=", "collections", ".", "defaultdict", "(", "list", ")", "visited", "=", "{", "}", "incomings", "=", "collections", ".", "defau...
https://github.com/csujedihy/lc-all-solutions/blob/b9fd938a7b3c164f28096361993600e338c399c3/444.sequence-reconstruction/sequence-reconstruction.py#L5-L45
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/django/contrib/gis/gdal/geometries.py
python
OGRGeometry.union
(self, other)
return self._geomgen(capi.geom_union, other)
Returns a new geometry consisting of the region which is the union of this geometry and the other.
Returns a new geometry consisting of the region which is the union of this geometry and the other.
[ "Returns", "a", "new", "geometry", "consisting", "of", "the", "region", "which", "is", "the", "union", "of", "this", "geometry", "and", "the", "other", "." ]
def union(self, other): """ Returns a new geometry consisting of the region which is the union of this geometry and the other. """ return self._geomgen(capi.geom_union, other)
[ "def", "union", "(", "self", ",", "other", ")", ":", "return", "self", ".", "_geomgen", "(", "capi", ".", "geom_union", ",", "other", ")" ]
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/django/contrib/gis/gdal/geometries.py#L522-L527
azavea/raster-vision
fc181a6f31f085affa1ee12f0204bdbc5a6bf85a
rastervision_core/rastervision/core/data/label_store/label_store.py
python
LabelStore.save
(self, labels)
Save. Args: labels - Labels to be saved, the type of which will be dependant on the type of pipeline.
Save.
[ "Save", "." ]
def save(self, labels): """Save. Args: labels - Labels to be saved, the type of which will be dependant on the type of pipeline. """ pass
[ "def", "save", "(", "self", ",", "labels", ")", ":", "pass" ]
https://github.com/azavea/raster-vision/blob/fc181a6f31f085affa1ee12f0204bdbc5a6bf85a/rastervision_core/rastervision/core/data/label_store/label_store.py#L11-L18
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/sqlalchemy/util/topological.py
python
sort
(tuples, allitems, deterministic_order=False)
sort the given list of items by dependency. 'tuples' is a list of tuples representing a partial ordering. 'deterministic_order' keeps items within a dependency tier in list order.
sort the given list of items by dependency.
[ "sort", "the", "given", "list", "of", "items", "by", "dependency", "." ]
def sort(tuples, allitems, deterministic_order=False): """sort the given list of items by dependency. 'tuples' is a list of tuples representing a partial ordering. 'deterministic_order' keeps items within a dependency tier in list order. """ for set_ in sort_as_subsets(tuples, allitems, deterministic_order): for s in set_: yield s
[ "def", "sort", "(", "tuples", ",", "allitems", ",", "deterministic_order", "=", "False", ")", ":", "for", "set_", "in", "sort_as_subsets", "(", "tuples", ",", "allitems", ",", "deterministic_order", ")", ":", "for", "s", "in", "set_", ":", "yield", "s" ]
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/sqlalchemy/util/topological.py#L43-L52
stackimpact/stackimpact-python
4d0a415b790c89e7bee1d70216f948b7fec11540
stackimpact/metric.py
python
Breakdown.floor
(self)
[]
def floor(self): self.measurement = int(self.measurement) for name, child in self.children.items(): child.floor()
[ "def", "floor", "(", "self", ")", ":", "self", ".", "measurement", "=", "int", "(", "self", ".", "measurement", ")", "for", "name", ",", "child", "in", "self", ".", "children", ".", "items", "(", ")", ":", "child", ".", "floor", "(", ")" ]
https://github.com/stackimpact/stackimpact-python/blob/4d0a415b790c89e7bee1d70216f948b7fec11540/stackimpact/metric.py#L326-L330
uqfoundation/multiprocess
028cc73f02655e6451d92e5147d19d8c10aebe50
py2.5/processing/managers.py
python
transact
(address, authkey, methodname, args=(), kwds={})
Create connection then send a message to manager and return response
Create connection then send a message to manager and return response
[ "Create", "connection", "then", "send", "a", "message", "to", "manager", "and", "return", "response" ]
def transact(address, authkey, methodname, args=(), kwds={}): ''' Create connection then send a message to manager and return response ''' conn = Client(address, authkey=authkey) try: return dispatch(conn, None, methodname, args, kwds) finally: conn.close()
[ "def", "transact", "(", "address", ",", "authkey", ",", "methodname", ",", "args", "=", "(", ")", ",", "kwds", "=", "{", "}", ")", ":", "conn", "=", "Client", "(", "address", ",", "authkey", "=", "authkey", ")", "try", ":", "return", "dispatch", "(...
https://github.com/uqfoundation/multiprocess/blob/028cc73f02655e6451d92e5147d19d8c10aebe50/py2.5/processing/managers.py#L99-L107
JelteF/PyLaTeX
1a73261b771ae15afbb3ca5f06d4ba61328f1c62
pylatex/figure.py
python
SubFigure.__init__
(self, width=NoEscape(r'0.45\linewidth'), **kwargs)
Args ---- width: str Width of the subfigure itself. It needs a width because it is inside another figure.
Args ---- width: str Width of the subfigure itself. It needs a width because it is inside another figure.
[ "Args", "----", "width", ":", "str", "Width", "of", "the", "subfigure", "itself", ".", "It", "needs", "a", "width", "because", "it", "is", "inside", "another", "figure", "." ]
def __init__(self, width=NoEscape(r'0.45\linewidth'), **kwargs): """ Args ---- width: str Width of the subfigure itself. It needs a width because it is inside another figure. """ super().__init__(arguments=width, **kwargs)
[ "def", "__init__", "(", "self", ",", "width", "=", "NoEscape", "(", "r'0.45\\linewidth'", ")", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", "arguments", "=", "width", ",", "*", "*", "kwargs", ")" ]
https://github.com/JelteF/PyLaTeX/blob/1a73261b771ae15afbb3ca5f06d4ba61328f1c62/pylatex/figure.py#L107-L117
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/light/__init__.py
python
LightEntity.rgbww_color
(self)
return self._attr_rgbww_color
Return the rgbww color value [int, int, int, int, int].
Return the rgbww color value [int, int, int, int, int].
[ "Return", "the", "rgbww", "color", "value", "[", "int", "int", "int", "int", "int", "]", "." ]
def rgbww_color(self) -> tuple[int, int, int, int, int] | None: """Return the rgbww color value [int, int, int, int, int].""" return self._attr_rgbww_color
[ "def", "rgbww_color", "(", "self", ")", "->", "tuple", "[", "int", ",", "int", ",", "int", ",", "int", ",", "int", "]", "|", "None", ":", "return", "self", ".", "_attr_rgbww_color" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/light/__init__.py#L785-L787
snok/django-auth-adfs
a2e9b37ae29081ea6c752facd7f5a8d0d63b8917
django_auth_adfs/views.py
python
OAuth2LoginNoSSOView.get
(self, request)
return redirect(provider_config.build_authorization_endpoint(request, disable_sso=True))
Initiates the OAuth2 flow and redirect the user agent to ADFS Args: request (django.http.request.HttpRequest): A Django Request object
Initiates the OAuth2 flow and redirect the user agent to ADFS
[ "Initiates", "the", "OAuth2", "flow", "and", "redirect", "the", "user", "agent", "to", "ADFS" ]
def get(self, request): """ Initiates the OAuth2 flow and redirect the user agent to ADFS Args: request (django.http.request.HttpRequest): A Django Request object """ return redirect(provider_config.build_authorization_endpoint(request, disable_sso=True))
[ "def", "get", "(", "self", ",", "request", ")", ":", "return", "redirect", "(", "provider_config", ".", "build_authorization_endpoint", "(", "request", ",", "disable_sso", "=", "True", ")", ")" ]
https://github.com/snok/django-auth-adfs/blob/a2e9b37ae29081ea6c752facd7f5a8d0d63b8917/django_auth_adfs/views.py#L89-L96
bridgecrewio/checkov
f4f8caead6aa2f1824ae1cc88cd1816b12211629
checkov/common/bridgecrew/integration_features/features/suppressions_integration.py
python
SuppressionsIntegration._check_suppression
(self, record, suppression)
return False
Returns True if and only if the specified suppression applies to the specified record. :param record: :param suppression: :return:
Returns True if and only if the specified suppression applies to the specified record. :param record: :param suppression: :return:
[ "Returns", "True", "if", "and", "only", "if", "the", "specified", "suppression", "applies", "to", "the", "specified", "record", ".", ":", "param", "record", ":", ":", "param", "suppression", ":", ":", "return", ":" ]
def _check_suppression(self, record, suppression): """ Returns True if and only if the specified suppression applies to the specified record. :param record: :param suppression: :return: """ if record.check_id != suppression['checkovPolicyId']: return False type = suppression['suppressionType'] if type == 'Policy': # We already validated the policy ID above return True elif type == 'Accounts': # This should be true, because we validated when we downloaded the policies. # But checking here adds some resiliency against bugs if that changes. return any(self._repo_matches(account) for account in suppression['accountIds']) elif type == 'Resources': for resource in suppression['resources']: if self._repo_matches(resource['accountId']) and resource['resourceId'] == f'{record.repo_file_path}:{record.resource}': return True return False elif type == 'Tags': entity_tags = record.entity_tags if not entity_tags: return False suppression_tags = suppression['tags'] # a list of objects of the form {key: str, value: str} for tag in suppression_tags: key = tag['key'] value = tag['value'] if entity_tags.get(key) == value: return True return False
[ "def", "_check_suppression", "(", "self", ",", "record", ",", "suppression", ")", ":", "if", "record", ".", "check_id", "!=", "suppression", "[", "'checkovPolicyId'", "]", ":", "return", "False", "type", "=", "suppression", "[", "'suppressionType'", "]", "if",...
https://github.com/bridgecrewio/checkov/blob/f4f8caead6aa2f1824ae1cc88cd1816b12211629/checkov/common/bridgecrew/integration_features/features/suppressions_integration.py#L76-L112
gwpy/gwpy
82becd78d166a32985cb657a54d0d39f6a207739
gwpy/astro/range.py
python
range_spectrogram
(hoft, stride=None, fftlength=None, overlap=None, window='hann', method=DEFAULT_FFT_METHOD, nproc=1, **rangekwargs)
return out
Calculate the average range or range power spectrogram (Mpc or Mpc^2 / Hz) directly from strain Parameters ---------- hoft : `~gwpy.timeseries.TimeSeries` or `~gwpy.spectrogram.Spectrogram` record of gravitational-wave strain output from a detector stride : `float`, optional number of seconds in a single PSD (i.e., step size of spectrogram), required if `hoft` is an instance of `TimeSeries` fftlength : `float`, optional number of seconds in a single FFT overlap : `float`, optional number of seconds of overlap between FFTs, defaults to the recommended overlap for the given window (if given), or 0 window : `str`, `numpy.ndarray`, optional window function to apply to timeseries prior to FFT, see :func:`scipy.signal.get_window` for details on acceptable formats method : `str`, optional FFT-averaging method, defaults to median averaging, see :meth:`~gwpy.timeseries.TimeSeries.spectrogram` for more details nproc : `int`, optional number of CPUs to use in parallel processing of FFTs, default: 1 fmin : `float`, optional low frequency cut-off (Hz), defaults to `1/fftlength` fmax : `float`, optional high frequency cut-off (Hz), defaults to Nyquist frequency of `hoft` **rangekwargs : `dict`, optional additional keyword arguments to :func:`burst_range_spectrum` or :func:`inspiral_range_psd` (see "Notes" below), defaults to inspiral range with `mass1 = mass2 = 1.4` solar masses Returns ------- out : `~gwpy.spectrogram.Spectrogram` time-frequency spectrogram of astrophysical range Notes ----- This method is designed to show the contribution to a gravitational-wave detector's sensitive range across frequency bins as a function of time. It supports the range to compact binary inspirals and to unmodelled GW bursts, each a class of transient event. If inspiral range is requested and `fmax` exceeds the frequency of the innermost stable circular orbit (ISCO), the output will extend only up to the latter. See also -------- gwpy.timeseries.TimeSeries.spectrogram for the underlying power spectral density estimator inspiral_range_psd for the function that computes inspiral range integrand burst_range_spectrum for the function that computes burst range integrand range_timeseries for `TimeSeries` trends of the astrophysical range
Calculate the average range or range power spectrogram (Mpc or Mpc^2 / Hz) directly from strain
[ "Calculate", "the", "average", "range", "or", "range", "power", "spectrogram", "(", "Mpc", "or", "Mpc^2", "/", "Hz", ")", "directly", "from", "strain" ]
def range_spectrogram(hoft, stride=None, fftlength=None, overlap=None, window='hann', method=DEFAULT_FFT_METHOD, nproc=1, **rangekwargs): """Calculate the average range or range power spectrogram (Mpc or Mpc^2 / Hz) directly from strain Parameters ---------- hoft : `~gwpy.timeseries.TimeSeries` or `~gwpy.spectrogram.Spectrogram` record of gravitational-wave strain output from a detector stride : `float`, optional number of seconds in a single PSD (i.e., step size of spectrogram), required if `hoft` is an instance of `TimeSeries` fftlength : `float`, optional number of seconds in a single FFT overlap : `float`, optional number of seconds of overlap between FFTs, defaults to the recommended overlap for the given window (if given), or 0 window : `str`, `numpy.ndarray`, optional window function to apply to timeseries prior to FFT, see :func:`scipy.signal.get_window` for details on acceptable formats method : `str`, optional FFT-averaging method, defaults to median averaging, see :meth:`~gwpy.timeseries.TimeSeries.spectrogram` for more details nproc : `int`, optional number of CPUs to use in parallel processing of FFTs, default: 1 fmin : `float`, optional low frequency cut-off (Hz), defaults to `1/fftlength` fmax : `float`, optional high frequency cut-off (Hz), defaults to Nyquist frequency of `hoft` **rangekwargs : `dict`, optional additional keyword arguments to :func:`burst_range_spectrum` or :func:`inspiral_range_psd` (see "Notes" below), defaults to inspiral range with `mass1 = mass2 = 1.4` solar masses Returns ------- out : `~gwpy.spectrogram.Spectrogram` time-frequency spectrogram of astrophysical range Notes ----- This method is designed to show the contribution to a gravitational-wave detector's sensitive range across frequency bins as a function of time. It supports the range to compact binary inspirals and to unmodelled GW bursts, each a class of transient event. If inspiral range is requested and `fmax` exceeds the frequency of the innermost stable circular orbit (ISCO), the output will extend only up to the latter. See also -------- gwpy.timeseries.TimeSeries.spectrogram for the underlying power spectral density estimator inspiral_range_psd for the function that computes inspiral range integrand burst_range_spectrum for the function that computes burst range integrand range_timeseries for `TimeSeries` trends of the astrophysical range """ rangekwargs = rangekwargs or {'mass1': 1.4, 'mass2': 1.4} range_func = (burst_range_spectrum if 'energy' in rangekwargs else inspiral_range_psd) hoft = _get_spectrogram( hoft, stride=stride, fftlength=fftlength, overlap=overlap, window=window, method=method, nproc=nproc) # set frequency limits f = hoft.frequencies.to('Hz') fmin = units.Quantity( rangekwargs.pop('fmin', hoft.df), 'Hz', ) fmax = units.Quantity( rangekwargs.pop( 'fmax', round_to_power(f[-1].value, which='lower'), ), 'Hz', ) frange = (f >= fmin) & (f < fmax) # loop over time bins out = Spectrogram( [range_func(psd[frange], **rangekwargs).value for psd in hoft], ) # finalise output out.__array_finalize__(hoft) out.override_unit('Mpc' if 'energy' in rangekwargs else 'Mpc^2 / Hz') out.f0 = fmin return out
[ "def", "range_spectrogram", "(", "hoft", ",", "stride", "=", "None", ",", "fftlength", "=", "None", ",", "overlap", "=", "None", ",", "window", "=", "'hann'", ",", "method", "=", "DEFAULT_FFT_METHOD", ",", "nproc", "=", "1", ",", "*", "*", "rangekwargs",...
https://github.com/gwpy/gwpy/blob/82becd78d166a32985cb657a54d0d39f6a207739/gwpy/astro/range.py#L435-L538
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/build/inline_copy/pkg_resources/pkg_resources/__init__.py
python
split_sections
(s)
Split a string or iterable thereof into (section, content) pairs Each ``section`` is a stripped version of the section header ("[section]") and each ``content`` is a list of stripped lines excluding blank lines and comment-only lines. If there are any such lines before the first section header, they're returned in a first ``section`` of ``None``.
Split a string or iterable thereof into (section, content) pairs
[ "Split", "a", "string", "or", "iterable", "thereof", "into", "(", "section", "content", ")", "pairs" ]
def split_sections(s): """Split a string or iterable thereof into (section, content) pairs Each ``section`` is a stripped version of the section header ("[section]") and each ``content`` is a list of stripped lines excluding blank lines and comment-only lines. If there are any such lines before the first section header, they're returned in a first ``section`` of ``None``. """ section = None content = [] for line in yield_lines(s): if line.startswith("["): if line.endswith("]"): if section or content: yield section, content section = line[1:-1].strip() content = [] else: raise ValueError("Invalid section heading", line) else: content.append(line) # wrap up last segment yield section, content
[ "def", "split_sections", "(", "s", ")", ":", "section", "=", "None", "content", "=", "[", "]", "for", "line", "in", "yield_lines", "(", "s", ")", ":", "if", "line", ".", "startswith", "(", "\"[\"", ")", ":", "if", "line", ".", "endswith", "(", "\"]...
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/pkg_resources/pkg_resources/__init__.py#L3154-L3177
datacenter/acitoolkit
629b84887dd0f0183b81efc8adb16817f985541a
applications/configpush/apicservice.py
python
ConfigDB.remove_contract_policy
(self, policy)
Remove the contract policy :param policy: Instance of ContractPolicy :return: None
Remove the contract policy :param policy: Instance of ContractPolicy :return: None
[ "Remove", "the", "contract", "policy", ":", "param", "policy", ":", "Instance", "of", "ContractPolicy", ":", "return", ":", "None" ]
def remove_contract_policy(self, policy): """ Remove the contract policy :param policy: Instance of ContractPolicy :return: None """ self._contract_policies.remove(policy)
[ "def", "remove_contract_policy", "(", "self", ",", "policy", ")", ":", "self", ".", "_contract_policies", ".", "remove", "(", "policy", ")" ]
https://github.com/datacenter/acitoolkit/blob/629b84887dd0f0183b81efc8adb16817f985541a/applications/configpush/apicservice.py#L763-L769
clockworkpi/launcher
13ed96d83cad6210c450c17445c5d0907b1081b0
Menu/GameShell/10_Settings/Brightness/brightness_page.py
python
BSlider.Draw
(self)
pygame.draw.line(self._CanvasHWND,(255,0,0), (posx,self._PosY),(self._Width,self._PosY),3) ## range line pygame.draw.line(self._CanvasHWND,(0,0,255), (self._PosX,self._PosY),(posx,self._PosY),3) ## range line pygame.draw.circle(self._CanvasHWND,(255,255,255),( posx, self._PosY),7,0) pygame.draw.circle(self._CanvasHWND,(0,0,0) ,( posx, self._PosY),7,1)## outer border
pygame.draw.line(self._CanvasHWND,(255,0,0), (posx,self._PosY),(self._Width,self._PosY),3) ## range line pygame.draw.line(self._CanvasHWND,(0,0,255), (self._PosX,self._PosY),(posx,self._PosY),3) ## range line pygame.draw.circle(self._CanvasHWND,(255,255,255),( posx, self._PosY),7,0) pygame.draw.circle(self._CanvasHWND,(0,0,0) ,( posx, self._PosY),7,1)## outer border
[ "pygame", ".", "draw", ".", "line", "(", "self", ".", "_CanvasHWND", "(", "255", "0", "0", ")", "(", "posx", "self", ".", "_PosY", ")", "(", "self", ".", "_Width", "self", ".", "_PosY", ")", "3", ")", "##", "range", "line", "pygame", ".", "draw",...
def Draw(self): self._Icons["bg"].NewCoord(self._Width/2,self._Height/2 +11 ) self._Icons["bg"].Draw() self._Icons["scale"].NewCoord(self._Width/2,self._Height/2 ) icon_idx = self._Value - 1 if icon_idx < 0: icon_idx = 0 self._Icons["scale"]._IconIndex = icon_idx self._Icons["scale"].Draw() """ pygame.draw.line(self._CanvasHWND,(255,0,0), (posx,self._PosY),(self._Width,self._PosY),3) ## range line pygame.draw.line(self._CanvasHWND,(0,0,255), (self._PosX,self._PosY),(posx,self._PosY),3) ## range line pygame.draw.circle(self._CanvasHWND,(255,255,255),( posx, self._PosY),7,0) pygame.draw.circle(self._CanvasHWND,(0,0,0) ,( posx, self._PosY),7,1)## outer border """
[ "def", "Draw", "(", "self", ")", ":", "self", ".", "_Icons", "[", "\"bg\"", "]", ".", "NewCoord", "(", "self", ".", "_Width", "/", "2", ",", "self", ".", "_Height", "/", "2", "+", "11", ")", "self", ".", "_Icons", "[", "\"bg\"", "]", ".", "Draw...
https://github.com/clockworkpi/launcher/blob/13ed96d83cad6210c450c17445c5d0907b1081b0/Menu/GameShell/10_Settings/Brightness/brightness_page.py#L80-L99
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/operator.py
python
ixor
(a, b)
return a
Same as a ^= b.
Same as a ^= b.
[ "Same", "as", "a", "^", "=", "b", "." ]
def ixor(a, b): "Same as a ^= b." a ^= b return a
[ "def", "ixor", "(", "a", ",", "b", ")", ":", "a", "^=", "b", "return", "a" ]
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/operator.py#L405-L408
ubuntu/ubuntu-make
939668aad1f4c38ffb74cce55b3678f6fded5c71
umake/tools.py
python
_get_shell_profile_file_path
()
return os.path.join(os.path.expanduser('~'), profile_filename)
Return profile filepath for current preferred shell
Return profile filepath for current preferred shell
[ "Return", "profile", "filepath", "for", "current", "preferred", "shell" ]
def _get_shell_profile_file_path(): """Return profile filepath for current preferred shell""" current_shell = os.getenv('SHELL', '/bin/bash').lower() profile_filename = '.zprofile' if 'zsh' in current_shell else '.profile' return os.path.join(os.path.expanduser('~'), profile_filename)
[ "def", "_get_shell_profile_file_path", "(", ")", ":", "current_shell", "=", "os", ".", "getenv", "(", "'SHELL'", ",", "'/bin/bash'", ")", ".", "lower", "(", ")", "profile_filename", "=", "'.zprofile'", "if", "'zsh'", "in", "current_shell", "else", "'.profile'", ...
https://github.com/ubuntu/ubuntu-make/blob/939668aad1f4c38ffb74cce55b3678f6fded5c71/umake/tools.py#L415-L419
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/sqlalchemy/engine/reflection.py
python
Inspector.get_table_options
(self, table_name, schema=None, **kw)
return {}
Return a dictionary of options specified when the table of the given name was created. This currently includes some options that apply to MySQL tables. :param table_name: string name of the table. For special quoting, use :class:`.quoted_name`. :param schema: string schema name; if omitted, uses the default schema of the database connection. For special quoting, use :class:`.quoted_name`.
Return a dictionary of options specified when the table of the given name was created.
[ "Return", "a", "dictionary", "of", "options", "specified", "when", "the", "table", "of", "the", "given", "name", "was", "created", "." ]
def get_table_options(self, table_name, schema=None, **kw): """Return a dictionary of options specified when the table of the given name was created. This currently includes some options that apply to MySQL tables. :param table_name: string name of the table. For special quoting, use :class:`.quoted_name`. :param schema: string schema name; if omitted, uses the default schema of the database connection. For special quoting, use :class:`.quoted_name`. """ if hasattr(self.dialect, 'get_table_options'): return self.dialect.get_table_options( self.bind, table_name, schema, info_cache=self.info_cache, **kw) return {}
[ "def", "get_table_options", "(", "self", ",", "table_name", ",", "schema", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "hasattr", "(", "self", ".", "dialect", ",", "'get_table_options'", ")", ":", "return", "self", ".", "dialect", ".", "get_table_o...
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/sqlalchemy/engine/reflection.py#L295-L313
JDAI-CV/fast-reid
31d99b793fe0937461b9c9bc8a8a11f88bf5642c
fastreid/data/transforms/autoaugment.py
python
auto_augment_policy
(name="original")
[]
def auto_augment_policy(name="original"): hparams = _HPARAMS_DEFAULT if name == 'original': return auto_augment_policy_original(hparams) elif name == 'originalr': return auto_augment_policy_originalr(hparams) elif name == 'v0': return auto_augment_policy_v0(hparams) elif name == 'v0r': return auto_augment_policy_v0r(hparams) else: assert False, 'Unknown AA policy (%s)' % name
[ "def", "auto_augment_policy", "(", "name", "=", "\"original\"", ")", ":", "hparams", "=", "_HPARAMS_DEFAULT", "if", "name", "==", "'original'", ":", "return", "auto_augment_policy_original", "(", "hparams", ")", "elif", "name", "==", "'originalr'", ":", "return", ...
https://github.com/JDAI-CV/fast-reid/blob/31d99b793fe0937461b9c9bc8a8a11f88bf5642c/fastreid/data/transforms/autoaugment.py#L481-L492
Cadene/tensorflow-model-zoo.torch
990b10ffc22d4c8eacb2a502f20415b4f70c74c2
models/research/pcl_rl/policy.py
python
Policy.entropy
(self, logits, sampling_dim, act_dim, act_type)
return entropy
Calculate entropy of distribution.
Calculate entropy of distribution.
[ "Calculate", "entropy", "of", "distribution", "." ]
def entropy(self, logits, sampling_dim, act_dim, act_type): """Calculate entropy of distribution.""" if self.env_spec.is_discrete(act_type): entropy = tf.reduce_sum( -tf.nn.softmax(logits) * tf.nn.log_softmax(logits), -1) elif self.env_spec.is_box(act_type): means = logits[:, :sampling_dim / 2] std = logits[:, sampling_dim / 2:] entropy = tf.reduce_sum( 0.5 * (1 + tf.log(2 * np.pi * tf.square(std))), -1) else: assert False return entropy
[ "def", "entropy", "(", "self", ",", "logits", ",", "sampling_dim", ",", "act_dim", ",", "act_type", ")", ":", "if", "self", ".", "env_spec", ".", "is_discrete", "(", "act_type", ")", ":", "entropy", "=", "tf", ".", "reduce_sum", "(", "-", "tf", ".", ...
https://github.com/Cadene/tensorflow-model-zoo.torch/blob/990b10ffc22d4c8eacb2a502f20415b4f70c74c2/models/research/pcl_rl/policy.py#L130-L144
dmeranda/demjson
5bc65974e7141746acc88c581f5d2dfb8ea14064
demjson.py
python
JSON.encode_number
(self, n, state)
Encodes a Python numeric type into a JSON numeric literal. The special non-numeric values of float('nan'), float('inf') and float('-inf') are translated into appropriate JSON literals. Note that Python complex types are not handled, as there is no ECMAScript equivalent type.
Encodes a Python numeric type into a JSON numeric literal. The special non-numeric values of float('nan'), float('inf') and float('-inf') are translated into appropriate JSON literals. Note that Python complex types are not handled, as there is no ECMAScript equivalent type.
[ "Encodes", "a", "Python", "numeric", "type", "into", "a", "JSON", "numeric", "literal", ".", "The", "special", "non", "-", "numeric", "values", "of", "float", "(", "nan", ")", "float", "(", "inf", ")", "and", "float", "(", "-", "inf", ")", "are", "tr...
def encode_number(self, n, state): """Encodes a Python numeric type into a JSON numeric literal. The special non-numeric values of float('nan'), float('inf') and float('-inf') are translated into appropriate JSON literals. Note that Python complex types are not handled, as there is no ECMAScript equivalent type. """ if isinstance(n, complex): if n.imag: raise JSONEncodeError('Can not encode a complex number that has a non-zero imaginary part',n) n = n.real if isinstance(n, json_int): state.append( n.json_format() ) return if isinstance(n, (int,long)): state.append( str(n) ) return if decimal and isinstance(n, decimal.Decimal): if n.is_nan(): # Could be 'NaN' or 'sNaN' state.append( 'NaN' ) elif n.is_infinite(): if n.is_signed(): state.append( '-Infinity' ) else: state.append( 'Infinity' ) else: s = str(n).lower() if 'e' not in s and '.' not in s: s = s + '.0' state.append( s ) return global nan, inf, neginf if n is nan: state.append( 'NaN' ) elif n is inf: state.append( 'Infinity' ) elif n is neginf: state.append( '-Infinity' ) elif isinstance(n, float): # Check for non-numbers. # In python nan == inf == -inf, so must use repr() to distinguish reprn = repr(n).lower() if ('inf' in reprn and '-' in reprn) or n == neginf: state.append( '-Infinity' ) elif 'inf' in reprn or n is inf: state.append( 'Infinity' ) elif 'nan' in reprn or n is nan: state.append( 'NaN' ) else: # A normal float. state.append( repr(n) ) else: raise TypeError('encode_number expected an integral, float, or decimal number type',type(n))
[ "def", "encode_number", "(", "self", ",", "n", ",", "state", ")", ":", "if", "isinstance", "(", "n", ",", "complex", ")", ":", "if", "n", ".", "imag", ":", "raise", "JSONEncodeError", "(", "'Can not encode a complex number that has a non-zero imaginary part'", "...
https://github.com/dmeranda/demjson/blob/5bc65974e7141746acc88c581f5d2dfb8ea14064/demjson.py#L3982-L4042
GoogleCloudPlatform/PerfKitBenchmarker
6e3412d7d5e414b8ca30ed5eaf970cef1d919a67
perfkitbenchmarker/windows_benchmarks/diskspd_benchmark.py
python
Run
(benchmark_spec)
return results
Measure the disk performance in one VM. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects with the benchmark results.
Measure the disk performance in one VM.
[ "Measure", "the", "disk", "performance", "in", "one", "VM", "." ]
def Run(benchmark_spec): """Measure the disk performance in one VM. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects with the benchmark results. """ vm = benchmark_spec.vms[0] results = [] results.extend(diskspd.RunDiskSpd(vm)) return results
[ "def", "Run", "(", "benchmark_spec", ")", ":", "vm", "=", "benchmark_spec", ".", "vms", "[", "0", "]", "results", "=", "[", "]", "results", ".", "extend", "(", "diskspd", ".", "RunDiskSpd", "(", "vm", ")", ")", "return", "results" ]
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/windows_benchmarks/diskspd_benchmark.py#L44-L58
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/wagtail_bak/contrib/modeladmin/options.py
python
ModelAdmin.get_permissions_for_registration
(self)
return Permission.objects.none()
Utilised by Wagtail's 'register_permissions' hook to allow permissions for a model to be assigned to groups in settings. This is only required if the model isn't a Page model, and isn't registered as a Snippet
Utilised by Wagtail's 'register_permissions' hook to allow permissions for a model to be assigned to groups in settings. This is only required if the model isn't a Page model, and isn't registered as a Snippet
[ "Utilised", "by", "Wagtail", "s", "register_permissions", "hook", "to", "allow", "permissions", "for", "a", "model", "to", "be", "assigned", "to", "groups", "in", "settings", ".", "This", "is", "only", "required", "if", "the", "model", "isn", "t", "a", "Pa...
def get_permissions_for_registration(self): """ Utilised by Wagtail's 'register_permissions' hook to allow permissions for a model to be assigned to groups in settings. This is only required if the model isn't a Page model, and isn't registered as a Snippet """ from wagtail.wagtailsnippets.models import SNIPPET_MODELS if not self.is_pagemodel and self.model not in SNIPPET_MODELS: return self.permission_helper.get_all_model_permissions() return Permission.objects.none()
[ "def", "get_permissions_for_registration", "(", "self", ")", ":", "from", "wagtail", ".", "wagtailsnippets", ".", "models", "import", "SNIPPET_MODELS", "if", "not", "self", ".", "is_pagemodel", "and", "self", ".", "model", "not", "in", "SNIPPET_MODELS", ":", "re...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail_bak/contrib/modeladmin/options.py#L450-L459
dcramer/django-sphinx
0071d1cae5390d0ec8c669786ca3c7275abb6410
djangosphinx/apis/api263/__init__.py
python
SphinxClient.SetServer
(self, host, port)
set searchd server
set searchd server
[ "set", "searchd", "server" ]
def SetServer (self, host, port): """ set searchd server """ assert(isinstance(host, str)) assert(isinstance(port, int)) self._host = host self._port = port
[ "def", "SetServer", "(", "self", ",", "host", ",", "port", ")", ":", "assert", "(", "isinstance", "(", "host", ",", "str", ")", ")", "assert", "(", "isinstance", "(", "port", ",", "int", ")", ")", "self", ".", "_host", "=", "host", "self", ".", "...
https://github.com/dcramer/django-sphinx/blob/0071d1cae5390d0ec8c669786ca3c7275abb6410/djangosphinx/apis/api263/__init__.py#L101-L109
cyverse/atmosphere
4a3e522f1f7b58abd9fa944c10b7455dc5cddac1
core/plugins.py
python
ExpirationPluginManager.is_expired
(cls, user)
return _is_expired
Load each ExpirationPlugin and call `plugin.is_expired(user)`
Load each ExpirationPlugin and call `plugin.is_expired(user)`
[ "Load", "each", "ExpirationPlugin", "and", "call", "plugin", ".", "is_expired", "(", "user", ")" ]
def is_expired(cls, user): """ Load each ExpirationPlugin and call `plugin.is_expired(user)` """ _is_expired = False for ExpirationPlugin in cls.load_plugins(cls.list_of_classes): plugin = ExpirationPlugin() try: inspect.getcallargs(getattr(plugin, 'is_expired'), user=user) except AttributeError: logger.info( "Expiration plugin %s does not have a 'is_expired' method" % ExpirationPlugin ) except TypeError: logger.info( "Expiration plugin %s does not accept kwarg `user`" % ExpirationPlugin ) try: # TODO: Set a reasonable timeout but don't let it hold this indefinitely _is_expired = plugin.is_expired(user=user) except Exception as exc: logger.info( "Expiration plugin %s encountered an error: %s" % (ExpirationPlugin, exc) ) _is_expired = True if _is_expired: return True return _is_expired
[ "def", "is_expired", "(", "cls", ",", "user", ")", ":", "_is_expired", "=", "False", "for", "ExpirationPlugin", "in", "cls", ".", "load_plugins", "(", "cls", ".", "list_of_classes", ")", ":", "plugin", "=", "ExpirationPlugin", "(", ")", "try", ":", "inspec...
https://github.com/cyverse/atmosphere/blob/4a3e522f1f7b58abd9fa944c10b7455dc5cddac1/core/plugins.py#L316-L347
autotest/autotest
4614ae5f550cc888267b9a419e4b90deb54f8fae
client/job.py
python
base_client_job.complete
(self, status)
Write pending TAP reports, clean up, and exit
Write pending TAP reports, clean up, and exit
[ "Write", "pending", "TAP", "reports", "clean", "up", "and", "exit" ]
def complete(self, status): """Write pending TAP reports, clean up, and exit""" # write out TAP reports if self._tap.do_tap_report: self._tap.write() self._tap._write_tap_archive() # write out a job HTML report try: report.write_html_report(self.resultdir) except Exception as e: logging.error("Error writing job HTML report: %s", e) # We are about to exit 'complete' so clean up the control file. dest = os.path.join(self.resultdir, os.path.basename(self._state_file)) shutil.move(self._state_file, dest) self.harness.run_complete() self.disable_external_logging() sys.exit(status)
[ "def", "complete", "(", "self", ",", "status", ")", ":", "# write out TAP reports", "if", "self", ".", "_tap", ".", "do_tap_report", ":", "self", ".", "_tap", ".", "write", "(", ")", "self", ".", "_tap", ".", "_write_tap_archive", "(", ")", "# write out a ...
https://github.com/autotest/autotest/blob/4614ae5f550cc888267b9a419e4b90deb54f8fae/client/job.py#L918-L937
openstack/ironic
b392dc19bcd29cef5a69ec00d2f18a7a19a679e5
ironic/api/controllers/v1/notification_utils.py
python
handle_error_notification
(context, obj, action, **kwargs)
Context manager to handle any error notifications. :param context: request context. :param obj: resource rpc object. :param action: Action string to go in the EventType. :param kwargs: kwargs to use when creating the notification payload.
Context manager to handle any error notifications.
[ "Context", "manager", "to", "handle", "any", "error", "notifications", "." ]
def handle_error_notification(context, obj, action, **kwargs): """Context manager to handle any error notifications. :param context: request context. :param obj: resource rpc object. :param action: Action string to go in the EventType. :param kwargs: kwargs to use when creating the notification payload. """ try: yield except Exception: with excutils.save_and_reraise_exception(): _emit_api_notification(context, obj, action, fields.NotificationLevel.ERROR, fields.NotificationStatus.ERROR, **kwargs)
[ "def", "handle_error_notification", "(", "context", ",", "obj", ",", "action", ",", "*", "*", "kwargs", ")", ":", "try", ":", "yield", "except", "Exception", ":", "with", "excutils", ".", "save_and_reraise_exception", "(", ")", ":", "_emit_api_notification", "...
https://github.com/openstack/ironic/blob/b392dc19bcd29cef5a69ec00d2f18a7a19a679e5/ironic/api/controllers/v1/notification_utils.py#L140-L155
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/collections/__init__.py
python
OrderedDict.__reversed__
(self)
od.__reversed__() <==> reversed(od)
od.__reversed__() <==> reversed(od)
[ "od", ".", "__reversed__", "()", "<", "==", ">", "reversed", "(", "od", ")" ]
def __reversed__(self): 'od.__reversed__() <==> reversed(od)' # Traverse the linked list in reverse order. root = self.__root curr = root[0] # start at the last node while curr is not root: yield curr[2] # yield the curr[KEY] curr = curr[0]
[ "def", "__reversed__", "(", "self", ")", ":", "# Traverse the linked list in reverse order.", "root", "=", "self", ".", "__root", "curr", "=", "root", "[", "0", "]", "# start at the last node", "while", "curr", "is", "not", "root", ":", "yield", "curr", "[", "...
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/collections/__init__.py#L100-L107
craffel/mir_eval
576aad4e0b5931e7c697c078a1153c99b885c64f
mir_eval/multipitch.py
python
evaluate
(ref_time, ref_freqs, est_time, est_freqs, **kwargs)
return scores
Evaluate two multipitch (multi-f0) transcriptions, where the first is treated as the reference (ground truth) and the second as the estimate to be evaluated (prediction). Examples -------- >>> ref_time, ref_freq = mir_eval.io.load_ragged_time_series('ref.txt') >>> est_time, est_freq = mir_eval.io.load_ragged_time_series('est.txt') >>> scores = mir_eval.multipitch.evaluate(ref_time, ref_freq, ... est_time, est_freq) Parameters ---------- ref_time : np.ndarray Time of each reference frequency value ref_freqs : list of np.ndarray List of np.ndarrays of reference frequency values est_time : np.ndarray Time of each estimated frequency value est_freqs : list of np.ndarray List of np.ndarrays of estimate frequency values kwargs Additional keyword arguments which will be passed to the appropriate metric or preprocessing functions. Returns ------- scores : dict Dictionary of scores, where the key is the metric name (str) and the value is the (float) score achieved.
Evaluate two multipitch (multi-f0) transcriptions, where the first is treated as the reference (ground truth) and the second as the estimate to be evaluated (prediction).
[ "Evaluate", "two", "multipitch", "(", "multi", "-", "f0", ")", "transcriptions", "where", "the", "first", "is", "treated", "as", "the", "reference", "(", "ground", "truth", ")", "and", "the", "second", "as", "the", "estimate", "to", "be", "evaluated", "(",...
def evaluate(ref_time, ref_freqs, est_time, est_freqs, **kwargs): """Evaluate two multipitch (multi-f0) transcriptions, where the first is treated as the reference (ground truth) and the second as the estimate to be evaluated (prediction). Examples -------- >>> ref_time, ref_freq = mir_eval.io.load_ragged_time_series('ref.txt') >>> est_time, est_freq = mir_eval.io.load_ragged_time_series('est.txt') >>> scores = mir_eval.multipitch.evaluate(ref_time, ref_freq, ... est_time, est_freq) Parameters ---------- ref_time : np.ndarray Time of each reference frequency value ref_freqs : list of np.ndarray List of np.ndarrays of reference frequency values est_time : np.ndarray Time of each estimated frequency value est_freqs : list of np.ndarray List of np.ndarrays of estimate frequency values kwargs Additional keyword arguments which will be passed to the appropriate metric or preprocessing functions. Returns ------- scores : dict Dictionary of scores, where the key is the metric name (str) and the value is the (float) score achieved. """ scores = collections.OrderedDict() (scores['Precision'], scores['Recall'], scores['Accuracy'], scores['Substitution Error'], scores['Miss Error'], scores['False Alarm Error'], scores['Total Error'], scores['Chroma Precision'], scores['Chroma Recall'], scores['Chroma Accuracy'], scores['Chroma Substitution Error'], scores['Chroma Miss Error'], scores['Chroma False Alarm Error'], scores['Chroma Total Error']) = util.filter_kwargs( metrics, ref_time, ref_freqs, est_time, est_freqs, **kwargs) return scores
[ "def", "evaluate", "(", "ref_time", ",", "ref_freqs", ",", "est_time", ",", "est_freqs", ",", "*", "*", "kwargs", ")", ":", "scores", "=", "collections", ".", "OrderedDict", "(", ")", "(", "scores", "[", "'Precision'", "]", ",", "scores", "[", "'Recall'"...
https://github.com/craffel/mir_eval/blob/576aad4e0b5931e7c697c078a1153c99b885c64f/mir_eval/multipitch.py#L456-L507
memray/seq2seq-keyphrase
9145c63ebdc4c3bc431f8091dc52547a46804012
emolga/models/pointers.py
python
PtrDecoder.__init__
(self, config, rng, prefix='ptrdec')
Create all elements of the Decoder's computational graph.
Create all elements of the Decoder's computational graph.
[ "Create", "all", "elements", "of", "the", "Decoder", "s", "computational", "graph", "." ]
def __init__(self, config, rng, prefix='ptrdec'): super(PtrDecoder, self).__init__() self.config = config self.rng = rng self.prefix = prefix """ Create all elements of the Decoder's computational graph. """ # create Initialization Layers logger.info("{}_create initialization layers.".format(self.prefix)) self.Initializer = Dense( config['ptr_contxt_dim'], config['ptr_hidden_dim'], activation='tanh', name="{}_init".format(self.prefix) ) # create RNN cells logger.info("{}_create RNN cells.".format(self.prefix)) self.RNN = RNN( self.config['ptr_embedd_dim'], self.config['ptr_hidden_dim'], self.config['ptr_contxt_dim'], name="{}_cell".format(self.prefix) ) self._add(self.Initializer) self._add(self.RNN) # create readout layers logger.info("_create Attention-Readout layers") self.attender = Attention( self.config['ptr_hidden_dim'], self.config['ptr_source_dim'], self.config['ptr_middle_dim'], name='{}_attender'.format(self.prefix) ) self._add(self.attender)
[ "def", "__init__", "(", "self", ",", "config", ",", "rng", ",", "prefix", "=", "'ptrdec'", ")", ":", "super", "(", "PtrDecoder", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "config", "=", "config", "self", ".", "rng", "=", "rng", "sel...
https://github.com/memray/seq2seq-keyphrase/blob/9145c63ebdc4c3bc431f8091dc52547a46804012/emolga/models/pointers.py#L23-L61
deanishe/alfred-vpn-manager
f5d0dd1433ea69b1517d4866a12b1118097057b9
src/workflow/workflow.py
python
Workflow._default_cachedir
(self)
return os.path.join( os.path.expanduser( '~/Library/Caches/com.runningwithcrayons.Alfred-2/' 'Workflow Data/'), self.bundleid)
Alfred 2's default cache directory.
Alfred 2's default cache directory.
[ "Alfred", "2", "s", "default", "cache", "directory", "." ]
def _default_cachedir(self): """Alfred 2's default cache directory.""" return os.path.join( os.path.expanduser( '~/Library/Caches/com.runningwithcrayons.Alfred-2/' 'Workflow Data/'), self.bundleid)
[ "def", "_default_cachedir", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "'~/Library/Caches/com.runningwithcrayons.Alfred-2/'", "'Workflow Data/'", ")", ",", "self", ".", "bundleid", ")" ]
https://github.com/deanishe/alfred-vpn-manager/blob/f5d0dd1433ea69b1517d4866a12b1118097057b9/src/workflow/workflow.py#L1247-L1253
nicolas-chaulet/torch-points3d
8e4c19ecb81926626231bf185e9eca77d92a0606
torch_points3d/datasets/segmentation/forward/shapenet.py
python
_ForwardShapenet.get_raw
(self, index)
return self._read_file(self._files[index])
returns the untransformed data associated with an element
returns the untransformed data associated with an element
[ "returns", "the", "untransformed", "data", "associated", "with", "an", "element" ]
def get_raw(self, index): """ returns the untransformed data associated with an element """ return self._read_file(self._files[index])
[ "def", "get_raw", "(", "self", ",", "index", ")", ":", "return", "self", ".", "_read_file", "(", "self", ".", "_files", "[", "index", "]", ")" ]
https://github.com/nicolas-chaulet/torch-points3d/blob/8e4c19ecb81926626231bf185e9eca77d92a0606/torch_points3d/datasets/segmentation/forward/shapenet.py#L56-L59
wrye-bash/wrye-bash
d495c47cfdb44475befa523438a40c4419cb386f
Mopy/bash/brec/record_structs.py
python
MelSet.convertFids
(self,record, mapper,toLong)
Converts fids between formats according to mapper. toLong should be True if converting to long format or False if converting to short format.
Converts fids between formats according to mapper. toLong should be True if converting to long format or False if converting to short format.
[ "Converts", "fids", "between", "formats", "according", "to", "mapper", ".", "toLong", "should", "be", "True", "if", "converting", "to", "long", "format", "or", "False", "if", "converting", "to", "short", "format", "." ]
def convertFids(self,record, mapper,toLong): """Converts fids between formats according to mapper. toLong should be True if converting to long format or False if converting to short format.""" if record.longFids == toLong: return record.fid = mapper(record.fid) for element in self.formElements: element.mapFids(record,mapper,True) record.longFids = toLong record.setChanged()
[ "def", "convertFids", "(", "self", ",", "record", ",", "mapper", ",", "toLong", ")", ":", "if", "record", ".", "longFids", "==", "toLong", ":", "return", "record", ".", "fid", "=", "mapper", "(", "record", ".", "fid", ")", "for", "element", "in", "se...
https://github.com/wrye-bash/wrye-bash/blob/d495c47cfdb44475befa523438a40c4419cb386f/Mopy/bash/brec/record_structs.py#L217-L225
bastibe/python-soundfile
d1d125f5749780b0b068b5fcb49d8e84f7f4f045
soundfile.py
python
SoundFile._update_frames
(self, written)
Update self.frames after writing.
Update self.frames after writing.
[ "Update", "self", ".", "frames", "after", "writing", "." ]
def _update_frames(self, written): """Update self.frames after writing.""" if self.seekable(): curr = self.tell() self._info.frames = self.seek(0, SEEK_END) self.seek(curr, SEEK_SET) else: self._info.frames += written
[ "def", "_update_frames", "(", "self", ",", "written", ")", ":", "if", "self", ".", "seekable", "(", ")", ":", "curr", "=", "self", ".", "tell", "(", ")", "self", ".", "_info", ".", "frames", "=", "self", ".", "seek", "(", "0", ",", "SEEK_END", ")...
https://github.com/bastibe/python-soundfile/blob/d1d125f5749780b0b068b5fcb49d8e84f7f4f045/soundfile.py#L1339-L1346
NoGameNoLife00/mybolg
afe17ea5bfe405e33766e5682c43a4262232ee12
libs/sqlalchemy/dialects/postgresql/base.py
python
ENUM._check_for_name_in_memos
(self, checkfirst, kw)
Look in the 'ddl runner' for 'memos', then note our name in that collection. This to ensure a particular named enum is operated upon only once within any kind of create/drop sequence without relying upon "checkfirst".
Look in the 'ddl runner' for 'memos', then note our name in that collection.
[ "Look", "in", "the", "ddl", "runner", "for", "memos", "then", "note", "our", "name", "in", "that", "collection", "." ]
def _check_for_name_in_memos(self, checkfirst, kw): """Look in the 'ddl runner' for 'memos', then note our name in that collection. This to ensure a particular named enum is operated upon only once within any kind of create/drop sequence without relying upon "checkfirst". """ if not self.create_type: return True if '_ddl_runner' in kw: ddl_runner = kw['_ddl_runner'] if '_pg_enums' in ddl_runner.memo: pg_enums = ddl_runner.memo['_pg_enums'] else: pg_enums = ddl_runner.memo['_pg_enums'] = set() present = self.name in pg_enums pg_enums.add(self.name) return present else: return False
[ "def", "_check_for_name_in_memos", "(", "self", ",", "checkfirst", ",", "kw", ")", ":", "if", "not", "self", ".", "create_type", ":", "return", "True", "if", "'_ddl_runner'", "in", "kw", ":", "ddl_runner", "=", "kw", "[", "'_ddl_runner'", "]", "if", "'_pg_...
https://github.com/NoGameNoLife00/mybolg/blob/afe17ea5bfe405e33766e5682c43a4262232ee12/libs/sqlalchemy/dialects/postgresql/base.py#L1103-L1124
merkremont/LineVodka
c2fa74107cecf00dd17416b62e4eb579e2c7bbaf
LineAlpha/LineThrift/TalkService.py
python
Iface.getMessageBoxWrapUp
(self, mid)
Parameters: - mid
Parameters: - mid
[ "Parameters", ":", "-", "mid" ]
def getMessageBoxWrapUp(self, mid): """ Parameters: - mid """ pass
[ "def", "getMessageBoxWrapUp", "(", "self", ",", "mid", ")", ":", "pass" ]
https://github.com/merkremont/LineVodka/blob/c2fa74107cecf00dd17416b62e4eb579e2c7bbaf/LineAlpha/LineThrift/TalkService.py#L479-L484
mrkipling/maraschino
c6be9286937783ae01df2d6d8cebfc8b2734a7d7
lib/sqlalchemy/pool.py
python
Pool.recreate
(self)
Return a new :class:`.Pool`, of the same class as this one and configured with identical creation arguments. This method is used in conjunection with :meth:`dispose` to close out an entire :class:`.Pool` and create a new one in its place.
Return a new :class:`.Pool`, of the same class as this one and configured with identical creation arguments.
[ "Return", "a", "new", ":", "class", ":", ".", "Pool", "of", "the", "same", "class", "as", "this", "one", "and", "configured", "with", "identical", "creation", "arguments", "." ]
def recreate(self): """Return a new :class:`.Pool`, of the same class as this one and configured with identical creation arguments. This method is used in conjunection with :meth:`dispose` to close out an entire :class:`.Pool` and create a new one in its place. """ raise NotImplementedError()
[ "def", "recreate", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/sqlalchemy/pool.py#L176-L186
microsoft/azure-devops-python-api
451cade4c475482792cbe9e522c1fee32393139e
azure-devops/azure/devops/v6_0/build/build_client.py
python
BuildClient.get_changes_between_builds
(self, project, from_build_id=None, to_build_id=None, top=None)
return self._deserialize('[Change]', self._unwrap_collection(response))
GetChangesBetweenBuilds. [Preview API] Gets the changes made to the repository between two given builds. :param str project: Project ID or project name :param int from_build_id: The ID of the first build. :param int to_build_id: The ID of the last build. :param int top: The maximum number of changes to return. :rtype: [Change]
GetChangesBetweenBuilds. [Preview API] Gets the changes made to the repository between two given builds. :param str project: Project ID or project name :param int from_build_id: The ID of the first build. :param int to_build_id: The ID of the last build. :param int top: The maximum number of changes to return. :rtype: [Change]
[ "GetChangesBetweenBuilds", ".", "[", "Preview", "API", "]", "Gets", "the", "changes", "made", "to", "the", "repository", "between", "two", "given", "builds", ".", ":", "param", "str", "project", ":", "Project", "ID", "or", "project", "name", ":", "param", ...
def get_changes_between_builds(self, project, from_build_id=None, to_build_id=None, top=None): """GetChangesBetweenBuilds. [Preview API] Gets the changes made to the repository between two given builds. :param str project: Project ID or project name :param int from_build_id: The ID of the first build. :param int to_build_id: The ID of the last build. :param int top: The maximum number of changes to return. :rtype: [Change] """ route_values = {} if project is not None: route_values['project'] = self._serialize.url('project', project, 'str') query_parameters = {} if from_build_id is not None: query_parameters['fromBuildId'] = self._serialize.query('from_build_id', from_build_id, 'int') if to_build_id is not None: query_parameters['toBuildId'] = self._serialize.query('to_build_id', to_build_id, 'int') if top is not None: query_parameters['$top'] = self._serialize.query('top', top, 'int') response = self._send(http_method='GET', location_id='f10f0ea5-18a1-43ec-a8fb-2042c7be9b43', version='6.0-preview.2', route_values=route_values, query_parameters=query_parameters) return self._deserialize('[Change]', self._unwrap_collection(response))
[ "def", "get_changes_between_builds", "(", "self", ",", "project", ",", "from_build_id", "=", "None", ",", "to_build_id", "=", "None", ",", "top", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values...
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v6_0/build/build_client.py#L556-L580
nussl/nussl
471e7965c5788bff9fe2e1f7884537cae2d18e6f
nussl/ml/__init__.py
python
register_module
(module)
Your custom modules can be registered with nussl's SeparationModel via this function. For example, if you have some module `ExampleModule`, you can register it as follows: .. code-block:: python class ExampleModule(nn.Module): def forward(self, data): data = data * 2 return data ml.register_module(ExampleModule) You can now use the name `ExampleModule` in the config for a SeparationModel. Args: module ([type]): [description]
Your custom modules can be registered with nussl's SeparationModel via this function. For example, if you have some module `ExampleModule`, you can register it as follows:
[ "Your", "custom", "modules", "can", "be", "registered", "with", "nussl", "s", "SeparationModel", "via", "this", "function", ".", "For", "example", "if", "you", "have", "some", "module", "ExampleModule", "you", "can", "register", "it", "as", "follows", ":" ]
def register_module(module): """ Your custom modules can be registered with nussl's SeparationModel via this function. For example, if you have some module `ExampleModule`, you can register it as follows: .. code-block:: python class ExampleModule(nn.Module): def forward(self, data): data = data * 2 return data ml.register_module(ExampleModule) You can now use the name `ExampleModule` in the config for a SeparationModel. Args: module ([type]): [description] """ setattr(modules, module.__name__, module)
[ "def", "register_module", "(", "module", ")", ":", "setattr", "(", "modules", ",", "module", ".", "__name__", ",", "module", ")" ]
https://github.com/nussl/nussl/blob/471e7965c5788bff9fe2e1f7884537cae2d18e6f/nussl/ml/__init__.py#L55-L75
ropnop/impacket_static_binaries
9b5dedf7c851db6867cbd7750e7103e51957d7c4
impacket/dot11.py
python
Dot11ControlFrameACK.set_ra
(self, value)
Set 802.11 ACK control frame 48 bit 'Receiver Address' field as a 6 bytes array
Set 802.11 ACK control frame 48 bit 'Receiver Address' field as a 6 bytes array
[ "Set", "802", ".", "11", "ACK", "control", "frame", "48", "bit", "Receiver", "Address", "field", "as", "a", "6", "bytes", "array" ]
def set_ra(self, value): "Set 802.11 ACK control frame 48 bit 'Receiver Address' field as a 6 bytes array" for i in range(0, 6): self.header.set_byte(2+i, value[i])
[ "def", "set_ra", "(", "self", ",", "value", ")", ":", "for", "i", "in", "range", "(", "0", ",", "6", ")", ":", "self", ".", "header", ".", "set_byte", "(", "2", "+", "i", ",", "value", "[", "i", "]", ")" ]
https://github.com/ropnop/impacket_static_binaries/blob/9b5dedf7c851db6867cbd7750e7103e51957d7c4/impacket/dot11.py#L581-L584
Project-Platypus/Platypus
a4e56410a772798e905407e99f80d03b86296ad3
platypus/core.py
python
AdaptiveGridArchive.adapt_grid
(self)
[]
def adapt_grid(self): self.minimum = [POSITIVE_INFINITY]*self.nobjs self.maximum = [-POSITIVE_INFINITY]*self.nobjs self.density = [0.0]*(self.divisions**self.nobjs) for solution in self: for i in range(self.nobjs): self.minimum[i] = min(self.minimum[i], solution.objectives[i]) self.maximum[i] = max(self.maximum[i], solution.objectives[i]) for solution in self: self.density[self.find_index(solution)] += 1
[ "def", "adapt_grid", "(", "self", ")", ":", "self", ".", "minimum", "=", "[", "POSITIVE_INFINITY", "]", "*", "self", ".", "nobjs", "self", ".", "maximum", "=", "[", "-", "POSITIVE_INFINITY", "]", "*", "self", ".", "nobjs", "self", ".", "density", "=", ...
https://github.com/Project-Platypus/Platypus/blob/a4e56410a772798e905407e99f80d03b86296ad3/platypus/core.py#L892-L903
Pylons/pyramid
0b24ac16cc04746b25cf460f1497c157f6d3d6f4
src/pyramid/i18n.py
python
negotiate_locale_name
(request)
return locale_name
Negotiate and return the :term:`locale name` associated with the current request.
Negotiate and return the :term:`locale name` associated with the current request.
[ "Negotiate", "and", "return", "the", ":", "term", ":", "locale", "name", "associated", "with", "the", "current", "request", "." ]
def negotiate_locale_name(request): """Negotiate and return the :term:`locale name` associated with the current request.""" try: registry = request.registry except AttributeError: registry = get_current_registry() negotiator = registry.queryUtility( ILocaleNegotiator, default=default_locale_negotiator ) locale_name = negotiator(request) if locale_name is None: settings = registry.settings or {} locale_name = settings.get('default_locale_name', 'en') return locale_name
[ "def", "negotiate_locale_name", "(", "request", ")", ":", "try", ":", "registry", "=", "request", ".", "registry", "except", "AttributeError", ":", "registry", "=", "get_current_registry", "(", ")", "negotiator", "=", "registry", ".", "queryUtility", "(", "ILoca...
https://github.com/Pylons/pyramid/blob/0b24ac16cc04746b25cf460f1497c157f6d3d6f4/src/pyramid/i18n.py#L141-L157
HuobiRDCenter/huobi_Python
c75a7fa8b31e99ffc1c173d74dcfcad83682e943
huobi/model/etf/etf_swap_in_out.py
python
EtfSwapInOut.__init__
(self)
[]
def __init__(self): self.code = 0 self.data = None self.message = "" self.success = False
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "code", "=", "0", "self", ".", "data", "=", "None", "self", ".", "message", "=", "\"\"", "self", ".", "success", "=", "False" ]
https://github.com/HuobiRDCenter/huobi_Python/blob/c75a7fa8b31e99ffc1c173d74dcfcad83682e943/huobi/model/etf/etf_swap_in_out.py#L8-L12
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/storage/memory_mixins/regioned_memory/regioned_memory_mixin.py
python
RegionedMemoryMixin.unset_stack_address_mapping
(self, absolute_address: int)
Remove a stack mapping. :param absolute_address: An absolute memory address that is the base address of the stack frame to destroy.
Remove a stack mapping.
[ "Remove", "a", "stack", "mapping", "." ]
def unset_stack_address_mapping(self, absolute_address: int): """ Remove a stack mapping. :param absolute_address: An absolute memory address that is the base address of the stack frame to destroy. """ if self._stack_region_map is None: raise SimMemoryError('Stack region map is not initialized.') self._stack_region_map.unmap_by_address(absolute_address)
[ "def", "unset_stack_address_mapping", "(", "self", ",", "absolute_address", ":", "int", ")", ":", "if", "self", ".", "_stack_region_map", "is", "None", ":", "raise", "SimMemoryError", "(", "'Stack region map is not initialized.'", ")", "self", ".", "_stack_region_map"...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/storage/memory_mixins/regioned_memory/regioned_memory_mixin.py#L195-L203
rgs1/zk_shell
ab4223c8f165a32b7f652932329b0880e43b9922
zk_shell/shell.py
python
Shell.do_reconfig
(self, params)
\x1b[1mNAME\x1b[0m reconfig - Reconfigures a ZooKeeper cluster (adds/removes members) \x1b[1mSYNOPSIS\x1b[0m reconfig <add|remove> <arg> [from_config] \x1b[1mDESCRIPTION\x1b[0m reconfig add <members> [from_config] adds the given members (i.e.: 'server.100=10.0.0.10:2889:3888:observer;0.0.0.0:2181'). reconfig remove <members_ids> [from_config] removes the members with the given ids (i.e.: '2,3,5'). \x1b[1mEXAMPLES\x1b[0m > reconfig add server.100=0.0.0.0:56954:37866:observer;0.0.0.0:42969 server.1=localhost:20002:20001:participant server.2=localhost:20012:20011:participant server.3=localhost:20022:20021:participant server.100=0.0.0.0:56954:37866:observer;0.0.0.0:42969 version=100000003 > reconfig remove 100 server.1=localhost:20002:20001:participant server.2=localhost:20012:20011:participant server.3=localhost:20022:20021:participant version=100000004
\x1b[1mNAME\x1b[0m reconfig - Reconfigures a ZooKeeper cluster (adds/removes members)
[ "\\", "x1b", "[", "1mNAME", "\\", "x1b", "[", "0m", "reconfig", "-", "Reconfigures", "a", "ZooKeeper", "cluster", "(", "adds", "/", "removes", "members", ")" ]
def do_reconfig(self, params): """ \x1b[1mNAME\x1b[0m reconfig - Reconfigures a ZooKeeper cluster (adds/removes members) \x1b[1mSYNOPSIS\x1b[0m reconfig <add|remove> <arg> [from_config] \x1b[1mDESCRIPTION\x1b[0m reconfig add <members> [from_config] adds the given members (i.e.: 'server.100=10.0.0.10:2889:3888:observer;0.0.0.0:2181'). reconfig remove <members_ids> [from_config] removes the members with the given ids (i.e.: '2,3,5'). \x1b[1mEXAMPLES\x1b[0m > reconfig add server.100=0.0.0.0:56954:37866:observer;0.0.0.0:42969 server.1=localhost:20002:20001:participant server.2=localhost:20012:20011:participant server.3=localhost:20022:20021:participant server.100=0.0.0.0:56954:37866:observer;0.0.0.0:42969 version=100000003 > reconfig remove 100 server.1=localhost:20002:20001:participant server.2=localhost:20012:20011:participant server.3=localhost:20022:20021:participant version=100000004 """ if params.cmd not in ["add", "remove"]: raise ValueError("Bad command: %s" % params.cmd) joining, leaving, from_config = None, None, params.from_config if params.cmd == "add": joining = params.args elif params.cmd == "remove": leaving = params.args try: value, _ = self._zk.reconfig( joining=joining, leaving=leaving, new_members=None, from_config=from_config) self.show_output(value) except NewConfigNoQuorumError: self.show_output("No quorum available to perform reconfig.") except ReconfigInProcessError: self.show_output("There's a reconfig in process.")
[ "def", "do_reconfig", "(", "self", ",", "params", ")", ":", "if", "params", ".", "cmd", "not", "in", "[", "\"add\"", ",", "\"remove\"", "]", ":", "raise", "ValueError", "(", "\"Bad command: %s\"", "%", "params", ".", "cmd", ")", "joining", ",", "leaving"...
https://github.com/rgs1/zk_shell/blob/ab4223c8f165a32b7f652932329b0880e43b9922/zk_shell/shell.py#L2914-L2964
VivekPa/OptimalPortfolio
cb27cbc6f0832bfc531c085454afe1ca457ea95e
build/lib/optimalportfolio/utility_functions.py
python
mean
(weights, mean)
return -weights.dot(mean)
Calculate the negative mean return of a portfolio :param weights: asset weights of the portfolio :type weights: np.ndarray :param expected_returns: expected return of each asset :type expected_returns: pd.Series :return: negative mean return :rtype: float
Calculate the negative mean return of a portfolio :param weights: asset weights of the portfolio :type weights: np.ndarray :param expected_returns: expected return of each asset :type expected_returns: pd.Series :return: negative mean return :rtype: float
[ "Calculate", "the", "negative", "mean", "return", "of", "a", "portfolio", ":", "param", "weights", ":", "asset", "weights", "of", "the", "portfolio", ":", "type", "weights", ":", "np", ".", "ndarray", ":", "param", "expected_returns", ":", "expected", "retur...
def mean(weights, mean): """ Calculate the negative mean return of a portfolio :param weights: asset weights of the portfolio :type weights: np.ndarray :param expected_returns: expected return of each asset :type expected_returns: pd.Series :return: negative mean return :rtype: float """ return -weights.dot(mean)
[ "def", "mean", "(", "weights", ",", "mean", ")", ":", "return", "-", "weights", ".", "dot", "(", "mean", ")" ]
https://github.com/VivekPa/OptimalPortfolio/blob/cb27cbc6f0832bfc531c085454afe1ca457ea95e/build/lib/optimalportfolio/utility_functions.py#L16-L26
django-nonrel/mongodb-engine
1314786975d3d17fb1a2e870dfba004158a5e431
django_mongodb_engine/fields.py
python
GridFSField._property_set
(self, model_instance, value)
Sets a new value. If value is an ObjectID it must be coming from Django's ORM internals being the value fetched from the database on query. In that case just update the id stored in the model instance. Otherwise it sets the value and checks whether a save is needed or not.
Sets a new value.
[ "Sets", "a", "new", "value", "." ]
def _property_set(self, model_instance, value): """ Sets a new value. If value is an ObjectID it must be coming from Django's ORM internals being the value fetched from the database on query. In that case just update the id stored in the model instance. Otherwise it sets the value and checks whether a save is needed or not. """ meta = self._get_meta(model_instance) if isinstance(value, ObjectId) and meta.oid is None: meta.oid = value else: meta.should_save = meta.filelike != value meta.filelike = value
[ "def", "_property_set", "(", "self", ",", "model_instance", ",", "value", ")", ":", "meta", "=", "self", ".", "_get_meta", "(", "model_instance", ")", "if", "isinstance", "(", "value", ",", "ObjectId", ")", "and", "meta", ".", "oid", "is", "None", ":", ...
https://github.com/django-nonrel/mongodb-engine/blob/1314786975d3d17fb1a2e870dfba004158a5e431/django_mongodb_engine/fields.py#L83-L98