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
smicallef/spiderfoot
fd4bf9394c9ab3ecc90adc3115c56349fb23165b
modules/sfp_dnsbrute.py
python
sfp_dnsbrute.tryHostWrapper
(self, hostList, sourceEvent)
[]
def tryHostWrapper(self, hostList, sourceEvent): self.hostResults = dict() running = True i = 0 t = [] # Spawn threads for scanning self.info("Spawning threads to check hosts: " + str(hostList)) for name in hostList: tn = 'thread_sfp_dnsbrute_' + str(random.SystemRandom().randint(1, 999999999)) t.append(threading.Thread(name=tn, target=self.tryHost, args=(name,))) t[i].start() i += 1 # Block until all threads are finished while running: found = False for rt in threading.enumerate(): if rt.name.startswith("thread_sfp_dnsbrute_"): found = True if not found: running = False time.sleep(0.05) for res in self.hostResults: if self.hostResults.get(res, False): self.sendEvent(sourceEvent, res)
[ "def", "tryHostWrapper", "(", "self", ",", "hostList", ",", "sourceEvent", ")", ":", "self", ".", "hostResults", "=", "dict", "(", ")", "running", "=", "True", "i", "=", "0", "t", "=", "[", "]", "# Spawn threads for scanning", "self", ".", "info", "(", ...
https://github.com/smicallef/spiderfoot/blob/fd4bf9394c9ab3ecc90adc3115c56349fb23165b/modules/sfp_dnsbrute.py#L106-L134
bikalims/bika.lims
35e4bbdb5a3912cae0b5eb13e51097c8b0486349
bika/lims/browser/reports/selection_macros/__init__.py
python
SelectionMacrosView.parse_state
(self, request, workflow_id, field_id, field_title)
[]
def parse_state(self, request, workflow_id, field_id, field_title): val = request.form.get(field_id, "") states = self.portal_workflow[workflow_id].states if val in states: state_title = states[val].title res = {} res['contentFilter'] = (field_id, val) res['parms'] = {'title': _('State'), 'value': state_title} res['titles'] = state_title return res
[ "def", "parse_state", "(", "self", ",", "request", ",", "workflow_id", ",", "field_id", ",", "field_title", ")", ":", "val", "=", "request", ".", "form", ".", "get", "(", "field_id", ",", "\"\"", ")", "states", "=", "self", ".", "portal_workflow", "[", ...
https://github.com/bikalims/bika.lims/blob/35e4bbdb5a3912cae0b5eb13e51097c8b0486349/bika/lims/browser/reports/selection_macros/__init__.py#L237-L246
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/_vendor/requests/utils.py
python
get_netrc_auth
(url, raise_errors=False)
Returns the Requests tuple auth for a given url from netrc.
Returns the Requests tuple auth for a given url from netrc.
[ "Returns", "the", "Requests", "tuple", "auth", "for", "a", "given", "url", "from", "netrc", "." ]
def get_netrc_auth(url, raise_errors=False): """Returns the Requests tuple auth for a given url from netrc.""" netrc_file = os.environ.get('NETRC') if netrc_file is not None: netrc_locations = (netrc_file,) else: netrc_locations = ('~/{}'.format(f) for f in NETRC_FILES) try: from netrc import netrc, NetrcParseError netrc_path = None for f in netrc_locations: try: loc = os.path.expanduser(f) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See https://bugs.python.org/issue20164 & # https://github.com/psf/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc. This weird `if...encode`` dance is # used for Python 3.2, which doesn't support unicode literals. splitstr = b':' if isinstance(url, str): splitstr = splitstr.decode('ascii') host = ri.netloc.split(splitstr)[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth unless explicitly asked to raise errors. if raise_errors: raise # App Engine hackiness. except (ImportError, AttributeError): pass
[ "def", "get_netrc_auth", "(", "url", ",", "raise_errors", "=", "False", ")", ":", "netrc_file", "=", "os", ".", "environ", ".", "get", "(", "'NETRC'", ")", "if", "netrc_file", "is", "not", "None", ":", "netrc_locations", "=", "(", "netrc_file", ",", ")",...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/_vendor/requests/utils.py#L174-L228
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/_pydecimal.py
python
_insert_thousands_sep
(digits, spec, min_width=1)
return sep.join(reversed(groups))
Insert thousands separators into a digit string. spec is a dictionary whose keys should include 'thousands_sep' and 'grouping'; typically it's the result of parsing the format specifier using _parse_format_specifier. The min_width keyword argument gives the minimum length of the result, which will be padded on the left with zeros if necessary. If necessary, the zero padding adds an extra '0' on the left to avoid a leading thousands separator. For example, inserting commas every three digits in '123456', with min_width=8, gives '0,123,456', even though that has length 9.
Insert thousands separators into a digit string.
[ "Insert", "thousands", "separators", "into", "a", "digit", "string", "." ]
def _insert_thousands_sep(digits, spec, min_width=1): """Insert thousands separators into a digit string. spec is a dictionary whose keys should include 'thousands_sep' and 'grouping'; typically it's the result of parsing the format specifier using _parse_format_specifier. The min_width keyword argument gives the minimum length of the result, which will be padded on the left with zeros if necessary. If necessary, the zero padding adds an extra '0' on the left to avoid a leading thousands separator. For example, inserting commas every three digits in '123456', with min_width=8, gives '0,123,456', even though that has length 9. """ sep = spec['thousands_sep'] grouping = spec['grouping'] groups = [] for l in _group_lengths(grouping): if l <= 0: raise ValueError("group length should be positive") # max(..., 1) forces at least 1 digit to the left of a separator l = min(max(len(digits), min_width, 1), l) groups.append('0'*(l - len(digits)) + digits[-l:]) digits = digits[:-l] min_width -= l if not digits and min_width <= 0: break min_width -= len(sep) else: l = max(len(digits), min_width, 1) groups.append('0'*(l - len(digits)) + digits[-l:]) return sep.join(reversed(groups))
[ "def", "_insert_thousands_sep", "(", "digits", ",", "spec", ",", "min_width", "=", "1", ")", ":", "sep", "=", "spec", "[", "'thousands_sep'", "]", "grouping", "=", "spec", "[", "'grouping'", "]", "groups", "=", "[", "]", "for", "l", "in", "_group_lengths...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/_pydecimal.py#L6303-L6338
LinkedInAttic/indextank-service
880c6295ce8e7a3a55bf9b3777cc35c7680e0d7e
nebu/flaptor/indextank/rpc/Indexer.py
python
Client.updateTimestampBoost
(self, docid, timestamp_boost)
Parameters: - docid - timestamp_boost
Parameters: - docid - timestamp_boost
[ "Parameters", ":", "-", "docid", "-", "timestamp_boost" ]
def updateTimestampBoost(self, docid, timestamp_boost): """ Parameters: - docid - timestamp_boost """ self.send_updateTimestampBoost(docid, timestamp_boost) self.recv_updateTimestampBoost()
[ "def", "updateTimestampBoost", "(", "self", ",", "docid", ",", "timestamp_boost", ")", ":", "self", ".", "send_updateTimestampBoost", "(", "docid", ",", "timestamp_boost", ")", "self", ".", "recv_updateTimestampBoost", "(", ")" ]
https://github.com/LinkedInAttic/indextank-service/blob/880c6295ce8e7a3a55bf9b3777cc35c7680e0d7e/nebu/flaptor/indextank/rpc/Indexer.py#L151-L158
Netflix/lemur
3468be93cc84ba7a29f789155763d087ef68b7fe
lemur/dns_providers/service.py
python
render
(args)
return database.sort_and_page(query, DnsProvider, args)
Helper that helps us render the REST Api responses. :param args: :return:
Helper that helps us render the REST Api responses. :param args: :return:
[ "Helper", "that", "helps", "us", "render", "the", "REST", "Api", "responses", ".", ":", "param", "args", ":", ":", "return", ":" ]
def render(args): """ Helper that helps us render the REST Api responses. :param args: :return: """ query = database.session_query(DnsProvider) return database.sort_and_page(query, DnsProvider, args)
[ "def", "render", "(", "args", ")", ":", "query", "=", "database", ".", "session_query", "(", "DnsProvider", ")", "return", "database", ".", "sort_and_page", "(", "query", ",", "DnsProvider", ",", "args", ")" ]
https://github.com/Netflix/lemur/blob/3468be93cc84ba7a29f789155763d087ef68b7fe/lemur/dns_providers/service.py#L10-L18
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/distutils/ccompiler.py
python
CCompiler.move_file
(self, src, dst)
return move_file(src, dst, dry_run=self.dry_run)
[]
def move_file(self, src, dst): return move_file(src, dst, dry_run=self.dry_run)
[ "def", "move_file", "(", "self", ",", "src", ",", "dst", ")", ":", "return", "move_file", "(", "src", ",", "dst", ",", "dry_run", "=", "self", ".", "dry_run", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/distutils/ccompiler.py#L912-L913
researchmm/tasn
5dba8ccc096cedc63913730eeea14a9647911129
tasn-mxnet/3rdparty/tvm/python/tvm/make.py
python
range_by_min_extent
(min_value, extent)
return _range_by_min_extent(min_value, extent)
Construct a Range by min and extent. This constructs a range in [min_value, min_value + extent) Parameters ---------- min_value : Expr The minimum value of the range. extent : Expr The extent of the range. Returns ------- rng : Range The constructed range.
Construct a Range by min and extent.
[ "Construct", "a", "Range", "by", "min", "and", "extent", "." ]
def range_by_min_extent(min_value, extent): """Construct a Range by min and extent. This constructs a range in [min_value, min_value + extent) Parameters ---------- min_value : Expr The minimum value of the range. extent : Expr The extent of the range. Returns ------- rng : Range The constructed range. """ return _range_by_min_extent(min_value, extent)
[ "def", "range_by_min_extent", "(", "min_value", ",", "extent", ")", ":", "return", "_range_by_min_extent", "(", "min_value", ",", "extent", ")" ]
https://github.com/researchmm/tasn/blob/5dba8ccc096cedc63913730eeea14a9647911129/tasn-mxnet/3rdparty/tvm/python/tvm/make.py#L14-L32
skyhehe123/VoxelNet-pytorch
bfd7be1ca6e5c5b39eece8a4c5fad3ad7b1f7c74
utils.py
python
load_kitti_calib
(calib_file)
return {'P2': P2.reshape(3, 4), 'R0': R0.reshape(3, 3), 'Tr_velo2cam': Tr_velo_to_cam.reshape(3, 4)}
load projection matrix
load projection matrix
[ "load", "projection", "matrix" ]
def load_kitti_calib(calib_file): """ load projection matrix """ with open(calib_file) as fi: lines = fi.readlines() assert (len(lines) == 8) obj = lines[0].strip().split(' ')[1:] P0 = np.array(obj, dtype=np.float32) obj = lines[1].strip().split(' ')[1:] P1 = np.array(obj, dtype=np.float32) obj = lines[2].strip().split(' ')[1:] P2 = np.array(obj, dtype=np.float32) obj = lines[3].strip().split(' ')[1:] P3 = np.array(obj, dtype=np.float32) obj = lines[4].strip().split(' ')[1:] R0 = np.array(obj, dtype=np.float32) obj = lines[5].strip().split(' ')[1:] Tr_velo_to_cam = np.array(obj, dtype=np.float32) obj = lines[6].strip().split(' ')[1:] Tr_imu_to_velo = np.array(obj, dtype=np.float32) return {'P2': P2.reshape(3, 4), 'R0': R0.reshape(3, 3), 'Tr_velo2cam': Tr_velo_to_cam.reshape(3, 4)}
[ "def", "load_kitti_calib", "(", "calib_file", ")", ":", "with", "open", "(", "calib_file", ")", "as", "fi", ":", "lines", "=", "fi", ".", "readlines", "(", ")", "assert", "(", "len", "(", "lines", ")", "==", "8", ")", "obj", "=", "lines", "[", "0",...
https://github.com/skyhehe123/VoxelNet-pytorch/blob/bfd7be1ca6e5c5b39eece8a4c5fad3ad7b1f7c74/utils.py#L234-L259
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-build/python-libs/gdata/src/gdata/Crypto/Protocol/Chaffing.py
python
Chaff.chaff
(self, blocks)
return chaffedblocks
chaff( [(serial-number:int, data:string, MAC:string)] ) : [(int, string, string)] Add chaff to message blocks. blocks is a list of 3-tuples of the form (serial-number, data, MAC). Chaff is created by choosing a random number of the same byte-length as data, and another random number of the same byte-length as MAC. The message block's serial number is placed on the chaff block and all the packet's chaff blocks are randomly interspersed with the single wheat block. This method then returns a list of 3-tuples of the same form. Chaffed blocks will contain multiple instances of 3-tuples with the same serial number, but the only way to figure out which blocks are wheat and which are chaff is to perform the MAC hash and compare values.
chaff( [(serial-number:int, data:string, MAC:string)] ) : [(int, string, string)]
[ "chaff", "(", "[", "(", "serial", "-", "number", ":", "int", "data", ":", "string", "MAC", ":", "string", ")", "]", ")", ":", "[", "(", "int", "string", "string", ")", "]" ]
def chaff(self, blocks): """chaff( [(serial-number:int, data:string, MAC:string)] ) : [(int, string, string)] Add chaff to message blocks. blocks is a list of 3-tuples of the form (serial-number, data, MAC). Chaff is created by choosing a random number of the same byte-length as data, and another random number of the same byte-length as MAC. The message block's serial number is placed on the chaff block and all the packet's chaff blocks are randomly interspersed with the single wheat block. This method then returns a list of 3-tuples of the same form. Chaffed blocks will contain multiple instances of 3-tuples with the same serial number, but the only way to figure out which blocks are wheat and which are chaff is to perform the MAC hash and compare values. """ chaffedblocks = [] # count is the number of blocks to add chaff to. blocksper is the # number of chaff blocks to add per message block that is being # chaffed. count = len(blocks) * self.__factor blocksper = range(self.__blocksper) for i, wheat in map(None, range(len(blocks)), blocks): # it shouldn't matter which of the n blocks we add chaff to, so for # ease of implementation, we'll just add them to the first count # blocks if i < count: serial, data, mac = wheat datasize = len(data) macsize = len(mac) addwheat = 1 # add chaff to this block for j in blocksper: import sys chaffdata = self._randnum(datasize) chaffmac = self._randnum(macsize) chaff = (serial, chaffdata, chaffmac) # mix up the order, if the 5th bit is on then put the # wheat on the list if addwheat and bytes_to_long(self._randnum(16)) & 0x40: chaffedblocks.append(wheat) addwheat = 0 chaffedblocks.append(chaff) if addwheat: chaffedblocks.append(wheat) else: # just add the wheat chaffedblocks.append(wheat) return chaffedblocks
[ "def", "chaff", "(", "self", ",", "blocks", ")", ":", "chaffedblocks", "=", "[", "]", "# count is the number of blocks to add chaff to. blocksper is the", "# number of chaff blocks to add per message block that is being", "# chaffed.", "count", "=", "len", "(", "blocks", ")"...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/gdata/src/gdata/Crypto/Protocol/Chaffing.py#L92-L144
google/brain-tokyo-workshop
faf12f6bbae773fbe535c7a6cf357dc662c6c1d8
WANNRelease/WANNTool/custom_envs/classify_gym.py
python
deskew
(image, image_shape, negated=True)
return img
This method deskwes an image using moments :param image: a numpy nd array input image :param image_shape: a tuple denoting the image`s shape :param negated: a boolean flag telling whether the input image is negated :returns: a numpy nd array deskewd image source: https://github.com/vsvinayak/mnist-helper
This method deskwes an image using moments :param image: a numpy nd array input image :param image_shape: a tuple denoting the image`s shape :param negated: a boolean flag telling whether the input image is negated
[ "This", "method", "deskwes", "an", "image", "using", "moments", ":", "param", "image", ":", "a", "numpy", "nd", "array", "input", "image", ":", "param", "image_shape", ":", "a", "tuple", "denoting", "the", "image", "s", "shape", ":", "param", "negated", ...
def deskew(image, image_shape, negated=True): """ This method deskwes an image using moments :param image: a numpy nd array input image :param image_shape: a tuple denoting the image`s shape :param negated: a boolean flag telling whether the input image is negated :returns: a numpy nd array deskewd image source: https://github.com/vsvinayak/mnist-helper """ # negate the image if not negated: image = 255-image # calculate the moments of the image m = cv2.moments(image) if abs(m['mu02']) < 1e-2: return image.copy() # caclulating the skew skew = m['mu11']/m['mu02'] M = np.float32([[1, skew, -0.5*image_shape[0]*skew], [0,1,0]]) img = cv2.warpAffine(image, M, image_shape, \ flags=cv2.WARP_INVERSE_MAP|cv2.INTER_LINEAR) return img
[ "def", "deskew", "(", "image", ",", "image_shape", ",", "negated", "=", "True", ")", ":", "# negate the image", "if", "not", "negated", ":", "image", "=", "255", "-", "image", "# calculate the moments of the image", "m", "=", "cv2", ".", "moments", "(", "ima...
https://github.com/google/brain-tokyo-workshop/blob/faf12f6bbae773fbe535c7a6cf357dc662c6c1d8/WANNRelease/WANNTool/custom_envs/classify_gym.py#L193-L217
iclavera/learning_to_adapt
bd7d99ba402521c96631e7d09714128f549db0f1
learning_to_adapt/mujoco_py/glfw.py
python
get_video_mode
(monitor)
return videomode.unwrap()
Returns the current mode of the specified monitor. Wrapper for: const GLFWvidmode* glfwGetVideoMode(GLFWmonitor* monitor);
Returns the current mode of the specified monitor.
[ "Returns", "the", "current", "mode", "of", "the", "specified", "monitor", "." ]
def get_video_mode(monitor): ''' Returns the current mode of the specified monitor. Wrapper for: const GLFWvidmode* glfwGetVideoMode(GLFWmonitor* monitor); ''' videomode = _glfw.glfwGetVideoMode(monitor).contents return videomode.unwrap()
[ "def", "get_video_mode", "(", "monitor", ")", ":", "videomode", "=", "_glfw", ".", "glfwGetVideoMode", "(", "monitor", ")", ".", "contents", "return", "videomode", ".", "unwrap", "(", ")" ]
https://github.com/iclavera/learning_to_adapt/blob/bd7d99ba402521c96631e7d09714128f549db0f1/learning_to_adapt/mujoco_py/glfw.py#L706-L714
pig6/login_taobao
3550f21af8d4ea68c077f5d82d9f55df68b2c5ef
username_login.py
python
UsernameLogin._get_umidToken
(self)
return st_match.group(1)
获取umidToken参数 :return:
获取umidToken参数 :return:
[ "获取umidToken参数", ":", "return", ":" ]
def _get_umidToken(self): """ 获取umidToken参数 :return: """ response = s.get('https://login.taobao.com/member/login.jhtml') st_match = re.search(r'"umidToken":"(.*?)"', response.text) print(st_match.group(1)) return st_match.group(1)
[ "def", "_get_umidToken", "(", "self", ")", ":", "response", "=", "s", ".", "get", "(", "'https://login.taobao.com/member/login.jhtml'", ")", "st_match", "=", "re", ".", "search", "(", "r'\"umidToken\":\"(.*?)\"'", ",", "response", ".", "text", ")", "print", "(",...
https://github.com/pig6/login_taobao/blob/3550f21af8d4ea68c077f5d82d9f55df68b2c5ef/username_login.py#L74-L82
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e
scipy/thinkstats2.py
python
CoefDetermination
(ys, res)
return 1 - Var(res) / Var(ys)
Computes the coefficient of determination (R^2) for given residuals. Args: ys: dependent variable res: residuals Returns: float coefficient of determination
Computes the coefficient of determination (R^2) for given residuals.
[ "Computes", "the", "coefficient", "of", "determination", "(", "R^2", ")", "for", "given", "residuals", "." ]
def CoefDetermination(ys, res): """Computes the coefficient of determination (R^2) for given residuals. Args: ys: dependent variable res: residuals Returns: float coefficient of determination """ return 1 - Var(res) / Var(ys)
[ "def", "CoefDetermination", "(", "ys", ",", "res", ")", ":", "return", "1", "-", "Var", "(", "res", ")", "/", "Var", "(", "ys", ")" ]
https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/scipy/thinkstats2.py#L2461-L2471
Tencent/bk-bcs-saas
2b437bf2f5fd5ce2078f7787c3a12df609f7679d
bcs-app/backend/accounts/bcs_perm/__init__.py
python
PermissionMeta.get_msg
(self, cmd)
return ""
获取消息
获取消息
[ "获取消息" ]
def get_msg(self, cmd): """获取消息""" return ""
[ "def", "get_msg", "(", "self", ",", "cmd", ")", ":", "return", "\"\"" ]
https://github.com/Tencent/bk-bcs-saas/blob/2b437bf2f5fd5ce2078f7787c3a12df609f7679d/bcs-app/backend/accounts/bcs_perm/__init__.py#L83-L85
dragonchain/dragonchain
495130a40f79bca48371a2af8645d6476c92339b
dragonchain/lib/dto/model.py
python
Model.export_as_search_index
(self)
Abstract Method
Abstract Method
[ "Abstract", "Method" ]
def export_as_search_index(self) -> dict: """Abstract Method""" raise NotImplementedError("This is an abstract method")
[ "def", "export_as_search_index", "(", "self", ")", "->", "dict", ":", "raise", "NotImplementedError", "(", "\"This is an abstract method\"", ")" ]
https://github.com/dragonchain/dragonchain/blob/495130a40f79bca48371a2af8645d6476c92339b/dragonchain/lib/dto/model.py#L24-L26
mrJean1/PyGeodesy
7da5ca71aa3edb7bc49e219e0b8190686e1a7965
pygeodesy/hausdorff.py
python
HausdorffHaversine.distance
(self, p1, p2)
return haversine_(p2.phi, p1.phi, r)
Return the L{pygeodesy.haversine_} distance in C{radians}.
Return the L{pygeodesy.haversine_} distance in C{radians}.
[ "Return", "the", "L", "{", "pygeodesy", ".", "haversine_", "}", "distance", "in", "C", "{", "radians", "}", "." ]
def distance(self, p1, p2): '''Return the L{pygeodesy.haversine_} distance in C{radians}. ''' r, _ = unrollPI(p1.lam, p2.lam, wrap=self._wrap) return haversine_(p2.phi, p1.phi, r)
[ "def", "distance", "(", "self", ",", "p1", ",", "p2", ")", ":", "r", ",", "_", "=", "unrollPI", "(", "p1", ".", "lam", ",", "p2", ".", "lam", ",", "wrap", "=", "self", ".", "_wrap", ")", "return", "haversine_", "(", "p2", ".", "phi", ",", "p1...
https://github.com/mrJean1/PyGeodesy/blob/7da5ca71aa3edb7bc49e219e0b8190686e1a7965/pygeodesy/hausdorff.py#L767-L771
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/flo/device.py
python
FloDeviceDataUpdateCoordinator.pending_warning_alerts_count
(self)
return self._device_information["notifications"]["pending"]["warningCount"]
Return the number of pending warning alerts for the device.
Return the number of pending warning alerts for the device.
[ "Return", "the", "number", "of", "pending", "warning", "alerts", "for", "the", "device", "." ]
def pending_warning_alerts_count(self) -> int: """Return the number of pending warning alerts for the device.""" return self._device_information["notifications"]["pending"]["warningCount"]
[ "def", "pending_warning_alerts_count", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_device_information", "[", "\"notifications\"", "]", "[", "\"pending\"", "]", "[", "\"warningCount\"", "]" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/flo/device.py#L157-L159
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v2beta2_cross_version_object_reference.py
python
V2beta2CrossVersionObjectReference.__repr__
(self)
return self.to_str()
For `print` and `pprint`
For `print` and `pprint`
[ "For", "print", "and", "pprint" ]
def __repr__(self): """For `print` and `pprint`""" return self.to_str()
[ "def", "__repr__", "(", "self", ")", ":", "return", "self", ".", "to_str", "(", ")" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v2beta2_cross_version_object_reference.py#L164-L166
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/gse/v20191112/gse_client.py
python
GseClient.DescribeFleetPortSettings
(self, request)
本接口(DescribeFleetPortSettings)用于获取服务器舰队安全组信息。 :param request: Request instance for DescribeFleetPortSettings. :type request: :class:`tencentcloud.gse.v20191112.models.DescribeFleetPortSettingsRequest` :rtype: :class:`tencentcloud.gse.v20191112.models.DescribeFleetPortSettingsResponse`
本接口(DescribeFleetPortSettings)用于获取服务器舰队安全组信息。
[ "本接口(DescribeFleetPortSettings)用于获取服务器舰队安全组信息。" ]
def DescribeFleetPortSettings(self, request): """本接口(DescribeFleetPortSettings)用于获取服务器舰队安全组信息。 :param request: Request instance for DescribeFleetPortSettings. :type request: :class:`tencentcloud.gse.v20191112.models.DescribeFleetPortSettingsRequest` :rtype: :class:`tencentcloud.gse.v20191112.models.DescribeFleetPortSettingsResponse` """ try: params = request._serialize() body = self.call("DescribeFleetPortSettings", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeFleetPortSettingsResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "DescribeFleetPortSettings", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"DescribeFleetPortSettings\"", ",", "params", ")", "response", "=", "json",...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/gse/v20191112/gse_client.py#L660-L685
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/pkg_resources/__init__.py
python
IMetadataProvider.get_metadata
(name)
The named metadata resource as a string
The named metadata resource as a string
[ "The", "named", "metadata", "resource", "as", "a", "string" ]
def get_metadata(name): """The named metadata resource as a string"""
[ "def", "get_metadata", "(", "name", ")", ":" ]
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/pkg_resources/__init__.py#L501-L502
yt-project/yt
dc7b24f9b266703db4c843e329c6c8644d47b824
yt/frontends/boxlib/data_structures.py
python
WarpXHierarchy.__init__
(self, ds, dataset_type="boxlib_native")
[]
def __init__(self, ds, dataset_type="boxlib_native"): super().__init__(ds, dataset_type) is_checkpoint = True for ptype in self.ds.particle_types: self._read_particles(ptype, is_checkpoint) # Additional WarpX particle information (used to set up species) self.warpx_header = WarpXHeader(self.ds.output_dir + "/WarpXHeader") for key, val in self.warpx_header.data.items(): if key.startswith("species_"): i = int(key.split("_")[-1]) charge_name = "particle%.1d_charge" % i mass_name = "particle%.1d_mass" % i self.parameters[charge_name] = val[0] self.parameters[mass_name] = val[1]
[ "def", "__init__", "(", "self", ",", "ds", ",", "dataset_type", "=", "\"boxlib_native\"", ")", ":", "super", "(", ")", ".", "__init__", "(", "ds", ",", "dataset_type", ")", "is_checkpoint", "=", "True", "for", "ptype", "in", "self", ".", "ds", ".", "pa...
https://github.com/yt-project/yt/blob/dc7b24f9b266703db4c843e329c6c8644d47b824/yt/frontends/boxlib/data_structures.py#L1432-L1448
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/distutils/msvc9compiler.py
python
Reg.read_keys
(cls, base, key)
return L
Return list of registry keys.
Return list of registry keys.
[ "Return", "list", "of", "registry", "keys", "." ]
def read_keys(cls, base, key): """Return list of registry keys.""" try: handle = RegOpenKeyEx(base, key) except RegError: return None L = [] i = 0 while True: try: k = RegEnumKey(handle, i) except RegError: break L.append(k) i += 1 return L
[ "def", "read_keys", "(", "cls", ",", "base", ",", "key", ")", ":", "try", ":", "handle", "=", "RegOpenKeyEx", "(", "base", ",", "key", ")", "except", "RegError", ":", "return", "None", "L", "=", "[", "]", "i", "=", "0", "while", "True", ":", "try...
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/distutils/msvc9compiler.py#L73-L88
wanggrun/Adaptively-Connected-Neural-Networks
e27066ef52301bdafa5932f43af8feeb23647edb
tensorpack-installed/build/lib/tensorpack/dataflow/imgaug/imgproc.py
python
Saturation.__init__
(self, alpha=0.4, rgb=True)
Args: alpha(float): maximum saturation change. rgb (bool): whether input is RGB or BGR.
Args: alpha(float): maximum saturation change. rgb (bool): whether input is RGB or BGR.
[ "Args", ":", "alpha", "(", "float", ")", ":", "maximum", "saturation", "change", ".", "rgb", "(", "bool", ")", ":", "whether", "input", "is", "RGB", "or", "BGR", "." ]
def __init__(self, alpha=0.4, rgb=True): """ Args: alpha(float): maximum saturation change. rgb (bool): whether input is RGB or BGR. """ super(Saturation, self).__init__() rgb = bool(rgb) assert alpha < 1 self._init(locals())
[ "def", "__init__", "(", "self", ",", "alpha", "=", "0.4", ",", "rgb", "=", "True", ")", ":", "super", "(", "Saturation", ",", "self", ")", ".", "__init__", "(", ")", "rgb", "=", "bool", "(", "rgb", ")", "assert", "alpha", "<", "1", "self", ".", ...
https://github.com/wanggrun/Adaptively-Connected-Neural-Networks/blob/e27066ef52301bdafa5932f43af8feeb23647edb/tensorpack-installed/build/lib/tensorpack/dataflow/imgaug/imgproc.py#L224-L233
pulp/pulp
a0a28d804f997b6f81c391378aff2e4c90183df9
server/pulp/server/managers/repo/group/publish.py
python
RepoGroupPublishManager.publish
(group_id, distributor_id, publish_config_override=None)
Requests the given distributor publish the repository group. :param group_id: identifies the repo group :type group_id: str :param distributor_id: identifies the group's distributor :type distributor_id: str :param publish_config_override: values to pass the plugin for this publish call alone :type publish_config_override: dict
Requests the given distributor publish the repository group.
[ "Requests", "the", "given", "distributor", "publish", "the", "repository", "group", "." ]
def publish(group_id, distributor_id, publish_config_override=None): """ Requests the given distributor publish the repository group. :param group_id: identifies the repo group :type group_id: str :param distributor_id: identifies the group's distributor :type distributor_id: str :param publish_config_override: values to pass the plugin for this publish call alone :type publish_config_override: dict """ distributor_manager = manager_factory.repo_group_distributor_manager() distributor = distributor_manager.get_distributor(group_id, distributor_id) distributor_type_id = distributor['distributor_type_id'] distributor_instance, plugin_config = plugin_api.get_group_distributor_by_id( distributor_type_id) group_query_manager = manager_factory.repo_group_query_manager() # Validation group = group_query_manager.get_group(group_id) distributor_type_id = distributor['distributor_type_id'] # Assemble the data needed for publish conduit = RepoGroupPublishConduit(group_id, distributor) call_config = PluginCallConfiguration(plugin_config, distributor['config'], publish_config_override) transfer_group = common_utils.to_transfer_repo_group(group) transfer_group.working_dir = common_utils.get_working_directory() # TODO: Add events for group publish start/complete RepoGroupPublishManager._do_publish(transfer_group, distributor_id, distributor_instance, conduit, call_config)
[ "def", "publish", "(", "group_id", ",", "distributor_id", ",", "publish_config_override", "=", "None", ")", ":", "distributor_manager", "=", "manager_factory", ".", "repo_group_distributor_manager", "(", ")", "distributor", "=", "distributor_manager", ".", "get_distribu...
https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/server/pulp/server/managers/repo/group/publish.py#L24-L59
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/set/src/core/scapy.py
python
Dot11Addr2MACField.is_applicable
(self, pkt)
return 1
[]
def is_applicable(self, pkt): if pkt.type == 1: return pkt.subtype in [ 0xb, 0xa, 0xe, 0xf] # RTS, PS-Poll, CF-End, CF-End+CF-Ack return 1
[ "def", "is_applicable", "(", "self", ",", "pkt", ")", ":", "if", "pkt", ".", "type", "==", "1", ":", "return", "pkt", ".", "subtype", "in", "[", "0xb", ",", "0xa", ",", "0xe", ",", "0xf", "]", "# RTS, PS-Poll, CF-End, CF-End+CF-Ack", "return", "1" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/set/src/core/scapy.py#L3599-L3602
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Tools/msi/msilib.py
python
gen_schema
(destpath, schemapath)
[]
def gen_schema(destpath, schemapath): d = MakeInstaller() schema = d.OpenDatabase(schemapath, win32com.client.constants.msiOpenDatabaseModeReadOnly) # XXX ORBER BY v=schema.OpenView("SELECT * FROM _Columns") curtable=None tables = [] v.Execute(None) f = open(destpath, "wt") f.write("from msilib import Table\n") while 1: r=v.Fetch() if not r:break name=r.StringData(1) if curtable != name: f.write("\n%s = Table('%s')\n" % (name,name)) curtable = name tables.append(name) f.write("%s.add_field(%d,'%s',%d)\n" % (name, r.IntegerData(2), r.StringData(3), r.IntegerData(4))) v.Close() f.write("\ntables=[%s]\n\n" % (", ".join(tables))) # Fill the _Validation table f.write("_Validation_records = [\n") v = schema.OpenView("SELECT * FROM _Validation") v.Execute(None) while 1: r = v.Fetch() if not r:break # Table, Column, Nullable f.write("(%s,%s,%s," % (`r.StringData(1)`, `r.StringData(2)`, `r.StringData(3)`)) def put_int(i): if r.IsNull(i):f.write("None, ") else:f.write("%d," % r.IntegerData(i)) def put_str(i): if r.IsNull(i):f.write("None, ") else:f.write("%s," % `r.StringData(i)`) put_int(4) # MinValue put_int(5) # MaxValue put_str(6) # KeyTable put_int(7) # KeyColumn put_str(8) # Category put_str(9) # Set put_str(10)# Description f.write("),\n") f.write("]\n\n") f.close()
[ "def", "gen_schema", "(", "destpath", ",", "schemapath", ")", ":", "d", "=", "MakeInstaller", "(", ")", "schema", "=", "d", ".", "OpenDatabase", "(", "schemapath", ",", "win32com", ".", "client", ".", "constants", ".", "msiOpenDatabaseModeReadOnly", ")", "# ...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Tools/msi/msilib.py#L142-L194
jfzhang95/pytorch-deeplab-xception
9135e104a7a51ea9effa9c6676a2fcffe6a6a2e6
doc/deeplab_xception.py
python
get_1x_lr_params
(model)
This generator returns all the parameters of the net except for the last classification layer. Note that for each batchnorm layer, requires_grad is set to False in deeplab_resnet.py, therefore this function does not return any batchnorm parameter
This generator returns all the parameters of the net except for the last classification layer. Note that for each batchnorm layer, requires_grad is set to False in deeplab_resnet.py, therefore this function does not return any batchnorm parameter
[ "This", "generator", "returns", "all", "the", "parameters", "of", "the", "net", "except", "for", "the", "last", "classification", "layer", ".", "Note", "that", "for", "each", "batchnorm", "layer", "requires_grad", "is", "set", "to", "False", "in", "deeplab_res...
def get_1x_lr_params(model): """ This generator returns all the parameters of the net except for the last classification layer. Note that for each batchnorm layer, requires_grad is set to False in deeplab_resnet.py, therefore this function does not return any batchnorm parameter """ b = [model.xception_features] for i in range(len(b)): for k in b[i].parameters(): if k.requires_grad: yield k
[ "def", "get_1x_lr_params", "(", "model", ")", ":", "b", "=", "[", "model", ".", "xception_features", "]", "for", "i", "in", "range", "(", "len", "(", "b", ")", ")", ":", "for", "k", "in", "b", "[", "i", "]", ".", "parameters", "(", ")", ":", "i...
https://github.com/jfzhang95/pytorch-deeplab-xception/blob/9135e104a7a51ea9effa9c6676a2fcffe6a6a2e6/doc/deeplab_xception.py#L389-L400
filerock/FileRock-Client
37214f701666e76e723595f8f9ed238a42f6eb06
filerockclient/workers/filters/encryption/helpers.py
python
recalc_encrypted_etag_in_mem
(ivs, warebox, cfg, interruption=None)
return encrypted_etags
Encrypt all the files into the encrypted folder and return a list of etag @param ivs: a dictionary with pathname as key and ivs as value @param warebox: an instance of warebox class @param cfg: an instance of config class
Encrypt all the files into the encrypted folder and return a list of etag
[ "Encrypt", "all", "the", "files", "into", "the", "encrypted", "folder", "and", "return", "a", "list", "of", "etag" ]
def recalc_encrypted_etag_in_mem(ivs, warebox, cfg, interruption=None): """ Encrypt all the files into the encrypted folder and return a list of etag @param ivs: a dictionary with pathname as key and ivs as value @param warebox: an instance of warebox class @param cfg: an instance of config class """ key = unhexlify(cfg.get('User', 'encryption_key')) encrypted_etags = dict() chunksize = CryptoUtils.CHUNK_SIZE padder = PKCS7Padder() for pathname in ivs: if interruption is not None and interruption.is_set(): raise ExecutionInterrupted() try: fp = warebox.open(pathname, mode="rb") md5 = hashlib.md5() iv = unhexlify(ivs[pathname]) encryptor = AES.new(key, AES.MODE_CFB, iv, segment_size=128) #Initialize encryptor md5.update(CryptoUtils.PROTOCOL_VERSION) md5.update(iv) completed = False chunk = fp.read(chunksize) while not completed: next_chunk = fp.read(chunksize) if len(next_chunk) > 0: md5.update(encryptor.encrypt(chunk)) chunk = next_chunk else: chunk_padded = padder.encode(chunk) encrypted_chunk=encryptor.encrypt(chunk_padded) md5.update(encrypted_chunk) completed = True encrypted_etags[pathname] = md5.hexdigest() except Exception: raise finally: fp.close() return encrypted_etags
[ "def", "recalc_encrypted_etag_in_mem", "(", "ivs", ",", "warebox", ",", "cfg", ",", "interruption", "=", "None", ")", ":", "key", "=", "unhexlify", "(", "cfg", ".", "get", "(", "'User'", ",", "'encryption_key'", ")", ")", "encrypted_etags", "=", "dict", "(...
https://github.com/filerock/FileRock-Client/blob/37214f701666e76e723595f8f9ed238a42f6eb06/filerockclient/workers/filters/encryption/helpers.py#L150-L189
nodesign/weio
1d67d705a5c36a2e825ad13feab910b0aca9a2e8
openWrt/files/usr/lib/python2.7/site-packages/tornado/iostream.py
python
BaseIOStream.reading
(self)
return self._read_callback is not None
Returns true if we are currently reading from the stream.
Returns true if we are currently reading from the stream.
[ "Returns", "true", "if", "we", "are", "currently", "reading", "from", "the", "stream", "." ]
def reading(self): """Returns true if we are currently reading from the stream.""" return self._read_callback is not None
[ "def", "reading", "(", "self", ")", ":", "return", "self", ".", "_read_callback", "is", "not", "None" ]
https://github.com/nodesign/weio/blob/1d67d705a5c36a2e825ad13feab910b0aca9a2e8/openWrt/files/usr/lib/python2.7/site-packages/tornado/iostream.py#L260-L262
NoGameNoLife00/mybolg
afe17ea5bfe405e33766e5682c43a4262232ee12
libs/werkzeug/datastructures.py
python
ImmutableOrderedMultiDict.copy
(self)
return OrderedMultiDict(self)
Return a shallow mutable copy of this object. Keep in mind that the standard library's :func:`copy` function is a no-op for this class like for any other python immutable type (eg: :class:`tuple`).
Return a shallow mutable copy of this object. Keep in mind that the standard library's :func:`copy` function is a no-op for this class like for any other python immutable type (eg: :class:`tuple`).
[ "Return", "a", "shallow", "mutable", "copy", "of", "this", "object", ".", "Keep", "in", "mind", "that", "the", "standard", "library", "s", ":", "func", ":", "copy", "function", "is", "a", "no", "-", "op", "for", "this", "class", "like", "for", "any", ...
def copy(self): """Return a shallow mutable copy of this object. Keep in mind that the standard library's :func:`copy` function is a no-op for this class like for any other python immutable type (eg: :class:`tuple`). """ return OrderedMultiDict(self)
[ "def", "copy", "(", "self", ")", ":", "return", "OrderedMultiDict", "(", "self", ")" ]
https://github.com/NoGameNoLife00/mybolg/blob/afe17ea5bfe405e33766e5682c43a4262232ee12/libs/werkzeug/datastructures.py#L1513-L1518
joschabach/micropsi2
74a2642d20da9da1d64acc5e4c11aeabee192a27
micropsi_core/nodenet/netapi.py
python
NetAPI.set_gatefunction
(self, nodespace, nodetype, gatetype, gatefunction)
Sets the gatefunction for gates of type gatetype of nodes of type nodetype, in the given nodespace. The gatefunction needs to be given as a string.
Sets the gatefunction for gates of type gatetype of nodes of type nodetype, in the given nodespace. The gatefunction needs to be given as a string.
[ "Sets", "the", "gatefunction", "for", "gates", "of", "type", "gatetype", "of", "nodes", "of", "type", "nodetype", "in", "the", "given", "nodespace", ".", "The", "gatefunction", "needs", "to", "be", "given", "as", "a", "string", "." ]
def set_gatefunction(self, nodespace, nodetype, gatetype, gatefunction): """Sets the gatefunction for gates of type gatetype of nodes of type nodetype, in the given nodespace. The gatefunction needs to be given as a string. """ nodespace = self.get_nodespace(nodespace) for uid in nodespace.get_known_ids(entitytype="nodes"): node = self.get_node(uid) if node.type == nodetype: node.set_gatefunction_name(gatetype, gatefunction)
[ "def", "set_gatefunction", "(", "self", ",", "nodespace", ",", "nodetype", ",", "gatetype", ",", "gatefunction", ")", ":", "nodespace", "=", "self", ".", "get_nodespace", "(", "nodespace", ")", "for", "uid", "in", "nodespace", ".", "get_known_ids", "(", "ent...
https://github.com/joschabach/micropsi2/blob/74a2642d20da9da1d64acc5e4c11aeabee192a27/micropsi_core/nodenet/netapi.py#L338-L347
i-pan/kaggle-rsna18
2db498fe99615d935aa676f04847d0c562fd8e46
models/RelationNetworks/relation_rcnn/core/module.py
python
Module.update_metric
(self, eval_metric, labels)
Evaluate and accumulate evaluation metric on outputs of the last forward computation. Parameters ---------- eval_metric : EvalMetric labels : list of NDArray Typically `data_batch.label`.
Evaluate and accumulate evaluation metric on outputs of the last forward computation.
[ "Evaluate", "and", "accumulate", "evaluation", "metric", "on", "outputs", "of", "the", "last", "forward", "computation", "." ]
def update_metric(self, eval_metric, labels): """Evaluate and accumulate evaluation metric on outputs of the last forward computation. Parameters ---------- eval_metric : EvalMetric labels : list of NDArray Typically `data_batch.label`. """ self._exec_group.update_metric(eval_metric, labels)
[ "def", "update_metric", "(", "self", ",", "eval_metric", ",", "labels", ")", ":", "self", ".", "_exec_group", ".", "update_metric", "(", "eval_metric", ",", "labels", ")" ]
https://github.com/i-pan/kaggle-rsna18/blob/2db498fe99615d935aa676f04847d0c562fd8e46/models/RelationNetworks/relation_rcnn/core/module.py#L667-L676
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/elements.py
python
ClauseList.__init__
(self, *clauses, **kwargs)
[]
def __init__(self, *clauses, **kwargs): self.operator = kwargs.pop('operator', operators.comma_op) self.group = kwargs.pop('group', True) self.group_contents = kwargs.pop('group_contents', True) text_converter = kwargs.pop( '_literal_as_text', _expression_literal_as_text) if self.group_contents: self.clauses = [ text_converter(clause).self_group(against=self.operator) for clause in clauses] else: self.clauses = [ text_converter(clause) for clause in clauses]
[ "def", "__init__", "(", "self", ",", "*", "clauses", ",", "*", "*", "kwargs", ")", ":", "self", ".", "operator", "=", "kwargs", ".", "pop", "(", "'operator'", ",", "operators", ".", "comma_op", ")", "self", ".", "group", "=", "kwargs", ".", "pop", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/elements.py#L1801-L1815
InvestmentSystems/static-frame
0b19d6969bf6c17fb0599871aca79eb3b52cf2ed
static_frame/core/yarn.py
python
Yarn.iter_element
(self)
return IterNodeNoArg( container=self, function_items=self._axis_element_items, function_values=self._axis_element, yield_type=IterNodeType.VALUES, apply_type=IterNodeApplyType.SERIES_VALUES, )
Iterator of elements.
Iterator of elements.
[ "Iterator", "of", "elements", "." ]
def iter_element(self) -> IterNodeNoArg['Yarn']: ''' Iterator of elements. ''' return IterNodeNoArg( container=self, function_items=self._axis_element_items, function_values=self._axis_element, yield_type=IterNodeType.VALUES, apply_type=IterNodeApplyType.SERIES_VALUES, )
[ "def", "iter_element", "(", "self", ")", "->", "IterNodeNoArg", "[", "'Yarn'", "]", ":", "return", "IterNodeNoArg", "(", "container", "=", "self", ",", "function_items", "=", "self", ".", "_axis_element_items", ",", "function_values", "=", "self", ".", "_axis_...
https://github.com/InvestmentSystems/static-frame/blob/0b19d6969bf6c17fb0599871aca79eb3b52cf2ed/static_frame/core/yarn.py#L264-L274
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/redis/lock.py
python
Lock.__init__
(self, redis, name, timeout=None, sleep=0.1, blocking=True, blocking_timeout=None, thread_local=True)
Create a new Lock instance named ``name`` using the Redis client supplied by ``redis``. ``timeout`` indicates a maximum life for the lock. By default, it will remain locked until release() is called. ``timeout`` can be specified as a float or integer, both representing the number of seconds to wait. ``sleep`` indicates the amount of time to sleep per loop iteration when the lock is in blocking mode and another client is currently holding the lock. ``blocking`` indicates whether calling ``acquire`` should block until the lock has been acquired or to fail immediately, causing ``acquire`` to return False and the lock not being acquired. Defaults to True. Note this value can be overridden by passing a ``blocking`` argument to ``acquire``. ``blocking_timeout`` indicates the maximum amount of time in seconds to spend trying to acquire the lock. A value of ``None`` indicates continue trying forever. ``blocking_timeout`` can be specified as a float or integer, both representing the number of seconds to wait. ``thread_local`` indicates whether the lock token is placed in thread-local storage. By default, the token is placed in thread local storage so that a thread only sees its token, not a token set by another thread. Consider the following timeline: time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds. thread-1 sets the token to "abc" time: 1, thread-2 blocks trying to acquire `my-lock` using the Lock instance. time: 5, thread-1 has not yet completed. redis expires the lock key. time: 5, thread-2 acquired `my-lock` now that it's available. thread-2 sets the token to "xyz" time: 6, thread-1 finishes its work and calls release(). if the token is *not* stored in thread local storage, then thread-1 would see the token value as "xyz" and would be able to successfully release the thread-2's lock. In some use cases it's necessary to disable thread local storage. For example, if you have code where one thread acquires a lock and passes that lock instance to a worker thread to release later. If thread local storage isn't disabled in this case, the worker thread won't see the token set by the thread that acquired the lock. Our assumption is that these cases aren't common and as such default to using thread local storage.
Create a new Lock instance named ``name`` using the Redis client supplied by ``redis``.
[ "Create", "a", "new", "Lock", "instance", "named", "name", "using", "the", "Redis", "client", "supplied", "by", "redis", "." ]
def __init__(self, redis, name, timeout=None, sleep=0.1, blocking=True, blocking_timeout=None, thread_local=True): """ Create a new Lock instance named ``name`` using the Redis client supplied by ``redis``. ``timeout`` indicates a maximum life for the lock. By default, it will remain locked until release() is called. ``timeout`` can be specified as a float or integer, both representing the number of seconds to wait. ``sleep`` indicates the amount of time to sleep per loop iteration when the lock is in blocking mode and another client is currently holding the lock. ``blocking`` indicates whether calling ``acquire`` should block until the lock has been acquired or to fail immediately, causing ``acquire`` to return False and the lock not being acquired. Defaults to True. Note this value can be overridden by passing a ``blocking`` argument to ``acquire``. ``blocking_timeout`` indicates the maximum amount of time in seconds to spend trying to acquire the lock. A value of ``None`` indicates continue trying forever. ``blocking_timeout`` can be specified as a float or integer, both representing the number of seconds to wait. ``thread_local`` indicates whether the lock token is placed in thread-local storage. By default, the token is placed in thread local storage so that a thread only sees its token, not a token set by another thread. Consider the following timeline: time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds. thread-1 sets the token to "abc" time: 1, thread-2 blocks trying to acquire `my-lock` using the Lock instance. time: 5, thread-1 has not yet completed. redis expires the lock key. time: 5, thread-2 acquired `my-lock` now that it's available. thread-2 sets the token to "xyz" time: 6, thread-1 finishes its work and calls release(). if the token is *not* stored in thread local storage, then thread-1 would see the token value as "xyz" and would be able to successfully release the thread-2's lock. In some use cases it's necessary to disable thread local storage. For example, if you have code where one thread acquires a lock and passes that lock instance to a worker thread to release later. If thread local storage isn't disabled in this case, the worker thread won't see the token set by the thread that acquired the lock. Our assumption is that these cases aren't common and as such default to using thread local storage. """ self.redis = redis self.name = name self.timeout = timeout self.sleep = sleep self.blocking = blocking self.blocking_timeout = blocking_timeout self.thread_local = bool(thread_local) self.local = threading.local() if self.thread_local else dummy() self.local.token = None if self.timeout and self.sleep > self.timeout: raise LockError("'sleep' must be less than 'timeout'")
[ "def", "__init__", "(", "self", ",", "redis", ",", "name", ",", "timeout", "=", "None", ",", "sleep", "=", "0.1", ",", "blocking", "=", "True", ",", "blocking_timeout", "=", "None", ",", "thread_local", "=", "True", ")", ":", "self", ".", "redis", "=...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/redis/lock.py#L17-L79
marinho/geraldo
868ebdce67176d9b6205cddc92476f642c783fff
site/newsite/django_1_0/django/core/servers/basehttp.py
python
Headers.get
(self,name,default=None)
return default
Get the first header value for 'name', or return 'default
Get the first header value for 'name', or return 'default
[ "Get", "the", "first", "header", "value", "for", "name", "or", "return", "default" ]
def get(self,name,default=None): """Get the first header value for 'name', or return 'default'""" name = name.lower() for k,v in self._headers: if k.lower()==name: return v return default
[ "def", "get", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "for", "k", ",", "v", "in", "self", ".", "_headers", ":", "if", "k", ".", "lower", "(", ")", "==", "name", ":", "retur...
https://github.com/marinho/geraldo/blob/868ebdce67176d9b6205cddc92476f642c783fff/site/newsite/django_1_0/django/core/servers/basehttp.py#L124-L130
wistbean/fxxkpython
88e16d79d8dd37236ba6ecd0d0ff11d63143968c
vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/distlib/metadata.py
python
LegacyMetadata.write_file
(self, fileobject, skip_unknown=False)
Write the PKG-INFO format data to a file object.
Write the PKG-INFO format data to a file object.
[ "Write", "the", "PKG", "-", "INFO", "format", "data", "to", "a", "file", "object", "." ]
def write_file(self, fileobject, skip_unknown=False): """Write the PKG-INFO format data to a file object.""" self.set_metadata_version() for field in _version2fieldlist(self['Metadata-Version']): values = self.get(field) if skip_unknown and values in ('UNKNOWN', [], ['UNKNOWN']): continue if field in _ELEMENTSFIELD: self._write_field(fileobject, field, ','.join(values)) continue if field not in _LISTFIELDS: if field == 'Description': if self.metadata_version in ('1.0', '1.1'): values = values.replace('\n', '\n ') else: values = values.replace('\n', '\n |') values = [values] if field in _LISTTUPLEFIELDS: values = [','.join(value) for value in values] for value in values: self._write_field(fileobject, field, value)
[ "def", "write_file", "(", "self", ",", "fileobject", ",", "skip_unknown", "=", "False", ")", ":", "self", ".", "set_metadata_version", "(", ")", "for", "field", "in", "_version2fieldlist", "(", "self", "[", "'Metadata-Version'", "]", ")", ":", "values", "=",...
https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/distlib/metadata.py#L393-L416
OpenCobolIDE/OpenCobolIDE
c78d0d335378e5fe0a5e74f53c19b68b55e85388
open_cobol_ide/extlibs/future/backports/urllib/request.py
python
Request.is_unverifiable
(self)
return self.unverifiable
[]
def is_unverifiable(self): msg = "Request.is_unverifiable method is deprecated." warnings.warn(msg, DeprecationWarning, stacklevel=1) return self.unverifiable
[ "def", "is_unverifiable", "(", "self", ")", ":", "msg", "=", "\"Request.is_unverifiable method is deprecated.\"", "warnings", ".", "warn", "(", "msg", ",", "DeprecationWarning", ",", "stacklevel", "=", "1", ")", "return", "self", ".", "unverifiable" ]
https://github.com/OpenCobolIDE/OpenCobolIDE/blob/c78d0d335378e5fe0a5e74f53c19b68b55e85388/open_cobol_ide/extlibs/future/backports/urllib/request.py#L351-L354
enthought/traitsui
b7c38c7a47bf6ae7971f9ddab70c8a358647dd25
traitsui/qt4/enum_editor.py
python
ListEditor.rebuild_editor
(self)
Rebuilds the contents of the editor whenever the original factory object's **values** trait changes.
Rebuilds the contents of the editor whenever the original factory object's **values** trait changes.
[ "Rebuilds", "the", "contents", "of", "the", "editor", "whenever", "the", "original", "factory", "object", "s", "**", "values", "**", "trait", "changes", "." ]
def rebuild_editor(self): """Rebuilds the contents of the editor whenever the original factory object's **values** trait changes. """ self.control.blockSignals(True) self.control.clear() for name in self.names: self.control.addItem(name) self.control.blockSignals(False) self.update_editor()
[ "def", "rebuild_editor", "(", "self", ")", ":", "self", ".", "control", ".", "blockSignals", "(", "True", ")", "self", ".", "control", ".", "clear", "(", ")", "for", "name", "in", "self", ".", "names", ":", "self", ".", "control", ".", "addItem", "("...
https://github.com/enthought/traitsui/blob/b7c38c7a47bf6ae7971f9ddab70c8a358647dd25/traitsui/qt4/enum_editor.py#L448-L459
plotly/arduino-api
38ee5b191682532ebee908ceafbc67692730d39c
plotly_yun/Linino/pytz/tzfile.py
python
_byte_string
(s)
return s.encode('US-ASCII')
Cast a string or byte string to an ASCII byte string.
Cast a string or byte string to an ASCII byte string.
[ "Cast", "a", "string", "or", "byte", "string", "to", "an", "ASCII", "byte", "string", "." ]
def _byte_string(s): """Cast a string or byte string to an ASCII byte string.""" return s.encode('US-ASCII')
[ "def", "_byte_string", "(", "s", ")", ":", "return", "s", ".", "encode", "(", "'US-ASCII'", ")" ]
https://github.com/plotly/arduino-api/blob/38ee5b191682532ebee908ceafbc67692730d39c/plotly_yun/Linino/pytz/tzfile.py#L16-L18
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/groups/perm_gps/permgroup_named.py
python
ComplexReflectionGroup._latex_
(self)
return "G(%s,%s,%s)" % (self._m, self._p, self._n)
Return a string representation of ``self``. EXAMPLES:: sage: G = groups.permutation.ComplexReflection(3, 1, 5) sage: latex(G) G(3,1,5)
Return a string representation of ``self``.
[ "Return", "a", "string", "representation", "of", "self", "." ]
def _latex_(self): """ Return a string representation of ``self``. EXAMPLES:: sage: G = groups.permutation.ComplexReflection(3, 1, 5) sage: latex(G) G(3,1,5) """ return "G(%s,%s,%s)" % (self._m, self._p, self._n)
[ "def", "_latex_", "(", "self", ")", ":", "return", "\"G(%s,%s,%s)\"", "%", "(", "self", ".", "_m", ",", "self", ".", "_p", ",", "self", ".", "_n", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/groups/perm_gps/permgroup_named.py#L3225-L3235
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /tools/sqli/thirdparty/gprof2dot/gprof2dot.py
python
XmlParser.consume
(self)
[]
def consume(self): self.token = self.tokenizer.next()
[ "def", "consume", "(", "self", ")", ":", "self", ".", "token", "=", "self", ".", "tokenizer", ".", "next", "(", ")" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /tools/sqli/thirdparty/gprof2dot/gprof2dot.py#L734-L735
rcorcs/NatI
fdf014f4292afdc95250add7b6658468043228e1
en/wordnet/wordnet.py
python
Sense.isTagged
(self)
return _index(self, word.getSenses()) < word.taggedSenseCount
Return 1 if any sense is tagged. >>> N['dog'][0].isTagged() 1 >>> N['dog'][1].isTagged() 0
Return 1 if any sense is tagged. >>> N['dog'][0].isTagged() 1 >>> N['dog'][1].isTagged() 0
[ "Return", "1", "if", "any", "sense", "is", "tagged", ".", ">>>", "N", "[", "dog", "]", "[", "0", "]", ".", "isTagged", "()", "1", ">>>", "N", "[", "dog", "]", "[", "1", "]", ".", "isTagged", "()", "0" ]
def isTagged(self): """Return 1 if any sense is tagged. >>> N['dog'][0].isTagged() 1 >>> N['dog'][1].isTagged() 0 """ word = self.word() return _index(self, word.getSenses()) < word.taggedSenseCount
[ "def", "isTagged", "(", "self", ")", ":", "word", "=", "self", ".", "word", "(", ")", "return", "_index", "(", "self", ",", "word", ".", "getSenses", "(", ")", ")", "<", "word", ".", "taggedSenseCount" ]
https://github.com/rcorcs/NatI/blob/fdf014f4292afdc95250add7b6658468043228e1/en/wordnet/wordnet.py#L637-L646
python-social-auth/social-core
1ea27e8989657bb35dd37b6ee2e038e1358fbc96
social_core/backends/skyrock.py
python
SkyrockOAuth.get_user_details
(self, response)
return {'username': response['username'], 'email': response['email'], 'fullname': fullname, 'first_name': first_name, 'last_name': last_name}
Return user details from Skyrock account
Return user details from Skyrock account
[ "Return", "user", "details", "from", "Skyrock", "account" ]
def get_user_details(self, response): """Return user details from Skyrock account""" fullname, first_name, last_name = self.get_user_names( first_name=response['firstname'], last_name=response['name'] ) return {'username': response['username'], 'email': response['email'], 'fullname': fullname, 'first_name': first_name, 'last_name': last_name}
[ "def", "get_user_details", "(", "self", ",", "response", ")", ":", "fullname", ",", "first_name", ",", "last_name", "=", "self", ".", "get_user_names", "(", "first_name", "=", "response", "[", "'firstname'", "]", ",", "last_name", "=", "response", "[", "'nam...
https://github.com/python-social-auth/social-core/blob/1ea27e8989657bb35dd37b6ee2e038e1358fbc96/social_core/backends/skyrock.py#L17-L27
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/templatetags/i18n.py
python
GetLanguageInfoNode.__init__
(self, lang_code, variable)
[]
def __init__(self, lang_code, variable): self.lang_code = lang_code self.variable = variable
[ "def", "__init__", "(", "self", ",", "lang_code", ",", "variable", ")", ":", "self", ".", "lang_code", "=", "lang_code", "self", ".", "variable", "=", "variable" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/templatetags/i18n.py#L25-L27
pytroll/satpy
09e51f932048f98cce7919a4ff8bd2ec01e1ae98
satpy/readers/goes_imager_nc.py
python
GOESNCBaseFileHandler._viscounts2radiance
(counts, slope, offset)
return rad.clip(min=0)
Convert VIS counts to radiance. References: [VIS] Args: counts: Raw detector counts slope: Slope [W m-2 um-1 sr-1] offset: Offset [W m-2 um-1 sr-1] Returns: Radiance [W m-2 um-1 sr-1]
Convert VIS counts to radiance.
[ "Convert", "VIS", "counts", "to", "radiance", "." ]
def _viscounts2radiance(counts, slope, offset): """Convert VIS counts to radiance. References: [VIS] Args: counts: Raw detector counts slope: Slope [W m-2 um-1 sr-1] offset: Offset [W m-2 um-1 sr-1] Returns: Radiance [W m-2 um-1 sr-1] """ rad = counts * slope + offset return rad.clip(min=0)
[ "def", "_viscounts2radiance", "(", "counts", ",", "slope", ",", "offset", ")", ":", "rad", "=", "counts", "*", "slope", "+", "offset", "return", "rad", ".", "clip", "(", "min", "=", "0", ")" ]
https://github.com/pytroll/satpy/blob/09e51f932048f98cce7919a4ff8bd2ec01e1ae98/satpy/readers/goes_imager_nc.py#L883-L896
fake-name/ChromeController
6c70d855e33e06463516b263bf9e6f34c48e29e8
ChromeController/Generator/Generated.py
python
ChromeRemoteDebugInterface.Target_activateTarget
(self, targetId)
return subdom_funcs
Function path: Target.activateTarget Domain: Target Method name: activateTarget Parameters: Required arguments: 'targetId' (type: TargetID) -> No description No return value. Description: Activates (focuses) the target.
Function path: Target.activateTarget Domain: Target Method name: activateTarget Parameters: Required arguments: 'targetId' (type: TargetID) -> No description No return value. Description: Activates (focuses) the target.
[ "Function", "path", ":", "Target", ".", "activateTarget", "Domain", ":", "Target", "Method", "name", ":", "activateTarget", "Parameters", ":", "Required", "arguments", ":", "targetId", "(", "type", ":", "TargetID", ")", "-", ">", "No", "description", "No", "...
def Target_activateTarget(self, targetId): """ Function path: Target.activateTarget Domain: Target Method name: activateTarget Parameters: Required arguments: 'targetId' (type: TargetID) -> No description No return value. Description: Activates (focuses) the target. """ subdom_funcs = self.synchronous_command('Target.activateTarget', targetId =targetId) return subdom_funcs
[ "def", "Target_activateTarget", "(", "self", ",", "targetId", ")", ":", "subdom_funcs", "=", "self", ".", "synchronous_command", "(", "'Target.activateTarget'", ",", "targetId", "=", "targetId", ")", "return", "subdom_funcs" ]
https://github.com/fake-name/ChromeController/blob/6c70d855e33e06463516b263bf9e6f34c48e29e8/ChromeController/Generator/Generated.py#L9140-L9155
Scifabric/pybossa
fd87953c067a94ae211cd8771d4eead130ef3c64
pybossa/util.py
python
Pagination.to_json
(self)
return dict(page=self.page, per_page=self.per_page, total=self.total_count, next=self.has_next, prev=self.has_prev)
Return the object in JSON format.
Return the object in JSON format.
[ "Return", "the", "object", "in", "JSON", "format", "." ]
def to_json(self): """Return the object in JSON format.""" return dict(page=self.page, per_page=self.per_page, total=self.total_count, next=self.has_next, prev=self.has_prev)
[ "def", "to_json", "(", "self", ")", ":", "return", "dict", "(", "page", "=", "self", ".", "page", ",", "per_page", "=", "self", ".", "per_page", ",", "total", "=", "self", ".", "total_count", ",", "next", "=", "self", ".", "has_next", ",", "prev", ...
https://github.com/Scifabric/pybossa/blob/fd87953c067a94ae211cd8771d4eead130ef3c64/pybossa/util.py#L280-L286
joxeankoret/pyew
8eb3e49a9bf57c0787fa79ecae0671129ef3f2e8
pymsasid/decode.py
python
decode_o
(u, inst, s, op)
Decodes offset.
Decodes offset.
[ "Decodes", "offset", "." ]
def decode_o(u, inst, s, op): """Decodes offset.""" op.seg = inst.pfx.seg op.offset = inst.adr_mode op.lval = u.input.read(inst.adr_mode) op.type = 'OP_MEM' op.size = resolve_operand_size(u, inst, s)
[ "def", "decode_o", "(", "u", ",", "inst", ",", "s", ",", "op", ")", ":", "op", ".", "seg", "=", "inst", ".", "pfx", ".", "seg", "op", ".", "offset", "=", "inst", ".", "adr_mode", "op", ".", "lval", "=", "u", ".", "input", ".", "read", "(", ...
https://github.com/joxeankoret/pyew/blob/8eb3e49a9bf57c0787fa79ecae0671129ef3f2e8/pymsasid/decode.py#L532-L538
akanimax/Variational_Discriminator_Bottleneck
26a39ddbf9ee2213dbc1b60894a9092b1a5d3710
source/vdb/Losses.py
python
GANLossWithBottleneck._bottleneck_loss
(mus, sigmas, i_c, alpha=1e-8)
return bottleneck_loss
calculate the bottleneck loss for the given mus and sigmas :param mus: means of the gaussian distributions :param sigmas: stds of the gaussian distributions :param i_c: value of bottleneck :param alpha: small value for numerical stability :return: loss_value: scalar tensor
calculate the bottleneck loss for the given mus and sigmas :param mus: means of the gaussian distributions :param sigmas: stds of the gaussian distributions :param i_c: value of bottleneck :param alpha: small value for numerical stability :return: loss_value: scalar tensor
[ "calculate", "the", "bottleneck", "loss", "for", "the", "given", "mus", "and", "sigmas", ":", "param", "mus", ":", "means", "of", "the", "gaussian", "distributions", ":", "param", "sigmas", ":", "stds", "of", "the", "gaussian", "distributions", ":", "param",...
def _bottleneck_loss(mus, sigmas, i_c, alpha=1e-8): """ calculate the bottleneck loss for the given mus and sigmas :param mus: means of the gaussian distributions :param sigmas: stds of the gaussian distributions :param i_c: value of bottleneck :param alpha: small value for numerical stability :return: loss_value: scalar tensor """ # add a small value to sigmas to avoid inf log kl_divergence = (0.5 * th.sum((mus ** 2) + (sigmas ** 2) - th.log((sigmas ** 2) + alpha) - 1, dim=1)) # calculate the bottleneck loss: bottleneck_loss = (th.mean(kl_divergence) - i_c) # return the bottleneck_loss: return bottleneck_loss
[ "def", "_bottleneck_loss", "(", "mus", ",", "sigmas", ",", "i_c", ",", "alpha", "=", "1e-8", ")", ":", "# add a small value to sigmas to avoid inf log", "kl_divergence", "=", "(", "0.5", "*", "th", ".", "sum", "(", "(", "mus", "**", "2", ")", "+", "(", "...
https://github.com/akanimax/Variational_Discriminator_Bottleneck/blob/26a39ddbf9ee2213dbc1b60894a9092b1a5d3710/source/vdb/Losses.py#L33-L50
galaxyproject/galaxy
4c03520f05062e0f4a1b3655dc0b7452fda69943
lib/galaxy/webapps/galaxy/controllers/workflow.py
python
WorkflowController.load_workflow
(self, trans, id, version=None)
return workflow_contents_manager.workflow_to_dict(trans, stored, style="editor", version=version)
Get the latest Workflow for the StoredWorkflow identified by `id` and encode it as a json string that can be read by the workflow editor web interface.
Get the latest Workflow for the StoredWorkflow identified by `id` and encode it as a json string that can be read by the workflow editor web interface.
[ "Get", "the", "latest", "Workflow", "for", "the", "StoredWorkflow", "identified", "by", "id", "and", "encode", "it", "as", "a", "json", "string", "that", "can", "be", "read", "by", "the", "workflow", "editor", "web", "interface", "." ]
def load_workflow(self, trans, id, version=None): """ Get the latest Workflow for the StoredWorkflow identified by `id` and encode it as a json string that can be read by the workflow editor web interface. """ trans.workflow_building_mode = workflow_building_modes.ENABLED stored = self.get_stored_workflow(trans, id, check_ownership=True, check_accessible=False) workflow_contents_manager = self.app.workflow_contents_manager return workflow_contents_manager.workflow_to_dict(trans, stored, style="editor", version=version)
[ "def", "load_workflow", "(", "self", ",", "trans", ",", "id", ",", "version", "=", "None", ")", ":", "trans", ".", "workflow_building_mode", "=", "workflow_building_modes", ".", "ENABLED", "stored", "=", "self", ".", "get_stored_workflow", "(", "trans", ",", ...
https://github.com/galaxyproject/galaxy/blob/4c03520f05062e0f4a1b3655dc0b7452fda69943/lib/galaxy/webapps/galaxy/controllers/workflow.py#L735-L744
crits/crits_services
c7abf91f1865d913cffad4b966599da204f8ae43
taxii_service/migrate.py
python
migrate_1_to_2
(self)
Migrate from schema 1 to 2.
Migrate from schema 1 to 2.
[ "Migrate", "from", "schema", "1", "to", "2", "." ]
def migrate_1_to_2(self): """ Migrate from schema 1 to 2. """ if self.schema_version < 1: migrate_0_to_1(self) if self.schema_version == 1: if self.unsupported_attrs: if self.unsupported_attrs.timestamp: ts = self.unsupported_attrs.timestamp self.block_label = ts.strftime('%Y-%m-%d %H:%M:%S') del self.unsupported_attrs.timestamp if not self.unsupported_attrs.to_dict(): del self.unsupported_attrs self.schema_version = 2 self.save()
[ "def", "migrate_1_to_2", "(", "self", ")", ":", "if", "self", ".", "schema_version", "<", "1", ":", "migrate_0_to_1", "(", "self", ")", "if", "self", ".", "schema_version", "==", "1", ":", "if", "self", ".", "unsupported_attrs", ":", "if", "self", ".", ...
https://github.com/crits/crits_services/blob/c7abf91f1865d913cffad4b966599da204f8ae43/taxii_service/migrate.py#L8-L25
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/pip/_vendor/cachecontrol/_cmd.py
python
setup_logging
()
[]
def setup_logging(): logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() logger.addHandler(handler)
[ "def", "setup_logging", "(", ")", ":", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "logger", ".", "addHandler", "(", "handler", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/_vendor/cachecontrol/_cmd.py#L12-L15
googlearchive/pywebsocket
c459a5f9a04714e596726e876fcb46951c61a5f7
mod_pywebsocket/dispatch.py
python
_enumerate_handler_file_paths
(directory)
Returns a generator that enumerates WebSocket Handler source file names in the given directory.
Returns a generator that enumerates WebSocket Handler source file names in the given directory.
[ "Returns", "a", "generator", "that", "enumerates", "WebSocket", "Handler", "source", "file", "names", "in", "the", "given", "directory", "." ]
def _enumerate_handler_file_paths(directory): """Returns a generator that enumerates WebSocket Handler source file names in the given directory. """ for root, unused_dirs, files in os.walk(directory): for base in files: path = os.path.join(root, base) if _SOURCE_PATH_PATTERN.search(path): yield path
[ "def", "_enumerate_handler_file_paths", "(", "directory", ")", ":", "for", "root", ",", "unused_dirs", ",", "files", "in", "os", ".", "walk", "(", "directory", ")", ":", "for", "base", "in", "files", ":", "path", "=", "os", ".", "path", ".", "join", "(...
https://github.com/googlearchive/pywebsocket/blob/c459a5f9a04714e596726e876fcb46951c61a5f7/mod_pywebsocket/dispatch.py#L114-L123
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
opy/compiler2/transformer.py
python
Transformer.for_stmt
(self, nodelist)
return For(assignNode, listNode, bodyNode, elseNode, lineno=nodelist[0][2])
[]
def for_stmt(self, nodelist): # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] assignNode = self.com_assign(nodelist[1], OP_ASSIGN) listNode = self.com_node(nodelist[3]) bodyNode = self.com_node(nodelist[5]) if len(nodelist) > 8: elseNode = self.com_node(nodelist[8]) else: elseNode = None return For(assignNode, listNode, bodyNode, elseNode, lineno=nodelist[0][2])
[ "def", "for_stmt", "(", "self", ",", "nodelist", ")", ":", "# 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]", "assignNode", "=", "self", ".", "com_assign", "(", "nodelist", "[", "1", "]", ",", "OP_ASSIGN", ")", "listNode", "=", "self", ".", "com_node",...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/opy/compiler2/transformer.py#L618-L631
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
rpython/memory/gc/generation.py
python
GenerationGC.trace_and_drag_out_of_nursery
(self, obj)
obj must not be in the nursery. This copies all the young objects it references out of the nursery.
obj must not be in the nursery. This copies all the young objects it references out of the nursery.
[ "obj", "must", "not", "be", "in", "the", "nursery", ".", "This", "copies", "all", "the", "young", "objects", "it", "references", "out", "of", "the", "nursery", "." ]
def trace_and_drag_out_of_nursery(self, obj): """obj must not be in the nursery. This copies all the young objects it references out of the nursery. """ self.trace(obj, self._trace_drag_out, None)
[ "def", "trace_and_drag_out_of_nursery", "(", "self", ",", "obj", ")", ":", "self", ".", "trace", "(", "obj", ",", "self", ".", "_trace_drag_out", ",", "None", ")" ]
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/rpython/memory/gc/generation.py#L446-L450
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/bleach/_vendor/html5lib/_trie/_base.py
python
Trie.longest_prefix_item
(self, prefix)
return (lprefix, self[lprefix])
[]
def longest_prefix_item(self, prefix): lprefix = self.longest_prefix(prefix) return (lprefix, self[lprefix])
[ "def", "longest_prefix_item", "(", "self", ",", "prefix", ")", ":", "lprefix", "=", "self", ".", "longest_prefix", "(", "prefix", ")", "return", "(", "lprefix", ",", "self", "[", "lprefix", "]", ")" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/bleach/_vendor/html5lib/_trie/_base.py#L38-L40
thomaxxl/safrs
bc97c81f58bbcf6441797ea92f11ef855ca54e61
safrs/jsonapi.py
python
SAFRSRestAPI._patch_instance
(self, data, id=None)
return instance
Update the inst :param data: jsonapi payload :param id: jsonapi id :return: instance
Update the inst :param data: jsonapi payload :param id: jsonapi id :return: instance
[ "Update", "the", "inst", ":", "param", "data", ":", "jsonapi", "payload", ":", "param", "id", ":", "jsonapi", "id", ":", "return", ":", "instance" ]
def _patch_instance(self, data, id=None): """ Update the inst :param data: jsonapi payload :param id: jsonapi id :return: instance """ # validate the jsonapi id in the url path and convert it to a database id path_id = self.SAFRSObject.id_type.validate_id(id) # Check that the id in the body is equal to the id in the url body_id = data.get("id", None) if body_id is None: raise ValidationError("No ID in body") body_id = self.SAFRSObject.id_type.validate_id(body_id) if path_id is not None and path_id != body_id: raise ValidationError(f"Invalid ID {type(path_id)} {path_id} != {type(body_id)} {body_id}") attributes = data.get("attributes", {}) attributes["id"] = body_id # Create the object instance with the specified id and json data # If the instance (id) already exists, it will be updated with the data instance = self._parse_target_data(data) if not instance: raise ValidationError("No instance with ID") instance._s_patch(**attributes) return instance
[ "def", "_patch_instance", "(", "self", ",", "data", ",", "id", "=", "None", ")", ":", "# validate the jsonapi id in the url path and convert it to a database id", "path_id", "=", "self", ".", "SAFRSObject", ".", "id_type", ".", "validate_id", "(", "id", ")", "# Chec...
https://github.com/thomaxxl/safrs/blob/bc97c81f58bbcf6441797ea92f11ef855ca54e61/safrs/jsonapi.py#L328-L355
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/plugins/attack/db/sqlmap/lib/core/common.py
python
Backend.setVersionList
(versionsList)
[]
def setVersionList(versionsList): if isinstance(versionsList, list): kb.dbmsVersion = versionsList elif isinstance(versionsList, basestring): Backend.setVersion(versionsList) else: logger.error("invalid format of versionsList")
[ "def", "setVersionList", "(", "versionsList", ")", ":", "if", "isinstance", "(", "versionsList", ",", "list", ")", ":", "kb", ".", "dbmsVersion", "=", "versionsList", "elif", "isinstance", "(", "versionsList", ",", "basestring", ")", ":", "Backend", ".", "se...
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/attack/db/sqlmap/lib/core/common.py#L354-L360
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-build/python-libs/gdata/build/lib/gdata/Crypto/Hash/HMAC.py
python
HMAC.digest
(self)
return h.digest()
Return the hash value of this hashing object. This returns a string containing 8-bit data. The object is not altered in any way by this function; you can continue updating the object after calling this function.
Return the hash value of this hashing object.
[ "Return", "the", "hash", "value", "of", "this", "hashing", "object", "." ]
def digest(self): """Return the hash value of this hashing object. This returns a string containing 8-bit data. The object is not altered in any way by this function; you can continue updating the object after calling this function. """ h = self.outer.copy() h.update(self.inner.digest()) return h.digest()
[ "def", "digest", "(", "self", ")", ":", "h", "=", "self", ".", "outer", ".", "copy", "(", ")", "h", ".", "update", "(", "self", ".", "inner", ".", "digest", "(", ")", ")", "return", "h", ".", "digest", "(", ")" ]
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/gdata/build/lib/gdata/Crypto/Hash/HMAC.py#L79-L88
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/CFNetwork/__init__.py
python
CFSocketStreamSOCKSGetError
(err)
return err.error & 0xFFFF
[]
def CFSocketStreamSOCKSGetError(err): return err.error & 0xFFFF
[ "def", "CFSocketStreamSOCKSGetError", "(", "err", ")", ":", "return", "err", ".", "error", "&", "0xFFFF" ]
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/CFNetwork/__init__.py#L15-L16
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/nodes/NodeBases.py
python
NodeBase.mayHaveSideEffects
()
return True
Unless we are told otherwise, everything may have a side effect.
Unless we are told otherwise, everything may have a side effect.
[ "Unless", "we", "are", "told", "otherwise", "everything", "may", "have", "a", "side", "effect", "." ]
def mayHaveSideEffects(): """Unless we are told otherwise, everything may have a side effect.""" return True
[ "def", "mayHaveSideEffects", "(", ")", ":", "return", "True" ]
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/nodes/NodeBases.py#L418-L421
inkandswitch/livebook
93c8d467734787366ad084fc3566bf5cbe249c51
public/pypyjs/modules/numpy/lib/financial.py
python
ipmt
(rate, per, nper, pv, fv=0.0, when='end')
return ipmt
Compute the interest portion of a payment. Parameters ---------- rate : scalar or array_like of shape(M, ) Rate of interest as decimal (not per cent) per period per : scalar or array_like of shape(M, ) Interest paid against the loan changes during the life or the loan. The `per` is the payment period to calculate the interest amount. nper : scalar or array_like of shape(M, ) Number of compounding periods pv : scalar or array_like of shape(M, ) Present value fv : scalar or array_like of shape(M, ), optional Future value when : {{'begin', 1}, {'end', 0}}, {string, int}, optional When payments are due ('begin' (1) or 'end' (0)). Defaults to {'end', 0}. Returns ------- out : ndarray Interest portion of payment. If all input is scalar, returns a scalar float. If any input is array_like, returns interest payment for each input element. If multiple inputs are array_like, they all must have the same shape. See Also -------- ppmt, pmt, pv Notes ----- The total payment is made up of payment against principal plus interest. ``pmt = ppmt + ipmt`` Examples -------- What is the amortization schedule for a 1 year loan of $2500 at 8.24% interest per year compounded monthly? >>> principal = 2500.00 The 'per' variable represents the periods of the loan. Remember that financial equations start the period count at 1! >>> per = np.arange(1*12) + 1 >>> ipmt = np.ipmt(0.0824/12, per, 1*12, principal) >>> ppmt = np.ppmt(0.0824/12, per, 1*12, principal) Each element of the sum of the 'ipmt' and 'ppmt' arrays should equal 'pmt'. >>> pmt = np.pmt(0.0824/12, 1*12, principal) >>> np.allclose(ipmt + ppmt, pmt) True >>> fmt = '{0:2d} {1:8.2f} {2:8.2f} {3:8.2f}' >>> for payment in per: ... index = payment - 1 ... principal = principal + ppmt[index] ... print fmt.format(payment, ppmt[index], ipmt[index], principal) 1 -200.58 -17.17 2299.42 2 -201.96 -15.79 2097.46 3 -203.35 -14.40 1894.11 4 -204.74 -13.01 1689.37 5 -206.15 -11.60 1483.22 6 -207.56 -10.18 1275.66 7 -208.99 -8.76 1066.67 8 -210.42 -7.32 856.25 9 -211.87 -5.88 644.38 10 -213.32 -4.42 431.05 11 -214.79 -2.96 216.26 12 -216.26 -1.49 -0.00 >>> interestpd = np.sum(ipmt) >>> np.round(interestpd, 2) -112.98
Compute the interest portion of a payment.
[ "Compute", "the", "interest", "portion", "of", "a", "payment", "." ]
def ipmt(rate, per, nper, pv, fv=0.0, when='end'): """ Compute the interest portion of a payment. Parameters ---------- rate : scalar or array_like of shape(M, ) Rate of interest as decimal (not per cent) per period per : scalar or array_like of shape(M, ) Interest paid against the loan changes during the life or the loan. The `per` is the payment period to calculate the interest amount. nper : scalar or array_like of shape(M, ) Number of compounding periods pv : scalar or array_like of shape(M, ) Present value fv : scalar or array_like of shape(M, ), optional Future value when : {{'begin', 1}, {'end', 0}}, {string, int}, optional When payments are due ('begin' (1) or 'end' (0)). Defaults to {'end', 0}. Returns ------- out : ndarray Interest portion of payment. If all input is scalar, returns a scalar float. If any input is array_like, returns interest payment for each input element. If multiple inputs are array_like, they all must have the same shape. See Also -------- ppmt, pmt, pv Notes ----- The total payment is made up of payment against principal plus interest. ``pmt = ppmt + ipmt`` Examples -------- What is the amortization schedule for a 1 year loan of $2500 at 8.24% interest per year compounded monthly? >>> principal = 2500.00 The 'per' variable represents the periods of the loan. Remember that financial equations start the period count at 1! >>> per = np.arange(1*12) + 1 >>> ipmt = np.ipmt(0.0824/12, per, 1*12, principal) >>> ppmt = np.ppmt(0.0824/12, per, 1*12, principal) Each element of the sum of the 'ipmt' and 'ppmt' arrays should equal 'pmt'. >>> pmt = np.pmt(0.0824/12, 1*12, principal) >>> np.allclose(ipmt + ppmt, pmt) True >>> fmt = '{0:2d} {1:8.2f} {2:8.2f} {3:8.2f}' >>> for payment in per: ... index = payment - 1 ... principal = principal + ppmt[index] ... print fmt.format(payment, ppmt[index], ipmt[index], principal) 1 -200.58 -17.17 2299.42 2 -201.96 -15.79 2097.46 3 -203.35 -14.40 1894.11 4 -204.74 -13.01 1689.37 5 -206.15 -11.60 1483.22 6 -207.56 -10.18 1275.66 7 -208.99 -8.76 1066.67 8 -210.42 -7.32 856.25 9 -211.87 -5.88 644.38 10 -213.32 -4.42 431.05 11 -214.79 -2.96 216.26 12 -216.26 -1.49 -0.00 >>> interestpd = np.sum(ipmt) >>> np.round(interestpd, 2) -112.98 """ when = _convert_when(when) rate, per, nper, pv, fv, when = np.broadcast_arrays(rate, per, nper, pv, fv, when) total_pmt = pmt(rate, nper, pv, fv, when) ipmt = _rbl(rate, per, total_pmt, pv, when)*rate try: ipmt = np.where(when == 1, ipmt/(1 + rate), ipmt) ipmt = np.where(np.logical_and(when == 1, per == 1), 0.0, ipmt) except IndexError: pass return ipmt
[ "def", "ipmt", "(", "rate", ",", "per", ",", "nper", ",", "pv", ",", "fv", "=", "0.0", ",", "when", "=", "'end'", ")", ":", "when", "=", "_convert_when", "(", "when", ")", "rate", ",", "per", ",", "nper", ",", "pv", ",", "fv", ",", "when", "=...
https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/numpy/lib/financial.py#L286-L379
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
info
(*args)
return _idaapi.info(*args)
info(format)
info(format)
[ "info", "(", "format", ")" ]
def info(*args): """ info(format) """ return _idaapi.info(*args)
[ "def", "info", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "info", "(", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L43669-L43673
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
extensions/pyRevitCore.extension/pyRevit.tab/pyRevit.panel/Settings.smartbutton/script.py
python
SettingsWindow.update_apptelemetry_status
(self, status)
Update app telemetry server status light
Update app telemetry server status light
[ "Update", "app", "telemetry", "server", "status", "light" ]
def update_apptelemetry_status(self, status): """Update app telemetry server status light""" self.update_status_lights( status, self.apptelemetryserver_statusbox, self.apptelemetryserver_statusmsg )
[ "def", "update_apptelemetry_status", "(", "self", ",", "status", ")", ":", "self", ".", "update_status_lights", "(", "status", ",", "self", ".", "apptelemetryserver_statusbox", ",", "self", ".", "apptelemetryserver_statusmsg", ")" ]
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/extensions/pyRevitCore.extension/pyRevit.tab/pyRevit.panel/Settings.smartbutton/script.py#L581-L587
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/networkx/classes/multigraph.py
python
MultiGraph.to_undirected
(self, as_view=False)
return G
Return an undirected copy of the graph. Returns ------- G : Graph/MultiGraph A deepcopy of the graph. See Also -------- copy, add_edge, add_edges_from Notes ----- This returns a "deepcopy" of the edge, node, and graph attributes which attempts to completely copy all of the data and references. This is in contrast to the similar `G = nx.MultiGraph(D)` which returns a shallow copy of the data. See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/copy.html. Warning: If you have subclassed MultiiGraph to use dict-like objects in the data structure, those changes do not transfer to the MultiGraph created by this method. Examples -------- >>> G = nx.path_graph(2) # or MultiGraph, etc >>> H = G.to_directed() >>> list(H.edges) [(0, 1), (1, 0)] >>> G2 = H.to_undirected() >>> list(G2.edges) [(0, 1)]
Return an undirected copy of the graph.
[ "Return", "an", "undirected", "copy", "of", "the", "graph", "." ]
def to_undirected(self, as_view=False): """Return an undirected copy of the graph. Returns ------- G : Graph/MultiGraph A deepcopy of the graph. See Also -------- copy, add_edge, add_edges_from Notes ----- This returns a "deepcopy" of the edge, node, and graph attributes which attempts to completely copy all of the data and references. This is in contrast to the similar `G = nx.MultiGraph(D)` which returns a shallow copy of the data. See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/copy.html. Warning: If you have subclassed MultiiGraph to use dict-like objects in the data structure, those changes do not transfer to the MultiGraph created by this method. Examples -------- >>> G = nx.path_graph(2) # or MultiGraph, etc >>> H = G.to_directed() >>> list(H.edges) [(0, 1), (1, 0)] >>> G2 = H.to_undirected() >>> list(G2.edges) [(0, 1)] """ if as_view is True: return nx.graphviews.MultiGraphView(self) # deepcopy when not a view G = MultiGraph() G.graph.update(deepcopy(self.graph)) G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items()) G.add_edges_from((u, v, key, deepcopy(datadict)) for u, nbrs in self.adj.items() for v, keydict in nbrs.items() for key, datadict in keydict.items()) return G
[ "def", "to_undirected", "(", "self", ",", "as_view", "=", "False", ")", ":", "if", "as_view", "is", "True", ":", "return", "nx", ".", "graphviews", ".", "MultiGraphView", "(", "self", ")", "# deepcopy when not a view", "G", "=", "MultiGraph", "(", ")", "G"...
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/networkx/classes/multigraph.py#L1004-L1052
home-assistant/supervisor
69c2517d5211b483fdfe968b0a2b36b672ee7ab2
supervisor/misc/tasks.py
python
Tasks.load
(self)
Add Tasks to scheduler.
Add Tasks to scheduler.
[ "Add", "Tasks", "to", "scheduler", "." ]
async def load(self): """Add Tasks to scheduler.""" # Update self.sys_scheduler.register_task(self._update_addons, RUN_UPDATE_ADDONS) self.sys_scheduler.register_task(self._update_supervisor, RUN_UPDATE_SUPERVISOR) self.sys_scheduler.register_task(self._update_cli, RUN_UPDATE_CLI) self.sys_scheduler.register_task(self._update_dns, RUN_UPDATE_DNS) self.sys_scheduler.register_task(self._update_audio, RUN_UPDATE_AUDIO) self.sys_scheduler.register_task(self._update_multicast, RUN_UPDATE_MULTICAST) self.sys_scheduler.register_task(self._update_observer, RUN_UPDATE_OBSERVER) # Reload self.sys_scheduler.register_task(self.sys_store.reload, RUN_RELOAD_ADDONS) self.sys_scheduler.register_task(self.sys_updater.reload, RUN_RELOAD_UPDATER) self.sys_scheduler.register_task(self.sys_backups.reload, RUN_RELOAD_BACKUPS) self.sys_scheduler.register_task(self.sys_host.reload, RUN_RELOAD_HOST) self.sys_scheduler.register_task(self.sys_ingress.reload, RUN_RELOAD_INGRESS) # Watchdog self.sys_scheduler.register_task( self._watchdog_homeassistant_docker, RUN_WATCHDOG_HOMEASSISTANT_DOCKER ) self.sys_scheduler.register_task( self._watchdog_homeassistant_api, RUN_WATCHDOG_HOMEASSISTANT_API ) self.sys_scheduler.register_task( self._watchdog_dns_docker, RUN_WATCHDOG_DNS_DOCKER ) self.sys_scheduler.register_task( self._watchdog_audio_docker, RUN_WATCHDOG_AUDIO_DOCKER ) self.sys_scheduler.register_task( self._watchdog_cli_docker, RUN_WATCHDOG_CLI_DOCKER ) self.sys_scheduler.register_task( self._watchdog_observer_docker, RUN_WATCHDOG_OBSERVER_DOCKER ) self.sys_scheduler.register_task( self._watchdog_observer_application, RUN_WATCHDOG_OBSERVER_APPLICATION ) self.sys_scheduler.register_task( self._watchdog_multicast_docker, RUN_WATCHDOG_MULTICAST_DOCKER ) self.sys_scheduler.register_task( self._watchdog_addon_docker, RUN_WATCHDOG_ADDON_DOCKER ) self.sys_scheduler.register_task( self._watchdog_addon_application, RUN_WATCHDOG_ADDON_APPLICATON ) # Refresh self.sys_scheduler.register_task(self._refresh_addon, RUN_REFRESH_ADDON) # Connectivity self.sys_scheduler.register_task( self._check_connectivity, RUN_CHECK_CONNECTIVITY ) _LOGGER.info("All core tasks are scheduled")
[ "async", "def", "load", "(", "self", ")", ":", "# Update", "self", ".", "sys_scheduler", ".", "register_task", "(", "self", ".", "_update_addons", ",", "RUN_UPDATE_ADDONS", ")", "self", ".", "sys_scheduler", ".", "register_task", "(", "self", ".", "_update_sup...
https://github.com/home-assistant/supervisor/blob/69c2517d5211b483fdfe968b0a2b36b672ee7ab2/supervisor/misc/tasks.py#L62-L120
Blizzard/heroprotocol
3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c
heroprotocol/versions/protocol31090.py
python
decode_replay_initdata
(contents)
return decoder.instance(replay_initdata_typeid)
Decodes and return the replay init data from the contents byte string.
Decodes and return the replay init data from the contents byte string.
[ "Decodes", "and", "return", "the", "replay", "init", "data", "from", "the", "contents", "byte", "string", "." ]
def decode_replay_initdata(contents): """Decodes and return the replay init data from the contents byte string.""" decoder = BitPackedDecoder(contents, typeinfos) return decoder.instance(replay_initdata_typeid)
[ "def", "decode_replay_initdata", "(", "contents", ")", ":", "decoder", "=", "BitPackedDecoder", "(", "contents", ",", "typeinfos", ")", "return", "decoder", ".", "instance", "(", "replay_initdata_typeid", ")" ]
https://github.com/Blizzard/heroprotocol/blob/3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c/heroprotocol/versions/protocol31090.py#L442-L445
kozec/syncthing-gtk
01eeeb9ed485232e145bf39d90142832e1c9751e
syncthing_gtk/daemon.py
python
RESTRequest._format_request
(self)
return "\r\n".join([ "GET /rest/%s HTTP/1.0" % self._command, "Host: %s" % self._parent._address, "Cookie: %s" % self._parent._CSRFtoken, (("X-%s" % self._parent._CSRFtoken.replace("=", ": ")) if self._parent._CSRFtoken else "X-nothing: x"), (("X-API-Key: %s" % self._parent._api_key) if not self._parent._api_key is None else "X-nothing2: x"), "Connection: close", "", "" ]).encode("utf-8")
Formats HTTP request (GET /xyz HTTP/1.0... ) before sending it to daemon
Formats HTTP request (GET /xyz HTTP/1.0... ) before sending it to daemon
[ "Formats", "HTTP", "request", "(", "GET", "/", "xyz", "HTTP", "/", "1", ".", "0", "...", ")", "before", "sending", "it", "to", "daemon" ]
def _format_request(self): """ Formats HTTP request (GET /xyz HTTP/1.0... ) before sending it to daemon """ return "\r\n".join([ "GET /rest/%s HTTP/1.0" % self._command, "Host: %s" % self._parent._address, "Cookie: %s" % self._parent._CSRFtoken, (("X-%s" % self._parent._CSRFtoken.replace("=", ": ")) if self._parent._CSRFtoken else "X-nothing: x"), (("X-API-Key: %s" % self._parent._api_key) if not self._parent._api_key is None else "X-nothing2: x"), "Connection: close", "", "" ]).encode("utf-8")
[ "def", "_format_request", "(", "self", ")", ":", "return", "\"\\r\\n\"", ".", "join", "(", "[", "\"GET /rest/%s HTTP/1.0\"", "%", "self", ".", "_command", ",", "\"Host: %s\"", "%", "self", ".", "_parent", ".", "_address", ",", "\"Cookie: %s\"", "%", "self", ...
https://github.com/kozec/syncthing-gtk/blob/01eeeb9ed485232e145bf39d90142832e1c9751e/syncthing_gtk/daemon.py#L1105-L1117
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/boto-2.46.1/boto/kms/layer1.py
python
KMSConnection.list_aliases
(self, limit=None, marker=None)
return self.make_request(action='ListAliases', body=json.dumps(params))
Lists all of the key aliases in the account. :type limit: integer :param limit: Specify this parameter when paginating results to indicate the maximum number of aliases you want in each response. If there are additional aliases beyond the maximum you specify, the `Truncated` response element will be set to `true.` :type marker: string :param marker: Use this parameter when paginating results, and only in a subsequent request after you've received a response where the results are truncated. Set it to the value of the `NextMarker` element in the response you just received.
Lists all of the key aliases in the account.
[ "Lists", "all", "of", "the", "key", "aliases", "in", "the", "account", "." ]
def list_aliases(self, limit=None, marker=None): """ Lists all of the key aliases in the account. :type limit: integer :param limit: Specify this parameter when paginating results to indicate the maximum number of aliases you want in each response. If there are additional aliases beyond the maximum you specify, the `Truncated` response element will be set to `true.` :type marker: string :param marker: Use this parameter when paginating results, and only in a subsequent request after you've received a response where the results are truncated. Set it to the value of the `NextMarker` element in the response you just received. """ params = {} if limit is not None: params['Limit'] = limit if marker is not None: params['Marker'] = marker return self.make_request(action='ListAliases', body=json.dumps(params))
[ "def", "list_aliases", "(", "self", ",", "limit", "=", "None", ",", "marker", "=", "None", ")", ":", "params", "=", "{", "}", "if", "limit", "is", "not", "None", ":", "params", "[", "'Limit'", "]", "=", "limit", "if", "marker", "is", "not", "None",...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/boto-2.46.1/boto/kms/layer1.py#L569-L592
dmlc/dgl
8d14a739bc9e446d6c92ef83eafe5782398118de
python/dgl/backend/backend.py
python
sync
()
Synchronize computation. In DL frameworks such as MXNet and TensorFlow, the computation in operators are done asynchronously. This is to synchronize computation and makes sure that all computation is complete after this function call.
Synchronize computation.
[ "Synchronize", "computation", "." ]
def sync(): """Synchronize computation. In DL frameworks such as MXNet and TensorFlow, the computation in operators are done asynchronously. This is to synchronize computation and makes sure that all computation is complete after this function call. """ pass
[ "def", "sync", "(", ")", ":", "pass" ]
https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/python/dgl/backend/backend.py#L1807-L1814
TensorMSA/tensormsa
c36b565159cd934533636429add3c7d7263d622b
master/workflow/netconf/workflow_netconf_seq2seq.py
python
WorkFlowNetConfSeq2Seq.get_vocab_size
(self)
return self.conf.get('vocab_size')
:param node_id: :return:
[]
def get_vocab_size(self): """ :param node_id: :return: """ if ('conf' not in self.__dict__): self.conf = self.get_view_obj(self.key) return self.conf.get('vocab_size')
[ "def", "get_vocab_size", "(", "self", ")", ":", "if", "(", "'conf'", "not", "in", "self", ".", "__dict__", ")", ":", "self", ".", "conf", "=", "self", ".", "get_view_obj", "(", "self", ".", "key", ")", "return", "self", ".", "conf", ".", "get", "("...
https://github.com/TensorMSA/tensormsa/blob/c36b565159cd934533636429add3c7d7263d622b/master/workflow/netconf/workflow_netconf_seq2seq.py#L190-L198
brython-dev/brython
9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3
www/src/Lib/pydoc.py
python
classname
(object, modname)
return name
Get a class name and qualify it with a module name if necessary.
Get a class name and qualify it with a module name if necessary.
[ "Get", "a", "class", "name", "and", "qualify", "it", "with", "a", "module", "name", "if", "necessary", "." ]
def classname(object, modname): """Get a class name and qualify it with a module name if necessary.""" name = object.__name__ if object.__module__ != modname: name = object.__module__ + '.' + name return name
[ "def", "classname", "(", "object", ",", "modname", ")", ":", "name", "=", "object", ".", "__name__", "if", "object", ".", "__module__", "!=", "modname", ":", "name", "=", "object", ".", "__module__", "+", "'.'", "+", "name", "return", "name" ]
https://github.com/brython-dev/brython/blob/9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3/www/src/Lib/pydoc.py#L199-L204
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/plistlib.py
python
UID.__eq__
(self, other)
return self.data == other.data
[]
def __eq__(self, other): if not isinstance(other, UID): return NotImplemented return self.data == other.data
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "UID", ")", ":", "return", "NotImplemented", "return", "self", ".", "data", "==", "other", ".", "data" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/plistlib.py#L197-L200
entropy1337/infernal-twin
10995cd03312e39a48ade0f114ebb0ae3a711bb8
Modules/build/reportlab/src/reportlab/lib/utils.py
python
recursiveImport
(modulename, baseDir=None, noCWD=0, debug=0)
Dynamically imports possible packagized module, or raises ImportError
Dynamically imports possible packagized module, or raises ImportError
[ "Dynamically", "imports", "possible", "packagized", "module", "or", "raises", "ImportError" ]
def recursiveImport(modulename, baseDir=None, noCWD=0, debug=0): """Dynamically imports possible packagized module, or raises ImportError""" normalize = lambda x: os.path.normcase(os.path.abspath(os.path.normpath(x))) path = [normalize(p) for p in sys.path] if baseDir: if not isSeq(baseDir): tp = [baseDir] else: tp = filter(None,list(baseDir)) for p in tp: p = normalize(p) if p not in path: path.insert(0,p) if noCWD: for p in ('','.',normalize('.')): while p in path: if debug: print('removed "%s" from path' % p) path.remove(p) elif '.' not in path: path.insert(0,'.') if debug: import pprint pp = pprint.pprint print('path=') pp(path) #make import errors a bit more informative opath = sys.path try: try: sys.path = path NS = {} rl_exec('import %s as m' % modulename,NS) return NS['m'] except ImportError: sys.path = opath msg = "Could not import '%s'" % modulename if baseDir: msg = msg + " under %s" % baseDir annotateException(msg) except: e = sys.exc_info() msg = "Exception raised while importing '%s': %s" % (modulename, e[1]) annotateException(msg) finally: sys.path = opath
[ "def", "recursiveImport", "(", "modulename", ",", "baseDir", "=", "None", ",", "noCWD", "=", "0", ",", "debug", "=", "0", ")", ":", "normalize", "=", "lambda", "x", ":", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(...
https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/reportlab/src/reportlab/lib/utils.py#L436-L482
paulwinex/pw_MultiScriptEditor
e447e99f87cb07e238baf693b7e124e50efdbc51
multi_script_editor/managers/nuke/callbacks.py
python
removeAutolabel
(call, args=(), kwargs={}, nodeClass='*')
Remove a previously-added callback with the same arguments.
Remove a previously-added callback with the same arguments.
[ "Remove", "a", "previously", "-", "added", "callback", "with", "the", "same", "arguments", "." ]
def removeAutolabel(call, args=(), kwargs={}, nodeClass='*'): """Remove a previously-added callback with the same arguments."""
[ "def", "removeAutolabel", "(", "call", ",", "args", "=", "(", ")", ",", "kwargs", "=", "{", "}", ",", "nodeClass", "=", "'*'", ")", ":" ]
https://github.com/paulwinex/pw_MultiScriptEditor/blob/e447e99f87cb07e238baf693b7e124e50efdbc51/multi_script_editor/managers/nuke/callbacks.py#L110-L111
Esri/ArcREST
ab240fde2b0200f61d4a5f6df033516e53f2f416
src/arcrest/hostedservice/service.py
python
AdminFeatureService.capabilities
(self)
return self._capabilities
returns a list of capabilities
returns a list of capabilities
[ "returns", "a", "list", "of", "capabilities" ]
def capabilities(self): """ returns a list of capabilities """ if self._capabilities is None: self.__init() return self._capabilities
[ "def", "capabilities", "(", "self", ")", ":", "if", "self", ".", "_capabilities", "is", "None", ":", "self", ".", "__init", "(", ")", "return", "self", ".", "_capabilities" ]
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/hostedservice/service.py#L862-L866
ValdikSS/blockcheck
81879695b768c28d12597718577cad2f6859b874
osx_hooks/hook-_tkinter.py
python
_collect_tcl_tk_files
(hook_api)
return (tcltree + tktree)
Get a list of TOC-style 3-tuples describing all external Tcl/Tk data files. Returns ------- Tree Such list.
Get a list of TOC-style 3-tuples describing all external Tcl/Tk data files.
[ "Get", "a", "list", "of", "TOC", "-", "style", "3", "-", "tuples", "describing", "all", "external", "Tcl", "/", "Tk", "data", "files", "." ]
def _collect_tcl_tk_files(hook_api): """ Get a list of TOC-style 3-tuples describing all external Tcl/Tk data files. Returns ------- Tree Such list. """ # Workaround for broken Tcl/Tk detection in virtualenv on Windows. _handle_broken_tcl_tk() tcl_root, tk_root = _find_tcl_tk(hook_api) # TODO Shouldn't these be fatal exceptions? if not tcl_root: logger.error('Tcl/Tk improperly installed on this system.') return [] if not os.path.isdir(tcl_root): logger.error('Tcl data directory "%s" not found.', tcl_root) return [] if not os.path.isdir(tk_root): logger.error('Tk data directory "%s" not found.', tk_root) return [] tcltree = Tree( tcl_root, prefix='tclResources', excludes=['demos', '*.lib', 'tclConfig.sh']) tktree = Tree( tk_root, prefix='tkResources', excludes=['demos', '*.lib', 'tkConfig.sh']) # If the current Tcl installation is a Teapot-distributed version of # ActiveTcl and the current platform is OS X, warn that this is bad. if is_darwin: _warn_if_activetcl_or_teapot_installed(tcl_root, tcltree) return (tcltree + tktree)
[ "def", "_collect_tcl_tk_files", "(", "hook_api", ")", ":", "# Workaround for broken Tcl/Tk detection in virtualenv on Windows.", "_handle_broken_tcl_tk", "(", ")", "tcl_root", ",", "tk_root", "=", "_find_tcl_tk", "(", "hook_api", ")", "# TODO Shouldn't these be fatal exceptions?"...
https://github.com/ValdikSS/blockcheck/blob/81879695b768c28d12597718577cad2f6859b874/osx_hooks/hook-_tkinter.py#L196-L231
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/idlelib/configHandler.py
python
IdleConf.SetOption
(self, configType, section, option, value)
Set section option to value in user config file.
Set section option to value in user config file.
[ "Set", "section", "option", "to", "value", "in", "user", "config", "file", "." ]
def SetOption(self, configType, section, option, value): """Set section option to value in user config file.""" self.userCfg[configType].SetOption(section, option, value)
[ "def", "SetOption", "(", "self", ",", "configType", ",", "section", ",", "option", ",", "value", ")", ":", "self", ".", "userCfg", "[", "configType", "]", ".", "SetOption", "(", "section", ",", "option", ",", "value", ")" ]
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/idlelib/configHandler.py#L261-L263
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/concurrent/futures/_base.py
python
_AsCompletedWaiter.add_result
(self, future)
[]
def add_result(self, future): with self.lock: super(_AsCompletedWaiter, self).add_result(future) self.event.set()
[ "def", "add_result", "(", "self", ",", "future", ")", ":", "with", "self", ".", "lock", ":", "super", "(", "_AsCompletedWaiter", ",", "self", ")", ".", "add_result", "(", "future", ")", "self", ".", "event", ".", "set", "(", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/concurrent/futures/_base.py#L82-L85
researchmm/TracKit
510e240faf71b4a225d6f18bcf49b3eebf8b436e
lib/models/online/classifier/features.py
python
residual_basic_block
(feature_dim=256, num_blocks=1, l2norm=True, final_conv=False, norm_scale=1.0, out_dim=None, interp_cat=False)
return nn.Sequential(*feat_layers)
Construct a network block based on the BasicBlock used in ResNet 18 and 34.
Construct a network block based on the BasicBlock used in ResNet 18 and 34.
[ "Construct", "a", "network", "block", "based", "on", "the", "BasicBlock", "used", "in", "ResNet", "18", "and", "34", "." ]
def residual_basic_block(feature_dim=256, num_blocks=1, l2norm=True, final_conv=False, norm_scale=1.0, out_dim=None, interp_cat=False): """Construct a network block based on the BasicBlock used in ResNet 18 and 34.""" if out_dim is None: out_dim = feature_dim feat_layers = [] if interp_cat: feat_layers.append(InterpCat()) for i in range(num_blocks): odim = feature_dim if i < num_blocks - 1 + int(final_conv) else out_dim feat_layers.append(BasicBlock(feature_dim, odim)) if final_conv: feat_layers.append(nn.Conv2d(feature_dim, out_dim, kernel_size=3, padding=1, bias=False)) if l2norm: feat_layers.append(InstanceL2Norm(scale=norm_scale)) return nn.Sequential(*feat_layers)
[ "def", "residual_basic_block", "(", "feature_dim", "=", "256", ",", "num_blocks", "=", "1", ",", "l2norm", "=", "True", ",", "final_conv", "=", "False", ",", "norm_scale", "=", "1.0", ",", "out_dim", "=", "None", ",", "interp_cat", "=", "False", ")", ":"...
https://github.com/researchmm/TracKit/blob/510e240faf71b4a225d6f18bcf49b3eebf8b436e/lib/models/online/classifier/features.py#L9-L24
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/twisted/internet/base.py
python
_ThreePhaseEvent.fireEvent
(self)
Call the triggers added to this event.
Call the triggers added to this event.
[ "Call", "the", "triggers", "added", "to", "this", "event", "." ]
def fireEvent(self): """ Call the triggers added to this event. """ self.state = 'BEFORE' self.finishedBefore = [] beforeResults = [] while self.before: callable, args, kwargs = self.before.pop(0) self.finishedBefore.append((callable, args, kwargs)) try: result = callable(*args, **kwargs) except: log.err() else: if isinstance(result, Deferred): beforeResults.append(result) DeferredList(beforeResults).addCallback(self._continueFiring)
[ "def", "fireEvent", "(", "self", ")", ":", "self", ".", "state", "=", "'BEFORE'", "self", ".", "finishedBefore", "=", "[", "]", "beforeResults", "=", "[", "]", "while", "self", ".", "before", ":", "callable", ",", "args", ",", "kwargs", "=", "self", ...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/twisted/internet/base.py#L417-L434
sametmax/Django--an-app-at-a-time
99eddf12ead76e6dfbeb09ce0bae61e282e22f8a
ignore_this_directory/django/db/backends/utils.py
python
split_identifier
(identifier)
return namespace.strip('"'), name.strip('"')
Split a SQL identifier into a two element tuple of (namespace, name). The identifier could be a table, column, or sequence name might be prefixed by a namespace.
Split a SQL identifier into a two element tuple of (namespace, name).
[ "Split", "a", "SQL", "identifier", "into", "a", "two", "element", "tuple", "of", "(", "namespace", "name", ")", "." ]
def split_identifier(identifier): """ Split a SQL identifier into a two element tuple of (namespace, name). The identifier could be a table, column, or sequence name might be prefixed by a namespace. """ try: namespace, name = identifier.split('"."') except ValueError: namespace, name = '', identifier return namespace.strip('"'), name.strip('"')
[ "def", "split_identifier", "(", "identifier", ")", ":", "try", ":", "namespace", ",", "name", "=", "identifier", ".", "split", "(", "'\".\"'", ")", "except", "ValueError", ":", "namespace", ",", "name", "=", "''", ",", "identifier", "return", "namespace", ...
https://github.com/sametmax/Django--an-app-at-a-time/blob/99eddf12ead76e6dfbeb09ce0bae61e282e22f8a/ignore_this_directory/django/db/backends/utils.py#L185-L196
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/core/power.py
python
Pow.as_base_exp
(self)
return b, e
Return base and exp of self. If base is 1/Integer, then return Integer, -exp. If this extra processing is not needed, the base and exp properties will give the raw arguments Examples ======== >>> from sympy import Pow, S >>> p = Pow(S.Half, 2, evaluate=False) >>> p.as_base_exp() (2, -2) >>> p.args (1/2, 2)
Return base and exp of self.
[ "Return", "base", "and", "exp", "of", "self", "." ]
def as_base_exp(self): """Return base and exp of self. If base is 1/Integer, then return Integer, -exp. If this extra processing is not needed, the base and exp properties will give the raw arguments Examples ======== >>> from sympy import Pow, S >>> p = Pow(S.Half, 2, evaluate=False) >>> p.as_base_exp() (2, -2) >>> p.args (1/2, 2) """ b, e = self.args if b.is_Rational and b.p == 1 and b.q != 1: return Integer(b.q), -e return b, e
[ "def", "as_base_exp", "(", "self", ")", ":", "b", ",", "e", "=", "self", ".", "args", "if", "b", ".", "is_Rational", "and", "b", ".", "p", "==", "1", "and", "b", ".", "q", "!=", "1", ":", "return", "Integer", "(", "b", ".", "q", ")", ",", "...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/core/power.py#L833-L855
plangrid/flask-rebar
a5b8697450689e2ae2234992b0f2f7f2ef8eec78
flask_rebar/rebar.py
python
prefix_url
(prefix, url)
return "/{}/{}".format(prefix, url)
Returns a new URL with the prefix prepended to the provided URL. :param str prefix: :param str url: :rtype: str
Returns a new URL with the prefix prepended to the provided URL.
[ "Returns", "a", "new", "URL", "with", "the", "prefix", "prepended", "to", "the", "provided", "URL", "." ]
def prefix_url(prefix, url): """ Returns a new URL with the prefix prepended to the provided URL. :param str prefix: :param str url: :rtype: str """ prefix = normalize_prefix(prefix) url = url[1:] if url.startswith("/") else url return "/{}/{}".format(prefix, url)
[ "def", "prefix_url", "(", "prefix", ",", "url", ")", ":", "prefix", "=", "normalize_prefix", "(", "prefix", ")", "url", "=", "url", "[", "1", ":", "]", "if", "url", ".", "startswith", "(", "\"/\"", ")", "else", "url", "return", "\"/{}/{}\"", ".", "fo...
https://github.com/plangrid/flask-rebar/blob/a5b8697450689e2ae2234992b0f2f7f2ef8eec78/flask_rebar/rebar.py#L217-L227
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/pymongo/message.py
python
_op_msg_compressed
(flags, command, identifier, docs, check_keys, opts, ctx)
return rid, msg, total_size, max_bson_size
Internal OP_MSG message helper.
Internal OP_MSG message helper.
[ "Internal", "OP_MSG", "message", "helper", "." ]
def _op_msg_compressed(flags, command, identifier, docs, check_keys, opts, ctx): """Internal OP_MSG message helper.""" msg, total_size, max_bson_size = _op_msg_no_header( flags, command, identifier, docs, check_keys, opts) rid, msg = _compress(2013, msg, ctx) return rid, msg, total_size, max_bson_size
[ "def", "_op_msg_compressed", "(", "flags", ",", "command", ",", "identifier", ",", "docs", ",", "check_keys", ",", "opts", ",", "ctx", ")", ":", "msg", ",", "total_size", ",", "max_bson_size", "=", "_op_msg_no_header", "(", "flags", ",", "command", ",", "i...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/pymongo/message.py#L663-L669
thomaxxl/safrs
bc97c81f58bbcf6441797ea92f11ef855ca54e61
safrs/safrs_init.py
python
test_decorator
(func)
return func
Example flask-restful decorator that can be used in the "decorators" Api argument cfr. https://flask-restful.readthedocs.io/en/latest/api.html#id1
Example flask-restful decorator that can be used in the "decorators" Api argument cfr. https://flask-restful.readthedocs.io/en/latest/api.html#id1
[ "Example", "flask", "-", "restful", "decorator", "that", "can", "be", "used", "in", "the", "decorators", "Api", "argument", "cfr", ".", "https", ":", "//", "flask", "-", "restful", ".", "readthedocs", ".", "io", "/", "en", "/", "latest", "/", "api", "....
def test_decorator(func): # pragma: no cover """Example flask-restful decorator that can be used in the "decorators" Api argument cfr. https://flask-restful.readthedocs.io/en/latest/api.html#id1 """ @wraps(func) def api_wrapper(*args, **kwargs): return func(*args, **kwargs) if func.__name__.lower() == "get": result = api_wrapper return result return func
[ "def", "test_decorator", "(", "func", ")", ":", "# pragma: no cover", "@", "wraps", "(", "func", ")", "def", "api_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", ...
https://github.com/thomaxxl/safrs/blob/bc97c81f58bbcf6441797ea92f11ef855ca54e61/safrs/safrs_init.py#L138-L151
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
bin/x86/Debug/scripting_engine/Lib/httplib.py
python
HTTP.getfile
(self)
return self.file
Provide a getfile, since the superclass' does not use this concept.
Provide a getfile, since the superclass' does not use this concept.
[ "Provide", "a", "getfile", "since", "the", "superclass", "does", "not", "use", "this", "concept", "." ]
def getfile(self): "Provide a getfile, since the superclass' does not use this concept." return self.file
[ "def", "getfile", "(", "self", ")", ":", "return", "self", ".", "file" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/bin/x86/Debug/scripting_engine/Lib/httplib.py#L1085-L1087
wonderworks-software/PyFlow
57e2c858933bf63890d769d985396dfad0fca0f0
PyFlow/Packages/PyFlowBase/FunctionLibraries/IntLib.py
python
IntLib.binaryLeftShift
(a=('IntPin', 0), b=('IntPin', 0))
return a << b
Binary left shift ``a << b``
Binary left shift ``a << b``
[ "Binary", "left", "shift", "a", "<<", "b" ]
def binaryLeftShift(a=('IntPin', 0), b=('IntPin', 0)): """Binary left shift ``a << b``""" return a << b
[ "def", "binaryLeftShift", "(", "a", "=", "(", "'IntPin'", ",", "0", ")", ",", "b", "=", "(", "'IntPin'", ",", "0", ")", ")", ":", "return", "a", "<<", "b" ]
https://github.com/wonderworks-software/PyFlow/blob/57e2c858933bf63890d769d985396dfad0fca0f0/PyFlow/Packages/PyFlowBase/FunctionLibraries/IntLib.py#L54-L56
oaubert/python-vlc
908ffdbd0844dc1849728c456e147788798c99da
generated/3.0/vlc.py
python
libvlc_get_fullscreen
(p_mi)
return f(p_mi)
Get current fullscreen status. @param p_mi: the media player. @return: the fullscreen status (boolean) \libvlc_return_bool.
Get current fullscreen status.
[ "Get", "current", "fullscreen", "status", "." ]
def libvlc_get_fullscreen(p_mi): '''Get current fullscreen status. @param p_mi: the media player. @return: the fullscreen status (boolean) \libvlc_return_bool. ''' f = _Cfunctions.get('libvlc_get_fullscreen', None) or \ _Cfunction('libvlc_get_fullscreen', ((1,),), None, ctypes.c_int, MediaPlayer) return f(p_mi)
[ "def", "libvlc_get_fullscreen", "(", "p_mi", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_get_fullscreen'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_get_fullscreen'", ",", "(", "(", "1", ",", ")", ",", ")", ",", "None", ",", "c...
https://github.com/oaubert/python-vlc/blob/908ffdbd0844dc1849728c456e147788798c99da/generated/3.0/vlc.py#L6928-L6936
BerkeleyAutomation/dex-net
cccf93319095374b0eefc24b8b6cd40bc23966d2
src/dexnet/grasping/contacts.py
python
Contact3D.surface_information
(self, width, num_steps, sigma_range=0.1, sigma_spatial=1, back_up=0.0, max_projection=0.1, direction=None, debug_objs=None, samples_per_grid=2)
return SurfaceWindow(proj_window, grad_win, hess_x, hess_y, gauss_curvature)
Returns the local surface window, gradient, and curvature for a single contact. Parameters ---------- width : float width of surface window in object frame num_steps : int number of steps to use along the in direction sigma_range : float bandwidth of bilateral range filter on window sigma_spatial : float bandwidth of gaussian spatial filter of bilateral filter back_up : float amount to back up before finding a contact in meters max_projection : float maximum amount to search forward for a contact (meters) direction : 3x1 :obj:`numpy.ndarray` direction along width to render the window debug_objs : :obj:`list` list to put debugging info into samples_per_grid : float number of samples per grid when finding contacts Returns ------- surface_window : :obj:`SurfaceWindow` window information for local surface patch of contact on the given object
Returns the local surface window, gradient, and curvature for a single contact.
[ "Returns", "the", "local", "surface", "window", "gradient", "and", "curvature", "for", "a", "single", "contact", "." ]
def surface_information(self, width, num_steps, sigma_range=0.1, sigma_spatial=1, back_up=0.0, max_projection=0.1, direction=None, debug_objs=None, samples_per_grid=2): """ Returns the local surface window, gradient, and curvature for a single contact. Parameters ---------- width : float width of surface window in object frame num_steps : int number of steps to use along the in direction sigma_range : float bandwidth of bilateral range filter on window sigma_spatial : float bandwidth of gaussian spatial filter of bilateral filter back_up : float amount to back up before finding a contact in meters max_projection : float maximum amount to search forward for a contact (meters) direction : 3x1 :obj:`numpy.ndarray` direction along width to render the window debug_objs : :obj:`list` list to put debugging info into samples_per_grid : float number of samples per grid when finding contacts Returns ------- surface_window : :obj:`SurfaceWindow` window information for local surface patch of contact on the given object """ if self.surface_info_ is not None: return self.surface_info_ if direction is None: direction = self.in_direction_ proj_window = self.surface_window_projection(width, num_steps, sigma_range=sigma_range, sigma_spatial=sigma_spatial, back_up=back_up, max_projection=max_projection, samples_per_grid=samples_per_grid, direction=direction, vis=False, debug_objs=debug_objs) if proj_window is None: raise ValueError('Surface window could not be computed') grad_win = np.gradient(proj_window) hess_x = np.gradient(grad_win[0]) hess_y = np.gradient(grad_win[1]) gauss_curvature = np.zeros(proj_window.shape) for i in range(num_steps): for j in range(num_steps): local_hess = np.array([[hess_x[0][i, j], hess_x[1][i, j]], [hess_y[0][i, j], hess_y[1][i, j]]]) # symmetrize local_hess = (local_hess + local_hess.T) / 2.0 # curvature gauss_curvature[i, j] = np.linalg.det(local_hess) return SurfaceWindow(proj_window, grad_win, hess_x, hess_y, gauss_curvature)
[ "def", "surface_information", "(", "self", ",", "width", ",", "num_steps", ",", "sigma_range", "=", "0.1", ",", "sigma_spatial", "=", "1", ",", "back_up", "=", "0.0", ",", "max_projection", "=", "0.1", ",", "direction", "=", "None", ",", "debug_objs", "=",...
https://github.com/BerkeleyAutomation/dex-net/blob/cccf93319095374b0eefc24b8b6cd40bc23966d2/src/dexnet/grasping/contacts.py#L552-L611
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/mps/v20190612/models.py
python
CreateWatermarkTemplateRequest.__init__
(self)
r""" :param Type: 水印类型,可选值: <li>image:图片水印;</li> <li>text:文字水印;</li> <li>svg:SVG 水印。</li> :type Type: str :param Name: 水印模板名称,长度限制:64 个字符。 :type Name: str :param Comment: 模板描述信息,长度限制:256 个字符。 :type Comment: str :param CoordinateOrigin: 原点位置,可选值: <li>TopLeft:表示坐标原点位于视频图像左上角,水印原点为图片或文字的左上角;</li> <li>TopRight:表示坐标原点位于视频图像的右上角,水印原点为图片或文字的右上角;</li> <li>BottomLeft:表示坐标原点位于视频图像的左下角,水印原点为图片或文字的左下角;</li> <li>BottomRight:表示坐标原点位于视频图像的右下角,水印原点为图片或文字的右下角。</li> 默认值:TopLeft。 :type CoordinateOrigin: str :param XPos: 水印原点距离视频图像坐标原点的水平位置。支持 %、px 两种格式: <li>当字符串以 % 结尾,表示水印 XPos 为视频宽度指定百分比,如 10% 表示 XPos 为视频宽度的 10%;</li> <li>当字符串以 px 结尾,表示水印 XPos 为指定像素,如 100px 表示 XPos 为 100 像素。</li> 默认值:0px。 :type XPos: str :param YPos: 水印原点距离视频图像坐标原点的垂直位置。支持 %、px 两种格式: <li>当字符串以 % 结尾,表示水印 YPos 为视频高度指定百分比,如 10% 表示 YPos 为视频高度的 10%;</li> <li>当字符串以 px 结尾,表示水印 YPos 为指定像素,如 100px 表示 YPos 为 100 像素。</li> 默认值:0px。 :type YPos: str :param ImageTemplate: 图片水印模板,仅当 Type 为 image,该字段必填且有效。 :type ImageTemplate: :class:`tencentcloud.mps.v20190612.models.ImageWatermarkInput` :param TextTemplate: 文字水印模板,仅当 Type 为 text,该字段必填且有效。 :type TextTemplate: :class:`tencentcloud.mps.v20190612.models.TextWatermarkTemplateInput` :param SvgTemplate: SVG 水印模板,仅当 Type 为 svg,该字段必填且有效。 :type SvgTemplate: :class:`tencentcloud.mps.v20190612.models.SvgWatermarkInput`
r""" :param Type: 水印类型,可选值: <li>image:图片水印;</li> <li>text:文字水印;</li> <li>svg:SVG 水印。</li> :type Type: str :param Name: 水印模板名称,长度限制:64 个字符。 :type Name: str :param Comment: 模板描述信息,长度限制:256 个字符。 :type Comment: str :param CoordinateOrigin: 原点位置,可选值: <li>TopLeft:表示坐标原点位于视频图像左上角,水印原点为图片或文字的左上角;</li> <li>TopRight:表示坐标原点位于视频图像的右上角,水印原点为图片或文字的右上角;</li> <li>BottomLeft:表示坐标原点位于视频图像的左下角,水印原点为图片或文字的左下角;</li> <li>BottomRight:表示坐标原点位于视频图像的右下角,水印原点为图片或文字的右下角。</li> 默认值:TopLeft。 :type CoordinateOrigin: str :param XPos: 水印原点距离视频图像坐标原点的水平位置。支持 %、px 两种格式: <li>当字符串以 % 结尾,表示水印 XPos 为视频宽度指定百分比,如 10% 表示 XPos 为视频宽度的 10%;</li> <li>当字符串以 px 结尾,表示水印 XPos 为指定像素,如 100px 表示 XPos 为 100 像素。</li> 默认值:0px。 :type XPos: str :param YPos: 水印原点距离视频图像坐标原点的垂直位置。支持 %、px 两种格式: <li>当字符串以 % 结尾,表示水印 YPos 为视频高度指定百分比,如 10% 表示 YPos 为视频高度的 10%;</li> <li>当字符串以 px 结尾,表示水印 YPos 为指定像素,如 100px 表示 YPos 为 100 像素。</li> 默认值:0px。 :type YPos: str :param ImageTemplate: 图片水印模板,仅当 Type 为 image,该字段必填且有效。 :type ImageTemplate: :class:`tencentcloud.mps.v20190612.models.ImageWatermarkInput` :param TextTemplate: 文字水印模板,仅当 Type 为 text,该字段必填且有效。 :type TextTemplate: :class:`tencentcloud.mps.v20190612.models.TextWatermarkTemplateInput` :param SvgTemplate: SVG 水印模板,仅当 Type 为 svg,该字段必填且有效。 :type SvgTemplate: :class:`tencentcloud.mps.v20190612.models.SvgWatermarkInput`
[ "r", ":", "param", "Type", ":", "水印类型,可选值:", "<li", ">", "image:图片水印;<", "/", "li", ">", "<li", ">", "text:文字水印;<", "/", "li", ">", "<li", ">", "svg:SVG", "水印。<", "/", "li", ">", ":", "type", "Type", ":", "str", ":", "param", "Name", ":", "水印模板名称,长...
def __init__(self): r""" :param Type: 水印类型,可选值: <li>image:图片水印;</li> <li>text:文字水印;</li> <li>svg:SVG 水印。</li> :type Type: str :param Name: 水印模板名称,长度限制:64 个字符。 :type Name: str :param Comment: 模板描述信息,长度限制:256 个字符。 :type Comment: str :param CoordinateOrigin: 原点位置,可选值: <li>TopLeft:表示坐标原点位于视频图像左上角,水印原点为图片或文字的左上角;</li> <li>TopRight:表示坐标原点位于视频图像的右上角,水印原点为图片或文字的右上角;</li> <li>BottomLeft:表示坐标原点位于视频图像的左下角,水印原点为图片或文字的左下角;</li> <li>BottomRight:表示坐标原点位于视频图像的右下角,水印原点为图片或文字的右下角。</li> 默认值:TopLeft。 :type CoordinateOrigin: str :param XPos: 水印原点距离视频图像坐标原点的水平位置。支持 %、px 两种格式: <li>当字符串以 % 结尾,表示水印 XPos 为视频宽度指定百分比,如 10% 表示 XPos 为视频宽度的 10%;</li> <li>当字符串以 px 结尾,表示水印 XPos 为指定像素,如 100px 表示 XPos 为 100 像素。</li> 默认值:0px。 :type XPos: str :param YPos: 水印原点距离视频图像坐标原点的垂直位置。支持 %、px 两种格式: <li>当字符串以 % 结尾,表示水印 YPos 为视频高度指定百分比,如 10% 表示 YPos 为视频高度的 10%;</li> <li>当字符串以 px 结尾,表示水印 YPos 为指定像素,如 100px 表示 YPos 为 100 像素。</li> 默认值:0px。 :type YPos: str :param ImageTemplate: 图片水印模板,仅当 Type 为 image,该字段必填且有效。 :type ImageTemplate: :class:`tencentcloud.mps.v20190612.models.ImageWatermarkInput` :param TextTemplate: 文字水印模板,仅当 Type 为 text,该字段必填且有效。 :type TextTemplate: :class:`tencentcloud.mps.v20190612.models.TextWatermarkTemplateInput` :param SvgTemplate: SVG 水印模板,仅当 Type 为 svg,该字段必填且有效。 :type SvgTemplate: :class:`tencentcloud.mps.v20190612.models.SvgWatermarkInput` """ self.Type = None self.Name = None self.Comment = None self.CoordinateOrigin = None self.XPos = None self.YPos = None self.ImageTemplate = None self.TextTemplate = None self.SvgTemplate = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "Type", "=", "None", "self", ".", "Name", "=", "None", "self", ".", "Comment", "=", "None", "self", ".", "CoordinateOrigin", "=", "None", "self", ".", "XPos", "=", "None", "self", ".", "YPos", ...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/mps/v20190612/models.py#L4865-L4908
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-build/python-libs/xmpppy/xmpp/dispatcher.py
python
Dispatcher.Process
(self, timeout=0)
return '0'
Check incoming stream for data waiting. If "timeout" is positive - block for as max. this time. Returns: 1) length of processed data if some data were processed; 2) '0' string if no data were processed but link is alive; 3) 0 (zero) if underlying connection is closed. Take note that in case of disconnection detect during Process() call disconnect handlers are called automatically.
Check incoming stream for data waiting. If "timeout" is positive - block for as max. this time. Returns: 1) length of processed data if some data were processed; 2) '0' string if no data were processed but link is alive; 3) 0 (zero) if underlying connection is closed. Take note that in case of disconnection detect during Process() call disconnect handlers are called automatically.
[ "Check", "incoming", "stream", "for", "data", "waiting", ".", "If", "timeout", "is", "positive", "-", "block", "for", "as", "max", ".", "this", "time", ".", "Returns", ":", "1", ")", "length", "of", "processed", "data", "if", "some", "data", "were", "p...
def Process(self, timeout=0): """ Check incoming stream for data waiting. If "timeout" is positive - block for as max. this time. Returns: 1) length of processed data if some data were processed; 2) '0' string if no data were processed but link is alive; 3) 0 (zero) if underlying connection is closed. Take note that in case of disconnection detect during Process() call disconnect handlers are called automatically. """ for handler in self._cycleHandlers: handler(self) if len(self._pendingExceptions) > 0: _pendingException = self._pendingExceptions.pop() raise _pendingException[0], _pendingException[1], _pendingException[2] if self._owner.Connection.pending_data(timeout): try: data=self._owner.Connection.receive() except IOError: return self.Stream.Parse(data) if len(self._pendingExceptions) > 0: _pendingException = self._pendingExceptions.pop() raise _pendingException[0], _pendingException[1], _pendingException[2] if data: return len(data) return '0'
[ "def", "Process", "(", "self", ",", "timeout", "=", "0", ")", ":", "for", "handler", "in", "self", ".", "_cycleHandlers", ":", "handler", "(", "self", ")", "if", "len", "(", "self", ".", "_pendingExceptions", ")", ">", "0", ":", "_pendingException", "=...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/xmpppy/xmpp/dispatcher.py#L106-L127
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
src/codeintel/play/core.py
python
Menu.GetParent
(*args, **kwargs)
return _core.Menu_GetParent(*args, **kwargs)
GetParent() -> Menu
GetParent() -> Menu
[ "GetParent", "()", "-", ">", "Menu" ]
def GetParent(*args, **kwargs): """GetParent() -> Menu""" return _core.Menu_GetParent(*args, **kwargs)
[ "def", "GetParent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core", ".", "Menu_GetParent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/src/codeintel/play/core.py#L7535-L7537
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/future/backports/urllib/parse.py
python
parse_qsl
(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace')
return r
Parse a query given as a string argument. Arguments: qs: percent-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. encoding and errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. Returns a list, as G-d intended.
Parse a query given as a string argument.
[ "Parse", "a", "query", "given", "as", "a", "string", "argument", "." ]
def parse_qsl(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace'): """Parse a query given as a string argument. Arguments: qs: percent-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. encoding and errors: specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. Returns a list, as G-d intended. """ qs, _coerce_result = _coerce_args(qs) pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')] r = [] for name_value in pairs: if not name_value and not strict_parsing: continue nv = name_value.split('=', 1) if len(nv) != 2: if strict_parsing: raise ValueError("bad query field: %r" % (name_value,)) # Handle case of a control-name with no equal sign if keep_blank_values: nv.append('') else: continue if len(nv[1]) or keep_blank_values: name = nv[0].replace('+', ' ') name = unquote(name, encoding=encoding, errors=errors) name = _coerce_result(name) value = nv[1].replace('+', ' ') value = unquote(value, encoding=encoding, errors=errors) value = _coerce_result(value) r.append((name, value)) return r
[ "def", "parse_qsl", "(", "qs", ",", "keep_blank_values", "=", "False", ",", "strict_parsing", "=", "False", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'replace'", ")", ":", "qs", ",", "_coerce_result", "=", "_coerce_args", "(", "qs", ")", "pairs...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/future/backports/urllib/parse.py#L572-L618
jaryee/wechat_sogou_crawl
388887e4c8e5e60bc2558d8359740d108345e61b
wechatsogou/db.py
python
mysql.order
(self, order)
return self
排序
排序
[ "排序" ]
def order(self, order): """排序 """ if type(order) is dict: for k, v in order.items(): self.order_sql = " order by `" + k + "` " + v break else: raise MysqlDbException('排序参数不是字典 - Model.order') return self
[ "def", "order", "(", "self", ",", "order", ")", ":", "if", "type", "(", "order", ")", "is", "dict", ":", "for", "k", ",", "v", "in", "order", ".", "items", "(", ")", ":", "self", ".", "order_sql", "=", "\" order by `\"", "+", "k", "+", "\"` \"", ...
https://github.com/jaryee/wechat_sogou_crawl/blob/388887e4c8e5e60bc2558d8359740d108345e61b/wechatsogou/db.py#L156-L165
bobbui/json-logging-python
efbe367527203a88e0fec9f81ccb2f1e9252b1bf
json_logging/framework/connexion/__init__.py
python
ConnexionRequestInfoExtractor.get_path
(self, request)
return request.path
[]
def get_path(self, request): return request.path
[ "def", "get_path", "(", "self", ",", "request", ")", ":", "return", "request", ".", "path" ]
https://github.com/bobbui/json-logging-python/blob/efbe367527203a88e0fec9f81ccb2f1e9252b1bf/json_logging/framework/connexion/__init__.py#L108-L109
pgq/skytools-legacy
8b7e6c118572a605d28b7a3403c96aeecfd0d272
python/londiste/exec_attrs.py
python
ExecAttrs.add_value
(self, k, v)
Add single value to key.
Add single value to key.
[ "Add", "single", "value", "to", "key", "." ]
def add_value(self, k, v): """Add single value to key.""" xk = k.lower().strip() if xk not in META_KEYS: raise ExecAttrsException("Invalid key: %s" % k) if xk not in self.attrs: self.attrs[xk] = [] xv = v.strip() self.attrs[xk].append(xv)
[ "def", "add_value", "(", "self", ",", "k", ",", "v", ")", ":", "xk", "=", "k", ".", "lower", "(", ")", ".", "strip", "(", ")", "if", "xk", "not", "in", "META_KEYS", ":", "raise", "ExecAttrsException", "(", "\"Invalid key: %s\"", "%", "k", ")", "if"...
https://github.com/pgq/skytools-legacy/blob/8b7e6c118572a605d28b7a3403c96aeecfd0d272/python/londiste/exec_attrs.py#L189-L199
pythonarcade/arcade
1ee3eb1900683213e8e8df93943327c2ea784564
arcade/buffered_draw_commands.py
python
create_polygon
(point_list: PointList, color: Color)
return create_line_generic(point_list, color, gl.GL_TRIANGLE_STRIP, 1)
Draw a convex polygon. This will NOT draw a concave polygon. Because of this, you might not want to use this function. The function returns a Shape object that can be drawn with ``my_shape.draw()``. Don't create the shape in the draw method, create it in the setup method and then draw it in ``on_draw``. For even faster performance, add multiple shapes into a ShapeElementList and draw that list. This allows nearly unlimited shapes to be drawn just as fast as one. :param PointList point_list: :param color: :Returns Shape:
Draw a convex polygon. This will NOT draw a concave polygon. Because of this, you might not want to use this function.
[ "Draw", "a", "convex", "polygon", ".", "This", "will", "NOT", "draw", "a", "concave", "polygon", ".", "Because", "of", "this", "you", "might", "not", "want", "to", "use", "this", "function", "." ]
def create_polygon(point_list: PointList, color: Color): """ Draw a convex polygon. This will NOT draw a concave polygon. Because of this, you might not want to use this function. The function returns a Shape object that can be drawn with ``my_shape.draw()``. Don't create the shape in the draw method, create it in the setup method and then draw it in ``on_draw``. For even faster performance, add multiple shapes into a ShapeElementList and draw that list. This allows nearly unlimited shapes to be drawn just as fast as one. :param PointList point_list: :param color: :Returns Shape: """ # We assume points were given in order, either clockwise or counter clockwise. # Polygon is assumed to be monotone. # To fill the polygon, we start by one vertex, and we chain triangle strips # alternating with vertices to the left and vertices to the right of the # initial vertex. half = len(point_list) // 2 interleaved = itertools.chain.from_iterable( itertools.zip_longest(point_list[:half], reversed(point_list[half:])) ) point_list = [p for p in interleaved if p is not None] return create_line_generic(point_list, color, gl.GL_TRIANGLE_STRIP, 1)
[ "def", "create_polygon", "(", "point_list", ":", "PointList", ",", "color", ":", "Color", ")", ":", "# We assume points were given in order, either clockwise or counter clockwise.", "# Polygon is assumed to be monotone.", "# To fill the polygon, we start by one vertex, and we chain trian...
https://github.com/pythonarcade/arcade/blob/1ee3eb1900683213e8e8df93943327c2ea784564/arcade/buffered_draw_commands.py#L240-L270