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
jobovy/galpy
8e6a230bbe24ce16938db10053f92eb17fe4bb52
galpy/actionAngle/actionAngleAdiabatic.py
python
actionAngleAdiabatic.calczmax
(self,*args,**kwargs)
return aAAxi.calczmax(**kwargs)
NAME: calczmax PURPOSE: calculate the maximum height INPUT: Either: a) R,vR,vT,z,vz b) Orbit instance: initial condition used if that's it, orbit(t) if there is a time given as well OUTPUT: zmax HISTORY: 2012-06-01 - Written - Bovy (IAS)
NAME: calczmax PURPOSE: calculate the maximum height INPUT: Either: a) R,vR,vT,z,vz b) Orbit instance: initial condition used if that's it, orbit(t) if there is a time given as well OUTPUT: zmax HISTORY: 2012-06-01 - Written - Bovy (IAS)
[ "NAME", ":", "calczmax", "PURPOSE", ":", "calculate", "the", "maximum", "height", "INPUT", ":", "Either", ":", "a", ")", "R", "vR", "vT", "z", "vz", "b", ")", "Orbit", "instance", ":", "initial", "condition", "used", "if", "that", "s", "it", "orbit", ...
def calczmax(self,*args,**kwargs): #pragma: no cover """ NAME: calczmax PURPOSE: calculate the maximum height INPUT: Either: a) R,vR,vT,z,vz b) Orbit instance: initial condition used if that's it, orbit(t) if there is a time given as well OUTPUT: zmax HISTORY: 2012-06-01 - Written - Bovy (IAS) """ warnings.warn("actionAngleAdiabatic.calczmax function will soon be deprecated; please contact galpy's maintainer if you require this function") #Set up the actionAngleAxi object self._parse_eval_args(*args) thispot= toPlanarPotential(self._pot) thisverticalpot= toVerticalPotential(self._pot,self._eval_R) aAAxi= actionAngleAxi(*args,pot=thispot, verticalPot=thisverticalpot, gamma=self._gamma) return aAAxi.calczmax(**kwargs)
[ "def", "calczmax", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "#pragma: no cover", "warnings", ".", "warn", "(", "\"actionAngleAdiabatic.calczmax function will soon be deprecated; please contact galpy's maintainer if you require this function\"", ")", "...
https://github.com/jobovy/galpy/blob/8e6a230bbe24ce16938db10053f92eb17fe4bb52/galpy/actionAngle/actionAngleAdiabatic.py#L258-L282
ansible/ansible-modules-core
00911a75ad6635834b6d28eef41f197b2f73c381
packaging/os/yum.py
python
local_nvra
(module, path)
return '%s-%s-%s.%s' % (header[rpm.RPMTAG_NAME], header[rpm.RPMTAG_VERSION], header[rpm.RPMTAG_RELEASE], header[rpm.RPMTAG_ARCH])
return nvra of a local rpm passed in
return nvra of a local rpm passed in
[ "return", "nvra", "of", "a", "local", "rpm", "passed", "in" ]
def local_nvra(module, path): """return nvra of a local rpm passed in""" ts = rpm.TransactionSet() ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES) fd = os.open(path, os.O_RDONLY) try: header = ts.hdrFromFdno(fd) finally: os.close(fd) return '%s-%s-%s.%s' % (header[rpm.RPMTAG_NAME], header[rpm.RPMTAG_VERSION], header[rpm.RPMTAG_RELEASE], header[rpm.RPMTAG_ARCH])
[ "def", "local_nvra", "(", "module", ",", "path", ")", ":", "ts", "=", "rpm", ".", "TransactionSet", "(", ")", "ts", ".", "setVSFlags", "(", "rpm", ".", "_RPMVSF_NOSIGNATURES", ")", "fd", "=", "os", ".", "open", "(", "path", ",", "os", ".", "O_RDONLY"...
https://github.com/ansible/ansible-modules-core/blob/00911a75ad6635834b6d28eef41f197b2f73c381/packaging/os/yum.py#L524-L538
mrkipling/maraschino
c6be9286937783ae01df2d6d8cebfc8b2734a7d7
lib/sqlalchemy/event.py
python
remove
(target, identifier, fn)
Remove an event listener. Note that some event removals, particularly for those event dispatchers which create wrapper functions and secondary even listeners, may not yet be supported.
Remove an event listener.
[ "Remove", "an", "event", "listener", "." ]
def remove(target, identifier, fn): """Remove an event listener. Note that some event removals, particularly for those event dispatchers which create wrapper functions and secondary even listeners, may not yet be supported. """ for evt_cls in _registrars[identifier]: for tgt in evt_cls._accept_with(target): tgt.dispatch._remove(identifier, tgt, fn, *args, **kw) return
[ "def", "remove", "(", "target", ",", "identifier", ",", "fn", ")", ":", "for", "evt_cls", "in", "_registrars", "[", "identifier", "]", ":", "for", "tgt", "in", "evt_cls", ".", "_accept_with", "(", "target", ")", ":", "tgt", ".", "dispatch", ".", "_remo...
https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/sqlalchemy/event.py#L62-L73
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v7/services/services/feed_item_target_service/client.py
python
FeedItemTargetServiceClientMeta.get_transport_class
( cls, label: str = None, )
return next(iter(cls._transport_registry.values()))
Return an appropriate transport class. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use.
Return an appropriate transport class.
[ "Return", "an", "appropriate", "transport", "class", "." ]
def get_transport_class( cls, label: str = None, ) -> Type[FeedItemTargetServiceTransport]: """Return an appropriate transport class. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label: return cls._transport_registry[label] # No transport is requested; return the default (that is, the first one # in the dictionary). return next(iter(cls._transport_registry.values()))
[ "def", "get_transport_class", "(", "cls", ",", "label", ":", "str", "=", "None", ",", ")", "->", "Type", "[", "FeedItemTargetServiceTransport", "]", ":", "# If a specific transport is requested, return that one.", "if", "label", ":", "return", "cls", ".", "_transpor...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/feed_item_target_service/client.py#L52-L70
garywiz/chaperone
9ff2c3a5b9c6820f8750320a564ea214042df06f
chaperone/cproc/pt/inetd.py
python
InetdService._create_server
(self)
return asyncio.get_event_loop().create_server(InetdServiceProtocol.buildProtocol(self, process=self.process), '0.0.0.0', self.process.port)
[]
def _create_server(self): return asyncio.get_event_loop().create_server(InetdServiceProtocol.buildProtocol(self, process=self.process), '0.0.0.0', self.process.port)
[ "def", "_create_server", "(", "self", ")", ":", "return", "asyncio", ".", "get_event_loop", "(", ")", ".", "create_server", "(", "InetdServiceProtocol", ".", "buildProtocol", "(", "self", ",", "process", "=", "self", ".", "process", ")", ",", "'0.0.0.0'", ",...
https://github.com/garywiz/chaperone/blob/9ff2c3a5b9c6820f8750320a564ea214042df06f/chaperone/cproc/pt/inetd.py#L83-L86
weinbe58/QuSpin
5bbc3204dbf5c227a87a44f0dacf39509cba580c
quspin/basis/basis_general/fermion.py
python
spinful_fermion_basis_general.__init__
(self,N,Nf=None,nf=None,Ns_block_est=None,simple_symm=True,make_basis=True,block_order=None,double_occupancy=True,**blocks)
Intializes the `spinful_fermion_basis_general` object (basis for fermionic operators). Parameters ----------- L: int Length of chain/number of sites. Nf: tuple(int), optional Number of fermions in chain. Can be tupe of integers or list of tuples of integers `[(Nup,Ndown),...]` to specify one or more particle sectors. nf: float, optional Density of fermions in chain (fermions per site). Ns_block_est: int, optional Overwrites the internal estimate of the size of the reduced Hilbert space for the given symmetries. This can be used to help conserve memory if the exact size of the H-space is known ahead of time. simple_sym: bool, optional Flags whidh toggles the setting for the types of mappings and operator strings the basis will use. See this tutorial for more details. make_basis: bool, optional Boolean to control whether to make the basis. Allows the use to use some functionality of the basis constructor without constructing the entire basis. double_occupancy: bool, optional Boolean to toggle the presence of doubly-occupied sites (both a spin up and a spin-down fermion present on the same lattice site) in the basis. Default is `double_occupancy=True`, for which doubly-occupied states are present. block_order: list of strings, optional A list of strings containing the names of the symmetry blocks which specifies the order in which the symmetries will be applied to the state when calculating the basis. The first element in the list is applied to the state first followed by the second element, etc. If the list is not specificed the ordering is such that the symmetry with the largest cycle is the first, followed by the second largest, etc. **blocks: optional keyword arguments which pass the symmetry generator arrays. For instance: >>> basis(...,kxblock=(Q,q),...) The keys of the symmetry sector, e.g. `kxblock`, can be chosen arbitrarily by the user. The values are tuples where the first entry contains the symmetry transformation :math:`Q` acting on the lattice sites (see class example), and the second entry is an integer :math:`q` to label the symmetry sector.
Intializes the `spinful_fermion_basis_general` object (basis for fermionic operators).
[ "Intializes", "the", "spinful_fermion_basis_general", "object", "(", "basis", "for", "fermionic", "operators", ")", "." ]
def __init__(self,N,Nf=None,nf=None,Ns_block_est=None,simple_symm=True,make_basis=True,block_order=None,double_occupancy=True,**blocks): """Intializes the `spinful_fermion_basis_general` object (basis for fermionic operators). Parameters ----------- L: int Length of chain/number of sites. Nf: tuple(int), optional Number of fermions in chain. Can be tupe of integers or list of tuples of integers `[(Nup,Ndown),...]` to specify one or more particle sectors. nf: float, optional Density of fermions in chain (fermions per site). Ns_block_est: int, optional Overwrites the internal estimate of the size of the reduced Hilbert space for the given symmetries. This can be used to help conserve memory if the exact size of the H-space is known ahead of time. simple_sym: bool, optional Flags whidh toggles the setting for the types of mappings and operator strings the basis will use. See this tutorial for more details. make_basis: bool, optional Boolean to control whether to make the basis. Allows the use to use some functionality of the basis constructor without constructing the entire basis. double_occupancy: bool, optional Boolean to toggle the presence of doubly-occupied sites (both a spin up and a spin-down fermion present on the same lattice site) in the basis. Default is `double_occupancy=True`, for which doubly-occupied states are present. block_order: list of strings, optional A list of strings containing the names of the symmetry blocks which specifies the order in which the symmetries will be applied to the state when calculating the basis. The first element in the list is applied to the state first followed by the second element, etc. If the list is not specificed the ordering is such that the symmetry with the largest cycle is the first, followed by the second largest, etc. **blocks: optional keyword arguments which pass the symmetry generator arrays. For instance: >>> basis(...,kxblock=(Q,q),...) The keys of the symmetry sector, e.g. `kxblock`, can be chosen arbitrarily by the user. The values are tuples where the first entry contains the symmetry transformation :math:`Q` acting on the lattice sites (see class example), and the second entry is an integer :math:`q` to label the symmetry sector. """ # Nf = [(Nup,Ndown),...] # Nup is left side of basis sites 0 - N-1 # Ndown is right side of basis sites N - 2*N-1 _Np = blocks.get("_Np") if _Np is not None: blocks.pop("_Np") if Nf is not None and nf is not None: raise ValueError("cannot use 'nf' and 'Nf' simultaineously.") if Nf is None and nf is not None: Nf = (int(nf[0]*N),int(nf[1]*N)) if any((type(map) is not tuple) and (len(map)!=2) for map in blocks.values() if map is not None): raise ValueError("blocks must contain tuple: (map,q).") self._simple_symm = simple_symm if simple_symm: if any(len(item[0]) != N for item in blocks.values() if item is not None): raise ValueError("Simple symmetries must have mapping of length N.") else: if any(len(item[0]) != 2*N for item in blocks.values() if item is not None): raise ValueError("Simple symmetries must have mapping of length N.") new_blocks = {key:process_spinful_map(N,*item) for key,item in blocks.items() if item is not None} blocks.update(new_blocks) basis_general.__init__(self,2*N,block_order=block_order,**blocks) # self._check_pcon = False self._count_particles = False if _Np is not None and Nf is None: self._count_particles = True if type(_Np) is not int: raise ValueError("_Np must be integer") if _Np >= -1: if _Np+1 > N: Nf = [] for n in range(N+1): Nf.extend((n-i,i)for i in range(n+1)) Nf = tuple(Nf) elif _Np==-1: Nf = None else: Nf=[] for n in range(_Np+1): Nf.extend((n-i,i)for i in range(n+1)) Nf = tuple(Nf) else: raise ValueError("_Np == -1 for no particle conservation, _Np >= 0 for particle conservation") if Nf is None: self._Ns = (1<<N)**2 else: if type(Nf) is tuple: if len(Nf)==2: self._get_proj_pcon = True Nup,Ndown = Nf if (type(Nup) is int) and type(Ndown) is int: self._Ns = comb(N,Nup,exact=True)*comb(N,Ndown,exact=True) else: raise ValueError("Nf must be tuple of integers or iterable object of tuples.") Nf = [Nf] else: Nf = list(Nf) if any((type(tup)is not tuple) and len(tup)!=2 for tup in Nf): raise ValueError("Nf must be tuple of integers or iterable object of tuples.") self._Ns = 0 for Nup,Ndown in Nf: if Nup > N or Nup < 0: raise ValueError("particle numbers in Nf must satisfy: 0 <= n <= N") if Ndown > N or Ndown < 0: raise ValueError("particle numbers in Nf must satisfy: 0 <= n <= N") self._Ns += comb(N,Nup,exact=True)*comb(N,Ndown,exact=True) else: try: Nf_iter = iter(Nf) except TypeError: raise ValueError("Nf must be tuple of integers or iterable object of tuples.") if any((type(tup)is not tuple) and len(tup)!=2 for tup in Nf): raise ValueError("Nf must be tuple of integers or iterable object of tuples.") Nf = list(Nf) self._Ns = 0 for Nup,Ndown in Nf: if Nup > N or Nup < 0: raise ValueError("particle numbers in Nf must satisfy: 0 <= n <= N") if Ndown > N or Ndown < 0: raise ValueError("particle numbers in Nf must satisfy: 0 <= n <= N") self._Ns += comb(N,Nup,exact=True)*comb(N,Ndown,exact=True) self._pcon_args = dict(N=N,Nf=Nf) if len(self._pers)>0 or not double_occupancy: if Ns_block_est is None: self._Ns = int(float(self._Ns)/_np.multiply.reduce(self._pers))*4 else: if type(Ns_block_est) is not int: raise TypeError("Ns_block_est must be integer value.") if Ns_block_est <= 0: raise ValueError("Ns_block_est must be an integer > 0") self._Ns = Ns_block_est self._basis_dtype = get_basis_type(2*N,None,2) self._core = spinful_fermion_basis_core_wrap(self._basis_dtype,N,self._maps,self._pers,self._qs,double_occupancy) self._sps = 2 self._N = 2*N self._Ns_block_est=self._Ns self._Np = Nf self._double_occupancy = double_occupancy self._noncommuting_bits = [(_np.arange(self.N),_np.array(-1,dtype=_np.int8))] # make the basis; make() is function method of base_general if make_basis: self.make() else: self._Ns=1 self._basis=basis_zeros(self._Ns,dtype=self._basis_dtype) self._n=_np.zeros(self._Ns,dtype=self._n_dtype) self._operators = ("availible operators for ferion_basis_1d:"+ "\n\tI: identity "+ "\n\t+: raising operator"+ "\n\t-: lowering operator"+ "\n\tn: number operator"+ "\n\tz: c-symm number operator"+ "\n\tx: majorana x-operator"+ "\n\ty: majorana y-operator") self._allowed_ops=set(["I","n","+","-","z","x","y"])
[ "def", "__init__", "(", "self", ",", "N", ",", "Nf", "=", "None", ",", "nf", "=", "None", ",", "Ns_block_est", "=", "None", ",", "simple_symm", "=", "True", ",", "make_basis", "=", "True", ",", "block_order", "=", "None", ",", "double_occupancy", "=", ...
https://github.com/weinbe58/QuSpin/blob/5bbc3204dbf5c227a87a44f0dacf39509cba580c/quspin/basis/basis_general/fermion.py#L328-L501
yangxudong/deeplearning
1b925c2171902d9a352d3747495030e058220204
telepath/mobilenet_v2.py
python
mobilenet
(input_tensor, num_classes=1001, depth_multiplier=1.0, scope='MobilenetV2', conv_defs=None, finegrain_classification_mode=False, min_depth=None, divisible_by=None, **kwargs)
Creates mobilenet V2 network. Inference mode is created by default. To create training use training_scope below. with tf.contrib.slim.arg_scope(mobilenet_v2.training_scope()): logits, endpoints = mobilenet_v2.mobilenet(input_tensor) Args: input_tensor: The input tensor num_classes: number of classes depth_multiplier: The multiplier applied to scale number of channels in each layer. Note: this is called depth multiplier in the paper but the name is kept for consistency with slim's model builder. scope: Scope of the operator conv_defs: Allows to override default conv def. finegrain_classification_mode: When set to True, the model will keep the last layer large even for small multipliers. Following https://arxiv.org/abs/1801.04381 suggests that it improves performance for ImageNet-type of problems. *Note* ignored if final_endpoint makes the builder exit earlier. min_depth: If provided, will ensure that all layers will have that many channels after application of depth multiplier. divisible_by: If provided will ensure that all layers # channels will be divisible by this number. **kwargs: passed directly to mobilenet.mobilenet: prediction_fn- what prediction function to use. reuse-: whether to reuse variables (if reuse set to true, scope must be given). Returns: logits/endpoints pair Raises: ValueError: On invalid arguments
Creates mobilenet V2 network.
[ "Creates", "mobilenet", "V2", "network", "." ]
def mobilenet(input_tensor, num_classes=1001, depth_multiplier=1.0, scope='MobilenetV2', conv_defs=None, finegrain_classification_mode=False, min_depth=None, divisible_by=None, **kwargs): """Creates mobilenet V2 network. Inference mode is created by default. To create training use training_scope below. with tf.contrib.slim.arg_scope(mobilenet_v2.training_scope()): logits, endpoints = mobilenet_v2.mobilenet(input_tensor) Args: input_tensor: The input tensor num_classes: number of classes depth_multiplier: The multiplier applied to scale number of channels in each layer. Note: this is called depth multiplier in the paper but the name is kept for consistency with slim's model builder. scope: Scope of the operator conv_defs: Allows to override default conv def. finegrain_classification_mode: When set to True, the model will keep the last layer large even for small multipliers. Following https://arxiv.org/abs/1801.04381 suggests that it improves performance for ImageNet-type of problems. *Note* ignored if final_endpoint makes the builder exit earlier. min_depth: If provided, will ensure that all layers will have that many channels after application of depth multiplier. divisible_by: If provided will ensure that all layers # channels will be divisible by this number. **kwargs: passed directly to mobilenet.mobilenet: prediction_fn- what prediction function to use. reuse-: whether to reuse variables (if reuse set to true, scope must be given). Returns: logits/endpoints pair Raises: ValueError: On invalid arguments """ if conv_defs is None: conv_defs = V2_DEF if 'multiplier' in kwargs: raise ValueError('mobilenetv2 doesn\'t support generic ' 'multiplier parameter use "depth_multiplier" instead.') if finegrain_classification_mode: conv_defs = copy.deepcopy(conv_defs) if depth_multiplier < 1: conv_defs['spec'][-1].params['num_outputs'] /= depth_multiplier depth_args = {} # NB: do not set depth_args unless they are provided to avoid overriding # whatever default depth_multiplier might have thanks to arg_scope. if min_depth is not None: depth_args['min_depth'] = min_depth if divisible_by is not None: depth_args['divisible_by'] = divisible_by with slim.arg_scope((lib.depth_multiplier,), **depth_args): return lib.mobilenet( input_tensor, num_classes=num_classes, conv_defs=conv_defs, scope=scope, multiplier=depth_multiplier, **kwargs)
[ "def", "mobilenet", "(", "input_tensor", ",", "num_classes", "=", "1001", ",", "depth_multiplier", "=", "1.0", ",", "scope", "=", "'MobilenetV2'", ",", "conv_defs", "=", "None", ",", "finegrain_classification_mode", "=", "False", ",", "min_depth", "=", "None", ...
https://github.com/yangxudong/deeplearning/blob/1b925c2171902d9a352d3747495030e058220204/telepath/mobilenet_v2.py#L85-L154
galaxyproject/galaxy
4c03520f05062e0f4a1b3655dc0b7452fda69943
lib/galaxy/web_stack/__init__.py
python
ApplicationStack._set_default_job_handler_assignment_methods
(self, job_config, base_pool)
Override in subclasses to set default job handler assignment methods if not explicitly configured by the administrator. Called once per job_config.
Override in subclasses to set default job handler assignment methods if not explicitly configured by the administrator.
[ "Override", "in", "subclasses", "to", "set", "default", "job", "handler", "assignment", "methods", "if", "not", "explicitly", "configured", "by", "the", "administrator", "." ]
def _set_default_job_handler_assignment_methods(self, job_config, base_pool): """Override in subclasses to set default job handler assignment methods if not explicitly configured by the administrator. Called once per job_config. """
[ "def", "_set_default_job_handler_assignment_methods", "(", "self", ",", "job_config", ",", "base_pool", ")", ":" ]
https://github.com/galaxyproject/galaxy/blob/4c03520f05062e0f4a1b3655dc0b7452fda69943/lib/galaxy/web_stack/__init__.py#L110-L114
web2py/web2py
095905c4e010a1426c729483d912e270a51b7ba8
gluon/contrib/login_methods/openid_auth.py
python
OpenIDAuth._form_with_notification
(self)
return lambda: form
Render the form for normal login with a notice of OpenID authenticated
Render the form for normal login with a notice of OpenID authenticated
[ "Render", "the", "form", "for", "normal", "login", "with", "a", "notice", "of", "OpenID", "authenticated" ]
def _form_with_notification(self): """ Render the form for normal login with a notice of OpenID authenticated """ form = DIV() # TODO: check when will happen if self.auth.settings.login_form in (self.auth, self): self.auth.settings.login_form = self.auth form = DIV(self.auth()) register_note = DIV(P(self.messages.p_openid_not_registered)) form.components.append(register_note) return lambda: form
[ "def", "_form_with_notification", "(", "self", ")", ":", "form", "=", "DIV", "(", ")", "# TODO: check when will happen", "if", "self", ".", "auth", ".", "settings", ".", "login_form", "in", "(", "self", ".", "auth", ",", "self", ")", ":", "self", ".", "a...
https://github.com/web2py/web2py/blob/095905c4e010a1426c729483d912e270a51b7ba8/gluon/contrib/login_methods/openid_auth.py#L247-L259
fooying/3102
0faee38c30b2e24154f41e68457cfd8f7a61c040
thirdparty/dns/tokenizer.py
python
Tokenizer.get_identifier
(self, origin=None)
return token.value
Read the next token and raise an exception if it is not an identifier. @raises dns.exception.SyntaxError: @rtype: string
Read the next token and raise an exception if it is not an identifier.
[ "Read", "the", "next", "token", "and", "raise", "an", "exception", "if", "it", "is", "not", "an", "identifier", "." ]
def get_identifier(self, origin=None): """Read the next token and raise an exception if it is not an identifier. @raises dns.exception.SyntaxError: @rtype: string """ token = self.get().unescape() if not token.is_identifier(): raise dns.exception.SyntaxError('expecting an identifier') return token.value
[ "def", "get_identifier", "(", "self", ",", "origin", "=", "None", ")", ":", "token", "=", "self", ".", "get", "(", ")", ".", "unescape", "(", ")", "if", "not", "token", ".", "is_identifier", "(", ")", ":", "raise", "dns", ".", "exception", ".", "Sy...
https://github.com/fooying/3102/blob/0faee38c30b2e24154f41e68457cfd8f7a61c040/thirdparty/dns/tokenizer.py#L507-L517
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/plistlib.py
python
_is_fmt_xml
(header)
return False
[]
def _is_fmt_xml(header): prefixes = (b'<?xml', b'<plist') for pfx in prefixes: if header.startswith(pfx): return True # Also check for alternative XML encodings, this is slightly # overkill because the Apple tools (and plistlib) will not # generate files with these encodings. for bom, encoding in ( (codecs.BOM_UTF8, "utf-8"), (codecs.BOM_UTF16_BE, "utf-16-be"), (codecs.BOM_UTF16_LE, "utf-16-le"), # expat does not support utf-32 #(codecs.BOM_UTF32_BE, "utf-32-be"), #(codecs.BOM_UTF32_LE, "utf-32-le"), ): if not header.startswith(bom): continue for start in prefixes: prefix = bom + start.decode('ascii').encode(encoding) if header[:len(prefix)] == prefix: return True return False
[ "def", "_is_fmt_xml", "(", "header", ")", ":", "prefixes", "=", "(", "b'<?xml'", ",", "b'<plist'", ")", "for", "pfx", "in", "prefixes", ":", "if", "header", ".", "startswith", "(", "pfx", ")", ":", "return", "True", "# Also check for alternative XML encodings,...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/plistlib.py#L406-L432
Blizzard/heroprotocol
3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c
heroprotocol/versions/protocol52351.py
python
decode_replay_game_events
(contents)
Decodes and yields each game event from the contents byte string.
Decodes and yields each game event from the contents byte string.
[ "Decodes", "and", "yields", "each", "game", "event", "from", "the", "contents", "byte", "string", "." ]
def decode_replay_game_events(contents): """Decodes and yields each game event from the contents byte string.""" decoder = BitPackedDecoder(contents, typeinfos) for event in _decode_event_stream(decoder, game_eventid_typeid, game_event_types, decode_user_id=True): yield event
[ "def", "decode_replay_game_events", "(", "contents", ")", ":", "decoder", "=", "BitPackedDecoder", "(", "contents", ",", "typeinfos", ")", "for", "event", "in", "_decode_event_stream", "(", "decoder", ",", "game_eventid_typeid", ",", "game_event_types", ",", "decode...
https://github.com/Blizzard/heroprotocol/blob/3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c/heroprotocol/versions/protocol52351.py#L395-L402
certtools/intelmq
7c1ab88b77bcbb30c7cabca5bb3525ad4aaac138
intelmq/lib/bot.py
python
Bot.__handle_sighup_signal
(self, signum: int, stack: Optional[object])
Called when signal is received and postpone.
Called when signal is received and postpone.
[ "Called", "when", "signal", "is", "received", "and", "postpone", "." ]
def __handle_sighup_signal(self, signum: int, stack: Optional[object]): """ Called when signal is received and postpone. """ self.__sighup.set() if not self._sighup_delay: self.__handle_sighup() else: self.logger.info('Received SIGHUP, initializing again later.')
[ "def", "__handle_sighup_signal", "(", "self", ",", "signum", ":", "int", ",", "stack", ":", "Optional", "[", "object", "]", ")", ":", "self", ".", "__sighup", ".", "set", "(", ")", "if", "not", "self", ".", "_sighup_delay", ":", "self", ".", "__handle_...
https://github.com/certtools/intelmq/blob/7c1ab88b77bcbb30c7cabca5bb3525ad4aaac138/intelmq/lib/bot.py#L262-L270
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/venv/lib/python3.7/site-packages/pip/_vendor/distlib/metadata.py
python
LegacyMetadata.is_field
(self, name)
return name in _ALL_FIELDS
return True if name is a valid metadata key
return True if name is a valid metadata key
[ "return", "True", "if", "name", "is", "a", "valid", "metadata", "key" ]
def is_field(self, name): """return True if name is a valid metadata key""" name = self._convert_name(name) return name in _ALL_FIELDS
[ "def", "is_field", "(", "self", ",", "name", ")", ":", "name", "=", "self", ".", "_convert_name", "(", "name", ")", "return", "name", "in", "_ALL_FIELDS" ]
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/venv/lib/python3.7/site-packages/pip/_vendor/distlib/metadata.py#L345-L348
loicland/superpoint_graph
9dfa370542aed1f817c6267e5af7921747da30a6
partition/provider.py
python
object_name_to_label
(object_class)
return object_label
convert from object name in S3DIS to an int
convert from object name in S3DIS to an int
[ "convert", "from", "object", "name", "in", "S3DIS", "to", "an", "int" ]
def object_name_to_label(object_class): """convert from object name in S3DIS to an int""" object_label = { 'ceiling': 1, 'floor': 2, 'wall': 3, 'column': 4, 'beam': 5, 'window': 6, 'door': 7, 'table': 8, 'chair': 9, 'bookcase': 10, 'sofa': 11, 'board': 12, 'clutter': 13, 'stairs': 0, }.get(object_class, 0) return object_label
[ "def", "object_name_to_label", "(", "object_class", ")", ":", "object_label", "=", "{", "'ceiling'", ":", "1", ",", "'floor'", ":", "2", ",", "'wall'", ":", "3", ",", "'column'", ":", "4", ",", "'beam'", ":", "5", ",", "'window'", ":", "6", ",", "'do...
https://github.com/loicland/superpoint_graph/blob/9dfa370542aed1f817c6267e5af7921747da30a6/partition/provider.py#L229-L247
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_user.py
python
Yedit.update
(self, path, value, index=None, curr_value=None)
return (False, self.yaml_dict)
put path, value into a dict
put path, value into a dict
[ "put", "path", "value", "into", "a", "dict" ]
def update(self, path, value, index=None, curr_value=None): ''' put path, value into a dict ''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError: entry = None if isinstance(entry, dict): # AUDIT:maybe-no-member makes sense due to fuzzy types # pylint: disable=maybe-no-member if not isinstance(value, dict): raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' + 'value=[{}] type=[{}]'.format(value, type(value))) entry.update(value) return (True, self.yaml_dict) elif isinstance(entry, list): # AUDIT:maybe-no-member makes sense due to fuzzy types # pylint: disable=maybe-no-member ind = None if curr_value: try: ind = entry.index(curr_value) except ValueError: return (False, self.yaml_dict) elif index is not None: ind = index if ind is not None and entry[ind] != value: entry[ind] = value return (True, self.yaml_dict) # see if it exists in the list try: ind = entry.index(value) except ValueError: # doesn't exist, append it entry.append(value) return (True, self.yaml_dict) # already exists, return if ind is not None: return (False, self.yaml_dict) return (False, self.yaml_dict)
[ "def", "update", "(", "self", ",", "path", ",", "value", ",", "index", "=", "None", ",", "curr_value", "=", "None", ")", ":", "try", ":", "entry", "=", "Yedit", ".", "get_entry", "(", "self", ".", "yaml_dict", ",", "path", ",", "self", ".", "separa...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_user.py#L595-L640
NVIDIA/DeepLearningExamples
589604d49e016cd9ef4525f7abcc9c7b826cfc5e
TensorFlow2/Classification/ConvNets/efficientnet/utils/augment.py
python
unwrap
(image: tf.Tensor, replace: int)
return image
Unwraps an image produced by wrap. Where there is a 0 in the last channel for every spatial position, the rest of the three channels in that spatial dimension are grayed (set to 128). Operations like translate and shear on a wrapped Tensor will leave 0s in empty locations. Some transformations look at the intensity of values to do preprocessing, and we want these empty pixels to assume the 'average' value, rather than pure black. Args: image: A 3D Image Tensor with 4 channels. replace: A one or three value 1D tensor to fill empty pixels. Returns: image: A 3D image Tensor with 3 channels.
Unwraps an image produced by wrap.
[ "Unwraps", "an", "image", "produced", "by", "wrap", "." ]
def unwrap(image: tf.Tensor, replace: int) -> tf.Tensor: """Unwraps an image produced by wrap. Where there is a 0 in the last channel for every spatial position, the rest of the three channels in that spatial dimension are grayed (set to 128). Operations like translate and shear on a wrapped Tensor will leave 0s in empty locations. Some transformations look at the intensity of values to do preprocessing, and we want these empty pixels to assume the 'average' value, rather than pure black. Args: image: A 3D Image Tensor with 4 channels. replace: A one or three value 1D tensor to fill empty pixels. Returns: image: A 3D image Tensor with 3 channels. """ image_shape = tf.shape(image) # Flatten the spatial dimensions. flattened_image = tf.reshape(image, [-1, image_shape[2]]) # Find all pixels where the last channel is zero. alpha_channel = tf.expand_dims(flattened_image[:, 3], axis=-1) replace = tf.concat([replace, tf.ones([1], image.dtype)], 0) # Where they are zero, fill them in with 'replace'. flattened_image = tf.where( tf.equal(alpha_channel, 0), tf.ones_like(flattened_image, dtype=image.dtype) * replace, flattened_image) image = tf.reshape(flattened_image, image_shape) image = tf.slice(image, [0, 0, 0], [image_shape[0], image_shape[1], 3]) return image
[ "def", "unwrap", "(", "image", ":", "tf", ".", "Tensor", ",", "replace", ":", "int", ")", "->", "tf", ".", "Tensor", ":", "image_shape", "=", "tf", ".", "shape", "(", "image", ")", "# Flatten the spatial dimensions.", "flattened_image", "=", "tf", ".", "...
https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/TensorFlow2/Classification/ConvNets/efficientnet/utils/augment.py#L538-L573
pandas-dev/pandas
5ba7d714014ae8feaccc0dd4a98890828cf2832d
pandas/core/apply.py
python
Apply.normalize_dictlike_arg
( self, how: str, obj: DataFrame | Series, func: AggFuncTypeDict )
return func
Handler for dict-like argument. Ensures that necessary columns exist if obj is a DataFrame, and that a nested renamer is not passed. Also normalizes to all lists when values consists of a mix of list and non-lists.
Handler for dict-like argument.
[ "Handler", "for", "dict", "-", "like", "argument", "." ]
def normalize_dictlike_arg( self, how: str, obj: DataFrame | Series, func: AggFuncTypeDict ) -> AggFuncTypeDict: """ Handler for dict-like argument. Ensures that necessary columns exist if obj is a DataFrame, and that a nested renamer is not passed. Also normalizes to all lists when values consists of a mix of list and non-lists. """ assert how in ("apply", "agg", "transform") # Can't use func.values(); wouldn't work for a Series if ( how == "agg" and isinstance(obj, ABCSeries) and any(is_list_like(v) for _, v in func.items()) ) or (any(is_dict_like(v) for _, v in func.items())): # GH 15931 - deprecation of renaming keys raise SpecificationError("nested renamer is not supported") if obj.ndim != 1: # Check for missing columns on a frame cols = set(func.keys()) - set(obj.columns) if len(cols) > 0: cols_sorted = list(safe_sort(list(cols))) raise KeyError(f"Column(s) {cols_sorted} do not exist") is_aggregator = lambda x: isinstance(x, (list, tuple, dict)) # if we have a dict of any non-scalars # eg. {'A' : ['mean']}, normalize all to # be list-likes # Cannot use func.values() because arg may be a Series if any(is_aggregator(x) for _, x in func.items()): new_func: AggFuncTypeDict = {} for k, v in func.items(): if not is_aggregator(v): # mypy can't realize v is not a list here new_func[k] = [v] # type:ignore[list-item] else: new_func[k] = v func = new_func return func
[ "def", "normalize_dictlike_arg", "(", "self", ",", "how", ":", "str", ",", "obj", ":", "DataFrame", "|", "Series", ",", "func", ":", "AggFuncTypeDict", ")", "->", "AggFuncTypeDict", ":", "assert", "how", "in", "(", "\"apply\"", ",", "\"agg\"", ",", "\"tran...
https://github.com/pandas-dev/pandas/blob/5ba7d714014ae8feaccc0dd4a98890828cf2832d/pandas/core/apply.py#L559-L602
ClementPinard/DepthNet
3c753fc21b06c9be307d73c8e7a0c61f2ea56cc3
datasets/listdataset.py
python
default_loader
(root, path_imgs, path_depth)
return [imgs, depth]
[]
def default_loader(root, path_imgs, path_depth): imgs = [imread(root/path) for path in path_imgs] depth = np.load(root/path_depth) return [imgs, depth]
[ "def", "default_loader", "(", "root", ",", "path_imgs", ",", "path_depth", ")", ":", "imgs", "=", "[", "imread", "(", "root", "/", "path", ")", "for", "path", "in", "path_imgs", "]", "depth", "=", "np", ".", "load", "(", "root", "/", "path_depth", ")...
https://github.com/ClementPinard/DepthNet/blob/3c753fc21b06c9be307d73c8e7a0c61f2ea56cc3/datasets/listdataset.py#L6-L9
awslabs/aws-lambda-powertools-python
0c6ac0fe183476140ee1df55fe9fa1cc20925577
aws_lambda_powertools/utilities/parameters/base.py
python
BaseProvider._get
(self, name: str, **sdk_options)
Retrieve parameter value from the underlying parameter store
Retrieve parameter value from the underlying parameter store
[ "Retrieve", "parameter", "value", "from", "the", "underlying", "parameter", "store" ]
def _get(self, name: str, **sdk_options) -> Union[str, bytes]: """ Retrieve parameter value from the underlying parameter store """ raise NotImplementedError()
[ "def", "_get", "(", "self", ",", "name", ":", "str", ",", "*", "*", "sdk_options", ")", "->", "Union", "[", "str", ",", "bytes", "]", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/awslabs/aws-lambda-powertools-python/blob/0c6ac0fe183476140ee1df55fe9fa1cc20925577/aws_lambda_powertools/utilities/parameters/base.py#L105-L109
1012598167/flask_mongodb_game
60c7e0351586656ec38f851592886338e50b4110
python_flask/venv/Lib/site-packages/jinja2/environment.py
python
Template.stream
(self, *args, **kwargs)
return TemplateStream(self.generate(*args, **kwargs))
Works exactly like :meth:`generate` but returns a :class:`TemplateStream`.
Works exactly like :meth:`generate` but returns a :class:`TemplateStream`.
[ "Works", "exactly", "like", ":", "meth", ":", "generate", "but", "returns", "a", ":", "class", ":", "TemplateStream", "." ]
def stream(self, *args, **kwargs): """Works exactly like :meth:`generate` but returns a :class:`TemplateStream`. """ return TemplateStream(self.generate(*args, **kwargs))
[ "def", "stream", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "TemplateStream", "(", "self", ".", "generate", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/jinja2/environment.py#L1023-L1027
mozilla/kitsune
7c7cf9baed57aa776547aea744243ccad6ca91fb
kitsune/groups/views.py
python
remove_leader
(request, group_slug, user_id)
return render(request, "groups/confirm_remove_leader.html", {"profile": prof, "leader": user})
Remove a leader from the group.
Remove a leader from the group.
[ "Remove", "a", "leader", "from", "the", "group", "." ]
def remove_leader(request, group_slug, user_id): """Remove a leader from the group.""" prof = get_object_or_404(GroupProfile, slug=group_slug) user = get_object_or_404(User, id=user_id) if not _user_can_manage_leaders(request.user, prof): raise PermissionDenied if request.method == "POST": prof.leaders.remove(user) msg = _("{user} removed from the group leaders successfully!").format(user=user.username) messages.add_message(request, messages.SUCCESS, msg) return HttpResponseRedirect(prof.get_absolute_url()) return render(request, "groups/confirm_remove_leader.html", {"profile": prof, "leader": user})
[ "def", "remove_leader", "(", "request", ",", "group_slug", ",", "user_id", ")", ":", "prof", "=", "get_object_or_404", "(", "GroupProfile", ",", "slug", "=", "group_slug", ")", "user", "=", "get_object_or_404", "(", "User", ",", "id", "=", "user_id", ")", ...
https://github.com/mozilla/kitsune/blob/7c7cf9baed57aa776547aea744243ccad6ca91fb/kitsune/groups/views.py#L201-L215
mysql/mysql-utilities
08276b2258bf9739f53406b354b21195ff69a261
mysql/utilities/common/replication.py
python
Slave.get_delay
(self)
return (state, sec_behind, delay_remaining, read_log_file, read_log_pos)
Return slave delay values This method retrieves the slave's delay parameters. Returns tuple - slave delay values or None if not connected
Return slave delay values
[ "Return", "slave", "delay", "values" ]
def get_delay(self): """Return slave delay values This method retrieves the slave's delay parameters. Returns tuple - slave delay values or None if not connected """ res = self.get_status() if res == []: return None # slave IO state state = res[0][_SLAVE_IO_STATE] # seconds behind master if res[0][_SLAVE_DELAY] is None: sec_behind = 0 else: sec_behind = int(res[0][_SLAVE_DELAY]) # remaining delay delay_remaining = res[0][_SLAVE_REMAINING_DELAY] # master's log file read read_log_file = res[0][_SLAVE_MASTER_LOG_FILE] # position in master's binlog read_log_pos = res[0][_SLAVE_MASTER_LOG_FILE_POS] return (state, sec_behind, delay_remaining, read_log_file, read_log_pos)
[ "def", "get_delay", "(", "self", ")", ":", "res", "=", "self", ".", "get_status", "(", ")", "if", "res", "==", "[", "]", ":", "return", "None", "# slave IO state", "state", "=", "res", "[", "0", "]", "[", "_SLAVE_IO_STATE", "]", "# seconds behind master"...
https://github.com/mysql/mysql-utilities/blob/08276b2258bf9739f53406b354b21195ff69a261/mysql/utilities/common/replication.py#L1466-L1492
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pkg_resources/__init__.py
python
get_distribution
(dist)
return dist
Return a current distribution object for a Requirement or string
Return a current distribution object for a Requirement or string
[ "Return", "a", "current", "distribution", "object", "for", "a", "Requirement", "or", "string" ]
def get_distribution(dist): """Return a current distribution object for a Requirement or string""" if isinstance(dist, six.string_types): dist = Requirement.parse(dist) if isinstance(dist, Requirement): dist = get_provider(dist) if not isinstance(dist, Distribution): raise TypeError("Expected string, Requirement, or Distribution", dist) return dist
[ "def", "get_distribution", "(", "dist", ")", ":", "if", "isinstance", "(", "dist", ",", "six", ".", "string_types", ")", ":", "dist", "=", "Requirement", ".", "parse", "(", "dist", ")", "if", "isinstance", "(", "dist", ",", "Requirement", ")", ":", "di...
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pkg_resources/__init__.py#L476-L484
modin-project/modin
0d9d14e6669be3dd6bb3b72222dbe6a6dffe1bee
modin/pandas/indexing.py
python
boolean_mask_to_numeric
(indexer)
Convert boolean mask to numeric indices. Parameters ---------- indexer : list-like of booleans Returns ------- np.ndarray of ints Numerical positions of ``True`` elements in the passed `indexer`.
Convert boolean mask to numeric indices.
[ "Convert", "boolean", "mask", "to", "numeric", "indices", "." ]
def boolean_mask_to_numeric(indexer): """ Convert boolean mask to numeric indices. Parameters ---------- indexer : list-like of booleans Returns ------- np.ndarray of ints Numerical positions of ``True`` elements in the passed `indexer`. """ if isinstance(indexer, (np.ndarray, Series, pandas.Series)): return np.where(indexer)[0] else: # It's faster to build the resulting numpy array from the reduced amount of data via # `compress` iterator than convert non-numpy-like `indexer` to numpy and apply `np.where`. return np.fromiter( # `itertools.compress` masks `data` with the `selectors` mask, # works about ~10% faster than a pure list comprehension itertools.compress(data=range(len(indexer)), selectors=indexer), dtype=np.int64, )
[ "def", "boolean_mask_to_numeric", "(", "indexer", ")", ":", "if", "isinstance", "(", "indexer", ",", "(", "np", ".", "ndarray", ",", "Series", ",", "pandas", ".", "Series", ")", ")", ":", "return", "np", ".", "where", "(", "indexer", ")", "[", "0", "...
https://github.com/modin-project/modin/blob/0d9d14e6669be3dd6bb3b72222dbe6a6dffe1bee/modin/pandas/indexing.py#L204-L227
pillone/usntssearch
24b5e5bc4b6af2589d95121c4d523dc58cb34273
NZBmegasearch/mechanize/_pullparser.py
python
_AbstractParser.get_tag
(self, *names)
Return the next Token that represents an opening or closing tag. If arguments are given, they are taken to be element names in which the caller is interested: tags representing other elements will be skipped. Element names must be given in lower case. Raises NoMoreTokensError.
Return the next Token that represents an opening or closing tag.
[ "Return", "the", "next", "Token", "that", "represents", "an", "opening", "or", "closing", "tag", "." ]
def get_tag(self, *names): """Return the next Token that represents an opening or closing tag. If arguments are given, they are taken to be element names in which the caller is interested: tags representing other elements will be skipped. Element names must be given in lower case. Raises NoMoreTokensError. """ while 1: tok = self.get_token() if tok.type not in ["starttag", "endtag", "startendtag"]: continue if names: if tok.data in names: return tok else: return tok
[ "def", "get_tag", "(", "self", ",", "*", "names", ")", ":", "while", "1", ":", "tok", "=", "self", ".", "get_token", "(", ")", "if", "tok", ".", "type", "not", "in", "[", "\"starttag\"", ",", "\"endtag\"", ",", "\"startendtag\"", "]", ":", "continue"...
https://github.com/pillone/usntssearch/blob/24b5e5bc4b6af2589d95121c4d523dc58cb34273/NZBmegasearch/mechanize/_pullparser.py#L245-L263
OpenCobolIDE/OpenCobolIDE
c78d0d335378e5fe0a5e74f53c19b68b55e85388
open_cobol_ide/extlibs/pyqode/core/api/utils.py
python
TextHelper.selection_range
(self)
return start, end
Returns the selected lines boundaries (start line, end line) :return: tuple(int, int)
Returns the selected lines boundaries (start line, end line)
[ "Returns", "the", "selected", "lines", "boundaries", "(", "start", "line", "end", "line", ")" ]
def selection_range(self): """ Returns the selected lines boundaries (start line, end line) :return: tuple(int, int) """ editor = self._editor doc = editor.document() start = doc.findBlock( editor.textCursor().selectionStart()).blockNumber() end = doc.findBlock( editor.textCursor().selectionEnd()).blockNumber() text_cursor = QtGui.QTextCursor(editor.textCursor()) text_cursor.setPosition(editor.textCursor().selectionEnd()) if text_cursor.columnNumber() == 0 and start != end: end -= 1 return start, end
[ "def", "selection_range", "(", "self", ")", ":", "editor", "=", "self", ".", "_editor", "doc", "=", "editor", ".", "document", "(", ")", "start", "=", "doc", ".", "findBlock", "(", "editor", ".", "textCursor", "(", ")", ".", "selectionStart", "(", ")",...
https://github.com/OpenCobolIDE/OpenCobolIDE/blob/c78d0d335378e5fe0a5e74f53c19b68b55e85388/open_cobol_ide/extlibs/pyqode/core/api/utils.py#L467-L483
cloudera/impyla
0c736af4cad2bade9b8e313badc08ec50e81c948
impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py
python
open_txns_args.__init__
(self, rqst=None,)
[]
def __init__(self, rqst=None,): self.rqst = rqst
[ "def", "__init__", "(", "self", ",", "rqst", "=", "None", ",", ")", ":", "self", ".", "rqst", "=", "rqst" ]
https://github.com/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L32104-L32105
mozman/ezdxf
59d0fc2ea63f5cf82293428f5931da7e9f9718e9
src/ezdxf/document.py
python
Drawing.dxfversion
(self)
return self._dxfversion
Get current DXF version.
Get current DXF version.
[ "Get", "current", "DXF", "version", "." ]
def dxfversion(self) -> str: """Get current DXF version.""" return self._dxfversion
[ "def", "dxfversion", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_dxfversion" ]
https://github.com/mozman/ezdxf/blob/59d0fc2ea63f5cf82293428f5931da7e9f9718e9/src/ezdxf/document.py#L272-L274
holland-backup/holland
77dcfe9f23d4254e4c351cdc18f29a8d34945812
holland/core/util/path.py
python
disk_capacity
(target_path)
return info.f_frsize * info.f_blocks
Find the total capacity of the filesystem that target_path is on :returns: integer number of input_bytes
Find the total capacity of the filesystem that target_path is on
[ "Find", "the", "total", "capacity", "of", "the", "filesystem", "that", "target_path", "is", "on" ]
def disk_capacity(target_path): """Find the total capacity of the filesystem that target_path is on :returns: integer number of input_bytes """ path = getmount(target_path) info = os.statvfs(path) return info.f_frsize * info.f_blocks
[ "def", "disk_capacity", "(", "target_path", ")", ":", "path", "=", "getmount", "(", "target_path", ")", "info", "=", "os", ".", "statvfs", "(", "path", ")", "return", "info", ".", "f_frsize", "*", "info", ".", "f_blocks" ]
https://github.com/holland-backup/holland/blob/77dcfe9f23d4254e4c351cdc18f29a8d34945812/holland/core/util/path.py#L126-L133
brainiak/brainiak
ee093597c6c11597b0a59e95b48d2118e40394a5
brainiak/fcma/classifier.py
python
Classifier._prepare_test_data
(self, corr_data)
return data
Prepare the data to be applied to the predict function. if the classifier is SVM, do kernel precomputation, otherwise the test data is the reshaped corr_data Parameters ---------- corr_data: the (normalized) correlation data in shape [num_samples, num_voxels, num_voxels2] Returns ------- data: the data to be predicted, in shape of [num_samples, num_dim]
Prepare the data to be applied to the predict function.
[ "Prepare", "the", "data", "to", "be", "applied", "to", "the", "predict", "function", "." ]
def _prepare_test_data(self, corr_data): """Prepare the data to be applied to the predict function. if the classifier is SVM, do kernel precomputation, otherwise the test data is the reshaped corr_data Parameters ---------- corr_data: the (normalized) correlation data in shape [num_samples, num_voxels, num_voxels2] Returns ------- data: the data to be predicted, in shape of [num_samples, num_dim] """ num_test_samples = corr_data.shape[0] assert num_test_samples > 0, \ 'at least one test sample is needed' if isinstance(self.clf, sklearn.svm.SVC) \ and self.clf.kernel == 'precomputed': assert self.training_data_ is not None, \ 'when using precomputed kernel of SVM, ' \ 'all training data must be provided' num_training_samples = self.training_data_.shape[0] data = np.zeros((num_test_samples, num_training_samples), np.float32, order='C') num_features = self.num_features_ corr_data = corr_data.reshape(num_test_samples, num_features) # compute the similarity vectors using corr_data and training_data blas.compute_single_matrix_multiplication('T', 'N', num_training_samples, num_test_samples, num_features, 1.0, self.training_data_, num_features, corr_data, num_features, 0.0, data, num_training_samples) # shrink the values for getting more stable alpha values # in SVM training iteration num_digits = self.num_digits_ if num_digits > 2: proportion = 10**(2-num_digits) data *= proportion logger.debug( 'similarity vectors computation done' ) else: data = corr_data.reshape(num_test_samples, self.num_features_) return data
[ "def", "_prepare_test_data", "(", "self", ",", "corr_data", ")", ":", "num_test_samples", "=", "corr_data", ".", "shape", "[", "0", "]", "assert", "num_test_samples", ">", "0", ",", "'at least one test sample is needed'", "if", "isinstance", "(", "self", ".", "c...
https://github.com/brainiak/brainiak/blob/ee093597c6c11597b0a59e95b48d2118e40394a5/brainiak/fcma/classifier.py#L222-L277
RiotGames/cloud-inquisitor
29a26c705381fdba3538b4efedb25b9e09b387ed
plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py
python
RequiredTagsAuditor.process_actions
(self, actions)
return notices
Process the actions we want to take Args: actions (`list`): List of actions we want to take Returns: `list` of notifications
Process the actions we want to take
[ "Process", "the", "actions", "we", "want", "to", "take" ]
def process_actions(self, actions): """Process the actions we want to take Args: actions (`list`): List of actions we want to take Returns: `list` of notifications """ notices = {} notification_contacts = {} for action in actions: resource = action['resource'] action_status = ActionStatus.SUCCEED try: if action['action'] == AuditActions.REMOVE: action_status = self.process_action( resource, AuditActions.REMOVE ) if action_status == ActionStatus.SUCCEED: db.session.delete(action['issue'].issue) elif action['action'] == AuditActions.STOP: action_status = self.process_action( resource, AuditActions.STOP ) if action_status == ActionStatus.SUCCEED: action['issue'].update({ 'missing_tags': action['missing_tags'], 'notes': action['notes'], 'last_alert': action['last_alert'], 'state': action['action'] }) elif action['action'] == AuditActions.FIXED: db.session.delete(action['issue'].issue) elif action['action'] == AuditActions.ALERT: action['issue'].update({ 'missing_tags': action['missing_tags'], 'notes': action['notes'], 'last_alert': action['last_alert'], 'state': action['action'] }) db.session.commit() if action_status == ActionStatus.SUCCEED: for owner in [ dict(t) for t in {tuple(d.items()) for d in (action['owners'] + self.permanent_emails)} ]: if owner['value'] not in notification_contacts: contact = NotificationContact(type=owner['type'], value=owner['value']) notification_contacts[owner['value']] = contact notices[contact] = { 'fixed': [], 'not_fixed': [] } else: contact = notification_contacts[owner['value']] if action['action'] == AuditActions.FIXED: notices[contact]['fixed'].append(action) else: notices[contact]['not_fixed'].append(action) except Exception as ex: self.log.exception('Unexpected error while processing resource {}/{}/{}/{}'.format( action['resource'].account.account_name, action['resource'].id, action['resource'], ex )) return notices
[ "def", "process_actions", "(", "self", ",", "actions", ")", ":", "notices", "=", "{", "}", "notification_contacts", "=", "{", "}", "for", "action", "in", "actions", ":", "resource", "=", "action", "[", "'resource'", "]", "action_status", "=", "ActionStatus",...
https://github.com/RiotGames/cloud-inquisitor/blob/29a26c705381fdba3538b4efedb25b9e09b387ed/plugins/public/cinq-auditor-required-tags/cinq_auditor_required_tags/__init__.py#L347-L423
grnet/synnefo
d06ec8c7871092131cdaabf6b03ed0b504c93e43
snf-pithos-backend/pithos/backends/lib/sqlalchemy/node.py
python
Node.node_get_properties
(self, node)
return l
Return the node's (parent, path). Return None if the node is not found.
Return the node's (parent, path). Return None if the node is not found.
[ "Return", "the", "node", "s", "(", "parent", "path", ")", ".", "Return", "None", "if", "the", "node", "is", "not", "found", "." ]
def node_get_properties(self, node): """Return the node's (parent, path). Return None if the node is not found. """ s = select([self.nodes.c.parent, self.nodes.c.path]) s = s.where(self.nodes.c.node == node) r = self.conn.execute(s) l = r.fetchone() r.close() return l
[ "def", "node_get_properties", "(", "self", ",", "node", ")", ":", "s", "=", "select", "(", "[", "self", ".", "nodes", ".", "c", ".", "parent", ",", "self", ".", "nodes", ".", "c", ".", "path", "]", ")", "s", "=", "s", ".", "where", "(", "self",...
https://github.com/grnet/synnefo/blob/d06ec8c7871092131cdaabf6b03ed0b504c93e43/snf-pithos-backend/pithos/backends/lib/sqlalchemy/node.py#L299-L309
mayank93/Twitter-Sentiment-Analysis
f095c6ca6bf69787582b5dabb140fefaf278eb37
front-end/web2py/gluon/contrib/feedparser.py
python
_stripDoctype
(data)
return version, data, dict(replacement and [(k.decode('utf-8'), v.decode('utf-8')) for k, v in safe_pattern.findall(replacement)])
Strips DOCTYPE from XML document, returns (rss_version, stripped_data) rss_version may be 'rss091n' or None stripped_data is the same XML document, minus the DOCTYPE
Strips DOCTYPE from XML document, returns (rss_version, stripped_data)
[ "Strips", "DOCTYPE", "from", "XML", "document", "returns", "(", "rss_version", "stripped_data", ")" ]
def _stripDoctype(data): '''Strips DOCTYPE from XML document, returns (rss_version, stripped_data) rss_version may be 'rss091n' or None stripped_data is the same XML document, minus the DOCTYPE ''' start = re.search(_s2bytes('<\w'), data) start = start and start.start() or -1 head,data = data[:start+1], data[start+1:] entity_pattern = re.compile(_s2bytes(r'^\s*<!ENTITY([^>]*?)>'), re.MULTILINE) entity_results=entity_pattern.findall(head) head = entity_pattern.sub(_s2bytes(''), head) doctype_pattern = re.compile(_s2bytes(r'^\s*<!DOCTYPE([^>]*?)>'), re.MULTILINE) doctype_results = doctype_pattern.findall(head) doctype = doctype_results and doctype_results[0] or _s2bytes('') if doctype.lower().count(_s2bytes('netscape')): version = u'rss091n' else: version = None # only allow in 'safe' inline entity definitions replacement=_s2bytes('') if len(doctype_results)==1 and entity_results: safe_pattern=re.compile(_s2bytes('\s+(\w+)\s+"(&#\w+;|[^&"]*)"')) safe_entities=filter(lambda e: safe_pattern.match(e),entity_results) if safe_entities: replacement=_s2bytes('<!DOCTYPE feed [\n <!ENTITY') + _s2bytes('>\n <!ENTITY ').join(safe_entities) + _s2bytes('>\n]>') data = doctype_pattern.sub(replacement, head) + data return version, data, dict(replacement and [(k.decode('utf-8'), v.decode('utf-8')) for k, v in safe_pattern.findall(replacement)])
[ "def", "_stripDoctype", "(", "data", ")", ":", "start", "=", "re", ".", "search", "(", "_s2bytes", "(", "'<\\w'", ")", ",", "data", ")", "start", "=", "start", "and", "start", ".", "start", "(", ")", "or", "-", "1", "head", ",", "data", "=", "dat...
https://github.com/mayank93/Twitter-Sentiment-Analysis/blob/f095c6ca6bf69787582b5dabb140fefaf278eb37/front-end/web2py/gluon/contrib/feedparser.py#L3648-L3678
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/tornado-6.0.1-py3.7-macosx-12.1-iPad6,7.egg/tornado/netutil.py
python
Resolver.close
(self)
Closes the `Resolver`, freeing any resources used. .. versionadded:: 3.1
Closes the `Resolver`, freeing any resources used.
[ "Closes", "the", "Resolver", "freeing", "any", "resources", "used", "." ]
def close(self) -> None: """Closes the `Resolver`, freeing any resources used. .. versionadded:: 3.1 """ pass
[ "def", "close", "(", "self", ")", "->", "None", ":", "pass" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/tornado-6.0.1-py3.7-macosx-12.1-iPad6,7.egg/tornado/netutil.py#L362-L368
rafellerc/Pytorch-SiamFC
d64d0fee08c7972726337be07e783d44bd9c275e
training/summary_utils.py
python
SummaryMaker.__init__
(self, log_dir, params, up_factor)
Args: log_dir: (str) The path to the folder where the summary files are going to be written. The summary object creates a train and a val folders to store the summary files. params: (train.utils.Params) The parameters loaded from the parameters.json file. up_factor: (int) The upscale factor that indicates how much the scores maps need to be upscaled to match the original scale (used when superposing the embeddings and score maps to the input images). Attributes: writer_train: (tensorboardX.writer.SummaryWriter) The tensorboardX writer that writes the training informations. writer_val: (tensorboardX.writer.SummaryWriter) The tensorboardX writer that writes the validation informations. epoch: (int) Stores the current epoch. ref_sz: (int) The size in pixels of the reference image. srch_sz: (int) The size in pixels of the search image. up_factor: (int) The upscale factor. See Args.
Args: log_dir: (str) The path to the folder where the summary files are going to be written. The summary object creates a train and a val folders to store the summary files. params: (train.utils.Params) The parameters loaded from the parameters.json file. up_factor: (int) The upscale factor that indicates how much the scores maps need to be upscaled to match the original scale (used when superposing the embeddings and score maps to the input images).
[ "Args", ":", "log_dir", ":", "(", "str", ")", "The", "path", "to", "the", "folder", "where", "the", "summary", "files", "are", "going", "to", "be", "written", ".", "The", "summary", "object", "creates", "a", "train", "and", "a", "val", "folders", "to",...
def __init__(self, log_dir, params, up_factor): """ Args: log_dir: (str) The path to the folder where the summary files are going to be written. The summary object creates a train and a val folders to store the summary files. params: (train.utils.Params) The parameters loaded from the parameters.json file. up_factor: (int) The upscale factor that indicates how much the scores maps need to be upscaled to match the original scale (used when superposing the embeddings and score maps to the input images). Attributes: writer_train: (tensorboardX.writer.SummaryWriter) The tensorboardX writer that writes the training informations. writer_val: (tensorboardX.writer.SummaryWriter) The tensorboardX writer that writes the validation informations. epoch: (int) Stores the current epoch. ref_sz: (int) The size in pixels of the reference image. srch_sz: (int) The size in pixels of the search image. up_factor: (int) The upscale factor. See Args. """ # We use two different summary writers so we can plot both curves in # the same plot, as suggested in https://www.quora.com/How-do-you-plot-training-and-validation-loss-on-the-same-graph-using-TensorFlow%E2%80%99s-TensorBoard self.writer_train = SummaryWriter(join(log_dir, 'train')) self.writer_val = SummaryWriter(join(log_dir, 'val')) self.epoch = None self.ref_sz = params.reference_sz self.srch_sz = params.search_sz self.up_factor = up_factor
[ "def", "__init__", "(", "self", ",", "log_dir", ",", "params", ",", "up_factor", ")", ":", "# We use two different summary writers so we can plot both curves in", "# the same plot, as suggested in https://www.quora.com/How-do-you-plot-training-and-validation-loss-on-the-same-graph-using-Te...
https://github.com/rafellerc/Pytorch-SiamFC/blob/d64d0fee08c7972726337be07e783d44bd9c275e/training/summary_utils.py#L20-L51
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/pyasn1/type/univ.py
python
Real.isMinusInfinity
(self)
return self.isMinusInf
[]
def isMinusInfinity(self): return self.isMinusInf
[ "def", "isMinusInfinity", "(", "self", ")", ":", "return", "self", ".", "isMinusInf" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/pyasn1/type/univ.py#L1544-L1545
iagcl/watchmen
d329b357e6fde3ad91e972988b160a33c12afc2a
elasticsearch/roll_indexes/packages/requests/sessions.py
python
Session.prepare_request
(self, request)
return p
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`.
[ "Constructs", "a", ":", "class", ":", "PreparedRequest", "<PreparedRequest", ">", "for", "transmission", "and", "returns", "it", ".", "The", ":", "class", ":", "PreparedRequest", "has", "settings", "merged", "from", "the", ":", "class", ":", "Request", "<Reque...
def prepare_request(self, request): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest """ cookies = request.cookies or {} # Bootstrap CookieJar. if not isinstance(cookies, cookielib.CookieJar): cookies = cookiejar_from_dict(cookies) # Merge with session cookies merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies) # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(request.url) p = PreparedRequest() p.prepare( method=request.method.upper(), url=request.url, files=request.files, data=request.data, json=request.json, headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict), params=merge_setting(request.params, self.params), auth=merge_setting(auth, self.auth), cookies=merged_cookies, hooks=merge_hooks(request.hooks, self.hooks), ) return p
[ "def", "prepare_request", "(", "self", ",", "request", ")", ":", "cookies", "=", "request", ".", "cookies", "or", "{", "}", "# Bootstrap CookieJar.", "if", "not", "isinstance", "(", "cookies", ",", "cookielib", ".", "CookieJar", ")", ":", "cookies", "=", "...
https://github.com/iagcl/watchmen/blob/d329b357e6fde3ad91e972988b160a33c12afc2a/elasticsearch/roll_indexes/packages/requests/sessions.py#L401-L439
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/schemes/toric/divisor.py
python
ToricDivisor_generic._sheaf_complex
(self, m)
return SimplicialComplex([c.ambient_ray_indices() for c in negative_cones])
r""" Return a simplicial complex whose cohomology is isomorphic to the `m\in M`-graded piece of the sheaf cohomology. Helper for :meth:`cohomology`. INPUT: - `m` -- a point in ``self.scheme().fan().dual_lattice()``. OUTPUT: - :class:`simplicial complex <sage.topology.simplicial_complex.SimplicialComplex>`. EXAMPLES:: sage: dP6 = toric_varieties.dP6() sage: D0 = dP6.divisor(0) sage: D2 = dP6.divisor(2) sage: D3 = dP6.divisor(3) sage: D = -D0 + 2*D2 - D3 sage: M = dP6.fan().dual_lattice() sage: D._sheaf_complex( M(1,0) ) Simplicial complex with vertex set (0, 1, 3) and facets {(3,), (0, 1)}
r""" Return a simplicial complex whose cohomology is isomorphic to the `m\in M`-graded piece of the sheaf cohomology.
[ "r", "Return", "a", "simplicial", "complex", "whose", "cohomology", "is", "isomorphic", "to", "the", "m", "\\", "in", "M", "-", "graded", "piece", "of", "the", "sheaf", "cohomology", "." ]
def _sheaf_complex(self, m): r""" Return a simplicial complex whose cohomology is isomorphic to the `m\in M`-graded piece of the sheaf cohomology. Helper for :meth:`cohomology`. INPUT: - `m` -- a point in ``self.scheme().fan().dual_lattice()``. OUTPUT: - :class:`simplicial complex <sage.topology.simplicial_complex.SimplicialComplex>`. EXAMPLES:: sage: dP6 = toric_varieties.dP6() sage: D0 = dP6.divisor(0) sage: D2 = dP6.divisor(2) sage: D3 = dP6.divisor(3) sage: D = -D0 + 2*D2 - D3 sage: M = dP6.fan().dual_lattice() sage: D._sheaf_complex( M(1,0) ) Simplicial complex with vertex set (0, 1, 3) and facets {(3,), (0, 1)} """ fan = self.parent().scheme().fan() ray_is_negative = [ m*ray + self.coefficient(i) < 0 for i, ray in enumerate(fan.rays()) ] def cone_is_negative(cone): # and non-trivial if cone.is_trivial(): return False return all(ray_is_negative[i] for i in cone.ambient_ray_indices()) negative_cones = [cone for cone in flatten(fan.cones()) if cone_is_negative(cone)] return SimplicialComplex([c.ambient_ray_indices() for c in negative_cones])
[ "def", "_sheaf_complex", "(", "self", ",", "m", ")", ":", "fan", "=", "self", ".", "parent", "(", ")", ".", "scheme", "(", ")", ".", "fan", "(", ")", "ray_is_negative", "=", "[", "m", "*", "ray", "+", "self", ".", "coefficient", "(", "i", ")", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/schemes/toric/divisor.py#L1543-L1579
weewx/weewx
cb594fce224560bd8696050fc5c7843c7839320e
bin/weewx/wxxtypes.py
python
StdWXXTypes.__init__
(self, engine, config_dict)
Initialize an instance of StdWXXTypes
Initialize an instance of StdWXXTypes
[ "Initialize", "an", "instance", "of", "StdWXXTypes" ]
def __init__(self, engine, config_dict): """Initialize an instance of StdWXXTypes""" super(StdWXXTypes, self).__init__(engine, config_dict) altitude_vt = engine.stn_info.altitude_vt latitude_f = engine.stn_info.latitude_f longitude_f = engine.stn_info.longitude_f # These options were never documented. They have moved. Fail hard if they are present. if 'StdWXCalculate' in config_dict \ and any(key in config_dict['StdWXCalculate'] for key in ['rain_period', 'et_period', 'wind_height', 'atc', 'nfac', 'max_delta_12h']): raise ValueError("Undocumented options for [StdWXCalculate] have moved. " "See User's Guide.") # Get any user-defined overrides try: override_dict = config_dict['StdWXCalculate']['WXXTypes'] except KeyError: override_dict = {} # Get the default values, then merge the user overrides into it option_dict = weeutil.config.deep_copy(defaults_dict['StdWXCalculate']['WXXTypes']) option_dict.merge(override_dict) # Get force_null from the option dictionary force_null = to_bool(option_dict['windDir'].get('force_null', True)) # Option ignore_zero_wind has also moved, but we will support it in a backwards-compatible # way, provided that it doesn't conflict with any setting of force_null. try: # Is there a value for ignore_zero_wind as well? ignore_zero_wind = to_bool(config_dict['StdWXCalculate']['ignore_zero_wind']) except KeyError: # No. We're done pass else: # No exception, so there must be a value for ignore_zero_wind. # Is there an explicit value for 'force_null'? That is, a default was not used? if 'force_null' in override_dict: # Yes. Make sure they match if ignore_zero_wind != to_bool(override_dict['force_null']): raise ValueError("Conflicting values for " "ignore_zero_wind (%s) and force_null (%s)" % (ignore_zero_wind, force_null)) else: # No explicit value for 'force_null'. Use 'ignore_zero_wind' in its place force_null = ignore_zero_wind # maxSolarRad-related options maxSolarRad_algo = option_dict['maxSolarRad'].get('algorithm', 'rs').lower() # atmospheric transmission coefficient [0.7-0.91] atc = to_float(option_dict['maxSolarRad'].get('atc', 0.8)) # atmospheric turbidity (2=clear, 4-5=smoggy) nfac = to_float(option_dict['maxSolarRad'].get('nfac', 2)) # ET-related options # height above ground at which wind is measured, in meters wind_height = to_float(weeutil.config.search_up(option_dict['ET'], 'wind_height', 2.0)) # window of time for evapotranspiration calculation, in seconds et_period = to_int(option_dict['ET'].get('et_period', 3600)) # heatindex-related options heatindex_algo = option_dict['heatindex'].get('algorithm', 'new').lower() self.wxxtypes = WXXTypes(altitude_vt, latitude_f, longitude_f, et_period, atc, nfac, wind_height, force_null, maxSolarRad_algo, heatindex_algo) # Add to the xtypes system weewx.xtypes.xtypes.append(self.wxxtypes)
[ "def", "__init__", "(", "self", ",", "engine", ",", "config_dict", ")", ":", "super", "(", "StdWXXTypes", ",", "self", ")", ".", "__init__", "(", "engine", ",", "config_dict", ")", "altitude_vt", "=", "engine", ".", "stn_info", ".", "altitude_vt", "latitud...
https://github.com/weewx/weewx/blob/cb594fce224560bd8696050fc5c7843c7839320e/bin/weewx/wxxtypes.py#L617-L691
thiagopena/djangoSIGE
e32186b27bfd8acf21b0fa400e699cb5c73e5433
djangosige/apps/base/custom_views.py
python
CustomUpdateView.post
(self, request, *args, **kwargs)
return self.form_invalid(form)
[]
def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = form_class(request.POST, instance=self.object) if form.is_valid(): self.object = form.save() return redirect(self.success_url) return self.form_invalid(form)
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "form_class", "=", "self", ".", "get_form_class", "(", ")", "form", "=", "form_class", ...
https://github.com/thiagopena/djangoSIGE/blob/e32186b27bfd8acf21b0fa400e699cb5c73e5433/djangosige/apps/base/custom_views.py#L68-L75
kennethreitz-archive/requests3
69eb662703b40db58fdc6c095d0fe130c56649bb
requests3/core/_http/exceptions.py
python
BadVersionError.__init__
(self, version)
[]
def __init__(self, version): message = "HTTP version {} is unsupported".format(version) super(BadVersionError, self).__init__(message)
[ "def", "__init__", "(", "self", ",", "version", ")", ":", "message", "=", "\"HTTP version {} is unsupported\"", ".", "format", "(", "version", ")", "super", "(", "BadVersionError", ",", "self", ")", ".", "__init__", "(", "message", ")" ]
https://github.com/kennethreitz-archive/requests3/blob/69eb662703b40db58fdc6c095d0fe130c56649bb/requests3/core/_http/exceptions.py#L192-L194
theislab/anndata
664e32b0aa6625fe593370d37174384c05abfd4e
anndata/_core/anndata.py
python
AnnData.__getitem__
(self, index: Index)
return AnnData(self, oidx=oidx, vidx=vidx, asview=True)
Returns a sliced view of the object.
Returns a sliced view of the object.
[ "Returns", "a", "sliced", "view", "of", "the", "object", "." ]
def __getitem__(self, index: Index) -> "AnnData": """Returns a sliced view of the object.""" oidx, vidx = self._normalize_indices(index) return AnnData(self, oidx=oidx, vidx=vidx, asview=True)
[ "def", "__getitem__", "(", "self", ",", "index", ":", "Index", ")", "->", "\"AnnData\"", ":", "oidx", ",", "vidx", "=", "self", ".", "_normalize_indices", "(", "index", ")", "return", "AnnData", "(", "self", ",", "oidx", "=", "oidx", ",", "vidx", "=", ...
https://github.com/theislab/anndata/blob/664e32b0aa6625fe593370d37174384c05abfd4e/anndata/_core/anndata.py#L1097-L1100
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
vdloc_t.reg1
(self, *args)
return _idaapi.vdloc_t_reg1(self, *args)
reg1(self) -> int
reg1(self) -> int
[ "reg1", "(", "self", ")", "-", ">", "int" ]
def reg1(self, *args): """ reg1(self) -> int """ return _idaapi.vdloc_t_reg1(self, *args)
[ "def", "reg1", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "vdloc_t_reg1", "(", "self", ",", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L35683-L35687
digidotcom/xbee-python
0757f4be0017530c205175fbee8f9f61be9614d1
digi/xbee/comm_interface.py
python
XBeeCommunicationInterface.close
(self)
Terminates the underlying hardware communication interface. Subclasses may throw specific exceptions to signal implementation specific hardware errors.
Terminates the underlying hardware communication interface.
[ "Terminates", "the", "underlying", "hardware", "communication", "interface", "." ]
def close(self): """ Terminates the underlying hardware communication interface. Subclasses may throw specific exceptions to signal implementation specific hardware errors. """
[ "def", "close", "(", "self", ")", ":" ]
https://github.com/digidotcom/xbee-python/blob/0757f4be0017530c205175fbee8f9f61be9614d1/digi/xbee/comm_interface.py#L35-L41
vanheeringen-lab/genomepy
4c10e69b6886cf52381caf6498395391834a675b
genomepy/functions.py
python
_provider_selection
(name, localname, genomes_dir, provider=None)
return _lazy_provider_selection(name, provider)
Return a provider object First tries to return a specified provider, Second tries to return the provider from the README Third tries to return the first provider which has the genome (Ensembl>UCSC>NCBI)
Return a provider object
[ "Return", "a", "provider", "object" ]
def _provider_selection(name, localname, genomes_dir, provider=None): """ Return a provider object First tries to return a specified provider, Second tries to return the provider from the README Third tries to return the first provider which has the genome (Ensembl>UCSC>NCBI) """ readme = os.path.join(genomes_dir, localname, "README.txt") if provider is None and os.path.exists(readme): m, _ = read_readme(readme) p = m["provider"].lower() if p in ["ensembl", "ucsc", "ncbi"]: provider = p return _lazy_provider_selection(name, provider)
[ "def", "_provider_selection", "(", "name", ",", "localname", ",", "genomes_dir", ",", "provider", "=", "None", ")", ":", "readme", "=", "os", ".", "path", ".", "join", "(", "genomes_dir", ",", "localname", ",", "\"README.txt\"", ")", "if", "provider", "is"...
https://github.com/vanheeringen-lab/genomepy/blob/4c10e69b6886cf52381caf6498395391834a675b/genomepy/functions.py#L338-L353
ronf/asyncssh
ee1714c598d8c2ea6f5484e465443f38b68714aa
asyncssh/kex.py
python
register_gss_kex_alg
(alg: bytes, handler: Type[Kex], hash_alg: HashType, args: Tuple, default: bool)
Register a GSSAPI key exchange algorithm
Register a GSSAPI key exchange algorithm
[ "Register", "a", "GSSAPI", "key", "exchange", "algorithm" ]
def register_gss_kex_alg(alg: bytes, handler: Type[Kex], hash_alg: HashType, args: Tuple, default: bool) -> None: """Register a GSSAPI key exchange algorithm""" _gss_kex_algs.append(alg) if default: _default_gss_kex_algs.append(alg) _gss_kex_handlers[alg] = (handler, hash_alg, args)
[ "def", "register_gss_kex_alg", "(", "alg", ":", "bytes", ",", "handler", ":", "Type", "[", "Kex", "]", ",", "hash_alg", ":", "HashType", ",", "args", ":", "Tuple", ",", "default", ":", "bool", ")", "->", "None", ":", "_gss_kex_algs", ".", "append", "("...
https://github.com/ronf/asyncssh/blob/ee1714c598d8c2ea6f5484e465443f38b68714aa/asyncssh/kex.py#L104-L113
joke2k/faker
0ebe46fc9b9793fe315cf0fce430258ce74df6f8
faker/providers/address/az_AZ/__init__.py
python
Provider.village
(self)
return self.random_element(self.villages)
:example 'Didivar'
:example 'Didivar'
[ ":", "example", "Didivar" ]
def village(self): """ :example 'Didivar' """ return self.random_element(self.villages)
[ "def", "village", "(", "self", ")", ":", "return", "self", ".", "random_element", "(", "self", ".", "villages", ")" ]
https://github.com/joke2k/faker/blob/0ebe46fc9b9793fe315cf0fce430258ce74df6f8/faker/providers/address/az_AZ/__init__.py#L641-L645
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/op2/tables/geom/ept.py
python
EPT._read_nsm1
(self, data: bytes, n: int)
return n
NSM1(3301, 33, 992) Defines the properties of a nonstructural mass. Word Name Type Description 1 SID I Set identification number 2 PROP CHAR4 Set of properties 3 TYPE CHAR4 Set of elements 4 ORIGIN I Entry origin 5 VALUE RS Nonstructural mass value 6 SPECOPT I Specification option SPECOPT=1 By IDs 7 ID I Word 7 repeats until -1 occurs SPECOPT=2 All 7 ALL(2) CHAR4 Words 7 and 8 repeat until -1 occurs SPECOPT=3 Thru range 7 ID I 8 THRU(2) CHAR4 10 ID I Words 7 through 10 repeat until -1 occurs SPECOPT=4 Thru range with by 7 ID I 8 THRU(2) CHAR4 10 ID I 11 BY(2) CHAR4 13 N I Words 7 through 13 repeat until -1 occurs data = (3, PCOMP, 0, 0.37, 2, ALL, -1, 4, ELEMENT, 2, 2.1, 1, 3301, -1)
NSM1(3301, 33, 992)
[ "NSM1", "(", "3301", "33", "992", ")" ]
def _read_nsm1(self, data: bytes, n: int) -> int: """ NSM1(3301, 33, 992) Defines the properties of a nonstructural mass. Word Name Type Description 1 SID I Set identification number 2 PROP CHAR4 Set of properties 3 TYPE CHAR4 Set of elements 4 ORIGIN I Entry origin 5 VALUE RS Nonstructural mass value 6 SPECOPT I Specification option SPECOPT=1 By IDs 7 ID I Word 7 repeats until -1 occurs SPECOPT=2 All 7 ALL(2) CHAR4 Words 7 and 8 repeat until -1 occurs SPECOPT=3 Thru range 7 ID I 8 THRU(2) CHAR4 10 ID I Words 7 through 10 repeat until -1 occurs SPECOPT=4 Thru range with by 7 ID I 8 THRU(2) CHAR4 10 ID I 11 BY(2) CHAR4 13 N I Words 7 through 13 repeat until -1 occurs data = (3, PCOMP, 0, 0.37, 2, ALL, -1, 4, ELEMENT, 2, 2.1, 1, 3301, -1) """ op2 = self.op2 #op2.show_data(data[n:], types='ifs') n0 = n #op2.show_data(data[n:]) ints = np.frombuffer(data[n:], op2.idtype8).copy() floats = np.frombuffer(data[n:], op2.fdtype8).copy() istart, iend = get_minus1_start_end(ints) ncards = 0 size = self.size for (i0, i1) in zip(istart, iend): assert ints[i1] == -1, ints[i1] # 1 SID I Set identification number sid = ints[i0] # 2 PROP CHAR4 Set of properties # 3 TYPE CHAR4 Set of elements # 4 ORIGIN I Entry origin # 5 VALUE RS Nonstructural mass value # 6 SPECOPT I Specification option nsm_type = data[n0+(i0+1)*size:n0+(i0+3)*size].decode('latin1').rstrip() zero_two = ints[i0+3] value = float(floats[i0+4]) spec_opt = ints[i0+5] assert zero_two in [0, 2], zero_two #nii = 6 #print(ints[i0+nii:i1]) #print(floats[i0+nii:i1]) #print(sid, nsm_type, value, spec_opt) iminus1 = i0 + np.where(ints[i0:i1] == -1)[0] #print('-1', iminus1) #print('-2', iminus2) istart2 = [i0 + 5] + list(iminus1[:-1] + 1) iend2 = iminus1 #print(istart2, iend2) if spec_opt == 1: # 7 ID I ids = ints[i0+6:i1] elif spec_opt == 2: word = data[n0+(i0+6)*size:n0+i1*size] ids = word elif spec_opt == 3: # thru # datai = (249311, 'THRU ', 250189) #datai = data[n0+(i0+6)*size:n0+i1*size] ids = ints[i0+6:i1] istart = ids[0] iend = ids[-1] ids = list(range(istart, iend+1)) else: raise NotImplementedError(spec_opt) #print(sid, nsm_type, zero_two, value, ids) #if nsm_type == 'ELEM': #nsm_type = 'ELEMENT' #for pid_eid in pid_eids: #nsml = self.add_nsml1(sid, nsm_type, pid_eids, [value]) nsm1 = op2.add_nsm1(sid, nsm_type, value, ids) #print(nsm1) str(nsm1) n += (i1 - i0 + 1) * size ncards += 1 op2.card_count['NSM1'] = ncards return n
[ "def", "_read_nsm1", "(", "self", ",", "data", ":", "bytes", ",", "n", ":", "int", ")", "->", "int", ":", "op2", "=", "self", ".", "op2", "#op2.show_data(data[n:], types='ifs')", "n0", "=", "n", "#op2.show_data(data[n:])", "ints", "=", "np", ".", "frombuff...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/op2/tables/geom/ept.py#L456-L554
cyberdelia/metrology
a029ec45228f59dfa82d8068698a3fa60ea8f7c2
metrology/instruments/counter.py
python
Counter.decrement
(self, value=1)
Decrement the counter. By default it will decrement by 1. :param value: value to decrement the counter.
Decrement the counter. By default it will decrement by 1.
[ "Decrement", "the", "counter", ".", "By", "default", "it", "will", "decrement", "by", "1", "." ]
def decrement(self, value=1): """Decrement the counter. By default it will decrement by 1. :param value: value to decrement the counter. """ self._count -= value
[ "def", "decrement", "(", "self", ",", "value", "=", "1", ")", ":", "self", ".", "_count", "-=", "value" ]
https://github.com/cyberdelia/metrology/blob/a029ec45228f59dfa82d8068698a3fa60ea8f7c2/metrology/instruments/counter.py#L24-L29
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/dna/operations/crossovers.py
python
Pl5_recognizer._C_strand_direction_well_defined
(self)
return self.ordered_bases is not None
[compute method for self.strand_direction_well_defined] ###doc
[compute method for self.strand_direction_well_defined] ###doc
[ "[", "compute", "method", "for", "self", ".", "strand_direction_well_defined", "]", "###doc" ]
def _C_strand_direction_well_defined(self): """ [compute method for self.strand_direction_well_defined] ###doc """ return self.ordered_bases is not None
[ "def", "_C_strand_direction_well_defined", "(", "self", ")", ":", "return", "self", ".", "ordered_bases", "is", "not", "None" ]
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/dna/operations/crossovers.py#L401-L406
charlesq34/frustum-pointnets
2ffdd345e1fce4775ecb508d207e0ad465bcca80
kitti/kitti_util.py
python
Calibration.project_velo_to_image
(self, pts_3d_velo)
return self.project_rect_to_image(pts_3d_rect)
Input: nx3 points in velodyne coord. Output: nx2 points in image2 coord.
Input: nx3 points in velodyne coord. Output: nx2 points in image2 coord.
[ "Input", ":", "nx3", "points", "in", "velodyne", "coord", ".", "Output", ":", "nx2", "points", "in", "image2", "coord", "." ]
def project_velo_to_image(self, pts_3d_velo): ''' Input: nx3 points in velodyne coord. Output: nx2 points in image2 coord. ''' pts_3d_rect = self.project_velo_to_rect(pts_3d_velo) return self.project_rect_to_image(pts_3d_rect)
[ "def", "project_velo_to_image", "(", "self", ",", "pts_3d_velo", ")", ":", "pts_3d_rect", "=", "self", ".", "project_velo_to_rect", "(", "pts_3d_velo", ")", "return", "self", ".", "project_rect_to_image", "(", "pts_3d_rect", ")" ]
https://github.com/charlesq34/frustum-pointnets/blob/2ffdd345e1fce4775ecb508d207e0ad465bcca80/kitti/kitti_util.py#L190-L195
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Doc/jinja2/compiler.py
python
CodeGenerator.macro_def
(self, node, frame)
Dump the macro definition for the def created by macro_body.
Dump the macro definition for the def created by macro_body.
[ "Dump", "the", "macro", "definition", "for", "the", "def", "created", "by", "macro_body", "." ]
def macro_def(self, node, frame): """Dump the macro definition for the def created by macro_body.""" arg_tuple = ', '.join(repr(x.name) for x in node.args) name = getattr(node, 'name', None) if len(node.args) == 1: arg_tuple += ',' self.write('Macro(environment, macro, %r, (%s), (' % (name, arg_tuple)) for arg in node.defaults: self.visit(arg, frame) self.write(', ') self.write('), %r, %r, %r)' % ( bool(frame.accesses_kwargs), bool(frame.accesses_varargs), bool(frame.accesses_caller) ))
[ "def", "macro_def", "(", "self", ",", "node", ",", "frame", ")", ":", "arg_tuple", "=", "', '", ".", "join", "(", "repr", "(", "x", ".", "name", ")", "for", "x", "in", "node", ".", "args", ")", "name", "=", "getattr", "(", "node", ",", "'name'", ...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Doc/jinja2/compiler.py#L668-L683
xtiankisutsa/MARA_Framework
ac4ac88bfd38f33ae8780a606ed09ab97177c562
tools/AndroBugs/tools/modified/androguard/core/bytecode.py
python
method2jpg
(output, mx, raw=False)
Export method to a jpg file format :param output: output filename :type output: string :param mx: specify the MethodAnalysis object :type mx: :class:`MethodAnalysis` object :param raw: use directly a dot raw buffer (optional) :type raw: string
Export method to a jpg file format
[ "Export", "method", "to", "a", "jpg", "file", "format" ]
def method2jpg(output, mx, raw=False): """ Export method to a jpg file format :param output: output filename :type output: string :param mx: specify the MethodAnalysis object :type mx: :class:`MethodAnalysis` object :param raw: use directly a dot raw buffer (optional) :type raw: string """ buff = raw if raw == False: buff = method2dot(mx) method2format(output, "jpg", mx, buff)
[ "def", "method2jpg", "(", "output", ",", "mx", ",", "raw", "=", "False", ")", ":", "buff", "=", "raw", "if", "raw", "==", "False", ":", "buff", "=", "method2dot", "(", "mx", ")", "method2format", "(", "output", ",", "\"jpg\"", ",", "mx", ",", "buff...
https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/AndroBugs/tools/modified/androguard/core/bytecode.py#L381-L396
kadalu/kadalu
5d91d92830553b47d3729adc3c7f69ce6fd45e2d
kadalulib.py
python
ProcState.restart
(self)
Restart a Process
Restart a Process
[ "Restart", "a", "Process" ]
def restart(self): """Restart a Process""" self.stop() self.start()
[ "def", "restart", "(", "self", ")", ":", "self", ".", "stop", "(", ")", "self", ".", "start", "(", ")" ]
https://github.com/kadalu/kadalu/blob/5d91d92830553b47d3729adc3c7f69ce6fd45e2d/kadalulib.py#L345-L348
pyqteval/evlal_win
ce7fc77ac5cdf864cd6aa9b04b5329501f8f4c92
pyinstaller-2.0/PyInstaller/compat.py
python
exec_python_all
(*args, **kwargs)
return exec_command_all(*cmdargs, **kwargs)
Wrap running python script in a subprocess. Return tuple (exit_code, stdout, stderr) of the invoked command.
Wrap running python script in a subprocess.
[ "Wrap", "running", "python", "script", "in", "a", "subprocess", "." ]
def exec_python_all(*args, **kwargs): """ Wrap running python script in a subprocess. Return tuple (exit_code, stdout, stderr) of the invoked command. """ cmdargs, kwargs = __wrap_python(args, kwargs) return exec_command_all(*cmdargs, **kwargs)
[ "def", "exec_python_all", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cmdargs", ",", "kwargs", "=", "__wrap_python", "(", "args", ",", "kwargs", ")", "return", "exec_command_all", "(", "*", "cmdargs", ",", "*", "*", "kwargs", ")" ]
https://github.com/pyqteval/evlal_win/blob/ce7fc77ac5cdf864cd6aa9b04b5329501f8f4c92/pyinstaller-2.0/PyInstaller/compat.py#L309-L316
beetbox/beets
2fea53c34dd505ba391cb345424e0613901c8025
beets/plugins.py
python
BeetsPlugin.add_media_field
(self, name, descriptor)
Add a field that is synchronized between media files and items. When a media field is added ``item.write()`` will set the name property of the item's MediaFile to ``item[name]`` and save the changes. Similarly ``item.read()`` will set ``item[name]`` to the value of the name property of the media file. ``descriptor`` must be an instance of ``mediafile.MediaField``.
Add a field that is synchronized between media files and items.
[ "Add", "a", "field", "that", "is", "synchronized", "between", "media", "files", "and", "items", "." ]
def add_media_field(self, name, descriptor): """Add a field that is synchronized between media files and items. When a media field is added ``item.write()`` will set the name property of the item's MediaFile to ``item[name]`` and save the changes. Similarly ``item.read()`` will set ``item[name]`` to the value of the name property of the media file. ``descriptor`` must be an instance of ``mediafile.MediaField``. """ # Defer import to prevent circular dependency from beets import library mediafile.MediaFile.add_field(name, descriptor) library.Item._media_fields.add(name)
[ "def", "add_media_field", "(", "self", ",", "name", ",", "descriptor", ")", ":", "# Defer import to prevent circular dependency", "from", "beets", "import", "library", "mediafile", ".", "MediaFile", ".", "add_field", "(", "name", ",", "descriptor", ")", "library", ...
https://github.com/beetbox/beets/blob/2fea53c34dd505ba391cb345424e0613901c8025/beets/plugins.py#L192-L205
brython-dev/brython
9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3
www/src/Lib/importlib/_bootstrap_external.py
python
decode_source
(source_bytes)
return newline_decoder.decode(source_bytes.decode(encoding[0]))
Decode bytes representing source code and return the string. Universal newline support is used in the decoding.
Decode bytes representing source code and return the string.
[ "Decode", "bytes", "representing", "source", "code", "and", "return", "the", "string", "." ]
def decode_source(source_bytes): """Decode bytes representing source code and return the string. Universal newline support is used in the decoding. """ import tokenize # To avoid bootstrap issues. source_bytes_readline = _io.BytesIO(source_bytes).readline encoding = tokenize.detect_encoding(source_bytes_readline) newline_decoder = _io.IncrementalNewlineDecoder(None, True) return newline_decoder.decode(source_bytes.decode(encoding[0]))
[ "def", "decode_source", "(", "source_bytes", ")", ":", "import", "tokenize", "# To avoid bootstrap issues.", "source_bytes_readline", "=", "_io", ".", "BytesIO", "(", "source_bytes", ")", ".", "readline", "encoding", "=", "tokenize", ".", "detect_encoding", "(", "so...
https://github.com/brython-dev/brython/blob/9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3/www/src/Lib/importlib/_bootstrap_external.py#L635-L644
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v2beta2_horizontal_pod_autoscaler_status.py
python
V2beta2HorizontalPodAutoscalerStatus.__init__
(self, conditions=None, current_metrics=None, current_replicas=None, desired_replicas=None, last_scale_time=None, observed_generation=None, local_vars_configuration=None)
V2beta2HorizontalPodAutoscalerStatus - a model defined in OpenAPI
V2beta2HorizontalPodAutoscalerStatus - a model defined in OpenAPI
[ "V2beta2HorizontalPodAutoscalerStatus", "-", "a", "model", "defined", "in", "OpenAPI" ]
def __init__(self, conditions=None, current_metrics=None, current_replicas=None, desired_replicas=None, last_scale_time=None, observed_generation=None, local_vars_configuration=None): # noqa: E501 """V2beta2HorizontalPodAutoscalerStatus - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._conditions = None self._current_metrics = None self._current_replicas = None self._desired_replicas = None self._last_scale_time = None self._observed_generation = None self.discriminator = None self.conditions = conditions if current_metrics is not None: self.current_metrics = current_metrics self.current_replicas = current_replicas self.desired_replicas = desired_replicas if last_scale_time is not None: self.last_scale_time = last_scale_time if observed_generation is not None: self.observed_generation = observed_generation
[ "def", "__init__", "(", "self", ",", "conditions", "=", "None", ",", "current_metrics", "=", "None", ",", "current_replicas", "=", "None", ",", "desired_replicas", "=", "None", ",", "last_scale_time", "=", "None", ",", "observed_generation", "=", "None", ",", ...
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v2beta2_horizontal_pod_autoscaler_status.py#L53-L75
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/utils/dummy_flax_objects.py
python
FlaxGPT2PreTrainedModel.from_pretrained
(cls, *args, **kwargs)
[]
def from_pretrained(cls, *args, **kwargs): requires_backends(cls, ["flax"])
[ "def", "from_pretrained", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "requires_backends", "(", "cls", ",", "[", "\"flax\"", "]", ")" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_flax_objects.py#L1000-L1001
ReactionMechanismGenerator/RMG-Py
2b7baf51febf27157def58fb3f6cee03fb6a684c
rmgpy/__init__.py
python
Settings.report
(self)
return '\n'.join(lines)
Returns a string saying what is set and where things came from, suitable for logging
Returns a string saying what is set and where things came from, suitable for logging
[ "Returns", "a", "string", "saying", "what", "is", "set", "and", "where", "things", "came", "from", "suitable", "for", "logging" ]
def report(self): """ Returns a string saying what is set and where things came from, suitable for logging """ lines = ['Global RMG Settings:'] for key in self.keys(): lines.append(" {0:20s} = {1:20s} ({2})".format(key, self[key], self.sources[key])) return '\n'.join(lines)
[ "def", "report", "(", "self", ")", ":", "lines", "=", "[", "'Global RMG Settings:'", "]", "for", "key", "in", "self", ".", "keys", "(", ")", ":", "lines", ".", "append", "(", "\" {0:20s} = {1:20s} ({2})\"", ".", "format", "(", "key", ",", "self", "[", ...
https://github.com/ReactionMechanismGenerator/RMG-Py/blob/2b7baf51febf27157def58fb3f6cee03fb6a684c/rmgpy/__init__.py#L73-L80
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
tokumx/datadog_checks/tokumx/vendor/pymongo/server_selectors.py
python
any_server_selector
(selection)
return selection
[]
def any_server_selector(selection): return selection
[ "def", "any_server_selector", "(", "selection", ")", ":", "return", "selection" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/tokumx/datadog_checks/tokumx/vendor/pymongo/server_selectors.py#L81-L82
BMW-InnovationLab/BMW-TensorFlow-Training-GUI
4f10d1f00f9ac312ca833e5b28fd0f8952cfee17
training_api/research/object_detection/utils/vrd_evaluation.py
python
_VRDDetectionEvaluation.clear_detections
(self)
Clears detections.
Clears detections.
[ "Clears", "detections", "." ]
def clear_detections(self): """Clears detections.""" self._detection_keys = set() self._scores = [] self._relation_field_values = [] self._tp_fp_labels = [] self._average_precisions = {} self._precisions = [] self._recalls = []
[ "def", "clear_detections", "(", "self", ")", ":", "self", ".", "_detection_keys", "=", "set", "(", ")", "self", ".", "_scores", "=", "[", "]", "self", ".", "_relation_field_values", "=", "[", "]", "self", ".", "_tp_fp_labels", "=", "[", "]", "self", "....
https://github.com/BMW-InnovationLab/BMW-TensorFlow-Training-GUI/blob/4f10d1f00f9ac312ca833e5b28fd0f8952cfee17/training_api/research/object_detection/utils/vrd_evaluation.py#L437-L445
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/group/binary_sensor.py
python
BinarySensorGroup.async_added_to_hass
(self)
Register callbacks.
Register callbacks.
[ "Register", "callbacks", "." ]
async def async_added_to_hass(self) -> None: """Register callbacks.""" @callback def async_state_changed_listener(event: Event) -> None: """Handle child updates.""" self.async_set_context(event.context) self.async_defer_or_update_ha_state() self.async_on_remove( async_track_state_change_event( self.hass, self._entity_ids, async_state_changed_listener ) ) await super().async_added_to_hass()
[ "async", "def", "async_added_to_hass", "(", "self", ")", "->", "None", ":", "@", "callback", "def", "async_state_changed_listener", "(", "event", ":", "Event", ")", "->", "None", ":", "\"\"\"Handle child updates.\"\"\"", "self", ".", "async_set_context", "(", "eve...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/group/binary_sensor.py#L90-L105
Cadene/tensorflow-model-zoo.torch
990b10ffc22d4c8eacb2a502f20415b4f70c74c2
models/research/object_detection/data_decoders/tf_example_decoder.py
python
TfExampleDecoder.__init__
(self, load_instance_masks=False, label_map_proto_file=None, use_display_name=False)
Constructor sets keys_to_features and items_to_handlers. Args: load_instance_masks: whether or not to load and handle instance masks. label_map_proto_file: a file path to a object_detection.protos.StringIntLabelMap proto. If provided, then the mapped IDs of 'image/object/class/text' will take precedence over the existing 'image/object/class/label' ID. Also, if provided, it is assumed that 'image/object/class/text' will be in the data. use_display_name: whether or not to use the `display_name` for label mapping (instead of `name`). Only used if label_map_proto_file is provided.
Constructor sets keys_to_features and items_to_handlers.
[ "Constructor", "sets", "keys_to_features", "and", "items_to_handlers", "." ]
def __init__(self, load_instance_masks=False, label_map_proto_file=None, use_display_name=False): """Constructor sets keys_to_features and items_to_handlers. Args: load_instance_masks: whether or not to load and handle instance masks. label_map_proto_file: a file path to a object_detection.protos.StringIntLabelMap proto. If provided, then the mapped IDs of 'image/object/class/text' will take precedence over the existing 'image/object/class/label' ID. Also, if provided, it is assumed that 'image/object/class/text' will be in the data. use_display_name: whether or not to use the `display_name` for label mapping (instead of `name`). Only used if label_map_proto_file is provided. """ self.keys_to_features = { 'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'), 'image/filename': tf.FixedLenFeature((), tf.string, default_value=''), 'image/key/sha256': tf.FixedLenFeature((), tf.string, default_value=''), 'image/source_id': tf.FixedLenFeature((), tf.string, default_value=''), 'image/height': tf.FixedLenFeature((), tf.int64, 1), 'image/width': tf.FixedLenFeature((), tf.int64, 1), # Object boxes and classes. 'image/object/bbox/xmin': tf.VarLenFeature(tf.float32), 'image/object/bbox/xmax': tf.VarLenFeature(tf.float32), 'image/object/bbox/ymin': tf.VarLenFeature(tf.float32), 'image/object/bbox/ymax': tf.VarLenFeature(tf.float32), 'image/object/class/label': tf.VarLenFeature(tf.int64), 'image/object/class/text': tf.VarLenFeature(tf.string), 'image/object/area': tf.VarLenFeature(tf.float32), 'image/object/is_crowd': tf.VarLenFeature(tf.int64), 'image/object/difficult': tf.VarLenFeature(tf.int64), 'image/object/group_of': tf.VarLenFeature(tf.int64), } self.items_to_handlers = { fields.InputDataFields.image: slim_example_decoder.Image( image_key='image/encoded', format_key='image/format', channels=3), fields.InputDataFields.source_id: ( slim_example_decoder.Tensor('image/source_id')), fields.InputDataFields.key: ( slim_example_decoder.Tensor('image/key/sha256')), fields.InputDataFields.filename: ( slim_example_decoder.Tensor('image/filename')), # Object boxes and classes. fields.InputDataFields.groundtruth_boxes: ( slim_example_decoder.BoundingBox( ['ymin', 'xmin', 'ymax', 'xmax'], 'image/object/bbox/')), fields.InputDataFields.groundtruth_area: slim_example_decoder.Tensor( 'image/object/area'), fields.InputDataFields.groundtruth_is_crowd: ( slim_example_decoder.Tensor('image/object/is_crowd')), fields.InputDataFields.groundtruth_difficult: ( slim_example_decoder.Tensor('image/object/difficult')), fields.InputDataFields.groundtruth_group_of: ( slim_example_decoder.Tensor('image/object/group_of')) } if load_instance_masks: self.keys_to_features['image/object/mask'] = tf.VarLenFeature(tf.float32) self.items_to_handlers[ fields.InputDataFields.groundtruth_instance_masks] = ( slim_example_decoder.ItemHandlerCallback( ['image/object/mask', 'image/height', 'image/width'], self._reshape_instance_masks)) # TODO: Add label_handler that decodes from 'image/object/class/text' # primarily after the recent tf.contrib.slim changes make into a release # supported by cloudml. label_handler = slim_example_decoder.Tensor('image/object/class/label') self.items_to_handlers[ fields.InputDataFields.groundtruth_classes] = label_handler
[ "def", "__init__", "(", "self", ",", "load_instance_masks", "=", "False", ",", "label_map_proto_file", "=", "None", ",", "use_display_name", "=", "False", ")", ":", "self", ".", "keys_to_features", "=", "{", "'image/encoded'", ":", "tf", ".", "FixedLenFeature", ...
https://github.com/Cadene/tensorflow-model-zoo.torch/blob/990b10ffc22d4c8eacb2a502f20415b4f70c74c2/models/research/object_detection/data_decoders/tf_example_decoder.py#L33-L121
python-control/python-control
df6b35212f8f657469627c227c893a175a6902cc
control/ctrlutil.py
python
unwrap
(angle, period=2*math.pi)
return angle
Unwrap a phase angle to give a continuous curve Parameters ---------- angle : array_like Array of angles to be unwrapped period : float, optional Period (defaults to `2*pi`) Returns ------- angle_out : array_like Output array, with jumps of period/2 eliminated Examples -------- >>> import numpy as np >>> theta = [5.74, 5.97, 6.19, 0.13, 0.35, 0.57] >>> unwrap(theta, period=2 * np.pi) [5.74, 5.97, 6.19, 6.413185307179586, 6.633185307179586, 6.8531853071795865]
Unwrap a phase angle to give a continuous curve
[ "Unwrap", "a", "phase", "angle", "to", "give", "a", "continuous", "curve" ]
def unwrap(angle, period=2*math.pi): """Unwrap a phase angle to give a continuous curve Parameters ---------- angle : array_like Array of angles to be unwrapped period : float, optional Period (defaults to `2*pi`) Returns ------- angle_out : array_like Output array, with jumps of period/2 eliminated Examples -------- >>> import numpy as np >>> theta = [5.74, 5.97, 6.19, 0.13, 0.35, 0.57] >>> unwrap(theta, period=2 * np.pi) [5.74, 5.97, 6.19, 6.413185307179586, 6.633185307179586, 6.8531853071795865] """ dangle = np.diff(angle) dangle_desired = (dangle + period/2.) % period - period/2. correction = np.cumsum(dangle_desired - dangle) angle[1:] += correction return angle
[ "def", "unwrap", "(", "angle", ",", "period", "=", "2", "*", "math", ".", "pi", ")", ":", "dangle", "=", "np", ".", "diff", "(", "angle", ")", "dangle_desired", "=", "(", "dangle", "+", "period", "/", "2.", ")", "%", "period", "-", "period", "/",...
https://github.com/python-control/python-control/blob/df6b35212f8f657469627c227c893a175a6902cc/control/ctrlutil.py#L51-L78
zacharyvoase/urlobject
5699ad545648fb976fef8905f3defbcba7cf04ba
urlobject/urlobject.py
python
URLObject.with_username
(self, username)
return self.with_netloc(self.netloc.with_username(username))
Add or replace this URL's :attr:`.username`. >>> print(URLObject("http://user@www.google.com").with_username("user2")) http://user2@www.google.com
Add or replace this URL's :attr:`.username`.
[ "Add", "or", "replace", "this", "URL", "s", ":", "attr", ":", ".", "username", "." ]
def with_username(self, username): """ Add or replace this URL's :attr:`.username`. >>> print(URLObject("http://user@www.google.com").with_username("user2")) http://user2@www.google.com """ return self.with_netloc(self.netloc.with_username(username))
[ "def", "with_username", "(", "self", ",", "username", ")", ":", "return", "self", ".", "with_netloc", "(", "self", ".", "netloc", ".", "with_username", "(", "username", ")", ")" ]
https://github.com/zacharyvoase/urlobject/blob/5699ad545648fb976fef8905f3defbcba7cf04ba/urlobject/urlobject.py#L129-L136
john-kurkowski/tldextract
bdaa6f309c62465daa50a7759c9508f4a9472279
tldextract/suffix_list.py
python
extract_tlds_from_suffix_list
(suffix_list_text)
return public_tlds, private_tlds
Parse the raw suffix list text for its different designations of suffixes.
Parse the raw suffix list text for its different designations of suffixes.
[ "Parse", "the", "raw", "suffix", "list", "text", "for", "its", "different", "designations", "of", "suffixes", "." ]
def extract_tlds_from_suffix_list(suffix_list_text): """Parse the raw suffix list text for its different designations of suffixes.""" public_text, _, private_text = suffix_list_text.partition( PUBLIC_PRIVATE_SUFFIX_SEPARATOR ) public_tlds = [m.group("suffix") for m in PUBLIC_SUFFIX_RE.finditer(public_text)] private_tlds = [m.group("suffix") for m in PUBLIC_SUFFIX_RE.finditer(private_text)] return public_tlds, private_tlds
[ "def", "extract_tlds_from_suffix_list", "(", "suffix_list_text", ")", ":", "public_text", ",", "_", ",", "private_text", "=", "suffix_list_text", ".", "partition", "(", "PUBLIC_PRIVATE_SUFFIX_SEPARATOR", ")", "public_tlds", "=", "[", "m", ".", "group", "(", "\"suffi...
https://github.com/john-kurkowski/tldextract/blob/bdaa6f309c62465daa50a7759c9508f4a9472279/tldextract/suffix_list.py#L41-L50
ialbert/biostar-central
2dc7bd30691a50b2da9c2833ba354056bc686afa
biostar/forum/util.py
python
datetime_to_iso
(date)
return date.isoformat()
Converts a datetime to the ISO8601 format, like: 2014-05-20T06:11:41.733900. Parameters: date -- a `datetime` instance.
Converts a datetime to the ISO8601 format, like: 2014-05-20T06:11:41.733900.
[ "Converts", "a", "datetime", "to", "the", "ISO8601", "format", "like", ":", "2014", "-", "05", "-", "20T06", ":", "11", ":", "41", ".", "733900", "." ]
def datetime_to_iso(date): """ Converts a datetime to the ISO8601 format, like: 2014-05-20T06:11:41.733900. Parameters: date -- a `datetime` instance. """ if not isinstance(date, datetime): date = datetime.combine(date, datetime.min.time()) return date.isoformat()
[ "def", "datetime_to_iso", "(", "date", ")", ":", "if", "not", "isinstance", "(", "date", ",", "datetime", ")", ":", "date", "=", "datetime", ".", "combine", "(", "date", ",", "datetime", ".", "min", ".", "time", "(", ")", ")", "return", "date", ".", ...
https://github.com/ialbert/biostar-central/blob/2dc7bd30691a50b2da9c2833ba354056bc686afa/biostar/forum/util.py#L40-L49
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/core/grr_response_core/lib/utils.py
python
ShellQuote
(value)
return pipes.quote(SmartUnicode(value))
Escapes the string for the safe use inside shell command line.
Escapes the string for the safe use inside shell command line.
[ "Escapes", "the", "string", "for", "the", "safe", "use", "inside", "shell", "command", "line", "." ]
def ShellQuote(value): """Escapes the string for the safe use inside shell command line.""" # TODO(user): replace pipes.quote with shlex.quote when time comes. return pipes.quote(SmartUnicode(value))
[ "def", "ShellQuote", "(", "value", ")", ":", "# TODO(user): replace pipes.quote with shlex.quote when time comes.", "return", "pipes", ".", "quote", "(", "SmartUnicode", "(", "value", ")", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/core/grr_response_core/lib/utils.py#L614-L617
opengapps/apkcrawler
e33ab5d1f37c54139ebf9fa93214adbe037bc679
googleplayapi/googleplay.py
python
GooglePlayAPI.details
(self, packageName)
return RequestResult(status_code, None)
Get app details from a package name. packageName is the app unique ID (usually starting with 'com.').
Get app details from a package name. packageName is the app unique ID (usually starting with 'com.').
[ "Get", "app", "details", "from", "a", "package", "name", ".", "packageName", "is", "the", "app", "unique", "ID", "(", "usually", "starting", "with", "com", ".", ")", "." ]
def details(self, packageName): """Get app details from a package name. packageName is the app unique ID (usually starting with 'com.').""" path = "details?doc=%s" % requests.utils.quote(packageName) (status_code, message) = self.executeRequestApi2(path) if status_code == http.client.OK: return RequestResult(status_code, message.payload.detailsResponse) return RequestResult(status_code, None)
[ "def", "details", "(", "self", ",", "packageName", ")", ":", "path", "=", "\"details?doc=%s\"", "%", "requests", ".", "utils", ".", "quote", "(", "packageName", ")", "(", "status_code", ",", "message", ")", "=", "self", ".", "executeRequestApi2", "(", "pat...
https://github.com/opengapps/apkcrawler/blob/e33ab5d1f37c54139ebf9fa93214adbe037bc679/googleplayapi/googleplay.py#L304-L311
oaubert/python-vlc
908ffdbd0844dc1849728c456e147788798c99da
generated/dev/vlc.py
python
Instance.media_new_fd
(self, fd)
return libvlc_media_new_fd(self, fd)
Create a media for an already open file descriptor. The file descriptor shall be open for reading (or reading and writing). Regular file descriptors, pipe read descriptors and character device descriptors (including TTYs) are supported on all platforms. Block device descriptors are supported where available. Directory descriptors are supported on systems that provide fdopendir(). Sockets are supported on all platforms where they are file descriptors, i.e. all except Windows. @note: This library will B{not} automatically close the file descriptor under any circumstance. Nevertheless, a file descriptor can usually only be rendered once in a media player. To render it a second time, the file descriptor should probably be rewound to the beginning with lseek(). See L{media_release}. @param fd: open file descriptor. @return: the newly created media or None on error. @version: LibVLC 1.1.5 and later.
Create a media for an already open file descriptor. The file descriptor shall be open for reading (or reading and writing). Regular file descriptors, pipe read descriptors and character device descriptors (including TTYs) are supported on all platforms. Block device descriptors are supported where available. Directory descriptors are supported on systems that provide fdopendir(). Sockets are supported on all platforms where they are file descriptors, i.e. all except Windows.
[ "Create", "a", "media", "for", "an", "already", "open", "file", "descriptor", ".", "The", "file", "descriptor", "shall", "be", "open", "for", "reading", "(", "or", "reading", "and", "writing", ")", ".", "Regular", "file", "descriptors", "pipe", "read", "de...
def media_new_fd(self, fd): '''Create a media for an already open file descriptor. The file descriptor shall be open for reading (or reading and writing). Regular file descriptors, pipe read descriptors and character device descriptors (including TTYs) are supported on all platforms. Block device descriptors are supported where available. Directory descriptors are supported on systems that provide fdopendir(). Sockets are supported on all platforms where they are file descriptors, i.e. all except Windows. @note: This library will B{not} automatically close the file descriptor under any circumstance. Nevertheless, a file descriptor can usually only be rendered once in a media player. To render it a second time, the file descriptor should probably be rewound to the beginning with lseek(). See L{media_release}. @param fd: open file descriptor. @return: the newly created media or None on error. @version: LibVLC 1.1.5 and later. ''' return libvlc_media_new_fd(self, fd)
[ "def", "media_new_fd", "(", "self", ",", "fd", ")", ":", "return", "libvlc_media_new_fd", "(", "self", ",", "fd", ")" ]
https://github.com/oaubert/python-vlc/blob/908ffdbd0844dc1849728c456e147788798c99da/generated/dev/vlc.py#L2301-L2319
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/helpdesk/management/commands/create_escalation_exclusions.py
python
usage
()
[]
def usage(): print("Options:") print(" --days, -d: Days of week (monday, tuesday, etc)") print(" --occurrences, -o: Occurrences: How many weeks ahead to exclude this day") print(" --queues, -q: Queues to include (default: all). Use queue slugs") print(" --verbose, -v: Display a list of dates excluded")
[ "def", "usage", "(", ")", ":", "print", "(", "\"Options:\"", ")", "print", "(", "\" --days, -d: Days of week (monday, tuesday, etc)\"", ")", "print", "(", "\" --occurrences, -o: Occurrences: How many weeks ahead to exclude this day\"", ")", "print", "(", "\" --queues, -q: Queue...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/helpdesk/management/commands/create_escalation_exclusions.py#L105-L110
hamcrest/PyHamcrest
11aafabd688af2db23e8614f89da3015fd39f611
src/hamcrest/core/description.py
python
Description.append_text
(self, text: str)
Appends some plain text to the description. :returns: ``self``, for chaining
Appends some plain text to the description.
[ "Appends", "some", "plain", "text", "to", "the", "description", "." ]
def append_text(self, text: str) -> "Description": """Appends some plain text to the description. :returns: ``self``, for chaining """ raise NotImplementedError("append_text")
[ "def", "append_text", "(", "self", ",", "text", ":", "str", ")", "->", "\"Description\"", ":", "raise", "NotImplementedError", "(", "\"append_text\"", ")" ]
https://github.com/hamcrest/PyHamcrest/blob/11aafabd688af2db23e8614f89da3015fd39f611/src/hamcrest/core/description.py#L16-L22
ProgVal/Limnoria
181e34baf90a8cabc281e8349da6e36e1e558608
plugins/PluginDownloader/plugin.py
python
PluginDownloader.info
(self, irc, msg, args, repository, plugin)
<repository> <plugin> Displays informations on the <plugin> in the <repository>.
<repository> <plugin>
[ "<repository", ">", "<plugin", ">" ]
def info(self, irc, msg, args, repository, plugin): """<repository> <plugin> Displays informations on the <plugin> in the <repository>.""" global repositories if repository not in repositories: irc.error(_( 'This repository does not exist or is not known by ' 'this bot.' )) elif plugin not in repositories[repository].getPluginList(): irc.error(_('This plugin does not exist in this repository.')) else: info = repositories[repository].getInfo(plugin) if info is None: irc.error(_('No README found for this plugin.')) else: if info.startswith('Insert a description of your plugin here'): irc.error(_('This plugin has no description.')) else: info = info.split('\n\n')[0] irc.reply(info.replace('\n', ' '))
[ "def", "info", "(", "self", ",", "irc", ",", "msg", ",", "args", ",", "repository", ",", "plugin", ")", ":", "global", "repositories", "if", "repository", "not", "in", "repositories", ":", "irc", ".", "error", "(", "_", "(", "'This repository does not exis...
https://github.com/ProgVal/Limnoria/blob/181e34baf90a8cabc281e8349da6e36e1e558608/plugins/PluginDownloader/plugin.py#L419-L440
tensorflow/tensor2tensor
2a33b152d7835af66a6d20afe7961751047e28dd
tensor2tensor/utils/cloud_mlengine.py
python
flags_as_args
()
return args
Convert FLAGS to list of args suitable for passing on cmd line.
Convert FLAGS to list of args suitable for passing on cmd line.
[ "Convert", "FLAGS", "to", "list", "of", "args", "suitable", "for", "passing", "on", "cmd", "line", "." ]
def flags_as_args(): """Convert FLAGS to list of args suitable for passing on cmd line.""" if hasattr(FLAGS, "flag_values_dict"): args_dict = FLAGS.flag_values_dict() else: args_dict = dict(FLAGS.__dict__["__flags"]) del args_dict["cloud_mlengine"] # Configured later del args_dict["t2t_usr_dir"] args_dict.pop("h", None) args_dict.pop("helpfull", None) args_dict.pop("helpshort", None) args_dict.pop("help", None) args = [] for name, val in args_dict.items(): if val is None: continue if name.startswith("autotune"): continue args.extend(["--%s=%s" % (name, str(val))]) return args
[ "def", "flags_as_args", "(", ")", ":", "if", "hasattr", "(", "FLAGS", ",", "\"flag_values_dict\"", ")", ":", "args_dict", "=", "FLAGS", ".", "flag_values_dict", "(", ")", "else", ":", "args_dict", "=", "dict", "(", "FLAGS", ".", "__dict__", "[", "\"__flags...
https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/utils/cloud_mlengine.py#L93-L113
patrickdessalle/periscope
74537da58c3f930ef61cb04d3f8f964aedde88ef
periscope/periscope.py
python
Periscope.listSubtitles
(self, filename, langs=None)
return subtitles
Searches subtitles within the active plugins and returns all found matching subtitles ordered by language then by plugin.
Searches subtitles within the active plugins and returns all found matching subtitles ordered by language then by plugin.
[ "Searches", "subtitles", "within", "the", "active", "plugins", "and", "returns", "all", "found", "matching", "subtitles", "ordered", "by", "language", "then", "by", "plugin", "." ]
def listSubtitles(self, filename, langs=None): '''Searches subtitles within the active plugins and returns all found matching subtitles ordered by language then by plugin.''' #if not os.path.isfile(filename): #raise InvalidFileException(filename, "does not exist") log.info("Searching subtitles for %s with langs %s" %(filename, langs)) subtitles = [] q = Queue() for name in self.pluginNames: try : plugin = getattr(plugins, name)(self.config, self.cache_path) log.info("Searching on %s " %plugin.__class__.__name__) thread = threading.Thread(target=plugin.searchInThread, args=(q, filename, langs)) thread.start() except ImportError : log.error("Plugin %s is not a valid plugin name. Skipping it.") # Get data from the queue and wait till we have a result for name in self.pluginNames: subs = q.get(True) if subs and len(subs) > 0: if not langs: subtitles += subs else: for sub in subs: if sub["lang"] in langs: subtitles += [sub] # Add an array with just that sub if len(subtitles) == 0: return [] return subtitles
[ "def", "listSubtitles", "(", "self", ",", "filename", ",", "langs", "=", "None", ")", ":", "#if not os.path.isfile(filename):", "#raise InvalidFileException(filename, \"does not exist\")", "log", ".", "info", "(", "\"Searching subtitles for %s with langs %s\"", "%", "(", "f...
https://github.com/patrickdessalle/periscope/blob/74537da58c3f930ef61cb04d3f8f964aedde88ef/periscope/periscope.py#L144-L174
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/utils/itemmodels.py
python
ContinuousPalettesModel.indexOf
(self, x)
return None
[]
def indexOf(self, x): if isinstance(x, str): for i, item in enumerate(self.items): if not isinstance(item, str) \ and x in (item.name, item.friendly_name): return i elif isinstance(x, ContinuousPalette): return self.items.index(x) return None
[ "def", "indexOf", "(", "self", ",", "x", ")", ":", "if", "isinstance", "(", "x", ",", "str", ")", ":", "for", "i", ",", "item", "in", "enumerate", "(", "self", ".", "items", ")", ":", "if", "not", "isinstance", "(", "item", ",", "str", ")", "an...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/utils/itemmodels.py#L661-L669
VirtueSecurity/aws-extender
d123b7e1a845847709ba3a481f11996bddc68a1c
BappModules/boto/ec2/connection.py
python
EC2Connection.get_all_reservations
(self, instance_ids=None, filters=None, dry_run=False, max_results=None, next_token=None)
return self.get_list('DescribeInstances', params, [('item', Reservation)], verb='POST')
Retrieve all the instance reservations associated with your account. :type instance_ids: list :param instance_ids: A list of strings of instance IDs :type filters: dict :param filters: Optional filters that can be used to limit the results returned. Filters are provided in the form of a dictionary consisting of filter names as the key and filter values as the value. The set of allowable filter names/values is dependent on the request being performed. Check the EC2 API guide for details. :type dry_run: bool :param dry_run: Set to True if the operation should not actually run. :type max_results: int :param max_results: The maximum number of paginated instance items per response. :type next_token: str :param next_token: A string specifying the next paginated set of results to return. :rtype: list :return: A list of :class:`boto.ec2.instance.Reservation`
Retrieve all the instance reservations associated with your account.
[ "Retrieve", "all", "the", "instance", "reservations", "associated", "with", "your", "account", "." ]
def get_all_reservations(self, instance_ids=None, filters=None, dry_run=False, max_results=None, next_token=None): """ Retrieve all the instance reservations associated with your account. :type instance_ids: list :param instance_ids: A list of strings of instance IDs :type filters: dict :param filters: Optional filters that can be used to limit the results returned. Filters are provided in the form of a dictionary consisting of filter names as the key and filter values as the value. The set of allowable filter names/values is dependent on the request being performed. Check the EC2 API guide for details. :type dry_run: bool :param dry_run: Set to True if the operation should not actually run. :type max_results: int :param max_results: The maximum number of paginated instance items per response. :type next_token: str :param next_token: A string specifying the next paginated set of results to return. :rtype: list :return: A list of :class:`boto.ec2.instance.Reservation` """ params = {} if instance_ids: self.build_list_params(params, instance_ids, 'InstanceId') if filters: if 'group-id' in filters: gid = filters.get('group-id') if not gid.startswith('sg-') or len(gid) != 11: warnings.warn( "The group-id filter now requires a security group " "identifier (sg-*) instead of a group name. To filter " "by group name use the 'group-name' filter instead.", UserWarning) self.build_filter_params(params, filters) if dry_run: params['DryRun'] = 'true' if max_results is not None: params['MaxResults'] = max_results if next_token: params['NextToken'] = next_token return self.get_list('DescribeInstances', params, [('item', Reservation)], verb='POST')
[ "def", "get_all_reservations", "(", "self", ",", "instance_ids", "=", "None", ",", "filters", "=", "None", ",", "dry_run", "=", "False", ",", "max_results", "=", "None", ",", "next_token", "=", "None", ")", ":", "params", "=", "{", "}", "if", "instance_i...
https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/boto/ec2/connection.py#L631-L681
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib-python/2.7/mhlib.py
python
Folder._copysequences
(self, fromfolder, refileditems)
Helper for refilemessages() to copy sequences.
Helper for refilemessages() to copy sequences.
[ "Helper", "for", "refilemessages", "()", "to", "copy", "sequences", "." ]
def _copysequences(self, fromfolder, refileditems): """Helper for refilemessages() to copy sequences.""" fromsequences = fromfolder.getsequences() tosequences = self.getsequences() changed = 0 for name, seq in fromsequences.items(): try: toseq = tosequences[name] new = 0 except KeyError: toseq = [] new = 1 for fromn, ton in refileditems: if fromn in seq: toseq.append(ton) changed = 1 if new and toseq: tosequences[name] = toseq if changed: self.putsequences(tosequences)
[ "def", "_copysequences", "(", "self", ",", "fromfolder", ",", "refileditems", ")", ":", "fromsequences", "=", "fromfolder", ".", "getsequences", "(", ")", "tosequences", "=", "self", ".", "getsequences", "(", ")", "changed", "=", "0", "for", "name", ",", "...
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/mhlib.py#L525-L544
openvinotoolkit/training_extensions
e7aa33af94a1f8004d3ea2df259d99234dfca046
ote_sdk/ote_sdk/entities/annotation.py
python
AnnotationSceneEntity.editor_name
(self)
return self.__editor
Returns the editor's name that made the AnnotationSceneEntity object.
Returns the editor's name that made the AnnotationSceneEntity object.
[ "Returns", "the", "editor", "s", "name", "that", "made", "the", "AnnotationSceneEntity", "object", "." ]
def editor_name(self): """ Returns the editor's name that made the AnnotationSceneEntity object. """ return self.__editor
[ "def", "editor_name", "(", "self", ")", ":", "return", "self", ".", "__editor" ]
https://github.com/openvinotoolkit/training_extensions/blob/e7aa33af94a1f8004d3ea2df259d99234dfca046/ote_sdk/ote_sdk/entities/annotation.py#L211-L215
sapruash/RecursiveNN
0ec71d3762625d1f72c0af42127d3d588f33c539
tf_seq_lstm.py
python
tf_seqLSTM.add_placeholders
(self)
[]
def add_placeholders(self): self.batch_len = tf.placeholder(tf.int32,name="batch_len") self.max_time = tf.placeholder(tf.int32,name="max_time") dim1=self.config.batch_size*(1+self.internal) self.input = tf.placeholder(tf.int32,shape=[None,self.config.maxseqlen],name="input") self.labels = tf.placeholder(tf.int32,shape=None ,name="labels") self.dropout = tf.placeholder(tf.float32,name="dropout") self.lngths = tf.placeholder(tf.int32,shape=None ,name="lnghts")
[ "def", "add_placeholders", "(", "self", ")", ":", "self", ".", "batch_len", "=", "tf", ".", "placeholder", "(", "tf", ".", "int32", ",", "name", "=", "\"batch_len\"", ")", "self", ".", "max_time", "=", "tf", ".", "placeholder", "(", "tf", ".", "int32",...
https://github.com/sapruash/RecursiveNN/blob/0ec71d3762625d1f72c0af42127d3d588f33c539/tf_seq_lstm.py#L14-L28
peterbrittain/asciimatics
9a490faddf484ee5b9b845316f921f5888b23b18
asciimatics/paths.py
python
Path._add_step
(self, pos)
Add a step to the end of the current recorded path. :param pos: The position tuple (x, y) to add to the list.
Add a step to the end of the current recorded path.
[ "Add", "a", "step", "to", "the", "end", "of", "the", "current", "recorded", "path", "." ]
def _add_step(self, pos): """ Add a step to the end of the current recorded path. :param pos: The position tuple (x, y) to add to the list. """ self._steps.append(pos) self._rec_x = pos[0] self._rec_y = pos[1]
[ "def", "_add_step", "(", "self", ",", "pos", ")", ":", "self", ".", "_steps", ".", "append", "(", "pos", ")", "self", ".", "_rec_x", "=", "pos", "[", "0", "]", "self", ".", "_rec_y", "=", "pos", "[", "1", "]" ]
https://github.com/peterbrittain/asciimatics/blob/9a490faddf484ee5b9b845316f921f5888b23b18/asciimatics/paths.py#L113-L121
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/client/grr_response_client/osx/objc.py
python
CFBoolean.__bool__
(self)
return self.value
[]
def __bool__(self): return self.value
[ "def", "__bool__", "(", "self", ")", ":", "return", "self", ".", "value" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/client/grr_response_client/osx/objc.py#L304-L305
nipy/nibabel
4703f4d8e32be4cec30e829c2d93ebe54759bb62
nibabel/_version.py
python
render_git_describe
(pieces)
return rendered
TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
TAG[-DISTANCE-gHEX][-dirty].
[ "TAG", "[", "-", "DISTANCE", "-", "gHEX", "]", "[", "-", "dirty", "]", "." ]
def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered
[ "def", "render_git_describe", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", ":", "rendered", "+=", "\"-%d-g%s\"", "%", "(", "pieces...
https://github.com/nipy/nibabel/blob/4703f4d8e32be4cec30e829c2d93ebe54759bb62/nibabel/_version.py#L424-L441
TengXiaoDai/DistributedCrawling
f5c2439e6ce68dd9b49bde084d76473ff9ed4963
Lib/site-packages/setuptools/package_index.py
python
open_with_auth
(url, opener=urllib.request.urlopen)
return fp
Open a urllib2 request, handling HTTP authentication
Open a urllib2 request, handling HTTP authentication
[ "Open", "a", "urllib2", "request", "handling", "HTTP", "authentication" ]
def open_with_auth(url, opener=urllib.request.urlopen): """Open a urllib2 request, handling HTTP authentication""" scheme, netloc, path, params, query, frag = urllib.parse.urlparse(url) # Double scheme does not raise on Mac OS X as revealed by a # failing test. We would expect "nonnumeric port". Refs #20. if netloc.endswith(':'): raise http_client.InvalidURL("nonnumeric port: ''") if scheme in ('http', 'https'): auth, host = splituser(netloc) else: auth = None if not auth: cred = PyPIConfig().find_credential(url) if cred: auth = str(cred) info = cred.username, url log.info('Authenticating as %s for %s (from .pypirc)', *info) if auth: auth = "Basic " + _encode_auth(auth) parts = scheme, host, path, params, query, frag new_url = urllib.parse.urlunparse(parts) request = urllib.request.Request(new_url) request.add_header("Authorization", auth) else: request = urllib.request.Request(url) request.add_header('User-Agent', user_agent) fp = opener(request) if auth: # Put authentication info back into request URL if same host, # so that links found on the page will work s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url) if s2 == scheme and h2 == host: parts = s2, netloc, path2, param2, query2, frag2 fp.url = urllib.parse.urlunparse(parts) return fp
[ "def", "open_with_auth", "(", "url", ",", "opener", "=", "urllib", ".", "request", ".", "urlopen", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "frag", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")"...
https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/site-packages/setuptools/package_index.py#L1035-L1077
enthought/traitsui
b7c38c7a47bf6ae7971f9ddab70c8a358647dd25
traitsui/examples/demo/Advanced/Tabular_editor_with_context_menu_demo.py
python
PlayerAdapter.sub
(self, object, column)
Decrement the affected player statistic.
Decrement the affected player statistic.
[ "Decrement", "the", "affected", "player", "statistic", "." ]
def sub(self, object, column): """Decrement the affected player statistic.""" column_name = self.column_map[column] setattr(object, column_name, getattr(object, column_name) - 1)
[ "def", "sub", "(", "self", ",", "object", ",", "column", ")", ":", "column_name", "=", "self", ".", "column_map", "[", "column", "]", "setattr", "(", "object", ",", "column_name", ",", "getattr", "(", "object", ",", "column_name", ")", "-", "1", ")" ]
https://github.com/enthought/traitsui/blob/b7c38c7a47bf6ae7971f9ddab70c8a358647dd25/traitsui/examples/demo/Advanced/Tabular_editor_with_context_menu_demo.py#L81-L84
rsmusllp/termineter
9311d6d995a7bf0f80853a00a115a8fa16aa0727
lib/termineter/interface.py
python
InteractiveInterpreter.do_reload
(self, args)
Reload a module in to the framework
Reload a module in to the framework
[ "Reload", "a", "module", "in", "to", "the", "framework" ]
def do_reload(self, args): """Reload a module in to the framework""" if args.module is not None: if args.module not in self.frmwk.modules: self.print_error('Invalid Module Selected.') return module = self.frmwk.modules[args.module] elif self.frmwk.current_module: module = self.frmwk.current_module else: self.print_error('Must \'use\' module first') return self.reload_module(module)
[ "def", "do_reload", "(", "self", ",", "args", ")", ":", "if", "args", ".", "module", "is", "not", "None", ":", "if", "args", ".", "module", "not", "in", "self", ".", "frmwk", ".", "modules", ":", "self", ".", "print_error", "(", "'Invalid Module Select...
https://github.com/rsmusllp/termineter/blob/9311d6d995a7bf0f80853a00a115a8fa16aa0727/lib/termineter/interface.py#L428-L440
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/asyncio/sslproto.py
python
_SSLProtocolTransport.can_write_eof
(self)
return False
Return True if this transport supports write_eof(), False if not.
Return True if this transport supports write_eof(), False if not.
[ "Return", "True", "if", "this", "transport", "supports", "write_eof", "()", "False", "if", "not", "." ]
def can_write_eof(self): """Return True if this transport supports write_eof(), False if not.""" return False
[ "def", "can_write_eof", "(", "self", ")", ":", "return", "False" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/asyncio/sslproto.py#L392-L394
lvpengyuan/masktextspotter.caffe2
da99ef31f5ccb4de5248bb881d5b4a291910c8ae
lib/datasets/roidb.py
python
filter_for_training
(roidb)
return filtered_roidb
Remove roidb entries that have no usable RoIs based on config settings.
Remove roidb entries that have no usable RoIs based on config settings.
[ "Remove", "roidb", "entries", "that", "have", "no", "usable", "RoIs", "based", "on", "config", "settings", "." ]
def filter_for_training(roidb): """Remove roidb entries that have no usable RoIs based on config settings. """ def is_valid(entry): # Valid images have: # (1) At least one foreground RoI OR # (2) At least one background RoI overlaps = entry['max_overlaps'] # find boxes with sufficient overlap fg_inds = np.where(overlaps >= cfg.TRAIN.FG_THRESH)[0] # Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI) bg_inds = np.where((overlaps < cfg.TRAIN.BG_THRESH_HI) & (overlaps >= cfg.TRAIN.BG_THRESH_LO))[0] # image is only valid if such boxes exist valid = len(fg_inds) > 0 or len(bg_inds) > 0 if cfg.MODEL.KEYPOINTS_ON: # If we're training for keypoints, exclude images with no keypoints valid = valid and entry['has_visible_keypoints'] return valid num = len(roidb) filtered_roidb = [entry for entry in roidb if is_valid(entry)] num_after = len(filtered_roidb) logger.info('Filtered {} roidb entries: {} -> {}'. format(num - num_after, num, num_after)) return filtered_roidb
[ "def", "filter_for_training", "(", "roidb", ")", ":", "def", "is_valid", "(", "entry", ")", ":", "# Valid images have:", "# (1) At least one foreground RoI OR", "# (2) At least one background RoI", "overlaps", "=", "entry", "[", "'max_overlaps'", "]", "# find boxes with...
https://github.com/lvpengyuan/masktextspotter.caffe2/blob/da99ef31f5ccb4de5248bb881d5b4a291910c8ae/lib/datasets/roidb.py#L111-L136
reclosedev/requests-cache
a29b85c3df40f874f80d06c949463b9532dada40
requests_cache/patcher.py
python
install_cache
( cache_name: str = 'http_cache', backend: BackendSpecifier = None, expire_after: ExpirationTime = -1, urls_expire_after: Dict[str, ExpirationTime] = None, allowable_codes: Iterable[int] = (200,), allowable_methods: Iterable['str'] = ('GET', 'HEAD'), filter_fn: Callable = None, stale_if_error: bool = False, session_factory: Type[OriginalSession] = CachedSession, **kwargs, )
Install the cache for all ``requests`` functions by monkey-patching :py:class:`requests.Session` Example: >>> requests_cache.install_cache('demo_cache') Accepts all the same parameters as :py:class:`.CachedSession`. Additional parameters: Args: session_factory: Session class to use. It must inherit from either :py:class:`.CachedSession` or :py:class:`.CacheMixin`
Install the cache for all ``requests`` functions by monkey-patching :py:class:`requests.Session`
[ "Install", "the", "cache", "for", "all", "requests", "functions", "by", "monkey", "-", "patching", ":", "py", ":", "class", ":", "requests", ".", "Session" ]
def install_cache( cache_name: str = 'http_cache', backend: BackendSpecifier = None, expire_after: ExpirationTime = -1, urls_expire_after: Dict[str, ExpirationTime] = None, allowable_codes: Iterable[int] = (200,), allowable_methods: Iterable['str'] = ('GET', 'HEAD'), filter_fn: Callable = None, stale_if_error: bool = False, session_factory: Type[OriginalSession] = CachedSession, **kwargs, ): """ Install the cache for all ``requests`` functions by monkey-patching :py:class:`requests.Session` Example: >>> requests_cache.install_cache('demo_cache') Accepts all the same parameters as :py:class:`.CachedSession`. Additional parameters: Args: session_factory: Session class to use. It must inherit from either :py:class:`.CachedSession` or :py:class:`.CacheMixin` """ class _ConfiguredCachedSession(session_factory): # type: ignore # See mypy issue #5865 def __init__(self): super().__init__( cache_name=cache_name, backend=backend, expire_after=expire_after, urls_expire_after=urls_expire_after, allowable_codes=allowable_codes, allowable_methods=allowable_methods, filter_fn=filter_fn, stale_if_error=stale_if_error, **kwargs, ) _patch_session_factory(_ConfiguredCachedSession)
[ "def", "install_cache", "(", "cache_name", ":", "str", "=", "'http_cache'", ",", "backend", ":", "BackendSpecifier", "=", "None", ",", "expire_after", ":", "ExpirationTime", "=", "-", "1", ",", "urls_expire_after", ":", "Dict", "[", "str", ",", "ExpirationTime...
https://github.com/reclosedev/requests-cache/blob/a29b85c3df40f874f80d06c949463b9532dada40/requests_cache/patcher.py#L23-L63
trakt/Plex-Trakt-Scrobbler
aeb0bfbe62fad4b06c164f1b95581da7f35dce0b
Trakttv.bundle/Contents/Libraries/Shared/requests/packages/urllib3/packages/ordered_dict.py
python
OrderedDict.keys
(self)
return list(self)
od.keys() -> list of keys in od
od.keys() -> list of keys in od
[ "od", ".", "keys", "()", "-", ">", "list", "of", "keys", "in", "od" ]
def keys(self): 'od.keys() -> list of keys in od' return list(self)
[ "def", "keys", "(", "self", ")", ":", "return", "list", "(", "self", ")" ]
https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/Shared/requests/packages/urllib3/packages/ordered_dict.py#L116-L118
inducer/loopy
55143b21711a534c07bbb14aaa63ff3879a93433
loopy/symbolic.py
python
AffineConditionToISLSetMapper._map_logical_reduce
(self, expr, f)
return reduce(f, sets)
:arg f: Reduction callable.
:arg f: Reduction callable.
[ ":", "arg", "f", ":", "Reduction", "callable", "." ]
def _map_logical_reduce(self, expr, f): """ :arg f: Reduction callable. """ sets = [self.rec(child) for child in expr.children] return reduce(f, sets)
[ "def", "_map_logical_reduce", "(", "self", ",", "expr", ",", "f", ")", ":", "sets", "=", "[", "self", ".", "rec", "(", "child", ")", "for", "child", "in", "expr", ".", "children", "]", "return", "reduce", "(", "f", ",", "sets", ")" ]
https://github.com/inducer/loopy/blob/55143b21711a534c07bbb14aaa63ff3879a93433/loopy/symbolic.py#L2115-L2120
AutodeskRoboticsLab/Mimic
85447f0d346be66988303a6a054473d92f1ed6f4
mimic/scripts/extern/pyqtgraph_0_11_0/pyqtgraph/widgets/DataFilterWidget.py
python
DataFilterParameter.setFields
(self, fields)
Set the list of fields that are available to be filtered. *fields* must be a dict or list of tuples that maps field names to a specification describing the field. Each specification is itself a dict with either ``'mode':'range'`` or ``'mode':'enum'``:: filter.setFields([ ('field1', {'mode': 'range'}), ('field2', {'mode': 'enum', 'values': ['val1', 'val2', 'val3']}), ('field3', {'mode': 'enum', 'values': {'val1':True, 'val2':False, 'val3':True}}), ])
Set the list of fields that are available to be filtered.
[ "Set", "the", "list", "of", "fields", "that", "are", "available", "to", "be", "filtered", "." ]
def setFields(self, fields): """Set the list of fields that are available to be filtered. *fields* must be a dict or list of tuples that maps field names to a specification describing the field. Each specification is itself a dict with either ``'mode':'range'`` or ``'mode':'enum'``:: filter.setFields([ ('field1', {'mode': 'range'}), ('field2', {'mode': 'enum', 'values': ['val1', 'val2', 'val3']}), ('field3', {'mode': 'enum', 'values': {'val1':True, 'val2':False, 'val3':True}}), ]) """ with fn.SignalBlock(self.sigTreeStateChanged, self.filterChanged): self.fields = OrderedDict(fields) names = self.fieldNames() self.setAddList(names) # update any existing filters for ch in self.children(): name = ch.fieldName if name in fields: ch.updateFilter(fields[name]) self.sigFilterChanged.emit(self)
[ "def", "setFields", "(", "self", ",", "fields", ")", ":", "with", "fn", ".", "SignalBlock", "(", "self", ".", "sigTreeStateChanged", ",", "self", ".", "filterChanged", ")", ":", "self", ".", "fields", "=", "OrderedDict", "(", "fields", ")", "names", "=",...
https://github.com/AutodeskRoboticsLab/Mimic/blob/85447f0d346be66988303a6a054473d92f1ed6f4/mimic/scripts/extern/pyqtgraph_0_11_0/pyqtgraph/widgets/DataFilterWidget.py#L67-L90
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/numbers.py
python
Real.__divmod__
(self, other)
return ( self // other, self % other)
divmod(self, other): The pair (self // other, self % other). Sometimes this can be computed faster than the pair of operations.
divmod(self, other): The pair (self // other, self % other). Sometimes this can be computed faster than the pair of operations.
[ "divmod", "(", "self", "other", ")", ":", "The", "pair", "(", "self", "//", "other", "self", "%", "other", ")", ".", "Sometimes", "this", "can", "be", "computed", "faster", "than", "the", "pair", "of", "operations", "." ]
def __divmod__(self, other): """divmod(self, other): The pair (self // other, self % other). Sometimes this can be computed faster than the pair of operations. """ return ( self // other, self % other)
[ "def", "__divmod__", "(", "self", ",", "other", ")", ":", "return", "(", "self", "//", "other", ",", "self", "%", "other", ")" ]
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/numbers.py#L188-L195
conansherry/detectron2
72c935d9aad8935406b1038af408aa06077d950a
detectron2/utils/visualizer.py
python
Visualizer.draw_sem_seg
(self, sem_seg, area_threshold=None, alpha=0.8)
return self.output
Draw semantic segmentation predictions/labels. Args: sem_seg (Tensor or ndarray): the segmentation of shape (H, W). area_threshold (int): segments with less than `area_threshold` are not drawn. alpha (float): the larger it is, the more opaque the segmentations are. Returns: output (VisImage): image object with visualizations.
Draw semantic segmentation predictions/labels.
[ "Draw", "semantic", "segmentation", "predictions", "/", "labels", "." ]
def draw_sem_seg(self, sem_seg, area_threshold=None, alpha=0.8): """ Draw semantic segmentation predictions/labels. Args: sem_seg (Tensor or ndarray): the segmentation of shape (H, W). area_threshold (int): segments with less than `area_threshold` are not drawn. alpha (float): the larger it is, the more opaque the segmentations are. Returns: output (VisImage): image object with visualizations. """ if isinstance(sem_seg, torch.Tensor): sem_seg = sem_seg.numpy() labels, areas = np.unique(sem_seg, return_counts=True) sorted_idxs = np.argsort(-areas).tolist() labels = labels[sorted_idxs] for label in filter(lambda l: l < len(self.metadata.stuff_classes), labels): try: mask_color = [x / 255 for x in self.metadata.stuff_colors[label]] except (AttributeError, IndexError): mask_color = None binary_mask = (sem_seg == label).astype(np.uint8) text = self.metadata.stuff_classes[label] self.draw_binary_mask( binary_mask, color=mask_color, edge_color=_OFF_WHITE, text=text, alpha=alpha, area_threshold=area_threshold, ) return self.output
[ "def", "draw_sem_seg", "(", "self", ",", "sem_seg", ",", "area_threshold", "=", "None", ",", "alpha", "=", "0.8", ")", ":", "if", "isinstance", "(", "sem_seg", ",", "torch", ".", "Tensor", ")", ":", "sem_seg", "=", "sem_seg", ".", "numpy", "(", ")", ...
https://github.com/conansherry/detectron2/blob/72c935d9aad8935406b1038af408aa06077d950a/detectron2/utils/visualizer.py#L372-L405
MontrealCorpusTools/Montreal-Forced-Aligner
63473f9a4fabd31eec14e1e5022882f85cfdaf31
montreal_forced_aligner/language_modeling/trainer.py
python
LmCorpusTrainer.normalized_text_iter
(self, min_count: int = 1)
Construct an iterator over the normalized texts in the corpus Parameters ---------- min_count: int Minimum word count to include in the output, otherwise will use OOV code, defaults to 1 Yields ------- str Normalized text
Construct an iterator over the normalized texts in the corpus
[ "Construct", "an", "iterator", "over", "the", "normalized", "texts", "in", "the", "corpus" ]
def normalized_text_iter(self, min_count: int = 1) -> Generator: """ Construct an iterator over the normalized texts in the corpus Parameters ---------- min_count: int Minimum word count to include in the output, otherwise will use OOV code, defaults to 1 Yields ------- str Normalized text """ unk_words = {k for k, v in self.word_counts.items() if v <= min_count} for u in self.utterances: text = u.text.split() new_text = [] for t in text: if u.speaker.dictionary is not None: u.speaker.dictionary.to_int(t) lookup = u.speaker.dictionary.split_clitics(t) if lookup is None: continue else: lookup = [t] for item in lookup: if item in unk_words: new_text.append(self.oov_word) self.oovs_found[item] += 1 elif ( u.speaker.dictionary is not None and item not in u.speaker.dictionary.words ): new_text.append(self.oov_word) else: new_text.append(item) yield " ".join(new_text)
[ "def", "normalized_text_iter", "(", "self", ",", "min_count", ":", "int", "=", "1", ")", "->", "Generator", ":", "unk_words", "=", "{", "k", "for", "k", ",", "v", "in", "self", ".", "word_counts", ".", "items", "(", ")", "if", "v", "<=", "min_count",...
https://github.com/MontrealCorpusTools/Montreal-Forced-Aligner/blob/63473f9a4fabd31eec14e1e5022882f85cfdaf31/montreal_forced_aligner/language_modeling/trainer.py#L313-L349
OpenNMT/OpenNMT-py
4815f07fcd482af9a1fe1d3b620d144197178bc5
onmt/translate/greedy_search.py
python
GreedySearch.__init__
(self, pad, bos, eos, unk, batch_size, global_scorer, min_length, block_ngram_repeat, exclusion_tokens, return_attention, max_length, sampling_temp, keep_topk, keep_topp, beam_size, ban_unk_token)
[]
def __init__(self, pad, bos, eos, unk, batch_size, global_scorer, min_length, block_ngram_repeat, exclusion_tokens, return_attention, max_length, sampling_temp, keep_topk, keep_topp, beam_size, ban_unk_token): super(GreedySearch, self).__init__( pad, bos, eos, unk, batch_size, beam_size, global_scorer, min_length, block_ngram_repeat, exclusion_tokens, return_attention, max_length, ban_unk_token) self.sampling_temp = sampling_temp self.keep_topk = keep_topk self.keep_topp = keep_topp self.topk_scores = None self.beam_size = beam_size
[ "def", "__init__", "(", "self", ",", "pad", ",", "bos", ",", "eos", ",", "unk", ",", "batch_size", ",", "global_scorer", ",", "min_length", ",", "block_ngram_repeat", ",", "exclusion_tokens", ",", "return_attention", ",", "max_length", ",", "sampling_temp", ",...
https://github.com/OpenNMT/OpenNMT-py/blob/4815f07fcd482af9a1fe1d3b620d144197178bc5/onmt/translate/greedy_search.py#L122-L134
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/setuptools/pep425tags.py
python
get_flag
(var, fallback, expected=True, warn=True)
return val == expected
Use a fallback method for determining SOABI flags if the needed config var is unset or unavailable.
Use a fallback method for determining SOABI flags if the needed config var is unset or unavailable.
[ "Use", "a", "fallback", "method", "for", "determining", "SOABI", "flags", "if", "the", "needed", "config", "var", "is", "unset", "or", "unavailable", "." ]
def get_flag(var, fallback, expected=True, warn=True): """Use a fallback method for determining SOABI flags if the needed config var is unset or unavailable.""" val = get_config_var(var) if val is None: if warn: warnings.warn("Config variable '{0}' is unset, Python ABI tag may " "be incorrect".format(var), RuntimeWarning, 2) return fallback() return val == expected
[ "def", "get_flag", "(", "var", ",", "fallback", ",", "expected", "=", "True", ",", "warn", "=", "True", ")", ":", "val", "=", "get_config_var", "(", "var", ")", "if", "val", "is", "None", ":", "if", "warn", ":", "warnings", ".", "warn", "(", "\"Con...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/setuptools/pep425tags.py#L66-L75
madduck/reclass
9c3478498a5dfa3d1e5cf7aa3b602ca3b53ee15b
reclass/storage/__init__.py
python
NodeStorageBase.enumerate_nodes
(self)
[]
def enumerate_nodes(self): msg = "Storage class '{0}' does not implement node enumeration." raise NotImplementedError(msg.format(self.name))
[ "def", "enumerate_nodes", "(", "self", ")", ":", "msg", "=", "\"Storage class '{0}' does not implement node enumeration.\"", "raise", "NotImplementedError", "(", "msg", ".", "format", "(", "self", ".", "name", ")", ")" ]
https://github.com/madduck/reclass/blob/9c3478498a5dfa3d1e5cf7aa3b602ca3b53ee15b/reclass/storage/__init__.py#L25-L27