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
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/bleach/_vendor/html5lib/_inputstream.py
python
HTMLUnicodeInputStream.openStream
(self, source)
return stream
Produces a file object from source. source can be either a file object, local filename or a string.
Produces a file object from source.
[ "Produces", "a", "file", "object", "from", "source", "." ]
def openStream(self, source): """Produces a file object from source. source can be either a file object, local filename or a string. """ # Already a file object if hasattr(source, 'read'): stream = source else: stream = StringIO(source) return stream
[ "def", "openStream", "(", "self", ",", "source", ")", ":", "# Already a file object", "if", "hasattr", "(", "source", ",", "'read'", ")", ":", "stream", "=", "source", "else", ":", "stream", "=", "StringIO", "(", "source", ")", "return", "stream" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/bleach/_vendor/html5lib/_inputstream.py#L204-L216
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/collections/__init__.py
python
Counter.__isub__
(self, other)
return self._keep_positive()
Inplace subtract counter, but keep only results with positive counts. >>> c = Counter('abbbc') >>> c -= Counter('bccd') >>> c Counter({'b': 2, 'a': 1})
Inplace subtract counter, but keep only results with positive counts.
[ "Inplace", "subtract", "counter", "but", "keep", "only", "results", "with", "positive", "counts", "." ]
def __isub__(self, other): '''Inplace subtract counter, but keep only results with positive counts. >>> c = Counter('abbbc') >>> c -= Counter('bccd') >>> c Counter({'b': 2, 'a': 1}) ''' for elem, count in other.items(): self[elem] -= count return self._keep_positive()
[ "def", "__isub__", "(", "self", ",", "other", ")", ":", "for", "elem", ",", "count", "in", "other", ".", "items", "(", ")", ":", "self", "[", "elem", "]", "-=", "count", "return", "self", ".", "_keep_positive", "(", ")" ]
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/collections/__init__.py#L800-L811
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/gdata/spreadsheet/service.py
python
SpreadsheetsService.ExecuteBatch
(self, batch_feed, url=None, spreadsheet_key=None, worksheet_id=None, converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString)
return self.Post(batch_feed, url, converter=converter)
Sends a batch request feed to the server. The batch request needs to be sent to the batch URL for a particular worksheet. You can specify the worksheet by providing the spreadsheet_key and worksheet_id, or by sending the URL from the cells feed's batch link. Args: batch_feed: gdata.spreadsheet.SpreadsheetsCellFeed A feed containing BatchEntry elements which contain the desired CRUD operation and any necessary data to modify a cell. url: str (optional) The batch URL for the cells feed to which these changes should be applied. This can be found by calling cells_feed.GetBatchLink().href. spreadsheet_key: str (optional) Used to generate the batch request URL if the url argument is None. If using the spreadsheet key to generate the URL, the worksheet id is also required. worksheet_id: str (optional) Used if the url is not provided, it is oart of the batch feed target URL. This is used with the spreadsheet key. converter: Function (optional) Function to be executed on the server's response. This function should take one string as a parameter. The default value is SpreadsheetsCellsFeedFromString which will turn the result into a gdata.spreadsheet.SpreadsheetsCellsFeed object. Returns: A gdata.BatchFeed containing the results.
Sends a batch request feed to the server.
[ "Sends", "a", "batch", "request", "feed", "to", "the", "server", "." ]
def ExecuteBatch(self, batch_feed, url=None, spreadsheet_key=None, worksheet_id=None, converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString): """Sends a batch request feed to the server. The batch request needs to be sent to the batch URL for a particular worksheet. You can specify the worksheet by providing the spreadsheet_key and worksheet_id, or by sending the URL from the cells feed's batch link. Args: batch_feed: gdata.spreadsheet.SpreadsheetsCellFeed A feed containing BatchEntry elements which contain the desired CRUD operation and any necessary data to modify a cell. url: str (optional) The batch URL for the cells feed to which these changes should be applied. This can be found by calling cells_feed.GetBatchLink().href. spreadsheet_key: str (optional) Used to generate the batch request URL if the url argument is None. If using the spreadsheet key to generate the URL, the worksheet id is also required. worksheet_id: str (optional) Used if the url is not provided, it is oart of the batch feed target URL. This is used with the spreadsheet key. converter: Function (optional) Function to be executed on the server's response. This function should take one string as a parameter. The default value is SpreadsheetsCellsFeedFromString which will turn the result into a gdata.spreadsheet.SpreadsheetsCellsFeed object. Returns: A gdata.BatchFeed containing the results. """ if url is None: url = self._GenerateCellsBatchUrl(spreadsheet_key, worksheet_id) return self.Post(batch_feed, url, converter=converter)
[ "def", "ExecuteBatch", "(", "self", ",", "batch_feed", ",", "url", "=", "None", ",", "spreadsheet_key", "=", "None", ",", "worksheet_id", "=", "None", ",", "converter", "=", "gdata", ".", "spreadsheet", ".", "SpreadsheetsCellsFeedFromString", ")", ":", "if", ...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/gdata/spreadsheet/service.py#L284-L317
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/zipfile.py
python
ZipFile.getinfo
(self, name)
return info
Return the instance of ZipInfo given 'name'.
Return the instance of ZipInfo given 'name'.
[ "Return", "the", "instance", "of", "ZipInfo", "given", "name", "." ]
def getinfo(self, name): """Return the instance of ZipInfo given 'name'.""" info = self.NameToInfo.get(name) if info is None: raise KeyError( 'There is no item named %r in the archive' % name) return info
[ "def", "getinfo", "(", "self", ",", "name", ")", ":", "info", "=", "self", ".", "NameToInfo", ".", "get", "(", "name", ")", "if", "info", "is", "None", ":", "raise", "KeyError", "(", "'There is no item named %r in the archive'", "%", "name", ")", "return",...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/zipfile.py#L904-L911
lisa-lab/pylearn2
af81e5c362f0df4df85c3e54e23b2adeec026055
pylearn2/models/dbm/layer.py
python
BVMP_Gaussian.beta_bias
(self)
return - 0.5 * T.dot(beta, T.sqr(W))
.. todo:: WRITEME
.. todo::
[ "..", "todo", "::" ]
def beta_bias(self): """ .. todo:: WRITEME """ W, = self.transformer.get_params() beta = self.input_layer.beta assert beta.ndim == 1 return - 0.5 * T.dot(beta, T.sqr(W))
[ "def", "beta_bias", "(", "self", ")", ":", "W", ",", "=", "self", ".", "transformer", ".", "get_params", "(", ")", "beta", "=", "self", ".", "input_layer", ".", "beta", "assert", "beta", ".", "ndim", "==", "1", "return", "-", "0.5", "*", "T", ".", ...
https://github.com/lisa-lab/pylearn2/blob/af81e5c362f0df4df85c3e54e23b2adeec026055/pylearn2/models/dbm/layer.py#L3774-L3783
bjmayor/hacker
e3ce2ad74839c2733b27dac6c0f495e0743e1866
venv/lib/python3.5/site-packages/pkg_resources/__init__.py
python
safe_extra
(extra)
return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower()
Convert an arbitrary string to a standard 'extra' name Any runs of non-alphanumeric characters are replaced with a single '_', and the result is always lowercased.
Convert an arbitrary string to a standard 'extra' name
[ "Convert", "an", "arbitrary", "string", "to", "a", "standard", "extra", "name" ]
def safe_extra(extra): """Convert an arbitrary string to a standard 'extra' name Any runs of non-alphanumeric characters are replaced with a single '_', and the result is always lowercased. """ return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower()
[ "def", "safe_extra", "(", "extra", ")", ":", "return", "re", ".", "sub", "(", "'[^A-Za-z0-9.-]+'", ",", "'_'", ",", "extra", ")", ".", "lower", "(", ")" ]
https://github.com/bjmayor/hacker/blob/e3ce2ad74839c2733b27dac6c0f495e0743e1866/venv/lib/python3.5/site-packages/pkg_resources/__init__.py#L1392-L1398
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/tkinter/tix.py
python
DisplayStyle.config
(self, cnf={}, **kw)
return _lst2dict( self.tk.split( self.tk.call( self.stylename, 'configure', *self._options(cnf,kw))))
[]
def config(self, cnf={}, **kw): return _lst2dict( self.tk.split( self.tk.call( self.stylename, 'configure', *self._options(cnf,kw))))
[ "def", "config", "(", "self", ",", "cnf", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "return", "_lst2dict", "(", "self", ".", "tk", ".", "split", "(", "self", ".", "tk", ".", "call", "(", "self", ".", "stylename", ",", "'configure'", ",", "*...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/tkinter/tix.py#L517-L521
MycroftAI/mycroft-core
3d963cee402e232174850f36918313e87313fb13
mycroft/skills/skill_updater.py
python
SkillUpdater.handle_not_connected
(self)
Notifications of the device not being connected to the internet
Notifications of the device not being connected to the internet
[ "Notifications", "of", "the", "device", "not", "being", "connected", "to", "the", "internet" ]
def handle_not_connected(self): """Notifications of the device not being connected to the internet""" LOG.error('msm failed, network connection not available') self.next_download = time() + FIVE_MINUTES
[ "def", "handle_not_connected", "(", "self", ")", ":", "LOG", ".", "error", "(", "'msm failed, network connection not available'", ")", "self", ".", "next_download", "=", "time", "(", ")", "+", "FIVE_MINUTES" ]
https://github.com/MycroftAI/mycroft-core/blob/3d963cee402e232174850f36918313e87313fb13/mycroft/skills/skill_updater.py#L174-L177
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/internet/process.py
python
PTYProcess.__init__
(self, reactor, executable, args, environment, path, proto, uid=None, gid=None, usePTY=None)
Spawn an operating-system process. This is where the hard work of disconnecting all currently open files / forking / executing the new process happens. (This is executed automatically when a Process is instantiated.) This will also run the subprocess as a given user ID and group ID, if specified. (Implementation Note: this doesn't support all the arcane nuances of setXXuid on UNIX: it will assume that either your effective or real UID is 0.)
Spawn an operating-system process.
[ "Spawn", "an", "operating", "-", "system", "process", "." ]
def __init__(self, reactor, executable, args, environment, path, proto, uid=None, gid=None, usePTY=None): """ Spawn an operating-system process. This is where the hard work of disconnecting all currently open files / forking / executing the new process happens. (This is executed automatically when a Process is instantiated.) This will also run the subprocess as a given user ID and group ID, if specified. (Implementation Note: this doesn't support all the arcane nuances of setXXuid on UNIX: it will assume that either your effective or real UID is 0.) """ if pty is None and not isinstance(usePTY, (tuple, list)): # no pty module and we didn't get a pty to use raise NotImplementedError( "cannot use PTYProcess on platforms without the pty module.") abstract.FileDescriptor.__init__(self, reactor) _BaseProcess.__init__(self, proto) if isinstance(usePTY, (tuple, list)): masterfd, slavefd, ttyname = usePTY else: masterfd, slavefd = pty.openpty() ttyname = os.ttyname(slavefd) try: self._fork(path, uid, gid, executable, args, environment, masterfd=masterfd, slavefd=slavefd) except: if not isinstance(usePTY, (tuple, list)): os.close(masterfd) os.close(slavefd) raise # we are now in parent process: os.close(slavefd) fdesc.setNonBlocking(masterfd) self.fd = masterfd self.startReading() self.connected = 1 self.status = -1 try: self.proto.makeConnection(self) except: log.err() registerReapProcessHandler(self.pid, self)
[ "def", "__init__", "(", "self", ",", "reactor", ",", "executable", ",", "args", ",", "environment", ",", "path", ",", "proto", ",", "uid", "=", "None", ",", "gid", "=", "None", ",", "usePTY", "=", "None", ")", ":", "if", "pty", "is", "None", "and",...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/internet/process.py#L929-L976
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/pygsm/scanwin32.py
python
comports
(available_only=True)
This generator scans the device registry for com ports and yields (order, port, desc, hwid). If available_only is true only return currently existing ports. Order is a helper to get sorted lists. it can be ignored otherwise.
This generator scans the device registry for com ports and yields (order, port, desc, hwid). If available_only is true only return currently existing ports. Order is a helper to get sorted lists. it can be ignored otherwise.
[ "This", "generator", "scans", "the", "device", "registry", "for", "com", "ports", "and", "yields", "(", "order", "port", "desc", "hwid", ")", ".", "If", "available_only", "is", "true", "only", "return", "currently", "existing", "ports", ".", "Order", "is", ...
def comports(available_only=True): """This generator scans the device registry for com ports and yields (order, port, desc, hwid). If available_only is true only return currently existing ports. Order is a helper to get sorted lists. it can be ignored otherwise.""" flags = DIGCF_DEVICEINTERFACE if available_only: flags |= DIGCF_PRESENT g_hdi = SetupDiGetClassDevs(ctypes.byref(GUID_CLASS_COMPORT), None, NULL, flags); #~ for i in range(256): for dwIndex in range(256): did = SP_DEVICE_INTERFACE_DATA() did.cbSize = ctypes.sizeof(did) if not SetupDiEnumDeviceInterfaces( g_hdi, None, ctypes.byref(GUID_CLASS_COMPORT), dwIndex, ctypes.byref(did) ): if ctypes.GetLastError() != ERROR_NO_MORE_ITEMS: raise ctypes.WinError() break dwNeeded = DWORD() # get the size if not SetupDiGetDeviceInterfaceDetail( g_hdi, ctypes.byref(did), None, 0, ctypes.byref(dwNeeded), None ): # Ignore ERROR_INSUFFICIENT_BUFFER if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER: raise ctypes.WinError() # allocate buffer class SP_DEVICE_INTERFACE_DETAIL_DATA_A(ctypes.Structure): _fields_ = [ ('cbSize', DWORD), ('DevicePath', CHAR*(dwNeeded.value - ctypes.sizeof(DWORD))), ] def __str__(self): return "DevicePath:%s" % (self.DevicePath,) idd = SP_DEVICE_INTERFACE_DETAIL_DATA_A() idd.cbSize = SIZEOF_SP_DEVICE_INTERFACE_DETAIL_DATA_A devinfo = SP_DEVINFO_DATA() devinfo.cbSize = ctypes.sizeof(devinfo) if not SetupDiGetDeviceInterfaceDetail( g_hdi, ctypes.byref(did), ctypes.byref(idd), dwNeeded, None, ctypes.byref(devinfo) ): raise ctypes.WinError() # hardware ID szHardwareID = ctypes.create_string_buffer(250) if not SetupDiGetDeviceRegistryProperty( g_hdi, ctypes.byref(devinfo), SPDRP_HARDWAREID, None, ctypes.byref(szHardwareID), ctypes.sizeof(szHardwareID) - 1, None ): # Ignore ERROR_INSUFFICIENT_BUFFER if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER: raise ctypes.WinError() # friendly name szFriendlyName = ctypes.create_string_buffer(1024) if not SetupDiGetDeviceRegistryProperty( g_hdi, ctypes.byref(devinfo), SPDRP_FRIENDLYNAME, None, ctypes.byref(szFriendlyName), ctypes.sizeof(szFriendlyName) - 1, None ): # Ignore ERROR_INSUFFICIENT_BUFFER if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER: #~ raise ctypes.WinError() # not getting friendly name for com0com devices, try something else szFriendlyName = ctypes.create_string_buffer(1024) if SetupDiGetDeviceRegistryProperty( g_hdi, ctypes.byref(devinfo), SPDRP_LOCATION_INFORMATION, None, ctypes.byref(szFriendlyName), ctypes.sizeof(szFriendlyName) - 1, None ): port_name = "\\\\.\\" + szFriendlyName.value order = None else: port_name = szFriendlyName.value order = None else: try: m = re.search(r"\((.*?(\d+))\)", szFriendlyName.value) #~ print szFriendlyName.value, m.groups() port_name = m.group(1) order = int(m.group(2)) except AttributeError, msg: port_name = szFriendlyName.value order = None yield order, port_name, szFriendlyName.value, szHardwareID.value SetupDiDestroyDeviceInfoList(g_hdi)
[ "def", "comports", "(", "available_only", "=", "True", ")", ":", "flags", "=", "DIGCF_DEVICEINTERFACE", "if", "available_only", ":", "flags", "|=", "DIGCF_PRESENT", "g_hdi", "=", "SetupDiGetClassDevs", "(", "ctypes", ".", "byref", "(", "GUID_CLASS_COMPORT", ")", ...
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/pygsm/scanwin32.py#L105-L214
web2py/web2py
095905c4e010a1426c729483d912e270a51b7ba8
gluon/contrib/fpdf/fpdf.py
python
FPDF.ellipse
(self, x,y,w,h,style='')
Draw a ellipse
Draw a ellipse
[ "Draw", "a", "ellipse" ]
def ellipse(self, x,y,w,h,style=''): "Draw a ellipse" if(style=='F'): op='f' elif(style=='FD' or style=='DF'): op='B' else: op='S' cx = x + w/2.0 cy = y + h/2.0 rx = w/2.0 ry = h/2.0 lx = 4.0/3.0*(math.sqrt(2)-1)*rx ly = 4.0/3.0*(math.sqrt(2)-1)*ry self._out(sprintf('%.2f %.2f m %.2f %.2f %.2f %.2f %.2f %.2f c', (cx+rx)*self.k, (self.h-cy)*self.k, (cx+rx)*self.k, (self.h-(cy-ly))*self.k, (cx+lx)*self.k, (self.h-(cy-ry))*self.k, cx*self.k, (self.h-(cy-ry))*self.k)) self._out(sprintf('%.2f %.2f %.2f %.2f %.2f %.2f c', (cx-lx)*self.k, (self.h-(cy-ry))*self.k, (cx-rx)*self.k, (self.h-(cy-ly))*self.k, (cx-rx)*self.k, (self.h-cy)*self.k)) self._out(sprintf('%.2f %.2f %.2f %.2f %.2f %.2f c', (cx-rx)*self.k, (self.h-(cy+ly))*self.k, (cx-lx)*self.k, (self.h-(cy+ry))*self.k, cx*self.k, (self.h-(cy+ry))*self.k)) self._out(sprintf('%.2f %.2f %.2f %.2f %.2f %.2f c %s', (cx+lx)*self.k, (self.h-(cy+ry))*self.k, (cx+rx)*self.k, (self.h-(cy+ly))*self.k, (cx+rx)*self.k, (self.h-cy)*self.k, op))
[ "def", "ellipse", "(", "self", ",", "x", ",", "y", ",", "w", ",", "h", ",", "style", "=", "''", ")", ":", "if", "(", "style", "==", "'F'", ")", ":", "op", "=", "'f'", "elif", "(", "style", "==", "'FD'", "or", "style", "==", "'DF'", ")", ":"...
https://github.com/web2py/web2py/blob/095905c4e010a1426c729483d912e270a51b7ba8/gluon/contrib/fpdf/fpdf.py#L439-L473
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_image.py
python
Utils.filter_versions
(stdout)
return version_dict
filter the oc version output
filter the oc version output
[ "filter", "the", "oc", "version", "output" ]
def filter_versions(stdout): ''' filter the oc version output ''' version_dict = {} version_search = ['oc', 'openshift', 'kubernetes'] for line in stdout.strip().split('\n'): for term in version_search: if not line: continue if line.startswith(term): version_dict[term] = line.split()[-1] # horrible hack to get openshift version in Openshift 3.2 # By default "oc version in 3.2 does not return an "openshift" version if "openshift" not in version_dict: version_dict["openshift"] = version_dict["oc"] return version_dict
[ "def", "filter_versions", "(", "stdout", ")", ":", "version_dict", "=", "{", "}", "version_search", "=", "[", "'oc'", ",", "'openshift'", ",", "'kubernetes'", "]", "for", "line", "in", "stdout", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_image.py#L1276-L1294
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/geometry/line.py
python
LinearEntity.p1
(self)
return self.args[0]
The first defining point of a linear entity. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(5, 3) >>> l = Line(p1, p2) >>> l.p1 Point2D(0, 0)
The first defining point of a linear entity.
[ "The", "first", "defining", "point", "of", "a", "linear", "entity", "." ]
def p1(self): """The first defining point of a linear entity. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(5, 3) >>> l = Line(p1, p2) >>> l.p1 Point2D(0, 0) """ return self.args[0]
[ "def", "p1", "(", "self", ")", ":", "return", "self", ".", "args", "[", "0", "]" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/geometry/line.py#L680-L698
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/ldap3/abstract/objectDef.py
python
ObjectDef.remove_attribute
(self, item)
Remove an AttrDef from the ObjectDef. Can be called with the -= operator. :param item: the AttrDef to remove, can also be a string containing the name of attribute to remove
Remove an AttrDef from the ObjectDef. Can be called with the -= operator. :param item: the AttrDef to remove, can also be a string containing the name of attribute to remove
[ "Remove", "an", "AttrDef", "from", "the", "ObjectDef", ".", "Can", "be", "called", "with", "the", "-", "=", "operator", ".", ":", "param", "item", ":", "the", "AttrDef", "to", "remove", "can", "also", "be", "a", "string", "containing", "the", "name", "...
def remove_attribute(self, item): """Remove an AttrDef from the ObjectDef. Can be called with the -= operator. :param item: the AttrDef to remove, can also be a string containing the name of attribute to remove """ key = None if isinstance(item, STRING_TYPES): key = ''.join(item.split()).lower() elif isinstance(item, AttrDef): key = item.key.lower() if key: for attr in self._attributes: if key == attr.lower(): del self._attributes[attr] break else: error_message = 'key \'%s\' not present' % key if log_enabled(ERROR): log(ERROR, '%s for <%s>', error_message, self) raise LDAPKeyError(error_message) else: error_message = 'key type must be str or AttrDef not ' + str(type(item)) if log_enabled(ERROR): log(ERROR, '%s for <%s>', error_message, self) raise LDAPAttributeError(error_message)
[ "def", "remove_attribute", "(", "self", ",", "item", ")", ":", "key", "=", "None", "if", "isinstance", "(", "item", ",", "STRING_TYPES", ")", ":", "key", "=", "''", ".", "join", "(", "item", ".", "split", "(", ")", ")", ".", "lower", "(", ")", "e...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/ldap3/abstract/objectDef.py#L237-L262
bungnoid/glTools
8ff0899de43784a18bd4543285655e68e28fb5e5
tools/meshCache.py
python
writeGeoCombineCache
(path,name,meshList,startFrame,endFrame,pad=4,uvSet='',worldSpace=True,gz=False)
Write a .geo cache per frame for the specified list of mesh objects. All meshes in the list will be combined to a single cache, and an 'id' vertex attribute will be added to identify the individual objects. @param path: Destination directory path for the cache files. @type path: str @param name: Cache file output name. @type name: str @param meshList: List of mesh objects to write cache for. @type meshList: list @param startFrame: Cache start frame @type startFrame: float @param endFrame: Cache end frame @type endFrame: float @param pad: Frame number padding for file name. @type pad: str @param uvSet: UVSet to export with cache @type uvSet: str @param worldSpace: Export mesh in world space instead of local or object space. @type worldSpace: bool @param gz: Gzip the cache files @type gz: bool
Write a .geo cache per frame for the specified list of mesh objects. All meshes in the list will be combined to a single cache, and an 'id' vertex attribute will be added to identify the individual objects.
[ "Write", "a", ".", "geo", "cache", "per", "frame", "for", "the", "specified", "list", "of", "mesh", "objects", ".", "All", "meshes", "in", "the", "list", "will", "be", "combined", "to", "a", "single", "cache", "and", "an", "id", "vertex", "attribute", ...
def writeGeoCombineCache(path,name,meshList,startFrame,endFrame,pad=4,uvSet='',worldSpace=True,gz=False): ''' Write a .geo cache per frame for the specified list of mesh objects. All meshes in the list will be combined to a single cache, and an 'id' vertex attribute will be added to identify the individual objects. @param path: Destination directory path for the cache files. @type path: str @param name: Cache file output name. @type name: str @param meshList: List of mesh objects to write cache for. @type meshList: list @param startFrame: Cache start frame @type startFrame: float @param endFrame: Cache end frame @type endFrame: float @param pad: Frame number padding for file name. @type pad: str @param uvSet: UVSet to export with cache @type uvSet: str @param worldSpace: Export mesh in world space instead of local or object space. @type worldSpace: bool @param gz: Gzip the cache files @type gz: bool ''' # Check path if not os.path.isdir(path): os.makedirs(path) # Check mesh list fullMeshList = meshList for mesh in meshList: if not mc.objExists(mesh): raise Exception('Mesh "'+mesh+'" does not exist!') if not glTools.utils.mesh.isMesh(mesh): raise Exception('Object "'+mesh+'" is not a valid mesh!') # Check UVs uv = False if uvSet: for mesh in meshList: if mc.polyUVSet(mesh,q=True,auv=True).count(uvSet): uv = True else: print('UVSet "'+uvSet+'" does not exist for mesh "'+mesh+'"!') # Determine Sample Space if worldSpace: sampleSpace = OpenMaya.MSpace.kWorld else: sampleSpace = OpenMaya.MSpace.kObject # Write mesh cache for f in range(startFrame,endFrame+1): # Update frame mc.currentTime(f) # Check mesh visibility meshList = [mesh for mesh in fullMeshList if mc.getAttr(mesh+'.v')] if not meshList: continue # ------------------------- # - Open file for writing - # ------------------------- fPad = glTools.utils.stringUtils.stringIndex(f,pad) if gz: filename = path+'/'+name+'.'+fPad+'.geo.gz' print 'Writing '+filename FILE = gzip.open(filename,"wb") else: filename = path+'/'+name+'.'+fPad+'.geo' print 'Writing '+filename FILE = open(filename,"w") # Write cache file header FILE.write('PGEOMETRY V5\n') # Determine the total number of vertices numVertList = [] numFaceList = [] totalNumVerts = 0 totalNumFaces = 0 # For each mesh for mesh in meshList: # Get mesh data numVerts = mc.polyEvaluate(mesh,v=True) numFaces = mc.polyEvaluate(mesh,f=True) totalNumVerts += numVerts totalNumFaces += numFaces numVertList.append(numVerts) numFaceList.append(numFaces) # Write total number pf points/primitives FILE.write('NPoints '+str(totalNumVerts)+' NPrims '+str(totalNumFaces)+'\n') # Write Point/Prim Group info FILE.write('NPointGroups 0 NPrimGroups 0\n') # Write Point/Vert/Prim/Detail Attribute info if uv: numVtxAttr = 1 else: numVtxAttr = 0 FILE.write('NPointAttrib 2 NVertexAttrib '+str(numVtxAttr)+' NPrimAttrib 0 NAttrib 0\n') # ------------------------- # - Write Point Attr Info - # ------------------------- FILE.write('PointAttrib\n') FILE.write('N 3 vector 0 0 0\n') FILE.write('id 1 int 0\n') # Write raw point data for m in range(len(meshList)): # Get vertex and normal arrays vtxArray = OpenMaya.MPointArray() normArray = OpenMaya.MFloatVectorArray() meshFn = glTools.utils.mesh.getMeshFn(meshList[m]) meshFn.getPoints(vtxArray,sampleSpace) meshFn.getVertexNormals(False,normArray,sampleSpace) # Write vertex array for i in range(vtxArray.length()): FILE.write(str(vtxArray[i].x)+' '+str(vtxArray[i].y)+' '+str(vtxArray[i].z)+' '+str(vtxArray[i].w)+' ('+str(normArray[i].x)+' '+str(normArray[i].y)+' '+str(normArray[i].z)+' '+str(m)+')\n') # ------------------- # - Write Face Data - # ------------------- if uv: FILE.write('VertexAttrib\n') FILE.write('uv 3 float 0 0 0\n') FILE.write('Run '+str(totalNumFaces)+' Poly\n') # Track per mesh vertex id offsets vertexOffset = 0 # Face vertex id array faceVtxArray = OpenMaya.MIntArray() faceUArray = OpenMaya.MFloatArray() faceVArray = OpenMaya.MFloatArray() # Iterate over meshes for m in range(len(meshList)): # Get mesh face iterator faceIter = glTools.utils.mesh.getMeshFaceIter(meshList[m]) # Iterate over mesh faces faceIter.reset() while not faceIter.isDone(): # Get face vertices faceIter.getVertices(faceVtxArray) vtxArray = list(faceVtxArray) #vtxArray.reverse() # Get face UVs if uv: faceIter.getUVs(faceUArray,faceVArray,uvSet) uArray = list(faceUArray) vArray = list(faceVArray) uArray.reverse() vArray.reverse() # Build face data string faceData = ' '+str(len(vtxArray))+' <' for i in range(len(vtxArray)): faceData += ' '+str(vtxArray[i]+vertexOffset) if uv: faceData += ' ( '+str(faceUArray[i])+' '+str(faceVArray[i])+' 0.0 )' faceData += '\n' # Write face data FILE.write(faceData) # Iterate to next face faceIter.next() # Update vertex offset vertexOffset += numVertList[m] # ----------------------- # - Finalize cache file - # ----------------------- FILE.write('beginExtra\n') FILE.write('endExtra\n') # Close File FILE.close() # Print result print 'Write cache completed!'
[ "def", "writeGeoCombineCache", "(", "path", ",", "name", ",", "meshList", ",", "startFrame", ",", "endFrame", ",", "pad", "=", "4", ",", "uvSet", "=", "''", ",", "worldSpace", "=", "True", ",", "gz", "=", "False", ")", ":", "# Check path", "if", "not",...
https://github.com/bungnoid/glTools/blob/8ff0899de43784a18bd4543285655e68e28fb5e5/tools/meshCache.py#L170-L359
matplotlib/matplotlib
8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322
lib/matplotlib/font_manager.py
python
FontManager.get_default_weight
(self)
return self.__default_weight
Return the default font weight.
Return the default font weight.
[ "Return", "the", "default", "font", "weight", "." ]
def get_default_weight(self): """ Return the default font weight. """ return self.__default_weight
[ "def", "get_default_weight", "(", "self", ")", ":", "return", "self", ".", "__default_weight" ]
https://github.com/matplotlib/matplotlib/blob/8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322/lib/matplotlib/font_manager.py#L1126-L1130
baidu-security/openrasp-iast
d4a5643420853a95614d371cf38d5c65ccf9cfd4
openrasp_iast/core/components/config.py
python
Config.get_running_info
(self)
return pid, running_config_path
获取运行的主进程pid和配置文件路径 Returns: pid, running_config_path - int, str pid获取失败返回0, config_path获取失败返回空
获取运行的主进程pid和配置文件路径
[ "获取运行的主进程pid和配置文件路径" ]
def get_running_info(self): """ 获取运行的主进程pid和配置文件路径 Returns: pid, running_config_path - int, str pid获取失败返回0, config_path获取失败返回空 """ try: with open(self._tmp_path + "/iast.pid", "r") as f: pid = int(f.read()) except FileNotFoundError: pid = 0 try: with open(self._tmp_path + "/iast.config", "r") as f: running_config_path = f.read() except FileNotFoundError: running_config_path = "" return pid, running_config_path
[ "def", "get_running_info", "(", "self", ")", ":", "try", ":", "with", "open", "(", "self", ".", "_tmp_path", "+", "\"/iast.pid\"", ",", "\"r\"", ")", "as", "f", ":", "pid", "=", "int", "(", "f", ".", "read", "(", ")", ")", "except", "FileNotFoundErro...
https://github.com/baidu-security/openrasp-iast/blob/d4a5643420853a95614d371cf38d5c65ccf9cfd4/openrasp_iast/core/components/config.py#L209-L228
jessemiller/HamlPy
acb79e14381ce46e6d1cb64e7cb154751ae02dfe
hamlpy/hamlpy_watcher.py
python
watch_folder
()
Main entry point. Expects one or two arguments (the watch folder + optional destination folder).
Main entry point. Expects one or two arguments (the watch folder + optional destination folder).
[ "Main", "entry", "point", ".", "Expects", "one", "or", "two", "arguments", "(", "the", "watch", "folder", "+", "optional", "destination", "folder", ")", "." ]
def watch_folder(): """Main entry point. Expects one or two arguments (the watch folder + optional destination folder).""" argv = sys.argv[1:] if len(sys.argv) > 1 else [] args = arg_parser.parse_args(sys.argv[1:]) compiler_args = {} input_folder = os.path.realpath(args.input_dir) if not args.output_dir: output_folder = input_folder else: output_folder = os.path.realpath(args.output_dir) if args.verbose: Options.VERBOSE = True print "Watching {} at refresh interval {} seconds".format(input_folder, args.refresh) if args.extension: Options.OUTPUT_EXT = args.extension if getattr(args, 'tags', False): hamlpynodes.TagNode.self_closing.update(args.tags) if args.input_extension: hamlpy.VALID_EXTENSIONS += args.input_extension if args.attr_wrapper: compiler_args['attr_wrapper'] = args.attr_wrapper if args.jinja: for k in ('ifchanged', 'ifequal', 'ifnotequal', 'autoescape', 'blocktrans', 'spaceless', 'comment', 'cache', 'localize', 'compress'): del hamlpynodes.TagNode.self_closing[k] hamlpynodes.TagNode.may_contain.pop(k, None) hamlpynodes.TagNode.self_closing.update({ 'macro' : 'endmacro', 'call' : 'endcall', 'raw' : 'endraw' }) hamlpynodes.TagNode.may_contain['for'] = 'else' while True: try: _watch_folder(input_folder, output_folder, compiler_args) time.sleep(args.refresh) except KeyboardInterrupt: # allow graceful exit (no stacktrace output) sys.exit(0)
[ "def", "watch_folder", "(", ")", ":", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", "if", "len", "(", "sys", ".", "argv", ")", ">", "1", "else", "[", "]", "args", "=", "arg_parser", ".", "parse_args", "(", "sys", ".", "argv", "[", "1", ...
https://github.com/jessemiller/HamlPy/blob/acb79e14381ce46e6d1cb64e7cb154751ae02dfe/hamlpy/hamlpy_watcher.py#L59-L108
peering-manager/peering-manager
62c870fb9caa6dfc056feb77c595d45bc3c4988a
utils/tables.py
python
TagColumn.__init__
(self, url_name=None)
[]
def __init__(self, url_name=None): super().__init__( template_code=self.template_code, extra_context={"url_name": url_name} )
[ "def", "__init__", "(", "self", ",", "url_name", "=", "None", ")", ":", "super", "(", ")", ".", "__init__", "(", "template_code", "=", "self", ".", "template_code", ",", "extra_context", "=", "{", "\"url_name\"", ":", "url_name", "}", ")" ]
https://github.com/peering-manager/peering-manager/blob/62c870fb9caa6dfc056feb77c595d45bc3c4988a/utils/tables.py#L310-L313
lixinsu/RCZoo
37fcb7962fbd4c751c561d4a0c84173881ea8339
reader/rnet/data.py
python
Dictionary.__getitem__
(self, key)
[]
def __getitem__(self, key): if type(key) == int: return self.ind2tok.get(key, self.UNK) if type(key) == str: return self.tok2ind.get(self.normalize(key), self.tok2ind.get(self.UNK))
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "if", "type", "(", "key", ")", "==", "int", ":", "return", "self", ".", "ind2tok", ".", "get", "(", "key", ",", "self", ".", "UNK", ")", "if", "type", "(", "key", ")", "==", "str", ":", ...
https://github.com/lixinsu/RCZoo/blob/37fcb7962fbd4c751c561d4a0c84173881ea8339/reader/rnet/data.py#L50-L55
conan-io/conan
28ec09f6cbf1d7e27ec27393fd7bbc74891e74a8
conans/util/config_parser.py
python
get_bool_from_text_value
(value)
return (value == "1" or value.lower() == "yes" or value.lower() == "y" or value.lower() == "true") if value else True
to be deprecated It has issues, as accepting into the registry whatever=value, as False, without complaining
to be deprecated It has issues, as accepting into the registry whatever=value, as False, without complaining
[ "to", "be", "deprecated", "It", "has", "issues", "as", "accepting", "into", "the", "registry", "whatever", "=", "value", "as", "False", "without", "complaining" ]
def get_bool_from_text_value(value): """ to be deprecated It has issues, as accepting into the registry whatever=value, as False, without complaining """ return (value == "1" or value.lower() == "yes" or value.lower() == "y" or value.lower() == "true") if value else True
[ "def", "get_bool_from_text_value", "(", "value", ")", ":", "return", "(", "value", "==", "\"1\"", "or", "value", ".", "lower", "(", ")", "==", "\"yes\"", "or", "value", ".", "lower", "(", ")", "==", "\"y\"", "or", "value", ".", "lower", "(", ")", "==...
https://github.com/conan-io/conan/blob/28ec09f6cbf1d7e27ec27393fd7bbc74891e74a8/conans/util/config_parser.py#L6-L12
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/scipy/interpolate/polyint.py
python
BarycentricInterpolator.add_xi
(self, xi, yi=None)
Add more x values to the set to be interpolated The barycentric interpolation algorithm allows easy updating by adding more points for the polynomial to pass through. Parameters ---------- xi : array_like The x coordinates of the points that the polynomial should pass through. yi : array_like, optional The y coordinates of the points the polynomial should pass through. Should have shape ``(xi.size, R)``; if R > 1 then the polynomial is vector-valued. If `yi` is not given, the y values will be supplied later. `yi` should be given if and only if the interpolator has y values specified.
Add more x values to the set to be interpolated
[ "Add", "more", "x", "values", "to", "the", "set", "to", "be", "interpolated" ]
def add_xi(self, xi, yi=None): """ Add more x values to the set to be interpolated The barycentric interpolation algorithm allows easy updating by adding more points for the polynomial to pass through. Parameters ---------- xi : array_like The x coordinates of the points that the polynomial should pass through. yi : array_like, optional The y coordinates of the points the polynomial should pass through. Should have shape ``(xi.size, R)``; if R > 1 then the polynomial is vector-valued. If `yi` is not given, the y values will be supplied later. `yi` should be given if and only if the interpolator has y values specified. """ if yi is not None: if self.yi is None: raise ValueError("No previous yi value to update!") yi = self._reshape_yi(yi, check=True) self.yi = np.vstack((self.yi,yi)) else: if self.yi is not None: raise ValueError("No update to yi provided!") old_n = self.n self.xi = np.concatenate((self.xi,xi)) self.n = len(self.xi) self.wi **= -1 old_wi = self.wi self.wi = np.zeros(self.n) self.wi[:old_n] = old_wi for j in xrange(old_n,self.n): self.wi[:j] *= (self.xi[j]-self.xi[:j]) self.wi[j] = np.multiply.reduce(self.xi[:j]-self.xi[j]) self.wi **= -1
[ "def", "add_xi", "(", "self", ",", "xi", ",", "yi", "=", "None", ")", ":", "if", "yi", "is", "not", "None", ":", "if", "self", ".", "yi", "is", "None", ":", "raise", "ValueError", "(", "\"No previous yi value to update!\"", ")", "yi", "=", "self", "....
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/scipy/interpolate/polyint.py#L539-L577
PySimpleGUI/PySimpleGUI
6c0d1fb54f493d45e90180b322fbbe70f7a5af3c
DemoPrograms/Demo_Uno_Card_Game.py
python
Match.getPlayer
(self, playerID)
return self.players[playerID]
[]
def getPlayer(self, playerID): return self.players[playerID]
[ "def", "getPlayer", "(", "self", ",", "playerID", ")", ":", "return", "self", ".", "players", "[", "playerID", "]" ]
https://github.com/PySimpleGUI/PySimpleGUI/blob/6c0d1fb54f493d45e90180b322fbbe70f7a5af3c/DemoPrograms/Demo_Uno_Card_Game.py#L2912-L2913
suurjaak/Skyperious
6a4f264dbac8d326c2fa8aeb5483dbca987860bf
skyperious/export.py
python
export_chat_template
(chat, filename, db, messages, opts=None)
return count, message_count
Exports the chat messages to file using templates. @param chat chat data dict, as returned from SkypeDatabase @param filename full path and filename of resulting file, file extension .html|.txt determines file format @param db SkypeDatabase instance @param messages list of message data dicts @param opts export options dictionary, as {"media_folder": true} if saving images to subfolder in HTML export @return (number of chats exported, number of messages exported)
Exports the chat messages to file using templates.
[ "Exports", "the", "chat", "messages", "to", "file", "using", "templates", "." ]
def export_chat_template(chat, filename, db, messages, opts=None): """ Exports the chat messages to file using templates. @param chat chat data dict, as returned from SkypeDatabase @param filename full path and filename of resulting file, file extension .html|.txt determines file format @param db SkypeDatabase instance @param messages list of message data dicts @param opts export options dictionary, as {"media_folder": true} if saving images to subfolder in HTML export @return (number of chats exported, number of messages exported) """ count, message_count, opts = 0, 0, opts or {} tmpfile, tmpname = None, None # Temporary file for exported messages try: is_html = filename.lower().endswith(".html") parser = skypedata.MessageParser(db, chat=chat, stats=True) namespace = {"db": db, "chat": chat, "messages": messages, "parser": parser} if opts.get("media_folder"): filedir, basename = os.path.split(filename) basename = os.path.splitext(basename)[0] mediadir = os.path.join(filedir, "%s_files" % basename) namespace["media_folder"] = mediadir # As HTML and TXT contain statistics in their headers before # messages, write out all messages to a temporary file first, # statistics will be available for the main file after parsing. # Cannot keep all messages in memory at once - very large chats # (500,000+ messages) can take gigabytes. tmpname = util.unique_path("%s.messages" % filename) tmpfile = open(tmpname, "w+") template = step.Template(templates.CHAT_MESSAGES_HTML if is_html else templates.CHAT_MESSAGES_TXT, strip=False, escape=is_html) template.stream(tmpfile, namespace) namespace["stats"] = stats = parser.get_collected_stats() namespace.update({ "date1": stats["startdate"].strftime("%d.%m.%Y") if stats.get("startdate") else "", "date2": stats["enddate"].strftime("%d.%m.%Y") if stats.get("enddate") else "", "emoticons_used": [x for x in stats["emoticons"] if hasattr(emoticons, x)], "message_count": stats.get("total", 0), }) if is_html: # Collect chat and participant images. namespace.update({"participants": [], "chat_picture_size": None, "chat_picture_raw": None, }) pic = chat["meta_picture"] or chat.get("__link", {}).get("meta_picture") if pic: raw = skypedata.fix_image_raw(pic) namespace["chat_picture_raw"] = raw namespace["chat_picture_size"] = util.img_size(raw) contacts = dict((c["skypename"], c) for c in db.get_contacts()) partics = dict((p["identity"], p) for p in chat["participants"]) # There can be authors not among participants, and vice versa for author in stats["authors"].union(partics): contact = partics.get(author, {}).get("contact") contact = contact or contacts.get(author, {}) contact = contact or {"identity": author, "name": author} bmp = contact.get("avatar_bitmap") raw = contact.get("avatar_raw_small") or "" raw_large = contact.get("avatar_raw_large") or "" if not raw and not bmp: raw = skypedata.get_avatar_raw(contact, conf.AvatarImageSize) raw = bmp and util.img_wx_to_raw(bmp) or raw if raw: raw_large = raw_large or skypedata.get_avatar_raw( contact, conf.AvatarImageLargeSize) contact["avatar_raw_small"] = raw contact["avatar_raw_large"] = raw_large contact["rank"] = partics.get(author, {}).get("rank") namespace["participants"].append(contact) timeline, units = parser.get_timeline_stats() namespace["timeline"], namespace["timeline_units"] = timeline, units tmpfile.flush(), tmpfile.seek(0) namespace["message_buffer"] = iter(lambda: tmpfile.read(65536), "") with util.create_file(filename, handle=True) as f: t = templates.CHAT_HTML if is_html else templates.CHAT_TXT step.Template(t, strip=False, escape=is_html).stream(f, namespace) count = bool(namespace["message_count"]) message_count = namespace["message_count"] finally: if tmpfile: util.try_ignore(tmpfile.close) if tmpname: util.try_ignore(os.unlink, tmpname) return count, message_count
[ "def", "export_chat_template", "(", "chat", ",", "filename", ",", "db", ",", "messages", ",", "opts", "=", "None", ")", ":", "count", ",", "message_count", ",", "opts", "=", "0", ",", "0", ",", "opts", "or", "{", "}", "tmpfile", ",", "tmpname", "=", ...
https://github.com/suurjaak/Skyperious/blob/6a4f264dbac8d326c2fa8aeb5483dbca987860bf/skyperious/export.py#L226-L319
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-build/python-libs/gdata/samples/oauth/oauth_on_appengine/appengine_utilities/sessions.py
python
Session._get
(self, keyname=None)
return self.session.get_items()
Return all of the SessionData object data from the datastore onlye, unless keyname is specified, in which case only that instance of SessionData is returned. Important: This does not interact with memcache and pulls directly from the datastore. This also does not get items from the cookie store. Args: keyname: The keyname of the value you are trying to retrieve.
Return all of the SessionData object data from the datastore onlye, unless keyname is specified, in which case only that instance of SessionData is returned. Important: This does not interact with memcache and pulls directly from the datastore. This also does not get items from the cookie store.
[ "Return", "all", "of", "the", "SessionData", "object", "data", "from", "the", "datastore", "onlye", "unless", "keyname", "is", "specified", "in", "which", "case", "only", "that", "instance", "of", "SessionData", "is", "returned", ".", "Important", ":", "This",...
def _get(self, keyname=None): """ Return all of the SessionData object data from the datastore onlye, unless keyname is specified, in which case only that instance of SessionData is returned. Important: This does not interact with memcache and pulls directly from the datastore. This also does not get items from the cookie store. Args: keyname: The keyname of the value you are trying to retrieve. """ if keyname != None: return self.session.get_item(keyname) return self.session.get_items() """ OLD query = _AppEngineUtilities_SessionData.all() query.filter('session', self.session) if keyname != None: query.filter('keyname =', keyname) results = query.fetch(1000) if len(results) is 0: return None if keyname != None: return results[0] return results """
[ "def", "_get", "(", "self", ",", "keyname", "=", "None", ")", ":", "if", "keyname", "!=", "None", ":", "return", "self", ".", "session", ".", "get_item", "(", "keyname", ")", "return", "self", ".", "session", ".", "get_items", "(", ")", "\"\"\"\n ...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/gdata/samples/oauth/oauth_on_appengine/appengine_utilities/sessions.py#L551-L579
LeslieZhoa/tensorflow-MTCNN
b3e13ecee9a42534721370d9e6cd80db632aff7e
preprocess/BBox_utils.py
python
BBox.reprojectLandmark
(self,landmark)
return p
对所有关键点进行reproject操作
对所有关键点进行reproject操作
[ "对所有关键点进行reproject操作" ]
def reprojectLandmark(self,landmark): '''对所有关键点进行reproject操作''' p=np.zeros((len(landmark),2)) for i in range(len(landmark)): p[i]=self.reproject(landmark[i]) return p
[ "def", "reprojectLandmark", "(", "self", ",", "landmark", ")", ":", "p", "=", "np", ".", "zeros", "(", "(", "len", "(", "landmark", ")", ",", "2", ")", ")", "for", "i", "in", "range", "(", "len", "(", "landmark", ")", ")", ":", "p", "[", "i", ...
https://github.com/LeslieZhoa/tensorflow-MTCNN/blob/b3e13ecee9a42534721370d9e6cd80db632aff7e/preprocess/BBox_utils.py#L86-L91
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/packaging/markers.py
python
_get_env
(environment, name)
return value
[]
def _get_env(environment, name): value = environment.get(name, _undefined) if value is _undefined: raise UndefinedEnvironmentName( "{0!r} does not exist in evaluation environment.".format(name) ) return value
[ "def", "_get_env", "(", "environment", ",", "name", ")", ":", "value", "=", "environment", ".", "get", "(", "name", ",", "_undefined", ")", "if", "value", "is", "_undefined", ":", "raise", "UndefinedEnvironmentName", "(", "\"{0!r} does not exist in evaluation envi...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/packaging/markers.py#L205-L213
getsentry/sentry
83b1f25aac3e08075e0e2495bc29efaf35aca18a
src/sentry/integrations/custom_scm/integration.py
python
CustomSCMIntegration.get_stacktrace_link
( self, repo: Repository, filepath: str, default: str, version: str )
return self.format_source_url(repo, filepath, default)
We don't have access to verify that the file does exists (using `check_file`) so instead we just return the formatted source url using the default branch provided.
We don't have access to verify that the file does exists (using `check_file`) so instead we just return the formatted source url using the default branch provided.
[ "We", "don", "t", "have", "access", "to", "verify", "that", "the", "file", "does", "exists", "(", "using", "check_file", ")", "so", "instead", "we", "just", "return", "the", "formatted", "source", "url", "using", "the", "default", "branch", "provided", "."...
def get_stacktrace_link( self, repo: Repository, filepath: str, default: str, version: str ) -> str | None: """ We don't have access to verify that the file does exists (using `check_file`) so instead we just return the formatted source url using the default branch provided. """ return self.format_source_url(repo, filepath, default)
[ "def", "get_stacktrace_link", "(", "self", ",", "repo", ":", "Repository", ",", "filepath", ":", "str", ",", "default", ":", "str", ",", "version", ":", "str", ")", "->", "str", "|", "None", ":", "return", "self", ".", "format_source_url", "(", "repo", ...
https://github.com/getsentry/sentry/blob/83b1f25aac3e08075e0e2495bc29efaf35aca18a/src/sentry/integrations/custom_scm/integration.py#L59-L67
scikit-learn/scikit-learn
1d1aadd0711b87d2a11c80aad15df6f8cf156712
sklearn/utils/__init__.py
python
_list_indexing
(X, key, key_dtype)
return [X[idx] for idx in key]
Index a Python list.
Index a Python list.
[ "Index", "a", "Python", "list", "." ]
def _list_indexing(X, key, key_dtype): """Index a Python list.""" if np.isscalar(key) or isinstance(key, slice): # key is a slice or a scalar return X[key] if key_dtype == "bool": # key is a boolean array-like return list(compress(X, key)) # key is a integer array-like of key return [X[idx] for idx in key]
[ "def", "_list_indexing", "(", "X", ",", "key", ",", "key_dtype", ")", ":", "if", "np", ".", "isscalar", "(", "key", ")", "or", "isinstance", "(", "key", ",", "slice", ")", ":", "# key is a slice or a scalar", "return", "X", "[", "key", "]", "if", "key_...
https://github.com/scikit-learn/scikit-learn/blob/1d1aadd0711b87d2a11c80aad15df6f8cf156712/sklearn/utils/__init__.py#L178-L187
hatching/vmcloak
2dcb008d4b66f106b54070901bc6ac26d42be3da
vmcloak/abstract.py
python
OperatingSystem.set_serial_key
(self, serial_key)
Abstract method for checking a serial key if provided and otherwise use a default serial key if available.
Abstract method for checking a serial key if provided and otherwise use a default serial key if available.
[ "Abstract", "method", "for", "checking", "a", "serial", "key", "if", "provided", "and", "otherwise", "use", "a", "default", "serial", "key", "if", "available", "." ]
def set_serial_key(self, serial_key): """Abstract method for checking a serial key if provided and otherwise use a default serial key if available."""
[ "def", "set_serial_key", "(", "self", ",", "serial_key", ")", ":" ]
https://github.com/hatching/vmcloak/blob/2dcb008d4b66f106b54070901bc6ac26d42be3da/vmcloak/abstract.py#L107-L109
lohriialo/photoshop-scripting-python
6b97da967a5d0a45e54f7c99631b29773b923f09
api_reference/photoshop_CC_2018.py
python
_ActionDescriptor.__iter__
(self)
return win32com.client.util.Iterator(ob, None)
Return a Python iterator for this object
Return a Python iterator for this object
[ "Return", "a", "Python", "iterator", "for", "this", "object" ]
def __iter__(self): "Return a Python iterator for this object" try: ob = self._oleobj_.InvokeTypes(-4,LCID,3,(13, 10),()) except pythoncom.error: raise TypeError("This object does not support enumeration") return win32com.client.util.Iterator(ob, None)
[ "def", "__iter__", "(", "self", ")", ":", "try", ":", "ob", "=", "self", ".", "_oleobj_", ".", "InvokeTypes", "(", "-", "4", ",", "LCID", ",", "3", ",", "(", "13", ",", "10", ")", ",", "(", ")", ")", "except", "pythoncom", ".", "error", ":", ...
https://github.com/lohriialo/photoshop-scripting-python/blob/6b97da967a5d0a45e54f7c99631b29773b923f09/api_reference/photoshop_CC_2018.py#L3452-L3458
nschloe/quadpy
c4c076d8ddfa968486a2443a95e2fb3780dcde0f
src/quadpy/t2/_hillion.py
python
hillion_04
()
return T2Scheme("Hillion 4", d, 2, source)
[]
def hillion_04(): a0, a1 = ((3 + i * sqrt(3)) / 8 for i in [+1, -1]) d = {"s2_static": [[frac(1, 9)], [0]], "swap_ab": [[frac(4, 9)], [a0], [a1]]} return T2Scheme("Hillion 4", d, 2, source)
[ "def", "hillion_04", "(", ")", ":", "a0", ",", "a1", "=", "(", "(", "3", "+", "i", "*", "sqrt", "(", "3", ")", ")", "/", "8", "for", "i", "in", "[", "+", "1", ",", "-", "1", "]", ")", "d", "=", "{", "\"s2_static\"", ":", "[", "[", "frac...
https://github.com/nschloe/quadpy/blob/c4c076d8ddfa968486a2443a95e2fb3780dcde0f/src/quadpy/t2/_hillion.py#L37-L40
joke2k/faker
0ebe46fc9b9793fe315cf0fce430258ce74df6f8
faker/providers/ssn/ro_RO/__init__.py
python
Provider.ssn
(self)
return num
Romanian Social Security Number. :return: a random Romanian SSN
Romanian Social Security Number.
[ "Romanian", "Social", "Security", "Number", "." ]
def ssn(self) -> str: """ Romanian Social Security Number. :return: a random Romanian SSN """ gender = self.random_int(min=1, max=8) year = self.random_int(min=0, max=99) month = self.random_int(min=1, max=12) day = self.random_int(min=1, max=31) county = int( self.random_element( [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "51", "52", ] ) ) serial = self.random_int(min=1, max=999) num = f"{gender:01d}{year:02d}{month:02d}{day:02d}{county:02d}{serial:03d}" check = ssn_checksum(num) num += str(check) return num
[ "def", "ssn", "(", "self", ")", "->", "str", ":", "gender", "=", "self", ".", "random_int", "(", "min", "=", "1", ",", "max", "=", "8", ")", "year", "=", "self", ".", "random_int", "(", "min", "=", "0", ",", "max", "=", "99", ")", "month", "=...
https://github.com/joke2k/faker/blob/0ebe46fc9b9793fe315cf0fce430258ce74df6f8/faker/providers/ssn/ro_RO/__init__.py#L65-L135
Scarygami/mirror-api
497783f6d721b24b793c1fcd8c71d0c7d11956d4
lib/cloudstorage/rest_api.py
python
_RestApi.get_token_async
(self, refresh=False)
Get an authentication token. The token is cached in memcache, keyed by the scopes argument. Args: refresh: If True, ignore a cached token; default False. Yields: An authentication token. This token is guaranteed to be non-expired.
Get an authentication token.
[ "Get", "an", "authentication", "token", "." ]
def get_token_async(self, refresh=False): """Get an authentication token. The token is cached in memcache, keyed by the scopes argument. Args: refresh: If True, ignore a cached token; default False. Yields: An authentication token. This token is guaranteed to be non-expired. """ key = '%s,%s' % (self.service_account_id, ','.join(self.scopes)) ts = yield _AE_TokenStorage_.get_by_id_async( key, use_cache=True, use_memcache=True, use_datastore=self.retry_params.save_access_token) if refresh or ts is None or ts.expires < ( time.time() + self._TOKEN_EXPIRATION_HEADROOM): token, expires_at = yield self.make_token_async( self.scopes, self.service_account_id) timeout = int(expires_at - time.time()) ts = _AE_TokenStorage_(id=key, token=token, expires=expires_at) if timeout > 0: yield ts.put_async(memcache_timeout=timeout, use_datastore=self.retry_params.save_access_token, use_cache=True, use_memcache=True) raise ndb.Return(ts.token)
[ "def", "get_token_async", "(", "self", ",", "refresh", "=", "False", ")", ":", "key", "=", "'%s,%s'", "%", "(", "self", ".", "service_account_id", ",", "','", ".", "join", "(", "self", ".", "scopes", ")", ")", "ts", "=", "yield", "_AE_TokenStorage_", "...
https://github.com/Scarygami/mirror-api/blob/497783f6d721b24b793c1fcd8c71d0c7d11956d4/lib/cloudstorage/rest_api.py#L191-L216
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/ADT/AutoDockTools/MoleculePreparation.py
python
LigandWriter.writeBreadthFirst
(self, outfptr, fromAtom, startAtom)
return queue
None <-writeBreadthFirst(outfptr, fromAtom, startAtom) writeBreadthFirst visits all the atoms in the current level then the first level down etc in a Breadth First Order traversal. 1 <-1 5 6 7 8 <-3 9 10 11 12 <-4 It is used to write out the molecule with the correct format for AutoDock. Specifically, appropriate BRANCH/ENDBRANCH statements are added.
None <-writeBreadthFirst(outfptr, fromAtom, startAtom) writeBreadthFirst visits all the atoms in the current level then the first level down etc in a Breadth First Order traversal. 1 <-1 5 6 7 8 <-3 9 10 11 12 <-4 It is used to write out the molecule with the correct format for AutoDock. Specifically, appropriate BRANCH/ENDBRANCH statements are added.
[ "None", "<", "-", "writeBreadthFirst", "(", "outfptr", "fromAtom", "startAtom", ")", "writeBreadthFirst", "visits", "all", "the", "atoms", "in", "the", "current", "level", "then", "the", "first", "level", "down", "etc", "in", "a", "Breadth", "First", "Order", ...
def writeBreadthFirst(self, outfptr, fromAtom, startAtom): """ None <-writeBreadthFirst(outfptr, fromAtom, startAtom) writeBreadthFirst visits all the atoms in the current level then the first level down etc in a Breadth First Order traversal. 1 <-1 5 6 7 8 <-3 9 10 11 12 <-4 It is used to write out the molecule with the correct format for AutoDock. Specifically, appropriate BRANCH/ENDBRANCH statements are added. """ if self.debug: print "in wBF with fromAtom=", fromAtom.name, '+ startAtom=', startAtom.name, 'startAtom.used=', startAtom.used queue = [] if startAtom.used==0: startAtom.used = 1 startAtom.number = startAtom.newindex = self.outatom_counter self.writer.write_atom(outfptr,startAtom) if self.debug: print 'wBF: wrote ', startAtom.name self.writtenAtoms.append(startAtom) self.outatom_counter += 1 if self.debug: print "self.outatom_counter=", self.outatom_counter activeTors = [] #outfptr.write(outstring) for bond in startAtom.bonds: at2 = bond.atom1 if at2==startAtom: at2 = bond.atom2 if at2==fromAtom: continue #this is current bond elif not at2.used: if bond.activeTors: queue.append((startAtom,at2)) else: at2.number = at2.newindex = self.outatom_counter if self.debug: print "\n\nwriting and calling wL with nA=", at2.name, '-', at2.number self.writer.write_atom(outfptr, at2) if self.debug: print 'wBF2: wrote ', at2.name at2.written = 1 self.writtenAtoms.append(at2) at2.newindex = self.outatom_counter self.outatom_counter = self.outatom_counter + 1 if self.debug: print '!!!2:calling wL' newQ = self.writeLevel(at2, outfptr) if self.debug: print "newQ=", newQ at2.used = 1 if len(newQ): if self.debug: print "@@@@len(newq)=", len(newQ) queue.extend(newQ) if self.debug: print "queue=", queue if self.debug: print " currently queue=", for atom1, atom2 in queue: print atom1.name, '-', atom2.name, ',', print return queue
[ "def", "writeBreadthFirst", "(", "self", ",", "outfptr", ",", "fromAtom", ",", "startAtom", ")", ":", "if", "self", ".", "debug", ":", "print", "\"in wBF with fromAtom=\"", ",", "fromAtom", ".", "name", ",", "'+ startAtom='", ",", "startAtom", ".", "name", "...
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/ADT/AutoDockTools/MoleculePreparation.py#L1258-L1313
PrefectHQ/prefect
67bdc94e2211726d99561f6f52614bec8970e981
src/prefect/backend/flow_run.py
python
check_for_compatible_agents
(labels: Iterable[str], since_minutes: int = 1)
return ( f"You have {len(healthy_agents)} healthy agents in your tenant but do not have " f"an agent with {labels_blurb}. Start an agent with matching labels to deploy " "your flow run." )
Checks for agents compatible with a set of labels returning a user-friendly message indicating the status, roughly one of the following cases: - There is a healthy agent with matching labels - There are N healthy agents with matching labels - There is an unhealthy agent with matching labels but no healthy agents matching - There are N unhealthy agents with matching labels but no healthy agents matching - There are no healthy agents at all and no unhealthy agents with matching labels - There are healthy agents but no healthy or unhealthy agent has matching labels EXPERIMENTAL: This interface is experimental and subject to change Args: - labels: A set of labels; typically associated with a flow run - since_minutes: The amount of time in minutes to allow an agent to be idle and considered active/healthy still Returns: A message string
Checks for agents compatible with a set of labels returning a user-friendly message indicating the status, roughly one of the following cases:
[ "Checks", "for", "agents", "compatible", "with", "a", "set", "of", "labels", "returning", "a", "user", "-", "friendly", "message", "indicating", "the", "status", "roughly", "one", "of", "the", "following", "cases", ":" ]
def check_for_compatible_agents(labels: Iterable[str], since_minutes: int = 1) -> str: """ Checks for agents compatible with a set of labels returning a user-friendly message indicating the status, roughly one of the following cases: - There is a healthy agent with matching labels - There are N healthy agents with matching labels - There is an unhealthy agent with matching labels but no healthy agents matching - There are N unhealthy agents with matching labels but no healthy agents matching - There are no healthy agents at all and no unhealthy agents with matching labels - There are healthy agents but no healthy or unhealthy agent has matching labels EXPERIMENTAL: This interface is experimental and subject to change Args: - labels: A set of labels; typically associated with a flow run - since_minutes: The amount of time in minutes to allow an agent to be idle and considered active/healthy still Returns: A message string """ client = prefect.Client() labels = set(labels) labels_blurb = f"labels {labels!r}" if labels else "empty labels" result = client.graphql( {"query": {"agent": {"last_queried", "labels", "name", "id"}}} ) agents = result.get("data", {}).get("agent") if agents is None: raise ValueError(f"Received bad result while querying for agents: {result}") # Parse last query times for agent in agents: agent.last_queried = cast( Optional[pendulum.DateTime], pendulum.parse(agent.last_queried) if agent.last_queried else None, ) # Drop agents that have not queried agents = [agent for agent in agents if agent.last_queried is not None] # Drop agents that have not sent a recent hearbeat since = pendulum.now().subtract(minutes=since_minutes) healthy_agents = [agent for agent in agents if agent.last_queried >= since] # Search for the flow run labels in running agents matching_healthy = [] matching_unhealthy = [] for agent in agents: empty_labels_match = not agent.labels and not labels if empty_labels_match or (labels and labels.issubset(agent.labels)): if agent in healthy_agents: matching_healthy.append(agent) else: matching_unhealthy.append(agent) if len(matching_healthy) == 1: agent = matching_healthy[0] # Display the single matching agent name_blurb = f" ({agent.name})" if agent.name else "" return ( f"Agent {agent.id}{name_blurb} has matching labels and last queried " f"{agent.last_queried.diff_for_humans()}. It should deploy your flow run." ) if len(matching_healthy) > 1: # Display that there are multiple matching agents return ( f"Found {len(matching_healthy)} healthy agents with matching labels. One " "of them should pick up your flow." ) # We now know we have no matching healthy agents... if not healthy_agents and not matching_unhealthy: # Display that there are no matching agents all-time return ( "There are no healthy agents in your tenant and it does not look like an " "agent with the required labels has been run recently. Start an agent with " f"{labels_blurb} to run your flow." ) if len(matching_unhealthy) == 1: agent = matching_unhealthy[0] # Display that there is a single matching unhealthy agent name_blurb = f" ({agent.name})" if agent.name else "" return ( f"Agent {agent.id}{name_blurb} has matching labels and last queried " f"{agent.last_queried.diff_for_humans()}. Since it hasn't queried recently, it looks " f"unhealthy. Restart it or start a new agent with {labels_blurb} to deploy " f"your flow run." ) if len(matching_unhealthy) > 1: # Display that there are multiple matching unhealthy agents return ( f"Found {len(matching_unhealthy)} agents with matching labels but they " "have not queried recently and look unhealthy. Restart one of them or " f"start a new agent with {labels_blurb} deploy your flow run." ) # No matching healthy or unhealthy agents return ( f"You have {len(healthy_agents)} healthy agents in your tenant but do not have " f"an agent with {labels_blurb}. Start an agent with matching labels to deploy " "your flow run." )
[ "def", "check_for_compatible_agents", "(", "labels", ":", "Iterable", "[", "str", "]", ",", "since_minutes", ":", "int", "=", "1", ")", "->", "str", ":", "client", "=", "prefect", ".", "Client", "(", ")", "labels", "=", "set", "(", "labels", ")", "labe...
https://github.com/PrefectHQ/prefect/blob/67bdc94e2211726d99561f6f52614bec8970e981/src/prefect/backend/flow_run.py#L171-L282
godotengine/godot-blender-exporter
b8b883df64f601acc4c40110e99631422a4978ff
io_scene_godot/converters/material/script_shader/node_converters.py
python
NodeConverterBase.zup_to_yup
(self, var)
Convert a vec3 from z-up space to y-up space
Convert a vec3 from z-up space to y-up space
[ "Convert", "a", "vec3", "from", "z", "-", "up", "space", "to", "y", "-", "up", "space" ]
def zup_to_yup(self, var): """Convert a vec3 from z-up space to y-up space""" function = find_function_by_name("space_convert_zup_to_yup") self.add_function_call(function, [var], [])
[ "def", "zup_to_yup", "(", "self", ",", "var", ")", ":", "function", "=", "find_function_by_name", "(", "\"space_convert_zup_to_yup\"", ")", "self", ".", "add_function_call", "(", "function", ",", "[", "var", "]", ",", "[", "]", ")" ]
https://github.com/godotengine/godot-blender-exporter/blob/b8b883df64f601acc4c40110e99631422a4978ff/io_scene_godot/converters/material/script_shader/node_converters.py#L301-L304
privacyidea/privacyidea
9490c12ddbf77a34ac935b082d09eb583dfafa2c
privacyidea/lib/tokens/smstoken.py
python
SmsTokenClass._get_sms_provider
()
return SMSProvider, SMSProviderClass
get the SMS Provider class definition :return: tuple of SMSProvider and Provider Class as string :rtype: tuple of (string, string)
get the SMS Provider class definition
[ "get", "the", "SMS", "Provider", "class", "definition" ]
def _get_sms_provider(): """ get the SMS Provider class definition :return: tuple of SMSProvider and Provider Class as string :rtype: tuple of (string, string) """ smsProvider = get_from_config("sms.provider", default="privacyidea.lib.smsprovider." "HttpSMSProvider.HttpSMSProvider") (SMSProvider, SMSProviderClass) = smsProvider.rsplit(".", 1) return SMSProvider, SMSProviderClass
[ "def", "_get_sms_provider", "(", ")", ":", "smsProvider", "=", "get_from_config", "(", "\"sms.provider\"", ",", "default", "=", "\"privacyidea.lib.smsprovider.\"", "\"HttpSMSProvider.HttpSMSProvider\"", ")", "(", "SMSProvider", ",", "SMSProviderClass", ")", "=", "smsProvi...
https://github.com/privacyidea/privacyidea/blob/9490c12ddbf77a34ac935b082d09eb583dfafa2c/privacyidea/lib/tokens/smstoken.py#L468-L479
srusskih/SublimeJEDI
8a5054f0a053c8a8170c06c56216245240551d54
dependencies/parso/python/errors.py
python
_iter_stmts
(scope)
Iterates over all statements and splits up simple_stmt.
Iterates over all statements and splits up simple_stmt.
[ "Iterates", "over", "all", "statements", "and", "splits", "up", "simple_stmt", "." ]
def _iter_stmts(scope): """ Iterates over all statements and splits up simple_stmt. """ for child in scope.children: if child.type == 'simple_stmt': for child2 in child.children: if child2.type == 'newline' or child2 == ';': continue yield child2 else: yield child
[ "def", "_iter_stmts", "(", "scope", ")", ":", "for", "child", "in", "scope", ".", "children", ":", "if", "child", ".", "type", "==", "'simple_stmt'", ":", "for", "child2", "in", "child", ".", "children", ":", "if", "child2", ".", "type", "==", "'newlin...
https://github.com/srusskih/SublimeJEDI/blob/8a5054f0a053c8a8170c06c56216245240551d54/dependencies/parso/python/errors.py#L22-L33
deepchem/deepchem
054eb4b2b082e3df8e1a8e77f36a52137ae6e375
deepchem/data/datasets.py
python
DiskDataset.memory_cache_size
(self)
return self._memory_cache_size
Get the size of the memory cache for this dataset, measured in bytes.
Get the size of the memory cache for this dataset, measured in bytes.
[ "Get", "the", "size", "of", "the", "memory", "cache", "for", "this", "dataset", "measured", "in", "bytes", "." ]
def memory_cache_size(self) -> int: """Get the size of the memory cache for this dataset, measured in bytes.""" return self._memory_cache_size
[ "def", "memory_cache_size", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_memory_cache_size" ]
https://github.com/deepchem/deepchem/blob/054eb4b2b082e3df8e1a8e77f36a52137ae6e375/deepchem/data/datasets.py#L2519-L2521
certbot/certbot
30b066f08260b73fc26256b5484a180468b9d0a6
certbot/certbot/_internal/storage.py
python
RenewableCert.newest_available_version
(self, kind: str)
return max(self.available_versions(kind))
Newest available version of the specified kind of item? :param str kind: the lineage member item (``cert``, ``privkey``, ``chain``, or ``fullchain``) :returns: the newest available version of this member :rtype: int
Newest available version of the specified kind of item?
[ "Newest", "available", "version", "of", "the", "specified", "kind", "of", "item?" ]
def newest_available_version(self, kind: str) -> int: """Newest available version of the specified kind of item? :param str kind: the lineage member item (``cert``, ``privkey``, ``chain``, or ``fullchain``) :returns: the newest available version of this member :rtype: int """ return max(self.available_versions(kind))
[ "def", "newest_available_version", "(", "self", ",", "kind", ":", "str", ")", "->", "int", ":", "return", "max", "(", "self", ".", "available_versions", "(", "kind", ")", ")" ]
https://github.com/certbot/certbot/blob/30b066f08260b73fc26256b5484a180468b9d0a6/certbot/certbot/_internal/storage.py#L803-L813
django-nonrel/django-nonrel
4fbfe7344481a5eab8698f79207f09124310131b
django/utils/datastructures.py
python
MergeDict.__repr__
(self)
return '%s(%s)' % (self.__class__.__name__, dictreprs)
Returns something like MergeDict({'key1': 'val1', 'key2': 'val2'}, {'key3': 'val3'}) instead of generic "<object meta-data>" inherited from object.
Returns something like
[ "Returns", "something", "like" ]
def __repr__(self): ''' Returns something like MergeDict({'key1': 'val1', 'key2': 'val2'}, {'key3': 'val3'}) instead of generic "<object meta-data>" inherited from object. ''' dictreprs = ', '.join(repr(d) for d in self.dicts) return '%s(%s)' % (self.__class__.__name__, dictreprs)
[ "def", "__repr__", "(", "self", ")", ":", "dictreprs", "=", "', '", ".", "join", "(", "repr", "(", "d", ")", "for", "d", "in", "self", ".", "dicts", ")", "return", "'%s(%s)'", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "dictreprs", "...
https://github.com/django-nonrel/django-nonrel/blob/4fbfe7344481a5eab8698f79207f09124310131b/django/utils/datastructures.py#L90-L99
pybliometrics-dev/pybliometrics
26ad9656e5a1d4c80774937706a0df85776f07d0
pybliometrics/scopus/affiliation_retrieval.py
python
AffiliationRetrieval.__init__
(self, aff_id: Union[int, str], refresh: Union[bool, int] = False, view: str = "STANDARD", **kwds: str )
Interaction with the Affiliation Retrieval API. :param aff_id: Scopus ID or EID of the affiliation profile. :param refresh: Whether to refresh the cached file if it exists or not. If int is passed, cached file will be refreshed if the number of days since last modification exceeds that value. :param view: The view of the file that should be downloaded. Allowed values: LIGHT, STANDARD, where STANDARD includes all information of the LIGHT view. For details see https://dev.elsevier.com/sc_affil_retrieval_views.html. Note: Neither the BASIC view nor DOCUMENTS or AUTHORS views are active, although documented. :param kwds: Keywords passed on as query parameters. Must contain fields and values mentioned in the API specification at https://dev.elsevier.com/documentation/AffiliationRetrievalAPI.wadl. Raises ------ ValueError If any of the parameters `refresh` or `view` is not one of the allowed values. Notes ----- The directory for cached results is `{path}/{view}/{aff_id}`, where `path` is specified in your configuration file.
Interaction with the Affiliation Retrieval API.
[ "Interaction", "with", "the", "Affiliation", "Retrieval", "API", "." ]
def __init__(self, aff_id: Union[int, str], refresh: Union[bool, int] = False, view: str = "STANDARD", **kwds: str ) -> None: """Interaction with the Affiliation Retrieval API. :param aff_id: Scopus ID or EID of the affiliation profile. :param refresh: Whether to refresh the cached file if it exists or not. If int is passed, cached file will be refreshed if the number of days since last modification exceeds that value. :param view: The view of the file that should be downloaded. Allowed values: LIGHT, STANDARD, where STANDARD includes all information of the LIGHT view. For details see https://dev.elsevier.com/sc_affil_retrieval_views.html. Note: Neither the BASIC view nor DOCUMENTS or AUTHORS views are active, although documented. :param kwds: Keywords passed on as query parameters. Must contain fields and values mentioned in the API specification at https://dev.elsevier.com/documentation/AffiliationRetrievalAPI.wadl. Raises ------ ValueError If any of the parameters `refresh` or `view` is not one of the allowed values. Notes ----- The directory for cached results is `{path}/{view}/{aff_id}`, where `path` is specified in your configuration file. """ # Checks check_parameter_value(view, ('LIGHT', 'STANDARD'), "view") # Load json self._view = view self._refresh = refresh aff_id = str(int(str(aff_id).split('-')[-1])) Retrieval.__init__(self, aff_id, api='AffiliationRetrieval', **kwds) self._json = self._json['affiliation-retrieval-response'] self._profile = self._json.get("institution-profile", {})
[ "def", "__init__", "(", "self", ",", "aff_id", ":", "Union", "[", "int", ",", "str", "]", ",", "refresh", ":", "Union", "[", "bool", ",", "int", "]", "=", "False", ",", "view", ":", "str", "=", "\"STANDARD\"", ",", "*", "*", "kwds", ":", "str", ...
https://github.com/pybliometrics-dev/pybliometrics/blob/26ad9656e5a1d4c80774937706a0df85776f07d0/pybliometrics/scopus/affiliation_retrieval.py#L128-L170
PINTO0309/PINTO_model_zoo
2924acda7a7d541d8712efd7cc4fd1c61ef5bddd
045_ssd_mobilenet_v2_oid_v4/01_float32/detect_common.py
python
make_interpreter
(model_file)
return tflite.Interpreter( model_path=model_file, experimental_delegates=[ tflite.load_delegate(EDGETPU_SHARED_LIB, {'device': device[0]} if device else {}) ])
[]
def make_interpreter(model_file): model_file, *device = model_file.split('@') return tflite.Interpreter( model_path=model_file, experimental_delegates=[ tflite.load_delegate(EDGETPU_SHARED_LIB, {'device': device[0]} if device else {}) ])
[ "def", "make_interpreter", "(", "model_file", ")", ":", "model_file", ",", "", "*", "device", "=", "model_file", ".", "split", "(", "'@'", ")", "return", "tflite", ".", "Interpreter", "(", "model_path", "=", "model_file", ",", "experimental_delegates", "=", ...
https://github.com/PINTO0309/PINTO_model_zoo/blob/2924acda7a7d541d8712efd7cc4fd1c61ef5bddd/045_ssd_mobilenet_v2_oid_v4/01_float32/detect_common.py#L8-L15
tdeboissiere/DeepLearningImplementations
5c4094880fc6992cca2d6e336463b2525026f6e2
DFI/src/data/make_dataset.py
python
build_HDF5
(size)
Gather the data in a single HDF5 file.
Gather the data in a single HDF5 file.
[ "Gather", "the", "data", "in", "a", "single", "HDF5", "file", "." ]
def build_HDF5(size): """ Gather the data in a single HDF5 file. """ df_attr = parse_attibutes() list_col_labels = [c for c in df_attr.columns.values if c not in ["person", "imagenum", "image_path"]] # Put train data in HDF5 hdf5_file = os.path.join(data_dir, "lfw_%s_data.h5" % size) with h5py.File(hdf5_file, "w") as hfw: data_color = hfw.create_dataset("data", (0, 3, size, size), maxshape=(None, 3, size, size), dtype=np.uint8) label = hfw.create_dataset("labels", data=df_attr[list_col_labels].values) label.attrs["label_names"] = list_col_labels arr_img = df_attr.image_path.values num_files = len(arr_img) chunk_size = 1000 num_chunks = num_files / chunk_size arr_chunks = np.array_split(np.arange(num_files), num_chunks) for chunk_idx in tqdm(arr_chunks): list_img_path = arr_img[chunk_idx].tolist() output = parmap.map(format_image, list_img_path, size, pm_parallel=True) arr_img_color = np.concatenate(output, axis=0) # Resize HDF5 dataset data_color.resize(data_color.shape[0] + arr_img_color.shape[0], axis=0) data_color[-arr_img_color.shape[0]:] = arr_img_color.astype(np.uint8)
[ "def", "build_HDF5", "(", "size", ")", ":", "df_attr", "=", "parse_attibutes", "(", ")", "list_col_labels", "=", "[", "c", "for", "c", "in", "df_attr", ".", "columns", ".", "values", "if", "c", "not", "in", "[", "\"person\"", ",", "\"imagenum\"", ",", ...
https://github.com/tdeboissiere/DeepLearningImplementations/blob/5c4094880fc6992cca2d6e336463b2525026f6e2/DFI/src/data/make_dataset.py#L55-L93
colour-science/colour
38782ac059e8ddd91939f3432bf06811c16667f0
colour/algebra/interpolation.py
python
SpragueInterpolator._evaluate
(self, x)
return y
Performs the interpolating polynomial evaluation at given point. Parameters ---------- x : numeric Point to evaluate the interpolant at. Returns ------- float Interpolated point values.
Performs the interpolating polynomial evaluation at given point.
[ "Performs", "the", "interpolating", "polynomial", "evaluation", "at", "given", "point", "." ]
def _evaluate(self, x): """ Performs the interpolating polynomial evaluation at given point. Parameters ---------- x : numeric Point to evaluate the interpolant at. Returns ------- float Interpolated point values. """ x = as_float_array(x) self._validate_dimensions() self._validate_interpolation_range(x) i = np.searchsorted(self._xp, x) - 1 X = (x - self._xp[i]) / (self._xp[i + 1] - self._xp[i]) r = self._yp a0p = r[i] a1p = ((2 * r[i - 2] - 16 * r[i - 1] + 16 * r[i + 1] - 2 * r[i + 2]) / 24) # yapf: disable a2p = ((-r[i - 2] + 16 * r[i - 1] - 30 * r[i] + 16 * r[i + 1] - r[i + 2]) / 24) # yapf: disable a3p = ((-9 * r[i - 2] + 39 * r[i - 1] - 70 * r[i] + 66 * r[i + 1] - 33 * r[i + 2] + 7 * r[i + 3]) / 24) a4p = ((13 * r[i - 2] - 64 * r[i - 1] + 126 * r[i] - 124 * r[i + 1] + 61 * r[i + 2] - 12 * r[i + 3]) / 24) a5p = ((-5 * r[i - 2] + 25 * r[i - 1] - 50 * r[i] + 50 * r[i + 1] - 25 * r[i + 2] + 5 * r[i + 3]) / 24) y = (a0p + a1p * X + a2p * X ** 2 + a3p * X ** 3 + a4p * X ** 4 + a5p * X ** 5) return y
[ "def", "_evaluate", "(", "self", ",", "x", ")", ":", "x", "=", "as_float_array", "(", "x", ")", "self", ".", "_validate_dimensions", "(", ")", "self", ".", "_validate_interpolation_range", "(", "x", ")", "i", "=", "np", ".", "searchsorted", "(", "self", ...
https://github.com/colour-science/colour/blob/38782ac059e8ddd91939f3432bf06811c16667f0/colour/algebra/interpolation.py#L1138-L1178
Mottl/hurst
5ca5005485a679e6ce11a2769c948915ae27b2da
hurst/__init__.py
python
__get_RS
(series, kind)
return R / S
Get rescaled range (using the range of cumulative sum of deviations instead of the range of a series as in the simplified version of R/S) from a time-series of values. Parameters ---------- series : array-like (Time-)series kind : str The kind of series (refer to compute_Hc docstring)
Get rescaled range (using the range of cumulative sum of deviations instead of the range of a series as in the simplified version of R/S) from a time-series of values.
[ "Get", "rescaled", "range", "(", "using", "the", "range", "of", "cumulative", "sum", "of", "deviations", "instead", "of", "the", "range", "of", "a", "series", "as", "in", "the", "simplified", "version", "of", "R", "/", "S", ")", "from", "a", "time", "-...
def __get_RS(series, kind): """ Get rescaled range (using the range of cumulative sum of deviations instead of the range of a series as in the simplified version of R/S) from a time-series of values. Parameters ---------- series : array-like (Time-)series kind : str The kind of series (refer to compute_Hc docstring) """ if kind == 'random_walk': incs = __to_inc(series) mean_inc = (series[-1] - series[0]) / len(incs) deviations = incs - mean_inc Z = np.cumsum(deviations) R = max(Z) - min(Z) S = np.std(incs, ddof=1) elif kind == 'price': incs = __to_pct(series) mean_inc = np.sum(incs) / len(incs) deviations = incs - mean_inc Z = np.cumsum(deviations) R = max(Z) - min(Z) S = np.std(incs, ddof=1) elif kind == 'change': incs = series mean_inc = np.sum(incs) / len(incs) deviations = incs - mean_inc Z = np.cumsum(deviations) R = max(Z) - min(Z) S = np.std(incs, ddof=1) if R == 0 or S == 0: return 0 # return 0 to skip this interval due undefined R/S return R / S
[ "def", "__get_RS", "(", "series", ",", "kind", ")", ":", "if", "kind", "==", "'random_walk'", ":", "incs", "=", "__to_inc", "(", "series", ")", "mean_inc", "=", "(", "series", "[", "-", "1", "]", "-", "series", "[", "0", "]", ")", "/", "len", "("...
https://github.com/Mottl/hurst/blob/5ca5005485a679e6ce11a2769c948915ae27b2da/hurst/__init__.py#L62-L104
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/expanded_landing_page_view_service/transports/grpc.py
python
ExpandedLandingPageViewServiceGrpcTransport.__init__
( self, *, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, )
Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason.
Instantiate the transport.
[ "Instantiate", "the", "transport", "." ]
def __init__( self, *, host: str = "googleads.googleapis.com", credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ self._ssl_channel_credentials = ssl_channel_credentials if channel: # Sanity check: Ensure that channel and credentials are not both # provided. credentials = False # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None elif api_mtls_endpoint: warnings.warn( "api_mtls_endpoint and client_cert_source are deprecated", DeprecationWarning, ) host = ( api_mtls_endpoint if ":" in api_mtls_endpoint else api_mtls_endpoint + ":443" ) if credentials is None: credentials, _ = google.auth.default( scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id ) # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: cert, key = client_cert_source() ssl_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) else: ssl_credentials = SslCredentials().ssl_credentials # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._ssl_channel_credentials = ssl_credentials else: host = host if ":" in host else host + ":443" if credentials is None: credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES) # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, ssl_credentials=ssl_channel_credentials, scopes=self.AUTH_SCOPES, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._stubs = {} # type: Dict[str, Callable] # Run the base constructor. super().__init__( host=host, credentials=credentials, client_info=client_info, )
[ "def", "__init__", "(", "self", ",", "*", ",", "host", ":", "str", "=", "\"googleads.googleapis.com\"", ",", "credentials", ":", "ga_credentials", ".", "Credentials", "=", "None", ",", "credentials_file", ":", "str", "=", "None", ",", "scopes", ":", "Sequenc...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/expanded_landing_page_view_service/transports/grpc.py#L49-L177
AutodeskRoboticsLab/Mimic
85447f0d346be66988303a6a054473d92f1ed6f4
mimic/scripts/extern/pyqtgraph_0_11_0_dev0/pyqtgraph/graphicsItems/ViewBox/ViewBox.py
python
ViewBox.setAspectLocked
(self, lock=True, ratio=1)
If the aspect ratio is locked, view scaling must always preserve the aspect ratio. By default, the ratio is set to 1; x and y both have the same scaling. This ratio can be overridden (xScale/yScale), or use None to lock in the current ratio.
If the aspect ratio is locked, view scaling must always preserve the aspect ratio. By default, the ratio is set to 1; x and y both have the same scaling. This ratio can be overridden (xScale/yScale), or use None to lock in the current ratio.
[ "If", "the", "aspect", "ratio", "is", "locked", "view", "scaling", "must", "always", "preserve", "the", "aspect", "ratio", ".", "By", "default", "the", "ratio", "is", "set", "to", "1", ";", "x", "and", "y", "both", "have", "the", "same", "scaling", "."...
def setAspectLocked(self, lock=True, ratio=1): """ If the aspect ratio is locked, view scaling must always preserve the aspect ratio. By default, the ratio is set to 1; x and y both have the same scaling. This ratio can be overridden (xScale/yScale), or use None to lock in the current ratio. """ if not lock: if self.state['aspectLocked'] == False: return self.state['aspectLocked'] = False else: rect = self.rect() vr = self.viewRect() if rect.height() == 0 or vr.width() == 0 or vr.height() == 0: currentRatio = 1.0 else: currentRatio = (rect.width()/float(rect.height())) / (vr.width()/vr.height()) if ratio is None: ratio = currentRatio if self.state['aspectLocked'] == ratio: # nothing to change return self.state['aspectLocked'] = ratio if ratio != currentRatio: ## If this would change the current range, do that now self.updateViewRange() self.updateAutoRange() self.updateViewRange() self.sigStateChanged.emit(self)
[ "def", "setAspectLocked", "(", "self", ",", "lock", "=", "True", ",", "ratio", "=", "1", ")", ":", "if", "not", "lock", ":", "if", "self", ".", "state", "[", "'aspectLocked'", "]", "==", "False", ":", "return", "self", ".", "state", "[", "'aspectLock...
https://github.com/AutodeskRoboticsLab/Mimic/blob/85447f0d346be66988303a6a054473d92f1ed6f4/mimic/scripts/extern/pyqtgraph_0_11_0_dev0/pyqtgraph/graphicsItems/ViewBox/ViewBox.py#L1037-L1065
radinsky/broadlink-http-rest
b88c5e2c6fecae90553c36394beb24839008563c
server.py
python
SigInt
(signum, frame)
[]
def SigInt(signum, frame): print ("\nShuting down server ...") global ShutdownRequested global InterruptRequested ShutdownRequested = True InterruptRequested = True
[ "def", "SigInt", "(", "signum", ",", "frame", ")", ":", "print", "(", "\"\\nShuting down server ...\"", ")", "global", "ShutdownRequested", "global", "InterruptRequested", "ShutdownRequested", "=", "True", "InterruptRequested", "=", "True" ]
https://github.com/radinsky/broadlink-http-rest/blob/b88c5e2c6fecae90553c36394beb24839008563c/server.py#L533-L538
qutebrowser/qutebrowser
3a2aaaacbf97f4bf0c72463f3da94ed2822a5442
qutebrowser/browser/commands.py
python
CommandDispatcher._current_title
(self)
return self._current_widget().title()
Convenience method to get the current title.
Convenience method to get the current title.
[ "Convenience", "method", "to", "get", "the", "current", "title", "." ]
def _current_title(self): """Convenience method to get the current title.""" return self._current_widget().title()
[ "def", "_current_title", "(", "self", ")", ":", "return", "self", ".", "_current_widget", "(", ")", ".", "title", "(", ")" ]
https://github.com/qutebrowser/qutebrowser/blob/3a2aaaacbf97f4bf0c72463f3da94ed2822a5442/qutebrowser/browser/commands.py#L101-L103
hirofumi0810/tensorflow_end2end_speech_recognition
65b9728089d5e92b25b92384a67419d970399a64
examples/timit/data/load_dataset_multitask_ctc.py
python
Dataset.__init__
(self, data_type, label_type_main, label_type_sub, batch_size, max_epoch=None, splice=1, num_stack=1, num_skip=1, shuffle=False, sort_utt=False, sort_stop_epoch=None, progressbar=False)
A class for loading dataset. Args: data_type (string): train or dev or test label_type_main (string): character or character_capital_divide label_type_sub (stirng): phone39 or phone48 or phone61 batch_size (int): the size of mini-batch max_epoch (int, optional): the max epoch. None means infinite loop. splice (int, optional): frames to splice. Default is 1 frame. num_stack (int, optional): the number of frames to stack num_skip (int, optional): the number of frames to skip shuffle (bool, optional): if True, shuffle utterances. This is disabled when sort_utt is True. sort_utt (bool, optional): if True, sort all utterances by the number of frames and utteraces in each mini-batch are shuffled. Otherwise, shuffle utteraces. sort_stop_epoch (int, optional): After sort_stop_epoch, training will revert back to a random order progressbar (bool, optional): if True, visualize progressbar
A class for loading dataset. Args: data_type (string): train or dev or test label_type_main (string): character or character_capital_divide label_type_sub (stirng): phone39 or phone48 or phone61 batch_size (int): the size of mini-batch max_epoch (int, optional): the max epoch. None means infinite loop. splice (int, optional): frames to splice. Default is 1 frame. num_stack (int, optional): the number of frames to stack num_skip (int, optional): the number of frames to skip shuffle (bool, optional): if True, shuffle utterances. This is disabled when sort_utt is True. sort_utt (bool, optional): if True, sort all utterances by the number of frames and utteraces in each mini-batch are shuffled. Otherwise, shuffle utteraces. sort_stop_epoch (int, optional): After sort_stop_epoch, training will revert back to a random order progressbar (bool, optional): if True, visualize progressbar
[ "A", "class", "for", "loading", "dataset", ".", "Args", ":", "data_type", "(", "string", ")", ":", "train", "or", "dev", "or", "test", "label_type_main", "(", "string", ")", ":", "character", "or", "character_capital_divide", "label_type_sub", "(", "stirng", ...
def __init__(self, data_type, label_type_main, label_type_sub, batch_size, max_epoch=None, splice=1, num_stack=1, num_skip=1, shuffle=False, sort_utt=False, sort_stop_epoch=None, progressbar=False): """A class for loading dataset. Args: data_type (string): train or dev or test label_type_main (string): character or character_capital_divide label_type_sub (stirng): phone39 or phone48 or phone61 batch_size (int): the size of mini-batch max_epoch (int, optional): the max epoch. None means infinite loop. splice (int, optional): frames to splice. Default is 1 frame. num_stack (int, optional): the number of frames to stack num_skip (int, optional): the number of frames to skip shuffle (bool, optional): if True, shuffle utterances. This is disabled when sort_utt is True. sort_utt (bool, optional): if True, sort all utterances by the number of frames and utteraces in each mini-batch are shuffled. Otherwise, shuffle utteraces. sort_stop_epoch (int, optional): After sort_stop_epoch, training will revert back to a random order progressbar (bool, optional): if True, visualize progressbar """ super(Dataset, self).__init__() self.is_test = True if data_type == 'test' else False self.data_type = data_type self.label_type_main = label_type_main self.label_type_sub = label_type_sub self.batch_size = batch_size self.max_epoch = max_epoch self.splice = splice self.num_stack = num_stack self.num_skip = num_skip self.shuffle = shuffle self.sort_utt = sort_utt self.sort_stop_epoch = sort_stop_epoch self.progressbar = progressbar self.num_gpu = 1 # paths where datasets exist dataset_root = ['/data/inaguma/timit', '/n/sd8/inaguma/corpus/timit/dataset'] input_path = join(dataset_root[0], 'inputs', data_type) # NOTE: ex.) save_path: timit_dataset_path/inputs/data_type/***.npy label_main_path = join( dataset_root[0], 'labels', data_type, label_type_main) label_sub_path = join( dataset_root[0], 'labels', data_type, label_type_sub) # NOTE: ex.) save_path: # timit_dataset_path/labels/data_type/label_type/***.npy # Load the frame number dictionary if isfile(join(input_path, 'frame_num.pickle')): with open(join(input_path, 'frame_num.pickle'), 'rb') as f: self.frame_num_dict = pickle.load(f) else: dataset_root.pop(0) input_path = join(dataset_root[0], 'inputs', data_type) label_main_path = join( dataset_root[0], 'labels', data_type, label_type_main) label_sub_path = join( dataset_root[0], 'labels', data_type, label_type_sub) with open(join(input_path, 'frame_num.pickle'), 'rb') as f: self.frame_num_dict = pickle.load(f) # Sort paths to input & label axis = 1 if sort_utt else 0 frame_num_tuple_sorted = sorted(self.frame_num_dict.items(), key=lambda x: x[axis]) input_paths, label_main_paths, label_sub_paths = [], [], [] for input_name, frame_num in frame_num_tuple_sorted: input_paths.append(join(input_path, input_name + '.npy')) label_main_paths.append(join(label_main_path, input_name + '.npy')) label_sub_paths.append(join(label_sub_path, input_name + '.npy')) if len(label_main_paths) != len(label_sub_paths): raise ValueError('The numbers of labels between ' + 'character and phone are not same.') self.input_paths = np.array(input_paths) self.label_main_paths = np.array(label_main_paths) self.label_sub_paths = np.array(label_sub_paths) # NOTE: Not load dataset yet self.rest = set(range(0, len(self.input_paths), 1))
[ "def", "__init__", "(", "self", ",", "data_type", ",", "label_type_main", ",", "label_type_sub", ",", "batch_size", ",", "max_epoch", "=", "None", ",", "splice", "=", "1", ",", "num_stack", "=", "1", ",", "num_skip", "=", "1", ",", "shuffle", "=", "False...
https://github.com/hirofumi0810/tensorflow_end2end_speech_recognition/blob/65b9728089d5e92b25b92384a67419d970399a64/examples/timit/data/load_dataset_multitask_ctc.py#L22-L108
SUSE/DeepSea
9c7fad93915ba1250c40d50c855011e9fe41ed21
srv/modules/runners/populate.py
python
CephRoles._client_roles
(self)
Allows admins to target non-Ceph minions
Allows admins to target non-Ceph minions
[ "Allows", "admins", "to", "target", "non", "-", "Ceph", "minions" ]
def _client_roles(self): """ Allows admins to target non-Ceph minions """ roles = [ 'client-cephfs', 'client-radosgw', 'client-iscsi', 'client-nfs', 'benchmark-rbd', 'benchmark-blockdev', 'benchmark-fs' ] self.available_roles.extend(roles) for role in roles: role_dir = "{}/role-{}".format(self.root_dir, role) self._role_assignment(role_dir, role)
[ "def", "_client_roles", "(", "self", ")", ":", "roles", "=", "[", "'client-cephfs'", ",", "'client-radosgw'", ",", "'client-iscsi'", ",", "'client-nfs'", ",", "'benchmark-rbd'", ",", "'benchmark-blockdev'", ",", "'benchmark-fs'", "]", "self", ".", "available_roles",...
https://github.com/SUSE/DeepSea/blob/9c7fad93915ba1250c40d50c855011e9fe41ed21/srv/modules/runners/populate.py#L353-L364
pm4py/pm4py-core
7807b09a088b02199cd0149d724d0e28793971bf
pm4py/objects/log/util/dataframe_utils.py
python
dataframe_to_activity_case_table
(df: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None)
return activity_table, case_table
Transforms a Pandas dataframe into: - an "activity" table, containing the events and their attributes - a "case" table, containing the cases and their attributes Parameters -------------- df Dataframe parameters Parameters of the algorithm that should be used, including: - Parameters.CASE_ID_KEY => the column to be used as case ID (shall be included both in the activity table and the case table) - Parameters.CASE_PREFIX => if a list of attributes at the case level is not provided, then all the ones of the dataframe starting with one of these are considered. - Parameters.CASE_ATTRIBUTES => the attributes of the dataframe to be used as case columns Returns --------------- activity_table Activity table case_table Case table
Transforms a Pandas dataframe into: - an "activity" table, containing the events and their attributes - a "case" table, containing the cases and their attributes
[ "Transforms", "a", "Pandas", "dataframe", "into", ":", "-", "an", "activity", "table", "containing", "the", "events", "and", "their", "attributes", "-", "a", "case", "table", "containing", "the", "cases", "and", "their", "attributes" ]
def dataframe_to_activity_case_table(df: pd.DataFrame, parameters: Optional[Dict[Any, Any]] = None): """ Transforms a Pandas dataframe into: - an "activity" table, containing the events and their attributes - a "case" table, containing the cases and their attributes Parameters -------------- df Dataframe parameters Parameters of the algorithm that should be used, including: - Parameters.CASE_ID_KEY => the column to be used as case ID (shall be included both in the activity table and the case table) - Parameters.CASE_PREFIX => if a list of attributes at the case level is not provided, then all the ones of the dataframe starting with one of these are considered. - Parameters.CASE_ATTRIBUTES => the attributes of the dataframe to be used as case columns Returns --------------- activity_table Activity table case_table Case table """ if parameters is None: parameters = {} # make sure we start from a dataframe object df = log_converter.apply(df, variant=log_converter.Variants.TO_DATA_FRAME, parameters=parameters) case_id_key = exec_utils.get_param_value(Parameters.CASE_ID_KEY, parameters, constants.CASE_CONCEPT_NAME) case_id_prefix = exec_utils.get_param_value(Parameters.CASE_PREFIX, parameters, constants.CASE_ATTRIBUTE_PREFIX) case_attributes = exec_utils.get_param_value(Parameters.CASE_ATTRIBUTES, parameters, set([x for x in df.columns if x.startswith(case_id_prefix)])) event_attributes = set([x for x in df.columns if x not in case_attributes]) activity_table = df[event_attributes.union({case_id_key})] case_table = df[case_attributes.union({case_id_key})].groupby(case_id_key).first().reset_index() return activity_table, case_table
[ "def", "dataframe_to_activity_case_table", "(", "df", ":", "pd", ".", "DataFrame", ",", "parameters", ":", "Optional", "[", "Dict", "[", "Any", ",", "Any", "]", "]", "=", "None", ")", ":", "if", "parameters", "is", "None", ":", "parameters", "=", "{", ...
https://github.com/pm4py/pm4py-core/blob/7807b09a088b02199cd0149d724d0e28793971bf/pm4py/objects/log/util/dataframe_utils.py#L459-L498
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
pypy/module/cpyext/cdatetime.py
python
PyDateTime_GET_MONTH
(space, w_obj)
return space.int_w(space.getattr(w_obj, space.newtext("month")))
Return the month, as an int from 1 through 12.
Return the month, as an int from 1 through 12.
[ "Return", "the", "month", "as", "an", "int", "from", "1", "through", "12", "." ]
def PyDateTime_GET_MONTH(space, w_obj): """Return the month, as an int from 1 through 12. """ return space.int_w(space.getattr(w_obj, space.newtext("month")))
[ "def", "PyDateTime_GET_MONTH", "(", "space", ",", "w_obj", ")", ":", "return", "space", ".", "int_w", "(", "space", ".", "getattr", "(", "w_obj", ",", "space", ".", "newtext", "(", "\"month\"", ")", ")", ")" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/pypy/module/cpyext/cdatetime.py#L306-L309
textX/textX
452b684d434c557a63ff7ae2b014770c29669e4c
textx/metamodel.py
python
TextXMetaModel.__getitem__
(self, name)
Search for and return class and peg_rule with the given name. Returns: TextXClass, ParsingExpression
Search for and return class and peg_rule with the given name. Returns: TextXClass, ParsingExpression
[ "Search", "for", "and", "return", "class", "and", "peg_rule", "with", "the", "given", "name", ".", "Returns", ":", "TextXClass", "ParsingExpression" ]
def __getitem__(self, name): """ Search for and return class and peg_rule with the given name. Returns: TextXClass, ParsingExpression """ if "." in name: # Name is fully qualified namespace, name = name.rsplit('.', 1) if namespace in self.referenced_languages: language = self.referenced_languages[namespace] referenced_metamodel = metamodel_for_language(language) return referenced_metamodel[name] else: return self.namespaces[namespace][name] else: # If not fully qualified search in the current namespace # and after that in the imported_namespaces if name in self._current_namespace: return self._current_namespace[name] for namespace in \ self._imported_namespaces[self._namespace_stack[-1]]: if name in namespace: return namespace[name] raise KeyError("{} metaclass does not exists in the meta-model " .format(name))
[ "def", "__getitem__", "(", "self", ",", "name", ")", ":", "if", "\".\"", "in", "name", ":", "# Name is fully qualified", "namespace", ",", "name", "=", "name", ".", "rsplit", "(", "'.'", ",", "1", ")", "if", "namespace", "in", "self", ".", "referenced_la...
https://github.com/textX/textX/blob/452b684d434c557a63ff7ae2b014770c29669e4c/textx/metamodel.py#L556-L583
lk-geimfari/mimesis
36653b49f28719c0a2aa20fef6c6df3911811b32
mimesis/providers/person.py
python
Person.occupation
(self)
return self.random.choice(jobs)
Get a random job. :return: The name of job. :Example: Programmer.
Get a random job.
[ "Get", "a", "random", "job", "." ]
def occupation(self) -> str: """Get a random job. :return: The name of job. :Example: Programmer. """ jobs: List[str] = self.extract(["occupation"]) return self.random.choice(jobs)
[ "def", "occupation", "(", "self", ")", "->", "str", ":", "jobs", ":", "List", "[", "str", "]", "=", "self", ".", "extract", "(", "[", "\"occupation\"", "]", ")", "return", "self", ".", "random", ".", "choice", "(", "jobs", ")" ]
https://github.com/lk-geimfari/mimesis/blob/36653b49f28719c0a2aa20fef6c6df3911811b32/mimesis/providers/person.py#L357-L366
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/future/backports/email/_header_value_parser.py
python
get_invalid_mailbox
(value, endchars)
return invalid_mailbox, value
Read everything up to one of the chars in endchars. This is outside the formal grammar. The InvalidMailbox TokenList that is returned acts like a Mailbox, but the data attributes are None.
Read everything up to one of the chars in endchars.
[ "Read", "everything", "up", "to", "one", "of", "the", "chars", "in", "endchars", "." ]
def get_invalid_mailbox(value, endchars): """ Read everything up to one of the chars in endchars. This is outside the formal grammar. The InvalidMailbox TokenList that is returned acts like a Mailbox, but the data attributes are None. """ invalid_mailbox = InvalidMailbox() while value and value[0] not in endchars: if value[0] in PHRASE_ENDS: invalid_mailbox.append(ValueTerminal(value[0], 'misplaced-special')) value = value[1:] else: token, value = get_phrase(value) invalid_mailbox.append(token) return invalid_mailbox, value
[ "def", "get_invalid_mailbox", "(", "value", ",", "endchars", ")", ":", "invalid_mailbox", "=", "InvalidMailbox", "(", ")", "while", "value", "and", "value", "[", "0", "]", "not", "in", "endchars", ":", "if", "value", "[", "0", "]", "in", "PHRASE_ENDS", "...
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/future/backports/email/_header_value_parser.py#L2147-L2163
TabbycatDebate/tabbycat
7cc3b2fa1cc34569501a4be10fe9234b98c65df3
tabbycat/importer/forms.py
python
TeamDetailsForm._post_clean_speakers
(self)
Validates the Speaker instances that would be created.
Validates the Speaker instances that would be created.
[ "Validates", "the", "Speaker", "instances", "that", "would", "be", "created", "." ]
def _post_clean_speakers(self): """Validates the Speaker instances that would be created.""" for i, name in enumerate(self.cleaned_data.get('speakers', [])): try: speaker = Speaker(name=name) speaker.full_clean(exclude=('team',)) except ValidationError as errors: for field, e in errors: # replace field with `speakers` self.add_error('speakers', e)
[ "def", "_post_clean_speakers", "(", "self", ")", ":", "for", "i", ",", "name", "in", "enumerate", "(", "self", ".", "cleaned_data", ".", "get", "(", "'speakers'", ",", "[", "]", ")", ")", ":", "try", ":", "speaker", "=", "Speaker", "(", "name", "=", ...
https://github.com/TabbycatDebate/tabbycat/blob/7cc3b2fa1cc34569501a4be10fe9234b98c65df3/tabbycat/importer/forms.py#L261-L269
ring04h/weakfilescan
b1a3066e3fdcd60b8ecf635526f49cb5ad603064
libs/requests/sessions.py
python
Session.options
(self, url, **kwargs)
return self.request('OPTIONS', url, **kwargs)
Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes.
Sends a OPTIONS request. Returns :class:`Response` object.
[ "Sends", "a", "OPTIONS", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
def options(self, url, **kwargs): """Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. """ kwargs.setdefault('allow_redirects', True) return self.request('OPTIONS', url, **kwargs)
[ "def", "options", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "True", ")", "return", "self", ".", "request", "(", "'OPTIONS'", ",", "url", ",", "*", "*", "kwargs", ")" ]
https://github.com/ring04h/weakfilescan/blob/b1a3066e3fdcd60b8ecf635526f49cb5ad603064/libs/requests/sessions.py#L475-L483
emeryberger/CSrankings
805e55a40e4d3669a51bef2f030492991395bfa9
util/clean-csrankings.py
python
find_fix
(name, affiliation)
[]
def find_fix(name, affiliation): string = name + " " + affiliation results = "" # DISABLED GOOGLE SEARCH google.search(string, stop=1) actualURL = "http://csrankings.org" for url in results: actualURL = url matched = 0 for t in trimstrings: match = re.search(t, url) if match != None: matched = matched + 1 if matched == 0: break # Output the name and this resolved URL. match = re.search("www.google.com", actualURL) if match == None: return actualURL else: return "http://csrankings.org"
[ "def", "find_fix", "(", "name", ",", "affiliation", ")", ":", "string", "=", "name", "+", "\" \"", "+", "affiliation", "results", "=", "\"\"", "# DISABLED GOOGLE SEARCH google.search(string, stop=1)", "actualURL", "=", "\"http://csrankings.org\"", "for", "url", "in", ...
https://github.com/emeryberger/CSrankings/blob/805e55a40e4d3669a51bef2f030492991395bfa9/util/clean-csrankings.py#L45-L64
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cdn/v20180606/models.py
python
DescribePushQuotaResponse.__init__
(self)
r""" :param UrlPush: Url预热用量及配额。 :type UrlPush: list of Quota :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param UrlPush: Url预热用量及配额。 :type UrlPush: list of Quota :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "UrlPush", ":", "Url预热用量及配额。", ":", "type", "UrlPush", ":", "list", "of", "Quota", ":", "param", "RequestId", ":", "唯一请求", "ID,每次请求都会返回。定位问题时需要提供该次请求的", "RequestId。", ":", "type", "RequestId", ":", "str" ]
def __init__(self): r""" :param UrlPush: Url预热用量及配额。 :type UrlPush: list of Quota :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.UrlPush = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "UrlPush", "=", "None", "self", ".", "RequestId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cdn/v20180606/models.py#L5426-L5434
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/tablib-0.12.1/tablib/core.py
python
Dataset.width
(self)
The number of columns currently in the :class:`Dataset`. Cannot be directly modified.
The number of columns currently in the :class:`Dataset`. Cannot be directly modified.
[ "The", "number", "of", "columns", "currently", "in", "the", ":", "class", ":", "Dataset", ".", "Cannot", "be", "directly", "modified", "." ]
def width(self): """The number of columns currently in the :class:`Dataset`. Cannot be directly modified. """ try: return len(self._data[0]) except IndexError: try: return len(self.headers) except TypeError: return 0
[ "def", "width", "(", "self", ")", ":", "try", ":", "return", "len", "(", "self", ".", "_data", "[", "0", "]", ")", "except", "IndexError", ":", "try", ":", "return", "len", "(", "self", ".", "headers", ")", "except", "TypeError", ":", "return", "0"...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/tablib-0.12.1/tablib/core.py#L424-L435
enthought/chaco
0907d1dedd07a499202efbaf2fe2a4e51b4c8e5f
chaco/tools/pan_tool2.py
python
PanTool.drag_start
(self, event)
Called when the drag operation starts
Called when the drag operation starts
[ "Called", "when", "the", "drag", "operation", "starts" ]
def drag_start(self, event): """ Called when the drag operation starts """ self._start_pan(event)
[ "def", "drag_start", "(", "self", ",", "event", ")", ":", "self", ".", "_start_pan", "(", "event", ")" ]
https://github.com/enthought/chaco/blob/0907d1dedd07a499202efbaf2fe2a4e51b4c8e5f/chaco/tools/pan_tool2.py#L70-L72
arthurdejong/python-stdnum
02dec52602ae0709b940b781fc1fcebfde7340b7
stdnum/fi/hetu.py
python
validate
(number, allow_temporary=False)
return number
Check if the number is a valid HETU. It checks the format, whether a valid date is given and whether the check digit is correct. Allows temporary identifier range for individuals (900-999) if allow_temporary is True.
Check if the number is a valid HETU. It checks the format, whether a valid date is given and whether the check digit is correct. Allows temporary identifier range for individuals (900-999) if allow_temporary is True.
[ "Check", "if", "the", "number", "is", "a", "valid", "HETU", ".", "It", "checks", "the", "format", "whether", "a", "valid", "date", "is", "given", "and", "whether", "the", "check", "digit", "is", "correct", ".", "Allows", "temporary", "identifier", "range",...
def validate(number, allow_temporary=False): """Check if the number is a valid HETU. It checks the format, whether a valid date is given and whether the check digit is correct. Allows temporary identifier range for individuals (900-999) if allow_temporary is True. """ number = compact(number) match = _hetu_re.search(number) if not match: raise InvalidFormat() day = int(match.group('day')) month = int(match.group('month')) year = int(match.group('year')) century = _century_codes[match.group('century')] individual = int(match.group('individual')) # check if birth date is valid try: datetime.date(century + year, month, day) except ValueError: raise InvalidComponent() # for historical reasons individual IDs start from 002 if individual < 2: raise InvalidComponent() # this range is for temporary identifiers if 900 <= individual <= 999 and not allow_temporary: raise InvalidComponent() checkable_number = '%02d%02d%02d%03d' % (day, month, year, individual) if match.group('control') != _calc_checksum(checkable_number): raise InvalidChecksum() return number
[ "def", "validate", "(", "number", ",", "allow_temporary", "=", "False", ")", ":", "number", "=", "compact", "(", "number", ")", "match", "=", "_hetu_re", ".", "search", "(", "number", ")", "if", "not", "match", ":", "raise", "InvalidFormat", "(", ")", ...
https://github.com/arthurdejong/python-stdnum/blob/02dec52602ae0709b940b781fc1fcebfde7340b7/stdnum/fi/hetu.py#L75-L104
tribe29/checkmk
6260f2512e159e311f426e16b84b19d0b8e9ad0c
cmk/gui/plugins/wato/utils/__init__.py
python
HostTagCondition._current_tag_setting
(self, choices, tag_specs)
return default_tag, deflt
Determine current (default) setting of tag by looking into tag_specs (e.g. [ "snmp", "!tcp", "test" ] )
Determine current (default) setting of tag by looking into tag_specs (e.g. [ "snmp", "!tcp", "test" ] )
[ "Determine", "current", "(", "default", ")", "setting", "of", "tag", "by", "looking", "into", "tag_specs", "(", "e", ".", "g", ".", "[", "snmp", "!tcp", "test", "]", ")" ]
def _current_tag_setting(self, choices, tag_specs): """Determine current (default) setting of tag by looking into tag_specs (e.g. [ "snmp", "!tcp", "test" ] )""" default_tag = None ignore = True for t in tag_specs: if t[0] == "!": n = True t = t[1:] else: n = False if t in [x[0] for x in choices]: default_tag = t ignore = False negate = n if ignore: deflt = "ignore" elif negate: deflt = "isnot" else: deflt = "is" return default_tag, deflt
[ "def", "_current_tag_setting", "(", "self", ",", "choices", ",", "tag_specs", ")", ":", "default_tag", "=", "None", "ignore", "=", "True", "for", "t", "in", "tag_specs", ":", "if", "t", "[", "0", "]", "==", "\"!\"", ":", "n", "=", "True", "t", "=", ...
https://github.com/tribe29/checkmk/blob/6260f2512e159e311f426e16b84b19d0b8e9ad0c/cmk/gui/plugins/wato/utils/__init__.py#L2436-L2456
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/pip/_vendor/requests/models.py
python
Response.__nonzero__
(self)
return self.ok
Returns true if :attr:`status_code` is 'OK'.
Returns true if :attr:`status_code` is 'OK'.
[ "Returns", "true", "if", ":", "attr", ":", "status_code", "is", "OK", "." ]
def __nonzero__(self): """Returns true if :attr:`status_code` is 'OK'.""" return self.ok
[ "def", "__nonzero__", "(", "self", ")", ":", "return", "self", ".", "ok" ]
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/pip/_vendor/requests/models.py#L626-L628
PokemonGoF/PokemonGo-Bot-Desktop
4bfa94f0183406c6a86f93645eff7abd3ad4ced8
build/pywin/Lib/decimal.py
python
_dlog10
(c, e, p)
return _div_nearest(log_tenpower+log_d, 100)
Given integers c, e and p with c > 0, p >= 0, compute an integer approximation to 10**p * log10(c*10**e), with an absolute error of at most 1. Assumes that c*10**e is not exactly 1.
Given integers c, e and p with c > 0, p >= 0, compute an integer approximation to 10**p * log10(c*10**e), with an absolute error of at most 1. Assumes that c*10**e is not exactly 1.
[ "Given", "integers", "c", "e", "and", "p", "with", "c", ">", "0", "p", ">", "=", "0", "compute", "an", "integer", "approximation", "to", "10", "**", "p", "*", "log10", "(", "c", "*", "10", "**", "e", ")", "with", "an", "absolute", "error", "of", ...
def _dlog10(c, e, p): """Given integers c, e and p with c > 0, p >= 0, compute an integer approximation to 10**p * log10(c*10**e), with an absolute error of at most 1. Assumes that c*10**e is not exactly 1.""" # increase precision by 2; compensate for this by dividing # final result by 100 p += 2 # write c*10**e as d*10**f with either: # f >= 0 and 1 <= d <= 10, or # f <= 0 and 0.1 <= d <= 1. # Thus for c*10**e close to 1, f = 0 l = len(str(c)) f = e+l - (e+l >= 1) if p > 0: M = 10**p k = e+p-f if k >= 0: c *= 10**k else: c = _div_nearest(c, 10**-k) log_d = _ilog(c, M) # error < 5 + 22 = 27 log_10 = _log10_digits(p) # error < 1 log_d = _div_nearest(log_d*M, log_10) log_tenpower = f*M # exact else: log_d = 0 # error < 2.31 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5 return _div_nearest(log_tenpower+log_d, 100)
[ "def", "_dlog10", "(", "c", ",", "e", ",", "p", ")", ":", "# increase precision by 2; compensate for this by dividing", "# final result by 100", "p", "+=", "2", "# write c*10**e as d*10**f with either:", "# f >= 0 and 1 <= d <= 10, or", "# f <= 0 and 0.1 <= d <= 1.", "# Thus ...
https://github.com/PokemonGoF/PokemonGo-Bot-Desktop/blob/4bfa94f0183406c6a86f93645eff7abd3ad4ced8/build/pywin/Lib/decimal.py#L5595-L5627
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Centos_6.4/pyasn1/type/base.py
python
AbstractSimpleAsn1Item.prettyIn
(self, value)
return value
[]
def prettyIn(self, value): return value
[ "def", "prettyIn", "(", "self", ",", "value", ")", ":", "return", "value" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Centos_6.4/pyasn1/type/base.py#L120-L120
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/xmlrpc/server.py
python
SimpleXMLRPCDispatcher.system_listMethods
(self)
return sorted(methods)
system.listMethods() => ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server.
system.listMethods() => ['add', 'subtract', 'multiple']
[ "system", ".", "listMethods", "()", "=", ">", "[", "add", "subtract", "multiple", "]" ]
def system_listMethods(self): """system.listMethods() => ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server.""" methods = set(self.funcs.keys()) if self.instance is not None: # Instance can implement _listMethod to return a list of # methods if hasattr(self.instance, '_listMethods'): methods |= set(self.instance._listMethods()) # if the instance has a _dispatch method then we # don't have enough information to provide a list # of methods elif not hasattr(self.instance, '_dispatch'): methods |= set(list_public_methods(self.instance)) return sorted(methods)
[ "def", "system_listMethods", "(", "self", ")", ":", "methods", "=", "set", "(", "self", ".", "funcs", ".", "keys", "(", ")", ")", "if", "self", ".", "instance", "is", "not", "None", ":", "# Instance can implement _listMethod to return a list of", "# methods", ...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/xmlrpc/server.py#L285-L301
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/lzma.py
python
LZMAFile.seek
(self, offset, whence=io.SEEK_SET)
return self._buffer.seek(offset, whence)
Change the file position. The new position is specified by offset, relative to the position indicated by whence. Possible values for whence are: 0: start of stream (default): offset must not be negative 1: current stream position 2: end of stream; offset must not be positive Returns the new file position. Note that seeking is emulated, so depending on the parameters, this operation may be extremely slow.
Change the file position.
[ "Change", "the", "file", "position", "." ]
def seek(self, offset, whence=io.SEEK_SET): """Change the file position. The new position is specified by offset, relative to the position indicated by whence. Possible values for whence are: 0: start of stream (default): offset must not be negative 1: current stream position 2: end of stream; offset must not be positive Returns the new file position. Note that seeking is emulated, so depending on the parameters, this operation may be extremely slow. """ self._check_can_seek() return self._buffer.seek(offset, whence)
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", "=", "io", ".", "SEEK_SET", ")", ":", "self", ".", "_check_can_seek", "(", ")", "return", "self", ".", "_buffer", ".", "seek", "(", "offset", ",", "whence", ")" ]
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/lzma.py#L245-L261
alexa/alexa-skills-kit-sdk-for-python
079de73bc8b827be51ea700a3e4e19c29983a173
ask-sdk-runtime/ask_sdk_runtime/dispatch_components/request_components.py
python
GenericHandlerAdapter.execute
(self, handler_input, handler)
return handler.handle(handler_input)
Executes the handler with the provided handler input. :param handler_input: Generic input passed to the dispatcher. :type handler_input: Input :param handler: Request Handler instance. :type handler: object :return: Result executed by passing handler_input to handler. :rtype: Union[None, Output]
Executes the handler with the provided handler input.
[ "Executes", "the", "handler", "with", "the", "provided", "handler", "input", "." ]
def execute(self, handler_input, handler): # type: (Input, AbstractRequestHandler) -> Union[None, Output] """Executes the handler with the provided handler input. :param handler_input: Generic input passed to the dispatcher. :type handler_input: Input :param handler: Request Handler instance. :type handler: object :return: Result executed by passing handler_input to handler. :rtype: Union[None, Output] """ return handler.handle(handler_input)
[ "def", "execute", "(", "self", ",", "handler_input", ",", "handler", ")", ":", "# type: (Input, AbstractRequestHandler) -> Union[None, Output]", "return", "handler", ".", "handle", "(", "handler_input", ")" ]
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/079de73bc8b827be51ea700a3e4e19c29983a173/ask-sdk-runtime/ask_sdk_runtime/dispatch_components/request_components.py#L425-L437
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/cryptography/hazmat/primitives/asymmetric/dsa.py
python
DSAPublicNumbers.__init__
(self, y, parameter_numbers)
[]
def __init__(self, y, parameter_numbers): if not isinstance(y, six.integer_types): raise TypeError("DSAPublicNumbers y argument must be an integer.") if not isinstance(parameter_numbers, DSAParameterNumbers): raise TypeError( "parameter_numbers must be a DSAParameterNumbers instance." ) self._y = y self._parameter_numbers = parameter_numbers
[ "def", "__init__", "(", "self", ",", "y", ",", "parameter_numbers", ")", ":", "if", "not", "isinstance", "(", "y", ",", "six", ".", "integer_types", ")", ":", "raise", "TypeError", "(", "\"DSAPublicNumbers y argument must be an integer.\"", ")", "if", "not", "...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/cryptography/hazmat/primitives/asymmetric/dsa.py#L190-L200
mhallsmoore/qstrader
7d1df112a0c7a941a44a1c155bb4208c1f61e1ca
qstrader/broker/portfolio/position.py
python
Position.net_incl_commission
(self)
return self.net_total - self.commission
Calculates the net total average cost of assets bought and sold including the commission. Returns ------- `float` The net total average cost of assets bought and sold including the commission.
Calculates the net total average cost of assets bought and sold including the commission.
[ "Calculates", "the", "net", "total", "average", "cost", "of", "assets", "bought", "and", "sold", "including", "the", "commission", "." ]
def net_incl_commission(self): """ Calculates the net total average cost of assets bought and sold including the commission. Returns ------- `float` The net total average cost of assets bought and sold including the commission. """ return self.net_total - self.commission
[ "def", "net_incl_commission", "(", "self", ")", ":", "return", "self", ".", "net_total", "-", "self", ".", "commission" ]
https://github.com/mhallsmoore/qstrader/blob/7d1df112a0c7a941a44a1c155bb4208c1f61e1ca/qstrader/broker/portfolio/position.py#L235-L246
dit/dit
2853cb13110c5a5b2fa7ad792e238e2177013da2
dit/distconst.py
python
uniform_like
(dist)
return uniform_distribution(outcome_length, alphabet_size, base)
Returns a uniform distribution with the same outcome length, alphabet size, and base as `dist`. Parameters ---------- dist : Distribution The distribution to mimic.
Returns a uniform distribution with the same outcome length, alphabet size, and base as `dist`.
[ "Returns", "a", "uniform", "distribution", "with", "the", "same", "outcome", "length", "alphabet", "size", "and", "base", "as", "dist", "." ]
def uniform_like(dist): """ Returns a uniform distribution with the same outcome length, alphabet size, and base as `dist`. Parameters ---------- dist : Distribution The distribution to mimic. """ outcome_length = dist.outcome_length() alphabet_size = dist.alphabet base = dist.get_base() return uniform_distribution(outcome_length, alphabet_size, base)
[ "def", "uniform_like", "(", "dist", ")", ":", "outcome_length", "=", "dist", ".", "outcome_length", "(", ")", "alphabet_size", "=", "dist", ".", "alphabet", "base", "=", "dist", ".", "get_base", "(", ")", "return", "uniform_distribution", "(", "outcome_length"...
https://github.com/dit/dit/blob/2853cb13110c5a5b2fa7ad792e238e2177013da2/dit/distconst.py#L541-L553
openstack/python-novaclient
63d368168c87bc0b9a9b7928b42553c609e46089
novaclient/utils.py
python
prepare_query_string
(params)
return '?%s' % parse.urlencode(params) if params else ''
Convert dict params to query string
Convert dict params to query string
[ "Convert", "dict", "params", "to", "query", "string" ]
def prepare_query_string(params): """Convert dict params to query string""" # Transform the dict to a sequence of two-element tuples in fixed # order, then the encoded string will be consistent in Python 2&3. if not params: return '' params = sorted(params.items(), key=lambda x: x[0]) return '?%s' % parse.urlencode(params) if params else ''
[ "def", "prepare_query_string", "(", "params", ")", ":", "# Transform the dict to a sequence of two-element tuples in fixed", "# order, then the encoded string will be consistent in Python 2&3.", "if", "not", "params", ":", "return", "''", "params", "=", "sorted", "(", "params", ...
https://github.com/openstack/python-novaclient/blob/63d368168c87bc0b9a9b7928b42553c609e46089/novaclient/utils.py#L425-L432
inkandswitch/livebook
93c8d467734787366ad084fc3566bf5cbe249c51
public/pypyjs/modules/tarfile.py
python
TarFile.open
(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs)
Open a tar archive for reading, writing or appending. Return an appropriate TarFile class. mode: 'r' or 'r:*' open for reading with transparent compression 'r:' open for reading exclusively uncompressed 'r:gz' open for reading with gzip compression 'r:bz2' open for reading with bzip2 compression 'a' or 'a:' open for appending, creating the file if necessary 'w' or 'w:' open for writing without compression 'w:gz' open for writing with gzip compression 'w:bz2' open for writing with bzip2 compression 'r|*' open a stream of tar blocks with transparent compression 'r|' open an uncompressed stream of tar blocks for reading 'r|gz' open a gzip compressed stream of tar blocks 'r|bz2' open a bzip2 compressed stream of tar blocks 'w|' open an uncompressed stream for writing 'w|gz' open a gzip compressed stream for writing 'w|bz2' open a bzip2 compressed stream for writing
Open a tar archive for reading, writing or appending. Return an appropriate TarFile class.
[ "Open", "a", "tar", "archive", "for", "reading", "writing", "or", "appending", ".", "Return", "an", "appropriate", "TarFile", "class", "." ]
def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs): """Open a tar archive for reading, writing or appending. Return an appropriate TarFile class. mode: 'r' or 'r:*' open for reading with transparent compression 'r:' open for reading exclusively uncompressed 'r:gz' open for reading with gzip compression 'r:bz2' open for reading with bzip2 compression 'a' or 'a:' open for appending, creating the file if necessary 'w' or 'w:' open for writing without compression 'w:gz' open for writing with gzip compression 'w:bz2' open for writing with bzip2 compression 'r|*' open a stream of tar blocks with transparent compression 'r|' open an uncompressed stream of tar blocks for reading 'r|gz' open a gzip compressed stream of tar blocks 'r|bz2' open a bzip2 compressed stream of tar blocks 'w|' open an uncompressed stream for writing 'w|gz' open a gzip compressed stream for writing 'w|bz2' open a bzip2 compressed stream for writing """ if not name and not fileobj: raise ValueError("nothing to open") if mode in ("r", "r:*"): # Find out which *open() is appropriate for opening the file. for comptype in cls.OPEN_METH: func = getattr(cls, cls.OPEN_METH[comptype]) if fileobj is not None: saved_pos = fileobj.tell() try: return func(name, "r", fileobj, **kwargs) except (ReadError, CompressionError), e: if fileobj is not None: fileobj.seek(saved_pos) continue raise ReadError("file could not be opened successfully") elif ":" in mode: filemode, comptype = mode.split(":", 1) filemode = filemode or "r" comptype = comptype or "tar" # Select the *open() function according to # given compression. if comptype in cls.OPEN_METH: func = getattr(cls, cls.OPEN_METH[comptype]) else: raise CompressionError("unknown compression type %r" % comptype) return func(name, filemode, fileobj, **kwargs) elif "|" in mode: filemode, comptype = mode.split("|", 1) filemode = filemode or "r" comptype = comptype or "tar" if filemode not in ("r", "w"): raise ValueError("mode must be 'r' or 'w'") stream = _Stream(name, filemode, comptype, fileobj, bufsize) try: t = cls(name, filemode, stream, **kwargs) except: stream.close() raise t._extfileobj = False return t elif mode in ("a", "w"): return cls.taropen(name, mode, fileobj, **kwargs) raise ValueError("undiscernible mode")
[ "def", "open", "(", "cls", ",", "name", "=", "None", ",", "mode", "=", "\"r\"", ",", "fileobj", "=", "None", ",", "bufsize", "=", "RECORDSIZE", ",", "*", "*", "kwargs", ")", ":", "if", "not", "name", "and", "not", "fileobj", ":", "raise", "ValueErr...
https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/tarfile.py#L1633-L1706
gluon/AbletonLive9_RemoteScripts
0c0db5e2e29bbed88c82bf327f54d4968d36937e
_Framework/ControlSurface.py
python
ControlSurface._register_control
(self, control)
puts control into the list of controls for triggering updates
puts control into the list of controls for triggering updates
[ "puts", "control", "into", "the", "list", "of", "controls", "for", "triggering", "updates" ]
def _register_control(self, control): """ puts control into the list of controls for triggering updates """ if not control != None: raise AssertionError raise control not in self.controls or AssertionError('Control registered twice') self.controls.append(control) control.canonical_parent = self isinstance(control, PhysicalDisplayElement) and self._displays.append(control)
[ "def", "_register_control", "(", "self", ",", "control", ")", ":", "if", "not", "control", "!=", "None", ":", "raise", "AssertionError", "raise", "control", "not", "in", "self", ".", "controls", "or", "AssertionError", "(", "'Control registered twice'", ")", "...
https://github.com/gluon/AbletonLive9_RemoteScripts/blob/0c0db5e2e29bbed88c82bf327f54d4968d36937e/_Framework/ControlSurface.py#L463-L470
yangxue0827/FPN_Tensorflow
c72110d2803455e6e55020f69144d9490a3d39ad
libs/networks/slim_nets/inception_v4.py
python
block_inception_a
(inputs, scope=None, reuse=None)
Builds Inception-A block for Inception v4 network.
Builds Inception-A block for Inception v4 network.
[ "Builds", "Inception", "-", "A", "block", "for", "Inception", "v4", "network", "." ]
def block_inception_a(inputs, scope=None, reuse=None): """Builds Inception-A block for Inception v4 network.""" # By default use stride=1 and SAME padding with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'): with tf.variable_scope(scope, 'BlockInceptionA', [inputs], reuse=reuse): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(inputs, 96, [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(inputs, 64, [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, 96, [3, 3], scope='Conv2d_0b_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(inputs, 64, [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, 96, [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, 96, [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(inputs, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, 96, [1, 1], scope='Conv2d_0b_1x1') return tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3])
[ "def", "block_inception_a", "(", "inputs", ",", "scope", "=", "None", ",", "reuse", "=", "None", ")", ":", "# By default use stride=1 and SAME padding", "with", "slim", ".", "arg_scope", "(", "[", "slim", ".", "conv2d", ",", "slim", ".", "avg_pool2d", ",", "...
https://github.com/yangxue0827/FPN_Tensorflow/blob/c72110d2803455e6e55020f69144d9490a3d39ad/libs/networks/slim_nets/inception_v4.py#L34-L52
FSecureLABS/Jandroid
e31d0dab58a2bfd6ed8e0a387172b8bd7c893436
libs/platform-tools/platform-tools_darwin/systrace/catapult/devil/devil/android/fastboot_utils.py
python
FastbootUtils.FlashDevice
(self, directory, partitions=None, wipe=False)
Flash device with build in |directory|. Directory must contain bootloader, radio, boot, recovery, system, userdata, and cache .img files from an android build. This is a dangerous operation so use with care. Args: fastboot: A FastbootUtils instance. directory: Directory with build files. wipe: Wipes cache and userdata if set to true. partitions: List of partitions to flash. Defaults to all.
Flash device with build in |directory|.
[ "Flash", "device", "with", "build", "in", "|directory|", "." ]
def FlashDevice(self, directory, partitions=None, wipe=False): """Flash device with build in |directory|. Directory must contain bootloader, radio, boot, recovery, system, userdata, and cache .img files from an android build. This is a dangerous operation so use with care. Args: fastboot: A FastbootUtils instance. directory: Directory with build files. wipe: Wipes cache and userdata if set to true. partitions: List of partitions to flash. Defaults to all. """ if partitions is None: partitions = ALL_PARTITIONS # If a device is wiped, then it will no longer have adb keys so it cannot be # communicated with to verify that it is rebooted. It is up to the user of # this script to ensure that the adb keys are set on the device after using # this to wipe a device. with self.FastbootMode(wait_for_reboot=not wipe): self._FlashPartitions(partitions, directory, wipe=wipe)
[ "def", "FlashDevice", "(", "self", ",", "directory", ",", "partitions", "=", "None", ",", "wipe", "=", "False", ")", ":", "if", "partitions", "is", "None", ":", "partitions", "=", "ALL_PARTITIONS", "# If a device is wiped, then it will no longer have adb keys so it ca...
https://github.com/FSecureLABS/Jandroid/blob/e31d0dab58a2bfd6ed8e0a387172b8bd7c893436/libs/platform-tools/platform-tools_darwin/systrace/catapult/devil/devil/android/fastboot_utils.py#L236-L256
matrix1001/welpwn
7274afe270ca5c59ecab8a53c22b228e5d514fe1
PwnContext/core.py
python
get_libc_version
(path)
Get the libc version. Args: path (str): Path to the libc. Returns: str: Libc version. Like '2.29', '2.26' ...
Get the libc version.
[ "Get", "the", "libc", "version", "." ]
def get_libc_version(path): """Get the libc version. Args: path (str): Path to the libc. Returns: str: Libc version. Like '2.29', '2.26' ... """ content = open(path).read() pattern = "libc[- ]([0-9]+\.[0-9]+)" result = re.findall(pattern, content) if result: return result[0] else: return ""
[ "def", "get_libc_version", "(", "path", ")", ":", "content", "=", "open", "(", "path", ")", ".", "read", "(", ")", "pattern", "=", "\"libc[- ]([0-9]+\\.[0-9]+)\"", "result", "=", "re", ".", "findall", "(", "pattern", ",", "content", ")", "if", "result", ...
https://github.com/matrix1001/welpwn/blob/7274afe270ca5c59ecab8a53c22b228e5d514fe1/PwnContext/core.py#L515-L529
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/lib2to3/fixer_util.py
python
find_indentation
(node)
return u""
Find the indentation of *node*.
Find the indentation of *node*.
[ "Find", "the", "indentation", "of", "*", "node", "*", "." ]
def find_indentation(node): """Find the indentation of *node*.""" while node is not None: if node.type == syms.suite and len(node.children) > 2: indent = node.children[1] if indent.type == token.INDENT: return indent.value node = node.parent return u""
[ "def", "find_indentation", "(", "node", ")", ":", "while", "node", "is", "not", "None", ":", "if", "node", ".", "type", "==", "syms", ".", "suite", "and", "len", "(", "node", ".", "children", ")", ">", "2", ":", "indent", "=", "node", ".", "childre...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/lib2to3/fixer_util.py#L250-L258
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/random.py
python
WichmannHill.random
(self)
return (x / 30269.0 + y / 30307.0 + z / 30323.0) % 1.0
Get the next random number in the range [0.0, 1.0).
Get the next random number in the range [0.0, 1.0).
[ "Get", "the", "next", "random", "number", "in", "the", "range", "[", "0", ".", "0", "1", ".", "0", ")", "." ]
def random(self): """Get the next random number in the range [0.0, 1.0).""" x, y, z = self._seed x = 171 * x % 30269 y = 172 * y % 30307 z = 170 * z % 30323 self._seed = (x, y, z) return (x / 30269.0 + y / 30307.0 + z / 30323.0) % 1.0
[ "def", "random", "(", "self", ")", ":", "x", ",", "y", ",", "z", "=", "self", ".", "_seed", "x", "=", "171", "*", "x", "%", "30269", "y", "=", "172", "*", "y", "%", "30307", "z", "=", "170", "*", "z", "%", "30323", "self", ".", "_seed", "...
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/random.py#L526-L533
007gzs/dingtalk-sdk
7979da2e259fdbc571728cae2425a04dbc65850a
dingtalk/client/api/taobao.py
python
TbBaiChuan.taobao_baichuan_openaccount_registercode_send
( self, name='' )
return self._top_request( "taobao.baichuan.openaccount.registercode.send", { "name": name }, result_processor=lambda x: x["name"] )
百川发送注册验证码 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=25130 :param name: name
百川发送注册验证码 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=25130
[ "百川发送注册验证码", "文档地址:https", ":", "//", "open", "-", "doc", ".", "dingtalk", ".", "com", "/", "docs", "/", "api", ".", "htm?apiId", "=", "25130" ]
def taobao_baichuan_openaccount_registercode_send( self, name='' ): """ 百川发送注册验证码 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=25130 :param name: name """ return self._top_request( "taobao.baichuan.openaccount.registercode.send", { "name": name }, result_processor=lambda x: x["name"] )
[ "def", "taobao_baichuan_openaccount_registercode_send", "(", "self", ",", "name", "=", "''", ")", ":", "return", "self", ".", "_top_request", "(", "\"taobao.baichuan.openaccount.registercode.send\"", ",", "{", "\"name\"", ":", "name", "}", ",", "result_processor", "="...
https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L56274-L56290
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/build/lib.linux-x86_64-2.7/flaskbb/themes/aurora/build_emoji_set.py
python
get_annotations
()
[]
def get_annotations(): resp = requests.get(URL) resp.raise_for_status() for line in resp.text.split('\n'): match = re.match('(.+?); fully-qualified +?# .+? (.+)', line) if match is not None: yield ( ''.join(chr(int(h, 16)) for h in match.group(1).strip().split(' ')), match.group(2) )
[ "def", "get_annotations", "(", ")", ":", "resp", "=", "requests", ".", "get", "(", "URL", ")", "resp", ".", "raise_for_status", "(", ")", "for", "line", "in", "resp", ".", "text", ".", "split", "(", "'\\n'", ")", ":", "match", "=", "re", ".", "matc...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/build/lib.linux-x86_64-2.7/flaskbb/themes/aurora/build_emoji_set.py#L10-L21
ganglia/gmond_python_modules
2f7fcab3d27926ef4a2feb1b53c09af16a43e729
beanstalk/python_modules/beanstalk.py
python
tube_stat_handler
(name)
return bean.stats_tube(name.split('_')[0])[name.split('_')[1]]
[]
def tube_stat_handler(name): bean=beanstalkc.Connection(host=HOST,port=PORT) return bean.stats_tube(name.split('_')[0])[name.split('_')[1]]
[ "def", "tube_stat_handler", "(", "name", ")", ":", "bean", "=", "beanstalkc", ".", "Connection", "(", "host", "=", "HOST", ",", "port", "=", "PORT", ")", "return", "bean", ".", "stats_tube", "(", "name", ".", "split", "(", "'_'", ")", "[", "0", "]", ...
https://github.com/ganglia/gmond_python_modules/blob/2f7fcab3d27926ef4a2feb1b53c09af16a43e729/beanstalk/python_modules/beanstalk.py#L11-L13
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/zipfile.py
python
PyZipFile._get_codename
(self, pathname, basename)
return (fname, archivename)
Return (filename, archivename) for the path. Given a module name path, return the correct file path and archive name, compiling if necessary. For example, given /python/lib/string, return (/python/lib/string.pyc, string).
Return (filename, archivename) for the path.
[ "Return", "(", "filename", "archivename", ")", "for", "the", "path", "." ]
def _get_codename(self, pathname, basename): """Return (filename, archivename) for the path. Given a module name path, return the correct file path and archive name, compiling if necessary. For example, given /python/lib/string, return (/python/lib/string.pyc, string). """ def _compile(file, optimize=-1): import py_compile if self.debug: print("Compiling", file) try: py_compile.compile(file, doraise=True, optimize=optimize) except py_compile.PyCompileError as err: print(err.msg) return False return True file_py = pathname + ".py" file_pyc = pathname + ".pyc" pycache_opt0 = importlib.util.cache_from_source(file_py, optimization='') pycache_opt1 = importlib.util.cache_from_source(file_py, optimization=1) pycache_opt2 = importlib.util.cache_from_source(file_py, optimization=2) if self._optimize == -1: # legacy mode: use whatever file is present if (os.path.isfile(file_pyc) and os.stat(file_pyc).st_mtime >= os.stat(file_py).st_mtime): # Use .pyc file. arcname = fname = file_pyc elif (os.path.isfile(pycache_opt0) and os.stat(pycache_opt0).st_mtime >= os.stat(file_py).st_mtime): # Use the __pycache__/*.pyc file, but write it to the legacy pyc # file name in the archive. fname = pycache_opt0 arcname = file_pyc elif (os.path.isfile(pycache_opt1) and os.stat(pycache_opt1).st_mtime >= os.stat(file_py).st_mtime): # Use the __pycache__/*.pyc file, but write it to the legacy pyc # file name in the archive. fname = pycache_opt1 arcname = file_pyc elif (os.path.isfile(pycache_opt2) and os.stat(pycache_opt2).st_mtime >= os.stat(file_py).st_mtime): # Use the __pycache__/*.pyc file, but write it to the legacy pyc # file name in the archive. fname = pycache_opt2 arcname = file_pyc else: # Compile py into PEP 3147 pyc file. if _compile(file_py): if sys.flags.optimize == 0: fname = pycache_opt0 elif sys.flags.optimize == 1: fname = pycache_opt1 else: fname = pycache_opt2 arcname = file_pyc else: fname = arcname = file_py else: # new mode: use given optimization level if self._optimize == 0: fname = pycache_opt0 arcname = file_pyc else: arcname = file_pyc if self._optimize == 1: fname = pycache_opt1 elif self._optimize == 2: fname = pycache_opt2 else: msg = "invalid value for 'optimize': {!r}".format(self._optimize) raise ValueError(msg) if not (os.path.isfile(fname) and os.stat(fname).st_mtime >= os.stat(file_py).st_mtime): if not _compile(file_py, optimize=self._optimize): fname = arcname = file_py archivename = os.path.split(arcname)[1] if basename: archivename = "%s/%s" % (basename, archivename) return (fname, archivename)
[ "def", "_get_codename", "(", "self", ",", "pathname", ",", "basename", ")", ":", "def", "_compile", "(", "file", ",", "optimize", "=", "-", "1", ")", ":", "import", "py_compile", "if", "self", ".", "debug", ":", "print", "(", "\"Compiling\"", ",", "fil...
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/zipfile.py#L1912-L1992
researchmm/tasn
5dba8ccc096cedc63913730eeea14a9647911129
tasn-mxnet/example/ctc/ctc_metrics.py
python
CtcMetrics._remove_blank
(l)
return ret
Removes trailing zeros in the list of integers and returns a new list of integers
Removes trailing zeros in the list of integers and returns a new list of integers
[ "Removes", "trailing", "zeros", "in", "the", "list", "of", "integers", "and", "returns", "a", "new", "list", "of", "integers" ]
def _remove_blank(l): """ Removes trailing zeros in the list of integers and returns a new list of integers""" ret = [] for i, _ in enumerate(l): if l[i] == 0: break ret.append(l[i]) return ret
[ "def", "_remove_blank", "(", "l", ")", ":", "ret", "=", "[", "]", "for", "i", ",", "_", "in", "enumerate", "(", "l", ")", ":", "if", "l", "[", "i", "]", "==", "0", ":", "break", "ret", ".", "append", "(", "l", "[", "i", "]", ")", "return", ...
https://github.com/researchmm/tasn/blob/5dba8ccc096cedc63913730eeea14a9647911129/tasn-mxnet/example/ctc/ctc_metrics.py#L51-L58
beancount/fava
69614956d3c01074403af0a07ddbaa986cf602a0
src/fava/application.py
python
fava_api_exception
(error: FavaAPIException)
return render_template( "_layout.html", page_title="Error", content=error.message )
Handle API errors.
Handle API errors.
[ "Handle", "API", "errors", "." ]
def fava_api_exception(error: FavaAPIException) -> str: """Handle API errors.""" return render_template( "_layout.html", page_title="Error", content=error.message )
[ "def", "fava_api_exception", "(", "error", ":", "FavaAPIException", ")", "->", "str", ":", "return", "render_template", "(", "\"_layout.html\"", ",", "page_title", "=", "\"Error\"", ",", "content", "=", "error", ".", "message", ")" ]
https://github.com/beancount/fava/blob/69614956d3c01074403af0a07ddbaa986cf602a0/src/fava/application.py#L265-L269
nussl/nussl
471e7965c5788bff9fe2e1f7884537cae2d18e6f
nussl/core/audio_signal.py
python
AudioSignal.get_magnitude_spectrogram_channel
(self, n)
return utils._get_axis(np.array(self.magnitude_spectrogram_data), constants.STFT_CHAN_INDEX, n)
Returns the n-th channel from ``self.magnitude_spectrogram_data``. Raises: Exception: If not ``0 <= n < self.num_channels``. Args: n: (int) index of magnitude spectrogram channel to get **0-based** Returns: (:obj:`np.array`): the magnitude spectrogram data in the n-th channel of the signal, 1D
Returns the n-th channel from ``self.magnitude_spectrogram_data``.
[ "Returns", "the", "n", "-", "th", "channel", "from", "self", ".", "magnitude_spectrogram_data", "." ]
def get_magnitude_spectrogram_channel(self, n): """ Returns the n-th channel from ``self.magnitude_spectrogram_data``. Raises: Exception: If not ``0 <= n < self.num_channels``. Args: n: (int) index of magnitude spectrogram channel to get **0-based** Returns: (:obj:`np.array`): the magnitude spectrogram data in the n-th channel of the signal, 1D """ self._verify_get_channel(n) # np.array helps with duck typing return utils._get_axis(np.array(self.magnitude_spectrogram_data), constants.STFT_CHAN_INDEX, n)
[ "def", "get_magnitude_spectrogram_channel", "(", "self", ",", "n", ")", ":", "self", ".", "_verify_get_channel", "(", "n", ")", "# np.array helps with duck typing", "return", "utils", ".", "_get_axis", "(", "np", ".", "array", "(", "self", ".", "magnitude_spectrog...
https://github.com/nussl/nussl/blob/471e7965c5788bff9fe2e1f7884537cae2d18e6f/nussl/core/audio_signal.py#L1631-L1647
shmilylty/OneForAll
48591142a641e80f8a64ab215d11d06b696702d7
modules/check/axfr.py
python
AXFR.axfr
(self, server)
Perform domain transfer :param server: domain server
Perform domain transfer
[ "Perform", "domain", "transfer" ]
def axfr(self, server): """ Perform domain transfer :param server: domain server """ logger.log('DEBUG', f'Trying to perform domain transfer in {server} ' f'of {self.domain}') try: xfr = dns.query.xfr(where=server, zone=self.domain, timeout=5.0, lifetime=10.0) zone = dns.zone.from_xfr(xfr) except Exception as e: logger.log('DEBUG', e.args) logger.log('DEBUG', f'Domain transfer to server {server} of ' f'{self.domain} failed') return names = zone.nodes.keys() for name in names: full_domain = str(name) + '.' + self.domain subdomain = self.match_subdomains(full_domain) self.subdomains.update(subdomain) record = zone[name].to_text(name) self.results.append(record) if self.results: logger.log('DEBUG', f'Found the domain transfer record of ' f'{self.domain} on {server}') logger.log('DEBUG', '\n'.join(self.results)) self.results = []
[ "def", "axfr", "(", "self", ",", "server", ")", ":", "logger", ".", "log", "(", "'DEBUG'", ",", "f'Trying to perform domain transfer in {server} '", "f'of {self.domain}'", ")", "try", ":", "xfr", "=", "dns", ".", "query", ".", "xfr", "(", "where", "=", "serv...
https://github.com/shmilylty/OneForAll/blob/48591142a641e80f8a64ab215d11d06b696702d7/modules/check/axfr.py#L26-L54
phimpme/phimpme-generator
ba6d11190b9016238f27672e1ad55e6a875b74a0
Phimpme/site-packages/mock.py
python
NonCallableMock.assert_called_once_with
(_mock_self, *args, **kwargs)
return self.assert_called_with(*args, **kwargs)
assert that the mock was called exactly once and with the specified arguments.
assert that the mock was called exactly once and with the specified arguments.
[ "assert", "that", "the", "mock", "was", "called", "exactly", "once", "and", "with", "the", "specified", "arguments", "." ]
def assert_called_once_with(_mock_self, *args, **kwargs): """assert that the mock was called exactly once and with the specified arguments.""" self = _mock_self if not self.call_count == 1: msg = ("Expected to be called once. Called %s times." % self.call_count) raise AssertionError(msg) return self.assert_called_with(*args, **kwargs)
[ "def", "assert_called_once_with", "(", "_mock_self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "_mock_self", "if", "not", "self", ".", "call_count", "==", "1", ":", "msg", "=", "(", "\"Expected to be called once. Called %s times.\"", "%...
https://github.com/phimpme/phimpme-generator/blob/ba6d11190b9016238f27672e1ad55e6a875b74a0/Phimpme/site-packages/mock.py#L838-L846
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/rings/polynomial/groebner_fan.py
python
PolyhedralFan.to_RationalPolyhedralFan
(self)
Converts to the RationalPolyhedralFan class, which is more actively maintained. While the information in each class is essentially the same, the methods and implementation are different. EXAMPLES:: sage: R.<x,y,z> = QQ[] sage: f = 1+x+y+x*y sage: I = R.ideal([f+z*f, 2*f+z*f, 3*f+z^2*f]) sage: GF = I.groebner_fan() sage: PF = GF.tropical_intersection() sage: fan = PF.to_RationalPolyhedralFan() sage: [tuple(q.facet_normals()) for q in fan] [(M(0, -1, 0), M(-1, 0, 0)), (M(0, 0, -1), M(-1, 0, 0)), (M(0, 0, 1), M(-1, 0, 0)), (M(0, 1, 0), M(-1, 0, 0)), (M(0, 0, -1), M(0, -1, 0)), (M(0, 0, 1), M(0, -1, 0)), (M(0, 1, 0), M(0, 0, -1)), (M(0, 1, 0), M(0, 0, 1)), (M(1, 0, 0), M(0, -1, 0)), (M(1, 0, 0), M(0, 0, -1)), (M(1, 0, 0), M(0, 0, 1)), (M(1, 0, 0), M(0, 1, 0))] Here we use the RationalPolyhedralFan's Gale_transform method on a tropical prevariety. .. link :: sage: fan.Gale_transform() [ 1 0 0 0 0 1 -2] [ 0 1 0 0 1 0 -2] [ 0 0 1 1 0 0 -2]
Converts to the RationalPolyhedralFan class, which is more actively maintained. While the information in each class is essentially the same, the methods and implementation are different.
[ "Converts", "to", "the", "RationalPolyhedralFan", "class", "which", "is", "more", "actively", "maintained", ".", "While", "the", "information", "in", "each", "class", "is", "essentially", "the", "same", "the", "methods", "and", "implementation", "are", "different"...
def to_RationalPolyhedralFan(self): """ Converts to the RationalPolyhedralFan class, which is more actively maintained. While the information in each class is essentially the same, the methods and implementation are different. EXAMPLES:: sage: R.<x,y,z> = QQ[] sage: f = 1+x+y+x*y sage: I = R.ideal([f+z*f, 2*f+z*f, 3*f+z^2*f]) sage: GF = I.groebner_fan() sage: PF = GF.tropical_intersection() sage: fan = PF.to_RationalPolyhedralFan() sage: [tuple(q.facet_normals()) for q in fan] [(M(0, -1, 0), M(-1, 0, 0)), (M(0, 0, -1), M(-1, 0, 0)), (M(0, 0, 1), M(-1, 0, 0)), (M(0, 1, 0), M(-1, 0, 0)), (M(0, 0, -1), M(0, -1, 0)), (M(0, 0, 1), M(0, -1, 0)), (M(0, 1, 0), M(0, 0, -1)), (M(0, 1, 0), M(0, 0, 1)), (M(1, 0, 0), M(0, -1, 0)), (M(1, 0, 0), M(0, 0, -1)), (M(1, 0, 0), M(0, 0, 1)), (M(1, 0, 0), M(0, 1, 0))] Here we use the RationalPolyhedralFan's Gale_transform method on a tropical prevariety. .. link :: sage: fan.Gale_transform() [ 1 0 0 0 0 1 -2] [ 0 1 0 0 1 0 -2] [ 0 0 1 1 0 0 -2] """ try: return self._fan except AttributeError: cdnt = [] cones = self.cones() for x in cones: if x > 1: cdnt += cones[x] fan = Fan(cones=cdnt, rays=self.rays(), discard_faces=True) self._fan = fan return self._fan
[ "def", "to_RationalPolyhedralFan", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_fan", "except", "AttributeError", ":", "cdnt", "=", "[", "]", "cones", "=", "self", ".", "cones", "(", ")", "for", "x", "in", "cones", ":", "if", "x", ">",...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/polynomial/groebner_fan.py#L494-L534
deluge-torrent/deluge
2316088f5c0dd6cb044d9d4832fa7d56dcc79cdc
deluge/ui/console/modes/cmdline.py
python
CmdLine.tab_completer
(self, line, cursor, hits)
Called when the user hits 'tab' and will autocomplete or show options. If a command is already supplied in the line, this function will call the complete method of the command. :param line: str, the current input string :param cursor: int, the cursor position in the line :param second_hit: bool, if this is the second time in a row the tab key has been pressed :returns: 2-tuple (string, cursor position)
Called when the user hits 'tab' and will autocomplete or show options. If a command is already supplied in the line, this function will call the complete method of the command.
[ "Called", "when", "the", "user", "hits", "tab", "and", "will", "autocomplete", "or", "show", "options", ".", "If", "a", "command", "is", "already", "supplied", "in", "the", "line", "this", "function", "will", "call", "the", "complete", "method", "of", "the...
def tab_completer(self, line, cursor, hits): """ Called when the user hits 'tab' and will autocomplete or show options. If a command is already supplied in the line, this function will call the complete method of the command. :param line: str, the current input string :param cursor: int, the cursor position in the line :param second_hit: bool, if this is the second time in a row the tab key has been pressed :returns: 2-tuple (string, cursor position) """ # First check to see if there is no space, this will mean that it's a # command that needs to be completed. # We don't want to split by escaped spaces def split(string): return re.split(r'(?<!\\) ', string) if ' ' not in line: possible_matches = [] # Iterate through the commands looking for ones that startwith the # line. for cmd in self.console._commands: if cmd.startswith(line): possible_matches.append(cmd) line_prefix = '' else: cmd = split(line)[0] if cmd in self.console._commands: # Call the command's complete method to get 'er done possible_matches = self.console._commands[cmd].complete(split(line)[-1]) line_prefix = ' '.join(split(line)[:-1]) + ' ' else: # This is a bogus command return (line, cursor) # No matches, so just return what we got passed if len(possible_matches) == 0: return (line, cursor) # If we only have 1 possible match, then just modify the line and # return it, else we need to print out the matches without modifying # the line. elif len(possible_matches) == 1: # Do not append space after directory names new_line = line_prefix + possible_matches[0] if not new_line.endswith('/') and not new_line.endswith(r'\\'): new_line += ' ' # We only want to print eventual colors or other control characters, not return them new_line = remove_formatting(new_line) return (new_line, len(new_line)) else: if hits == 1: p = ' '.join(split(line)[:-1]) try: l_arg = split(line)[-1] except IndexError: l_arg = '' new_line = ' '.join( [p, complete_line(l_arg, possible_matches)] ).lstrip() if len(remove_formatting(new_line)) > len(line): line = new_line cursor = len(line) elif hits >= 2: max_list = self.console_config['cmdline']['torrents_per_tab_press'] match_count = len(possible_matches) listed = (hits - 2) * max_list pages = (match_count - 1) // max_list + 1 left = match_count - listed if hits == 2: self.write(' ') if match_count >= 4: self.write('{!green!}Autocompletion matches:') # Only list some of the matching torrents as there can be hundreds of them if self.console_config['cmdline']['third_tab_lists_all']: if hits == 2 and left > max_list: for i in range(listed, listed + max_list): match = possible_matches[i] self.write(match.replace(r'\ ', ' ')) self.write( '{!error!}And %i more. Press <tab> to list them' % (left - max_list) ) else: self.tab_count = 0 for match in possible_matches[listed:]: self.write(match.replace(r'\ ', ' ')) else: if left > max_list: for i in range(listed, listed + max_list): match = possible_matches[i] self.write(match.replace(r'\ ', ' ')) self.write( '{!error!}And %i more (%i/%i). Press <tab> to view more' % (left - max_list, hits - 1, pages) ) else: self.tab_count = 0 for match in possible_matches[listed:]: self.write(match.replace(r'\ ', ' ')) if hits > 2: self.write( '{!green!}Finished listing %i torrents (%i/%i)' % (match_count, hits - 1, pages) ) # We only want to print eventual colors or other control characters, not return them line = remove_formatting(line) cursor = len(line) return (line, cursor)
[ "def", "tab_completer", "(", "self", ",", "line", ",", "cursor", ",", "hits", ")", ":", "# First check to see if there is no space, this will mean that it's a", "# command that needs to be completed.", "# We don't want to split by escaped spaces", "def", "split", "(", "string", ...
https://github.com/deluge-torrent/deluge/blob/2316088f5c0dd6cb044d9d4832fa7d56dcc79cdc/deluge/ui/console/modes/cmdline.py#L576-L693
Kozea/Radicale
8fa4345b6ffb32cd44154d64bba2caf28d54f214
radicale/web/internal.py
python
Web.__init__
(self, configuration: config.Configuration)
[]
def __init__(self, configuration: config.Configuration) -> None: super().__init__(configuration) self.folder = pkg_resources.resource_filename(__name__, "internal_data")
[ "def", "__init__", "(", "self", ",", "configuration", ":", "config", ".", "Configuration", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "configuration", ")", "self", ".", "folder", "=", "pkg_resources", ".", "resource_filename", "(", "_...
https://github.com/Kozea/Radicale/blob/8fa4345b6ffb32cd44154d64bba2caf28d54f214/radicale/web/internal.py#L61-L64
wbond/package_control
cfaaeb57612023e3679ecb7f8cd7ceac9f57990d
package_control/clients/github_client.py
python
GitHubClient.repo_info
(self, url)
return output
Retrieve general information about a repository :param url: The URL to the repository, in one of the forms: https://github.com/{user}/{repo} https://github.com/{user}/{repo}/tree/{branch} :raises: DownloaderException: when there is an error downloading ClientException: when there is an error parsing the response :return: None if no match, or a dict with the following keys: `name` `description` `homepage` - URL of the homepage `author` `readme` - URL of the readme `issues` - URL of bug tracker `donate` - URL of a donate page
Retrieve general information about a repository
[ "Retrieve", "general", "information", "about", "a", "repository" ]
def repo_info(self, url): """ Retrieve general information about a repository :param url: The URL to the repository, in one of the forms: https://github.com/{user}/{repo} https://github.com/{user}/{repo}/tree/{branch} :raises: DownloaderException: when there is an error downloading ClientException: when there is an error parsing the response :return: None if no match, or a dict with the following keys: `name` `description` `homepage` - URL of the homepage `author` `readme` - URL of the readme `issues` - URL of bug tracker `donate` - URL of a donate page """ user_repo, branch = self._user_repo_branch(url) if not user_repo: return user_repo api_url = self._make_api_url(user_repo) info = self.fetch_json(api_url) if branch is None: branch = info.get('default_branch', 'master') output = self._extract_repo_info(info) output['readme'] = None readme_info = self._readme_info(user_repo, branch) if not readme_info: return output output['readme'] = 'https://raw.githubusercontent.com/%s/%s/%s' % ( user_repo, branch, readme_info['path']) return output
[ "def", "repo_info", "(", "self", ",", "url", ")", ":", "user_repo", ",", "branch", "=", "self", ".", "_user_repo_branch", "(", "url", ")", "if", "not", "user_repo", ":", "return", "user_repo", "api_url", "=", "self", ".", "_make_api_url", "(", "user_repo",...
https://github.com/wbond/package_control/blob/cfaaeb57612023e3679ecb7f8cd7ceac9f57990d/package_control/clients/github_client.py#L143-L186
StanfordVL/ReferringRelationships
61e04c1ccad6a7f7dcbc07562ef68546ba4063cf
utils/visualization_utils.py
python
add_bbox_to_image
(image, bbox, color='red', width=3)
return output
Adds a bounding box to the image. Args: image: A PIL image. bbox: (ymin, ymax, xmin, xmax) box. color: Color to draw the box with. Returns: A PIL image with the bounding box drawn.
Adds a bounding box to the image.
[ "Adds", "a", "bounding", "box", "to", "the", "image", "." ]
def add_bbox_to_image(image, bbox, color='red', width=3): """Adds a bounding box to the image. Args: image: A PIL image. bbox: (ymin, ymax, xmin, xmax) box. color: Color to draw the box with. Returns: A PIL image with the bounding box drawn. """ output = image.copy() ymin, ymax, xmin, xmax = bbox draw = ImageDraw.Draw(output) for i in range(width): draw.rectangle(((xmin+i, ymin+i), (xmax+i, ymax+i)), outline=color) return output
[ "def", "add_bbox_to_image", "(", "image", ",", "bbox", ",", "color", "=", "'red'", ",", "width", "=", "3", ")", ":", "output", "=", "image", ".", "copy", "(", ")", "ymin", ",", "ymax", ",", "xmin", ",", "xmax", "=", "bbox", "draw", "=", "ImageDraw"...
https://github.com/StanfordVL/ReferringRelationships/blob/61e04c1ccad6a7f7dcbc07562ef68546ba4063cf/utils/visualization_utils.py#L58-L74
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/asyncore.py
python
dispatcher.readable
(self)
return True
[]
def readable(self): return True
[ "def", "readable", "(", "self", ")", ":", "return", "True" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/asyncore.py#L308-L309
sqlalchemy/sqlalchemy
eb716884a4abcabae84a6aaba105568e925b7d27
lib/sqlalchemy/sql/selectable.py
python
Select.except_
(self, *other, **kwargs)
return CompoundSelect._create_except(self, *other, **kwargs)
r"""Return a SQL ``EXCEPT`` of this select() construct against the given selectable provided as positional arguments. :param \*other: one or more elements with which to create a UNION. .. versionchanged:: 1.4.28 multiple elements are now accepted. :param \**kwargs: keyword arguments are forwarded to the constructor for the newly created :class:`_sql.CompoundSelect` object.
r"""Return a SQL ``EXCEPT`` of this select() construct against the given selectable provided as positional arguments.
[ "r", "Return", "a", "SQL", "EXCEPT", "of", "this", "select", "()", "construct", "against", "the", "given", "selectable", "provided", "as", "positional", "arguments", "." ]
def except_(self, *other, **kwargs): r"""Return a SQL ``EXCEPT`` of this select() construct against the given selectable provided as positional arguments. :param \*other: one or more elements with which to create a UNION. .. versionchanged:: 1.4.28 multiple elements are now accepted. :param \**kwargs: keyword arguments are forwarded to the constructor for the newly created :class:`_sql.CompoundSelect` object. """ return CompoundSelect._create_except(self, *other, **kwargs)
[ "def", "except_", "(", "self", ",", "*", "other", ",", "*", "*", "kwargs", ")", ":", "return", "CompoundSelect", ".", "_create_except", "(", "self", ",", "*", "other", ",", "*", "*", "kwargs", ")" ]
https://github.com/sqlalchemy/sqlalchemy/blob/eb716884a4abcabae84a6aaba105568e925b7d27/lib/sqlalchemy/sql/selectable.py#L5253-L5268
canonical/cloud-init
dc1aabfca851e520693c05322f724bd102c76364
cloudinit/sources/DataSourceVMware.py
python
guestinfo_set_value
(key, value, vmware_rpctool=VMWARE_RPCTOOL)
return None
Sets a guestinfo value for the specified key. Set value to an empty string to clear an existing guestinfo key.
Sets a guestinfo value for the specified key. Set value to an empty string to clear an existing guestinfo key.
[ "Sets", "a", "guestinfo", "value", "for", "the", "specified", "key", ".", "Set", "value", "to", "an", "empty", "string", "to", "clear", "an", "existing", "guestinfo", "key", "." ]
def guestinfo_set_value(key, value, vmware_rpctool=VMWARE_RPCTOOL): """ Sets a guestinfo value for the specified key. Set value to an empty string to clear an existing guestinfo key. """ # If value is an empty string then set it to a single space as it is not # possible to set a guestinfo key to an empty string. Setting a guestinfo # key to a single space is as close as it gets to clearing an existing # guestinfo key. if value == "": value = " " LOG.debug("Setting guestinfo key=%s to value=%s", key, value) try: subp( [ vmware_rpctool, "info-set %s %s" % (get_guestinfo_key_name(key), value), ] ) return True except ProcessExecutionError as error: util.logexc( LOG, "Failed to set guestinfo key=%s to value=%s: %s", key, value, error, ) except Exception: util.logexc( LOG, "Unexpected error while trying to set " + "guestinfo key=%s to value=%s", key, value, ) return None
[ "def", "guestinfo_set_value", "(", "key", ",", "value", ",", "vmware_rpctool", "=", "VMWARE_RPCTOOL", ")", ":", "# If value is an empty string then set it to a single space as it is not", "# possible to set a guestinfo key to an empty string. Setting a guestinfo", "# key to a single spac...
https://github.com/canonical/cloud-init/blob/dc1aabfca851e520693c05322f724bd102c76364/cloudinit/sources/DataSourceVMware.py#L443-L483