blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
777 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
listlengths
1
1
author_id
stringlengths
1
132
69c70ef47f8e836c53cd8e10637d1dc0f6b5cf45
52e733d03eb159011cd16157fceee34705e3f0aa
/qelos/scripts/rnnmnist_dec.py
0be9d86343b35d69efafeac6ef7a3bf31c092c1e
[ "MIT" ]
permissive
nilesh-c/qelos
4a677e52e42203a88af4297154ad9d032fc7a179
70862214a493fc8075bedb33d360a8213bce9ca7
refs/heads/master
2021-04-28T19:53:30.266992
2017-09-15T23:51:27
2017-09-15T23:51:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,577
py
import torch import torch.nn as nn import torchvision.datasets as dsets import torchvision.transforms as transforms import qelos as q, numpy as np from qelos.rnn import GRUCell, RecStack from qelos.util import ticktock tt = ticktock("script") class RNNStack(nn.Module): def __init__(self, *layers): super(RNNStack, self).__init__() self.layers = nn.ModuleList(modules=list(layers)) def forward(self, x, h0): y = x for i, layer in enumerate(self.layers): y, s = layer(y, h0[i].unsqueeze(0)) return y, s # RNN Model (Many-to-One) class Encoder(nn.Module): def __init__(self, input_size, hidden_size, num_layers, mode="nn"): super(Encoder, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.mode = mode if self.mode == "qrnn": tt.msg("using q.RNN") self.rnn = RecStack(*[GRUCell(input_size, hidden_size)] + [GRUCell(hidden_size, hidden_size) for i in range(num_layers - 1)]) \ .to_layer().return_all() elif self.mode == "nn": tt.msg("using nn.RNN") self.rnn = nn.GRU(input_size, hidden_size, num_layers, batch_first=True) elif self.mode == "stack": self.rnn = RNNStack( *([nn.GRU(input_size, hidden_size, 1, batch_first=True)] + [nn.GRU(hidden_size, hidden_size, 1, batch_first=True) for i in range(num_layers - 1)] ) ) def forward(self, x): # Set initial states h0 = q.var(torch.zeros(self.num_layers, x.size(0), self.hidden_size)).cuda(crit=x).v # c0 = Variable(torch.zeros(self.num_layers, x.size(0), self.hidden_size)) # Forward propagate RNN if self.mode == "qrnn": out = self.rnn(x) else: out, _ = self.rnn(x, h0) # Returns final state out = out[:, -1, :] return out class ImgToSeq(nn.Module): def __init__(self, encoder, decoder): super(ImgToSeq, self).__init__() self.encoder = encoder self.decoder = decoder def forward(self, img, outseq): enc = self.encoder(img) dec = self.decoder(outseq, enc) return dec class IdxToSeq(nn.Module): def __init__(self, decoder, vocsize=10, embdim=100): super(IdxToSeq, self).__init__() self.decoder = decoder self.embedder = nn.Embedding(vocsize, embdim) def forward(self, idx, seq): enc = self.embedder(idx) dec = self.decoder(seq, enc) return dec class DecoderLoss(nn.Module): def __init__(self): super(DecoderLoss, self).__init__() self.elem_loss = nn.NLLLoss(ignore_index=0) def forward(self, logprobs, gold): """ :param logprobs: (batsize, seqlen, vocsize) :param gold: (batsize, seqlen) :return: """ acc = 0 for i in range(logprobs.size(0)): acc += self.elem_loss(logprobs[i], gold[i]) acc /= i return acc def test_decoder_loss(): l = DecoderLoss() logprobs = -np.random.random((3, 5, 4)) gold = np.asarray([[1,2,3,0,0],[1,1,0,0,0],[3,3,3,3,3]]) logprobs = q.var(torch.FloatTensor(logprobs)).v gold = q.var(torch.LongTensor(gold)).v loss = l(logprobs, gold) print loss def number2charseq(x): dic = {0: "_zero ", 1: "_one ", 2: "_two ", 3: "_three ", 4: "_four ", 5: "_five ", 6: "_six ", 7: "_seven ", 8: "_eight ", 9: "_nine "} acc = [] tocuda = False if x.is_cuda: x = x.cpu() tocuda = True for i in range(x.size(0)): word = x[i].data.numpy()[0] word = dic[word] word = map(lambda x: ord(x) if x is not " " else 0, word) acc.append(word) acc = np.asarray(acc) acc = q.var(torch.LongTensor(acc)).cuda(crit=tocuda).v return acc def main( # Hyper Parameters sequence_length = 28, input_size = 28, hidden_size = 128, num_layers = 2, batch_size = 5, num_epochs = 2, learning_rate = 0.01, ctx_to_decinp=False, gpu = False, mode = "stack", # "nn" or "qrnn" or "stack" trivial=False, ): tt.msg("using q: {}".format(mode)) # MNIST Dataset train_dataset = dsets.MNIST(root='../../../datasets/mnist/', train=True, transform=transforms.ToTensor(), download=True) test_dataset = dsets.MNIST(root='../../../datasets/mnist/', train=False, transform=transforms.ToTensor()) # Data Loader (Input Pipeline) train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False) if gpu: q.var.all_cuda = True encoder = Encoder(input_size, hidden_size, num_layers, mode=mode) embdim = hidden_size decdim = 100 initstate = nn.Linear(hidden_size, decdim) decoder = q.ContextDecoder(*[ nn.Embedding(256, embdim), q.RecurrentStack( q.GRULayer((embdim + hidden_size if ctx_to_decinp else embdim), decdim), nn.Linear(decdim, 256), nn.LogSoftmax() ) ], ctx_to_h0=initstate, ctx_to_decinp=ctx_to_decinp) if trivial: encdec = IdxToSeq(decoder, embdim=hidden_size) else: encdec = ImgToSeq(encoder, decoder) if gpu: encdec.cuda() # Loss and Optimizer criterion = nn.CrossEntropyLoss() criterion = q.SeqNLLLoss(ignore_index=0) if gpu: criterion.cuda() optimizer = torch.optim.Adadelta(encdec.parameters(), lr=learning_rate) tt.msg("training") # Train the Model for epoch in range(num_epochs): tt.tick() btt = ticktock("batch") btt.tick() for i, (images, labels) in enumerate(train_loader): #btt.tick("doing batch") images = q.var(images.view(-1, sequence_length, input_size)).cuda(crit=gpu).v labels = q.var(labels).cuda(crit=gpu).v tgt = number2charseq(labels) if trivial: images = labels # Forward + Backward + Optimize optimizer.zero_grad() outputs = encdec(images, tgt[:, :-1]) loss = criterion(outputs, tgt[:, 1:]) loss.backward() optimizer.step() if (i+1) % 100 == 0: btt.tock("100 batches done") tgn = 0 for param in encdec.parameters(): tgn = tgn + torch.norm(param.grad, 2) print ('Epoch [%d/%d], Step [%d/%d], Loss: %.4f, TGN: %.8f' %(epoch+1, num_epochs, i+1, len(train_dataset)//batch_size, loss.data[0], tgn.cpu().data.numpy()[0])) btt.tick() #tt.tock("batch done") tt.tock("epoch {} done {}".format(epoch, loss.data[0])) # Test the Model correct = 0 total = 0 for images, labels in test_loader: images = q.var(images.view(-1, sequence_length, input_size)).cuda(crit=gpu).v labels = q.var(labels).cuda(crit=gpu).v if trivial: images = labels tgt = number2charseq(labels) outputs = encdec(images, tgt[:, :-1]) _, predicted = torch.max(outputs.data, 2) if tgt.is_cuda: tgt = tgt.cpu() if predicted.is_cuda: predicted = predicted.cpu() tgt = tgt[:, 1:].data.numpy() predicted = predicted.numpy() # print(predicted[:10]) # print(tgt[:10]) # print(labels[:10]) tgtmask = tgt == 0 eq = predicted == tgt eq = eq | tgtmask eq = np.all(eq, axis=1) correct += eq.sum() total += labels.size(0) print('Test Accuracy of the model on the 10000 test images: %d %%' % (100. * correct / total)) # Save the Model torch.save(encdec.state_dict(), 'rnn.pkl') if __name__ == "__main__": #test_decoder_loss() q.argprun(main)
[ "lukovnikov@outlook.com" ]
lukovnikov@outlook.com
0e5b73246e9bf01a3fa6831a2fc46a5a4f921ff8
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_048/ch78_2020_04_11_03_56_59_345262.py
bb5a6d95248403b0737f835dd5b64ee23d9c67f7
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
583
py
import math diciok=[] diciov=[] continua=True while continua: r=input('Digite um nome') diciok.append(r) if r=='sair': break u=input('Digite uma aceleracao') diciov.append(int(u)) dicio=dict(zip(diciok,diciov)) def calcula_tempo(dicio): k=dicio.keys() v=list(dicio.values()) d=[0]*len(v) for i in range(len(v)): d[i]=math.sqrt(200/v[i]) n=dict(zip(k, d)) j=min(n.values()) for chave,valor in n.items(): if valor==j: return print('O vencedor é {0} com tempo de conclusão de {1} s'.format(chave,j))
[ "you@example.com" ]
you@example.com
4c088ea72be2320c98c645d87980f54717db2794
286fb0c7ae765f55a85c027a88214249d0b5bebe
/pyppet/avformat/__init__.py
18bd6deb910bc777185a59eb66a0fcf8a66ab302
[ "BSD-3-Clause" ]
permissive
antwan2000arp/pyppet
e66aa87d5f87dbbbc2b927e74fa2bb9cfd97d9c4
a6a7dbe3be49d3492f85417d0b1a08ff5cadea70
refs/heads/master
2016-08-12T04:33:08.432568
2013-07-18T23:16:45
2013-07-18T23:16:45
52,249,482
0
0
null
null
null
null
UTF-8
Python
false
false
208,609
py
## generated by RPythonic 0.4.5a ## http://code.google.com/p/rpythonic/ import os, sys, ctypes, inspect __os = os __sys = sys __inspect = inspect PYTHON_RESERVED_KEYWORDS = 'for while in as global with try except lambda return raise if else elif eval exec and not or break continue finally print yield del def class assert from is pass'.split() IS32BIT = (ctypes.sizeof(ctypes.c_void_p)==4) _ISPYTHON2 = sys.version_info[0] == 2 if _ISPYTHON2: _NULLBYTE = '\0' else: _NULLBYTE = bytes( chr(0), 'ascii' ) def _CHARP2STRING( charp, encoding='utf-8' ): b = bytes() i = 0 while True: char = charp[ i ] if char == _NULLBYTE: break else: b += char i += 1 return b.decode( encoding ) ## try to load precompiled c-libraries from this directory, if the library is not there try to load from the system. _clibs_dir = os.path.dirname(os.path.abspath(__file__)) def _load_ctypes_lib( name ): if __os.name == 'posix': if __sys.platform.startswith('linux'): if not name.endswith('.so'): name += '.so' if not name.startswith('lib'): name = 'lib' + name if IS32BIT: path = __os.path.join(_clibs_dir,'linux32') else: path = __os.path.join(_clibs_dir,'linux64') url = __os.path.join( path, name ) if __os.path.isfile( url ): return ctypes.CDLL(url) elif __os.path.isfile( '/usr/local/lib/%s'%name ): return ctypes.CDLL('/usr/local/lib/%s'%name) elif __os.path.isfile( '/usr/local/lib64/%s'%name ) and not IS32BIT: return ctypes.CDLL('/usr/local/lib64/%s'%name) elif __os.path.isfile( '/usr/lib/%s'%name ): return ctypes.CDLL('/usr/lib/%s'%name) elif __os.path.isfile( './%s'%name ): return ctypes.CDLL('./%s'%name) else: # fallback try: return ctypes.CDLL(name) except: return ctypes.CDLL('') elif sys.platform == 'darwin': name += '.dylib' if IS32BIT: path = os.path.join(_clibs_dir,'osx32') else: path = os.path.join(_clibs_dir,'osx64') url = os.path.join( path, name ) if os.path.isfile( url ): return ctypes.CDLL(url) else: return ctypes.CDLL(name) #fallback elif os.name == 'nt': name += '.dll' if IS32BIT: path = os.path.join(_clibs_dir,'win32') else: path = os.path.join(_clibs_dir,'win64') url = os.path.join( path, name ) if os.path.isfile( url ): return ctypes.CDLL(url) else: return ctypes.CDLL(name) #fallback RPYTHONIC_WRAPPER_FUNCTIONS = {} RPYTHONIC_WRAPPER_FUNCTIONS_FAILURES = [] RPYTHONIC_AUTOPREFIX_IGNORE = [] ## ctypes does not clearly expose these types ## PyCFuncPtrType = type(ctypes.CFUNCTYPE(ctypes.c_void_p)) PyCArrayType = type( ctypes.c_int * 2 ) PyCPointerType = type( ctypes.POINTER(ctypes.c_int) ) PyCStructType = type( ctypes.Structure ) CArgObject = type( ctypes.byref(ctypes.c_int()) ) class _rpythonic_meta_(object): ''' Reserved Attributes: POINTER CSTRUCT CAST ''' _rpythonic_ = True # workaround for now, must have a way to know if object is a meta from another module, isinstance(o,_rpythonic_meta_) will fail in those cases. another workaround could be check sys.modules for other rpythonic modules and fetch _rpythonic_meta_ from there. def __init__(self, *args, **kw ): # cheap trick, abuse **kw, and look for "pointer", "cast" if kw and 'pointer' not in kw: raise SyntaxError # sorry, you can not init with keywords elif kw and 'pointer' in kw: if 'cast' in kw and kw['cast']: self.POINTER = ctypes.cast( kw['pointer'], ctypes.POINTER(self.CSTRUCT) ) else: self.POINTER = kw['pointer'] else: self.POINTER = ctypes.pointer( self.CSTRUCT(*args) ) self.POINTER.pyobject = self # .pyobject is local to this pointer "object" def __getattr__(self,name): if hasattr( self.POINTER.contents, name ): return getattr( self.POINTER.contents, name ) else: # when rpythonic failed to generate good bindings - these lookups should be cached for parent in self._rpythonic_parent_classes_: if hasattr( parent, name ): method = getattr( parent, name ) # should check if it really is an unbound method if method in parent._rpythonic_unbound_lookup_: func = parent._rpythonic_unbound_lookup_[ method ] n = func.name if len(func.argnames) > 1: argnames = func.argnames[ 1 : ] a = ',' + '=None,'.join( argnames ) + '=None' b = ','.join( argnames ) else: a = b = '' lamb = eval( 'lambda self %s: %s( self.POINTER, %s )' %(a,n,b) ) setattr( self.__class__, name, lamb ) #return lamb # this would return the unbound lambda, must call getattr again return getattr( self, name ) else: # this can happen if self also inherits from the same parent class, # assume that by continuing this reaches that shared parent class, # and the lambda above is created as normal. continue ## last resort, load from global name space ## G = globals() if name in G: return lambda *args: G[name](self.POINTER, *args) else: for prefix in self._autoprefix_: n = prefix + name if n in G: return lambda *args: G[n](self.POINTER, *args) print( 'possible auto-prefixes available', self._autoprefix_ ) raise AttributeError def __call__(self, type=False): print('calling object is DEPRECATED - use ob.POINTER or ob.CSTRUCT') if type: return self.CSTRUCT else: return self.POINTER def _rpythonic_generate_subclass_( name, struct, functions ): head = 'class %s( _rpythonic_meta_ ):' %name body = [ '_rpythonic_parent_classes_ = []' , '_rpythonic_unbound_lookup_ = {}' ] names = [ func.name for func in functions ] possibles = {} rank = [] # rank by longest name if len(names) > 3000: print('too many functions to use this hack') else: for n1 in names: prefix = '' for i,char in enumerate(n1): prefix += char if prefix not in possibles: possibles[ prefix ] = 0 for n2 in names: if n2.startswith( prefix ): possibles[ prefix ] += 1 if not rank or len(prefix) > len(rank[-1]) and possibles[prefix] > len(names)/4: rank.append( prefix ) top = [] while rank: best = rank.pop() if possibles[best] > len(functions)/2 and best not in names: if best.endswith('_set_') or best.endswith('_get_'): best = best[ : -4 ] elif best.endswith('Set') or best.endswith('Get'): best = best[ : -3 ] rem = [] for other in rank: if best.startswith(other): rem.append( other ) for r in rem: rank.remove( r ) if best not in top: top.append( best ) if len(top) > 3: break for n in names: # find shortest prefixes # prefix = '' for i,char in enumerate(n): # cammelCase if i==0: prefix += char; continue if char.isupper() and len(prefix) >= 2: break prefix += char if prefix and prefix != n and len(prefix) >= 2: hits = 0 for other in names: if other.startswith( prefix ): hits += 1 if hits >= 2 and prefix not in top: top.append( prefix ) if len(top) >= 6: break ## setup full names for func in functions: n = func.name if len(func.argnames) > 1: argnames = func.argnames[ 1 : ] a = ',' + '=None,'.join( argnames ) + '=None' b = ','.join( argnames ) else: a = b = '' fhead = 'def %s( self %s ):' %(n,a) fbody = ['return %s(self.POINTER, %s)' %(func.name,b)] g = fhead + '\n\t\t' + '\n\t\t'.join( fbody ) body.append( g ) #body.append( '%s._rpythonic_function_ = %s' %(func.name, func.name) ) ## setup short names ## for n in names: for prefix in top: if n.startswith(prefix) and n[len(prefix):] not in names: alt = n[ len(prefix) : ] if alt and alt != n and alt not in PYTHON_RESERVED_KEYWORDS and not alt.isdigit() and not alt[0].isdigit(): body.append( '%s = %s' %(alt,n) ) names.append( alt ) gen = head + '\n\t' + '\n\t'.join( body ) try: exec( gen ) except: print( gen ) raise SyntaxError klass = locals()[name] klass.CSTRUCT = struct # ctypes struct class klass._autoprefix_ = top for func in functions: unbound = getattr( klass, func.name ) klass._rpythonic_unbound_lookup_[ unbound ] = func # klass.longname is klass.shortname = False # klass.longname == klass.shortname = True return klass def _rpythonic_convert_structs_to_objects(): G = globals() for klass in _OOAPI_: altname = name = klass.__name__ prefix = '' for i,char in enumerate(name): if i==0: prefix += char; continue if char.isupper(): break prefix += char if prefix and prefix != name: hits = 0 for other in _OOAPI_: if other is not klass: if other.__name__.startswith( prefix ): hits += 1 if hits >= 2: altname = name[ len(prefix) : ] funcs = _OOAPI_[ klass ] newklass = _rpythonic_generate_subclass_( altname, klass, funcs ) klass._rpythonic_wrapper_class_ = newklass G[ name ] = newklass # replace struct with wrapper if altname not in G: G[ altname ] = newklass # safely define with nicer name elif altname != name: # odd cases, maybe a function that returns the object, almost never happens. print('WARN - not replacing something with struct wrapper:', G[altname] ) def _rpythonic_setup_return_wrappers(): R = _rpythonic_function_ for klass in _OOAPI_: if klass in _OOAPI_RETURNS_OBJECT_: for f in _OOAPI_RETURNS_OBJECT_[klass]: f.object_oriented = True if not f.return_wrapper: # just in case the ctypes footer had already defined it, do not overwrite f.return_wrapper = klass._rpythonic_wrapper_class_ def _rpythonic_function_( name, result=ctypes.c_void_p, args=[]): mname = '_metafunc_%s' %name exec( 'class %s( _rpythonic_metafunc_ ): pass' %mname ) k = locals()[mname] return k( name, result, args ) _OOAPI_ = {} _OOAPI_RETURNS_OBJECT_ = {} class _rpythonic_metafunc_(object): def __init__(self, name, result=ctypes.c_void_p, args=[]): self.name = name self.result = result self.argtypes = [] # can dynamically change CFUNCTYPE trick self.argnames = [] self.argtypestypes = [] for i,arg in enumerate(args): n,t = arg if n in PYTHON_RESERVED_KEYWORDS: n = 'C_'+n if n in self.argnames: n = '%s%s' %(n,i) self.argnames.append( n ) self.argtypes.append( t ) self.argtypestypes.append( type(t) ) # precomputed for speed self.argnames = tuple( self.argnames ) # should never change self.numargs = len( self.argtypes ) self.callbacks = [None] * self.numargs self.return_wrapper = None self.object_oriented = False self.function = None try: func = self.function = getattr(CTYPES_DLL, self.name ) RPYTHONIC_WRAPPER_FUNCTIONS[ name ] = self except: RPYTHONIC_WRAPPER_FUNCTIONS_FAILURES.append( name ) if self.function: self.reset() def change_argument_type( self, name, t ): idx = self.argnames.index( name ) self.argtypes[ idx ] = t self.argtypestypes[ idx ] = type(t) self.function.argtypes = self.argtypes def reset(self): if self.argnames: a = ',' + '=None,'.join( self.argnames ) + '=None' b = ','.join( self.argnames ) else: a = b = '' callmeth = eval( 'lambda self %s: self._call_( %s )' %(a,b) ) setattr( self.__class__, '__call__', callmeth ) self.function.restype = self.result self.function.argtypes = self.argtypes if type( self.result ) is PyCPointerType and type(self.result._type_) is PyCStructType: klass = self.result._type_ if klass not in _OOAPI_RETURNS_OBJECT_: _OOAPI_RETURNS_OBJECT_[klass] = [] _OOAPI_RETURNS_OBJECT_[klass].append( self ) self.defaults = [] for i in range( self.numargs ): T = self.argtypes[ i ] if type(T) is PyCFuncPtrType: p = T() # func pointers can not be None self.defaults.append( p ) self.callbacks[ i ] = p # save reference elif T in (ctypes.c_int, ctypes.c_uint, ctypes.c_long, ctypes.c_ulong): self.defaults.append( 0 ) elif T in (ctypes.c_float, ctypes.c_double): self.defaults.append( .0 ) else: self.defaults.append( None ) # None is allowed for all other types ## generate OO API ## if i == 0 and type(T) is PyCPointerType and type(T._type_) is PyCStructType: klass = T._type_ if klass not in _OOAPI_: _OOAPI_[ klass ] = [] _OOAPI_[ klass ].append( self ) def _call_( self, *args ): # allow flexible calling types cargs = list( self.defaults ) for i,arg in enumerate(args): if isinstance( arg, _rpythonic_meta_ ): arg = arg.POINTER elif hasattr( arg, '_rpythonic_' ): arg = arg.POINTER # workaround - instance from another module t = type(arg) k = self.argtypes[ i ] kt = self.argtypestypes[ i ] if arg is None and cargs[i] is not None: # use user defaults, very rare cases continue elif t is bool and k is ctypes.c_int: if arg: cargs[i] = 1 #ctypes.c_int(1) else: cargs[i] = 0 #ctypes.c_int(0) elif t in (list,tuple): # convert lists and tuples into array if kt is PyCArrayType: cargs[ i ] = k(*arg) elif kt is PyCStructType: if k._array_wrapper_: cargs[ i ] = k(arg) # allow easy array init else: cargs[ i ] = k(*arg) # allow multiple args elif kt is PyCPointerType: cargs[ i ] = _convert_nested_list_to_pointer( k, arg ) else: assert 0 elif isinstance( arg, ctypes._Pointer ) and t is not k and kt is PyCPointerType: cargs[ i ] = ctypes.cast( arg, k ) # generic's that need to be cast elif kt is PyCStructType and isinstance( arg, ctypes._Pointer ): cargs[ i ] = arg.contents # fixed may25 elif kt is PyCPointerType and not isinstance( arg, (ctypes._Pointer,CArgObject) ): if t in (int,float,bool): ptr = k( k._type_(arg) ) elif t is str: arg = arg.encode('utf-8') #ptr = k( k._type_() ) # not k() otherwise null pointer error #for j, char in enumerate(arg): ptr[ j ] = char # not correct - missing null byte? ptr = ctypes.create_string_buffer(arg) # correct and pypy compatible elif t in (PyCStructType, PyCArrayType): ptr = ctypes.cast( ctypes.pointer( arg ), k ) else: ptr = arg # TODO print warning? cargs[ i ] = ptr elif kt is PyCFuncPtrType: if t.__name__ == 'CFunctionType': cargs[ i ] = arg # assume outside holds pointer else: # this is not safe # cargs[ i ] = self.callbacks[ i ] = k( arg ) # assume arg is a callable else: cargs[ i ] = arg # directly pass ## if you define your own return_wrapper, it must take keyword "pointer" if self.return_wrapper: return self.return_wrapper( pointer=self.function( *cargs ) ) else: return self.function( *cargs ) def _convert_nested_list_to_pointer( k, arg ): depth = 0; s = k while True: if type(s) is PyCPointerType: s = getattr( s, '_type_' ) depth += 1 else: break assert depth and depth <= 2 if depth == 1: T = k._type_ ptr = k( k._type_() ) for i in range( len(arg) ): ptr[ i ] = T( *arg[i] ) elif depth == 2: T = k._type_._type_ _ptr = k._type_( k._type_._type_() ) for i in range(len( arg )): for j in range( len(arg[i]) ): _ptr[ j ] = T( *arg[ i ][ j ] ) ptr = k( _ptr ) return ptr def __freeze_rpythonic_struct( cls, fields ): if cls not in _OOAPI_: _OOAPI_[ cls ] = [] # wrap all structs try: setattr( cls, '_fields_', fields ) except: print( 'WARN - bad order struct freeze', cls ) #cls._fields_ = [] class _rpythonic_struct_( ctypes.Structure ): _array_wrapper_ = False _fields_ = [] _methods_ = {} #def __call__(self): return self def __init__(self, *args, **kw ): cargs = [] argtypes = [] for a in self._fields_: argtypes.append( a[1] ) if len(args) > len(argtypes): args = [args] # allow both calling conventions for i,arg in enumerate( args ): if isinstance( arg, _rpythonic_meta_ ): arg = arg.POINTER t = type(arg) k = argtypes[ i ] if t in (list,tuple): if k.__class__.__name__ == 'PyCArrayType': cargs.append( k(*arg) ) elif k.__class__.__name__ == 'PyCStructType': if k._array_wrapper_: cargs.append( k(arg) ) # allow easy array init else: cargs.append( k(*arg) ) # allow multiple args elif isinstance( arg, ctypes._Pointer ) and t is not k: cargs[ i ] = ctypes.cast( arg, k ) # generic's that need to be cast elif k.__class__.__name__ == 'PyCArrayType' and t in (float,int,bool): cargs.append( k(arg) ) # support init array from single value else: cargs.append( arg ) # directly pass ctypes.Structure.__init__(self, *cargs, **kw) def _rpythonic_make_nice_global_enums_(): G = globals() for name in RPYTHONIC_GLOBAL_ENUMS: if '_' in name and name.index('_') <= 4: altname = name[ name.index('_') + 1 : ] if altname not in G: G[altname] = RPYTHONIC_GLOBAL_ENUMS[ name ] def _rpythonic_clean_up_missing_functions_(): G = globals() for f in RPYTHONIC_WRAPPER_FUNCTIONS_FAILURES: G.pop( f ) print( "C functions loaded: %s" %len(RPYTHONIC_WRAPPER_FUNCTIONS) ) print( "C functions failed: %s" %len(RPYTHONIC_WRAPPER_FUNCTIONS_FAILURES) ) ###### NEW API ######### CTYPES_DLL = None class _VOID_POINTER_CONTAINER_(object): def __init__(self, ptr, name=None): self._pointer_ = ptr self.name = name NULL = _VOID_POINTER_CONTAINER_(None,'<null pointer>') class meta: # NEW API - allow run time switch from ctypes to rffi ''' Methods: RPython will not allow object wrapper around a method (__call__ not allowed) keep C function names in list "__cfunctions__" rpythonic.enable_rffi( classA, classB ) can take advantage of methods in object-method-wrapper, generate rffi wrapper and set method on classA, etc. replaces object-method-wrapper with rffi-method Properties: CPython: obj.x=1 RPython: obj.set_x(1) ''' METAS = [] def __init__(self, constructors=[], methods={}, properties={}): global CTYPES_DLL if not CTYPES_DLL: CTYPES_DLL = _load_ctypes_lib( _clib_name_ ) self.constructors = constructors self.methods = methods self.properties = properties self.METAS.append( self ) def __call__(self, cls ): print('@meta', cls ) if not self.constructors: lamb = lambda s, _explicit_pointer_=None: setattr(s,'_pointer_',getattr(_explicit_pointer_,'_pointer_')) if hasattr(_explicit_pointer_,'_pointer_') else setattr(s,'_pointer_',_explicit_pointer_) lamb._debug = '(no constructor)' setattr( cls, '__init__', lamb ) else: con = self._find_best_function( self.constructors ) cfunc = self._build_cfunc( con ) setattr( cls, '_%s'%con['name'], cfunc ) g = self._gen_init( con ) setattr( cls, '__init__', g ) ## set methods ## for name in self.methods: meth = self.methods[ name ] cfuncs = [] for m in meth['functions']: cfunc = self._build_cfunc( m, method=True, static=meth['static'] ) self._setup_return( cfunc, meth ) setattr( cls, '_%s'%m['name'], cfunc ) cfuncs.append( cfunc ) f = self._find_best_function( meth['functions'] ) g = self._gen_method( meth, f ) g._cfuncs = cfuncs if meth['static']: g = classmethod( g ) setattr( cls, name, g ) for name in self.properties: print( 'property:', name ) p = [] for f in self.properties[name]: cfunc = self._build_cfunc( f ) setattr( cls, '_%s'%f['name'], cfunc ) g = self._gen_method( f, f ) p.append( g ) setattr( cls, name, property(*p) ) return cls @staticmethod def _build_cfunc( info, method=False, static=False ): cfunc = getattr(CTYPES_DLL, info['name']) if method and not static: argtypes = [ ctypes.c_void_p ] else: argtypes = [] for p in info['parameters']: argtypes.append( eval(p['ctypes_type']) ) cfunc.argtypes = argtypes return cfunc @staticmethod def _setup_return( cfunc, info ): if not info['returns_fundamental']: cfunc.restype = ctypes.c_void_p elif info['returns_fundamental']: cfunc.restype = eval( info['returns_ctypes'] ) else: cfunc.restype = ctypes.c_void_p @staticmethod def _gen_prepare_args( m ): a = []; b = [] for i,p in enumerate(m['parameters']): if 'name' in p: n = p['name'] else: n = '_unnamed_%s' %i if '<' in n: n = '_TODOfixme_%s' %i if n in PYTHON_RESERVED_KEYWORDS: n += str(i) if p['fundamental']: b.append( n ) s = p['raw_type'].split() if 'default' in p: d = p['default'] if p['raw_type'] in ('float', 'double'): if d.endswith('f'): d = d[:-1] d = d.replace(' ', '.') if 'e' in d: d = 0.0 try: d = float(d) except: d = 0.0 elif ('int' in s or 'size_t' in s) and not d.isdigit(): d = 0 elif 'char' in s and '"' not in d: d = '""' elif d.lower() == 'false': d = False elif d.lower() == 'true': d = True elif 'char' in s: d = '""' elif 'float' in s or 'double' in s: d = 0.0 elif 'size_t' in s or 'int' in s or 'long' in s or 'short' in s: d = 0 elif p['raw_type'] == 'bool': d = False elif p['raw_type'] in ('void', '(template)'): d = 'NULL' else: print( p ) a.append( n+'=%s' %d ) else: b.append( '%s._pointer_'%n ) a.append( n+'=NULL' ) return a, b @staticmethod def _gen_init( m ): a, b = meta._gen_prepare_args( m ) if a: e = 'lambda _py_self_, %s, _explicit_pointer_=None: ' %(','.join(a)) else: e = 'lambda _py_self_, _explicit_pointer_=None: ' e += 'setattr(_py_self_, "_pointer_", _py_self_._%s(%s))' %( m['name'], ','.join(b) ) e += ' if not _explicit_pointer_ else ' e += 'setattr(_py_self_, "_pointer_", _explicit_pointer_)' print( e ) lamb = eval( e ); lamb._debug = e; lamb._introspect = m return lamb @staticmethod def _find_best_function( funcs ): best = funcs[0] score = -1 if len(funcs) > 1: for f in funcs: hits = 0 for p in f['parameters']: if p['fundamental']: hits += 1 if hits and hits == len( f['parameters'] ): if hits > score: score = hits best = f return best @staticmethod def _gen_method( m, f ): a, b = meta._gen_prepare_args( f ) if a: e = 'lambda _py_self_, %s: ' %(','.join(a)) else: e = 'lambda _py_self_: ' if 'static' in m and m['static']: # static in c++ is like a classmethod c = '_py_self_._%s( %s )' %( f['name'], ','.join(b) ) else: c = '_py_self_._%s( _py_self_._pointer_, %s )' %( f['name'], ','.join(b) ) if not m['returns_fundamental']: if 'returns_unknown' in m or '<' in m['returns']: c = '_VOID_POINTER_CONTAINER_( %s, name="%s" )' %(c,m['returns']) else: something = m['returns'].replace('::', '.') c = '%s( _explicit_pointer_=%s )' %(something, c) e += c; lamb = eval( e ) lamb._debug = e; lamb._introspect = f return lamb META_FUNCTIONS = [] @classmethod def function( self, info ): print('@meta.function', info['name'] ) global CTYPES_DLL if not CTYPES_DLL: CTYPES_DLL = _load_ctypes_lib( _clib_name_ ) cfunc = self._build_cfunc( info, method=False, static=True ) setattr( meta, '_%s'%info['name'], cfunc ) self._setup_return( cfunc, info ) a, b = meta._gen_prepare_args( info ) e = 'lambda %s: ' %(','.join(a)) c = 'meta._%s( %s )' %( info['name'], ','.join(b) ) if not info['returns_fundamental']: if 'returns_unknown' in info or '<' in info['returns']: c = '_VOID_POINTER_CONTAINER_( %s, name="%s" )' %(c,info['returns']) else: something = info['returns'].replace('::', '.') c = '%s( _explicit_pointer_=%s )' %(something, c) e += c lamb = eval( e ) lamb._debug = e lamb._introspect = info return lamb def _rpythonic_strip_prefixes_( prefixes ): G = globals() names = list(G.keys()) # ensure list in py3 for name in names: for prefix in prefixes: if name.startswith( prefix ): newname = name[ len(prefix) : ] if newname and newname not in G: G[ newname ] = G[ name ] _clib_name_ = 'libavformat' print('loading lib', _clib_name_) print( os.path.abspath( os.path.curdir ) ) CTYPES_DLL = _load_ctypes_lib( _clib_name_ ) assert CTYPES_DLL print( CTYPES_DLL._name ) ## macro globals ## AVPROBE_SCORE_MAX = 100 AVPROBE_PADDING_SIZE = 32 AVFMT_NOFILE = 1 AVFMT_NEEDNUMBER = 2 AVFMT_SHOW_IDS = 8 AVFMT_RAWPICTURE = 32 AVFMT_GLOBALHEADER = 64 AVFMT_NOTIMESTAMPS = 128 AVFMT_GENERIC_INDEX = 256 AVFMT_TS_DISCONT = 512 AVFMT_VARIABLE_FPS = 1024 AVFMT_NODIMENSIONS = 2048 AVFMT_NOSTREAMS = 4096 AVFMT_NOBINSEARCH = 8192 AVFMT_NOGENSEARCH = 16384 AVINDEX_KEYFRAME = 1 AV_DISPOSITION_DEFAULT = 1 AV_DISPOSITION_DUB = 2 AV_DISPOSITION_ORIGINAL = 4 AV_DISPOSITION_COMMENT = 8 AV_DISPOSITION_LYRICS = 16 AV_DISPOSITION_KARAOKE = 32 AV_DISPOSITION_FORCED = 64 AV_DISPOSITION_HEARING_IMPAIRED = 128 AV_DISPOSITION_VISUAL_IMPAIRED = 256 AV_DISPOSITION_CLEAN_EFFECTS = 512 MAX_REORDER_DELAY = 16 MAX_PROBE_PACKETS = 2500 MAX_STD_TIMEBASES = 725 AV_PROGRAM_RUNNING = 1 AVFMTCTX_NOHEADER = 1 AVFMT_NOOUTPUTLOOP = -1 AVFMT_INFINITEOUTPUTLOOP = 0 AVFMT_FLAG_GENPTS = 1 AVFMT_FLAG_IGNIDX = 2 AVFMT_FLAG_NONBLOCK = 4 AVFMT_FLAG_IGNDTS = 8 AVFMT_FLAG_NOFILLIN = 16 AVFMT_FLAG_NOPARSE = 32 AVFMT_FLAG_RTP_HINT = 64 AVFMT_FLAG_CUSTOM_IO = 128 FF_FDEBUG_TS = 1 RAW_PACKET_BUFFER_SIZE = 2500000 AVSEEK_FLAG_BACKWARD = 1 AVSEEK_FLAG_BYTE = 2 AVSEEK_FLAG_ANY = 4 AVSEEK_FLAG_FRAME = 8 ## enums ## _codecvt_result = { "__codecvt_ok" : 0, "__codecvt_partial" : 1, "__codecvt_error" : 2, "__codecvt_noconv" : 3, } AVMediaType = { "AVMEDIA_TYPE_UNKNOWN" : -1, "AVMEDIA_TYPE_VIDEO" : 0, "AVMEDIA_TYPE_AUDIO" : 1, "AVMEDIA_TYPE_DATA" : 2, "AVMEDIA_TYPE_SUBTITLE" : 3, "AVMEDIA_TYPE_ATTACHMENT" : 4, "AVMEDIA_TYPE_NB" : 5, } AVPictureType = { "AV_PICTURE_TYPE_I" : 1, "AV_PICTURE_TYPE_P" : 2, "AV_PICTURE_TYPE_B" : 3, "AV_PICTURE_TYPE_S" : 4, "AV_PICTURE_TYPE_SI" : 5, "AV_PICTURE_TYPE_SP" : 6, "AV_PICTURE_TYPE_BI" : 7, } ISupper = 0 ISlower = 1 ISalpha = 2 ISdigit = 3 ISxdigit = 4 ISspace = 5 ISprint = 6 ISgraph = 7 ISblank = 8 IScntrl = 9 ISpunct = 10 ISalnum = 11 PixelFormat = { "PIX_FMT_NONE" : -1, "PIX_FMT_YUV420P" : 0, "PIX_FMT_YUYV422" : 1, "PIX_FMT_RGB24" : 2, "PIX_FMT_BGR24" : 3, "PIX_FMT_YUV422P" : 4, "PIX_FMT_YUV444P" : 5, "PIX_FMT_YUV410P" : 6, "PIX_FMT_YUV411P" : 7, "PIX_FMT_GRAY8" : 8, "PIX_FMT_MONOWHITE" : 9, "PIX_FMT_MONOBLACK" : 10, "PIX_FMT_PAL8" : 11, "PIX_FMT_YUVJ420P" : 12, "PIX_FMT_YUVJ422P" : 13, "PIX_FMT_YUVJ444P" : 14, "PIX_FMT_XVMC_MPEG2_MC" : 15, "PIX_FMT_XVMC_MPEG2_IDCT" : 16, "PIX_FMT_UYVY422" : 17, "PIX_FMT_UYYVYY411" : 18, "PIX_FMT_BGR8" : 19, "PIX_FMT_BGR4" : 20, "PIX_FMT_BGR4_BYTE" : 21, "PIX_FMT_RGB8" : 22, "PIX_FMT_RGB4" : 23, "PIX_FMT_RGB4_BYTE" : 24, "PIX_FMT_NV12" : 25, "PIX_FMT_NV21" : 26, "PIX_FMT_ARGB" : 27, "PIX_FMT_RGBA" : 28, "PIX_FMT_ABGR" : 29, "PIX_FMT_BGRA" : 30, "PIX_FMT_GRAY16BE" : 31, "PIX_FMT_GRAY16LE" : 32, "PIX_FMT_YUV440P" : 33, "PIX_FMT_YUVJ440P" : 34, "PIX_FMT_YUVA420P" : 35, "PIX_FMT_VDPAU_H264" : 36, "PIX_FMT_VDPAU_MPEG1" : 37, "PIX_FMT_VDPAU_MPEG2" : 38, "PIX_FMT_VDPAU_WMV3" : 39, "PIX_FMT_VDPAU_VC1" : 40, "PIX_FMT_RGB48BE" : 41, "PIX_FMT_RGB48LE" : 42, "PIX_FMT_RGB565BE" : 43, "PIX_FMT_RGB565LE" : 44, "PIX_FMT_RGB555BE" : 45, "PIX_FMT_RGB555LE" : 46, "PIX_FMT_BGR565BE" : 47, "PIX_FMT_BGR565LE" : 48, "PIX_FMT_BGR555BE" : 49, "PIX_FMT_BGR555LE" : 50, "PIX_FMT_VAAPI_MOCO" : 51, "PIX_FMT_VAAPI_IDCT" : 52, "PIX_FMT_VAAPI_VLD" : 53, "PIX_FMT_YUV420P16LE" : 54, "PIX_FMT_YUV420P16BE" : 55, "PIX_FMT_YUV422P16LE" : 56, "PIX_FMT_YUV422P16BE" : 57, "PIX_FMT_YUV444P16LE" : 58, "PIX_FMT_YUV444P16BE" : 59, "PIX_FMT_VDPAU_MPEG4" : 60, "PIX_FMT_DXVA2_VLD" : 61, "PIX_FMT_RGB444LE" : 62, "PIX_FMT_RGB444BE" : 63, "PIX_FMT_BGR444LE" : 64, "PIX_FMT_BGR444BE" : 65, "PIX_FMT_Y400A" : 66, "PIX_FMT_BGR48BE" : 67, "PIX_FMT_BGR48LE" : 68, "PIX_FMT_YUV420P9BE" : 69, "PIX_FMT_YUV420P9LE" : 70, "PIX_FMT_YUV420P10BE" : 71, "PIX_FMT_YUV420P10LE" : 72, "PIX_FMT_YUV422P10BE" : 73, "PIX_FMT_YUV422P10LE" : 74, "PIX_FMT_YUV444P9BE" : 75, "PIX_FMT_YUV444P9LE" : 76, "PIX_FMT_YUV444P10BE" : 77, "PIX_FMT_YUV444P10LE" : 78, "PIX_FMT_NB" : 79, } AVSampleFormat = { "AV_SAMPLE_FMT_NONE" : -1, "AV_SAMPLE_FMT_U8" : 0, "AV_SAMPLE_FMT_S16" : 1, "AV_SAMPLE_FMT_S32" : 2, "AV_SAMPLE_FMT_FLT" : 3, "AV_SAMPLE_FMT_DBL" : 4, "AV_SAMPLE_FMT_NB" : 5, } CodecID = { "CODEC_ID_NONE" : 0, "CODEC_ID_MPEG1VIDEO" : 1, "CODEC_ID_MPEG2VIDEO" : 2, "CODEC_ID_MPEG2VIDEO_XVMC" : 3, "CODEC_ID_H261" : 4, "CODEC_ID_H263" : 5, "CODEC_ID_RV10" : 6, "CODEC_ID_RV20" : 7, "CODEC_ID_MJPEG" : 8, "CODEC_ID_MJPEGB" : 9, "CODEC_ID_LJPEG" : 10, "CODEC_ID_SP5X" : 11, "CODEC_ID_JPEGLS" : 12, "CODEC_ID_MPEG4" : 13, "CODEC_ID_RAWVIDEO" : 14, "CODEC_ID_MSMPEG4V1" : 15, "CODEC_ID_MSMPEG4V2" : 16, "CODEC_ID_MSMPEG4V3" : 17, "CODEC_ID_WMV1" : 18, "CODEC_ID_WMV2" : 19, "CODEC_ID_H263P" : 20, "CODEC_ID_H263I" : 21, "CODEC_ID_FLV1" : 22, "CODEC_ID_SVQ1" : 23, "CODEC_ID_SVQ3" : 24, "CODEC_ID_DVVIDEO" : 25, "CODEC_ID_HUFFYUV" : 26, "CODEC_ID_CYUV" : 27, "CODEC_ID_H264" : 28, "CODEC_ID_INDEO3" : 29, "CODEC_ID_VP3" : 30, "CODEC_ID_THEORA" : 31, "CODEC_ID_ASV1" : 32, "CODEC_ID_ASV2" : 33, "CODEC_ID_FFV1" : 34, "CODEC_ID_4XM" : 35, "CODEC_ID_VCR1" : 36, "CODEC_ID_CLJR" : 37, "CODEC_ID_MDEC" : 38, "CODEC_ID_ROQ" : 39, "CODEC_ID_INTERPLAY_VIDEO" : 40, "CODEC_ID_XAN_WC3" : 41, "CODEC_ID_XAN_WC4" : 42, "CODEC_ID_RPZA" : 43, "CODEC_ID_CINEPAK" : 44, "CODEC_ID_WS_VQA" : 45, "CODEC_ID_MSRLE" : 46, "CODEC_ID_MSVIDEO1" : 47, "CODEC_ID_IDCIN" : 48, "CODEC_ID_8BPS" : 49, "CODEC_ID_SMC" : 50, "CODEC_ID_FLIC" : 51, "CODEC_ID_TRUEMOTION1" : 52, "CODEC_ID_VMDVIDEO" : 53, "CODEC_ID_MSZH" : 54, "CODEC_ID_ZLIB" : 55, "CODEC_ID_QTRLE" : 56, "CODEC_ID_SNOW" : 57, "CODEC_ID_TSCC" : 58, "CODEC_ID_ULTI" : 59, "CODEC_ID_QDRAW" : 60, "CODEC_ID_VIXL" : 61, "CODEC_ID_QPEG" : 62, "CODEC_ID_PNG" : 63, "CODEC_ID_PPM" : 64, "CODEC_ID_PBM" : 65, "CODEC_ID_PGM" : 66, "CODEC_ID_PGMYUV" : 67, "CODEC_ID_PAM" : 68, "CODEC_ID_FFVHUFF" : 69, "CODEC_ID_RV30" : 70, "CODEC_ID_RV40" : 71, "CODEC_ID_VC1" : 72, "CODEC_ID_WMV3" : 73, "CODEC_ID_LOCO" : 74, "CODEC_ID_WNV1" : 75, "CODEC_ID_AASC" : 76, "CODEC_ID_INDEO2" : 77, "CODEC_ID_FRAPS" : 78, "CODEC_ID_TRUEMOTION2" : 79, "CODEC_ID_BMP" : 80, "CODEC_ID_CSCD" : 81, "CODEC_ID_MMVIDEO" : 82, "CODEC_ID_ZMBV" : 83, "CODEC_ID_AVS" : 84, "CODEC_ID_SMACKVIDEO" : 85, "CODEC_ID_NUV" : 86, "CODEC_ID_KMVC" : 87, "CODEC_ID_FLASHSV" : 88, "CODEC_ID_CAVS" : 89, "CODEC_ID_JPEG2000" : 90, "CODEC_ID_VMNC" : 91, "CODEC_ID_VP5" : 92, "CODEC_ID_VP6" : 93, "CODEC_ID_VP6F" : 94, "CODEC_ID_TARGA" : 95, "CODEC_ID_DSICINVIDEO" : 96, "CODEC_ID_TIERTEXSEQVIDEO" : 97, "CODEC_ID_TIFF" : 98, "CODEC_ID_GIF" : 99, "CODEC_ID_FFH264" : 100, "CODEC_ID_DXA" : 101, "CODEC_ID_DNXHD" : 102, "CODEC_ID_THP" : 103, "CODEC_ID_SGI" : 104, "CODEC_ID_C93" : 105, "CODEC_ID_BETHSOFTVID" : 106, "CODEC_ID_PTX" : 107, "CODEC_ID_TXD" : 108, "CODEC_ID_VP6A" : 109, "CODEC_ID_AMV" : 110, "CODEC_ID_VB" : 111, "CODEC_ID_PCX" : 112, "CODEC_ID_SUNRAST" : 113, "CODEC_ID_INDEO4" : 114, "CODEC_ID_INDEO5" : 115, "CODEC_ID_MIMIC" : 116, "CODEC_ID_RL2" : 117, "CODEC_ID_8SVX_EXP" : 118, "CODEC_ID_8SVX_FIB" : 119, "CODEC_ID_ESCAPE124" : 120, "CODEC_ID_DIRAC" : 121, "CODEC_ID_BFI" : 122, "CODEC_ID_CMV" : 123, "CODEC_ID_MOTIONPIXELS" : 124, "CODEC_ID_TGV" : 125, "CODEC_ID_TGQ" : 126, "CODEC_ID_TQI" : 127, "CODEC_ID_AURA" : 128, "CODEC_ID_AURA2" : 129, "CODEC_ID_V210X" : 130, "CODEC_ID_TMV" : 131, "CODEC_ID_V210" : 132, "CODEC_ID_DPX" : 133, "CODEC_ID_MAD" : 134, "CODEC_ID_FRWU" : 135, "CODEC_ID_FLASHSV2" : 136, "CODEC_ID_CDGRAPHICS" : 137, "CODEC_ID_R210" : 138, "CODEC_ID_ANM" : 139, "CODEC_ID_BINKVIDEO" : 140, "CODEC_ID_IFF_ILBM" : 141, "CODEC_ID_IFF_BYTERUN1" : 142, "CODEC_ID_KGV1" : 143, "CODEC_ID_YOP" : 144, "CODEC_ID_VP8" : 145, "CODEC_ID_PICTOR" : 146, "CODEC_ID_ANSI" : 147, "CODEC_ID_A64_MULTI" : 148, "CODEC_ID_A64_MULTI5" : 149, "CODEC_ID_R10K" : 150, "CODEC_ID_MXPEG" : 151, "CODEC_ID_LAGARITH" : 152, "CODEC_ID_PRORES" : 153, "CODEC_ID_JV" : 154, "CODEC_ID_DFA" : 155, "CODEC_ID_PCM_S16LE" : 65536, "CODEC_ID_PCM_S16BE" : 65537, "CODEC_ID_PCM_U16LE" : 65538, "CODEC_ID_PCM_U16BE" : 65539, "CODEC_ID_PCM_S8" : 65540, "CODEC_ID_PCM_U8" : 65541, "CODEC_ID_PCM_MULAW" : 65542, "CODEC_ID_PCM_ALAW" : 65543, "CODEC_ID_PCM_S32LE" : 65544, "CODEC_ID_PCM_S32BE" : 65545, "CODEC_ID_PCM_U32LE" : 65546, "CODEC_ID_PCM_U32BE" : 65547, "CODEC_ID_PCM_S24LE" : 65548, "CODEC_ID_PCM_S24BE" : 65549, "CODEC_ID_PCM_U24LE" : 65550, "CODEC_ID_PCM_U24BE" : 65551, "CODEC_ID_PCM_S24DAUD" : 65552, "CODEC_ID_PCM_ZORK" : 65553, "CODEC_ID_PCM_S16LE_PLANAR" : 65554, "CODEC_ID_PCM_DVD" : 65555, "CODEC_ID_PCM_F32BE" : 65556, "CODEC_ID_PCM_F32LE" : 65557, "CODEC_ID_PCM_F64BE" : 65558, "CODEC_ID_PCM_F64LE" : 65559, "CODEC_ID_PCM_BLURAY" : 65560, "CODEC_ID_PCM_LXF" : 65561, "CODEC_ID_S302M" : 65562, "CODEC_ID_ADPCM_IMA_QT" : 69632, "CODEC_ID_ADPCM_IMA_WAV" : 69633, "CODEC_ID_ADPCM_IMA_DK3" : 69634, "CODEC_ID_ADPCM_IMA_DK4" : 69635, "CODEC_ID_ADPCM_IMA_WS" : 69636, "CODEC_ID_ADPCM_IMA_SMJPEG" : 69637, "CODEC_ID_ADPCM_MS" : 69638, "CODEC_ID_ADPCM_4XM" : 69639, "CODEC_ID_ADPCM_XA" : 69640, "CODEC_ID_ADPCM_ADX" : 69641, "CODEC_ID_ADPCM_EA" : 69642, "CODEC_ID_ADPCM_G726" : 69643, "CODEC_ID_ADPCM_CT" : 69644, "CODEC_ID_ADPCM_SWF" : 69645, "CODEC_ID_ADPCM_YAMAHA" : 69646, "CODEC_ID_ADPCM_SBPRO_4" : 69647, "CODEC_ID_ADPCM_SBPRO_3" : 69648, "CODEC_ID_ADPCM_SBPRO_2" : 69649, "CODEC_ID_ADPCM_THP" : 69650, "CODEC_ID_ADPCM_IMA_AMV" : 69651, "CODEC_ID_ADPCM_EA_R1" : 69652, "CODEC_ID_ADPCM_EA_R3" : 69653, "CODEC_ID_ADPCM_EA_R2" : 69654, "CODEC_ID_ADPCM_IMA_EA_SEAD" : 69655, "CODEC_ID_ADPCM_IMA_EA_EACS" : 69656, "CODEC_ID_ADPCM_EA_XAS" : 69657, "CODEC_ID_ADPCM_EA_MAXIS_XA" : 69658, "CODEC_ID_ADPCM_IMA_ISS" : 69659, "CODEC_ID_ADPCM_G722" : 69660, "CODEC_ID_AMR_NB" : 73728, "CODEC_ID_AMR_WB" : 73729, "CODEC_ID_RA_144" : 77824, "CODEC_ID_RA_288" : 77825, "CODEC_ID_ROQ_DPCM" : 81920, "CODEC_ID_INTERPLAY_DPCM" : 81921, "CODEC_ID_XAN_DPCM" : 81922, "CODEC_ID_SOL_DPCM" : 81923, "CODEC_ID_MP2" : 86016, "CODEC_ID_MP3" : 86017, "CODEC_ID_AAC" : 86018, "CODEC_ID_AC3" : 86019, "CODEC_ID_DTS" : 86020, "CODEC_ID_VORBIS" : 86021, "CODEC_ID_DVAUDIO" : 86022, "CODEC_ID_WMAV1" : 86023, "CODEC_ID_WMAV2" : 86024, "CODEC_ID_MACE3" : 86025, "CODEC_ID_MACE6" : 86026, "CODEC_ID_VMDAUDIO" : 86027, "CODEC_ID_SONIC" : 86028, "CODEC_ID_SONIC_LS" : 86029, "CODEC_ID_FLAC" : 86030, "CODEC_ID_MP3ADU" : 86031, "CODEC_ID_MP3ON4" : 86032, "CODEC_ID_SHORTEN" : 86033, "CODEC_ID_ALAC" : 86034, "CODEC_ID_WESTWOOD_SND1" : 86035, "CODEC_ID_GSM" : 86036, "CODEC_ID_QDM2" : 86037, "CODEC_ID_COOK" : 86038, "CODEC_ID_TRUESPEECH" : 86039, "CODEC_ID_TTA" : 86040, "CODEC_ID_SMACKAUDIO" : 86041, "CODEC_ID_QCELP" : 86042, "CODEC_ID_WAVPACK" : 86043, "CODEC_ID_DSICINAUDIO" : 86044, "CODEC_ID_IMC" : 86045, "CODEC_ID_MUSEPACK7" : 86046, "CODEC_ID_MLP" : 86047, "CODEC_ID_GSM_MS" : 86048, "CODEC_ID_ATRAC3" : 86049, "CODEC_ID_VOXWARE" : 86050, "CODEC_ID_APE" : 86051, "CODEC_ID_NELLYMOSER" : 86052, "CODEC_ID_MUSEPACK8" : 86053, "CODEC_ID_SPEEX" : 86054, "CODEC_ID_WMAVOICE" : 86055, "CODEC_ID_WMAPRO" : 86056, "CODEC_ID_WMALOSSLESS" : 86057, "CODEC_ID_ATRAC3P" : 86058, "CODEC_ID_EAC3" : 86059, "CODEC_ID_SIPR" : 86060, "CODEC_ID_MP1" : 86061, "CODEC_ID_TWINVQ" : 86062, "CODEC_ID_TRUEHD" : 86063, "CODEC_ID_MP4ALS" : 86064, "CODEC_ID_ATRAC1" : 86065, "CODEC_ID_BINKAUDIO_RDFT" : 86066, "CODEC_ID_BINKAUDIO_DCT" : 86067, "CODEC_ID_AAC_LATM" : 86068, "CODEC_ID_QDMC" : 86069, "CODEC_ID_DVD_SUBTITLE" : 94208, "CODEC_ID_DVB_SUBTITLE" : 94209, "CODEC_ID_TEXT" : 94210, "CODEC_ID_XSUB" : 94211, "CODEC_ID_SSA" : 94212, "CODEC_ID_MOV_TEXT" : 94213, "CODEC_ID_HDMV_PGS_SUBTITLE" : 94214, "CODEC_ID_DVB_TELETEXT" : 94215, "CODEC_ID_SRT" : 94216, "CODEC_ID_TTF" : 98304, "CODEC_ID_PROBE" : 102400, "CODEC_ID_MPEG2TS" : 131072, "CODEC_ID_FFMETADATA" : 135168, } AVRounding = { "AV_ROUND_ZERO" : 0, "AV_ROUND_INF" : 1, "AV_ROUND_DOWN" : 2, "AV_ROUND_UP" : 3, "AV_ROUND_NEAR_INF" : 5, } AVStreamParseType = { "AVSTREAM_PARSE_NONE" : 0, "AVSTREAM_PARSE_FULL" : 1, "AVSTREAM_PARSE_HEADERS" : 2, "AVSTREAM_PARSE_TIMESTAMPS" : 3, "AVSTREAM_PARSE_FULL_ONCE" : 4, } AVLockOp = { "AV_LOCK_CREATE" : 0, "AV_LOCK_OBTAIN" : 1, "AV_LOCK_RELEASE" : 2, "AV_LOCK_DESTROY" : 3, } Motion_Est_ID = { "ME_ZERO" : 1, "ME_FULL" : 2, "ME_LOG" : 3, "ME_PHODS" : 4, "ME_EPZS" : 5, "ME_X1" : 6, "ME_HEX" : 7, "ME_UMH" : 8, "ME_ITER" : 9, "ME_TESA" : 10, } AVDiscard = { "AVDISCARD_NONE" : -16, "AVDISCARD_DEFAULT" : 0, "AVDISCARD_NONREF" : 8, "AVDISCARD_BIDIR" : 16, "AVDISCARD_NONKEY" : 32, "AVDISCARD_ALL" : 48, } AVColorPrimaries = { "AVCOL_PRI_BT709" : 1, "AVCOL_PRI_UNSPECIFIED" : 2, "AVCOL_PRI_BT470M" : 4, "AVCOL_PRI_BT470BG" : 5, "AVCOL_PRI_SMPTE170M" : 6, "AVCOL_PRI_SMPTE240M" : 7, "AVCOL_PRI_FILM" : 8, "AVCOL_PRI_NB" : 9, } AVColorTransferCharacteristic = { "AVCOL_TRC_BT709" : 1, "AVCOL_TRC_UNSPECIFIED" : 2, "AVCOL_TRC_GAMMA22" : 4, "AVCOL_TRC_GAMMA28" : 5, "AVCOL_TRC_NB" : 6, } AVColorSpace = { "AVCOL_SPC_RGB" : 0, "AVCOL_SPC_BT709" : 1, "AVCOL_SPC_UNSPECIFIED" : 2, "AVCOL_SPC_FCC" : 4, "AVCOL_SPC_BT470BG" : 5, "AVCOL_SPC_SMPTE170M" : 6, "AVCOL_SPC_SMPTE240M" : 7, "AVCOL_SPC_NB" : 8, } AVColorRange = { "AVCOL_RANGE_UNSPECIFIED" : 0, "AVCOL_RANGE_MPEG" : 1, "AVCOL_RANGE_JPEG" : 2, "AVCOL_RANGE_NB" : 3, } AVChromaLocation = { "AVCHROMA_LOC_UNSPECIFIED" : 0, "AVCHROMA_LOC_LEFT" : 1, "AVCHROMA_LOC_CENTER" : 2, "AVCHROMA_LOC_TOPLEFT" : 3, "AVCHROMA_LOC_TOP" : 4, "AVCHROMA_LOC_BOTTOMLEFT" : 5, "AVCHROMA_LOC_BOTTOM" : 6, "AVCHROMA_LOC_NB" : 7, } AVLPCType = { "AV_LPC_TYPE_DEFAULT" : -1, "AV_LPC_TYPE_NONE" : 0, "AV_LPC_TYPE_FIXED" : 1, "AV_LPC_TYPE_LEVINSON" : 2, "AV_LPC_TYPE_CHOLESKY" : 3, "AV_LPC_TYPE_NB" : 4, } AVAudioServiceType = { "AV_AUDIO_SERVICE_TYPE_MAIN" : 0, "AV_AUDIO_SERVICE_TYPE_EFFECTS" : 1, "AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED" : 2, "AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED" : 3, "AV_AUDIO_SERVICE_TYPE_DIALOGUE" : 4, "AV_AUDIO_SERVICE_TYPE_COMMENTARY" : 5, "AV_AUDIO_SERVICE_TYPE_EMERGENCY" : 6, "AV_AUDIO_SERVICE_TYPE_VOICE_OVER" : 7, "AV_AUDIO_SERVICE_TYPE_KARAOKE" : 8, "AV_AUDIO_SERVICE_TYPE_NB" : 9, } AVPacketSideDataType = { "AV_PKT_DATA_PALETTE" : 0, } AVSubtitleType = { "SUBTITLE_NONE" : 0, "SUBTITLE_BITMAP" : 1, "SUBTITLE_TEXT" : 2, "SUBTITLE_ASS" : 3, } FP_NAN = 0 FP_INFINITE = 1 FP_ZERO = 2 FP_SUBNORMAL = 3 FP_NORMAL = 4 IEEE_ = -1 SVID_ = 0 XOPEN_ = 1 POSIX_ = 2 ISOC_ = 3 ## simple enums ## RPYTHONIC_GLOBAL_ENUMS = { "ISupper" : 0, "ISlower" : 1, "ISalpha" : 2, "ISdigit" : 3, "ISxdigit" : 4, "ISspace" : 5, "ISprint" : 6, "ISgraph" : 7, "ISblank" : 8, "IScntrl" : 9, "ISpunct" : 10, "ISalnum" : 11, "FP_NAN" : 0, "FP_INFINITE" : 1, "FP_ZERO" : 2, "FP_SUBNORMAL" : 3, "FP_NORMAL" : 4, "IEEE_" : -1, "SVID_" : 0, "XOPEN_" : 1, "POSIX_" : 2, "ISOC_" : 3, } class __fsid_t(_rpythonic_struct_): _array_wrapper_ = True class timespec(_rpythonic_struct_): pass class tm(_rpythonic_struct_): pass class itimerspec(_rpythonic_struct_): pass class sigevent(_rpythonic_struct_): pass class __locale_struct(_rpythonic_struct_): _array_wrapper_ = True class __locale_data(_rpythonic_struct_): pass class __mbstate_t(_rpythonic_struct_): pass class __value(ctypes.Union): pass class _G_fpos_t(_rpythonic_struct_): pass class _G_fpos64_t(_rpythonic_struct_): pass class _IO_jump_t(_rpythonic_struct_): pass class _IO_marker(_rpythonic_struct_): pass class _IO_FILE(_rpythonic_struct_): _array_wrapper_ = True class _IO_FILE_plus(_rpythonic_struct_): pass class imaxdiv_t(_rpythonic_struct_): pass class exception(_rpythonic_struct_): pass class wait(ctypes.Union): pass class __wait_terminated(_rpythonic_struct_): pass class __wait_stopped(_rpythonic_struct_): pass class __WAIT_STATUS(ctypes.Union): pass class div_t(_rpythonic_struct_): pass class ldiv_t(_rpythonic_struct_): pass class lldiv_t(_rpythonic_struct_): pass class __sigset_t(_rpythonic_struct_): _array_wrapper_ = True class timeval(_rpythonic_struct_): pass class fd_set(_rpythonic_struct_): _array_wrapper_ = True class pthread_attr_t(ctypes.Union): pass class __pthread_internal_list(_rpythonic_struct_): pass class pthread_mutex_t(ctypes.Union): pass class __pthread_mutex_s(_rpythonic_struct_): pass class pthread_mutexattr_t(ctypes.Union): pass class pthread_cond_t(ctypes.Union): pass class pthread_condattr_t(ctypes.Union): pass class pthread_rwlock_t(ctypes.Union): pass class __data(_rpythonic_struct_): pass class pthread_rwlockattr_t(ctypes.Union): pass class pthread_barrier_t(ctypes.Union): pass class pthread_barrierattr_t(ctypes.Union): pass class random_data(_rpythonic_struct_): pass class drand48_data(_rpythonic_struct_): _array_wrapper_ = True class AVRational(_rpythonic_struct_): pass class AVExtFloat(_rpythonic_struct_): _array_wrapper_ = True class AVClass(_rpythonic_struct_): pass class AVOption(_rpythonic_struct_): pass class AVDictionaryEntry(_rpythonic_struct_): pass class AVDictionary(_rpythonic_struct_): pass class RcOverride(_rpythonic_struct_): pass class AVPanScan(_rpythonic_struct_): _array_wrapper_ = True class AVPacket(_rpythonic_struct_): pass class side_data(_rpythonic_struct_): pass class AVFrame(_rpythonic_struct_): _array_wrapper_ = True class AVCodecContext(_rpythonic_struct_): _array_wrapper_ = True class AVProfile(_rpythonic_struct_): pass class AVCodec(_rpythonic_struct_): pass class AVHWAccel(_rpythonic_struct_): pass class AVPicture(_rpythonic_struct_): _array_wrapper_ = True class AVPaletteControl(_rpythonic_struct_): _array_wrapper_ = True class AVSubtitleRect(_rpythonic_struct_): pass class AVSubtitle(_rpythonic_struct_): pass class ReSampleContext(_rpythonic_struct_): pass class AVResampleContext(_rpythonic_struct_): pass class AVCodecParserContext(_rpythonic_struct_): _array_wrapper_ = True class AVCodecParser(_rpythonic_struct_): _array_wrapper_ = True class AVBitStreamFilterContext(_rpythonic_struct_): pass class AVBitStreamFilter(_rpythonic_struct_): pass class AVIOContext(_rpythonic_struct_): pass class URLContext(_rpythonic_struct_): pass class URLProtocol(_rpythonic_struct_): pass class URLPollEntry(_rpythonic_struct_): pass class AVMetadataConv(_rpythonic_struct_): pass class AVFrac(_rpythonic_struct_): pass class AVCodecTag(_rpythonic_struct_): pass class AVProbeData(_rpythonic_struct_): pass class AVFormatParameters(_rpythonic_struct_): pass class AVOutputFormat(_rpythonic_struct_): pass class AVInputFormat(_rpythonic_struct_): pass class AVIndexEntry(_rpythonic_struct_): pass class AVStream(_rpythonic_struct_): _array_wrapper_ = True class info(_rpythonic_struct_): _array_wrapper_ = True class AVProgram(_rpythonic_struct_): pass class AVChapter(_rpythonic_struct_): pass class AVFormatContext(_rpythonic_struct_): _array_wrapper_ = True class AVPacketList(_rpythonic_struct_): pass ## union and structures ## __freeze_rpythonic_struct( __fsid_t, [ ( "__val", ( ctypes.c_int * 2 ) ), ]) __freeze_rpythonic_struct( timespec, [ ( "tv_sec", ctypes.c_int64 ), ( "tv_nsec", ctypes.c_int64 ), ]) __freeze_rpythonic_struct( tm, [ ( "tm_sec", ctypes.c_int ), ( "tm_min", ctypes.c_int ), ( "tm_hour", ctypes.c_int ), ( "tm_mday", ctypes.c_int ), ( "tm_mon", ctypes.c_int ), ( "tm_year", ctypes.c_int ), ( "tm_wday", ctypes.c_int ), ( "tm_yday", ctypes.c_int ), ( "tm_isdst", ctypes.c_int ), ( "tm_gmtoff", ctypes.c_int64 ), ( "tm_zone", ctypes.POINTER(ctypes.c_char) ), ]) __freeze_rpythonic_struct( itimerspec, [ ( "it_interval", timespec ), ( "it_value", timespec ), ]) __freeze_rpythonic_struct( sigevent, [ ]) __freeze_rpythonic_struct( __locale_data, [ ]) __freeze_rpythonic_struct( __locale_struct, [ ( "__locales", ctypes.POINTER(( __locale_data * 13 )) ), ( "__ctype_b", ctypes.POINTER(ctypes.c_uint16) ), ( "__ctype_tolower", ctypes.POINTER(ctypes.c_int) ), ( "__ctype_toupper", ctypes.POINTER(ctypes.c_int) ), ( "__names", ctypes.POINTER(( ctypes.c_char * 13 )) ), ]) __freeze_rpythonic_struct( __value, [ ( "__wch", ctypes.c_uint ), ( "__wchb", ( ctypes.c_char * 4 ) ), ]) __freeze_rpythonic_struct( __mbstate_t, [ ( "__count", ctypes.c_int ), ( "__value", __value ), ]) __freeze_rpythonic_struct( _G_fpos_t, [ ( "__pos", ctypes.c_int64 ), ( "__state", __mbstate_t ), ]) __freeze_rpythonic_struct( _G_fpos64_t, [ ( "__pos", ctypes.c_int64 ), ( "__state", __mbstate_t ), ]) __freeze_rpythonic_struct( _IO_jump_t, [ ]) __freeze_rpythonic_struct( _IO_marker, [ ( "_next", ctypes.POINTER(_IO_marker) ), ( "_sbuf", ctypes.POINTER(_IO_FILE) ), ( "_pos", ctypes.c_int ), ]) __freeze_rpythonic_struct( _IO_FILE, [ ( "_flags", ctypes.c_int ), ( "_IO_read_ptr", ctypes.POINTER(ctypes.c_char) ), ( "_IO_read_end", ctypes.POINTER(ctypes.c_char) ), ( "_IO_read_base", ctypes.POINTER(ctypes.c_char) ), ( "_IO_write_base", ctypes.POINTER(ctypes.c_char) ), ( "_IO_write_ptr", ctypes.POINTER(ctypes.c_char) ), ( "_IO_write_end", ctypes.POINTER(ctypes.c_char) ), ( "_IO_buf_base", ctypes.POINTER(ctypes.c_char) ), ( "_IO_buf_end", ctypes.POINTER(ctypes.c_char) ), ( "_IO_save_base", ctypes.POINTER(ctypes.c_char) ), ( "_IO_backup_base", ctypes.POINTER(ctypes.c_char) ), ( "_IO_save_end", ctypes.POINTER(ctypes.c_char) ), ( "_markers", ctypes.POINTER(_IO_marker) ), ( "_chain", ctypes.POINTER(_IO_FILE) ), ( "_fileno", ctypes.c_int ), ( "_flags2", ctypes.c_int ), ( "_old_offset", ctypes.c_int64 ), ( "_cur_column", ctypes.c_ushort ), ( "_vtable_offset", ctypes.c_char ), ( "_shortbuf", ( ctypes.c_char * 1 ) ), ( "_lock", ctypes.POINTER(ctypes.c_void_p) ), ( "_offset", ctypes.c_int64 ), ( "__pad1", ctypes.POINTER(ctypes.c_void_p) ), ( "__pad2", ctypes.POINTER(ctypes.c_void_p) ), ( "__pad3", ctypes.POINTER(ctypes.c_void_p) ), ( "__pad4", ctypes.POINTER(ctypes.c_void_p) ), ( "__pad5", ctypes.c_uint64 ), ( "_mode", ctypes.c_int ), ( "_unused2", ctypes.c_char ), ]) __freeze_rpythonic_struct( _IO_FILE_plus, [ ]) __freeze_rpythonic_struct( imaxdiv_t, [ ( "quot", ctypes.c_int64 ), ( "rem", ctypes.c_int64 ), ]) __freeze_rpythonic_struct( exception, [ ( "C_type", ctypes.c_int ), ( "name", ctypes.POINTER(ctypes.c_char) ), ( "arg1", ctypes.c_double ), ( "arg2", ctypes.c_double ), ( "retval", ctypes.c_double ), ]) __freeze_rpythonic_struct( __wait_terminated, [ ( "__w_termsig", ctypes.c_uint ), ( "__w_coredump", ctypes.c_uint ), ( "__w_retcode", ctypes.c_uint ), #opaque-warning# <rpythonic.rpythonic.SomeThing object at 0x2eddb10> ]) __freeze_rpythonic_struct( __wait_stopped, [ ( "__w_stopval", ctypes.c_uint ), ( "__w_stopsig", ctypes.c_uint ), #opaque-warning# <rpythonic.rpythonic.SomeThing object at 0x2edde10> ]) __freeze_rpythonic_struct( wait, [ ( "w_status", ctypes.c_int ), ( "__wait_terminated", __wait_terminated ), ( "__wait_stopped", __wait_stopped ), ]) __freeze_rpythonic_struct( __WAIT_STATUS, [ ( "__uptr", ctypes.POINTER(wait) ), ( "__iptr", ctypes.POINTER(ctypes.c_int) ), ]) __freeze_rpythonic_struct( div_t, [ ( "quot", ctypes.c_int ), ( "rem", ctypes.c_int ), ]) __freeze_rpythonic_struct( ldiv_t, [ ( "quot", ctypes.c_int64 ), ( "rem", ctypes.c_int64 ), ]) __freeze_rpythonic_struct( lldiv_t, [ ( "quot", ctypes.c_longlong ), ( "rem", ctypes.c_longlong ), ]) __freeze_rpythonic_struct( __sigset_t, [ ( "__val", ctypes.c_uint64 ), ]) __freeze_rpythonic_struct( timeval, [ ( "tv_sec", ctypes.c_int64 ), ( "tv_usec", ctypes.c_int64 ), ]) __freeze_rpythonic_struct( fd_set, [ ( "__fds_bits", ctypes.c_int64 ), ]) __freeze_rpythonic_struct( pthread_attr_t, [ ( "__size", ( ctypes.c_char * 56 ) ), ( "__align", ctypes.c_int64 ), ]) __freeze_rpythonic_struct( __pthread_internal_list, [ ( "__prev", ctypes.POINTER(__pthread_internal_list) ), ( "__next", ctypes.POINTER(__pthread_internal_list) ), ]) __freeze_rpythonic_struct( __pthread_mutex_s, [ ( "__lock", ctypes.c_int ), ( "__count", ctypes.c_uint ), ( "__owner", ctypes.c_int ), ( "__nusers", ctypes.c_uint ), ( "__kind", ctypes.c_int ), ( "__spins", ctypes.c_int ), ( "__list", __pthread_internal_list ), ]) __freeze_rpythonic_struct( pthread_mutex_t, [ ( "__data", __pthread_mutex_s ), ( "__size", ( ctypes.c_char * 40 ) ), ( "__align", ctypes.c_int64 ), ]) __freeze_rpythonic_struct( pthread_mutexattr_t, [ ( "__size", ( ctypes.c_char * 4 ) ), ( "__align", ctypes.c_int ), ]) __freeze_rpythonic_struct( __data, [ ( "__lock", ctypes.c_int ), ( "__nr_readers", ctypes.c_uint ), ( "__readers_wakeup", ctypes.c_uint ), ( "__writer_wakeup", ctypes.c_uint ), ( "__nr_readers_queued", ctypes.c_uint ), ( "__nr_writers_queued", ctypes.c_uint ), ( "__writer", ctypes.c_int ), ( "__shared", ctypes.c_int ), ( "__pad1", ctypes.c_uint64 ), ( "__pad2", ctypes.c_uint64 ), ( "__flags", ctypes.c_uint ), ]) __freeze_rpythonic_struct( pthread_cond_t, [ ( "__data", __data ), ( "__size", ( ctypes.c_char * 48 ) ), ( "__align", ctypes.c_longlong ), ]) __freeze_rpythonic_struct( pthread_condattr_t, [ ( "__size", ( ctypes.c_char * 4 ) ), ( "__align", ctypes.c_int ), ]) __freeze_rpythonic_struct( pthread_rwlock_t, [ ( "__data", __data ), ( "__size", ( ctypes.c_char * 56 ) ), ( "__align", ctypes.c_int64 ), ]) __freeze_rpythonic_struct( pthread_rwlockattr_t, [ ( "__size", ( ctypes.c_char * 8 ) ), ( "__align", ctypes.c_int64 ), ]) __freeze_rpythonic_struct( pthread_barrier_t, [ ( "__size", ( ctypes.c_char * 32 ) ), ( "__align", ctypes.c_int64 ), ]) __freeze_rpythonic_struct( pthread_barrierattr_t, [ ( "__size", ( ctypes.c_char * 4 ) ), ( "__align", ctypes.c_int ), ]) __freeze_rpythonic_struct( random_data, [ ( "fptr", ctypes.POINTER(ctypes.c_int32) ), ( "rptr", ctypes.POINTER(ctypes.c_int32) ), ( "state", ctypes.POINTER(ctypes.c_int32) ), ( "rand_type", ctypes.c_int ), ( "rand_deg", ctypes.c_int ), ( "rand_sep", ctypes.c_int ), ( "end_ptr", ctypes.POINTER(ctypes.c_int32) ), ]) __freeze_rpythonic_struct( drand48_data, [ ( "__x", ( ctypes.c_uint16 * 3 ) ), ( "__old_x", ( ctypes.c_uint16 * 3 ) ), ( "__c", ctypes.c_uint16 ), ( "__init", ctypes.c_uint16 ), ( "__a", ctypes.c_ulonglong ), ]) __freeze_rpythonic_struct( AVRational, [ ( "num", ctypes.c_int ), ( "den", ctypes.c_int ), ]) __freeze_rpythonic_struct( AVExtFloat, [ ( "exponent", ( ctypes.c_uint8 * 2 ) ), ( "mantissa", ( ctypes.c_uint8 * 8 ) ), ]) __freeze_rpythonic_struct( AVOption, [ ]) __freeze_rpythonic_struct( AVClass, [ ( "class_name", ctypes.POINTER(ctypes.c_char) ), ( "item_name", ctypes.POINTER(ctypes.c_void_p) ), ( "option", ctypes.POINTER(AVOption) ), ( "version", ctypes.c_int ), ( "log_level_offset_offset", ctypes.c_int ), ( "parent_log_context_offset", ctypes.c_int ), ( "opt_find", ctypes.POINTER(ctypes.c_void_p) ), ]) __freeze_rpythonic_struct( AVDictionaryEntry, [ ( "key", ctypes.POINTER(ctypes.c_char) ), ( "value", ctypes.POINTER(ctypes.c_char) ), ]) __freeze_rpythonic_struct( AVDictionary, [ ]) __freeze_rpythonic_struct( RcOverride, [ ( "start_frame", ctypes.c_int ), ( "end_frame", ctypes.c_int ), ( "qscale", ctypes.c_int ), ( "quality_factor", ctypes.c_float ), ]) __freeze_rpythonic_struct( AVPanScan, [ ( "C_id", ctypes.c_int ), ( "width", ctypes.c_int ), ( "height", ctypes.c_int ), ( "position", ( ctypes.c_int16 * 3 ) ), ]) __freeze_rpythonic_struct( side_data, [ ( "data", ctypes.POINTER(ctypes.c_uint8) ), ( "size", ctypes.c_int ), ( "C_type", ctypes.c_int ), ]) __freeze_rpythonic_struct( AVPacket, [ ( "pts", ctypes.c_int64 ), ( "dts", ctypes.c_int64 ), ( "data", ctypes.POINTER(ctypes.c_uint8) ), ( "size", ctypes.c_int ), ( "stream_index", ctypes.c_int ), ( "flags", ctypes.c_int ), ( "side_data", ctypes.POINTER(side_data) ), ( "side_data_elems", ctypes.c_int ), ( "duration", ctypes.c_int ), ( "destruct", ctypes.c_void_p ), ( "priv", ctypes.POINTER(ctypes.c_void_p) ), ( "pos", ctypes.c_int64 ), ( "convergence_duration", ctypes.c_int64 ), ]) __freeze_rpythonic_struct( AVFrame, [ ( "data", ctypes.POINTER(( ctypes.c_uint8 * 4 )) ), ( "linesize", ( ctypes.c_int * 4 ) ), ( "base", ctypes.POINTER(( ctypes.c_uint8 * 4 )) ), ( "key_frame", ctypes.c_int ), ( "pict_type", ctypes.c_int ), ( "pts", ctypes.c_int64 ), ( "coded_picture_number", ctypes.c_int ), ( "display_picture_number", ctypes.c_int ), ( "quality", ctypes.c_int ), ( "age", ctypes.c_int ), ( "reference", ctypes.c_int ), ( "qscale_table", ctypes.POINTER(ctypes.c_int8) ), ( "qstride", ctypes.c_int ), ( "mbskip_table", ctypes.POINTER(ctypes.c_uint8) ), ( "motion_val", ctypes.POINTER(( ctypes.c_int16 * 2 )) ), ( "mb_type", ctypes.POINTER(ctypes.c_uint32) ), ( "motion_subsample_log2", ctypes.c_uint8 ), ( "opaque", ctypes.POINTER(ctypes.c_void_p) ), ( "error", ( ctypes.c_uint64 * 4 ) ), ( "C_type", ctypes.c_int ), ( "repeat_pict", ctypes.c_int ), ( "qscale_type", ctypes.c_int ), ( "interlaced_frame", ctypes.c_int ), ( "top_field_first", ctypes.c_int ), ( "pan_scan", ctypes.POINTER(AVPanScan) ), ( "palette_has_changed", ctypes.c_int ), ( "buffer_hints", ctypes.c_int ), ( "dct_coeff", ctypes.POINTER(ctypes.c_short) ), ( "ref_index", ctypes.POINTER(( ctypes.c_int8 * 2 )) ), ( "reordered_opaque", ctypes.c_int64 ), ( "hwaccel_picture_private", ctypes.POINTER(ctypes.c_void_p) ), ( "pkt_pts", ctypes.c_int64 ), ( "pkt_dts", ctypes.c_int64 ), ( "owner", ctypes.POINTER(AVCodecContext) ), ( "thread_opaque", ctypes.POINTER(ctypes.c_void_p) ), ]) __freeze_rpythonic_struct( AVProfile, [ ( "profile", ctypes.c_int ), ( "name", ctypes.POINTER(ctypes.c_char) ), ]) __freeze_rpythonic_struct( AVCodec, [ ( "name", ctypes.POINTER(ctypes.c_char) ), ( "C_type", ctypes.c_int ), ( "C_id", ctypes.c_int ), ( "priv_data_size", ctypes.c_int ), ( "init", ctypes.c_void_p ), ( "encode", ctypes.c_void_p ), ( "close", ctypes.c_void_p ), ( "decode", ctypes.c_void_p ), ( "capabilities", ctypes.c_int ), ( "next", ctypes.POINTER(AVCodec) ), ( "flush", ctypes.c_void_p ), ( "supported_framerates", ctypes.POINTER(AVRational) ), ( "pix_fmts", ctypes.POINTER(ctypes.c_int) ), ( "long_name", ctypes.POINTER(ctypes.c_char) ), ( "supported_samplerates", ctypes.POINTER(ctypes.c_int) ), ( "sample_fmts", ctypes.POINTER(ctypes.c_int) ), ( "channel_layouts", ctypes.POINTER(ctypes.c_int64) ), ( "max_lowres", ctypes.c_uint8 ), ( "priv_class", ctypes.POINTER(AVClass) ), ( "profiles", ctypes.POINTER(AVProfile) ), ( "init_thread_copy", ctypes.c_void_p ), ( "update_thread_context", ctypes.c_void_p ), ]) __freeze_rpythonic_struct( AVPaletteControl, [ ( "palette_changed", ctypes.c_int ), ( "palette", ( ctypes.c_uint * 256 ) ), ]) __freeze_rpythonic_struct( AVHWAccel, [ ( "name", ctypes.POINTER(ctypes.c_char) ), ( "C_type", ctypes.c_int ), ( "C_id", ctypes.c_int ), ( "pix_fmt", ctypes.c_int ), ( "capabilities", ctypes.c_int ), ( "next", ctypes.POINTER(AVHWAccel) ), ( "start_frame", ctypes.c_void_p ), ( "decode_slice", ctypes.c_void_p ), ( "end_frame", ctypes.c_void_p ), ( "priv_data_size", ctypes.c_int ), ]) __freeze_rpythonic_struct( AVCodecContext, [ ( "av_class", ctypes.POINTER(AVClass) ), ( "bit_rate", ctypes.c_int ), ( "bit_rate_tolerance", ctypes.c_int ), ( "flags", ctypes.c_int ), ( "sub_id", ctypes.c_int ), ( "me_method", ctypes.c_int ), ( "extradata", ctypes.POINTER(ctypes.c_uint8) ), ( "extradata_size", ctypes.c_int ), ( "time_base", AVRational ), ( "width", ctypes.c_int ), ( "height", ctypes.c_int ), ( "gop_size", ctypes.c_int ), ( "pix_fmt", ctypes.c_int ), ( "draw_horiz_band", ctypes.c_void_p ), ( "sample_rate", ctypes.c_int ), ( "channels", ctypes.c_int ), ( "sample_fmt", ctypes.c_int ), ( "frame_size", ctypes.c_int ), ( "frame_number", ctypes.c_int ), ( "delay", ctypes.c_int ), ( "qcompress", ctypes.c_float ), ( "qblur", ctypes.c_float ), ( "qmin", ctypes.c_int ), ( "qmax", ctypes.c_int ), ( "max_qdiff", ctypes.c_int ), ( "max_b_frames", ctypes.c_int ), ( "b_quant_factor", ctypes.c_float ), ( "rc_strategy", ctypes.c_int ), ( "b_frame_strategy", ctypes.c_int ), ( "codec", ctypes.POINTER(AVCodec) ), ( "priv_data", ctypes.POINTER(ctypes.c_void_p) ), ( "rtp_payload_size", ctypes.c_int ), ( "rtp_callback", ctypes.c_void_p ), ( "mv_bits", ctypes.c_int ), ( "header_bits", ctypes.c_int ), ( "i_tex_bits", ctypes.c_int ), ( "p_tex_bits", ctypes.c_int ), ( "i_count", ctypes.c_int ), ( "p_count", ctypes.c_int ), ( "skip_count", ctypes.c_int ), ( "misc_bits", ctypes.c_int ), ( "frame_bits", ctypes.c_int ), ( "opaque", ctypes.POINTER(ctypes.c_void_p) ), ( "codec_name", ( ctypes.c_char * 32 ) ), ( "codec_type", ctypes.c_int ), ( "codec_id", ctypes.c_int ), ( "codec_tag", ctypes.c_uint ), ( "workaround_bugs", ctypes.c_int ), ( "luma_elim_threshold", ctypes.c_int ), ( "chroma_elim_threshold", ctypes.c_int ), ( "strict_std_compliance", ctypes.c_int ), ( "b_quant_offset", ctypes.c_float ), ( "error_recognition", ctypes.c_int ), ( "get_buffer", ctypes.c_void_p ), ( "release_buffer", ctypes.c_void_p ), ( "has_b_frames", ctypes.c_int ), ( "block_align", ctypes.c_int ), ( "parse_only", ctypes.c_int ), ( "mpeg_quant", ctypes.c_int ), ( "stats_out", ctypes.POINTER(ctypes.c_char) ), ( "stats_in", ctypes.POINTER(ctypes.c_char) ), ( "rc_qsquish", ctypes.c_float ), ( "rc_qmod_amp", ctypes.c_float ), ( "rc_qmod_freq", ctypes.c_int ), ( "rc_override", ctypes.POINTER(RcOverride) ), ( "rc_override_count", ctypes.c_int ), ( "rc_eq", ctypes.POINTER(ctypes.c_char) ), ( "rc_max_rate", ctypes.c_int ), ( "rc_min_rate", ctypes.c_int ), ( "rc_buffer_size", ctypes.c_int ), ( "rc_buffer_aggressivity", ctypes.c_float ), ( "i_quant_factor", ctypes.c_float ), ( "i_quant_offset", ctypes.c_float ), ( "rc_initial_cplx", ctypes.c_float ), ( "dct_algo", ctypes.c_int ), ( "lumi_masking", ctypes.c_float ), ( "temporal_cplx_masking", ctypes.c_float ), ( "spatial_cplx_masking", ctypes.c_float ), ( "p_masking", ctypes.c_float ), ( "dark_masking", ctypes.c_float ), ( "idct_algo", ctypes.c_int ), ( "slice_count", ctypes.c_int ), ( "slice_offset", ctypes.POINTER(ctypes.c_int) ), ( "error_concealment", ctypes.c_int ), ( "dsp_mask", ctypes.c_void_p ), ( "bits_per_coded_sample", ctypes.c_int ), ( "prediction_method", ctypes.c_int ), ( "sample_aspect_ratio", AVRational ), ( "coded_frame", ctypes.POINTER(AVFrame) ), ( "debug", ctypes.c_int ), ( "debug_mv", ctypes.c_int ), ( "error", ( ctypes.c_uint64 * 4 ) ), ( "me_cmp", ctypes.c_int ), ( "me_sub_cmp", ctypes.c_int ), ( "mb_cmp", ctypes.c_int ), ( "ildct_cmp", ctypes.c_int ), ( "dia_size", ctypes.c_int ), ( "last_predictor_count", ctypes.c_int ), ( "pre_me", ctypes.c_int ), ( "me_pre_cmp", ctypes.c_int ), ( "pre_dia_size", ctypes.c_int ), ( "me_subpel_quality", ctypes.c_int ), ( "get_format", ctypes.c_void_p ), ( "dtg_active_format", ctypes.c_int ), ( "me_range", ctypes.c_int ), ( "intra_quant_bias", ctypes.c_int ), ( "inter_quant_bias", ctypes.c_int ), ( "color_table_id", ctypes.c_int ), ( "internal_buffer_count", ctypes.c_int ), ( "internal_buffer", ctypes.POINTER(ctypes.c_void_p) ), ( "global_quality", ctypes.c_int ), ( "coder_type", ctypes.c_int ), ( "context_model", ctypes.c_int ), ( "slice_flags", ctypes.c_int ), ( "xvmc_acceleration", ctypes.c_int ), ( "mb_decision", ctypes.c_int ), ( "intra_matrix", ctypes.POINTER(ctypes.c_uint16) ), ( "inter_matrix", ctypes.POINTER(ctypes.c_uint16) ), ( "stream_codec_tag", ctypes.c_uint ), ( "scenechange_threshold", ctypes.c_int ), ( "lmin", ctypes.c_int ), ( "lmax", ctypes.c_int ), ( "palctrl", ctypes.POINTER(AVPaletteControl) ), ( "noise_reduction", ctypes.c_int ), ( "reget_buffer", ctypes.c_void_p ), ( "rc_initial_buffer_occupancy", ctypes.c_int ), ( "inter_threshold", ctypes.c_int ), ( "flags2", ctypes.c_int ), ( "error_rate", ctypes.c_int ), ( "antialias_algo", ctypes.c_int ), ( "quantizer_noise_shaping", ctypes.c_int ), ( "thread_count", ctypes.c_int ), ( "execute", ctypes.c_void_p ), ( "thread_opaque", ctypes.POINTER(ctypes.c_void_p) ), ( "me_threshold", ctypes.c_int ), ( "mb_threshold", ctypes.c_int ), ( "intra_dc_precision", ctypes.c_int ), ( "nsse_weight", ctypes.c_int ), ( "skip_top", ctypes.c_int ), ( "skip_bottom", ctypes.c_int ), ( "profile", ctypes.c_int ), ( "level", ctypes.c_int ), ( "lowres", ctypes.c_int ), ( "coded_width", ctypes.c_int ), ( "coded_height", ctypes.c_int ), ( "frame_skip_threshold", ctypes.c_int ), ( "frame_skip_factor", ctypes.c_int ), ( "frame_skip_exp", ctypes.c_int ), ( "frame_skip_cmp", ctypes.c_int ), ( "border_masking", ctypes.c_float ), ( "mb_lmin", ctypes.c_int ), ( "mb_lmax", ctypes.c_int ), ( "me_penalty_compensation", ctypes.c_int ), ( "skip_loop_filter", ctypes.c_int ), ( "skip_idct", ctypes.c_int ), ( "skip_frame", ctypes.c_int ), ( "bidir_refine", ctypes.c_int ), ( "brd_scale", ctypes.c_int ), ( "crf", ctypes.c_float ), ( "cqp", ctypes.c_int ), ( "keyint_min", ctypes.c_int ), ( "refs", ctypes.c_int ), ( "chromaoffset", ctypes.c_int ), ( "bframebias", ctypes.c_int ), ( "trellis", ctypes.c_int ), ( "complexityblur", ctypes.c_float ), ( "deblockalpha", ctypes.c_int ), ( "deblockbeta", ctypes.c_int ), ( "partitions", ctypes.c_int ), ( "directpred", ctypes.c_int ), ( "cutoff", ctypes.c_int ), ( "scenechange_factor", ctypes.c_int ), ( "mv0_threshold", ctypes.c_int ), ( "b_sensitivity", ctypes.c_int ), ( "compression_level", ctypes.c_int ), ( "min_prediction_order", ctypes.c_int ), ( "max_prediction_order", ctypes.c_int ), ( "lpc_coeff_precision", ctypes.c_int ), ( "prediction_order_method", ctypes.c_int ), ( "min_partition_order", ctypes.c_int ), ( "max_partition_order", ctypes.c_int ), ( "timecode_frame_start", ctypes.c_int64 ), ( "request_channels", ctypes.c_int ), ( "drc_scale", ctypes.c_float ), ( "reordered_opaque", ctypes.c_int64 ), ( "bits_per_raw_sample", ctypes.c_int ), ( "channel_layout", ctypes.c_int64 ), ( "request_channel_layout", ctypes.c_int64 ), ( "rc_max_available_vbv_use", ctypes.c_float ), ( "rc_min_vbv_overflow_use", ctypes.c_float ), ( "hwaccel", ctypes.POINTER(AVHWAccel) ), ( "ticks_per_frame", ctypes.c_int ), ( "hwaccel_context", ctypes.POINTER(ctypes.c_void_p) ), ( "color_primaries", ctypes.c_int ), ( "color_trc", ctypes.c_int ), ( "colorspace", ctypes.c_int ), ( "color_range", ctypes.c_int ), ( "chroma_sample_location", ctypes.c_int ), ( "execute2", ctypes.c_void_p ), ( "weighted_p_pred", ctypes.c_int ), ( "aq_mode", ctypes.c_int ), ( "aq_strength", ctypes.c_float ), ( "psy_rd", ctypes.c_float ), ( "psy_trellis", ctypes.c_float ), ( "rc_lookahead", ctypes.c_int ), ( "crf_max", ctypes.c_float ), ( "log_level_offset", ctypes.c_int ), ( "lpc_type", ctypes.c_int ), ( "lpc_passes", ctypes.c_int ), ( "slices", ctypes.c_int ), ( "subtitle_header", ctypes.POINTER(ctypes.c_uint8) ), ( "subtitle_header_size", ctypes.c_int ), ( "pkt", ctypes.POINTER(AVPacket) ), ( "is_copy", ctypes.c_int ), ( "thread_type", ctypes.c_int ), ( "active_thread_type", ctypes.c_int ), ( "thread_safe_callbacks", ctypes.c_int ), ( "vbv_delay", ctypes.c_uint64 ), ( "audio_service_type", ctypes.c_int ), ( "request_sample_fmt", ctypes.c_int ), ]) __freeze_rpythonic_struct( AVPicture, [ ( "data", ctypes.POINTER(( ctypes.c_uint8 * 4 )) ), ( "linesize", ( ctypes.c_int * 4 ) ), ]) __freeze_rpythonic_struct( AVSubtitleRect, [ ( "x", ctypes.c_int ), ( "y", ctypes.c_int ), ( "w", ctypes.c_int ), ( "h", ctypes.c_int ), ( "nb_colors", ctypes.c_int ), ( "pict", AVPicture ), ( "C_type", ctypes.c_int ), ( "text", ctypes.POINTER(ctypes.c_char) ), ( "ass", ctypes.POINTER(ctypes.c_char) ), ]) __freeze_rpythonic_struct( AVSubtitle, [ ( "format", ctypes.c_uint16 ), ( "start_display_time", ctypes.c_uint32 ), ( "end_display_time", ctypes.c_uint32 ), ( "num_rects", ctypes.c_void_p ), ( "rects", ctypes.POINTER(ctypes.POINTER(AVSubtitleRect)) ), ( "pts", ctypes.c_int64 ), ]) __freeze_rpythonic_struct( ReSampleContext, [ ]) __freeze_rpythonic_struct( AVResampleContext, [ ]) __freeze_rpythonic_struct( AVCodecParser, [ ( "codec_ids", ( ctypes.c_int * 5 ) ), ( "priv_data_size", ctypes.c_int ), ( "parser_init", ctypes.c_void_p ), ( "parser_parse", ctypes.c_void_p ), ( "parser_close", ctypes.c_void_p ), ( "split", ctypes.c_void_p ), ( "next", ctypes.POINTER(AVCodecParser) ), ]) __freeze_rpythonic_struct( AVCodecParserContext, [ ( "priv_data", ctypes.POINTER(ctypes.c_void_p) ), ( "parser", ctypes.POINTER(AVCodecParser) ), ( "frame_offset", ctypes.c_int64 ), ( "cur_offset", ctypes.c_int64 ), ( "next_frame_offset", ctypes.c_int64 ), ( "pict_type", ctypes.c_int ), ( "repeat_pict", ctypes.c_int ), ( "pts", ctypes.c_int64 ), ( "dts", ctypes.c_int64 ), ( "last_pts", ctypes.c_int64 ), ( "last_dts", ctypes.c_int64 ), ( "fetch_timestamp", ctypes.c_int ), ( "cur_frame_start_index", ctypes.c_int ), ( "cur_frame_offset", ( ctypes.c_int64 * 4 ) ), ( "cur_frame_pts", ( ctypes.c_int64 * 4 ) ), ( "cur_frame_dts", ( ctypes.c_int64 * 4 ) ), ( "flags", ctypes.c_int ), ( "offset", ctypes.c_int64 ), ( "cur_frame_end", ( ctypes.c_int64 * 4 ) ), ( "key_frame", ctypes.c_int ), ( "convergence_duration", ctypes.c_int64 ), ( "dts_sync_point", ctypes.c_int ), ( "dts_ref_dts_delta", ctypes.c_int ), ( "pts_dts_delta", ctypes.c_int ), ( "cur_frame_pos", ( ctypes.c_int64 * 4 ) ), ( "pos", ctypes.c_int64 ), ( "last_pos", ctypes.c_int64 ), ]) __freeze_rpythonic_struct( AVBitStreamFilter, [ ( "name", ctypes.POINTER(ctypes.c_char) ), ( "priv_data_size", ctypes.c_int ), ( "filter", ctypes.c_void_p ), ( "close", ctypes.c_void_p ), ( "next", ctypes.POINTER(AVBitStreamFilter) ), ]) __freeze_rpythonic_struct( AVBitStreamFilterContext, [ ( "priv_data", ctypes.POINTER(ctypes.c_void_p) ), ( "filter", ctypes.POINTER(AVBitStreamFilter) ), ( "parser", ctypes.POINTER(AVCodecParserContext) ), ( "next", ctypes.POINTER(AVBitStreamFilterContext) ), ]) __freeze_rpythonic_struct( AVIOContext, [ ( "buffer", ctypes.POINTER(ctypes.c_ubyte) ), ( "buffer_size", ctypes.c_int ), ( "buf_ptr", ctypes.POINTER(ctypes.c_ubyte) ), ( "buf_end", ctypes.POINTER(ctypes.c_ubyte) ), ( "opaque", ctypes.POINTER(ctypes.c_void_p) ), ( "read_packet", ctypes.c_void_p ), ( "write_packet", ctypes.c_void_p ), ( "seek", ctypes.c_void_p ), ( "pos", ctypes.c_int64 ), ( "must_flush", ctypes.c_int ), ( "eof_reached", ctypes.c_int ), ( "write_flag", ctypes.c_int ), ( "is_streamed", ctypes.c_int ), ( "max_packet_size", ctypes.c_int ), ( "checksum", ctypes.c_ulong ), ( "checksum_ptr", ctypes.POINTER(ctypes.c_ubyte) ), ( "update_checksum", ctypes.c_void_p ), ( "error", ctypes.c_int ), ( "read_pause", ctypes.c_void_p ), ( "read_seek", ctypes.c_void_p ), ( "seekable", ctypes.c_int ), ]) __freeze_rpythonic_struct( URLProtocol, [ ( "name", ctypes.POINTER(ctypes.c_char) ), ( "url_open", ctypes.c_void_p ), ( "url_read", ctypes.c_void_p ), ( "url_write", ctypes.c_void_p ), ( "url_seek", ctypes.c_void_p ), ( "url_close", ctypes.c_void_p ), ( "next", ctypes.POINTER(URLProtocol) ), ( "url_read_pause", ctypes.c_void_p ), ( "url_read_seek", ctypes.c_void_p ), ( "url_get_file_handle", ctypes.c_void_p ), ( "priv_data_size", ctypes.c_int ), ( "priv_data_class", ctypes.POINTER(AVClass) ), ( "flags", ctypes.c_int ), ( "url_check", ctypes.c_void_p ), ]) __freeze_rpythonic_struct( URLContext, [ ( "av_class", ctypes.POINTER(AVClass) ), ( "prot", ctypes.POINTER(URLProtocol) ), ( "flags", ctypes.c_int ), ( "is_streamed", ctypes.c_int ), ( "max_packet_size", ctypes.c_int ), ( "priv_data", ctypes.POINTER(ctypes.c_void_p) ), ( "filename", ctypes.POINTER(ctypes.c_char) ), ( "is_connected", ctypes.c_int ), ]) __freeze_rpythonic_struct( URLPollEntry, [ ( "handle", ctypes.POINTER(URLContext) ), ( "events", ctypes.c_int ), ( "revents", ctypes.c_int ), ]) __freeze_rpythonic_struct( AVMetadataConv, [ ]) __freeze_rpythonic_struct( AVFrac, [ ( "val", ctypes.c_int64 ), ( "num", ctypes.c_int64 ), ( "den", ctypes.c_int64 ), ]) __freeze_rpythonic_struct( AVCodecTag, [ ]) __freeze_rpythonic_struct( AVProbeData, [ ( "filename", ctypes.POINTER(ctypes.c_char) ), ( "buf", ctypes.POINTER(ctypes.c_ubyte) ), ( "buf_size", ctypes.c_int ), ]) __freeze_rpythonic_struct( AVFormatParameters, [ ( "time_base", AVRational ), ( "sample_rate", ctypes.c_int ), ( "channels", ctypes.c_int ), ( "width", ctypes.c_int ), ( "height", ctypes.c_int ), ( "pix_fmt", ctypes.c_int ), ( "channel", ctypes.c_int ), ( "standard", ctypes.POINTER(ctypes.c_char) ), ( "mpeg2ts_raw", ctypes.c_uint ), ( "mpeg2ts_compute_pcr", ctypes.c_uint ), ( "initial_pause", ctypes.c_uint ), ( "prealloced_context", ctypes.c_uint ), ]) __freeze_rpythonic_struct( AVOutputFormat, [ ( "name", ctypes.POINTER(ctypes.c_char) ), ( "long_name", ctypes.POINTER(ctypes.c_char) ), ( "mime_type", ctypes.POINTER(ctypes.c_char) ), ( "extensions", ctypes.POINTER(ctypes.c_char) ), ( "priv_data_size", ctypes.c_int ), ( "audio_codec", ctypes.c_int ), ( "video_codec", ctypes.c_int ), ( "write_header", ctypes.c_void_p ), ( "write_packet", ctypes.c_void_p ), ( "write_trailer", ctypes.c_void_p ), ( "flags", ctypes.c_int ), ( "set_parameters", ctypes.c_void_p ), ( "interleave_packet", ctypes.c_void_p ), ( "codec_tag", ctypes.POINTER(ctypes.POINTER(AVCodecTag)) ), ( "subtitle_codec", ctypes.c_int ), ( "metadata_conv", ctypes.POINTER(AVMetadataConv) ), ( "priv_class", ctypes.POINTER(AVClass) ), ( "next", ctypes.POINTER(AVOutputFormat) ), ]) __freeze_rpythonic_struct( AVInputFormat, [ ( "name", ctypes.POINTER(ctypes.c_char) ), ( "long_name", ctypes.POINTER(ctypes.c_char) ), ( "priv_data_size", ctypes.c_int ), ( "read_probe", ctypes.c_void_p ), ( "read_header", ctypes.c_void_p ), ( "read_packet", ctypes.c_void_p ), ( "read_close", ctypes.c_void_p ), ( "read_seek", ctypes.c_void_p ), ( "read_timestamp", ctypes.c_void_p ), ( "flags", ctypes.c_int ), ( "extensions", ctypes.POINTER(ctypes.c_char) ), ( "value", ctypes.c_int ), ( "read_play", ctypes.c_void_p ), ( "read_pause", ctypes.c_void_p ), ( "codec_tag", ctypes.POINTER(ctypes.POINTER(AVCodecTag)) ), ( "read_seek2", ctypes.c_void_p ), ( "metadata_conv", ctypes.POINTER(AVMetadataConv) ), ( "priv_class", ctypes.POINTER(AVClass) ), ( "next", ctypes.POINTER(AVInputFormat) ), ]) __freeze_rpythonic_struct( AVIndexEntry, [ ( "pos", ctypes.c_int64 ), ( "timestamp", ctypes.c_int64 ), ( "flags", ctypes.c_int ), ( "size", ctypes.c_int ), ( "min_distance", ctypes.c_int ), ]) __freeze_rpythonic_struct( AVPacketList, [ ( "pkt", AVPacket ), ( "next", ctypes.POINTER(AVPacketList) ), ]) __freeze_rpythonic_struct( info, [ ( "last_dts", ctypes.c_int64 ), ( "duration_gcd", ctypes.c_int64 ), ( "duration_count", ctypes.c_int ), ( "duration_error", ( ctypes.c_double * 1733 ) ), ( "codec_info_duration", ctypes.c_int64 ), ]) __freeze_rpythonic_struct( AVStream, [ ( "index", ctypes.c_int ), ( "C_id", ctypes.c_int ), ( "codec", ctypes.POINTER(AVCodecContext) ), ( "r_frame_rate", AVRational ), ( "priv_data", ctypes.POINTER(ctypes.c_void_p) ), ( "first_dts", ctypes.c_int64 ), ( "pts", AVFrac ), ( "time_base", AVRational ), ( "pts_wrap_bits", ctypes.c_int ), ( "stream_copy", ctypes.c_int ), ( "discard", ctypes.c_int ), ( "quality", ctypes.c_float ), ( "start_time", ctypes.c_int64 ), ( "duration", ctypes.c_int64 ), ( "need_parsing", ctypes.c_int ), ( "parser", ctypes.POINTER(AVCodecParserContext) ), ( "cur_dts", ctypes.c_int64 ), ( "last_IP_duration", ctypes.c_int ), ( "last_IP_pts", ctypes.c_int64 ), ( "index_entries", ctypes.POINTER(AVIndexEntry) ), ( "nb_index_entries", ctypes.c_int ), ( "index_entries_allocated_size", ctypes.c_uint ), ( "nb_frames", ctypes.c_int64 ), ( "disposition", ctypes.c_int ), ( "probe_data", AVProbeData ), ( "pts_buffer", ( ctypes.c_int64 * 23 ) ), ( "sample_aspect_ratio", AVRational ), ( "metadata", ctypes.POINTER(AVDictionary) ), ( "cur_ptr", ctypes.POINTER(ctypes.c_uint8) ), ( "cur_len", ctypes.c_int ), ( "cur_pkt", AVPacket ), ( "reference_dts", ctypes.c_int64 ), ( "probe_packets", ctypes.c_int ), ( "last_in_packet_buffer", ctypes.POINTER(AVPacketList) ), ( "avg_frame_rate", AVRational ), ( "codec_info_nb_frames", ctypes.c_int ), ( "info", ctypes.POINTER(info) ), ]) __freeze_rpythonic_struct( AVProgram, [ ( "C_id", ctypes.c_int ), ( "flags", ctypes.c_int ), ( "discard", ctypes.c_int ), ( "stream_index", ctypes.POINTER(ctypes.c_uint) ), ( "nb_stream_indexes", ctypes.c_uint ), ( "metadata", ctypes.POINTER(AVDictionary) ), ]) __freeze_rpythonic_struct( AVChapter, [ ( "C_id", ctypes.c_int ), ( "time_base", AVRational ), ( "start", ctypes.c_int64 ), ( "end", ctypes.c_int64 ), ( "metadata", ctypes.POINTER(AVDictionary) ), ]) __freeze_rpythonic_struct( AVFormatContext, [ ( "av_class", ctypes.POINTER(AVClass) ), ( "iformat", ctypes.POINTER(AVInputFormat) ), ( "oformat", ctypes.POINTER(AVOutputFormat) ), ( "priv_data", ctypes.POINTER(ctypes.c_void_p) ), ( "pb", ctypes.POINTER(AVIOContext) ), ( "nb_streams", ctypes.c_uint ), ( "streams", ctypes.POINTER(ctypes.POINTER(AVStream)) ), ( "filename", ( ctypes.c_char * 1024 ) ), ( "timestamp", ctypes.c_int64 ), ( "ctx_flags", ctypes.c_int ), ( "packet_buffer", ctypes.POINTER(AVPacketList) ), ( "start_time", ctypes.c_int64 ), ( "duration", ctypes.c_int64 ), ( "file_size", ctypes.c_int64 ), ( "bit_rate", ctypes.c_int ), ( "cur_st", ctypes.POINTER(AVStream) ), ( "data_offset", ctypes.c_int64 ), ( "mux_rate", ctypes.c_int ), ( "packet_size", ctypes.c_uint ), ( "preload", ctypes.c_int ), ( "max_delay", ctypes.c_int ), ( "loop_output", ctypes.c_int ), ( "flags", ctypes.c_int ), ( "loop_input", ctypes.c_int ), ( "probesize", ctypes.c_uint ), ( "max_analyze_duration", ctypes.c_int ), ( "key", ctypes.POINTER(ctypes.c_uint8) ), ( "keylen", ctypes.c_int ), ( "nb_programs", ctypes.c_uint ), ( "programs", ctypes.POINTER(ctypes.POINTER(AVProgram)) ), ( "video_codec_id", ctypes.c_int ), ( "audio_codec_id", ctypes.c_int ), ( "subtitle_codec_id", ctypes.c_int ), ( "max_index_size", ctypes.c_uint ), ( "max_picture_buffer", ctypes.c_uint ), ( "nb_chapters", ctypes.c_uint ), ( "chapters", ctypes.POINTER(ctypes.POINTER(AVChapter)) ), ( "debug", ctypes.c_int ), ( "raw_packet_buffer", ctypes.POINTER(AVPacketList) ), ( "raw_packet_buffer_end", ctypes.POINTER(AVPacketList) ), ( "packet_buffer_end", ctypes.POINTER(AVPacketList) ), ( "metadata", ctypes.POINTER(AVDictionary) ), ( "raw_packet_buffer_remaining_size", ctypes.c_int ), ( "start_time_realtime", ctypes.c_int64 ), ( "fps_probe_size", ctypes.c_int ), ]) ## wrapper functions ## vprintf = _rpythonic_function_( "vprintf", ctypes.c_int, [ ("__format", ctypes.POINTER(ctypes.c_char)), ("__arg", ctypes.c_char),] ) vsprintf = _rpythonic_function_( "vsprintf", ctypes.c_int, [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__format", ctypes.POINTER(ctypes.c_char)), ("__arg", ctypes.c_char),] ) snprintf = _rpythonic_function_( "snprintf", ctypes.c_int, [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__maxlen", ctypes.c_uint64), ("__format", ctypes.POINTER(ctypes.c_char)),] ) vsnprintf = _rpythonic_function_( "vsnprintf", ctypes.c_int, [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__maxlen", ctypes.c_uint64), ("__format", ctypes.POINTER(ctypes.c_char)), ("__arg", ctypes.c_char),] ) freopen = _rpythonic_function_( "freopen", ctypes.POINTER(_IO_FILE), [ ("__filename", ctypes.POINTER(ctypes.c_char)), ("__modes", ctypes.POINTER(ctypes.c_char)), ("__stream", ctypes.POINTER(_IO_FILE)),] ) fdopen = _rpythonic_function_( "fdopen", ctypes.POINTER(_IO_FILE), [ ("__fd", ctypes.c_int), ("__modes", ctypes.POINTER(ctypes.c_char)),] ) fmemopen = _rpythonic_function_( "fmemopen", ctypes.POINTER(_IO_FILE), [ ("__s", ctypes.POINTER(ctypes.c_void_p)), ("__len", ctypes.c_uint64), ("__modes", ctypes.POINTER(ctypes.c_char)),] ) tmpnam_r = _rpythonic_function_( "tmpnam_r", ctypes.POINTER(ctypes.c_char), [ ("__s", ctypes.POINTER(ctypes.c_char)),] ) tempnam = _rpythonic_function_( "tempnam", ctypes.POINTER(ctypes.c_char), [ ("__dir", ctypes.POINTER(ctypes.c_char)), ("__pfx", ctypes.POINTER(ctypes.c_char)),] ) fclose = _rpythonic_function_( "fclose", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) fflush = _rpythonic_function_( "fflush", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) fflush_unlocked = _rpythonic_function_( "fflush_unlocked", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) fopen = _rpythonic_function_( "fopen", ctypes.POINTER(_IO_FILE), [ ("__filename", ctypes.POINTER(ctypes.c_char)), ("__modes", ctypes.POINTER(ctypes.c_char)),] ) _IO_peekc_locked = _rpythonic_function_( "_IO_peekc_locked", ctypes.c_int, [ ("__fp", ctypes.POINTER(_IO_FILE)),] ) _IO_flockfile = _rpythonic_function_( "_IO_flockfile", ctypes.c_void_p, [ ("none", ctypes.POINTER(ctypes.c_void_p)),] ) _IO_funlockfile = _rpythonic_function_( "_IO_funlockfile", ctypes.c_void_p, [ ("none", ctypes.POINTER(ctypes.c_void_p)),] ) _IO_ftrylockfile = _rpythonic_function_( "_IO_ftrylockfile", ctypes.c_int, [ ("none", ctypes.POINTER(ctypes.c_void_p)),] ) _IO_vfscanf = _rpythonic_function_( "_IO_vfscanf", ctypes.c_int, [ ("__restrict", ctypes.POINTER(_IO_FILE)), ("__restrict", ctypes.POINTER(ctypes.c_char)), ("none", ctypes.c_char), ("__restrict", ctypes.POINTER(ctypes.c_int)),] ) localtime_r = _rpythonic_function_( "localtime_r", ctypes.POINTER(tm), [ ("__timer", ctypes.POINTER(ctypes.c_int64)), ("__tp", ctypes.POINTER(tm)),] ) asctime = _rpythonic_function_( "asctime", ctypes.POINTER(ctypes.c_char), [ ("__tp", ctypes.POINTER(tm)),] ) ctime_r = _rpythonic_function_( "ctime_r", ctypes.POINTER(ctypes.c_char), [ ("__timer", ctypes.POINTER(ctypes.c_int64)), ("__buf", ctypes.POINTER(ctypes.c_char)),] ) ctime = _rpythonic_function_( "ctime", ctypes.POINTER(ctypes.c_char), [ ("__timer", ctypes.POINTER(ctypes.c_int64)),] ) asctime_r = _rpythonic_function_( "asctime_r", ctypes.POINTER(ctypes.c_char), [ ("__tp", ctypes.POINTER(tm)), ("__buf", ctypes.POINTER(ctypes.c_char)),] ) vscanf = _rpythonic_function_( "vscanf", ctypes.c_int, [ ("__format", ctypes.POINTER(ctypes.c_char)), ("__arg", ctypes.c_char),] ) vsscanf = _rpythonic_function_( "vsscanf", ctypes.c_int, [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__format", ctypes.POINTER(ctypes.c_char)), ("__arg", ctypes.c_char),] ) avformat_version = _rpythonic_function_( "avformat_version", ctypes.c_void_p, [] ) avformat_configuration = _rpythonic_function_( "avformat_configuration", ctypes.POINTER(ctypes.c_char), [] ) avformat_license = _rpythonic_function_( "avformat_license", ctypes.POINTER(ctypes.c_char), [] ) fgetc = _rpythonic_function_( "fgetc", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) getc = _rpythonic_function_( "getc", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) getchar = _rpythonic_function_( "getchar", ctypes.c_int, [] ) getc_unlocked = _rpythonic_function_( "getc_unlocked", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) getchar_unlocked = _rpythonic_function_( "getchar_unlocked", ctypes.c_int, [] ) fgetc_unlocked = _rpythonic_function_( "fgetc_unlocked", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) fputc = _rpythonic_function_( "fputc", ctypes.c_int, [ ("__c", ctypes.c_int), ("__stream", ctypes.POINTER(_IO_FILE)),] ) putc = _rpythonic_function_( "putc", ctypes.c_int, [ ("__c", ctypes.c_int), ("__stream", ctypes.POINTER(_IO_FILE)),] ) putchar = _rpythonic_function_( "putchar", ctypes.c_int, [ ("__c", ctypes.c_int),] ) fputc_unlocked = _rpythonic_function_( "fputc_unlocked", ctypes.c_int, [ ("__c", ctypes.c_int), ("__stream", ctypes.POINTER(_IO_FILE)),] ) putc_unlocked = _rpythonic_function_( "putc_unlocked", ctypes.c_int, [ ("__c", ctypes.c_int), ("__stream", ctypes.POINTER(_IO_FILE)),] ) putchar_unlocked = _rpythonic_function_( "putchar_unlocked", ctypes.c_int, [ ("__c", ctypes.c_int),] ) getw = _rpythonic_function_( "getw", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) putw = _rpythonic_function_( "putw", ctypes.c_int, [ ("__w", ctypes.c_int), ("__stream", ctypes.POINTER(_IO_FILE)),] ) fgets = _rpythonic_function_( "fgets", ctypes.POINTER(ctypes.c_char), [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__n", ctypes.c_int), ("__stream", ctypes.POINTER(_IO_FILE)),] ) open_memstream = _rpythonic_function_( "open_memstream", ctypes.POINTER(_IO_FILE), [ ("__bufloc", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))), ("__sizeloc", ctypes.POINTER(ctypes.c_uint64)),] ) setbuf = _rpythonic_function_( "setbuf", ctypes.c_void_p, [ ("__stream", ctypes.POINTER(_IO_FILE)), ("__buf", ctypes.POINTER(ctypes.c_char)),] ) setvbuf = _rpythonic_function_( "setvbuf", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)), ("__buf", ctypes.POINTER(ctypes.c_char)), ("__modes", ctypes.c_int), ("__n", ctypes.c_uint64),] ) setbuffer = _rpythonic_function_( "setbuffer", ctypes.c_void_p, [ ("__stream", ctypes.POINTER(_IO_FILE)), ("__buf", ctypes.POINTER(ctypes.c_char)), ("__size", ctypes.c_uint64),] ) _IO_getc = _rpythonic_function_( "_IO_getc", ctypes.c_int, [ ("__fp", ctypes.POINTER(_IO_FILE)),] ) _IO_putc = _rpythonic_function_( "_IO_putc", ctypes.c_int, [ ("__c", ctypes.c_int), ("__fp", ctypes.POINTER(_IO_FILE)),] ) _IO_feof = _rpythonic_function_( "_IO_feof", ctypes.c_int, [ ("__fp", ctypes.POINTER(_IO_FILE)),] ) _IO_ferror = _rpythonic_function_( "_IO_ferror", ctypes.c_int, [ ("__fp", ctypes.POINTER(_IO_FILE)),] ) _IO_seekpos = _rpythonic_function_( "_IO_seekpos", ctypes.c_int64, [ ("none", ctypes.POINTER(ctypes.c_void_p)), ("none", ctypes.c_int64), ("none", ctypes.c_int),] ) _IO_free_backup_area = _rpythonic_function_( "_IO_free_backup_area", ctypes.c_void_p, [ ("none", ctypes.POINTER(ctypes.c_void_p)),] ) remove = _rpythonic_function_( "remove", ctypes.c_int, [ ("__filename", ctypes.POINTER(ctypes.c_char)),] ) strftime = _rpythonic_function_( "strftime", ctypes.c_uint64, [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__maxsize", ctypes.c_uint64), ("__format", ctypes.POINTER(ctypes.c_char)), ("__tp", ctypes.POINTER(tm)),] ) strftime_l = _rpythonic_function_( "strftime_l", ctypes.c_uint64, [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__maxsize", ctypes.c_uint64), ("__format", ctypes.POINTER(ctypes.c_char)), ("__tp", ctypes.POINTER(tm)), ("__loc", ctypes.POINTER(__locale_struct)),] ) setlinebuf = _rpythonic_function_( "setlinebuf", ctypes.c_void_p, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) fprintf = _rpythonic_function_( "fprintf", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)), ("__format", ctypes.POINTER(ctypes.c_char)),] ) printf = _rpythonic_function_( "printf", ctypes.c_int, [ ("__format", ctypes.POINTER(ctypes.c_char)),] ) sprintf = _rpythonic_function_( "sprintf", ctypes.c_int, [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__format", ctypes.POINTER(ctypes.c_char)),] ) vfprintf = _rpythonic_function_( "vfprintf", ctypes.c_int, [ ("__s", ctypes.POINTER(_IO_FILE)), ("__format", ctypes.POINTER(ctypes.c_char)), ("__arg", ctypes.c_char),] ) vdprintf = _rpythonic_function_( "vdprintf", ctypes.c_int, [ ("__fd", ctypes.c_int), ("__fmt", ctypes.POINTER(ctypes.c_char)), ("__arg", ctypes.c_char),] ) dprintf = _rpythonic_function_( "dprintf", ctypes.c_int, [ ("__fd", ctypes.c_int), ("__fmt", ctypes.POINTER(ctypes.c_char)),] ) fscanf = _rpythonic_function_( "fscanf", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)), ("__format", ctypes.POINTER(ctypes.c_char)),] ) scanf = _rpythonic_function_( "scanf", ctypes.c_int, [ ("__format", ctypes.POINTER(ctypes.c_char)),] ) sscanf = _rpythonic_function_( "sscanf", ctypes.c_int, [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__format", ctypes.POINTER(ctypes.c_char)),] ) vfscanf = _rpythonic_function_( "vfscanf", ctypes.c_int, [ ("__s", ctypes.POINTER(_IO_FILE)), ("__format", ctypes.POINTER(ctypes.c_char)), ("__arg", ctypes.c_char),] ) dysize = _rpythonic_function_( "dysize", ctypes.c_int, [ ("__year", ctypes.c_int),] ) nanosleep = _rpythonic_function_( "nanosleep", ctypes.c_int, [ ("__requested_time", ctypes.POINTER(timespec)), ("__remaining", ctypes.POINTER(timespec)),] ) clock_getres = _rpythonic_function_( "clock_getres", ctypes.c_int, [ ("__clock_id", ctypes.c_int), ("__res", ctypes.POINTER(timespec)),] ) clock_gettime = _rpythonic_function_( "clock_gettime", ctypes.c_int, [ ("__clock_id", ctypes.c_int), ("__tp", ctypes.POINTER(timespec)),] ) clock_settime = _rpythonic_function_( "clock_settime", ctypes.c_int, [ ("__clock_id", ctypes.c_int), ("__tp", ctypes.POINTER(timespec)),] ) tzset = _rpythonic_function_( "tzset", ctypes.c_void_p, [] ) stime = _rpythonic_function_( "stime", ctypes.c_int, [ ("__when", ctypes.POINTER(ctypes.c_int64)),] ) timegm = _rpythonic_function_( "timegm", ctypes.c_int64, [ ("__tp", ctypes.POINTER(tm)),] ) timelocal = _rpythonic_function_( "timelocal", ctypes.c_int64, [ ("__tp", ctypes.POINTER(tm)),] ) clock = _rpythonic_function_( "clock", ctypes.c_int64, [] ) time = _rpythonic_function_( "time", ctypes.c_int64, [ ("__timer", ctypes.POINTER(ctypes.c_int64)),] ) difftime = _rpythonic_function_( "difftime", ctypes.c_double, [ ("__time1", ctypes.c_int64), ("__time0", ctypes.c_int64),] ) mktime = _rpythonic_function_( "mktime", ctypes.c_int64, [ ("__tp", ctypes.POINTER(tm)),] ) timer_settime = _rpythonic_function_( "timer_settime", ctypes.c_int, [ ("__timerid", ctypes.c_void_p), ("__flags", ctypes.c_int), ("__value", ctypes.POINTER(itimerspec)), ("__ovalue", ctypes.POINTER(itimerspec)),] ) timer_gettime = _rpythonic_function_( "timer_gettime", ctypes.c_int, [ ("__timerid", ctypes.c_void_p), ("__value", ctypes.POINTER(itimerspec)),] ) timer_getoverrun = _rpythonic_function_( "timer_getoverrun", ctypes.c_int, [("__timerid", ctypes.c_void_p)] ) _IO_vfprintf = _rpythonic_function_( "_IO_vfprintf", ctypes.c_int, [ ("__restrict", ctypes.POINTER(_IO_FILE)), ("__restrict", ctypes.POINTER(ctypes.c_char)), ("none", ctypes.c_char),] ) _IO_padn = _rpythonic_function_( "_IO_padn", ctypes.c_int64, [ ("none", ctypes.POINTER(ctypes.c_void_p)), ("none", ctypes.c_int), ("none", ctypes.c_int64),] ) _IO_sgetn = _rpythonic_function_( "_IO_sgetn", ctypes.c_uint64, [ ("none", ctypes.POINTER(ctypes.c_void_p)), ("none", ctypes.POINTER(ctypes.c_void_p)), ("none", ctypes.c_uint64),] ) _IO_seekoff = _rpythonic_function_( "_IO_seekoff", ctypes.c_int64, [ ("none", ctypes.POINTER(ctypes.c_void_p)), ("none", ctypes.c_int64), ("none", ctypes.c_int), ("none", ctypes.c_int),] ) clock_nanosleep = _rpythonic_function_( "clock_nanosleep", ctypes.c_int, [ ("__clock_id", ctypes.c_int), ("__flags", ctypes.c_int), ("__req", ctypes.POINTER(timespec)), ("__rem", ctypes.POINTER(timespec)),] ) clock_getcpuclockid = _rpythonic_function_( "clock_getcpuclockid", ctypes.c_int, [ ("__pid", ctypes.c_int), ("__clock_id", ctypes.POINTER(ctypes.c_int)),] ) timer_create = _rpythonic_function_( "timer_create", ctypes.c_int, [ ("__clock_id", ctypes.c_int), ("__evp", ctypes.POINTER(sigevent)), ("__timerid", ctypes.POINTER(ctypes.c_void_p)),] ) timer_delete = _rpythonic_function_( "timer_delete", ctypes.c_int, [("__timerid", ctypes.c_void_p)] ) rename = _rpythonic_function_( "rename", ctypes.c_int, [ ("__old", ctypes.POINTER(ctypes.c_char)), ("__new", ctypes.POINTER(ctypes.c_char)),] ) renameat = _rpythonic_function_( "renameat", ctypes.c_int, [ ("__oldfd", ctypes.c_int), ("__old", ctypes.POINTER(ctypes.c_char)), ("__newfd", ctypes.c_int), ("__new", ctypes.POINTER(ctypes.c_char)),] ) tmpfile = _rpythonic_function_( "tmpfile", ctypes.POINTER(_IO_FILE), [] ) tmpnam = _rpythonic_function_( "tmpnam", ctypes.POINTER(ctypes.c_char), [ ("__s", ctypes.POINTER(ctypes.c_char)),] ) gmtime = _rpythonic_function_( "gmtime", ctypes.POINTER(tm), [ ("__timer", ctypes.POINTER(ctypes.c_int64)),] ) localtime = _rpythonic_function_( "localtime", ctypes.POINTER(tm), [ ("__timer", ctypes.POINTER(ctypes.c_int64)),] ) gmtime_r = _rpythonic_function_( "gmtime_r", ctypes.POINTER(tm), [ ("__timer", ctypes.POINTER(ctypes.c_int64)), ("__tp", ctypes.POINTER(tm)),] ) exp = _rpythonic_function_( "exp", ctypes.c_double, [ ("__x", ctypes.c_double),] ) frexp = _rpythonic_function_( "frexp", ctypes.c_double, [ ("__x", ctypes.c_double), ("__exponent", ctypes.POINTER(ctypes.c_int)),] ) ldexp = _rpythonic_function_( "ldexp", ctypes.c_double, [ ("__x", ctypes.c_double), ("__exponent", ctypes.c_int),] ) fgetpos = _rpythonic_function_( "fgetpos", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)), ("__pos", ctypes.POINTER(_G_fpos_t)),] ) fsetpos = _rpythonic_function_( "fsetpos", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)), ("__pos", ctypes.POINTER(_G_fpos_t)),] ) clearerr = _rpythonic_function_( "clearerr", ctypes.c_void_p, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) feof = _rpythonic_function_( "feof", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) ferror = _rpythonic_function_( "ferror", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) jn = _rpythonic_function_( "jn", ctypes.c_double, [ ("none", ctypes.c_int), ("none", ctypes.c_double),] ) y0 = _rpythonic_function_( "y0", ctypes.c_double, [ ("none", ctypes.c_double),] ) y1 = _rpythonic_function_( "y1", ctypes.c_double, [ ("none", ctypes.c_double),] ) funlockfile = _rpythonic_function_( "funlockfile", ctypes.c_void_p, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) avutil_version = _rpythonic_function_( "avutil_version", ctypes.c_void_p, [] ) avutil_configuration = _rpythonic_function_( "avutil_configuration", ctypes.POINTER(ctypes.c_char), [] ) avutil_license = _rpythonic_function_( "avutil_license", ctypes.POINTER(ctypes.c_char), [] ) av_get_picture_type_char = _rpythonic_function_( "av_get_picture_type_char", ctypes.c_char, [ ("pict_type", ctypes.c_int),] ) fwrite = _rpythonic_function_( "fwrite", ctypes.c_uint64, [ ("__ptr", ctypes.POINTER(ctypes.c_void_p)), ("__size", ctypes.c_uint64), ("__n", ctypes.c_uint64), ("__s", ctypes.POINTER(_IO_FILE)),] ) fread_unlocked = _rpythonic_function_( "fread_unlocked", ctypes.c_uint64, [ ("__ptr", ctypes.POINTER(ctypes.c_void_p)), ("__size", ctypes.c_uint64), ("__n", ctypes.c_uint64), ("__stream", ctypes.POINTER(_IO_FILE)),] ) fwrite_unlocked = _rpythonic_function_( "fwrite_unlocked", ctypes.c_uint64, [ ("__ptr", ctypes.POINTER(ctypes.c_void_p)), ("__size", ctypes.c_uint64), ("__n", ctypes.c_uint64), ("__stream", ctypes.POINTER(_IO_FILE)),] ) sqrt = _rpythonic_function_( "sqrt", ctypes.c_double, [ ("__x", ctypes.c_double),] ) hypot = _rpythonic_function_( "hypot", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) cbrt = _rpythonic_function_( "cbrt", ctypes.c_double, [ ("__x", ctypes.c_double),] ) expm1 = _rpythonic_function_( "expm1", ctypes.c_double, [ ("__x", ctypes.c_double),] ) log1p = _rpythonic_function_( "log1p", ctypes.c_double, [ ("__x", ctypes.c_double),] ) logb = _rpythonic_function_( "logb", ctypes.c_double, [ ("__x", ctypes.c_double),] ) log = _rpythonic_function_( "log", ctypes.c_double, [ ("__x", ctypes.c_double),] ) log10 = _rpythonic_function_( "log10", ctypes.c_double, [ ("__x", ctypes.c_double),] ) modf = _rpythonic_function_( "modf", ctypes.c_double, [ ("__x", ctypes.c_double), ("__iptr", ctypes.POINTER(ctypes.c_double)),] ) toupper_l = _rpythonic_function_( "toupper_l", ctypes.c_int, [ ("__c", ctypes.c_int), ("__l", ctypes.POINTER(__locale_struct)),] ) exp2 = _rpythonic_function_( "exp2", ctypes.c_double, [ ("__x", ctypes.c_double),] ) log2 = _rpythonic_function_( "log2", ctypes.c_double, [ ("__x", ctypes.c_double),] ) pow = _rpythonic_function_( "pow", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) isinf = _rpythonic_function_( "isinf", ctypes.c_int, [ ("__value", ctypes.c_double),] ) finite = _rpythonic_function_( "finite", ctypes.c_int, [ ("__value", ctypes.c_double),] ) drem = _rpythonic_function_( "drem", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) significand = _rpythonic_function_( "significand", ctypes.c_double, [ ("__x", ctypes.c_double),] ) copysign = _rpythonic_function_( "copysign", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) nan = _rpythonic_function_( "nan", ctypes.c_double, [ ("__tagb", ctypes.POINTER(ctypes.c_char)),] ) isnan = _rpythonic_function_( "isnan", ctypes.c_int, [ ("__value", ctypes.c_double),] ) j0 = _rpythonic_function_( "j0", ctypes.c_double, [ ("none", ctypes.c_double),] ) j1 = _rpythonic_function_( "j1", ctypes.c_double, [ ("none", ctypes.c_double),] ) yn = _rpythonic_function_( "yn", ctypes.c_double, [ ("none", ctypes.c_int), ("none", ctypes.c_double),] ) erf = _rpythonic_function_( "erf", ctypes.c_double, [ ("none", ctypes.c_double),] ) erfc = _rpythonic_function_( "erfc", ctypes.c_double, [ ("none", ctypes.c_double),] ) lgamma = _rpythonic_function_( "lgamma", ctypes.c_double, [ ("none", ctypes.c_double),] ) tgamma = _rpythonic_function_( "tgamma", ctypes.c_double, [ ("none", ctypes.c_double),] ) gamma = _rpythonic_function_( "gamma", ctypes.c_double, [ ("none", ctypes.c_double),] ) lgamma_r = _rpythonic_function_( "lgamma_r", ctypes.c_double, [ ("none", ctypes.c_double), ("__signgamp", ctypes.POINTER(ctypes.c_int)),] ) round = _rpythonic_function_( "round", ctypes.c_double, [ ("__x", ctypes.c_double),] ) trunc = _rpythonic_function_( "trunc", ctypes.c_double, [ ("__x", ctypes.c_double),] ) remquo = _rpythonic_function_( "remquo", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double), ("__quo", ctypes.POINTER(ctypes.c_int)),] ) rint = _rpythonic_function_( "rint", ctypes.c_double, [ ("__x", ctypes.c_double),] ) nextafter = _rpythonic_function_( "nextafter", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) nexttoward = _rpythonic_function_( "nexttoward", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) isdigit = _rpythonic_function_( "isdigit", ctypes.c_int, [ ("none", ctypes.c_int),] ) islower = _rpythonic_function_( "islower", ctypes.c_int, [ ("none", ctypes.c_int),] ) isgraph = _rpythonic_function_( "isgraph", ctypes.c_int, [ ("none", ctypes.c_int),] ) isprint = _rpythonic_function_( "isprint", ctypes.c_int, [ ("none", ctypes.c_int),] ) ispunct = _rpythonic_function_( "ispunct", ctypes.c_int, [ ("none", ctypes.c_int),] ) isspace = _rpythonic_function_( "isspace", ctypes.c_int, [ ("none", ctypes.c_int),] ) isupper = _rpythonic_function_( "isupper", ctypes.c_int, [ ("none", ctypes.c_int),] ) _tolower = _rpythonic_function_( "_tolower", ctypes.c_int, [ ("none", ctypes.c_int),] ) isalnum_l = _rpythonic_function_( "isalnum_l", ctypes.c_int, [ ("none", ctypes.c_int), ("none", ctypes.POINTER(ctypes.c_void_p)),] ) isalpha_l = _rpythonic_function_( "isalpha_l", ctypes.c_int, [ ("none", ctypes.c_int), ("none", ctypes.POINTER(ctypes.c_void_p)),] ) iscntrl_l = _rpythonic_function_( "iscntrl_l", ctypes.c_int, [ ("none", ctypes.c_int), ("none", ctypes.POINTER(ctypes.c_void_p)),] ) isdigit_l = _rpythonic_function_( "isdigit_l", ctypes.c_int, [ ("none", ctypes.c_int), ("none", ctypes.POINTER(ctypes.c_void_p)),] ) isxdigit = _rpythonic_function_( "isxdigit", ctypes.c_int, [ ("none", ctypes.c_int),] ) tolower = _rpythonic_function_( "tolower", ctypes.c_int, [ ("__c", ctypes.c_int),] ) toupper = _rpythonic_function_( "toupper", ctypes.c_int, [ ("__c", ctypes.c_int),] ) isblank = _rpythonic_function_( "isblank", ctypes.c_int, [ ("none", ctypes.c_int),] ) isascii = _rpythonic_function_( "isascii", ctypes.c_int, [ ("__c", ctypes.c_int),] ) toascii = _rpythonic_function_( "toascii", ctypes.c_int, [ ("__c", ctypes.c_int),] ) _toupper = _rpythonic_function_( "_toupper", ctypes.c_int, [ ("none", ctypes.c_int),] ) fdim = _rpythonic_function_( "fdim", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) fmax = _rpythonic_function_( "fmax", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) fmin = _rpythonic_function_( "fmin", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) clearerr_unlocked = _rpythonic_function_( "clearerr_unlocked", ctypes.c_void_p, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) feof_unlocked = _rpythonic_function_( "feof_unlocked", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) ferror_unlocked = _rpythonic_function_( "ferror_unlocked", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) perror = _rpythonic_function_( "perror", ctypes.c_void_p, [ ("__s", ctypes.POINTER(ctypes.c_char)),] ) fileno = _rpythonic_function_( "fileno", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) fileno_unlocked = _rpythonic_function_( "fileno_unlocked", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) remainder = _rpythonic_function_( "remainder", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) scalbn = _rpythonic_function_( "scalbn", ctypes.c_double, [ ("__x", ctypes.c_double), ("__n", ctypes.c_int),] ) popen = _rpythonic_function_( "popen", ctypes.POINTER(_IO_FILE), [ ("__command", ctypes.POINTER(ctypes.c_char)), ("__modes", ctypes.POINTER(ctypes.c_char)),] ) pclose = _rpythonic_function_( "pclose", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) ctermid = _rpythonic_function_( "ctermid", ctypes.POINTER(ctypes.c_char), [ ("__s", ctypes.POINTER(ctypes.c_char)),] ) flockfile = _rpythonic_function_( "flockfile", ctypes.c_void_p, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) ftrylockfile = _rpythonic_function_( "ftrylockfile", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) imaxabs = _rpythonic_function_( "imaxabs", ctypes.c_int64, [ ("__n", ctypes.c_int64),] ) imaxdiv = _rpythonic_function_( "imaxdiv", imaxdiv_t, [ ("__numer", ctypes.c_int64), ("__denom", ctypes.c_int64),] ) islower_l = _rpythonic_function_( "islower_l", ctypes.c_int, [ ("none", ctypes.c_int), ("none", ctypes.POINTER(ctypes.c_void_p)),] ) isgraph_l = _rpythonic_function_( "isgraph_l", ctypes.c_int, [ ("none", ctypes.c_int), ("none", ctypes.POINTER(ctypes.c_void_p)),] ) isprint_l = _rpythonic_function_( "isprint_l", ctypes.c_int, [ ("none", ctypes.c_int), ("none", ctypes.POINTER(ctypes.c_void_p)),] ) ispunct_l = _rpythonic_function_( "ispunct_l", ctypes.c_int, [ ("none", ctypes.c_int), ("none", ctypes.POINTER(ctypes.c_void_p)),] ) isspace_l = _rpythonic_function_( "isspace_l", ctypes.c_int, [ ("none", ctypes.c_int), ("none", ctypes.POINTER(ctypes.c_void_p)),] ) isupper_l = _rpythonic_function_( "isupper_l", ctypes.c_int, [ ("none", ctypes.c_int), ("none", ctypes.POINTER(ctypes.c_void_p)),] ) lrint = _rpythonic_function_( "lrint", ctypes.c_int64, [ ("__x", ctypes.c_double),] ) llrint = _rpythonic_function_( "llrint", ctypes.c_longlong, [ ("__x", ctypes.c_double),] ) lround = _rpythonic_function_( "lround", ctypes.c_int64, [ ("__x", ctypes.c_double),] ) llround = _rpythonic_function_( "llround", ctypes.c_longlong, [ ("__x", ctypes.c_double),] ) isalnum = _rpythonic_function_( "isalnum", ctypes.c_int, [ ("none", ctypes.c_int),] ) isalpha = _rpythonic_function_( "isalpha", ctypes.c_int, [ ("none", ctypes.c_int),] ) iscntrl = _rpythonic_function_( "iscntrl", ctypes.c_int, [ ("none", ctypes.c_int),] ) isxdigit_l = _rpythonic_function_( "isxdigit_l", ctypes.c_int, [ ("none", ctypes.c_int), ("none", ctypes.POINTER(ctypes.c_void_p)),] ) isblank_l = _rpythonic_function_( "isblank_l", ctypes.c_int, [ ("none", ctypes.c_int), ("none", ctypes.POINTER(ctypes.c_void_p)),] ) tolower_l = _rpythonic_function_( "tolower_l", ctypes.c_int, [ ("__c", ctypes.c_int), ("__l", ctypes.POINTER(__locale_struct)),] ) tanhf = _rpythonic_function_( "tanhf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) acoshf = _rpythonic_function_( "acoshf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) asinhf = _rpythonic_function_( "asinhf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) sinf = _rpythonic_function_( "sinf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) tanf = _rpythonic_function_( "tanf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) coshf = _rpythonic_function_( "coshf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) sinhf = _rpythonic_function_( "sinhf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) atanf = _rpythonic_function_( "atanf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) atan2f = _rpythonic_function_( "atan2f", ctypes.c_float, [ ("__y", ctypes.c_float), ("__x", ctypes.c_float),] ) cosf = _rpythonic_function_( "cosf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) strtoimax = _rpythonic_function_( "strtoimax", ctypes.c_int64, [ ("__nptr", ctypes.POINTER(ctypes.c_char)), ("__endptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))), ("__base", ctypes.c_int),] ) strtoumax = _rpythonic_function_( "strtoumax", ctypes.c_uint64, [ ("__nptr", ctypes.POINTER(ctypes.c_char)), ("__endptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))), ("__base", ctypes.c_int),] ) wcstoimax = _rpythonic_function_( "wcstoimax", ctypes.c_int64, [ ("__nptr", ctypes.POINTER(ctypes.c_int)), ("__endptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_int))), ("__base", ctypes.c_int),] ) scalb = _rpythonic_function_( "scalb", ctypes.c_double, [ ("__x", ctypes.c_double), ("__n", ctypes.c_double),] ) asinf = _rpythonic_function_( "asinf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) acosf = _rpythonic_function_( "acosf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) tanh = _rpythonic_function_( "tanh", ctypes.c_double, [ ("__x", ctypes.c_double),] ) acosh = _rpythonic_function_( "acosh", ctypes.c_double, [ ("__x", ctypes.c_double),] ) asinh = _rpythonic_function_( "asinh", ctypes.c_double, [ ("__x", ctypes.c_double),] ) atanh = _rpythonic_function_( "atanh", ctypes.c_double, [ ("__x", ctypes.c_double),] ) fma = _rpythonic_function_( "fma", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double), ("__z", ctypes.c_double),] ) ceil = _rpythonic_function_( "ceil", ctypes.c_double, [ ("__x", ctypes.c_double),] ) fabs = _rpythonic_function_( "fabs", ctypes.c_double, [ ("__x", ctypes.c_double),] ) floor = _rpythonic_function_( "floor", ctypes.c_double, [ ("__x", ctypes.c_double),] ) fmod = _rpythonic_function_( "fmod", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) wcstoumax = _rpythonic_function_( "wcstoumax", ctypes.c_uint64, [ ("__nptr", ctypes.POINTER(ctypes.c_int)), ("__endptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_int))), ("__base", ctypes.c_int),] ) acos = _rpythonic_function_( "acos", ctypes.c_double, [ ("__x", ctypes.c_double),] ) asin = _rpythonic_function_( "asin", ctypes.c_double, [ ("__x", ctypes.c_double),] ) atan = _rpythonic_function_( "atan", ctypes.c_double, [ ("__x", ctypes.c_double),] ) ilogb = _rpythonic_function_( "ilogb", ctypes.c_int, [ ("__x", ctypes.c_double),] ) scalbln = _rpythonic_function_( "scalbln", ctypes.c_double, [ ("__x", ctypes.c_double), ("__n", ctypes.c_int64),] ) nearbyint = _rpythonic_function_( "nearbyint", ctypes.c_double, [ ("__x", ctypes.c_double),] ) tan = _rpythonic_function_( "tan", ctypes.c_double, [ ("__x", ctypes.c_double),] ) cosh = _rpythonic_function_( "cosh", ctypes.c_double, [ ("__x", ctypes.c_double),] ) sinh = _rpythonic_function_( "sinh", ctypes.c_double, [ ("__x", ctypes.c_double),] ) atan2 = _rpythonic_function_( "atan2", ctypes.c_double, [ ("__y", ctypes.c_double), ("__x", ctypes.c_double),] ) cos = _rpythonic_function_( "cos", ctypes.c_double, [ ("__x", ctypes.c_double),] ) sin = _rpythonic_function_( "sin", ctypes.c_double, [ ("__x", ctypes.c_double),] ) gets = _rpythonic_function_( "gets", ctypes.POINTER(ctypes.c_char), [ ("__s", ctypes.POINTER(ctypes.c_char)),] ) getline = _rpythonic_function_( "getline", ctypes.c_int64, [ ("__lineptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))), ("__n", ctypes.POINTER(ctypes.c_uint64)), ("__stream", ctypes.POINTER(_IO_FILE)),] ) getdelim = _rpythonic_function_( "getdelim", ctypes.c_int64, [ ("__lineptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))), ("__n", ctypes.POINTER(ctypes.c_uint64)), ("__delimiter", ctypes.c_int), ("__stream", ctypes.POINTER(_IO_FILE)),] ) fputs = _rpythonic_function_( "fputs", ctypes.c_int, [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__stream", ctypes.POINTER(_IO_FILE)),] ) ungetc = _rpythonic_function_( "ungetc", ctypes.c_int, [ ("__c", ctypes.c_int), ("__stream", ctypes.POINTER(_IO_FILE)),] ) puts = _rpythonic_function_( "puts", ctypes.c_int, [ ("__s", ctypes.POINTER(ctypes.c_char)),] ) fread = _rpythonic_function_( "fread", ctypes.c_uint64, [ ("__ptr", ctypes.POINTER(ctypes.c_void_p)), ("__size", ctypes.c_uint64), ("__n", ctypes.c_uint64), ("__stream", ctypes.POINTER(_IO_FILE)),] ) fseek = _rpythonic_function_( "fseek", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)), ("__off", ctypes.c_int64), ("__whence", ctypes.c_int),] ) ftell = _rpythonic_function_( "ftell", ctypes.c_int64, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) rewind = _rpythonic_function_( "rewind", ctypes.c_void_p, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) fseeko = _rpythonic_function_( "fseeko", ctypes.c_int, [ ("__stream", ctypes.POINTER(_IO_FILE)), ("__off", ctypes.c_int64), ("__whence", ctypes.c_int),] ) ftello = _rpythonic_function_( "ftello", ctypes.c_int64, [ ("__stream", ctypes.POINTER(_IO_FILE)),] ) qecvt = _rpythonic_function_( "qecvt", ctypes.POINTER(ctypes.c_char), [ ("__value", ctypes.c_double), ("__ndigit", ctypes.c_int), ("__decpt", ctypes.POINTER(ctypes.c_int)), ("__sign", ctypes.POINTER(ctypes.c_int)),] ) qfcvt = _rpythonic_function_( "qfcvt", ctypes.POINTER(ctypes.c_char), [ ("__value", ctypes.c_double), ("__ndigit", ctypes.c_int), ("__decpt", ctypes.POINTER(ctypes.c_int)), ("__sign", ctypes.POINTER(ctypes.c_int)),] ) qgcvt = _rpythonic_function_( "qgcvt", ctypes.POINTER(ctypes.c_char), [ ("__value", ctypes.c_double), ("__ndigit", ctypes.c_int), ("__buf", ctypes.POINTER(ctypes.c_char)),] ) gnu_dev_makedev = _rpythonic_function_( "gnu_dev_makedev", ctypes.c_ulonglong, [ ("__major", ctypes.c_uint), ("__minor", ctypes.c_uint),] ) random = _rpythonic_function_( "random", ctypes.c_int64, [] ) srandom = _rpythonic_function_( "srandom", ctypes.c_void_p, [ ("__seed", ctypes.c_uint),] ) initstate = _rpythonic_function_( "initstate", ctypes.POINTER(ctypes.c_char), [ ("__seed", ctypes.c_uint), ("__statebuf", ctypes.POINTER(ctypes.c_char)), ("__statelen", ctypes.c_uint64),] ) mrand48_r = _rpythonic_function_( "mrand48_r", ctypes.c_int, [ ("__buffer", ctypes.POINTER(drand48_data)), ("__result", ctypes.POINTER(ctypes.c_int64)),] ) jrand48_r = _rpythonic_function_( "jrand48_r", ctypes.c_int, [ ("__xsubi", ( ctypes.c_uint16 * 3 )), ("__buffer", ctypes.POINTER(drand48_data)), ("__result", ctypes.POINTER(ctypes.c_int64)),] ) srand48_r = _rpythonic_function_( "srand48_r", ctypes.c_int, [ ("__seedval", ctypes.c_int64), ("__buffer", ctypes.POINTER(drand48_data)),] ) seed48_r = _rpythonic_function_( "seed48_r", ctypes.c_int, [ ("__seed16v", ( ctypes.c_uint16 * 3 )), ("__buffer", ctypes.POINTER(drand48_data)),] ) lcong48_r = _rpythonic_function_( "lcong48_r", ctypes.c_int, [ ("__param", ( ctypes.c_uint16 * 7 )), ("__buffer", ctypes.POINTER(drand48_data)),] ) memchr = _rpythonic_function_( "memchr", ctypes.POINTER(ctypes.c_void_p), [ ("__s", ctypes.POINTER(ctypes.c_void_p)), ("__c", ctypes.c_int), ("__n", ctypes.c_uint64),] ) strcpy = _rpythonic_function_( "strcpy", ctypes.POINTER(ctypes.c_char), [ ("__dest", ctypes.POINTER(ctypes.c_char)), ("__src", ctypes.POINTER(ctypes.c_char)),] ) strncpy = _rpythonic_function_( "strncpy", ctypes.POINTER(ctypes.c_char), [ ("__dest", ctypes.POINTER(ctypes.c_char)), ("__src", ctypes.POINTER(ctypes.c_char)), ("__n", ctypes.c_uint64),] ) strcat = _rpythonic_function_( "strcat", ctypes.POINTER(ctypes.c_char), [ ("__dest", ctypes.POINTER(ctypes.c_char)), ("__src", ctypes.POINTER(ctypes.c_char)),] ) av_reduce = _rpythonic_function_( "av_reduce", ctypes.c_int, [ ("dst_num", ctypes.POINTER(ctypes.c_int)), ("dst_den", ctypes.POINTER(ctypes.c_int)), ("num", ctypes.c_int64), ("den", ctypes.c_int64), ("max", ctypes.c_int64),] ) av_mul_q = _rpythonic_function_( "av_mul_q", AVRational, [ ("b", AVRational), ("c", AVRational),] ) av_div_q = _rpythonic_function_( "av_div_q", AVRational, [ ("b", AVRational), ("c", AVRational),] ) memccpy = _rpythonic_function_( "memccpy", ctypes.POINTER(ctypes.c_void_p), [ ("__dest", ctypes.POINTER(ctypes.c_void_p)), ("__src", ctypes.POINTER(ctypes.c_void_p)), ("__c", ctypes.c_int), ("__n", ctypes.c_uint64),] ) memset = _rpythonic_function_( "memset", ctypes.POINTER(ctypes.c_void_p), [ ("__s", ctypes.POINTER(ctypes.c_void_p)), ("__c", ctypes.c_int), ("__n", ctypes.c_uint64),] ) memcmp = _rpythonic_function_( "memcmp", ctypes.c_int, [ ("__s1", ctypes.POINTER(ctypes.c_void_p)), ("__s2", ctypes.POINTER(ctypes.c_void_p)), ("__n", ctypes.c_uint64),] ) jrand48 = _rpythonic_function_( "jrand48", ctypes.c_int64, [ ("__xsubi", ( ctypes.c_uint16 * 3 )),] ) srand48 = _rpythonic_function_( "srand48", ctypes.c_void_p, [ ("__seedval", ctypes.c_int64),] ) seed48 = _rpythonic_function_( "seed48", ctypes.POINTER(ctypes.c_uint16), [ ("__seed16v", ( ctypes.c_uint16 * 3 )),] ) lcong48 = _rpythonic_function_( "lcong48", ctypes.c_void_p, [ ("__param", ( ctypes.c_uint16 * 7 )),] ) alloca = _rpythonic_function_( "alloca", ctypes.POINTER(ctypes.c_void_p), [ ("__size", ctypes.c_uint64),] ) valloc = _rpythonic_function_( "valloc", ctypes.POINTER(ctypes.c_void_p), [ ("__size", ctypes.c_uint64),] ) posix_memalign = _rpythonic_function_( "posix_memalign", ctypes.c_int, [ ("__memptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))), ("__alignment", ctypes.c_uint64), ("__size", ctypes.c_uint64),] ) abort = _rpythonic_function_( "abort", ctypes.c_void_p, [] ) atexit = _rpythonic_function_( "atexit", ctypes.c_int, [ ("__func", ctypes.c_void_p),] ) srandom_r = _rpythonic_function_( "srandom_r", ctypes.c_int, [ ("__seed", ctypes.c_uint), ("__buf", ctypes.POINTER(random_data)),] ) initstate_r = _rpythonic_function_( "initstate_r", ctypes.c_int, [ ("__seed", ctypes.c_uint), ("__statebuf", ctypes.POINTER(ctypes.c_char)), ("__statelen", ctypes.c_uint64), ("__buf", ctypes.POINTER(random_data)),] ) setstate_r = _rpythonic_function_( "setstate_r", ctypes.c_int, [ ("__statebuf", ctypes.POINTER(ctypes.c_char)), ("__buf", ctypes.POINTER(random_data)),] ) rand = _rpythonic_function_( "rand", ctypes.c_int, [] ) av_log_get_level = _rpythonic_function_( "av_log_get_level", ctypes.c_int, [] ) av_log_set_level = _rpythonic_function_( "av_log_set_level", ctypes.c_void_p, [ ("none", ctypes.c_int),] ) av_log_set_callback = _rpythonic_function_( "av_log_set_callback", ctypes.c_void_p, [ ("none", ctypes.c_void_p),] ) av_log_default_callback = _rpythonic_function_( "av_log_default_callback", ctypes.c_void_p, [ ("ptr", ctypes.POINTER(ctypes.c_void_p)), ("level", ctypes.c_int), ("fmt", ctypes.POINTER(ctypes.c_char)), ("vl", ctypes.c_char),] ) strncat = _rpythonic_function_( "strncat", ctypes.POINTER(ctypes.c_char), [ ("__dest", ctypes.POINTER(ctypes.c_char)), ("__src", ctypes.POINTER(ctypes.c_char)), ("__n", ctypes.c_uint64),] ) strcmp = _rpythonic_function_( "strcmp", ctypes.c_int, [ ("__s1", ctypes.POINTER(ctypes.c_char)), ("__s2", ctypes.POINTER(ctypes.c_char)),] ) strncmp = _rpythonic_function_( "strncmp", ctypes.c_int, [ ("__s1", ctypes.POINTER(ctypes.c_char)), ("__s2", ctypes.POINTER(ctypes.c_char)), ("__n", ctypes.c_uint64),] ) mkstemp = _rpythonic_function_( "mkstemp", ctypes.c_int, [ ("__template", ctypes.POINTER(ctypes.c_char)),] ) mkstemps = _rpythonic_function_( "mkstemps", ctypes.c_int, [ ("__template", ctypes.POINTER(ctypes.c_char)), ("__suffixlen", ctypes.c_int),] ) mkdtemp = _rpythonic_function_( "mkdtemp", ctypes.POINTER(ctypes.c_char), [ ("__template", ctypes.POINTER(ctypes.c_char)),] ) system = _rpythonic_function_( "system", ctypes.c_int, [ ("__command", ctypes.POINTER(ctypes.c_char)),] ) realpath = _rpythonic_function_( "realpath", ctypes.POINTER(ctypes.c_char), [ ("__name", ctypes.POINTER(ctypes.c_char)), ("__resolved", ctypes.POINTER(ctypes.c_char)),] ) abs = _rpythonic_function_( "abs", ctypes.c_int, [ ("__x", ctypes.c_int),] ) labs = _rpythonic_function_( "labs", ctypes.c_int64, [ ("__x", ctypes.c_int64),] ) llabs = _rpythonic_function_( "llabs", ctypes.c_longlong, [ ("__x", ctypes.c_longlong),] ) div = _rpythonic_function_( "div", div_t, [ ("__numer", ctypes.c_int), ("__denom", ctypes.c_int),] ) ldiv = _rpythonic_function_( "ldiv", ldiv_t, [ ("__numer", ctypes.c_int64), ("__denom", ctypes.c_int64),] ) lldiv = _rpythonic_function_( "lldiv", lldiv_t, [ ("__numer", ctypes.c_longlong), ("__denom", ctypes.c_longlong),] ) av_malloc = _rpythonic_function_( "av_malloc", ctypes.POINTER(ctypes.c_void_p), [ ("size", ctypes.c_uint64),] ) av_realloc = _rpythonic_function_( "av_realloc", ctypes.POINTER(ctypes.c_void_p), [ ("ptr", ctypes.POINTER(ctypes.c_void_p)), ("size", ctypes.c_uint64),] ) av_free = _rpythonic_function_( "av_free", ctypes.c_void_p, [("ptr", ctypes.c_void_p)] ) av_mallocz = _rpythonic_function_( "av_mallocz", ctypes.POINTER(ctypes.c_void_p), [ ("size", ctypes.c_uint64),] ) av_strdup = _rpythonic_function_( "av_strdup", ctypes.POINTER(ctypes.c_char), [ ("s", ctypes.POINTER(ctypes.c_char)),] ) mbstowcs = _rpythonic_function_( "mbstowcs", ctypes.c_uint64, [ ("__pwcs", ctypes.POINTER(ctypes.c_int)), ("__s", ctypes.POINTER(ctypes.c_char)), ("__n", ctypes.c_uint64),] ) wctomb = _rpythonic_function_( "wctomb", ctypes.c_int, [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__wchar", ctypes.c_int),] ) wcstombs = _rpythonic_function_( "wcstombs", ctypes.c_uint64, [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__pwcs", ctypes.POINTER(ctypes.c_int)), ("__n", ctypes.c_uint64),] ) rpmatch = _rpythonic_function_( "rpmatch", ctypes.c_int, [ ("__response", ctypes.POINTER(ctypes.c_char)),] ) srand = _rpythonic_function_( "srand", ctypes.c_void_p, [ ("__seed", ctypes.c_uint),] ) rand_r = _rpythonic_function_( "rand_r", ctypes.c_int, [ ("__seed", ctypes.POINTER(ctypes.c_uint)),] ) drand48 = _rpythonic_function_( "drand48", ctypes.c_double, [] ) erand48 = _rpythonic_function_( "erand48", ctypes.c_double, [ ("__xsubi", ( ctypes.c_uint16 * 3 )),] ) lrand48 = _rpythonic_function_( "lrand48", ctypes.c_int64, [] ) nrand48 = _rpythonic_function_( "nrand48", ctypes.c_int64, [ ("__xsubi", ( ctypes.c_uint16 * 3 )),] ) mrand48 = _rpythonic_function_( "mrand48", ctypes.c_int64, [] ) getsubopt = _rpythonic_function_( "getsubopt", ctypes.c_int, [ ("__optionp", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))), ("__tokens", ctypes.POINTER(ctypes.c_char)), ("__valuep", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))),] ) getloadavg = _rpythonic_function_( "getloadavg", ctypes.c_int, [ ("__loadavg", ctypes.c_double), ("__nelem", ctypes.c_int),] ) memcpy = _rpythonic_function_( "memcpy", ctypes.POINTER(ctypes.c_void_p), [ ("__dest", ctypes.POINTER(ctypes.c_void_p)), ("__src", ctypes.POINTER(ctypes.c_void_p)), ("__n", ctypes.c_uint64),] ) memmove = _rpythonic_function_( "memmove", ctypes.POINTER(ctypes.c_void_p), [ ("__dest", ctypes.POINTER(ctypes.c_void_p)), ("__src", ctypes.POINTER(ctypes.c_void_p)), ("__n", ctypes.c_uint64),] ) bsearch = _rpythonic_function_( "bsearch", ctypes.POINTER(ctypes.c_void_p), [ ("__key", ctypes.POINTER(ctypes.c_void_p)), ("__base", ctypes.POINTER(ctypes.c_void_p)), ("__nmemb", ctypes.c_uint64), ("__size", ctypes.c_uint64), ("__compar", ctypes.CFUNCTYPE(ctypes.c_int, ctypes.POINTER(ctypes.c_void_p),ctypes.POINTER(ctypes.c_void_p),)),] ) qsort = _rpythonic_function_( "qsort", ctypes.c_void_p, [ ("__base", ctypes.POINTER(ctypes.c_void_p)), ("__nmemb", ctypes.c_uint64), ("__size", ctypes.c_uint64), ("__compar", ctypes.CFUNCTYPE(ctypes.c_int, ctypes.POINTER(ctypes.c_void_p),ctypes.POINTER(ctypes.c_void_p),)),] ) av_default_item_name = _rpythonic_function_( "av_default_item_name", ctypes.POINTER(ctypes.c_char), [("ctx", ctypes.c_void_p)] ) av_log_set_flags = _rpythonic_function_( "av_log_set_flags", ctypes.c_void_p, [ ("arg", ctypes.c_int),] ) av_get_sample_fmt_name = _rpythonic_function_( "av_get_sample_fmt_name", ctypes.POINTER(ctypes.c_char), [ ("sample_fmt", ctypes.c_int),] ) av_get_sample_fmt = _rpythonic_function_( "av_get_sample_fmt", ctypes.c_int, [ ("name", ctypes.POINTER(ctypes.c_char)),] ) av_get_sample_fmt_string = _rpythonic_function_( "av_get_sample_fmt_string", ctypes.POINTER(ctypes.c_char), [ ("buf", ctypes.POINTER(ctypes.c_char)), ("buf_size", ctypes.c_int), ("sample_fmt", ctypes.c_int),] ) av_freep = _rpythonic_function_( "av_freep", ctypes.c_void_p, [("ptr", ctypes.c_void_p)] ) av_strerror = _rpythonic_function_( "av_strerror", ctypes.c_int, [ ("errnum", ctypes.c_int), ("errbuf", ctypes.POINTER(ctypes.c_char)), ("errbuf_size", ctypes.c_uint64),] ) on_exit = _rpythonic_function_( "on_exit", ctypes.c_int, [ ("__func", ctypes.c_void_p), ("__arg", ctypes.POINTER(ctypes.c_void_p)),] ) exit = _rpythonic_function_( "exit", ctypes.c_void_p, [ ("__status", ctypes.c_int),] ) _Exit = _rpythonic_function_( "_Exit", ctypes.c_void_p, [ ("__status", ctypes.c_int),] ) getenv = _rpythonic_function_( "getenv", ctypes.POINTER(ctypes.c_char), [ ("__name", ctypes.POINTER(ctypes.c_char)),] ) av_compare_ts = _rpythonic_function_( "av_compare_ts", ctypes.c_int, [ ("ts_a", ctypes.c_int64), ("tb_a", AVRational), ("ts_b", ctypes.c_int64), ("tb_b", AVRational),] ) av_compare_mod = _rpythonic_function_( "av_compare_mod", ctypes.c_int64, [ ("a", ctypes.c_uint64), ("b", ctypes.c_uint64), ("mod", ctypes.c_uint64),] ) av_int2flt = _rpythonic_function_( "av_int2flt", ctypes.c_float, [ ("v", ctypes.c_int32),] ) av_int2dbl = _rpythonic_function_( "av_int2dbl", ctypes.c_double, [ ("v", ctypes.c_int64),] ) av_ext2dbl = _rpythonic_function_( "av_ext2dbl", ctypes.c_double, [ ("ext", AVExtFloat),] ) av_dict_get = _rpythonic_function_( "av_dict_get", ctypes.POINTER(AVDictionaryEntry), [ ("m", ctypes.POINTER(AVDictionary)), ("key", ctypes.POINTER(ctypes.c_char)), ("prev", ctypes.POINTER(AVDictionaryEntry)), ("flags", ctypes.c_int),] ) av_dict_set = _rpythonic_function_( "av_dict_set", ctypes.c_int, [ ("pm", ctypes.POINTER(ctypes.POINTER(AVDictionary))), ("key", ctypes.POINTER(ctypes.c_char)), ("value", ctypes.POINTER(ctypes.c_char)), ("flags", ctypes.c_int),] ) av_dict_copy = _rpythonic_function_( "av_dict_copy", ctypes.c_void_p, [ ("dst", ctypes.POINTER(ctypes.POINTER(AVDictionary))), ("src", ctypes.POINTER(AVDictionary)), ("flags", ctypes.c_int),] ) strcoll = _rpythonic_function_( "strcoll", ctypes.c_int, [ ("__s1", ctypes.POINTER(ctypes.c_char)), ("__s2", ctypes.POINTER(ctypes.c_char)),] ) strxfrm = _rpythonic_function_( "strxfrm", ctypes.c_uint64, [ ("__dest", ctypes.POINTER(ctypes.c_char)), ("__src", ctypes.POINTER(ctypes.c_char)), ("__n", ctypes.c_uint64),] ) strcoll_l = _rpythonic_function_( "strcoll_l", ctypes.c_int, [ ("__s1", ctypes.POINTER(ctypes.c_char)), ("__s2", ctypes.POINTER(ctypes.c_char)), ("__l", ctypes.POINTER(__locale_struct)),] ) strxfrm_l = _rpythonic_function_( "strxfrm_l", ctypes.c_uint64, [ ("__dest", ctypes.POINTER(ctypes.c_char)), ("__src", ctypes.POINTER(ctypes.c_char)), ("__n", ctypes.c_uint64), ("__l", ctypes.POINTER(__locale_struct)),] ) av_dict_free = _rpythonic_function_( "av_dict_free", ctypes.c_void_p, [ ("m", ctypes.POINTER(ctypes.POINTER(AVDictionary))),] ) av_get_channel_layout = _rpythonic_function_( "av_get_channel_layout", ctypes.c_int64, [ ("name", ctypes.POINTER(ctypes.c_char)),] ) av_get_channel_layout_string = _rpythonic_function_( "av_get_channel_layout_string", ctypes.c_void_p, [ ("buf", ctypes.POINTER(ctypes.c_char)), ("buf_size", ctypes.c_int), ("nb_channels", ctypes.c_int), ("channel_layout", ctypes.c_int64),] ) av_get_channel_layout_nb_channels = _rpythonic_function_( "av_get_channel_layout_nb_channels", ctypes.c_int, [ ("channel_layout", ctypes.c_int64),] ) drand48_r = _rpythonic_function_( "drand48_r", ctypes.c_int, [ ("__buffer", ctypes.POINTER(drand48_data)), ("__result", ctypes.POINTER(ctypes.c_double)),] ) erand48_r = _rpythonic_function_( "erand48_r", ctypes.c_int, [ ("__xsubi", ( ctypes.c_uint16 * 3 )), ("__buffer", ctypes.POINTER(drand48_data)), ("__result", ctypes.POINTER(ctypes.c_double)),] ) lrand48_r = _rpythonic_function_( "lrand48_r", ctypes.c_int, [ ("__buffer", ctypes.POINTER(drand48_data)), ("__result", ctypes.POINTER(ctypes.c_int64)),] ) nrand48_r = _rpythonic_function_( "nrand48_r", ctypes.c_int, [ ("__xsubi", ( ctypes.c_uint16 * 3 )), ("__buffer", ctypes.POINTER(drand48_data)), ("__result", ctypes.POINTER(ctypes.c_int64)),] ) strcspn = _rpythonic_function_( "strcspn", ctypes.c_uint64, [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__reject", ctypes.POINTER(ctypes.c_char)),] ) strspn = _rpythonic_function_( "strspn", ctypes.c_uint64, [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__accept", ctypes.POINTER(ctypes.c_char)),] ) strpbrk = _rpythonic_function_( "strpbrk", ctypes.POINTER(ctypes.c_char), [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__accept", ctypes.POINTER(ctypes.c_char)),] ) strstr = _rpythonic_function_( "strstr", ctypes.POINTER(ctypes.c_char), [ ("__haystack", ctypes.POINTER(ctypes.c_char)), ("__needle", ctypes.POINTER(ctypes.c_char)),] ) strtok = _rpythonic_function_( "strtok", ctypes.POINTER(ctypes.c_char), [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__delim", ctypes.POINTER(ctypes.c_char)),] ) strdup = _rpythonic_function_( "strdup", ctypes.POINTER(ctypes.c_char), [ ("__s", ctypes.POINTER(ctypes.c_char)),] ) strndup = _rpythonic_function_( "strndup", ctypes.POINTER(ctypes.c_char), [ ("__string", ctypes.POINTER(ctypes.c_char)), ("__n", ctypes.c_uint64),] ) strchr = _rpythonic_function_( "strchr", ctypes.POINTER(ctypes.c_char), [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__c", ctypes.c_int),] ) strrchr = _rpythonic_function_( "strrchr", ctypes.POINTER(ctypes.c_char), [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__c", ctypes.c_int),] ) strtok_r = _rpythonic_function_( "strtok_r", ctypes.POINTER(ctypes.c_char), [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__delim", ctypes.POINTER(ctypes.c_char)), ("__save_ptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))),] ) strlen = _rpythonic_function_( "strlen", ctypes.c_uint64, [ ("__s", ctypes.POINTER(ctypes.c_char)),] ) strnlen = _rpythonic_function_( "strnlen", ctypes.c_uint64, [ ("__string", ctypes.POINTER(ctypes.c_char)), ("__maxlen", ctypes.c_uint64),] ) strerror = _rpythonic_function_( "strerror", ctypes.POINTER(ctypes.c_char), [ ("__errnum", ctypes.c_int),] ) strerror_r = _rpythonic_function_( "strerror_r", ctypes.c_int, [ ("__errnum", ctypes.c_int), ("__buf", ctypes.POINTER(ctypes.c_char)), ("__buflen", ctypes.c_uint64),] ) strerror_l = _rpythonic_function_( "strerror_l", ctypes.POINTER(ctypes.c_char), [ ("__errnum", ctypes.c_int), ("__l", ctypes.POINTER(__locale_struct)),] ) bcopy = _rpythonic_function_( "bcopy", ctypes.c_void_p, [ ("__src", ctypes.POINTER(ctypes.c_void_p)), ("__dest", ctypes.POINTER(ctypes.c_void_p)), ("__n", ctypes.c_uint64),] ) bzero = _rpythonic_function_( "bzero", ctypes.c_void_p, [ ("__s", ctypes.POINTER(ctypes.c_void_p)), ("__n", ctypes.c_uint64),] ) bcmp = _rpythonic_function_( "bcmp", ctypes.c_int, [ ("__s1", ctypes.POINTER(ctypes.c_void_p)), ("__s2", ctypes.POINTER(ctypes.c_void_p)), ("__n", ctypes.c_uint64),] ) index = _rpythonic_function_( "index", ctypes.POINTER(ctypes.c_char), [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__c", ctypes.c_int),] ) strsignal = _rpythonic_function_( "strsignal", ctypes.POINTER(ctypes.c_char), [ ("__sig", ctypes.c_int),] ) stpcpy = _rpythonic_function_( "stpcpy", ctypes.POINTER(ctypes.c_char), [ ("__dest", ctypes.POINTER(ctypes.c_char)), ("__src", ctypes.POINTER(ctypes.c_char)),] ) malloc = _rpythonic_function_( "malloc", ctypes.POINTER(ctypes.c_void_p), [ ("__size", ctypes.c_uint64),] ) calloc = _rpythonic_function_( "calloc", ctypes.POINTER(ctypes.c_void_p), [ ("__nmemb", ctypes.c_uint64), ("__size", ctypes.c_uint64),] ) realloc = _rpythonic_function_( "realloc", ctypes.POINTER(ctypes.c_void_p), [ ("__ptr", ctypes.POINTER(ctypes.c_void_p)), ("__size", ctypes.c_uint64),] ) free = _rpythonic_function_( "free", ctypes.c_void_p, [("__ptr", ctypes.c_void_p)] ) cfree = _rpythonic_function_( "cfree", ctypes.c_void_p, [("__ptr", ctypes.c_void_p)] ) setstate = _rpythonic_function_( "setstate", ctypes.POINTER(ctypes.c_char), [ ("__statebuf", ctypes.POINTER(ctypes.c_char)),] ) random_r = _rpythonic_function_( "random_r", ctypes.c_int, [ ("__buf", ctypes.POINTER(random_data)), ("__result", ctypes.POINTER(ctypes.c_int32)),] ) rindex = _rpythonic_function_( "rindex", ctypes.POINTER(ctypes.c_char), [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__c", ctypes.c_int),] ) ffs = _rpythonic_function_( "ffs", ctypes.c_int, [ ("__i", ctypes.c_int),] ) strncasecmp = _rpythonic_function_( "strncasecmp", ctypes.c_int, [ ("__s1", ctypes.POINTER(ctypes.c_char)), ("__s2", ctypes.POINTER(ctypes.c_char)), ("__n", ctypes.c_uint64),] ) strcasecmp = _rpythonic_function_( "strcasecmp", ctypes.c_int, [ ("__s1", ctypes.POINTER(ctypes.c_char)), ("__s2", ctypes.POINTER(ctypes.c_char)),] ) strsep = _rpythonic_function_( "strsep", ctypes.POINTER(ctypes.c_char), [ ("__stringp", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))), ("__delim", ctypes.POINTER(ctypes.c_char)),] ) ecvt_r = _rpythonic_function_( "ecvt_r", ctypes.c_int, [ ("__value", ctypes.c_double), ("__ndigit", ctypes.c_int), ("__decpt", ctypes.POINTER(ctypes.c_int)), ("__sign", ctypes.POINTER(ctypes.c_int)), ("__buf", ctypes.POINTER(ctypes.c_char)), ("__len", ctypes.c_uint64),] ) fcvt_r = _rpythonic_function_( "fcvt_r", ctypes.c_int, [ ("__value", ctypes.c_double), ("__ndigit", ctypes.c_int), ("__decpt", ctypes.POINTER(ctypes.c_int)), ("__sign", ctypes.POINTER(ctypes.c_int)), ("__buf", ctypes.POINTER(ctypes.c_char)), ("__len", ctypes.c_uint64),] ) qecvt_r = _rpythonic_function_( "qecvt_r", ctypes.c_int, [ ("__value", ctypes.c_double), ("__ndigit", ctypes.c_int), ("__decpt", ctypes.POINTER(ctypes.c_int)), ("__sign", ctypes.POINTER(ctypes.c_int)), ("__buf", ctypes.POINTER(ctypes.c_char)), ("__len", ctypes.c_uint64),] ) qfcvt_r = _rpythonic_function_( "qfcvt_r", ctypes.c_int, [ ("__value", ctypes.c_double), ("__ndigit", ctypes.c_int), ("__decpt", ctypes.POINTER(ctypes.c_int)), ("__sign", ctypes.POINTER(ctypes.c_int)), ("__buf", ctypes.POINTER(ctypes.c_char)), ("__len", ctypes.c_uint64),] ) mblen = _rpythonic_function_( "mblen", ctypes.c_int, [ ("__s", ctypes.POINTER(ctypes.c_char)), ("__n", ctypes.c_uint64),] ) mbtowc = _rpythonic_function_( "mbtowc", ctypes.c_int, [ ("__pwc", ctypes.POINTER(ctypes.c_int)), ("__s", ctypes.POINTER(ctypes.c_char)), ("__n", ctypes.c_uint64),] ) av_get_bits_per_sample_fmt = _rpythonic_function_( "av_get_bits_per_sample_fmt", ctypes.c_int, [ ("sample_fmt", ctypes.c_int),] ) av_get_bytes_per_sample = _rpythonic_function_( "av_get_bytes_per_sample", ctypes.c_int, [ ("sample_fmt", ctypes.c_int),] ) av_get_cpu_flags = _rpythonic_function_( "av_get_cpu_flags", ctypes.c_int, [] ) ff_get_cpu_flags_arm = _rpythonic_function_( "ff_get_cpu_flags_arm", ctypes.c_int, [] ) ff_get_cpu_flags_ppc = _rpythonic_function_( "ff_get_cpu_flags_ppc", ctypes.c_int, [] ) ff_get_cpu_flags_x86 = _rpythonic_function_( "ff_get_cpu_flags_x86", ctypes.c_int, [] ) av_dbl2int = _rpythonic_function_( "av_dbl2int", ctypes.c_int64, [ ("d", ctypes.c_double),] ) av_flt2int = _rpythonic_function_( "av_flt2int", ctypes.c_int32, [ ("d", ctypes.c_float),] ) av_dbl2ext = _rpythonic_function_( "av_dbl2ext", AVExtFloat, [ ("d", ctypes.c_double),] ) item_name = _rpythonic_function_( "item_name", ctypes.POINTER(ctypes.c_char), [("ctx", ctypes.c_void_p)] ) av_gcd = _rpythonic_function_( "av_gcd", ctypes.c_int64, [ ("a", ctypes.c_int64), ("b", ctypes.c_int64),] ) av_rescale = _rpythonic_function_( "av_rescale", ctypes.c_int64, [ ("a", ctypes.c_int64), ("b", ctypes.c_int64), ("c", ctypes.c_int64),] ) av_rescale_rnd = _rpythonic_function_( "av_rescale_rnd", ctypes.c_int64, [ ("a", ctypes.c_int64), ("b", ctypes.c_int64), ("c", ctypes.c_int64), ("AVRounding", ctypes.c_int),] ) av_rescale_q = _rpythonic_function_( "av_rescale_q", ctypes.c_int64, [ ("a", ctypes.c_int64), ("bq", AVRational), ("cq", AVRational),] ) opt_find = _rpythonic_function_( "opt_find", ctypes.POINTER(AVOption), [ ("obj", ctypes.POINTER(ctypes.c_void_p)), ("name", ctypes.POINTER(ctypes.c_char)), ("unit", ctypes.POINTER(ctypes.c_char)), ("opt_flags", ctypes.c_int), ("search_flags", ctypes.c_int),] ) av_log = _rpythonic_function_( "av_log", ctypes.c_void_p, [ ("avcl", ctypes.POINTER(ctypes.c_void_p)), ("level", ctypes.c_int), ("fmt", ctypes.POINTER(ctypes.c_char)),] ) av_vlog = _rpythonic_function_( "av_vlog", ctypes.c_void_p, [ ("avcl", ctypes.POINTER(ctypes.c_void_p)), ("level", ctypes.c_int), ("fmt", ctypes.POINTER(ctypes.c_char)), ("none", ctypes.c_char),] ) stpncpy = _rpythonic_function_( "stpncpy", ctypes.POINTER(ctypes.c_char), [ ("__dest", ctypes.POINTER(ctypes.c_char)), ("__src", ctypes.POINTER(ctypes.c_char)), ("__n", ctypes.c_uint64),] ) putenv = _rpythonic_function_( "putenv", ctypes.c_int, [ ("__string", ctypes.POINTER(ctypes.c_char)),] ) setenv = _rpythonic_function_( "setenv", ctypes.c_int, [ ("__name", ctypes.POINTER(ctypes.c_char)), ("__value", ctypes.POINTER(ctypes.c_char)), ("__replace", ctypes.c_int),] ) unsetenv = _rpythonic_function_( "unsetenv", ctypes.c_int, [ ("__name", ctypes.POINTER(ctypes.c_char)),] ) clearenv = _rpythonic_function_( "clearenv", ctypes.c_int, [] ) mktemp = _rpythonic_function_( "mktemp", ctypes.POINTER(ctypes.c_char), [ ("__template", ctypes.POINTER(ctypes.c_char)),] ) av_add_q = _rpythonic_function_( "av_add_q", AVRational, [ ("b", AVRational), ("c", AVRational),] ) av_sub_q = _rpythonic_function_( "av_sub_q", AVRational, [ ("b", AVRational), ("c", AVRational),] ) av_d2q = _rpythonic_function_( "av_d2q", AVRational, [ ("d", ctypes.c_double), ("max", ctypes.c_int),] ) av_nearer_q = _rpythonic_function_( "av_nearer_q", ctypes.c_int, [ ("q", AVRational), ("q1", AVRational), ("q2", AVRational),] ) av_find_nearest_q_idx = _rpythonic_function_( "av_find_nearest_q_idx", ctypes.c_int, [ ("q", AVRational), ("q_list", ctypes.POINTER(AVRational)),] ) ecvt = _rpythonic_function_( "ecvt", ctypes.POINTER(ctypes.c_char), [ ("__value", ctypes.c_double), ("__ndigit", ctypes.c_int), ("__decpt", ctypes.POINTER(ctypes.c_int)), ("__sign", ctypes.POINTER(ctypes.c_int)),] ) fcvt = _rpythonic_function_( "fcvt", ctypes.POINTER(ctypes.c_char), [ ("__value", ctypes.c_double), ("__ndigit", ctypes.c_int), ("__decpt", ctypes.POINTER(ctypes.c_int)), ("__sign", ctypes.POINTER(ctypes.c_int)),] ) gcvt = _rpythonic_function_( "gcvt", ctypes.POINTER(ctypes.c_char), [ ("__value", ctypes.c_double), ("__ndigit", ctypes.c_int), ("__buf", ctypes.POINTER(ctypes.c_char)),] ) udp_get_local_port = _rpythonic_function_( "udp_get_local_port", ctypes.c_int, [ ("h", ctypes.POINTER(URLContext)),] ) init_checksum = _rpythonic_function_( "init_checksum", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("update_checksum", ctypes.c_void_p), ("checksum", ctypes.c_ulong),] ) put_strz = _rpythonic_function_( "put_strz", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("buf", ctypes.POINTER(ctypes.c_char)),] ) get_checksum = _rpythonic_function_( "get_checksum", ctypes.c_ulong, [ ("s", ctypes.POINTER(AVIOContext)),] ) put_buffer = _rpythonic_function_( "put_buffer", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("buf", ctypes.POINTER(ctypes.c_ubyte)), ("size", ctypes.c_int),] ) put_le64 = _rpythonic_function_( "put_le64", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint64),] ) put_be64 = _rpythonic_function_( "put_be64", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint64),] ) put_le32 = _rpythonic_function_( "put_le32", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint),] ) put_be32 = _rpythonic_function_( "put_be32", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint),] ) av_metadata_get = _rpythonic_function_( "av_metadata_get", ctypes.POINTER(AVDictionaryEntry), [ ("m", ctypes.POINTER(AVDictionary)), ("key", ctypes.POINTER(ctypes.c_char)), ("prev", ctypes.POINTER(AVDictionaryEntry)), ("flags", ctypes.c_int),] ) av_metadata_set2 = _rpythonic_function_( "av_metadata_set2", ctypes.c_int, [ ("pm", ctypes.POINTER(ctypes.POINTER(AVDictionary))), ("key", ctypes.POINTER(ctypes.c_char)), ("value", ctypes.POINTER(ctypes.c_char)), ("flags", ctypes.c_int),] ) av_metadata_conv = _rpythonic_function_( "av_metadata_conv", ctypes.c_void_p, [ ("ctx", ctypes.POINTER(AVFormatContext)), ("d_conv", ctypes.POINTER(AVMetadataConv)), ("s_conv", ctypes.POINTER(AVMetadataConv)),] ) avio_check = _rpythonic_function_( "avio_check", ctypes.c_int, [ ("url", ctypes.POINTER(ctypes.c_char)), ("flags", ctypes.c_int),] ) avio_set_interrupt_cb = _rpythonic_function_( "avio_set_interrupt_cb", ctypes.c_void_p, [ ("interrupt_cb", ctypes.c_void_p),] ) avio_alloc_context = _rpythonic_function_( "avio_alloc_context", ctypes.POINTER(AVIOContext), [ ("buffer", ctypes.POINTER(ctypes.c_ubyte)), ("buffer_size", ctypes.c_int), ("write_flag", ctypes.c_int), ("opaque", ctypes.POINTER(ctypes.c_void_p)), ("read_packet", ctypes.c_void_p), ("write_packet", ctypes.c_void_p), ("seek", ctypes.c_void_p),] ) url_close_dyn_buf = _rpythonic_function_( "url_close_dyn_buf", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)), ("pbuffer", ctypes.POINTER(ctypes.POINTER(ctypes.c_uint8))),] ) url_fdopen = _rpythonic_function_( "url_fdopen", ctypes.c_int, [ ("s", ctypes.POINTER(ctypes.POINTER(AVIOContext))), ("h", ctypes.POINTER(URLContext)),] ) url_feof = _rpythonic_function_( "url_feof", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)),] ) url_ferror = _rpythonic_function_( "url_ferror", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)),] ) udp_set_remote_url = _rpythonic_function_( "udp_set_remote_url", ctypes.c_int, [ ("h", ctypes.POINTER(URLContext)), ("uri", ctypes.POINTER(ctypes.c_char)),] ) avio_rb32 = _rpythonic_function_( "avio_rb32", ctypes.c_uint, [ ("s", ctypes.POINTER(AVIOContext)),] ) avio_rb64 = _rpythonic_function_( "avio_rb64", ctypes.c_uint64, [ ("s", ctypes.POINTER(AVIOContext)),] ) avio_get_str = _rpythonic_function_( "avio_get_str", ctypes.c_int, [ ("pb", ctypes.POINTER(AVIOContext)), ("maxlen", ctypes.c_int), ("buf", ctypes.POINTER(ctypes.c_char)), ("buflen", ctypes.c_int),] ) avio_get_str16le = _rpythonic_function_( "avio_get_str16le", ctypes.c_int, [ ("pb", ctypes.POINTER(AVIOContext)), ("maxlen", ctypes.c_int), ("buf", ctypes.POINTER(ctypes.c_char)), ("buflen", ctypes.c_int),] ) get_byte = _rpythonic_function_( "get_byte", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)),] ) get_le16 = _rpythonic_function_( "get_le16", ctypes.c_uint, [ ("s", ctypes.POINTER(AVIOContext)),] ) get_le24 = _rpythonic_function_( "get_le24", ctypes.c_uint, [ ("s", ctypes.POINTER(AVIOContext)),] ) get_le32 = _rpythonic_function_( "get_le32", ctypes.c_uint, [ ("s", ctypes.POINTER(AVIOContext)),] ) get_le64 = _rpythonic_function_( "get_le64", ctypes.c_uint64, [ ("s", ctypes.POINTER(AVIOContext)),] ) get_be16 = _rpythonic_function_( "get_be16", ctypes.c_uint, [ ("s", ctypes.POINTER(AVIOContext)),] ) avio_enum_protocols = _rpythonic_function_( "avio_enum_protocols", ctypes.POINTER(ctypes.c_char), [ ("opaque", ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))), ("output", ctypes.c_int),] ) avio_pause = _rpythonic_function_( "avio_pause", ctypes.c_int, [ ("h", ctypes.POINTER(AVIOContext)), ("pause", ctypes.c_int),] ) avio_seek_time = _rpythonic_function_( "avio_seek_time", ctypes.c_int64, [ ("h", ctypes.POINTER(AVIOContext)), ("stream_index", ctypes.c_int), ("timestamp", ctypes.c_int64), ("flags", ctypes.c_int),] ) url_fclose = _rpythonic_function_( "url_fclose", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)),] ) url_fseek = _rpythonic_function_( "url_fseek", ctypes.c_int64, [ ("s", ctypes.POINTER(AVIOContext)), ("offset", ctypes.c_int64), ("whence", ctypes.c_int),] ) url_fskip = _rpythonic_function_( "url_fskip", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)), ("offset", ctypes.c_int64),] ) url_ftell = _rpythonic_function_( "url_ftell", ctypes.c_int64, [ ("s", ctypes.POINTER(AVIOContext)),] ) url_fgetc = _rpythonic_function_( "url_fgetc", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)),] ) url_fsize = _rpythonic_function_( "url_fsize", ctypes.c_int64, [ ("s", ctypes.POINTER(AVIOContext)),] ) av_metadata_copy = _rpythonic_function_( "av_metadata_copy", ctypes.c_void_p, [ ("dst", ctypes.POINTER(ctypes.POINTER(AVDictionary))), ("src", ctypes.POINTER(AVDictionary)), ("flags", ctypes.c_int),] ) av_metadata_free = _rpythonic_function_( "av_metadata_free", ctypes.c_void_p, [ ("m", ctypes.POINTER(ctypes.POINTER(AVDictionary))),] ) av_get_packet = _rpythonic_function_( "av_get_packet", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)), ("pkt", ctypes.POINTER(AVPacket)), ("size", ctypes.c_int),] ) av_append_packet = _rpythonic_function_( "av_append_packet", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)), ("pkt", ctypes.POINTER(AVPacket)), ("size", ctypes.c_int),] ) url_setbufsize = _rpythonic_function_( "url_setbufsize", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)), ("buf_size", ctypes.c_int),] ) url_fprintf = _rpythonic_function_( "url_fprintf", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)), ("fmt", ctypes.POINTER(ctypes.c_char)),] ) put_flush_packet = _rpythonic_function_( "put_flush_packet", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)),] ) url_open_dyn_buf = _rpythonic_function_( "url_open_dyn_buf", ctypes.c_int, [ ("s", ctypes.POINTER(ctypes.POINTER(AVIOContext))),] ) url_open_dyn_packet_buf = _rpythonic_function_( "url_open_dyn_packet_buf", ctypes.c_int, [ ("s", ctypes.POINTER(ctypes.POINTER(AVIOContext))), ("max_packet_size", ctypes.c_int),] ) put_le24 = _rpythonic_function_( "put_le24", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint),] ) put_be24 = _rpythonic_function_( "put_be24", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint),] ) put_le16 = _rpythonic_function_( "put_le16", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint),] ) put_be16 = _rpythonic_function_( "put_be16", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint),] ) init_put_byte = _rpythonic_function_( "init_put_byte", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)), ("buffer", ctypes.POINTER(ctypes.c_ubyte)), ("buffer_size", ctypes.c_int), ("write_flag", ctypes.c_int), ("opaque", ctypes.POINTER(ctypes.c_void_p)), ("read_packet", ctypes.c_void_p), ("write_packet", ctypes.c_void_p), ("seek", ctypes.c_void_p),] ) put_tag = _rpythonic_function_( "put_tag", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("tag", ctypes.POINTER(ctypes.c_char)),] ) av_url_read_fpause = _rpythonic_function_( "av_url_read_fpause", ctypes.c_int, [ ("h", ctypes.POINTER(AVIOContext)), ("pause", ctypes.c_int),] ) av_url_read_fseek = _rpythonic_function_( "av_url_read_fseek", ctypes.c_int64, [ ("h", ctypes.POINTER(AVIOContext)), ("stream_index", ctypes.c_int), ("timestamp", ctypes.c_int64), ("flags", ctypes.c_int),] ) url_fopen = _rpythonic_function_( "url_fopen", ctypes.c_int, [ ("s", ctypes.POINTER(ctypes.POINTER(AVIOContext))), ("url", ctypes.POINTER(ctypes.c_char)), ("flags", ctypes.c_int),] ) url_alloc = _rpythonic_function_( "url_alloc", ctypes.c_int, [ ("h", ctypes.POINTER(ctypes.POINTER(URLContext))), ("url", ctypes.POINTER(ctypes.c_char)), ("flags", ctypes.c_int),] ) url_connect = _rpythonic_function_( "url_connect", ctypes.c_int, [ ("h", ctypes.POINTER(URLContext)),] ) av_url_read_pause = _rpythonic_function_( "av_url_read_pause", ctypes.c_int, [ ("h", ctypes.POINTER(URLContext)), ("pause", ctypes.c_int),] ) av_url_read_seek = _rpythonic_function_( "av_url_read_seek", ctypes.c_int64, [ ("h", ctypes.POINTER(URLContext)), ("stream_index", ctypes.c_int), ("timestamp", ctypes.c_int64), ("flags", ctypes.c_int),] ) url_set_interrupt_cb = _rpythonic_function_( "url_set_interrupt_cb", ctypes.c_void_p, [ ("interrupt_cb", ctypes.c_void_p),] ) interrupt_cb = _rpythonic_function_( "interrupt_cb", ctypes.c_int, [] ) av_protocol_next = _rpythonic_function_( "av_protocol_next", ctypes.POINTER(URLProtocol), [ ("p", ctypes.POINTER(URLProtocol)),] ) av_register_protocol2 = _rpythonic_function_( "av_register_protocol2", ctypes.c_int, [ ("protocol", ctypes.POINTER(URLProtocol)), ("size", ctypes.c_int),] ) av_alloc_put_byte = _rpythonic_function_( "av_alloc_put_byte", ctypes.POINTER(AVIOContext), [ ("buffer", ctypes.POINTER(ctypes.c_ubyte)), ("buffer_size", ctypes.c_int), ("write_flag", ctypes.c_int), ("opaque", ctypes.POINTER(ctypes.c_void_p)), ("read_packet", ctypes.c_void_p), ("write_packet", ctypes.c_void_p), ("seek", ctypes.c_void_p),] ) url_fileno = _rpythonic_function_( "url_fileno", ctypes.POINTER(URLContext), [ ("s", ctypes.POINTER(AVIOContext)),] ) url_fget_max_packet_size = _rpythonic_function_( "url_fget_max_packet_size", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)),] ) url_open_buf = _rpythonic_function_( "url_open_buf", ctypes.c_int, [ ("s", ctypes.POINTER(ctypes.POINTER(AVIOContext))), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_int), ("flags", ctypes.c_int),] ) url_close_buf = _rpythonic_function_( "url_close_buf", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)),] ) url_exist = _rpythonic_function_( "url_exist", ctypes.c_int, [ ("url", ctypes.POINTER(ctypes.c_char)),] ) url_fgets = _rpythonic_function_( "url_fgets", ctypes.POINTER(ctypes.c_char), [ ("s", ctypes.POINTER(AVIOContext)), ("buf", ctypes.POINTER(ctypes.c_char)), ("buf_size", ctypes.c_int),] ) get_strz = _rpythonic_function_( "get_strz", ctypes.POINTER(ctypes.c_char), [ ("s", ctypes.POINTER(AVIOContext)), ("buf", ctypes.POINTER(ctypes.c_char)), ("maxlen", ctypes.c_int),] ) avio_w8 = _rpythonic_function_( "avio_w8", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("b", ctypes.c_int),] ) avio_write = _rpythonic_function_( "avio_write", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("buf", ctypes.POINTER(ctypes.c_ubyte)), ("size", ctypes.c_int),] ) avio_size = _rpythonic_function_( "avio_size", ctypes.c_int64, [ ("s", ctypes.POINTER(AVIOContext)),] ) avio_printf = _rpythonic_function_( "avio_printf", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)), ("fmt", ctypes.POINTER(ctypes.c_char)),] ) avio_flush = _rpythonic_function_( "avio_flush", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)),] ) avio_read = _rpythonic_function_( "avio_read", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)), ("buf", ctypes.POINTER(ctypes.c_ubyte)), ("size", ctypes.c_int),] ) avio_r8 = _rpythonic_function_( "avio_r8", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)),] ) avio_get_str16be = _rpythonic_function_( "avio_get_str16be", ctypes.c_int, [ ("pb", ctypes.POINTER(AVIOContext)), ("maxlen", ctypes.c_int), ("buf", ctypes.POINTER(ctypes.c_char)), ("buflen", ctypes.c_int),] ) avio_open = _rpythonic_function_( "avio_open", ctypes.c_int, [ ("s", ctypes.POINTER(ctypes.POINTER(AVIOContext))), ("url", ctypes.POINTER(ctypes.c_char)), ("flags", ctypes.c_int),] ) avio_close = _rpythonic_function_( "avio_close", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)),] ) avio_close_dyn_buf = _rpythonic_function_( "avio_close_dyn_buf", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)), ("pbuffer", ctypes.POINTER(ctypes.POINTER(ctypes.c_uint8))),] ) avio_open_dyn_buf = _rpythonic_function_( "avio_open_dyn_buf", ctypes.c_int, [ ("s", ctypes.POINTER(ctypes.POINTER(AVIOContext))),] ) url_read_complete = _rpythonic_function_( "url_read_complete", ctypes.c_int, [ ("h", ctypes.POINTER(URLContext)), ("buf", ctypes.POINTER(ctypes.c_ubyte)), ("size", ctypes.c_int),] ) get_be24 = _rpythonic_function_( "get_be24", ctypes.c_uint, [ ("s", ctypes.POINTER(AVIOContext)),] ) get_be32 = _rpythonic_function_( "get_be32", ctypes.c_uint, [ ("s", ctypes.POINTER(AVIOContext)),] ) get_be64 = _rpythonic_function_( "get_be64", ctypes.c_uint64, [ ("s", ctypes.POINTER(AVIOContext)),] ) put_byte = _rpythonic_function_( "put_byte", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("b", ctypes.c_int),] ) put_nbyte = _rpythonic_function_( "put_nbyte", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("b", ctypes.c_int), ("count", ctypes.c_int),] ) avio_wb24 = _rpythonic_function_( "avio_wb24", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint),] ) avio_wl16 = _rpythonic_function_( "avio_wl16", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint),] ) avio_wb16 = _rpythonic_function_( "avio_wb16", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint),] ) avio_put_str = _rpythonic_function_( "avio_put_str", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)), ("C_str", ctypes.POINTER(ctypes.c_char)),] ) url_filesize = _rpythonic_function_( "url_filesize", ctypes.c_int64, [ ("h", ctypes.POINTER(URLContext)),] ) url_get_max_packet_size = _rpythonic_function_( "url_get_max_packet_size", ctypes.c_int, [ ("h", ctypes.POINTER(URLContext)),] ) url_get_filename = _rpythonic_function_( "url_get_filename", ctypes.c_void_p, [ ("h", ctypes.POINTER(URLContext)), ("buf", ctypes.POINTER(ctypes.c_char)), ("buf_size", ctypes.c_int),] ) avio_wl64 = _rpythonic_function_( "avio_wl64", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint64),] ) avio_wb64 = _rpythonic_function_( "avio_wb64", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint64),] ) avio_wl32 = _rpythonic_function_( "avio_wl32", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint),] ) avio_wb32 = _rpythonic_function_( "avio_wb32", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint),] ) avio_wl24 = _rpythonic_function_( "avio_wl24", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVIOContext)), ("val", ctypes.c_uint),] ) get_partial_buffer = _rpythonic_function_( "get_partial_buffer", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)), ("buf", ctypes.POINTER(ctypes.c_ubyte)), ("size", ctypes.c_int),] ) avio_put_str16le = _rpythonic_function_( "avio_put_str16le", ctypes.c_int, [ ("s", ctypes.POINTER(AVIOContext)), ("C_str", ctypes.POINTER(ctypes.c_char)),] ) avio_seek = _rpythonic_function_( "avio_seek", ctypes.c_int64, [ ("s", ctypes.POINTER(AVIOContext)), ("offset", ctypes.c_int64), ("whence", ctypes.c_int),] ) avio_rl16 = _rpythonic_function_( "avio_rl16", ctypes.c_uint, [ ("s", ctypes.POINTER(AVIOContext)),] ) avio_rl24 = _rpythonic_function_( "avio_rl24", ctypes.c_uint, [ ("s", ctypes.POINTER(AVIOContext)),] ) avio_rl32 = _rpythonic_function_( "avio_rl32", ctypes.c_uint, [ ("s", ctypes.POINTER(AVIOContext)),] ) avio_rb16 = _rpythonic_function_( "avio_rb16", ctypes.c_uint, [ ("s", ctypes.POINTER(AVIOContext)),] ) avio_rl64 = _rpythonic_function_( "avio_rl64", ctypes.c_uint64, [ ("s", ctypes.POINTER(AVIOContext)),] ) avio_rb24 = _rpythonic_function_( "avio_rb24", ctypes.c_uint, [ ("s", ctypes.POINTER(AVIOContext)),] ) url_check = _rpythonic_function_( "url_check", ctypes.c_int, [ ("h", ctypes.POINTER(URLContext)), ("mask", ctypes.c_int),] ) url_poll = _rpythonic_function_( "url_poll", ctypes.c_int, [ ("poll_table", ctypes.POINTER(URLPollEntry)), ("n", ctypes.c_int), ("timeout", ctypes.c_int),] ) URLInterruptCB = _rpythonic_function_( "URLInterruptCB", ctypes.c_int, [] ) url_open_protocol = _rpythonic_function_( "url_open_protocol", ctypes.c_int, [ ("puc", ctypes.POINTER(ctypes.POINTER(URLContext))), ("up", ctypes.POINTER(URLProtocol)), ("url", ctypes.POINTER(ctypes.c_char)), ("flags", ctypes.c_int),] ) update_checksum = _rpythonic_function_( "update_checksum", ctypes.c_ulong, [ ("checksum", ctypes.c_ulong), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("size", ctypes.c_uint),] ) read_pause = _rpythonic_function_( "read_pause", ctypes.c_int, [ ("opaque", ctypes.POINTER(ctypes.c_void_p)), ("pause", ctypes.c_int),] ) read_seek = _rpythonic_function_( "read_seek", ctypes.c_int64, [ ("opaque", ctypes.POINTER(ctypes.c_void_p)), ("stream_index", ctypes.c_int), ("timestamp", ctypes.c_int64), ("flags", ctypes.c_int),] ) avformat_open_input = _rpythonic_function_( "avformat_open_input", ctypes.c_int, [ ("ps", ctypes.POINTER(ctypes.POINTER(AVFormatContext))), ("filename", ctypes.POINTER(ctypes.c_char)), ("fmt", ctypes.POINTER(AVInputFormat)), ("options", ctypes.POINTER(ctypes.POINTER(AVDictionary))),] ) avformat_alloc_context = _rpythonic_function_( "avformat_alloc_context", ctypes.POINTER(AVFormatContext), [] ) av_find_stream_info = _rpythonic_function_( "av_find_stream_info", ctypes.c_int, [ ("ic", ctypes.POINTER(AVFormatContext)),] ) avformat_find_stream_info = _rpythonic_function_( "avformat_find_stream_info", ctypes.c_int, [ ("ic", ctypes.POINTER(AVFormatContext)), ("options", ctypes.POINTER(ctypes.POINTER(AVDictionary))),] ) av_find_best_stream = _rpythonic_function_( "av_find_best_stream", ctypes.c_int, [ ("ic", ctypes.POINTER(AVFormatContext)), ("C_type", ctypes.c_int), ("wanted_stream_nb", ctypes.c_int), ("related_stream", ctypes.c_int), ("decoder_ret", ctypes.POINTER(ctypes.POINTER(AVCodec))), ("flags", ctypes.c_int),] ) av_guess_codec = _rpythonic_function_( "av_guess_codec", ctypes.c_int, [ ("fmt", ctypes.POINTER(AVOutputFormat)), ("short_name", ctypes.POINTER(ctypes.c_char)), ("filename", ctypes.POINTER(ctypes.c_char)), ("mime_type", ctypes.POINTER(ctypes.c_char)), ("C_type", ctypes.c_int),] ) av_hex_dump = _rpythonic_function_( "av_hex_dump", ctypes.c_void_p, [ ("f", ctypes.POINTER(_IO_FILE)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("size", ctypes.c_int),] ) av_hex_dump_log = _rpythonic_function_( "av_hex_dump_log", ctypes.c_void_p, [ ("avcl", ctypes.POINTER(ctypes.c_void_p)), ("level", ctypes.c_int), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("size", ctypes.c_int),] ) write_trailer = _rpythonic_function_( "write_trailer", ctypes.c_int, [ ("AVFormatContext", ctypes.POINTER(AVFormatContext)),] ) set_parameters = _rpythonic_function_( "set_parameters", ctypes.c_int, [ ("AVFormatContext", ctypes.POINTER(AVFormatContext)), ("none", ctypes.POINTER(ctypes.c_void_p)),] ) interleave_packet = _rpythonic_function_( "interleave_packet", ctypes.c_int, [ ("AVFormatContext", ctypes.POINTER(AVFormatContext)), ("out", ctypes.POINTER(AVPacket)), ("C_in", ctypes.POINTER(AVPacket)), ("flush", ctypes.c_int),] ) read_play = _rpythonic_function_( "read_play", ctypes.c_int, [ ("AVFormatContext", ctypes.POINTER(AVFormatContext)),] ) read_seek2 = _rpythonic_function_( "read_seek2", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)), ("stream_index", ctypes.c_int), ("min_ts", ctypes.c_int64), ("ts", ctypes.c_int64), ("max_ts", ctypes.c_int64), ("flags", ctypes.c_int),] ) write_header = _rpythonic_function_( "write_header", ctypes.c_int, [ ("AVFormatContext", ctypes.POINTER(AVFormatContext)),] ) url_open = _rpythonic_function_( "url_open", ctypes.c_int, [ ("h", ctypes.POINTER(URLContext)), ("url", ctypes.POINTER(ctypes.c_char)), ("flags", ctypes.c_int),] ) read_probe = _rpythonic_function_( "read_probe", ctypes.c_int, [ ("none", ctypes.POINTER(ctypes.c_void_p)),] ) read_header = _rpythonic_function_( "read_header", ctypes.c_int, [ ("AVFormatContext", ctypes.POINTER(AVFormatContext)), ("ap", ctypes.POINTER(AVFormatParameters)),] ) av_oformat_next = _rpythonic_function_( "av_oformat_next", ctypes.POINTER(AVOutputFormat), [ ("f", ctypes.POINTER(AVOutputFormat)),] ) av_guess_image2_codec = _rpythonic_function_( "av_guess_image2_codec", ctypes.c_int, [ ("filename", ctypes.POINTER(ctypes.c_char)),] ) av_register_input_format = _rpythonic_function_( "av_register_input_format", ctypes.c_void_p, [ ("format", ctypes.POINTER(AVInputFormat)),] ) av_register_output_format = _rpythonic_function_( "av_register_output_format", ctypes.c_void_p, [ ("format", ctypes.POINTER(AVOutputFormat)),] ) av_guess_format = _rpythonic_function_( "av_guess_format", ctypes.POINTER(AVOutputFormat), [ ("short_name", ctypes.POINTER(ctypes.c_char)), ("filename", ctypes.POINTER(ctypes.c_char)), ("mime_type", ctypes.POINTER(ctypes.c_char)),] ) av_pkt_dump_log = _rpythonic_function_( "av_pkt_dump_log", ctypes.c_void_p, [ ("avcl", ctypes.POINTER(ctypes.c_void_p)), ("level", ctypes.c_int), ("pkt", ctypes.POINTER(AVPacket)), ("dump_payload", ctypes.c_int),] ) av_register_all = _rpythonic_function_( "av_register_all", ctypes.c_void_p, [] ) av_codec_get_id = _rpythonic_function_( "av_codec_get_id", ctypes.c_int, [ ("tags", ctypes.POINTER(ctypes.POINTER(AVCodecTag))), ("tag", ctypes.c_uint),] ) av_codec_get_tag = _rpythonic_function_( "av_codec_get_tag", ctypes.c_uint, [ ("tags", ctypes.POINTER(ctypes.POINTER(AVCodecTag))), ("C_id", ctypes.c_int),] ) av_find_input_format = _rpythonic_function_( "av_find_input_format", ctypes.POINTER(AVInputFormat), [ ("short_name", ctypes.POINTER(ctypes.c_char)),] ) av_probe_input_format = _rpythonic_function_( "av_probe_input_format", ctypes.POINTER(AVInputFormat), [ ("pd", ctypes.POINTER(AVProbeData)), ("is_opened", ctypes.c_int),] ) av_probe_input_format2 = _rpythonic_function_( "av_probe_input_format2", ctypes.POINTER(AVInputFormat), [ ("pd", ctypes.POINTER(AVProbeData)), ("is_opened", ctypes.c_int), ("score_max", ctypes.POINTER(ctypes.c_int)),] ) av_probe_input_buffer = _rpythonic_function_( "av_probe_input_buffer", ctypes.c_int, [ ("pb", ctypes.POINTER(AVIOContext)), ("fmt", ctypes.POINTER(ctypes.POINTER(AVInputFormat))), ("filename", ctypes.POINTER(ctypes.c_char)), ("logctx", ctypes.POINTER(ctypes.c_void_p)), ("offset", ctypes.c_uint), ("max_probe_size", ctypes.c_uint),] ) url_close = _rpythonic_function_( "url_close", ctypes.c_int, [ ("h", ctypes.POINTER(URLContext)),] ) url_read_pause = _rpythonic_function_( "url_read_pause", ctypes.c_int, [ ("h", ctypes.POINTER(URLContext)), ("pause", ctypes.c_int),] ) url_read_seek = _rpythonic_function_( "url_read_seek", ctypes.c_int64, [ ("h", ctypes.POINTER(URLContext)), ("stream_index", ctypes.c_int), ("timestamp", ctypes.c_int64), ("flags", ctypes.c_int),] ) url_get_file_handle = _rpythonic_function_( "url_get_file_handle", ctypes.c_int, [ ("h", ctypes.POINTER(URLContext)),] ) av_open_input_stream = _rpythonic_function_( "av_open_input_stream", ctypes.c_int, [ ("ic_ptr", ctypes.POINTER(ctypes.POINTER(AVFormatContext))), ("pb", ctypes.POINTER(AVIOContext)), ("filename", ctypes.POINTER(ctypes.c_char)), ("fmt", ctypes.POINTER(AVInputFormat)), ("ap", ctypes.POINTER(AVFormatParameters)),] ) av_open_input_file = _rpythonic_function_( "av_open_input_file", ctypes.c_int, [ ("ic_ptr", ctypes.POINTER(ctypes.POINTER(AVFormatContext))), ("filename", ctypes.POINTER(ctypes.c_char)), ("fmt", ctypes.POINTER(AVInputFormat)), ("buf_size", ctypes.c_int), ("ap", ctypes.POINTER(AVFormatParameters)),] ) av_iformat_next = _rpythonic_function_( "av_iformat_next", ctypes.POINTER(AVInputFormat), [ ("f", ctypes.POINTER(AVInputFormat)),] ) url_read = _rpythonic_function_( "url_read", ctypes.c_int, [ ("h", ctypes.POINTER(URLContext)), ("buf", ctypes.POINTER(ctypes.c_ubyte)), ("size", ctypes.c_int),] ) url_write = _rpythonic_function_( "url_write", ctypes.c_int, [ ("h", ctypes.POINTER(URLContext)), ("buf", ctypes.POINTER(ctypes.c_ubyte)), ("size", ctypes.c_int),] ) url_seek = _rpythonic_function_( "url_seek", ctypes.c_int64, [ ("h", ctypes.POINTER(URLContext)), ("pos", ctypes.c_int64), ("whence", ctypes.c_int),] ) read_close = _rpythonic_function_( "read_close", ctypes.c_int, [ ("AVFormatContext", ctypes.POINTER(AVFormatContext)),] ) read_timestamp = _rpythonic_function_( "read_timestamp", ctypes.c_int64, [ ("s", ctypes.POINTER(AVFormatContext)), ("stream_index", ctypes.c_int), ("pos", ctypes.POINTER(ctypes.c_int64)), ("pos_limit", ctypes.c_int64),] ) av_pkt_dump2 = _rpythonic_function_( "av_pkt_dump2", ctypes.c_void_p, [ ("f", ctypes.POINTER(_IO_FILE)), ("pkt", ctypes.POINTER(AVPacket)), ("dump_payload", ctypes.c_int), ("st", ctypes.POINTER(AVStream)),] ) av_pkt_dump_log2 = _rpythonic_function_( "av_pkt_dump_log2", ctypes.c_void_p, [ ("avcl", ctypes.POINTER(ctypes.c_void_p)), ("level", ctypes.c_int), ("pkt", ctypes.POINTER(AVPacket)), ("dump_payload", ctypes.c_int), ("st", ctypes.POINTER(AVStream)),] ) av_pkt_dump = _rpythonic_function_( "av_pkt_dump", ctypes.c_void_p, [ ("f", ctypes.POINTER(_IO_FILE)), ("pkt", ctypes.POINTER(AVPacket)), ("dump_payload", ctypes.c_int),] ) func = _rpythonic_function_( "func", ctypes.c_int, [ ("c2", ctypes.POINTER(AVCodecContext)), ("arg", ctypes.POINTER(ctypes.c_void_p)),] ) execute = _rpythonic_function_( "execute", ctypes.c_int, [ ("c", ctypes.POINTER(AVCodecContext)), ("func", ctypes.c_void_p), ("arg2", ctypes.POINTER(ctypes.c_void_p)), ("ret", ctypes.POINTER(ctypes.c_int)), ("count", ctypes.c_int), ("size", ctypes.c_int),] ) reget_buffer = _rpythonic_function_( "reget_buffer", ctypes.c_int, [ ("c", ctypes.POINTER(AVCodecContext)), ("pic", ctypes.POINTER(AVFrame)),] ) execute2 = _rpythonic_function_( "execute2", ctypes.c_int, [ ("c", ctypes.POINTER(AVCodecContext)), ("func", ctypes.c_void_p), ("arg2", ctypes.POINTER(ctypes.c_void_p)), ("ret", ctypes.POINTER(ctypes.c_int)), ("count", ctypes.c_int),] ) img_get_alpha_info = _rpythonic_function_( "img_get_alpha_info", ctypes.c_int, [ ("src", ctypes.POINTER(AVPicture)), ("pix_fmt", ctypes.c_int), ("width", ctypes.c_int), ("height", ctypes.c_int),] ) avpicture_deinterlace = _rpythonic_function_( "avpicture_deinterlace", ctypes.c_int, [ ("dst", ctypes.POINTER(AVPicture)), ("src", ctypes.POINTER(AVPicture)), ("pix_fmt", ctypes.c_int), ("width", ctypes.c_int), ("height", ctypes.c_int),] ) av_codec_next = _rpythonic_function_( "av_codec_next", ctypes.POINTER(AVCodec), [ ("c", ctypes.POINTER(AVCodec)),] ) init = _rpythonic_function_( "init", ctypes.c_int, [ ("none", ctypes.POINTER(ctypes.c_void_p)),] ) encode = _rpythonic_function_( "encode", ctypes.c_int, [ ("none", ctypes.POINTER(ctypes.c_void_p)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_int), ("data", ctypes.POINTER(ctypes.c_void_p)),] ) close = _rpythonic_function_( "close", ctypes.c_int, [ ("none", ctypes.POINTER(ctypes.c_void_p)),] ) decode = _rpythonic_function_( "decode", ctypes.c_int, [ ("none", ctypes.POINTER(ctypes.c_void_p)), ("outdata", ctypes.POINTER(ctypes.c_void_p)), ("outdata_size", ctypes.POINTER(ctypes.c_int)), ("avpkt", ctypes.POINTER(AVPacket)),] ) read_packet = _rpythonic_function_( "read_packet", ctypes.c_int, [ ("opaque", ctypes.POINTER(ctypes.c_void_p)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_int),] ) write_packet = _rpythonic_function_( "write_packet", ctypes.c_int, [ ("opaque", ctypes.POINTER(ctypes.c_void_p)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_int),] ) seek = _rpythonic_function_( "seek", ctypes.c_int64, [ ("opaque", ctypes.POINTER(ctypes.c_void_p)), ("offset", ctypes.c_int64), ("whence", ctypes.c_int),] ) av_register_hwaccel = _rpythonic_function_( "av_register_hwaccel", ctypes.c_void_p, [ ("hwaccel", ctypes.POINTER(AVHWAccel)),] ) av_hwaccel_next = _rpythonic_function_( "av_hwaccel_next", ctypes.POINTER(AVHWAccel), [ ("hwaccel", ctypes.POINTER(AVHWAccel)),] ) av_lockmgr_register = _rpythonic_function_( "av_lockmgr_register", ctypes.c_int, [ ("cb", ctypes.c_void_p),] ) cb = _rpythonic_function_( "cb", ctypes.c_int, [ ("mutex", ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))), ("op", ctypes.c_int),] ) av_xiphlacing = _rpythonic_function_( "av_xiphlacing", ctypes.c_uint, [ ("s", ctypes.POINTER(ctypes.c_ubyte)), ("v", ctypes.c_uint),] ) av_log_missing_feature = _rpythonic_function_( "av_log_missing_feature", ctypes.c_void_p, [ ("avc", ctypes.POINTER(ctypes.c_void_p)), ("feature", ctypes.POINTER(ctypes.c_char)), ("want_sample", ctypes.c_int),] ) av_log_ask_for_sample = _rpythonic_function_( "av_log_ask_for_sample", ctypes.c_void_p, [ ("avc", ctypes.POINTER(ctypes.c_void_p)), ("msg", ctypes.POINTER(ctypes.c_char)),] ) av_picture_copy = _rpythonic_function_( "av_picture_copy", ctypes.c_void_p, [ ("dst", ctypes.POINTER(AVPicture)), ("src", ctypes.POINTER(AVPicture)), ("pix_fmt", ctypes.c_int), ("width", ctypes.c_int), ("height", ctypes.c_int),] ) av_picture_crop = _rpythonic_function_( "av_picture_crop", ctypes.c_int, [ ("dst", ctypes.POINTER(AVPicture)), ("src", ctypes.POINTER(AVPicture)), ("pix_fmt", ctypes.c_int), ("top_band", ctypes.c_int), ("left_band", ctypes.c_int),] ) av_picture_pad = _rpythonic_function_( "av_picture_pad", ctypes.c_int, [ ("dst", ctypes.POINTER(AVPicture)), ("src", ctypes.POINTER(AVPicture)), ("height", ctypes.c_int), ("width", ctypes.c_int), ("pix_fmt", ctypes.c_int), ("padtop", ctypes.c_int), ("padbottom", ctypes.c_int), ("padleft", ctypes.c_int), ("padright", ctypes.c_int), ("color", ctypes.POINTER(ctypes.c_int)),] ) av_bitstream_filter_close = _rpythonic_function_( "av_bitstream_filter_close", ctypes.c_void_p, [ ("bsf", ctypes.POINTER(AVBitStreamFilterContext)),] ) av_bitstream_filter_next = _rpythonic_function_( "av_bitstream_filter_next", ctypes.POINTER(AVBitStreamFilter), [ ("f", ctypes.POINTER(AVBitStreamFilter)),] ) av_fast_realloc = _rpythonic_function_( "av_fast_realloc", ctypes.POINTER(ctypes.c_void_p), [ ("ptr", ctypes.POINTER(ctypes.c_void_p)), ("size", ctypes.POINTER(ctypes.c_uint)), ("min_size", ctypes.c_uint64),] ) av_fast_malloc = _rpythonic_function_( "av_fast_malloc", ctypes.c_void_p, [ ("ptr", ctypes.POINTER(ctypes.c_void_p)), ("size", ctypes.POINTER(ctypes.c_uint)), ("min_size", ctypes.c_uint64),] ) av_register_bitstream_filter = _rpythonic_function_( "av_register_bitstream_filter", ctypes.c_void_p, [ ("bsf", ctypes.POINTER(AVBitStreamFilter)),] ) av_bitstream_filter_init = _rpythonic_function_( "av_bitstream_filter_init", ctypes.POINTER(AVBitStreamFilterContext), [ ("name", ctypes.POINTER(ctypes.c_char)),] ) av_bitstream_filter_filter = _rpythonic_function_( "av_bitstream_filter_filter", ctypes.c_int, [ ("bsfc", ctypes.POINTER(AVBitStreamFilterContext)), ("avctx", ctypes.POINTER(AVCodecContext)), ("args", ctypes.POINTER(ctypes.c_char)), ("poutbuf", ctypes.POINTER(ctypes.POINTER(ctypes.c_uint8))), ("poutbuf_size", ctypes.POINTER(ctypes.c_int)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_int), ("keyframe", ctypes.c_int),] ) filter = _rpythonic_function_( "filter", ctypes.c_int, [ ("bsfc", ctypes.POINTER(AVBitStreamFilterContext)), ("avctx", ctypes.POINTER(AVCodecContext)), ("args", ctypes.POINTER(ctypes.c_char)), ("poutbuf", ctypes.POINTER(ctypes.POINTER(ctypes.c_uint8))), ("poutbuf_size", ctypes.POINTER(ctypes.c_int)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_int), ("keyframe", ctypes.c_int),] ) av_parser_change = _rpythonic_function_( "av_parser_change", ctypes.c_int, [ ("s", ctypes.POINTER(AVCodecParserContext)), ("avctx", ctypes.POINTER(AVCodecContext)), ("poutbuf", ctypes.POINTER(ctypes.POINTER(ctypes.c_uint8))), ("poutbuf_size", ctypes.POINTER(ctypes.c_int)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_int), ("keyframe", ctypes.c_int),] ) av_parser_close = _rpythonic_function_( "av_parser_close", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVCodecParserContext)),] ) av_parser_next = _rpythonic_function_( "av_parser_next", ctypes.POINTER(AVCodecParser), [ ("c", ctypes.POINTER(AVCodecParser)),] ) av_register_codec_parser = _rpythonic_function_( "av_register_codec_parser", ctypes.c_void_p, [ ("parser", ctypes.POINTER(AVCodecParser)),] ) av_parser_init = _rpythonic_function_( "av_parser_init", ctypes.POINTER(AVCodecParserContext), [ ("codec_id", ctypes.c_int),] ) av_parser_parse2 = _rpythonic_function_( "av_parser_parse2", ctypes.c_int, [ ("s", ctypes.POINTER(AVCodecParserContext)), ("avctx", ctypes.POINTER(AVCodecContext)), ("poutbuf", ctypes.POINTER(ctypes.POINTER(ctypes.c_uint8))), ("poutbuf_size", ctypes.POINTER(ctypes.c_int)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_int), ("pts", ctypes.c_int64), ("dts", ctypes.c_int64), ("pos", ctypes.c_int64),] ) parser_parse = _rpythonic_function_( "parser_parse", ctypes.c_int, [ ("s", ctypes.POINTER(AVCodecParserContext)), ("avctx", ctypes.POINTER(AVCodecContext)), ("poutbuf", ctypes.POINTER(ctypes.POINTER(ctypes.c_uint8))), ("poutbuf_size", ctypes.POINTER(ctypes.c_int)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_int),] ) parser_close = _rpythonic_function_( "parser_close", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVCodecParserContext)),] ) split = _rpythonic_function_( "split", ctypes.c_int, [ ("avctx", ctypes.POINTER(AVCodecContext)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_int),] ) parser_init = _rpythonic_function_( "parser_init", ctypes.c_int, [ ("s", ctypes.POINTER(AVCodecParserContext)),] ) av_get_bits_per_sample_format = _rpythonic_function_( "av_get_bits_per_sample_format", ctypes.c_int, [ ("sample_fmt", ctypes.c_int),] ) avcodec_decode_subtitle2 = _rpythonic_function_( "avcodec_decode_subtitle2", ctypes.c_int, [ ("avctx", ctypes.POINTER(AVCodecContext)), ("sub", ctypes.POINTER(AVSubtitle)), ("got_sub_ptr", ctypes.POINTER(ctypes.c_int)), ("avpkt", ctypes.POINTER(AVPacket)),] ) avsubtitle_free = _rpythonic_function_( "avsubtitle_free", ctypes.c_void_p, [ ("sub", ctypes.POINTER(AVSubtitle)),] ) avcodec_parse_frame = _rpythonic_function_( "avcodec_parse_frame", ctypes.c_int, [ ("avctx", ctypes.POINTER(AVCodecContext)), ("pdata", ctypes.POINTER(ctypes.POINTER(ctypes.c_uint8))), ("data_size_ptr", ctypes.POINTER(ctypes.c_int)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_int),] ) avcodec_close = _rpythonic_function_( "avcodec_close", ctypes.c_int, [ ("avctx", ctypes.POINTER(AVCodecContext)),] ) avcodec_register_all = _rpythonic_function_( "avcodec_register_all", ctypes.c_void_p, [] ) avcodec_flush_buffers = _rpythonic_function_( "avcodec_flush_buffers", ctypes.c_void_p, [ ("avctx", ctypes.POINTER(AVCodecContext)),] ) avcodec_default_free_buffers = _rpythonic_function_( "avcodec_default_free_buffers", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVCodecContext)),] ) av_get_pict_type_char = _rpythonic_function_( "av_get_pict_type_char", ctypes.c_char, [ ("pict_type", ctypes.c_int),] ) av_get_bits_per_sample = _rpythonic_function_( "av_get_bits_per_sample", ctypes.c_int, [ ("codec_id", ctypes.c_int),] ) avcodec_encode_audio = _rpythonic_function_( "avcodec_encode_audio", ctypes.c_int, [ ("avctx", ctypes.POINTER(AVCodecContext)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_int), ("samples", ctypes.POINTER(ctypes.c_short)),] ) avcodec_encode_video = _rpythonic_function_( "avcodec_encode_video", ctypes.c_int, [ ("avctx", ctypes.POINTER(AVCodecContext)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_int), ("pict", ctypes.POINTER(AVFrame)),] ) avcodec_encode_subtitle = _rpythonic_function_( "avcodec_encode_subtitle", ctypes.c_int, [ ("avctx", ctypes.POINTER(AVCodecContext)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_int), ("sub", ctypes.POINTER(AVSubtitle)),] ) avcodec_open2 = _rpythonic_function_( "avcodec_open2", ctypes.c_int, [ ("avctx", ctypes.POINTER(AVCodecContext)), ("codec", ctypes.POINTER(AVCodec)), ("options", ctypes.POINTER(ctypes.POINTER(AVDictionary))),] ) avcodec_open = _rpythonic_function_( "avcodec_open", ctypes.c_int, [ ("avctx", ctypes.POINTER(AVCodecContext)), ("codec", ctypes.POINTER(AVCodec)),] ) avcodec_decode_audio3 = _rpythonic_function_( "avcodec_decode_audio3", ctypes.c_int, [ ("avctx", ctypes.POINTER(AVCodecContext)), ("samples", ctypes.POINTER(ctypes.c_int16)), ("frame_size_ptr", ctypes.POINTER(ctypes.c_int)), ("avpkt", ctypes.POINTER(AVPacket)),] ) avcodec_decode_video2 = _rpythonic_function_( "avcodec_decode_video2", ctypes.c_int, [ ("avctx", ctypes.POINTER(AVCodecContext)), ("picture", ctypes.POINTER(AVFrame)), ("got_picture_ptr", ctypes.POINTER(ctypes.c_int)), ("avpkt", ctypes.POINTER(AVPacket)),] ) avcodec_default_execute2 = _rpythonic_function_( "avcodec_default_execute2", ctypes.c_int, [ ("c", ctypes.POINTER(AVCodecContext)), ("func", ctypes.c_void_p), ("arg", ctypes.POINTER(ctypes.c_void_p)), ("ret", ctypes.POINTER(ctypes.c_int)), ("count", ctypes.c_int),] ) avcodec_default_get_format = _rpythonic_function_( "avcodec_default_get_format", ctypes.c_int, [ ("s", ctypes.POINTER(AVCodecContext)), ("fmt", ctypes.POINTER(ctypes.c_int)),] ) avcodec_thread_init = _rpythonic_function_( "avcodec_thread_init", ctypes.c_int, [ ("s", ctypes.POINTER(AVCodecContext)), ("thread_count", ctypes.c_int),] ) avcodec_default_execute = _rpythonic_function_( "avcodec_default_execute", ctypes.c_int, [ ("c", ctypes.POINTER(AVCodecContext)), ("func", ctypes.c_void_p), ("arg", ctypes.POINTER(ctypes.c_void_p)), ("ret", ctypes.POINTER(ctypes.c_int)), ("count", ctypes.c_int), ("size", ctypes.c_int),] ) avcodec_default_release_buffer = _rpythonic_function_( "avcodec_default_release_buffer", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVCodecContext)), ("pic", ctypes.POINTER(AVFrame)),] ) avcodec_default_reget_buffer = _rpythonic_function_( "avcodec_default_reget_buffer", ctypes.c_int, [ ("s", ctypes.POINTER(AVCodecContext)), ("pic", ctypes.POINTER(AVFrame)),] ) avcodec_get_edge_width = _rpythonic_function_( "avcodec_get_edge_width", ctypes.c_void_p, [] ) avcodec_align_dimensions2 = _rpythonic_function_( "avcodec_align_dimensions2", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVCodecContext)), ("width", ctypes.POINTER(ctypes.c_int)), ("height", ctypes.POINTER(ctypes.c_int)), ("linesize_align", ( ctypes.c_int * 4 )),] ) avcodec_align_dimensions = _rpythonic_function_( "avcodec_align_dimensions", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVCodecContext)), ("width", ctypes.POINTER(ctypes.c_int)), ("height", ctypes.POINTER(ctypes.c_int)),] ) avcodec_alloc_context3 = _rpythonic_function_( "avcodec_alloc_context3", ctypes.POINTER(AVCodecContext), [ ("codec", ctypes.POINTER(AVCodec)),] ) avcodec_copy_context = _rpythonic_function_( "avcodec_copy_context", ctypes.c_int, [ ("dest", ctypes.POINTER(AVCodecContext)), ("src", ctypes.POINTER(AVCodecContext)),] ) avcodec_get_frame_defaults = _rpythonic_function_( "avcodec_get_frame_defaults", ctypes.c_void_p, [ ("pic", ctypes.POINTER(AVFrame)),] ) avcodec_alloc_frame = _rpythonic_function_( "avcodec_alloc_frame", ctypes.POINTER(AVFrame), [] ) avcodec_default_get_buffer = _rpythonic_function_( "avcodec_default_get_buffer", ctypes.c_int, [ ("s", ctypes.POINTER(AVCodecContext)), ("pic", ctypes.POINTER(AVFrame)),] ) avcodec_get_context_defaults = _rpythonic_function_( "avcodec_get_context_defaults", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVCodecContext)),] ) avcodec_get_context_defaults2 = _rpythonic_function_( "avcodec_get_context_defaults2", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVCodecContext)), ("AVMediaType", ctypes.c_int),] ) avcodec_get_context_defaults3 = _rpythonic_function_( "avcodec_get_context_defaults3", ctypes.c_int, [ ("s", ctypes.POINTER(AVCodecContext)), ("codec", ctypes.POINTER(AVCodec)),] ) avcodec_alloc_context2 = _rpythonic_function_( "avcodec_alloc_context2", ctypes.POINTER(AVCodecContext), [ ("AVMediaType", ctypes.c_int),] ) avcodec_alloc_context = _rpythonic_function_( "avcodec_alloc_context", ctypes.POINTER(AVCodecContext), [] ) avcodec_find_encoder_by_name = _rpythonic_function_( "avcodec_find_encoder_by_name", ctypes.POINTER(AVCodec), [ ("name", ctypes.POINTER(ctypes.c_char)),] ) avcodec_find_decoder = _rpythonic_function_( "avcodec_find_decoder", ctypes.POINTER(AVCodec), [ ("C_id", ctypes.c_int),] ) avcodec_find_decoder_by_name = _rpythonic_function_( "avcodec_find_decoder_by_name", ctypes.POINTER(AVCodec), [ ("name", ctypes.POINTER(ctypes.c_char)),] ) avcodec_string = _rpythonic_function_( "avcodec_string", ctypes.c_void_p, [ ("buf", ctypes.POINTER(ctypes.c_char)), ("buf_size", ctypes.c_int), ("enc", ctypes.POINTER(AVCodecContext)), ("encode", ctypes.c_int),] ) av_get_profile_name = _rpythonic_function_( "av_get_profile_name", ctypes.POINTER(ctypes.c_char), [ ("codec", ctypes.POINTER(AVCodec)), ("profile", ctypes.c_int),] ) avcodec_configuration = _rpythonic_function_( "avcodec_configuration", ctypes.POINTER(ctypes.c_char), [] ) avcodec_version = _rpythonic_function_( "avcodec_version", ctypes.c_void_p, [] ) avcodec_license = _rpythonic_function_( "avcodec_license", ctypes.POINTER(ctypes.c_char), [] ) avcodec_init = _rpythonic_function_( "avcodec_init", ctypes.c_void_p, [] ) avcodec_register = _rpythonic_function_( "avcodec_register", ctypes.c_void_p, [ ("codec", ctypes.POINTER(AVCodec)),] ) avcodec_find_encoder = _rpythonic_function_( "avcodec_find_encoder", ctypes.POINTER(AVCodec), [ ("C_id", ctypes.c_int),] ) rtp_callback = _rpythonic_function_( "rtp_callback", ctypes.c_void_p, [ ("avctx", ctypes.POINTER(AVCodecContext)), ("data", ctypes.POINTER(ctypes.c_void_p)), ("size", ctypes.c_int), ("mb_nb", ctypes.c_int),] ) draw_horiz_band = _rpythonic_function_( "draw_horiz_band", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVCodecContext)), ("src", ctypes.POINTER(AVFrame)), ("offset", ( ctypes.c_int * 4 )), ("y", ctypes.c_int), ("C_type", ctypes.c_int), ("height", ctypes.c_int),] ) get_buffer = _rpythonic_function_( "get_buffer", ctypes.c_int, [ ("c", ctypes.POINTER(AVCodecContext)), ("pic", ctypes.POINTER(AVFrame)),] ) release_buffer = _rpythonic_function_( "release_buffer", ctypes.c_void_p, [ ("c", ctypes.POINTER(AVCodecContext)), ("pic", ctypes.POINTER(AVFrame)),] ) destruct = _rpythonic_function_( "destruct", ctypes.c_void_p, [ ("AVPacket", ctypes.POINTER(AVPacket)),] ) flush = _rpythonic_function_( "flush", ctypes.c_void_p, [ ("none", ctypes.POINTER(ctypes.c_void_p)),] ) init_thread_copy = _rpythonic_function_( "init_thread_copy", ctypes.c_int, [ ("none", ctypes.POINTER(ctypes.c_void_p)),] ) update_thread_context = _rpythonic_function_( "update_thread_context", ctypes.c_int, [ ("dst", ctypes.POINTER(AVCodecContext)), ("src", ctypes.POINTER(AVCodecContext)),] ) start_frame = _rpythonic_function_( "start_frame", ctypes.c_int, [ ("avctx", ctypes.POINTER(AVCodecContext)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_uint32),] ) decode_slice = _rpythonic_function_( "decode_slice", ctypes.c_int, [ ("avctx", ctypes.POINTER(AVCodecContext)), ("buf", ctypes.POINTER(ctypes.c_uint8)), ("buf_size", ctypes.c_uint32),] ) end_frame = _rpythonic_function_( "end_frame", ctypes.c_int, [ ("avctx", ctypes.POINTER(AVCodecContext)),] ) av_destruct_packet_nofree = _rpythonic_function_( "av_destruct_packet_nofree", ctypes.c_void_p, [ ("pkt", ctypes.POINTER(AVPacket)),] ) av_destruct_packet = _rpythonic_function_( "av_destruct_packet", ctypes.c_void_p, [ ("pkt", ctypes.POINTER(AVPacket)),] ) av_init_packet = _rpythonic_function_( "av_init_packet", ctypes.c_void_p, [ ("pkt", ctypes.POINTER(AVPacket)),] ) av_new_packet = _rpythonic_function_( "av_new_packet", ctypes.c_int, [ ("pkt", ctypes.POINTER(AVPacket)), ("size", ctypes.c_int),] ) av_shrink_packet = _rpythonic_function_( "av_shrink_packet", ctypes.c_void_p, [ ("pkt", ctypes.POINTER(AVPacket)), ("size", ctypes.c_int),] ) av_grow_packet = _rpythonic_function_( "av_grow_packet", ctypes.c_int, [ ("pkt", ctypes.POINTER(AVPacket)), ("grow_by", ctypes.c_int),] ) av_dup_packet = _rpythonic_function_( "av_dup_packet", ctypes.c_int, [ ("pkt", ctypes.POINTER(AVPacket)),] ) av_free_packet = _rpythonic_function_( "av_free_packet", ctypes.c_void_p, [ ("pkt", ctypes.POINTER(AVPacket)),] ) av_packet_new_side_data = _rpythonic_function_( "av_packet_new_side_data", ctypes.POINTER(ctypes.c_uint8), [ ("pkt", ctypes.POINTER(AVPacket)), ("C_type", ctypes.c_int), ("size", ctypes.c_int),] ) av_packet_get_side_data = _rpythonic_function_( "av_packet_get_side_data", ctypes.POINTER(ctypes.c_uint8), [ ("pkt", ctypes.POINTER(AVPacket)), ("C_type", ctypes.c_int), ("size", ctypes.POINTER(ctypes.c_int)),] ) av_audio_resample_init = _rpythonic_function_( "av_audio_resample_init", ctypes.POINTER(ReSampleContext), [ ("output_channels", ctypes.c_int), ("input_channels", ctypes.c_int), ("output_rate", ctypes.c_int), ("input_rate", ctypes.c_int), ("sample_fmt_out", ctypes.c_int), ("sample_fmt_in", ctypes.c_int), ("filter_length", ctypes.c_int), ("log2_phase_count", ctypes.c_int), ("linear", ctypes.c_int), ("cutoff", ctypes.c_double),] ) audio_resample = _rpythonic_function_( "audio_resample", ctypes.c_int, [ ("s", ctypes.POINTER(ReSampleContext)), ("output", ctypes.POINTER(ctypes.c_short)), ("input", ctypes.POINTER(ctypes.c_short)), ("nb_samples", ctypes.c_int),] ) audio_resample_close = _rpythonic_function_( "audio_resample_close", ctypes.c_void_p, [ ("s", ctypes.POINTER(ReSampleContext)),] ) av_resample_init = _rpythonic_function_( "av_resample_init", ctypes.POINTER(AVResampleContext), [ ("out_rate", ctypes.c_int), ("in_rate", ctypes.c_int), ("filter_length", ctypes.c_int), ("log2_phase_count", ctypes.c_int), ("linear", ctypes.c_int), ("cutoff", ctypes.c_double),] ) get_format = _rpythonic_function_( "get_format", ctypes.c_int, [ ("s", ctypes.POINTER(AVCodecContext)), ("fmt", ctypes.POINTER(ctypes.c_int)),] ) av_resample = _rpythonic_function_( "av_resample", ctypes.c_int, [ ("c", ctypes.POINTER(AVResampleContext)), ("dst", ctypes.POINTER(ctypes.c_short)), ("src", ctypes.POINTER(ctypes.c_short)), ("consumed", ctypes.POINTER(ctypes.c_int)), ("src_size", ctypes.c_int), ("dst_size", ctypes.c_int), ("update_ctx", ctypes.c_int),] ) av_resample_compensate = _rpythonic_function_( "av_resample_compensate", ctypes.c_void_p, [ ("c", ctypes.POINTER(AVResampleContext)), ("sample_delta", ctypes.c_int), ("compensation_distance", ctypes.c_int),] ) av_resample_close = _rpythonic_function_( "av_resample_close", ctypes.c_void_p, [ ("c", ctypes.POINTER(AVResampleContext)),] ) avpicture_alloc = _rpythonic_function_( "avpicture_alloc", ctypes.c_int, [ ("picture", ctypes.POINTER(AVPicture)), ("pix_fmt", ctypes.c_int), ("width", ctypes.c_int), ("height", ctypes.c_int),] ) avpicture_free = _rpythonic_function_( "avpicture_free", ctypes.c_void_p, [ ("picture", ctypes.POINTER(AVPicture)),] ) avpicture_fill = _rpythonic_function_( "avpicture_fill", ctypes.c_int, [ ("picture", ctypes.POINTER(AVPicture)), ("ptr", ctypes.POINTER(ctypes.c_uint8)), ("pix_fmt", ctypes.c_int), ("width", ctypes.c_int), ("height", ctypes.c_int),] ) avpicture_layout = _rpythonic_function_( "avpicture_layout", ctypes.c_int, [ ("src", ctypes.POINTER(AVPicture)), ("pix_fmt", ctypes.c_int), ("width", ctypes.c_int), ("height", ctypes.c_int), ("dest", ctypes.POINTER(ctypes.c_ubyte)), ("dest_size", ctypes.c_int),] ) avpicture_get_size = _rpythonic_function_( "avpicture_get_size", ctypes.c_int, [ ("pix_fmt", ctypes.c_int), ("width", ctypes.c_int), ("height", ctypes.c_int),] ) avcodec_get_chroma_sub_sample = _rpythonic_function_( "avcodec_get_chroma_sub_sample", ctypes.c_void_p, [ ("pix_fmt", ctypes.c_int), ("h_shift", ctypes.POINTER(ctypes.c_int)), ("v_shift", ctypes.POINTER(ctypes.c_int)),] ) avcodec_get_pix_fmt_name = _rpythonic_function_( "avcodec_get_pix_fmt_name", ctypes.POINTER(ctypes.c_char), [ ("pix_fmt", ctypes.c_int),] ) avcodec_set_dimensions = _rpythonic_function_( "avcodec_set_dimensions", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVCodecContext)), ("width", ctypes.c_int), ("height", ctypes.c_int),] ) avcodec_pix_fmt_to_codec_tag = _rpythonic_function_( "avcodec_pix_fmt_to_codec_tag", ctypes.c_uint, [ ("pix_fmt", ctypes.c_int),] ) av_get_codec_tag_string = _rpythonic_function_( "av_get_codec_tag_string", ctypes.c_uint64, [ ("buf", ctypes.POINTER(ctypes.c_char)), ("buf_size", ctypes.c_uint64), ("codec_tag", ctypes.c_uint),] ) avcodec_get_pix_fmt_loss = _rpythonic_function_( "avcodec_get_pix_fmt_loss", ctypes.c_int, [ ("dst_pix_fmt", ctypes.c_int), ("src_pix_fmt", ctypes.c_int), ("has_alpha", ctypes.c_int),] ) avcodec_find_best_pix_fmt = _rpythonic_function_( "avcodec_find_best_pix_fmt", ctypes.c_int, [ ("pix_fmt_mask", ctypes.c_int64), ("src_pix_fmt", ctypes.c_int), ("has_alpha", ctypes.c_int), ("loss_ptr", ctypes.POINTER(ctypes.c_int)),] ) ldexpf = _rpythonic_function_( "ldexpf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__exponent", ctypes.c_int),] ) logf = _rpythonic_function_( "logf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) log10f = _rpythonic_function_( "log10f", ctypes.c_float, [ ("__x", ctypes.c_float),] ) modff = _rpythonic_function_( "modff", ctypes.c_float, [ ("__x", ctypes.c_float), ("__iptr", ctypes.POINTER(ctypes.c_float)),] ) expm1f = _rpythonic_function_( "expm1f", ctypes.c_float, [ ("__x", ctypes.c_float),] ) log1pf = _rpythonic_function_( "log1pf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) logbf = _rpythonic_function_( "logbf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) exp2f = _rpythonic_function_( "exp2f", ctypes.c_float, [ ("__x", ctypes.c_float),] ) log2f = _rpythonic_function_( "log2f", ctypes.c_float, [ ("__x", ctypes.c_float),] ) powf = _rpythonic_function_( "powf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__y", ctypes.c_float),] ) ceilf = _rpythonic_function_( "ceilf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) fabsf = _rpythonic_function_( "fabsf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) floorf = _rpythonic_function_( "floorf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) sqrtf = _rpythonic_function_( "sqrtf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) hypotf = _rpythonic_function_( "hypotf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__y", ctypes.c_float),] ) cbrtf = _rpythonic_function_( "cbrtf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) fmodf = _rpythonic_function_( "fmodf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__y", ctypes.c_float),] ) isinff = _rpythonic_function_( "isinff", ctypes.c_int, [ ("__value", ctypes.c_float),] ) finitef = _rpythonic_function_( "finitef", ctypes.c_int, [ ("__value", ctypes.c_float),] ) dremf = _rpythonic_function_( "dremf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__y", ctypes.c_float),] ) significandf = _rpythonic_function_( "significandf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) copysignf = _rpythonic_function_( "copysignf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__y", ctypes.c_float),] ) nanf = _rpythonic_function_( "nanf", ctypes.c_float, [ ("__tagb", ctypes.POINTER(ctypes.c_char)),] ) isnanf = _rpythonic_function_( "isnanf", ctypes.c_int, [ ("__value", ctypes.c_float),] ) j0f = _rpythonic_function_( "j0f", ctypes.c_float, [ ("none", ctypes.c_float),] ) j1f = _rpythonic_function_( "j1f", ctypes.c_float, [ ("none", ctypes.c_float),] ) jnf = _rpythonic_function_( "jnf", ctypes.c_float, [ ("none", ctypes.c_int), ("none", ctypes.c_float),] ) y0f = _rpythonic_function_( "y0f", ctypes.c_float, [ ("none", ctypes.c_float),] ) y1f = _rpythonic_function_( "y1f", ctypes.c_float, [ ("none", ctypes.c_float),] ) ynf = _rpythonic_function_( "ynf", ctypes.c_float, [ ("none", ctypes.c_int), ("none", ctypes.c_float),] ) erff = _rpythonic_function_( "erff", ctypes.c_float, [ ("none", ctypes.c_float),] ) erfcf = _rpythonic_function_( "erfcf", ctypes.c_float, [ ("none", ctypes.c_float),] ) lgammaf = _rpythonic_function_( "lgammaf", ctypes.c_float, [ ("none", ctypes.c_float),] ) tgammaf = _rpythonic_function_( "tgammaf", ctypes.c_float, [ ("none", ctypes.c_float),] ) gammaf = _rpythonic_function_( "gammaf", ctypes.c_float, [ ("none", ctypes.c_float),] ) lgammaf_r = _rpythonic_function_( "lgammaf_r", ctypes.c_float, [ ("none", ctypes.c_float), ("__signgamp", ctypes.POINTER(ctypes.c_int)),] ) rintf = _rpythonic_function_( "rintf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) nextafterf = _rpythonic_function_( "nextafterf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__y", ctypes.c_float),] ) nexttowardf = _rpythonic_function_( "nexttowardf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__y", ctypes.c_double),] ) remainderf = _rpythonic_function_( "remainderf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__y", ctypes.c_float),] ) scalbnf = _rpythonic_function_( "scalbnf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__n", ctypes.c_int),] ) ilogbf = _rpythonic_function_( "ilogbf", ctypes.c_int, [ ("__x", ctypes.c_float),] ) scalblnf = _rpythonic_function_( "scalblnf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__n", ctypes.c_int64),] ) nearbyintf = _rpythonic_function_( "nearbyintf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) lrintf = _rpythonic_function_( "lrintf", ctypes.c_int64, [ ("__x", ctypes.c_float),] ) llrintf = _rpythonic_function_( "llrintf", ctypes.c_longlong, [ ("__x", ctypes.c_float),] ) lroundf = _rpythonic_function_( "lroundf", ctypes.c_int64, [ ("__x", ctypes.c_float),] ) roundf = _rpythonic_function_( "roundf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) truncf = _rpythonic_function_( "truncf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) remquof = _rpythonic_function_( "remquof", ctypes.c_float, [ ("__x", ctypes.c_float), ("__y", ctypes.c_float), ("__quo", ctypes.POINTER(ctypes.c_int)),] ) llroundf = _rpythonic_function_( "llroundf", ctypes.c_longlong, [ ("__x", ctypes.c_float),] ) fdimf = _rpythonic_function_( "fdimf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__y", ctypes.c_float),] ) fmaxf = _rpythonic_function_( "fmaxf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__y", ctypes.c_float),] ) fminf = _rpythonic_function_( "fminf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__y", ctypes.c_float),] ) fmaf = _rpythonic_function_( "fmaf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__y", ctypes.c_float), ("__z", ctypes.c_float),] ) scalbf = _rpythonic_function_( "scalbf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__n", ctypes.c_float),] ) acosl = _rpythonic_function_( "acosl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) asinl = _rpythonic_function_( "asinl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) atanl = _rpythonic_function_( "atanl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) atan2l = _rpythonic_function_( "atan2l", ctypes.c_double, [ ("__y", ctypes.c_double), ("__x", ctypes.c_double),] ) cosl = _rpythonic_function_( "cosl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) sinl = _rpythonic_function_( "sinl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) tanl = _rpythonic_function_( "tanl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) coshl = _rpythonic_function_( "coshl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) sinhl = _rpythonic_function_( "sinhl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) tanhl = _rpythonic_function_( "tanhl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) acoshl = _rpythonic_function_( "acoshl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) asinhl = _rpythonic_function_( "asinhl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) ldexpl = _rpythonic_function_( "ldexpl", ctypes.c_double, [ ("__x", ctypes.c_double), ("__exponent", ctypes.c_int),] ) logl = _rpythonic_function_( "logl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) log10l = _rpythonic_function_( "log10l", ctypes.c_double, [ ("__x", ctypes.c_double),] ) atanhl = _rpythonic_function_( "atanhl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) expl = _rpythonic_function_( "expl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) frexpl = _rpythonic_function_( "frexpl", ctypes.c_double, [ ("__x", ctypes.c_double), ("__exponent", ctypes.POINTER(ctypes.c_int)),] ) modfl = _rpythonic_function_( "modfl", ctypes.c_double, [ ("__x", ctypes.c_double), ("__iptr", ctypes.POINTER(ctypes.c_double)),] ) expm1l = _rpythonic_function_( "expm1l", ctypes.c_double, [ ("__x", ctypes.c_double),] ) log1pl = _rpythonic_function_( "log1pl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) logbl = _rpythonic_function_( "logbl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) exp2l = _rpythonic_function_( "exp2l", ctypes.c_double, [ ("__x", ctypes.c_double),] ) log2l = _rpythonic_function_( "log2l", ctypes.c_double, [ ("__x", ctypes.c_double),] ) powl = _rpythonic_function_( "powl", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) sqrtl = _rpythonic_function_( "sqrtl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) hypotl = _rpythonic_function_( "hypotl", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) cbrtl = _rpythonic_function_( "cbrtl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) ceill = _rpythonic_function_( "ceill", ctypes.c_double, [ ("__x", ctypes.c_double),] ) fabsl = _rpythonic_function_( "fabsl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) floorl = _rpythonic_function_( "floorl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) fmodl = _rpythonic_function_( "fmodl", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) isinfl = _rpythonic_function_( "isinfl", ctypes.c_int, [ ("__value", ctypes.c_double),] ) finitel = _rpythonic_function_( "finitel", ctypes.c_int, [ ("__value", ctypes.c_double),] ) dreml = _rpythonic_function_( "dreml", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) significandl = _rpythonic_function_( "significandl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) copysignl = _rpythonic_function_( "copysignl", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) j1l = _rpythonic_function_( "j1l", ctypes.c_double, [ ("none", ctypes.c_double),] ) jnl = _rpythonic_function_( "jnl", ctypes.c_double, [ ("none", ctypes.c_int), ("none", ctypes.c_double),] ) y0l = _rpythonic_function_( "y0l", ctypes.c_double, [ ("none", ctypes.c_double),] ) y1l = _rpythonic_function_( "y1l", ctypes.c_double, [ ("none", ctypes.c_double),] ) nanl = _rpythonic_function_( "nanl", ctypes.c_double, [ ("__tagb", ctypes.POINTER(ctypes.c_char)),] ) isnanl = _rpythonic_function_( "isnanl", ctypes.c_int, [ ("__value", ctypes.c_double),] ) j0l = _rpythonic_function_( "j0l", ctypes.c_double, [ ("none", ctypes.c_double),] ) ynl = _rpythonic_function_( "ynl", ctypes.c_double, [ ("none", ctypes.c_int), ("none", ctypes.c_double),] ) erfl = _rpythonic_function_( "erfl", ctypes.c_double, [ ("none", ctypes.c_double),] ) erfcl = _rpythonic_function_( "erfcl", ctypes.c_double, [ ("none", ctypes.c_double),] ) lgammal = _rpythonic_function_( "lgammal", ctypes.c_double, [ ("none", ctypes.c_double),] ) tgammal = _rpythonic_function_( "tgammal", ctypes.c_double, [ ("none", ctypes.c_double),] ) gammal = _rpythonic_function_( "gammal", ctypes.c_double, [ ("none", ctypes.c_double),] ) lgammal_r = _rpythonic_function_( "lgammal_r", ctypes.c_double, [ ("none", ctypes.c_double), ("__signgamp", ctypes.POINTER(ctypes.c_int)),] ) rintl = _rpythonic_function_( "rintl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) nextafterl = _rpythonic_function_( "nextafterl", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) nexttowardl = _rpythonic_function_( "nexttowardl", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) remainderl = _rpythonic_function_( "remainderl", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) scalbnl = _rpythonic_function_( "scalbnl", ctypes.c_double, [ ("__x", ctypes.c_double), ("__n", ctypes.c_int),] ) ilogbl = _rpythonic_function_( "ilogbl", ctypes.c_int, [ ("__x", ctypes.c_double),] ) scalblnl = _rpythonic_function_( "scalblnl", ctypes.c_double, [ ("__x", ctypes.c_double), ("__n", ctypes.c_int64),] ) nearbyintl = _rpythonic_function_( "nearbyintl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) llroundl = _rpythonic_function_( "llroundl", ctypes.c_longlong, [ ("__x", ctypes.c_double),] ) fdiml = _rpythonic_function_( "fdiml", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) fmaxl = _rpythonic_function_( "fmaxl", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) lrintl = _rpythonic_function_( "lrintl", ctypes.c_int64, [ ("__x", ctypes.c_double),] ) llrintl = _rpythonic_function_( "llrintl", ctypes.c_longlong, [ ("__x", ctypes.c_double),] ) lroundl = _rpythonic_function_( "lroundl", ctypes.c_int64, [ ("__x", ctypes.c_double),] ) roundl = _rpythonic_function_( "roundl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) truncl = _rpythonic_function_( "truncl", ctypes.c_double, [ ("__x", ctypes.c_double),] ) remquol = _rpythonic_function_( "remquol", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double), ("__quo", ctypes.POINTER(ctypes.c_int)),] ) scalbl = _rpythonic_function_( "scalbl", ctypes.c_double, [ ("__x", ctypes.c_double), ("__n", ctypes.c_double),] ) fminl = _rpythonic_function_( "fminl", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double),] ) fmal = _rpythonic_function_( "fmal", ctypes.c_double, [ ("__x", ctypes.c_double), ("__y", ctypes.c_double), ("__z", ctypes.c_double),] ) matherr = _rpythonic_function_( "matherr", ctypes.c_int, [ ("__exc", ctypes.POINTER(exception)),] ) atanhf = _rpythonic_function_( "atanhf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) expf = _rpythonic_function_( "expf", ctypes.c_float, [ ("__x", ctypes.c_float),] ) frexpf = _rpythonic_function_( "frexpf", ctypes.c_float, [ ("__x", ctypes.c_float), ("__exponent", ctypes.POINTER(ctypes.c_int)),] ) atof = _rpythonic_function_( "atof", ctypes.c_double, [ ("__nptr", ctypes.POINTER(ctypes.c_char)),] ) atoi = _rpythonic_function_( "atoi", ctypes.c_int, [ ("__nptr", ctypes.POINTER(ctypes.c_char)),] ) atol = _rpythonic_function_( "atol", ctypes.c_int64, [ ("__nptr", ctypes.POINTER(ctypes.c_char)),] ) strtoll = _rpythonic_function_( "strtoll", ctypes.c_longlong, [ ("__nptr", ctypes.POINTER(ctypes.c_char)), ("__endptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))), ("__base", ctypes.c_int),] ) strtoull = _rpythonic_function_( "strtoull", ctypes.c_ulonglong, [ ("__nptr", ctypes.POINTER(ctypes.c_char)), ("__endptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))), ("__base", ctypes.c_int),] ) l64a = _rpythonic_function_( "l64a", ctypes.POINTER(ctypes.c_char), [ ("__n", ctypes.c_int64),] ) a64l = _rpythonic_function_( "a64l", ctypes.c_int64, [ ("__s", ctypes.POINTER(ctypes.c_char)),] ) strtol = _rpythonic_function_( "strtol", ctypes.c_int64, [ ("__nptr", ctypes.POINTER(ctypes.c_char)), ("__endptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))), ("__base", ctypes.c_int),] ) strtoul = _rpythonic_function_( "strtoul", ctypes.c_uint64, [ ("__nptr", ctypes.POINTER(ctypes.c_char)), ("__endptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))), ("__base", ctypes.c_int),] ) strtoq = _rpythonic_function_( "strtoq", ctypes.c_longlong, [ ("__nptr", ctypes.POINTER(ctypes.c_char)), ("__endptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))), ("__base", ctypes.c_int),] ) strtouq = _rpythonic_function_( "strtouq", ctypes.c_ulonglong, [ ("__nptr", ctypes.POINTER(ctypes.c_char)), ("__endptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))), ("__base", ctypes.c_int),] ) strtod = _rpythonic_function_( "strtod", ctypes.c_double, [ ("__nptr", ctypes.POINTER(ctypes.c_char)), ("__endptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))),] ) atoll = _rpythonic_function_( "atoll", ctypes.c_longlong, [ ("__nptr", ctypes.POINTER(ctypes.c_char)),] ) strtof = _rpythonic_function_( "strtof", ctypes.c_float, [ ("__nptr", ctypes.POINTER(ctypes.c_char)), ("__endptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))),] ) strtold = _rpythonic_function_( "strtold", ctypes.c_double, [ ("__nptr", ctypes.POINTER(ctypes.c_char)), ("__endptr", ctypes.POINTER(ctypes.POINTER(ctypes.c_char))),] ) select = _rpythonic_function_( "select", ctypes.c_int, [ ("__nfds", ctypes.c_int), ("__readfds", ctypes.POINTER(fd_set)), ("__writefds", ctypes.POINTER(fd_set)), ("__exceptfds", ctypes.POINTER(fd_set)), ("__timeout", ctypes.POINTER(timeval)),] ) pselect = _rpythonic_function_( "pselect", ctypes.c_int, [ ("__nfds", ctypes.c_int), ("__readfds", ctypes.POINTER(fd_set)), ("__writefds", ctypes.POINTER(fd_set)), ("__exceptfds", ctypes.POINTER(fd_set)), ("__timeout", ctypes.POINTER(timespec)), ("__sigmask", ctypes.POINTER(__sigset_t)),] ) gnu_dev_major = _rpythonic_function_( "gnu_dev_major", ctypes.c_uint, [ ("__dev", ctypes.c_ulonglong),] ) gnu_dev_minor = _rpythonic_function_( "gnu_dev_minor", ctypes.c_uint, [ ("__dev", ctypes.c_ulonglong),] ) av_read_packet = _rpythonic_function_( "av_read_packet", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)), ("pkt", ctypes.POINTER(AVPacket)),] ) av_read_frame = _rpythonic_function_( "av_read_frame", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)), ("pkt", ctypes.POINTER(AVPacket)),] ) av_seek_frame = _rpythonic_function_( "av_seek_frame", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)), ("stream_index", ctypes.c_int), ("timestamp", ctypes.c_int64), ("flags", ctypes.c_int),] ) avformat_seek_file = _rpythonic_function_( "avformat_seek_file", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)), ("stream_index", ctypes.c_int), ("min_ts", ctypes.c_int64), ("ts", ctypes.c_int64), ("max_ts", ctypes.c_int64), ("flags", ctypes.c_int),] ) av_read_play = _rpythonic_function_( "av_read_play", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)),] ) av_read_pause = _rpythonic_function_( "av_read_pause", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)),] ) av_close_input_stream = _rpythonic_function_( "av_close_input_stream", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVFormatContext)),] ) av_close_input_file = _rpythonic_function_( "av_close_input_file", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVFormatContext)),] ) avformat_free_context = _rpythonic_function_( "avformat_free_context", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVFormatContext)),] ) av_new_stream = _rpythonic_function_( "av_new_stream", ctypes.POINTER(AVStream), [ ("s", ctypes.POINTER(AVFormatContext)), ("C_id", ctypes.c_int),] ) av_new_program = _rpythonic_function_( "av_new_program", ctypes.POINTER(AVProgram), [ ("s", ctypes.POINTER(AVFormatContext)), ("C_id", ctypes.c_int),] ) av_set_pts_info = _rpythonic_function_( "av_set_pts_info", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVStream)), ("pts_wrap_bits", ctypes.c_int), ("pts_num", ctypes.c_uint), ("pts_den", ctypes.c_uint),] ) av_find_default_stream_index = _rpythonic_function_( "av_find_default_stream_index", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)),] ) av_index_search_timestamp = _rpythonic_function_( "av_index_search_timestamp", ctypes.c_int, [ ("st", ctypes.POINTER(AVStream)), ("timestamp", ctypes.c_int64), ("flags", ctypes.c_int),] ) av_add_index_entry = _rpythonic_function_( "av_add_index_entry", ctypes.c_int, [ ("st", ctypes.POINTER(AVStream)), ("pos", ctypes.c_int64), ("timestamp", ctypes.c_int64), ("size", ctypes.c_int), ("distance", ctypes.c_int), ("flags", ctypes.c_int),] ) av_seek_frame_binary = _rpythonic_function_( "av_seek_frame_binary", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)), ("stream_index", ctypes.c_int), ("target_ts", ctypes.c_int64), ("flags", ctypes.c_int),] ) av_interleave_packet_per_dts = _rpythonic_function_( "av_interleave_packet_per_dts", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)), ("out", ctypes.POINTER(AVPacket)), ("pkt", ctypes.POINTER(AVPacket)), ("flush", ctypes.c_int),] ) av_write_trailer = _rpythonic_function_( "av_write_trailer", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)),] ) dump_format = _rpythonic_function_( "dump_format", ctypes.c_void_p, [ ("ic", ctypes.POINTER(AVFormatContext)), ("index", ctypes.c_int), ("url", ctypes.POINTER(ctypes.c_char)), ("is_output", ctypes.c_int),] ) av_dump_format = _rpythonic_function_( "av_dump_format", ctypes.c_void_p, [ ("ic", ctypes.POINTER(AVFormatContext)), ("index", ctypes.c_int), ("url", ctypes.POINTER(ctypes.c_char)), ("is_output", ctypes.c_int),] ) av_update_cur_dts = _rpythonic_function_( "av_update_cur_dts", ctypes.c_void_p, [ ("s", ctypes.POINTER(AVFormatContext)), ("ref_st", ctypes.POINTER(AVStream)), ("timestamp", ctypes.c_int64),] ) av_gen_search = _rpythonic_function_( "av_gen_search", ctypes.c_int64, [ ("s", ctypes.POINTER(AVFormatContext)), ("stream_index", ctypes.c_int), ("target_ts", ctypes.c_int64), ("pos_min", ctypes.c_int64), ("pos_max", ctypes.c_int64), ("pos_limit", ctypes.c_int64), ("ts_min", ctypes.c_int64), ("ts_max", ctypes.c_int64), ("flags", ctypes.c_int), ("ts_ret", ctypes.POINTER(ctypes.c_int64)), ("read_timestamp", ctypes.c_void_p),] ) av_set_parameters = _rpythonic_function_( "av_set_parameters", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)), ("ap", ctypes.POINTER(AVFormatParameters)),] ) av_url_split = _rpythonic_function_( "av_url_split", ctypes.c_void_p, [ ("proto", ctypes.POINTER(ctypes.c_char)), ("proto_size", ctypes.c_int), ("authorization", ctypes.POINTER(ctypes.c_char)), ("authorization_size", ctypes.c_int), ("hostname", ctypes.POINTER(ctypes.c_char)), ("hostname_size", ctypes.c_int), ("port_ptr", ctypes.POINTER(ctypes.c_int)), ("path", ctypes.POINTER(ctypes.c_char)), ("path_size", ctypes.c_int), ("url", ctypes.POINTER(ctypes.c_char)),] ) avformat_write_header = _rpythonic_function_( "avformat_write_header", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)), ("options", ctypes.POINTER(ctypes.POINTER(AVDictionary))),] ) av_write_header = _rpythonic_function_( "av_write_header", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)),] ) av_write_frame = _rpythonic_function_( "av_write_frame", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)), ("pkt", ctypes.POINTER(AVPacket)),] ) av_interleaved_write_frame = _rpythonic_function_( "av_interleaved_write_frame", ctypes.c_int, [ ("s", ctypes.POINTER(AVFormatContext)), ("pkt", ctypes.POINTER(AVPacket)),] ) parse_date = _rpythonic_function_( "parse_date", ctypes.c_int64, [ ("datestr", ctypes.POINTER(ctypes.c_char)), ("duration", ctypes.c_int),] ) av_gettime = _rpythonic_function_( "av_gettime", ctypes.c_int64, [] ) find_info_tag = _rpythonic_function_( "find_info_tag", ctypes.c_int, [ ("arg", ctypes.POINTER(ctypes.c_char)), ("arg_size", ctypes.c_int), ("tag1", ctypes.POINTER(ctypes.c_char)), ("info", ctypes.POINTER(ctypes.c_char)),] ) av_get_frame_filename = _rpythonic_function_( "av_get_frame_filename", ctypes.c_int, [ ("buf", ctypes.POINTER(ctypes.c_char)), ("buf_size", ctypes.c_int), ("path", ctypes.POINTER(ctypes.c_char)), ("number", ctypes.c_int),] ) av_filename_number_test = _rpythonic_function_( "av_filename_number_test", ctypes.c_int, [ ("filename", ctypes.POINTER(ctypes.c_char)),] ) av_sdp_create = _rpythonic_function_( "av_sdp_create", ctypes.c_int, [ ("ac", ctypes.POINTER(AVFormatContext)), ("n_files", ctypes.c_int), ("buf", ctypes.POINTER(ctypes.c_char)), ("size", ctypes.c_int),] ) avf_sdp_create = _rpythonic_function_( "avf_sdp_create", ctypes.c_int, [ ("ac", ctypes.POINTER(AVFormatContext)), ("n_files", ctypes.c_int), ("buff", ctypes.POINTER(ctypes.c_char)), ("size", ctypes.c_int),] ) av_match_ext = _rpythonic_function_( "av_match_ext", ctypes.c_int, [ ("filename", ctypes.POINTER(ctypes.c_char)), ("extensions", ctypes.POINTER(ctypes.c_char)),] ) _rpythonic_convert_structs_to_objects() _rpythonic_setup_return_wrappers() _rpythonic_make_nice_global_enums_() _rpythonic_clean_up_missing_functions_() _rpythonic_strip_prefixes_(['AV', 'FF_'])
[ "goatman.py@gmail.com" ]
goatman.py@gmail.com
d90da441df51f7b5e335baf4510a25fea2231eee
6f797bae522927214b4c4065d88b92d6fff127e0
/kur/containers/layers/pooling.py
d8290b51f6cea476965e8cc31bbc828717a6bb70
[ "Apache-2.0", "Python-2.0" ]
permissive
deepgram/kur
5a3c6b5dba462327ccb134dcde53bf60ee4bf1fd
fd0c120e50815c1e5be64e5dde964dcd47234556
refs/heads/master
2023-08-17T11:38:47.613445
2020-11-04T19:09:50
2020-11-04T19:09:50
74,182,569
873
139
Apache-2.0
2023-01-28T21:50:24
2016-11-19T02:42:09
Python
UTF-8
Python
false
false
8,307
py
""" Copyright 2016 Deepgram Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from . import Layer, ParsingError ############################################################################### class Pooling(Layer): # pylint: disable=too-few-public-methods """ A pooling layer # Properties size: int or list of ints (required). The size of each kernel. If an integer is used, it is interpretted as a one-dimensional convolution, the same as if it were put into a length-1 list. strides: int or list of ints (optional; default: 1 in each dimension). The stride (subsampling rate) between convolutions. If a list, it must be the same length as `size` and specify the stride in each respective dimension. If a single number, it is used as the stride in each dimension. pool: one of (max, average). The pool function to apply. # Example ``` pool: size: [2, 2] strides: 1 type: max ``` """ POOL_TYPES = ('max', 'average') ########################################################################### @classmethod def get_container_name(cls): """ Returns the name of the container class. """ return 'pool' ########################################################################### def __init__(self, *args, **kwargs): """ Creates a new pooling layer. """ super().__init__(*args, **kwargs) self.size = None self.strides = None self.pooltype = None self.border = None ########################################################################### def _parse(self, engine): """ Parses out the pooling layer. """ # Parse self if isinstance(self.args, dict): if 'size' not in self.args: raise ParsingError('Missing key "size" in pooling container.') self.size = engine.evaluate(self.args['size'], recursive=True) if 'strides' in self.args: self.strides = engine.evaluate(self.args['strides'], recursive=True) if 'type' in self.args: self.pooltype = engine.evaluate(self.args['type']).lower() if self.pooltype not in Pooling.POOL_TYPES: raise ParsingError('Unknown pool type "{}". Pool type can ' 'be one of: {}'.format( self.pooltype, ', '.join(Pooling.POOL_TYPES) )) if 'border' in self.args: self.border = engine.evaluate(self.args['border']).lower() if not isinstance(self.border, str) or \ not self.border in ('valid', 'same'): raise ParsingError('"border" must be one of: "valid", ' '"same".') else: self.size = engine.evaluate(self.args, recursive=True) if self.pooltype is None: self.pooltype = Pooling.POOL_TYPES[0] if self.border is None: self.border = 'valid' if not isinstance(self.size, (list, tuple)): self.size = [self.size] if not 1 <= len(self.size) <= 3: raise ParsingError('Only pooling layers with dimensions 1, 2, ' 'or 3 are supported.') for i in range(len(self.size)): try: self.size[i] = int(self.size[i]) except ValueError: raise ParsingError('All "size" entries must evaluate to ' 'integers. We received this instead: {}' .format(self.size[i])) if self.strides is not None: if not isinstance(self.strides, (list, tuple)): try: self.strides = int(self.strides) except ValueError: raise ParsingError('"strides" must evaluate to an ' 'integer or a list of integers.') self.strides = [self.strides] * len(self.size) else: if len(self.strides) != len(self.size): raise ParsingError('If "strides" is a list, it must ' 'be the same length as "size".') for i in range(len(self.strides)): try: self.strides[i] = int(self.strides[i]) except ValueError: raise ParsingError('Each element of "strides" ' 'must evaluate to an integer.') else: self.strides = [1] * len(self.size) ########################################################################### def _build(self, model): """ Instantiates the layer with the given backend. """ backend = model.get_backend() if backend.get_name() == 'keras': if backend.keras_version() == 1: import keras.layers as L # pylint: disable=import-error kwargs = { 'pool_size' : self.size, 'strides' : self.strides, 'border_mode' : self.border, 'name' : self.name } if len(self.size) == 1: kwargs['pool_length'] = kwargs.pop('pool_size') kwargs['stride'] = kwargs.pop('strides') else: import keras.layers.pooling as L # pylint: disable=import-error kwargs = { 'pool_size' : self.size, 'strides' : self.strides, 'padding' : self.border, 'name' : self.name } if len(self.size) == 1: kwargs['pool_size'] = kwargs.pop('pool_size')[0] else: kwargs['data_format'] = 'channels_last' if self.pooltype == 'max': func = { 1 : L.MaxPooling1D, 2 : L.MaxPooling2D, 3 : L.MaxPooling3D }.get(len(self.size)) elif self.pooltype == 'average': func = { 1 : L.AveragePooling1D, 2 : L.AveragePooling2D, 3 : L.AveragePooling3D }.get(len(self.size)) else: raise ValueError('Unhandled pool type "{}". This is a bug.', self.pooltype) if func is None: raise ValueError('Invalid pool function for pool type "{}" ' 'the supplied pool parameters. This is a bug.' .format(self.pooltype)) yield func(**kwargs) elif backend.get_name() == 'pytorch': import torch.nn as nn # pylint: disable=import-error from kur.backend.pytorch.modules import swap_channels if self.pooltype == 'max': func = { 1 : nn.MaxPool1d, 2 : nn.MaxPool2d, 3 : nn.MaxPool3d }.get(len(self.size)) elif self.pooltype == 'average': func = { 1 : nn.AvgPool1d, 2 : nn.AvgPool2d, 3 : nn.AvgPool3d }.get(len(self.size)) else: raise ValueError('Unhandled pool type "{}". This is a bug.', self.pooltype) if self.border == 'valid': padding = 0 else: # "same" padding requires you to pad with P = S - 1 zeros # total. However, PyTorch always pads both sides of the input # tensor, implying that PyTorch only accepts padding P' such # that P = 2P'. This unfortunately means that if S is even, # then the desired padding P is odd, and so no P' exists. if any(s % 2 == 0 for s in self.size): raise ValueError('PyTorch pool layers cannot use "same" ' 'border mode when the receptive field "size" is even.') padding = tuple((s-1)//2 for s in self.size) def connect(inputs): """ Connects the layers. """ assert len(inputs) == 1 output = model.data.add_operation( swap_channels.begin )(inputs[0]['layer']) output = model.data.add_layer( self.name, func( self.size, self.strides, padding=padding, dilation=1, ceil_mode=False ) )(output) output = model.data.add_operation( swap_channels.end )(output) return { 'shape' : self.shape([inputs[0]['shape']]), 'layer' : output } yield connect else: raise ValueError( 'Unknown or unsupported backend: {}'.format(backend)) ########################################################################### def shape(self, input_shapes): """ Returns the output shape of this layer for a given input shape. """ if len(input_shapes) > 1: raise ValueError('Pooling layers only take a single input.') input_shape = input_shapes[0] if len(input_shape) != len(self.size) + 1: raise ValueError('Invalid input shape to a pooling layer: {}' .format(input_shape)) output_shape = tuple( (input_shape[i] - self.size[i]) // self.strides[i] + 1 \ if input_shape[i] else None for i in range(len(self.size)) ) + (input_shape[-1], ) return output_shape ### EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF
[ "ajsyp@syptech.net" ]
ajsyp@syptech.net
71d9b837299e9da2d6851ac2153b22150b38ad1f
7bededcada9271d92f34da6dae7088f3faf61c02
/pypureclient/flasharray/FA_2_17/models/remote_protection_group_snapshot_get_response.py
f3f01b74864fe85980624ee3cc7874ab70a375f9
[ "BSD-2-Clause" ]
permissive
PureStorage-OpenConnect/py-pure-client
a5348c6a153f8c809d6e3cf734d95d6946c5f659
7e3c3ec1d639fb004627e94d3d63a6fdc141ae1e
refs/heads/master
2023-09-04T10:59:03.009972
2023-08-25T07:40:41
2023-08-25T07:40:41
160,391,444
18
29
BSD-2-Clause
2023-09-08T09:08:30
2018-12-04T17:02:51
Python
UTF-8
Python
false
false
5,788
py
# coding: utf-8 """ FlashArray REST API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 2.17 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re import six import typing from ....properties import Property if typing.TYPE_CHECKING: from pypureclient.flasharray.FA_2_17 import models class RemoteProtectionGroupSnapshotGetResponse(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'more_items_remaining': 'bool', 'total_item_count': 'int', 'continuation_token': 'str', 'items': 'list[RemoteProtectionGroupSnapshot]' } attribute_map = { 'more_items_remaining': 'more_items_remaining', 'total_item_count': 'total_item_count', 'continuation_token': 'continuation_token', 'items': 'items' } required_args = { } def __init__( self, more_items_remaining=None, # type: bool total_item_count=None, # type: int continuation_token=None, # type: str items=None, # type: List[models.RemoteProtectionGroupSnapshot] ): """ Keyword args: more_items_remaining (bool): Returns a value of `true` if subsequent items can be retrieved. total_item_count (int): The total number of records after applying all filter query parameters. The `total_item_count` will be calculated if and only if the corresponding query parameter `total_item_count` is set to `true`. If this query parameter is not set or set to `false`, a value of `null` will be returned. continuation_token (str): Continuation token that can be provided in the `continuation_token` query param to get the next page of data. If you use the continuation token to page through data you are guaranteed to get all items exactly once regardless of how items are modified. If an item is added or deleted during the pagination then it may or may not be returned. The continuation token is generated if the limit is less than the remaining number of items, and the default sort is used (no sort is specified). items (list[RemoteProtectionGroupSnapshot]): Returns a list of all items after filtering. The values are displayed for each name where meaningful. """ if more_items_remaining is not None: self.more_items_remaining = more_items_remaining if total_item_count is not None: self.total_item_count = total_item_count if continuation_token is not None: self.continuation_token = continuation_token if items is not None: self.items = items def __setattr__(self, key, value): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `RemoteProtectionGroupSnapshotGetResponse`".format(key)) self.__dict__[key] = value def __getattribute__(self, item): value = object.__getattribute__(self, item) if isinstance(value, Property): raise AttributeError else: return value def __getitem__(self, key): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `RemoteProtectionGroupSnapshotGetResponse`".format(key)) return object.__getattribute__(self, key) def __setitem__(self, key, value): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `RemoteProtectionGroupSnapshotGetResponse`".format(key)) object.__setattr__(self, key, value) def __delitem__(self, key): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `RemoteProtectionGroupSnapshotGetResponse`".format(key)) object.__delattr__(self, key) def keys(self): return self.attribute_map.keys() def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): if hasattr(self, attr): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(RemoteProtectionGroupSnapshotGetResponse, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, RemoteProtectionGroupSnapshotGetResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "noreply@github.com" ]
PureStorage-OpenConnect.noreply@github.com
b42d9964bbce3a6b6dcdb1e6b5a49ec0faa8fdfa
8218813b16d2ea2b39b6bd599a0c45d698389c32
/ansible/roles/lib_zabbix/build/ansible/zbx_maintenance.py
5a1ced7f99961bd72389d822d28960f49d43144d
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
zgalor/openshift-tools
05f500bea6f7beb6b62e3c9f406751ea913f2639
63c8d0aea8f237939f290dc6e91530d9767f1945
refs/heads/stg
2021-01-12T16:24:59.753014
2016-10-25T22:11:06
2016-10-25T22:11:06
71,991,757
0
0
null
2016-10-26T10:18:56
2016-10-26T10:18:56
null
UTF-8
Python
false
false
1,361
py
# pylint: skip-file def main(): ''' Create a maintenace in zabbix ''' module = AnsibleModule( argument_spec=dict( zbx_server=dict(default='https://localhost/zabbix/api_jsonrpc.php', type='str'), zbx_user=dict(default=os.environ.get('ZABBIX_USER', None), type='str'), zbx_password=dict(default=os.environ.get('ZABBIX_PASSWORD', None), type='str'), zbx_debug=dict(default=False, type='bool'), zbx_sslverify=dict(default=False, type='bool'), state=dict(default='present', choices=['present', 'absent', 'list'], type='str'), hosts=dict(default=None, type='list'), hostgroups=dict(default=None, type='list'), name=dict(default=None, type='str'), description=dict(default=None, type='str'), start_time=dict(default=int(time.time()), type='int'), duration=dict(default=60, type='int'), data_collection=dict(default=True, type='bool'), ), supports_check_mode=False ) rval = ZbxMaintenance.run_ansible(module.params) module.exit_json(**rval) # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled # import module snippets. This are required if __name__ == '__main__': from ansible.module_utils.basic import * main()
[ "kwoodson@redhat.com" ]
kwoodson@redhat.com
f6912355091fa1ab626656b327d3abb7a2ded441
11d265eba2ced9de43c339e4014c779b521320cd
/accounts/migrations/0003_auto_20200423_2251.py
9e85e74a27235d2afa6d5ee07d8608f4d3d364ed
[]
no_license
Sloshpit/budget_old
d9271de625cd7e3aa66ccbec501b005e50cd2812
a5603996b026542adb3bc8c578c03bcb843bea01
refs/heads/master
2022-04-23T08:42:43.377827
2020-04-25T14:40:39
2020-04-25T14:40:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
366
py
# Generated by Django 3.0.5 on 2020-04-24 02:51 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0002_auto_20200423_2248'), ] operations = [ migrations.RenameField( model_name='account', old_name='tr', new_name='transaction', ), ]
[ "neel.maheshwari@gmail.com" ]
neel.maheshwari@gmail.com
30f90e427b984555b702c00242861da4f22e2aa2
205be8d429df36e27cdfc048bfca9212c5a62a87
/ward/views.py
616ad0dc9cc222cafec6a2601e1b9e59eda027dd
[]
no_license
KennyChrisUmurundi/HOsto
16c8f926282fc48c981532447f1685fbbc2b457c
33fa31524a08934f3deb8f622a1b1554d8ef1af4
refs/heads/master
2022-04-01T02:42:39.146227
2020-01-07T11:44:08
2020-01-07T11:44:08
193,458,881
0
0
null
null
null
null
UTF-8
Python
false
false
3,425
py
from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse from reception.models import Patient, Appointment from django.db.models import Sum from django.contrib.auth.decorators import login_required from .models import PatientStatus, PatientReport from . import forms as ward_forms import hashlib # Create your views here. @login_required(login_url='/') def ward_home(request): PatientCode = request.POST.get('PatientCode', False) context = { 'PatientByCode' : Patient.objects.filter(code__icontains=PatientCode), } return render(request, 'ward/ward_home.html', context) @login_required(login_url='/') def inpatient_info(request, code): thecode = code apptmt = Appointment.objects.filter(patient=thecode).aggregate(Sum('price'))['price__sum'] context = { 'CurrentPatient' : Patient.objects.filter(code=thecode), 'reception' : Appointment.objects.filter(patient=thecode), 'RecTotalPrice' : apptmt, } return render(request, 'ward/inpatient_info.html', context) @login_required(login_url='/') def patient_status_update(request, code, id): return render(request, 'ward/patientStatus.html') @login_required(login_url='/') def patient_status_update(request, code): app_instance = get_object_or_404(Patient, code=code) update_patientStatus_form = ward_forms.PatientStatusUpdate(request.POST or None, instance=app_instance.patientstatus) if request.method == 'POST': update_patientStatus_form = ward_forms.PatientStatusUpdate(request.POST or None, instance=app_instance.patientstatus) if update_patientStatus_form.is_valid(): u_patientStatus = update_patientStatus_form.save(commit=False) u_patientStatus.status = app_instance.patientstatus.status update_patientStatus_form.save() print('success') if request.user.role.role == 'is_doctor': return redirect('doctor:patient', code=app_instance.code) elif request.user.role.role == 'is_nurse': return redirect('ward:nurse-home') else: print('not valid') else: update_patientStatus_form = ward_forms.PatientStatusUpdate(instance=app_instance.patientstatus) context = { 'update_patientStatus_form' : update_patientStatus_form, 'patient' : Patient.objects.filter(code=code), } return render(request, 'ward/patientStatus.html', context) def nurse_home(request): context = { 'inpatient' : PatientStatus.objects.filter(status='InPatient') } return render(request, 'ward/nurse_home.html', context) def patientFinalReport(request, code, id): if request.method == 'POST': patient = Patient.objects.get(id=request.POST['patient']) prescription = request.POST['prescription'] n = len(prescription.split()) print(type(n)) print(n) report = request.POST['report'] p_report = PatientReport.objects.filter(patient=patient) if not p_report: print('Yes') PatientReport.objects.create( patient = patient, doctor_prescription = prescription, nurse_report = report ) else: for patient_report in p_report: p = len(patient_report.doctor_prescription.split()) print(type(p)) print(p) if p is not None and n == p: print('Nothing was modify') else: print('Yes') # PatientReport.objects.create( # patient = patient, # doctor_prescription = prescription, # nurse_report = report # ) return HttpResponse('')
[ "ndayikennysmuusic@gmail.com" ]
ndayikennysmuusic@gmail.com
183e831869771e445da8acbd31a8537370b2240a
9fe219d1971d0e8613eaa99b7ba238bedf4258c1
/bmf_proc.py
13486c33a54b37ca4fd7bd1fb1be80af44908494
[]
no_license
ShawnYi5/restore-iso
bb5fb0fdb1b5f6b200428266c7318e1ef27d6c59
725141f2283cc2c94c55f042b1929c845a1b8b14
refs/heads/master
2022-10-27T19:21:23.990688
2019-08-22T03:13:50
2019-08-22T03:13:50
203,700,366
0
2
null
2022-10-13T06:03:20
2019-08-22T02:35:54
Python
UTF-8
Python
false
false
5,310
py
import json import os import sys import win32api import win32file import win32con current_dir = os.path.split(os.path.realpath(__file__))[0] sys.path.append(current_dir) import xlogging class CBmfProc(xlogging.WorkWithLogger): def __init__(self): xlogging.WorkWithLogger.__init__(self, r'bmf_proc', 188) def search_need_disk_guid(self): ret_num = -1 flag_string = r'hhekaxxm9idsvW5PdutqgPthyuwuqwq6w5yjfbt9zgTbCtkvebrrknmpzspqhuC2' for i in range(26): try: handle = win32file.CreateFile('\\\\.\\PhysicalDrive' + str(i), win32con.GENERIC_READ, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, 0) win32file.SetFilePointer(handle, 1024 * 1024 * 2 - 512, win32con.FILE_BEGIN) (ret, ret_str) = win32file.ReadFile(handle, 512, None) win32api.CloseHandle(handle) if ret != 0: self.logger.info( 'win32file.CreateFile error file = {},continue search'.format('\\\\.\\PhysicalDrive' + str(i))) continue if -1 != ret_str.find(flag_string.encode('utf-8')): ret_num = i self.logger.info('find flag_string error file ,continue search') break except: continue return ret_num def read_bin_file_no_print_context(self, file_path): try: max_buffer_bytes = 8 * 1024 * 1024 with open(file_path, 'rb') as file_handle: while True: read_bytes = len(file_handle.read(max_buffer_bytes)) self.logger.info("file_path = {},read len = {}".format(file_path, read_bytes)) if read_bytes < max_buffer_bytes or read_bytes == 0: break except Exception as e: self.logger.error(r'read_bin_file_no_print_context {} failed. {}'.format(file_path, e), exc_info=True) def get_windows_version(self): ver_info = win32api.GetVersionEx() self.logger.info('ver_info = {}'.format(ver_info)) return ver_info[0], ver_info[1] def write_ext_info(self, disk_handle): windows_major_version, windows_minor_version = self.get_windows_version() ext_info = {'windows_version': {'major': windows_major_version, 'minor': windows_minor_version}} ext_info_data = json.dumps(ext_info).encode().ljust(512, b'\0') win32file.SetFilePointer(disk_handle, 1024 * 1024 * 2, win32con.FILE_BEGIN) win32file.WriteFile(disk_handle, ext_info_data, None) def work_real(self): disk_num = self.search_need_disk_guid() if -1 == disk_num: raise Exception('bmf can not find disk guid') windows_dir = win32api.GetWindowsDirectory() self.logger.info(windows_dir) windows_list = os.listdir(windows_dir) self.logger.info(windows_list) bmf_list = [] for i in windows_list: if i.endswith('.bmf'): bmf_list.append(os.path.join(windows_dir, i)) self.logger.info(bmf_list) bmf_list.sort() self.logger.info(bmf_list) disk_handle = win32file.CreateFile('\\\\.\\PhysicalDrive' + str(disk_num), win32con.GENERIC_WRITE, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, 0) self.logger.info('floppy_handle = {} {}'.format(disk_handle, disk_num)) win32file.SetFilePointer(disk_handle, 4 * 1024, win32file.FILE_BEGIN) self.logger.info('skip 4k') for i in bmf_list: # 必须把bmf文件完整的读取,否则在bmf文件跨越 64k 块并且未读取过时,会被还原掉。。。 self.read_bin_file_no_print_context(i) handle = win32file.CreateFile(i, win32con.GENERIC_READ, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, 0) self.logger.info('bmf name = {},file handle = {}'.format(i, handle)) (ret, ret_str) = win32file.ReadFile(handle, 4 * 1024, None) if ret != 0 or len(ret_str) != 4 * 1024: self.logger.info('ReadFile error,file = {} len = {}'.format(i, len(ret_str))) win32api.CloseHandle(handle) continue self.logger.info(ret_str) ret, _ = win32file.WriteFile(disk_handle, ret_str, None) if ret != 0: raise Exception('bmf WriteFile err ret = {}'.format(ret)) else: self.logger.info('WriteFile success : {}'.format(i)) win32api.CloseHandle(handle) self.write_ext_info(disk_handle) win32api.CloseHandle(disk_handle) if __name__ == "__main__": cbmf_proc = CBmfProc() cbmf_proc.work()
[ "yi.shihong@aliyun.com" ]
yi.shihong@aliyun.com
46bc3df195b3fe48b2c3449145f923d6b8818e5d
8668830f34ce260565217ea3b49e090778780b44
/coupon/factories/coupon_factory.py
d014517eb75905fd048a06d8f80fd5d7f104676e
[]
no_license
wcirillo/ten
72baf94da958b2ee6f34940c1fc3116660436762
a780ccdc3350d4b5c7990c65d1af8d71060c62cc
refs/heads/master
2016-09-06T13:39:03.966370
2015-07-02T12:37:36
2015-07-02T12:37:36
15,700,975
0
0
null
null
null
null
UTF-8
Python
false
false
5,446
py
""" Coupon Factory used to help create quick Coupon instances for tests. """ from advertiser.factories.location_factory import COUPON_LOCATION_FACTORY from coupon.factories.offer_factory import OFFER_FACTORY from coupon.models import Coupon class CouponFactory(object): """ Coupon Factory Class """ @staticmethod def _create(offer, coupon_type_id=3): """ Create a single coupon instance. """ coupon = Coupon.objects.create(offer=offer, coupon_type_id=coupon_type_id) return coupon def create_coupon(self, offer=None, **kwargs): """ Create a ONE basic coupon instance with an offer, business and advertiser association. """ create_location = kwargs.get('create_location', True) if not offer: offer = OFFER_FACTORY.create_offer(**kwargs) coupon = self._create(offer=offer) if create_location: COUPON_LOCATION_FACTORY.create_coupon_location(coupon) return coupon def create_coupons(self, offer=None, create_offer=False, create_count=1): """ This method will do 1 of 3 things. default.) offer == None create_offer == False Create 1 or more offers and associate them with different offers -> businesses -> advertisers. Ex: coupon -> offer -> business -> advertiser coupon1 -> offer1 -> business1 -> advertiser1 coupon2 -> offer2 -> business2 -> advertiser2 coupon3 -> offer3 -> business3 -> advertiser3 2.) offer == None create_offer == True Create an offer -> business -> advertiser. Then create coupons for that offer. Ex: coupon -> offer -> business -> advertiser coupon1 -> offer -> business -> advertiser coupon2 -> offer -> business -> advertiser 3.) offer != None create_offer == False If an offer is passed in use that offer. Create 1 or more coupons and associate them with the same offer -> business -> advertiser. Ex: coupon -> offer -> business -> advertiser coupon1 -> offer -> business -> advertiser coupon2 -> offer -> business -> advertiser """ coupon_list = [] current_create_count = 0 create_many_offers = True if create_offer: offer = OFFER_FACTORY.create_offer() create_many_offers = False else: if offer: create_many_offers = False while current_create_count < create_count: if create_many_offers: offer = OFFER_FACTORY.create_offer() coupon = self._create(offer=offer) COUPON_LOCATION_FACTORY.create_coupon_location(coupon) current_create_count += 1 coupon_list.append(coupon) return coupon_list def create_coupon_many_locations(self, offer=None, create_all=True, business_location_count=1, coupon_location_count=1): """ Create a coupon with multiple locations associated with it. ARG Definitions: create_all == True will ensure that every business_location will get associated with this coupon. business_location_count == the number of locations that the respective business of this coupon will have in total. coupon_location_count == The number of business_locations that will be associated with this coupon. """ coupon = self.create_coupon(offer=offer) #current_create_count = 1 #while(current_create_count < business_location_count): COUPON_LOCATION_FACTORY.create_coupon_locations(coupon, create_all=create_all, business_location_count=business_location_count, coupon_location_count=coupon_location_count) # current_create_count += 1 return coupon def create_coupons_many_locations(self, offer=None, create_all=True, create_count=1, **kwargs): """ Create multiple coupons with multiple locations associated with each one. ARG Definitions: create_all == True will ensure that every business_location will get associated with this coupon. business_location_count == the number of locations that the respective business of this coupon will have in total. coupon_location_count == The number of business_locations that will be associated with this coupon. """ coupon_list = self.create_coupons(offer=offer, create_count=create_count) for coupon in coupon_list: COUPON_LOCATION_FACTORY.create_coupon_locations(coupon, create_all=create_all, business_location_count=kwargs.get('business_location_count', 1), coupon_location_count=kwargs.get('coupon_location_count', 1)) return coupon_list @staticmethod def normalize_coupon_locations(coupon): """ Normalize locations of this coupon to NY state. """ locations = coupon.location.all() for location in locations: location.location_state_province = 'NY' location.save() COUPON_FACTORY = CouponFactory()
[ "williamcirillo@gmail.com" ]
williamcirillo@gmail.com
8563336093cb3a3bb777b14a25ef9b23beb1ffcf
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/116/usersdata/189/26740/submittedfiles/al1.py
6014af9ec62b958ab7597cc940108dd8387f02ba
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
137
py
# -*- coding: utf-8 - r=float(input("digite o raio:")) a=float(input("digite a altura:")) v=3.14159*(r**2)*a Print("o volume é %.2v" %v)
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
930a55e8215ef0a4cfc15b384a633ce6e4cd1c62
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/Configuration/StandardSequences/python/HLTtable_cff.py
7dd24de2fc17c57d918a5b2fa30dc0a8a92cef42
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
Python
false
false
110
py
import FWCore.ParameterSet.Config as cms # # HLTrigger table # from Configuration.HLT.HLTtable_cff import *
[ "giulio.eulisse@gmail.com" ]
giulio.eulisse@gmail.com
97e0c17a95a962957c152e80ff839d72bcad99b9
a1b3b1f6719bd00acabf0e411ad55058447d2103
/commis/clients/search_indexes.py
0cb58ccc9fc9866485ab65b831c2b5ab51dacc56
[]
no_license
ageron/commis
8794005fe40e0aa0288fae53a41731d784a1edd3
a015c734e1d9bb98bf576d1bc2529eda75ac3711
refs/heads/master
2021-01-18T07:39:09.064166
2013-04-20T21:14:37
2013-04-20T21:14:37
9,499,256
3
0
null
null
null
null
UTF-8
Python
false
false
204
py
from haystack import site from commis.clients.models import Client from commis.search.indexes import CommisSearchIndex class ClientIndex(CommisSearchIndex): pass site.register(Client, ClientIndex)
[ "noah@coderanger.net" ]
noah@coderanger.net
fc7cf9499d22e579fec326ad1c1bb0dc17dd69c8
018a1d8d59c00f69b0489ce05567a2972c335ff7
/2017_May23/generators/use_logger.py
61d24cc930c5596fd8704acd8a2e45b02303a186
[]
no_license
singhujjwal/python
f0127b604e2204a02836c95d89ee4903f760d48c
4fb4b34a318f093bd944cd70d7f0d69dd7dfef6e
refs/heads/master
2021-09-20T15:35:13.389400
2021-09-03T06:39:58
2021-09-03T06:39:58
92,157,309
0
0
null
null
null
null
UTF-8
Python
false
false
283
py
from logger import log testlog = log("test.log", "test program") for l in testlog: testlog.send("this is a test message...") print "sent one log message..." testlog.send("this is another log message..") print "Sent another log message..." testlog.send(None)
[ "ujjsingh@cisco.com" ]
ujjsingh@cisco.com
28d2ccf22274d749ca637405de3be579954f8792
3e24611b7315b5ad588b2128570f1341b9c968e8
/estscan.py
2f748d2268d7e8c36e555456b414934f5a11b82f
[ "BSD-2-Clause" ]
permissive
bioCKO/lpp_Script
dc327be88c7d12243e25557f7da68d963917aa90
0cb2eedb48d4afa25abc2ed7231eb1fdd9baecc2
refs/heads/master
2022-02-27T12:35:05.979231
2019-08-27T05:56:33
2019-08-27T05:56:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,238
py
#!/usr/bin/env python #coding:utf-8 """ Author: --<> Purpose: Created: 2014/9/15 """ import urllib,urllib2,re, HTMLParser,time from lpp import * RAW = fasta_check(open(sys.argv[1],'rU')) def get_data(data,result): url = "http://myhits.isb-sib.ch/cgi-bin/estscan" values = { "species":"Drosophila_melanogaster.smat", "text":data, "action":"ESTScan", "indelpenalty":-50 } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) Data = response.read() all_need = re.findall("""<td class='desc_summary' valign='top'><input type='radio' name='seqname' value='([^\']+)'""",Data,re.MULTILINE) html_parse = HTMLParser.HTMLParser() END=open(result,'a') all_need = map(lambda x:html_parse.unescape(x), all_need) all_need = map(lambda x:re.sub('<[^>]+>','',x),all_need) #all_need = filter(lambda x:"' onclick='theForm.text.value=this.value;' />" in x, all_need) END.write('\n'.join(all_need) +'\n') num=0 cache = "" end = sys.argv[2] for t,s in RAW: num+=1 cache+=t+s if num%50==0: get_data(cache, end) cache = "" #time.sleep(1) else: get_data(cache, end)
[ "409511038@qq.com" ]
409511038@qq.com
9d61a90c8b910a3ff26bc2b1c5d5961defe17a67
e964a22925a510801ad6395ea087115aa4c86a2e
/trunk/zopen/frs/core/utils.py
0fa6cbfc785fcdf6964dd61846bd1b20639af69f
[]
no_license
BGCX261/zopen-frs-svn-to-git
7378590e975ecee9668ccbe884ecb0b4912bf963
c3725bb99e5ceb219a54e42a2bbfcc4613c8833c
refs/heads/master
2021-01-21T02:36:30.851387
2015-08-25T15:50:59
2015-08-25T15:50:59
41,602,270
0
0
null
null
null
null
UTF-8
Python
false
false
1,598
py
import time import os import shutil import socket from random import random from md5 import md5 from config import FS_CHARSET from types import UnicodeType def timetag(the_time=None): if the_time is None: # use gmt time the_time = time.gmtime() return time.strftime('%Y-%m-%d-%H-%M-%S', the_time) else: return the_time.strftime('%Y-%m-%d-%H-%M-%S') def ucopy2(ossrc, osdst): # ucopy2 dosn't work with unicode filename yet if type(osdst) is UnicodeType and \ not os.path.supports_unicode_filenames: ossrc = ossrc.encode(FS_CHARSET) osdst = osdst.encode(FS_CHARSET) shutil.copy2(ossrc, osdst) def ucopytree(ossrc, osdst, symlinks=False): # ucopy2 dosn't work with unicode filename yet if type(osdst) is UnicodeType and \ not os.path.supports_unicode_filenames: ossrc = ossrc.encode(FS_CHARSET) osdst = osdst.encode(FS_CHARSET) shutil.copytree(ossrc, osdst, symlinks) def umove(ossrc, osdst): # umove dosn't work with unicode filename yet if type(osdst) is UnicodeType and \ not os.path.supports_unicode_filenames: ossrc = ossrc.encode(FS_CHARSET) osdst = osdst.encode(FS_CHARSET) shutil.move(ossrc, osdst) try: _v_network = str(socket.gethostbyname(socket.gethostname())) except: _v_network = str(random() * 100000000000000000L) def make_uuid(*args): t = str(time.time() * 1000L) r = str(random()*100000000000000000L) data = t +' '+ r +' '+ _v_network +' '+ str(args) uid = md5(data).hexdigest() return uid
[ "you@example.com" ]
you@example.com
3614b185bb6e6f16c39bfc81b77b9c9817f4f4cc
50a690ab7db8fe98a620f3c54aabd90c3ff3e7f3
/utils/nms_processor.py
8124388141a5df4f982118d5c8c9d8c353cd05ff
[]
no_license
yekeren/ADVISE-Image_ads_understanding
590754909d2f4259a57d32591a15bea845586a0f
2ea5e1405b1ab178b95f9c2cd9158b16847ac6a3
refs/heads/master
2021-10-02T08:01:29.193553
2018-11-29T16:32:25
2018-11-29T16:32:25
103,291,233
22
8
null
null
null
null
UTF-8
Python
false
false
1,362
py
import numpy as np import tensorflow as tf class NMSProcessor(object): """Helper class that process non maximum suppression on single image.""" def __init__(self, max_output_size, iou_threshold): """Init. Args: max_output_size: maximum number of boxes to maintain. iou_threshold: threhold for intersection over union. """ config = tf.ConfigProto() config.allow_soft_placement = True config.gpu_options.allow_growth = True config.gpu_options.per_process_gpu_memory_fraction = 0.5 self._sess = tf.Session(config=config) self._boxes = tf.placeholder(dtype=tf.float32, shape=[None, 4]) self._scores= tf.placeholder(dtype=tf.float32, shape=[None]) self._selected = tf.image.non_max_suppression( self._boxes, self._scores, max_output_size, iou_threshold) self._selected_boxes = tf.gather(self._boxes, self._selected) self._selected_scores = tf.gather(self._scores, self._selected) def process(self, boxes, scores): """Process non maximum suppression. Args: boxes: a [num_boxes, 4] np array. scores: a [num_boxes] np array. Returns: selected_boxes: a [num_selected_boxes, 4] np array. """ return self._sess.run([ self._selected, self._selected_boxes, self._selected_scores], feed_dict={self._boxes: boxes, self._scores: scores})
[ "yekeren.cn@gmail.com" ]
yekeren.cn@gmail.com
6556a57d0ecd1abdbfaa6ae76e58c383a5bacafe
a7d1030cb797b862b87ee3e8b8a206814d26eee2
/videoburnsubtitles
fa680dc836bf1c6fdd587e2e7baf42a4026708b0
[]
no_license
lmanul/sak
8bdf98d2e463f3e171aa79b82557cd4d6ade2724
37604f1d0dc61373bd24d73d742afe9c754e62a3
refs/heads/master
2023-08-30T07:51:04.727676
2023-08-27T06:09:46
2023-08-27T06:09:46
144,207,029
6
0
null
null
null
null
UTF-8
Python
false
false
361
#!/usr/bin/python3 import os import sys if __name__ == "__main__": movie = sys.argv[1] subs = sys.argv[2] dot_index = movie.rfind(".") out = movie[:dot_index] + "_burned" + movie[dot_index:] cmd = ("ffmpeg " "-i " + movie + " " "-vf subtitles=" + subs + " " "" + out) # print(cmd) os.system(cmd)
[ "m@ma.nu" ]
m@ma.nu
ed60ac1ec198440fffd89e7dee7b91d152ca163a
312a8fde11293cb142334a3860966ec1f75ac401
/api_client/python/timesketch_api_client/definitions.py
ad793b16a8572fc5bdd6f98a893f3a6dbe3c0a90
[ "Apache-2.0" ]
permissive
google/timesketch
f0fd09062a8a24bac581d2d4286d095d667d2f10
24f471b58ca4a87cb053961b5f05c07a544ca7b8
refs/heads/master
2023-08-31T21:48:19.602686
2023-08-31T11:24:17
2023-08-31T11:24:17
21,009,909
2,263
647
Apache-2.0
2023-09-14T14:08:07
2014-06-19T17:49:45
Python
UTF-8
Python
false
false
1,034
py
# Copyright 2017 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Timesketch API client definitions.""" # HTTP status codes HTTP_STATUS_CODE_OK = 200 HTTP_STATUS_CODE_CREATED = 201 HTTP_STATUS_CODE_REDIRECT = 302 HTTP_STATUS_CODE_BAD_REQUEST = 400 HTTP_STATUS_CODE_UNAUTHORIZED = 401 HTTP_STATUS_CODE_FORBIDDEN = 403 HTTP_STATUS_CODE_NOT_FOUND = 404 HTTP_STATUS_CODE_CONFLICT = 409 # Convenient buckets of return code families HTTP_STATUS_CODE_20X = [HTTP_STATUS_CODE_OK, HTTP_STATUS_CODE_CREATED]
[ "jberggren@gmail.com" ]
jberggren@gmail.com
7ddfb5530fce7faf50eb533dbce56928fbd1c9a8
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/cv5vRuexCzi4hvxdd_23.py
130aa8cd3bbc2ef6f359e7cfdcaa101194cf122b
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
488
py
album_dict = { 2015: ("Vulnicura", "Honeymoon", "Rebel Heart"), 2016: ("Lemonade", "Blackstar", "A Moon Shaped Pool"), 2017: ("Flower Boy", "Antisocialites"), 2018: ("El Mal Querer", "Someone Out There", "Cranberry", "Kamikaze"), 2019: ("thank u next", "Magdalene", "Ode to Joy"), 2020: ("Rough and Rowdy Ways", "folklore", "Future Nostalgia", "Colores") } ​ def release_year(album): for x in album_dict: if album in album_dict[x]: return x return "Unknown"
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
9e0822d195db12a6bbb6b3dd8b8b7894393db4a2
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/jyqcRv6giw8an8KB2_5.py
a8a86f9a8f6080eb0eb6969b0fcbdd4eb506f060
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
95
py
def invert(s): return "".join([i.lower() if i.isupper() else i.upper() for i in s ][::-1])
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
6705d40d4a43c95cf4a27e239b0b1391997ae24a
4df39792fa9ab392e4d89d8a038fe94a69d18520
/bin/multip.py
2398c733fe5641fe07749bd4b92e76fc68a486a6
[ "MIT" ]
permissive
ddierschow/bamca
85f36882b229c2d0c75b61ee5c18faca57561fd9
fc2efd62d6852113c4d053695f22c7b71b9eafe6
refs/heads/master
2023-03-10T19:24:53.194490
2023-02-26T02:02:33
2023-02-26T02:05:45
20,793,784
4
0
null
null
null
null
UTF-8
Python
false
false
20,316
py
#!/usr/local/bin/python import glob import os import basics import config import mbdata import models import render import useful # --------------------------------------------------------------------- # columns, colspan, rowspan, picsize # columns MUST NOT exceed 4! # picsize MUST NOT exceed h! # colspan must be <= columns! pack_layout_keys = ['columns', 'colspan', 'rowspan', 'picsize'] pack_layouts = { '01s': [1, 1, 1, 'h'], '02h': [2, 2, 1, 'h'], '02v': [2, 1, 2, 'l'], '03h': [3, 3, 1, 'h'], '03v': [2, 1, 3, 'm'], '04h': [4, 4, 1, 'h'], '04v': [2, 1, 4, 'm'], '05h': [4, 3, 1, 'l'], '05l': [2, 1, 3, 'l'], '05s': [3, 2, 2, 'l'], '05v': [2, 1, 5, 'm'], '06h': [3, 3, 1, 'h'], '06s': [3, 2, 3, 'l'], '06v': [2, 1, 4, 'm'], '07s': [4, 3, 3, 'l'], '08h': [4, 4, 1, 'h'], '08s': [3, 2, 2, 'l'], '08v': [4, 3, 4, 'm'], '09h': [3, 3, 1, 'h'], '10h': [4, 3, 2, 'l'], '10v': [3, 2, 4, 'm'], '20h': [4, 4, 1, 'h'], } # ---- pack list ------------------------------------------------------ def make_pack_list(pif, format_type, sec='', year='', region='', lid='', material='', verbose=False): # need to adapt this for id-var pif.render.set_button_comment(pif) years = set() regions = set() has_note = False title = pif.form.search('title') sections = pif.dbh.fetch_sections({'page_id': pif.page_id}) pack_ids_found = [] llineup = render.Listix() sec_id = sec if sec else sections[0]['id'] if sections else '5packs' num_mods = 2 if sec_id == '2packs' else 10 if sec_id == '10packs' else 5 for lsection in sections: if sec and lsection['id'] != sec: continue lsec = render.Section(section=lsection) packs = pif.dbh.depref(['base_id', 'pack'], pif.dbh.fetch_packs(page_id=pif.page_id)) cols = ['pic', 'name', 'year', 'product_code', 'material'] heads = ['', 'Name', 'Year', 'Product Code', 'Material'] if verbose: cols = ['edlink'] + cols + ['region', 'country', 'layout', 'thumb', 'stars', 'rel'] heads = ['Pack ID'] + heads + ['Rg', 'Cy', 'Ly', 'Th', 'Models', 'Related'] elif lsection['flags'] & config.FLAG_SECTION_SHOW_IDS: cols = ['id'] + cols + ['regionname'] heads = ['ID'] + heads + ['Region'] else: cols += ['regionname'] heads += ['Region'] cols += ['note'] heads += ['Note'] heads = dict(zip(cols, heads)) entries = list() for pack in packs: pack['longid'] = pack['id'] + ('-' + pack['var'] if pack['var'] else '') if pack['section_id'] == lsection['id']: if not verbose and pack['id'] in pack_ids_found: continue pack_ids_found.append(pack['id']) years.add(pack['first_year']) regions.add(pack['region']) pack['name'] = pack['rawname'].replace(';', ' ') if ((year and (year < pack['first_year'] or year > pack['end_year'])) or (region and region != pack['region']) or (lid and not pack['id'].startswith(lid)) or (material and pack['material'] != material) or not useful.search_match(title, pack['name'])): continue pack['year'] = ((pack['first_year'] + '-' + pack['end_year']) if (pack['end_year'] and pack['end_year'] != pack['first_year']) else pack['first_year']) pack['layout'] = (pack['layout'] if pack['layout'] in pack_layouts else '<font color="red">%s</font>' % pack['layout']) pack['page'] = pif.form.get_str('page') pack['regionname'] = mbdata.regions[pack['region']] pack['name'] = '<a href="?page=%(page)s&id=%(id)s">%(name)s</a>' % pack pack['pic'] = mbdata.comment_icon.get('c') if imgsizes( pif, pif.render.pic_dir, pack['id'].lower()) else '' pack['material'] = mbdata.materials.get(pack['material'], '') has_note = has_note or bool(pack['note']) if verbose: modify_pack_admin(pif, pack) entries.append(pack) if not entries and not pif.is_allowed('a'): continue entries.sort(key=lambda x: (x[pif.form.get_str('order', 'name')], x['name'], x['first_year'])) if pif.is_allowed('a'): # pragma: no cover if format_type == 'packs': lsec.name += ' ' + pif.render.format_button_link( 'see', "packs.cgi?page=%s&sec=%s" % (pif.form.get_str('page'), lsec.id)) lsec.name += ' ' + pif.render.format_button_link( 'add', "mass.cgi?tymass=pack&section_id=%s&num=%s" % (lsec.id, num_mods)) lsec.colist = cols lsec.headers = heads lsec.range = [render.Range(entry=entries, note='', styles=dict(zip(cols, cols)))] lsec.note = '' llineup.section.append(lsec) context = { 'page_id': pif.page_id, 'years': sorted(years), 'regions': [(x, mbdata.regions[x]) for x in sorted(regions)], 'llineup': llineup.prep(), 'section_id': sec_id, 'num': num_mods, # 'lid': calc_pack_select(pif, packs), } return pif.render.format_template('packlist.html', **context) def modify_pack_admin(pif, pack): pmodels = distill_models(pif, pack, pif.page_id) stars = '' for mod in sorted(pmodels.keys()): if not pmodels[mod].get('id'): stars += '<i class="fas fa-star green"></i> ' elif not pmodels[mod].get('vs.var_id'): stars += '<i class="fas fa-star red"></i> ' elif pmodels[mod]['imgstr'].find('-') < 0: stars += '<i class="fas fa-star yellow"></i> ' else: stars += '<i class="fas fa-star black"></i> ' pack['stars'] = stars pack['edlink'] = ( '<a href="mass.cgi?verbose=1&tymass=pack&section_id=%(section_id)s&pack=%(id)s&var=%(var)s&num=">%(longid)s</a>' % pack) relateds = pif.dbh.fetch_packs_related(pack['id']) pack['rel'] = ' '.join(sorted([x['pack.id'] for x in relateds])) # ---- single pack ---------------------------------------------------- def do_single_pack(pif, format_type, pid): pack = dict() packs = pif.dbh.fetch_pack(pid) if not packs: raise useful.SimpleError("That %s doesn't seem to exist." % ('pack' if format_type == 'packs' else 'playset')) pif.render.hierarchy_append('', packs[0]['base_id.rawname'].replace(';', ' ')) pif.render.print_html() llineup = render.Matrix(tail=['']) for pack in packs: pack_id = pack['pack.id'] page_id = pack['pack.page_id'] pack['longid'] = pack_id + ('-' + pack['pack.var'] if pack['pack.var'] else '') db_relateds = pif.dbh.fetch_packs_related(pack_id) relateds = [ { 'link': pif.render.format_link("?page=" + pif.form.get_str('page') + "&id=" + r['pack.id'], r['base_id.rawname'].replace(';', ' ')), 'product_code': r['pack.product_code'], 'region': mbdata.regions.get(r['pack.region'], ''), 'country': mbdata.get_country(r['pack.country']), 'material': mbdata.materials.get(r['pack.material'], ''), 'description': r['base_id.description'], } for r in db_relateds ] tcomments = set() pack.update({key[key.find('.') + 1:]: pack[key] for key in pack}) pack['name'] = pack['rawname'].replace(';', ' ') pmodels = distill_models(pif, pack, pack['page_id']) if pack['layout'].isdigit() and len(pack['layout']) == 4: layout = [int(x) for x in pack['layout'][:3]] + pack['layout'][3:] elif not pmodels: layout = pack_layouts['01s'] else: layout = pack_layouts.get(pack['layout'], pack_layouts['04h']) if len(layout) == 2: layout[3] = 1 if len(layout) == 3: layout[4] = 4 - (layout[0] - layout[1]) pif.render.comment('pack:', pack) entries = [render.Entry( text=show_pack(pif, pack, layout[3]), class_name='width_' + layout[3], display_id='0', colspan=layout[1], rowspan=layout[2])] for mod in sorted(pmodels.keys()): pif.render.comment("do_single_pack mod", pmodels[mod]) if not pmodels[mod].get('id'): pmodels[mod]['no_casting'] = 1 tcomments.add('m') else: if pmodels[mod]['imgstr'].find('-') < 0: tcomments.add('i') if not pmodels[mod].get('vs.var_id'): pmodels[mod]['no_variation'] = 1 tcomments.add('v') entries.append(render.Entry(text=show_pack_model(pif, pmodels[mod]), display_id=1)) llineup.section.append(render.Section(id='', columns=layout[0], anchor=pack['id'], range=[render.Range(entry=entries)])) # left bar left_bar_content = '' if pif.is_allowed('a'): # pragma: no cover left_bar_content += f'<br><center>{page_id}/{pack_id}<p>' left_bar_content += ('<p><b><a href="%s">Base ID</a></b><br>\n' % pif.dbh.get_editor_link('base_id', {'id': pack_id})) left_bar_content += '<b><a href="%s">Pack</a></b><br>\n' % pif.dbh.get_editor_link('pack', {'id': pack_id}) left_bar_content += ('<b><a href="traverse.cgi?d=.%s">Library</a></b><br>\n' % pif.render.pic_dir.replace('/pic/', '/lib/')) left_bar_content += ( '<b><a href="mass.cgi?verbose=1&tymass=pack&section_id=%s&pack=%s&num=">Edit</a></b><br>\n' % (packs[0]['section_id'], pack_id)) left_bar_content += ('<b><a href="upload.cgi?d=./%s&n=%s">Package</a><br>\n' % (pif.render.pic_dir.replace('pic', 'lib'), pack_id)) left_bar_content += ('<b><a href="upload.cgi?d=./%s&n=%s">Contents</a><br>\n' % (pif.render.pic_dir.replace('prod', 'set').replace('pic', 'lib'), pack_id)) left_bar_content += '</center>\n' pif.render.set_button_comment(pif, 'd=%s' % pif.form.get_str('id')) context = { 'title': packs[0]['name'], 'note': packs[0]['note'], 'type_id': 'p_' + packs[0]['section_id'], 'icon_id': '', # pack_id, 'vehicle_type': '', 'rowspan': 4, 'left_bar_content': left_bar_content, 'llineup': llineup.prep(), 'relateds': relateds, } return pif.render.format_template('pack.html', **context) def imgsizes(pif, pdir, pic_id): sizes_found = [] for imgsize in mbdata.image_size_types: if (glob.glob(os.path.join(pdir, imgsize + '_' + pic_id + '.jpg')) or glob.glob(os.path.join(pdir, imgsize + '_' + pic_id + '-*.jpg'))): sizes_found.append(imgsize.upper()) return ' '.join(sizes_found) def distill_models(pif, pack, page_id): pack_id = pack['id'] + ('-' + pack['var'] if pack['var'] else '') model_list = pif.dbh.fetch_pack_models(pack_id=pack['id'], pack_var=pack['var'], page_id=page_id) pack['pic'] = '' # for pic in glob.glob(os.path.join(config.IMG_DIR_PROD_PACK, '?_' + pack_id + '.jpg')): # path, pic = pif.render.find_image_file(pack_id, pdir=config.IMG_DIR_PROD_PACK, largest=mbdata.IMG_SIZ_HUGE) # pack['pic'] += imglib.format_image_star(pif, path, pic) pack['pic'] += imgsizes(pif, pif.render.pic_dir, pack_id.lower()) linmod = pif.dbh.fetch_lineup_model(where="mod_id='%s'" % pack_id) pack['thumb'] = '<i class="far fa-%s"></i>' % ('check-square' if linmod else 'square') if ''.join(pif.render.find_image_file(pack_id, pdir=config.IMG_DIR_MAN, prefix=mbdata.IMG_SIZ_SMALL)): pack['thumb'] += '<i class="fas fa-star"></i>' pmodels = {} for mod in model_list: mod = pif.dbh.modify_man_item(mod) mod['pdir'] = pif.render.pic_dir mod['spdir'] = mbdata.dirs.inverse.get(mod['pdir'], mod['pdir']) sec_ids = ['.', '', pack_id + '.', pack_id + '.' + str(mod['pack_model.display_order'])] if (mod['vs.sec_id'] or '') + '.' + (mod['vs.ran_id'] or '') in sec_ids: mod['imgl'] = [mbdata.IMG_SIZ_SMALL + '_' + mod['id'], mod['id'], mod['pack_model.mod_id']] for s in mod['descs']: if s.startswith('same as '): mod['imgl'].extend([mbdata.IMG_SIZ_SMALL + '_' + s[8:], s[8:]]) if not mod.get('vs.ref_id'): mod['vs.ref_id'] = '' if not mod.get('vs.sec_id'): mod['vs.sec_id'] = '' mod['pic_id'] = mod['vs.sec_id'] if mod['vs.sec_id'] else mod['pack_model.pack_id'] if mod['pack_model.mod_id'] != 'unknown': mod['href'] = ( "single.cgi?id=%(pack_model.mod_id)s&dir=%(spdir)s&pic=%(pic_id)s&ref=%(vs.ref_id)s&" "sec=%(vs.sec_id)s&ran=%(vs.ran_id)s" % mod) # '<a href="single.cgi?dir=%(dir)s&pic=%(link)s&ref=%(vs.ref_id)s&id=%(mod_id)s">' % ent # 'pack_model.pack_id': 'car02', # if mod['pack_model.var'] and mod['imgl']: # still not perfect # mod['href'] = mod['href'] + '&pic=' + mod['imgl'][mod['imgl'].rfind('/') + 1:-2] mod['vars'] = [] mod['pics'] = [] if not mod['pack_model.display_order'] in pmodels: pmodels[mod['pack_model.display_order']] = mod if mod['v.picture_id']: pmodels[mod['pack_model.display_order']]['pics'].append(mod['v.picture_id']) else: pmodels[mod['pack_model.display_order']]['pics'].append(mod['vs.var_id']) if mod.get('vs.var_id'): pmodels[mod['pack_model.display_order']]['vars'].append(mod['vs.var_id']) for dispo in pmodels: pmodels[dispo]['imgstr'] = pif.render.format_image_required( pmodels[dispo]['imgl'], pdir=config.IMG_DIR_MAN, prefix=mbdata.IMG_SIZ_SMALL, vars=pmodels[dispo].get('pics')) return pmodels # columns (id, page_id, section_id, name, first_year, end_year, region, layout, product_code, material, country) def show_pack(pif, pack, picsize): pack_id = pack['id'] + ('-' + pack['var'] if pack['var'] else '') prod_credit = pif.dbh.fetch_photo_credit(pif.render.pic_dir, pack_id, verbose=True) pack['credit'] = prod_credit['photographer.name'] if prod_credit else '' prod_pic = pif.render.find_image_path(pack_id, largest=picsize) cont_dir = pif.render.pic_dir.replace('prod', 'set') # cont_credit = pif.dbh.fetch_photo_credit(cont_dir, pack_id, verbose=True) # pack['credit'] = cont_credit['photographer.name'] if cont_credit else '' cont_pic = pif.render.find_image_path(pack_id, largest=picsize, pdir=cont_dir) pics = [] if prod_pic: ostr = prod_pic pics.append(prod_pic) if cont_pic: ostr = cont_pic pics.append(cont_pic) ostr = pif.render.format_image_selector(pics, 'ps') + '<br>' ostr += pif.render.format_image_selectable(pics, 'ps') if pack['credit']: ostr += '<div class="credit">Photo credit: %s</div>' % pack['credit'] # Ideally this would come from section.flags but we don't have that here. # So this is a giant FAKE OUT if pack['var']: ostr = '<b>' + pack['id'] + '-' + pack['var'] + '</b><br>' + ostr year = pack['first_year'] if pack['first_year'] else '' if pack['first_year'] and pack['end_year'] and pack['end_year'] != pack['first_year']: year += '-' + pack['end_year'] prod_title = [pack['base_id.rawname']] if year: prod_title.append(year) ostr += '<h4 class="prodtitle">{}</h4>'.format(' - '.join(prod_title)) pack['country'] = mbdata.get_country(pack['country']) pack['material'] = mbdata.materials.get(pack['material'], '') if pack['product_code']: ostr += pack['product_code'] + '<br>' if pack['region']: ostr += mbdata.regions[pack['region']] + '<br>' ostr += '<p>' if pack['first_year'] and pack['end_year'] and pack['end_year'] != pack['first_year']: ostr += '<b>%(first_year)s-%(end_year)s</b><br>' % pack dets = filter(None, [pack['country'], pack['material']]) ostr += ' - '.join(dets) return '<center>' + ostr + '</center>' # mdict: descriptions href imgstr name no_casting not_made number pdir picture_only product subname # def add_model_table_product_link(pif, mdict): def show_pack_model(pif, mdict): pif.render.comment("show_pack_model", mdict) mdict['number'] = '' mdict['descriptions'] = [] if mdict['v.text_description']: mdict['descriptions'] = [mdict['v.text_description']] # fix this mdict['product'] = '' if mdict['imgstr'].find('-') < 0: mdict['no_specific_image'] = 1 desclist = list() for var in mdict.get('descriptions', []): if var and var not in desclist: desclist.append(var) mdict['descriptions'] = desclist if not mdict.get('disp_format') or not mdict.get('shown_id'): mdict['displayed_id'] = '&nbsp;' else: mdict['displayed_id'] = mdict['disp_format'] % (mdict['shown_id']) return models.add_model_table_product_link(pif, mdict) # ---- main ----------------------------------------------------------- @basics.web_page def packs_main(pif): def fmt_link(sec): return pif.render.format_link( '?sec=' + sec.id, models.add_icons(pif, 'p_' + sec.id, '', '') + '<center>' + sec.name + '</center>') pif.render.set_page_extra(pif.render.image_selector_js) pif.render.hierarchy_append('/', 'Home') pif.render.hierarchy_append('/database.php', 'Database') pif.render.hierarchy_append('packs.cgi', 'Multi-Model Packs') if pif.form.has('id'): pif.render.hide_title = True pif.form.set_val('id', pif.form.get_list('id')[0]) # with no id this blows pid = useful.clean_id(pif.form.get_str('id')) return do_single_pack(pif, 'packs', pid) elif pif.form.has('page'): pif.render.print_html() return make_pack_list( pif, 'packs', verbose=pif.is_allowed('m') and pif.form.get_int('verbose'), **pif.form.get_dict(['sec', 'year', 'region', 'lid', 'material'])) elif pif.form.has('sec'): pif.render.hide_title = True # useful.write_comment(pif.form) sections = pif.dbh.fetch_sections_by_page_type('packs', pif.form.get_str('sec')) if not sections: pif.render.print_html() return models.make_page_list(pif, 'packs', fmt_link) pif.page_id = sections[0].page_info.id pif.render.print_html() return make_pack_list( pif, 'packs', verbose=pif.is_allowed('m') and pif.form.get_int('verbose'), **pif.form.get_dict(['sec', 'year', 'region', 'lid', 'material'])) pif.render.print_html() return models.make_page_list(pif, 'packs', fmt_link) # ---- play ---------------------------------- @basics.web_page def play_main(pif): pif.render.set_page_extra(pif.render.image_selector_js) # useful.write_comment(pif.form) pif.page_id = 'playset.ps' pif.set_page_info(pif.page_id) pif.render.print_html() pif.render.hierarchy_append('/', 'Home') pif.render.hierarchy_append('/database.php', 'Database') pif.render.hierarchy_append('play.cgi', 'Playsets') if pif.form.has('id'): pif.form.set_val('id', pif.form.get_list('id')[0]) # with no id this blows pid = useful.clean_id(pif.form.get_str('id')) return do_single_pack(pif, 'playset', pid) return make_pack_list(pif, 'playset', verbose=pif.is_allowed('m') and pif.form.get_int('verbose'), **pif.form.get_dict(['sec', 'year', 'region']))
[ "ddierschow@xocolatl.com" ]
ddierschow@xocolatl.com
78af297cc1a99dc9da70c9593add3529febc2163
f9d564f1aa83eca45872dab7fbaa26dd48210d08
/huaweicloud-sdk-codeartsdeploy/huaweicloudsdkcodeartsdeploy/v2/model/delete_deployment_group_request.py
19ce924355b8177a16f4bd1910979b60892d4fa0
[ "Apache-2.0" ]
permissive
huaweicloud/huaweicloud-sdk-python-v3
cde6d849ce5b1de05ac5ebfd6153f27803837d84
f69344c1dadb79067746ddf9bfde4bddc18d5ecf
refs/heads/master
2023-09-01T19:29:43.013318
2023-08-31T08:28:59
2023-08-31T08:28:59
262,207,814
103
44
NOASSERTION
2023-06-22T14:50:48
2020-05-08T02:28:43
Python
UTF-8
Python
false
false
3,106
py
# coding: utf-8 import six from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class DeleteDeploymentGroupRequest: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'group_id': 'str' } attribute_map = { 'group_id': 'group_id' } def __init__(self, group_id=None): """DeleteDeploymentGroupRequest The model defined in huaweicloud sdk :param group_id: 主机集群id :type group_id: str """ self._group_id = None self.discriminator = None self.group_id = group_id @property def group_id(self): """Gets the group_id of this DeleteDeploymentGroupRequest. 主机集群id :return: The group_id of this DeleteDeploymentGroupRequest. :rtype: str """ return self._group_id @group_id.setter def group_id(self, group_id): """Sets the group_id of this DeleteDeploymentGroupRequest. 主机集群id :param group_id: The group_id of this DeleteDeploymentGroupRequest. :type group_id: str """ self._group_id = group_id def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): """For `print`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, DeleteDeploymentGroupRequest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "hwcloudsdk@huawei.com" ]
hwcloudsdk@huawei.com
1530cf27ee08c2d4ffb6f4f98eb94712de8edc18
f1e3817c280557878c682bb92e1900d61de2d65d
/web_transbank_1/BACKEND/project/commerce/migrations/0002_categoria_imagen_producto.py
5408c0dc5f9a58966048aa6eee9c2937d98dc397
[]
no_license
netluxspa/web-transbank
f2f8099fef22883717ca76fc3aaaa7e3e52f91d4
bf9b743863d45103d48c19245832627b04b07108
refs/heads/master
2023-06-26T21:52:15.113911
2021-07-26T21:20:21
2021-07-26T21:20:21
363,288,390
0
0
null
null
null
null
UTF-8
Python
false
false
1,630
py
# Generated by Django 3.2 on 2021-04-26 23:06 import commerce.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('commerce', '0001_initial'), ] operations = [ migrations.CreateModel( name='Categoria', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('titulo', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='Imagen', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('imagen', models.ImageField(upload_to=commerce.models.scramble_uploaded_filename)), ('descripcion', models.CharField(blank=True, max_length=50, null=True)), ('prioridad', models.IntegerField(blank=True, null=True)), ], options={ 'ordering': ('prioridad',), }, ), migrations.CreateModel( name='Producto', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('titulo', models.CharField(max_length=50)), ('categoria', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='commerce.categoria')), ('imagenes', models.ManyToManyField(blank=True, to='commerce.Imagen')), ], ), ]
[ "netluxspa@gmail.com" ]
netluxspa@gmail.com
eeccb59ddb3e905bd4d10a2eb35ada77ac381c05
d9eef8dd3489682c8db41f2311e3058d1f369780
/.history/abel-network-files/mcmc_alg_implementation_own_two_20180630104728.py
576fd8873c53eb04f34d5536bd010e45f8a24b5c
[]
no_license
McKenzie-Lamb/Gerrymandering
93fe4a49fe39a0b307ed341e46ba8620ea1225be
b7a7c4129d6b0fcd760ba8952de51eafa701eac3
refs/heads/master
2021-01-25T06:06:43.824339
2018-10-16T14:27:01
2018-10-16T14:27:01
93,526,515
0
0
null
2018-07-12T19:07:35
2017-06-06T14:17:47
Python
UTF-8
Python
false
false
4,187
py
# Author: Abel Gonzalez # Date: 06/26/18 # # Description: # This program uses the .shp file to create a network graph where each node # represents a census tract and the edge represents adjacency between each # tract, usign graph-tool instead of networkx import random import numpy as np import graph_tool.all as gt from pathlib import Path def create_graph_views(district_total_no): graph_views = list() for i in range(district_total_no): main_graph_view = gt.GraphView(graph) graph_view_check = main_graph_view.new_vertex_property("bool") matched_vertices = gt.find_vertex(graph, district_no, i) for j in matched_vertices: graph_view_check[j] = True graph_view = gt.GraphView(main_graph_view, vfilt=graph_view_check) graph_views.append(graph_view) return graph_views def turn_off_edges(districts_graphs): turned_off_graphs = list() # Iterate through districts and selects random edges for district in range(len(districts_graphs)): to_delete = districts_graphs[district].new_edge_property('bool') edges = districts_graphs[district].get_edges() selected = edges[np.random.randint(edges.shape[0], size = len(edges)//3.5), :] for i in selected: to_delete[i] = True turned_off_graphs.append(gt.GraphView(districts_graphs[district], efilt=to_delete)) return turned_off_graphs def get_cp_boundaries(graph, turned_on_graphs): cp_boundary = list() for g in range(len(turned_on_graphs)): cp_label, hist = gt.label_components(turned_on_graphs[g]) labels = set(cp_label.a) for l in labels: cp = gt.find_vertex(turned_on_graphs[g], cp_label, l) label_boun = 0 for v in cp: vertex_bound = False for n in graph.vertex(v).all_neighbors(): for g_two in range(len(turned_on_graphs)): if g == g_two: continue try: turned_on_graphs[g_two].vertex(n) except ValueError: continue else: vertex_bound = True break if vertex_bound == True: label_boun += 1 break if label_boun == len(cp): cp_boundary.append(cp) return cp_boundary # Paths main_folder = Path("abel-network-files/") data_folder = Path("abel-network-files/data/") images_folder = Path("abel-network-files/images/") # Loading the previous created Graph and creating the prop maps graph = gt.load_graph(str(data_folder / "tmp_graph.gt")) color = graph.new_vertex_property("vector<double>") ring_color = graph.new_vertex_property("vector<double>") cp_label = graph.new_vertex_property("int") # Init variables district_total_no = 2 gt.graph_draw(graph, pos=graph.vp.pos, output=str(main_folder / ('tmp.png')), bg_color=(255, 255, 255, 1), vertex_text=graph.vertex_index) # Separates graph into blocks districts = gt.minimize_blockmodel_dl(graph, district_total_no, district_total_no) district_no = districts.get_blocks() districts.draw(output='tmp.png', vertex_text=graph.vertex_index) # Create the different graphs districts_graphs = create_graph_views(district_total_no) for i in range(len(districts_graphs)): gt.graph_draw( districts_graphs[i], pos=graph.vp.pos, output=str(main_folder / ('tmp'+str(i)+'.png')), bg_color=(255, 255, 255, 1)) turned_on_graphs = turn_off_edges(districts_graphs) for i in range(len(districts_graphs)): gt.graph_draw( turned_on_graphs[i], pos=graph.vp.pos,bg_color=(255,255,255,1),vertex_size=2, output=str(main_folder / ('tmp1'+str(i)+'.png')), vertex_text=graph.vertex_index) labels_in_boundaries = get_cp_boundaries(graph, turned_on_graphs) print(len(labels_in_boundaries)) slected_vertices = random.choice(labels_in_boundaries, k = 3) print(len(slected_vertices))
[ "gonzaleza@ripon.edu" ]
gonzaleza@ripon.edu
23697655f0b003d48049aee403c5081f30a2e48b
1109d81ac29335d7063557ee6d5bd2d9bda7a8d4
/chap06_Regression/exams/linear_regression_exam.py
855fbc53cfef92d1c318f3939acd731f1ea3346c
[]
no_license
yangmyongho/4_Python-II
68c3b6400cda2c614d40d96166ff42c92fee29e0
0f7e488e034a1dac0438ad5c16ed435d30498d47
refs/heads/master
2022-11-28T00:36:45.243930
2020-07-29T14:08:45
2020-07-29T14:08:45
283,514,268
0
0
null
null
null
null
UTF-8
Python
false
false
3,782
py
# -*- coding: utf-8 -*- """ 문) california 주택가격을 대상으로 다음과 같은 단계별로 선형회귀분석을 수행하시오. """ # california 주택가격 데이터셋 ''' 캘리포니아 주택 가격 데이터(회귀 분석용 예제 데이터) •타겟 변수 1990년 캘리포니아의 각 행정 구역 내 주택 가격의 중앙값 •특징 변수(8) MedInc : 행정 구역 내 소득의 중앙값 HouseAge : 행정 구역 내 주택 연식의 중앙값 AveRooms : 평균 방 갯수 AveBedrms : 평균 침실 갯수 Population : 행정 구역 내 인구 수 AveOccup : 평균 자가 비율 Latitude : 해당 행정 구역의 위도 Longitude : 해당 행정 구역의 경도 ''' from sklearn.datasets import fetch_california_housing # dataset load import pandas as pd # DataFrame 생성 from sklearn.linear_model import LinearRegression # model from sklearn.model_selection import train_test_split # dataset split from sklearn.metrics import mean_squared_error, r2_score # model 평가 import matplotlib.pyplot as plt import numpy as np # 캘리포니아 주택 가격 dataset load california = fetch_california_housing() print(california.DESCR) # 단계1 : 특징변수와 타켓변수(MEDV)를 이용하여 DataFrame 생성하기 california.feature_names # 타겟명들 DF = pd.DataFrame(california.data, columns=california.feature_names ) DF tg = pd.Series(california.target) # 집단변수 DF['MEDV'] = tg DF # 단계2 : 타켓변수와 가장 상관관계가 높은 특징변수 확인하기 cor = DF.corr() cor.loc['MEDV'] ''' MedInc 0.688075 HouseAge 0.105623 AveRooms 0.151948 AveBedrms -0.046701 Population -0.024650 AveOccup -0.023737 Latitude -0.144160 Longitude -0.045967 MEDV 1.000000 ''' # MedInc : 0.688075 # 단계3 : california 데이터셋을 대상으로 1만개 샘플링하여 서브셋 생성하기 ''' idx = np.random.choice(a=len(DF), size=10000) idx cal_data = DF.iloc[idx,:] cal_data.shape # (10000, 9) ''' cal_data = DF.sample(10000, random_state=123) # 단계4 : 75%(train) vs 25(test) 비율 데이터셋 split train, test = train_test_split(cal_data, random_state=123) train.shape # (7500, 9) test.shape #(2500, 9) # 단계5 : 선형회귀모델 생성 obj = LinearRegression() model = obj.fit(train.iloc[:, :8], train.loc[:,'MEDV']) model # 단계6 : 모델 검정(evaluation) : 예측력 검정, 과적합(overfitting) 확인 train_acc = model.score(train.iloc[:, :8], train.iloc[:, 8]) train_acc # 0.605786545196659 test_acc = model.score(test.iloc[:, :8], test.iloc[:, 8]) test_acc # 0.5885575812843817 # 해설 : 훈련셋과 검정셋 모두 비슷한 분류정확도가 나온다. -> 과적합 없다 # 단계7 : 모델 평가(test) # 조건1) 단계3의 서브셋 대상으로 30% 샘플링 자료 이용 # 조건2) 평가방법 : MSE, r2_score # df.sample() subset = cal_data.sample(3000, random_state=123) subset.shape # (3000, 9) x_train, x_test = train_test_split(subset) X = x_train.iloc[:, :8] Y = x_train.iloc[:, 8] X1 = x_test.iloc[:, :8] Y1 = x_test.iloc[:, 8] model2 = obj.fit(X, Y) model2 y_pred = model.predict(X1) y_true = Y1 MSE = mean_squared_error(y_true, y_pred) MSE # 0.5526871790284673 score = r2_score(y_true, y_pred) score # 0.5782616441222735 type(y_true) type(y_pred) y_true = np.array(y_true) # 단계8 : 예측치 100개 vs 정답 100개 비교 시각화 plt.plot(y_true[:100], color='b', label='real values') plt.plot(y_pred[:100], color='r', label='fitted values') plt.xlabel('index') plt.ylabel('fitted values') plt.legend(loc = 'best') plt.show()
[ "noreply@github.com" ]
yangmyongho.noreply@github.com
618110821f0afa8f222b5bb64e270724d37739ea
82b946da326148a3c1c1f687f96c0da165bb2c15
/sdk/python/pulumi_azure_native/network/v20191101/get_virtual_wan.py
03768969fdbeab5627a0cff53506f6281fc1e9ac
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
morrell/pulumi-azure-native
3916e978382366607f3df0a669f24cb16293ff5e
cd3ba4b9cb08c5e1df7674c1c71695b80e443f08
refs/heads/master
2023-06-20T19:37:05.414924
2021-07-19T20:57:53
2021-07-19T20:57:53
387,815,163
0
0
Apache-2.0
2021-07-20T14:18:29
2021-07-20T14:18:28
null
UTF-8
Python
false
false
8,538
py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs __all__ = [ 'GetVirtualWanResult', 'AwaitableGetVirtualWanResult', 'get_virtual_wan', ] @pulumi.output_type class GetVirtualWanResult: """ VirtualWAN Resource. """ def __init__(__self__, allow_branch_to_branch_traffic=None, allow_vnet_to_vnet_traffic=None, disable_vpn_encryption=None, etag=None, id=None, location=None, name=None, office365_local_breakout_category=None, provisioning_state=None, tags=None, type=None, virtual_hubs=None, vpn_sites=None): if allow_branch_to_branch_traffic and not isinstance(allow_branch_to_branch_traffic, bool): raise TypeError("Expected argument 'allow_branch_to_branch_traffic' to be a bool") pulumi.set(__self__, "allow_branch_to_branch_traffic", allow_branch_to_branch_traffic) if allow_vnet_to_vnet_traffic and not isinstance(allow_vnet_to_vnet_traffic, bool): raise TypeError("Expected argument 'allow_vnet_to_vnet_traffic' to be a bool") pulumi.set(__self__, "allow_vnet_to_vnet_traffic", allow_vnet_to_vnet_traffic) if disable_vpn_encryption and not isinstance(disable_vpn_encryption, bool): raise TypeError("Expected argument 'disable_vpn_encryption' to be a bool") pulumi.set(__self__, "disable_vpn_encryption", disable_vpn_encryption) if etag and not isinstance(etag, str): raise TypeError("Expected argument 'etag' to be a str") pulumi.set(__self__, "etag", etag) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if location and not isinstance(location, str): raise TypeError("Expected argument 'location' to be a str") pulumi.set(__self__, "location", location) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if office365_local_breakout_category and not isinstance(office365_local_breakout_category, str): raise TypeError("Expected argument 'office365_local_breakout_category' to be a str") pulumi.set(__self__, "office365_local_breakout_category", office365_local_breakout_category) if provisioning_state and not isinstance(provisioning_state, str): raise TypeError("Expected argument 'provisioning_state' to be a str") pulumi.set(__self__, "provisioning_state", provisioning_state) if tags and not isinstance(tags, dict): raise TypeError("Expected argument 'tags' to be a dict") pulumi.set(__self__, "tags", tags) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) if virtual_hubs and not isinstance(virtual_hubs, list): raise TypeError("Expected argument 'virtual_hubs' to be a list") pulumi.set(__self__, "virtual_hubs", virtual_hubs) if vpn_sites and not isinstance(vpn_sites, list): raise TypeError("Expected argument 'vpn_sites' to be a list") pulumi.set(__self__, "vpn_sites", vpn_sites) @property @pulumi.getter(name="allowBranchToBranchTraffic") def allow_branch_to_branch_traffic(self) -> Optional[bool]: """ True if branch to branch traffic is allowed. """ return pulumi.get(self, "allow_branch_to_branch_traffic") @property @pulumi.getter(name="allowVnetToVnetTraffic") def allow_vnet_to_vnet_traffic(self) -> Optional[bool]: """ True if Vnet to Vnet traffic is allowed. """ return pulumi.get(self, "allow_vnet_to_vnet_traffic") @property @pulumi.getter(name="disableVpnEncryption") def disable_vpn_encryption(self) -> Optional[bool]: """ Vpn encryption to be disabled or not. """ return pulumi.get(self, "disable_vpn_encryption") @property @pulumi.getter def etag(self) -> str: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def id(self) -> Optional[str]: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def location(self) -> str: """ Resource location. """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> str: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="office365LocalBreakoutCategory") def office365_local_breakout_category(self) -> str: """ The office local breakout category. """ return pulumi.get(self, "office365_local_breakout_category") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: """ The provisioning state of the virtual WAN resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def tags(self) -> Optional[Mapping[str, str]]: """ Resource tags. """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> str: """ Resource type. """ return pulumi.get(self, "type") @property @pulumi.getter(name="virtualHubs") def virtual_hubs(self) -> Sequence['outputs.SubResourceResponse']: """ List of VirtualHubs in the VirtualWAN. """ return pulumi.get(self, "virtual_hubs") @property @pulumi.getter(name="vpnSites") def vpn_sites(self) -> Sequence['outputs.SubResourceResponse']: """ List of VpnSites in the VirtualWAN. """ return pulumi.get(self, "vpn_sites") class AwaitableGetVirtualWanResult(GetVirtualWanResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetVirtualWanResult( allow_branch_to_branch_traffic=self.allow_branch_to_branch_traffic, allow_vnet_to_vnet_traffic=self.allow_vnet_to_vnet_traffic, disable_vpn_encryption=self.disable_vpn_encryption, etag=self.etag, id=self.id, location=self.location, name=self.name, office365_local_breakout_category=self.office365_local_breakout_category, provisioning_state=self.provisioning_state, tags=self.tags, type=self.type, virtual_hubs=self.virtual_hubs, vpn_sites=self.vpn_sites) def get_virtual_wan(resource_group_name: Optional[str] = None, virtual_wan_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetVirtualWanResult: """ VirtualWAN Resource. :param str resource_group_name: The resource group name of the VirtualWan. :param str virtual_wan_name: The name of the VirtualWAN being retrieved. """ __args__ = dict() __args__['resourceGroupName'] = resource_group_name __args__['virtualWANName'] = virtual_wan_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-native:network/v20191101:getVirtualWan', __args__, opts=opts, typ=GetVirtualWanResult).value return AwaitableGetVirtualWanResult( allow_branch_to_branch_traffic=__ret__.allow_branch_to_branch_traffic, allow_vnet_to_vnet_traffic=__ret__.allow_vnet_to_vnet_traffic, disable_vpn_encryption=__ret__.disable_vpn_encryption, etag=__ret__.etag, id=__ret__.id, location=__ret__.location, name=__ret__.name, office365_local_breakout_category=__ret__.office365_local_breakout_category, provisioning_state=__ret__.provisioning_state, tags=__ret__.tags, type=__ret__.type, virtual_hubs=__ret__.virtual_hubs, vpn_sites=__ret__.vpn_sites)
[ "noreply@github.com" ]
morrell.noreply@github.com
8faa8494916fc998c8fdb8e7c8ddef63790041ae
70589e7ed32fc1f70ee93a495170c1a5810ce584
/pip/_vendor/pkg_resources/__init__.py
bbceaac76c30f41440d306429fb47f12250f6c2e
[ "MIT" ]
permissive
ssbarnea/pip
e78244e5bb4403631f97d491412610e2051bdc58
d57336d466b1eddb272a58de94f1779b50a9c5ed
refs/heads/develop
2022-01-20T06:48:41.137455
2016-05-24T11:50:56
2016-05-24T11:50:56
57,436,240
0
0
null
2016-04-30T09:51:46
2016-04-30T09:51:44
null
UTF-8
Python
false
false
101,277
py
""" Package resource API -------------------- A resource is a logical file contained within a package, or a logical subdirectory thereof. The package resource API expects resource names to have their path parts separated with ``/``, *not* whatever the local path separator is. Do not use os.path operations to manipulate resource names being passed into the API. The package resource API is designed to work with normal filesystem packages, .egg files, and unpacked .egg files. It can also work in a limited way with .zip files and with custom PEP 302 loaders that support the ``get_data()`` method. """ from __future__ import absolute_import import sys import os import io import time import re import types import zipfile import zipimport import warnings import stat import functools import pkgutil import operator import platform import collections import plistlib import email.parser import tempfile import textwrap from pkgutil import get_importer try: import _imp except ImportError: # Python 3.2 compatibility import imp as _imp from pip._vendor import six from pip._vendor.six.moves import urllib, map, filter # capture these to bypass sandboxing from os import utime try: from os import mkdir, rename, unlink WRITE_SUPPORT = True except ImportError: # no write support, probably under GAE WRITE_SUPPORT = False from os import open as os_open from os.path import isdir, split try: import importlib.machinery as importlib_machinery # access attribute to force import under delayed import mechanisms. importlib_machinery.__name__ except ImportError: importlib_machinery = None from pip._vendor import packaging __import__('pip._vendor.packaging.version') __import__('pip._vendor.packaging.specifiers') __import__('pip._vendor.packaging.requirements') __import__('pip._vendor.packaging.markers') if (3, 0) < sys.version_info < (3, 3): msg = ( "Support for Python 3.0-3.2 has been dropped. Future versions " "will fail here." ) warnings.warn(msg) # declare some globals that will be defined later to # satisfy the linters. require = None working_set = None class PEP440Warning(RuntimeWarning): """ Used when there is an issue with a version or specifier not complying with PEP 440. """ class _SetuptoolsVersionMixin(object): def __hash__(self): return super(_SetuptoolsVersionMixin, self).__hash__() def __lt__(self, other): if isinstance(other, tuple): return tuple(self) < other else: return super(_SetuptoolsVersionMixin, self).__lt__(other) def __le__(self, other): if isinstance(other, tuple): return tuple(self) <= other else: return super(_SetuptoolsVersionMixin, self).__le__(other) def __eq__(self, other): if isinstance(other, tuple): return tuple(self) == other else: return super(_SetuptoolsVersionMixin, self).__eq__(other) def __ge__(self, other): if isinstance(other, tuple): return tuple(self) >= other else: return super(_SetuptoolsVersionMixin, self).__ge__(other) def __gt__(self, other): if isinstance(other, tuple): return tuple(self) > other else: return super(_SetuptoolsVersionMixin, self).__gt__(other) def __ne__(self, other): if isinstance(other, tuple): return tuple(self) != other else: return super(_SetuptoolsVersionMixin, self).__ne__(other) def __getitem__(self, key): return tuple(self)[key] def __iter__(self): component_re = re.compile(r'(\d+ | [a-z]+ | \.| -)', re.VERBOSE) replace = { 'pre': 'c', 'preview': 'c', '-': 'final-', 'rc': 'c', 'dev': '@', }.get def _parse_version_parts(s): for part in component_re.split(s): part = replace(part, part) if not part or part == '.': continue if part[:1] in '0123456789': # pad for numeric comparison yield part.zfill(8) else: yield '*'+part # ensure that alpha/beta/candidate are before final yield '*final' def old_parse_version(s): parts = [] for part in _parse_version_parts(s.lower()): if part.startswith('*'): # remove '-' before a prerelease tag if part < '*final': while parts and parts[-1] == '*final-': parts.pop() # remove trailing zeros from each series of numeric parts while parts and parts[-1] == '00000000': parts.pop() parts.append(part) return tuple(parts) # Warn for use of this function warnings.warn( "You have iterated over the result of " "pkg_resources.parse_version. This is a legacy behavior which is " "inconsistent with the new version class introduced in setuptools " "8.0. In most cases, conversion to a tuple is unnecessary. For " "comparison of versions, sort the Version instances directly. If " "you have another use case requiring the tuple, please file a " "bug with the setuptools project describing that need.", RuntimeWarning, stacklevel=1, ) for part in old_parse_version(str(self)): yield part class SetuptoolsVersion(_SetuptoolsVersionMixin, packaging.version.Version): pass class SetuptoolsLegacyVersion(_SetuptoolsVersionMixin, packaging.version.LegacyVersion): pass def parse_version(v): try: return SetuptoolsVersion(v) except packaging.version.InvalidVersion: return SetuptoolsLegacyVersion(v) _state_vars = {} def _declare_state(vartype, **kw): globals().update(kw) _state_vars.update(dict.fromkeys(kw, vartype)) def __getstate__(): state = {} g = globals() for k, v in _state_vars.items(): state[k] = g['_sget_'+v](g[k]) return state def __setstate__(state): g = globals() for k, v in state.items(): g['_sset_'+_state_vars[k]](k, g[k], v) return state def _sget_dict(val): return val.copy() def _sset_dict(key, ob, state): ob.clear() ob.update(state) def _sget_object(val): return val.__getstate__() def _sset_object(key, ob, state): ob.__setstate__(state) _sget_none = _sset_none = lambda *args: None def get_supported_platform(): """Return this platform's maximum compatible version. distutils.util.get_platform() normally reports the minimum version of Mac OS X that would be required to *use* extensions produced by distutils. But what we want when checking compatibility is to know the version of Mac OS X that we are *running*. To allow usage of packages that explicitly require a newer version of Mac OS X, we must also know the current version of the OS. If this condition occurs for any other platform with a version in its platform strings, this function should be extended accordingly. """ plat = get_build_platform() m = macosVersionString.match(plat) if m is not None and sys.platform == "darwin": try: plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3)) except ValueError: # not Mac OS X pass return plat __all__ = [ # Basic resource access and distribution/entry point discovery 'require', 'run_script', 'get_provider', 'get_distribution', 'load_entry_point', 'get_entry_map', 'get_entry_info', 'iter_entry_points', 'resource_string', 'resource_stream', 'resource_filename', 'resource_listdir', 'resource_exists', 'resource_isdir', # Environmental control 'declare_namespace', 'working_set', 'add_activation_listener', 'find_distributions', 'set_extraction_path', 'cleanup_resources', 'get_default_cache', # Primary implementation classes 'Environment', 'WorkingSet', 'ResourceManager', 'Distribution', 'Requirement', 'EntryPoint', # Exceptions 'ResolutionError', 'VersionConflict', 'DistributionNotFound', 'UnknownExtra', 'ExtractionError', # Warnings 'PEP440Warning', # Parsing functions and string utilities 'parse_requirements', 'parse_version', 'safe_name', 'safe_version', 'get_platform', 'compatible_platforms', 'yield_lines', 'split_sections', 'safe_extra', 'to_filename', 'invalid_marker', 'evaluate_marker', # filesystem utilities 'ensure_directory', 'normalize_path', # Distribution "precedence" constants 'EGG_DIST', 'BINARY_DIST', 'SOURCE_DIST', 'CHECKOUT_DIST', 'DEVELOP_DIST', # "Provider" interfaces, implementations, and registration/lookup APIs 'IMetadataProvider', 'IResourceProvider', 'FileMetadata', 'PathMetadata', 'EggMetadata', 'EmptyProvider', 'empty_provider', 'NullProvider', 'EggProvider', 'DefaultProvider', 'ZipProvider', 'register_finder', 'register_namespace_handler', 'register_loader_type', 'fixup_namespace_packages', 'get_importer', # Deprecated/backward compatibility only 'run_main', 'AvailableDistributions', ] class ResolutionError(Exception): """Abstract base for dependency resolution errors""" def __repr__(self): return self.__class__.__name__+repr(self.args) class VersionConflict(ResolutionError): """ An already-installed version conflicts with the requested version. Should be initialized with the installed Distribution and the requested Requirement. """ _template = "{self.dist} is installed but {self.req} is required" @property def dist(self): return self.args[0] @property def req(self): return self.args[1] def report(self): return self._template.format(**locals()) def with_context(self, required_by): """ If required_by is non-empty, return a version of self that is a ContextualVersionConflict. """ if not required_by: return self args = self.args + (required_by,) return ContextualVersionConflict(*args) class ContextualVersionConflict(VersionConflict): """ A VersionConflict that accepts a third parameter, the set of the requirements that required the installed Distribution. """ _template = VersionConflict._template + ' by {self.required_by}' @property def required_by(self): return self.args[2] class DistributionNotFound(ResolutionError): """A requested distribution was not found""" _template = ("The '{self.req}' distribution was not found " "and is required by {self.requirers_str}") @property def req(self): return self.args[0] @property def requirers(self): return self.args[1] @property def requirers_str(self): if not self.requirers: return 'the application' return ', '.join(self.requirers) def report(self): return self._template.format(**locals()) def __str__(self): return self.report() class UnknownExtra(ResolutionError): """Distribution doesn't have an "extra feature" of the given name""" _provider_factories = {} PY_MAJOR = sys.version[:3] EGG_DIST = 3 BINARY_DIST = 2 SOURCE_DIST = 1 CHECKOUT_DIST = 0 DEVELOP_DIST = -1 def register_loader_type(loader_type, provider_factory): """Register `provider_factory` to make providers for `loader_type` `loader_type` is the type or class of a PEP 302 ``module.__loader__``, and `provider_factory` is a function that, passed a *module* object, returns an ``IResourceProvider`` for that module. """ _provider_factories[loader_type] = provider_factory def get_provider(moduleOrReq): """Return an IResourceProvider for the named module or requirement""" if isinstance(moduleOrReq, Requirement): return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0] try: module = sys.modules[moduleOrReq] except KeyError: __import__(moduleOrReq) module = sys.modules[moduleOrReq] loader = getattr(module, '__loader__', None) return _find_adapter(_provider_factories, loader)(module) def _macosx_vers(_cache=[]): if not _cache: version = platform.mac_ver()[0] # fallback for MacPorts if version == '': plist = '/System/Library/CoreServices/SystemVersion.plist' if os.path.exists(plist): if hasattr(plistlib, 'readPlist'): plist_content = plistlib.readPlist(plist) if 'ProductVersion' in plist_content: version = plist_content['ProductVersion'] _cache.append(version.split('.')) return _cache[0] def _macosx_arch(machine): return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine) def get_build_platform(): """Return this platform's string for platform-specific distributions XXX Currently this is the same as ``distutils.util.get_platform()``, but it needs some hacks for Linux and Mac OS X. """ try: # Python 2.7 or >=3.2 from sysconfig import get_platform except ImportError: from distutils.util import get_platform plat = get_platform() if sys.platform == "darwin" and not plat.startswith('macosx-'): try: version = _macosx_vers() machine = os.uname()[4].replace(" ", "_") return "macosx-%d.%d-%s" % (int(version[0]), int(version[1]), _macosx_arch(machine)) except ValueError: # if someone is running a non-Mac darwin system, this will fall # through to the default implementation pass return plat macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)") darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)") # XXX backward compat get_platform = get_build_platform def compatible_platforms(provided, required): """Can code for the `provided` platform run on the `required` platform? Returns true if either platform is ``None``, or the platforms are equal. XXX Needs compatibility checks for Linux and other unixy OSes. """ if provided is None or required is None or provided==required: # easy case return True # Mac OS X special cases reqMac = macosVersionString.match(required) if reqMac: provMac = macosVersionString.match(provided) # is this a Mac package? if not provMac: # this is backwards compatibility for packages built before # setuptools 0.6. All packages built after this point will # use the new macosx designation. provDarwin = darwinVersionString.match(provided) if provDarwin: dversion = int(provDarwin.group(1)) macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2)) if dversion == 7 and macosversion >= "10.3" or \ dversion == 8 and macosversion >= "10.4": return True # egg isn't macosx or legacy darwin return False # are they the same major version and machine type? if provMac.group(1) != reqMac.group(1) or \ provMac.group(3) != reqMac.group(3): return False # is the required OS major update >= the provided one? if int(provMac.group(2)) > int(reqMac.group(2)): return False return True # XXX Linux and other platforms' special cases should go here return False def run_script(dist_spec, script_name): """Locate distribution `dist_spec` and run its `script_name` script""" ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name require(dist_spec)[0].run_script(script_name, ns) # backward compatibility run_main = run_script 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 load_entry_point(dist, group, name): """Return `name` entry point of `group` for `dist` or raise ImportError""" return get_distribution(dist).load_entry_point(group, name) def get_entry_map(dist, group=None): """Return the entry point map for `group`, or the full entry map""" return get_distribution(dist).get_entry_map(group) def get_entry_info(dist, group, name): """Return the EntryPoint object for `group`+`name`, or ``None``""" return get_distribution(dist).get_entry_info(group, name) class IMetadataProvider: def has_metadata(name): """Does the package's distribution contain the named metadata?""" def get_metadata(name): """The named metadata resource as a string""" def get_metadata_lines(name): """Yield named metadata resource as list of non-blank non-comment lines Leading and trailing whitespace is stripped from each line, and lines with ``#`` as the first non-blank character are omitted.""" def metadata_isdir(name): """Is the named metadata a directory? (like ``os.path.isdir()``)""" def metadata_listdir(name): """List of metadata names in the directory (like ``os.listdir()``)""" def run_script(script_name, namespace): """Execute the named script in the supplied namespace dictionary""" class IResourceProvider(IMetadataProvider): """An object that provides access to package resources""" def get_resource_filename(manager, resource_name): """Return a true filesystem path for `resource_name` `manager` must be an ``IResourceManager``""" def get_resource_stream(manager, resource_name): """Return a readable file-like object for `resource_name` `manager` must be an ``IResourceManager``""" def get_resource_string(manager, resource_name): """Return a string containing the contents of `resource_name` `manager` must be an ``IResourceManager``""" def has_resource(resource_name): """Does the package contain the named resource?""" def resource_isdir(resource_name): """Is the named resource a directory? (like ``os.path.isdir()``)""" def resource_listdir(resource_name): """List of resource names in the directory (like ``os.listdir()``)""" class WorkingSet(object): """A collection of active distributions on sys.path (or a similar list)""" def __init__(self, entries=None): """Create working set from list of path entries (default=sys.path)""" self.entries = [] self.entry_keys = {} self.by_key = {} self.callbacks = [] if entries is None: entries = sys.path for entry in entries: self.add_entry(entry) @classmethod def _build_master(cls): """ Prepare the master working set. """ ws = cls() try: from __main__ import __requires__ except ImportError: # The main program does not list any requirements return ws # ensure the requirements are met try: ws.require(__requires__) except VersionConflict: return cls._build_from_requirements(__requires__) return ws @classmethod def _build_from_requirements(cls, req_spec): """ Build a working set from a requirement spec. Rewrites sys.path. """ # try it without defaults already on sys.path # by starting with an empty path ws = cls([]) reqs = parse_requirements(req_spec) dists = ws.resolve(reqs, Environment()) for dist in dists: ws.add(dist) # add any missing entries from sys.path for entry in sys.path: if entry not in ws.entries: ws.add_entry(entry) # then copy back to sys.path sys.path[:] = ws.entries return ws def add_entry(self, entry): """Add a path item to ``.entries``, finding any distributions on it ``find_distributions(entry, True)`` is used to find distributions corresponding to the path entry, and they are added. `entry` is always appended to ``.entries``, even if it is already present. (This is because ``sys.path`` can contain the same value more than once, and the ``.entries`` of the ``sys.path`` WorkingSet should always equal ``sys.path``.) """ self.entry_keys.setdefault(entry, []) self.entries.append(entry) for dist in find_distributions(entry, True): self.add(dist, entry, False) def __contains__(self, dist): """True if `dist` is the active distribution for its project""" return self.by_key.get(dist.key) == dist def find(self, req): """Find a distribution matching requirement `req` If there is an active distribution for the requested project, this returns it as long as it meets the version requirement specified by `req`. But, if there is an active distribution for the project and it does *not* meet the `req` requirement, ``VersionConflict`` is raised. If there is no active distribution for the requested project, ``None`` is returned. """ dist = self.by_key.get(req.key) if dist is not None and dist not in req: # XXX add more info raise VersionConflict(dist, req) return dist def iter_entry_points(self, group, name=None): """Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution order). """ for dist in self: entries = dist.get_entry_map(group) if name is None: for ep in entries.values(): yield ep elif name in entries: yield entries[name] def run_script(self, requires, script_name): """Locate distribution for `requires` and run `script_name` script""" ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name self.require(requires)[0].run_script(script_name, ns) def __iter__(self): """Yield distributions for non-duplicate projects in the working set The yield order is the order in which the items' path entries were added to the working set. """ seen = {} for item in self.entries: if item not in self.entry_keys: # workaround a cache issue continue for key in self.entry_keys[item]: if key not in seen: seen[key]=1 yield self.by_key[key] def add(self, dist, entry=None, insert=True, replace=False): """Add `dist` to working set, associated with `entry` If `entry` is unspecified, it defaults to the ``.location`` of `dist`. On exit from this routine, `entry` is added to the end of the working set's ``.entries`` (if it wasn't already present). `dist` is only added to the working set if it's for a project that doesn't already have a distribution in the set, unless `replace=True`. If it's added, any callbacks registered with the ``subscribe()`` method will be called. """ if insert: dist.insert_on(self.entries, entry, replace=replace) if entry is None: entry = dist.location keys = self.entry_keys.setdefault(entry,[]) keys2 = self.entry_keys.setdefault(dist.location,[]) if not replace and dist.key in self.by_key: # ignore hidden distros return self.by_key[dist.key] = dist if dist.key not in keys: keys.append(dist.key) if dist.key not in keys2: keys2.append(dist.key) self._added_new(dist) def resolve(self, requirements, env=None, installer=None, replace_conflicting=False): """List all distributions needed to (recursively) meet `requirements` `requirements` must be a sequence of ``Requirement`` objects. `env`, if supplied, should be an ``Environment`` instance. If not supplied, it defaults to all distributions available within any entry or distribution in the working set. `installer`, if supplied, will be invoked with each requirement that cannot be met by an already-installed distribution; it should return a ``Distribution`` or ``None``. Unless `replace_conflicting=True`, raises a VersionConflict exception if any requirements are found on the path that have the correct name but the wrong version. Otherwise, if an `installer` is supplied it will be invoked to obtain the correct version of the requirement and activate it. """ # set up the stack requirements = list(requirements)[::-1] # set of processed requirements processed = {} # key -> dist best = {} to_activate = [] req_extras = _ReqExtras() # Mapping of requirement to set of distributions that required it; # useful for reporting info about conflicts. required_by = collections.defaultdict(set) while requirements: # process dependencies breadth-first req = requirements.pop(0) if req in processed: # Ignore cyclic or redundant dependencies continue if not req_extras.markers_pass(req): continue dist = best.get(req.key) if dist is None: # Find the best distribution and add it to the map dist = self.by_key.get(req.key) if dist is None or (dist not in req and replace_conflicting): ws = self if env is None: if dist is None: env = Environment(self.entries) else: # Use an empty environment and workingset to avoid # any further conflicts with the conflicting # distribution env = Environment([]) ws = WorkingSet([]) dist = best[req.key] = env.best_match(req, ws, installer) if dist is None: requirers = required_by.get(req, None) raise DistributionNotFound(req, requirers) to_activate.append(dist) if dist not in req: # Oops, the "best" so far conflicts with a dependency dependent_req = required_by[req] raise VersionConflict(dist, req).with_context(dependent_req) # push the new requirements onto the stack new_requirements = dist.requires(req.extras)[::-1] requirements.extend(new_requirements) # Register the new requirements needed by req for new_requirement in new_requirements: required_by[new_requirement].add(req.project_name) req_extras[new_requirement] = req.extras processed[req] = True # return list of distros to activate return to_activate def find_plugins(self, plugin_env, full_env=None, installer=None, fallback=True): """Find all activatable distributions in `plugin_env` Example usage:: distributions, errors = working_set.find_plugins( Environment(plugin_dirlist) ) # add plugins+libs to sys.path map(working_set.add, distributions) # display errors print('Could not load', errors) The `plugin_env` should be an ``Environment`` instance that contains only distributions that are in the project's "plugin directory" or directories. The `full_env`, if supplied, should be an ``Environment`` contains all currently-available distributions. If `full_env` is not supplied, one is created automatically from the ``WorkingSet`` this method is called on, which will typically mean that every directory on ``sys.path`` will be scanned for distributions. `installer` is a standard installer callback as used by the ``resolve()`` method. The `fallback` flag indicates whether we should attempt to resolve older versions of a plugin if the newest version cannot be resolved. This method returns a 2-tuple: (`distributions`, `error_info`), where `distributions` is a list of the distributions found in `plugin_env` that were loadable, along with any other distributions that are needed to resolve their dependencies. `error_info` is a dictionary mapping unloadable plugin distributions to an exception instance describing the error that occurred. Usually this will be a ``DistributionNotFound`` or ``VersionConflict`` instance. """ plugin_projects = list(plugin_env) # scan project names in alphabetic order plugin_projects.sort() error_info = {} distributions = {} if full_env is None: env = Environment(self.entries) env += plugin_env else: env = full_env + plugin_env shadow_set = self.__class__([]) # put all our entries in shadow_set list(map(shadow_set.add, self)) for project_name in plugin_projects: for dist in plugin_env[project_name]: req = [dist.as_requirement()] try: resolvees = shadow_set.resolve(req, env, installer) except ResolutionError as v: # save error info error_info[dist] = v if fallback: # try the next older version of project continue else: # give up on this project, keep going break else: list(map(shadow_set.add, resolvees)) distributions.update(dict.fromkeys(resolvees)) # success, no need to try any more versions of this project break distributions = list(distributions) distributions.sort() return distributions, error_info def require(self, *requirements): """Ensure that distributions matching `requirements` are activated `requirements` must be a string or a (possibly-nested) sequence thereof, specifying the distributions and versions required. The return value is a sequence of the distributions that needed to be activated to fulfill the requirements; all relevant distributions are included, even if they were already activated in this working set. """ needed = self.resolve(parse_requirements(requirements)) for dist in needed: self.add(dist) return needed def subscribe(self, callback): """Invoke `callback` for all distributions (including existing ones)""" if callback in self.callbacks: return self.callbacks.append(callback) for dist in self: callback(dist) def _added_new(self, dist): for callback in self.callbacks: callback(dist) def __getstate__(self): return ( self.entries[:], self.entry_keys.copy(), self.by_key.copy(), self.callbacks[:] ) def __setstate__(self, e_k_b_c): entries, keys, by_key, callbacks = e_k_b_c self.entries = entries[:] self.entry_keys = keys.copy() self.by_key = by_key.copy() self.callbacks = callbacks[:] class _ReqExtras(dict): """ Map each requirement to the extras that demanded it. """ def markers_pass(self, req): """ Evaluate markers for req against each extra that demanded it. Return False if the req has a marker and fails evaluation. Otherwise, return True. """ evals = ( req.marker.evaluate({'extra': extra}) for extra in self.get(req) or [''] ) return not req.marker or any(evals) class Environment(object): """Searchable snapshot of distributions on a search path""" def __init__(self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR): """Snapshot distributions available on a search path Any distributions found on `search_path` are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. `platform` is an optional string specifying the name of the platform that platform-specific distributions must be compatible with. If unspecified, it defaults to the current platform. `python` is an optional string naming the desired version of Python (e.g. ``'3.3'``); it defaults to the current version. You may explicitly set `platform` (and/or `python`) to ``None`` if you wish to map *all* distributions, not just those compatible with the running platform or Python version. """ self._distmap = {} self.platform = platform self.python = python self.scan(search_path) def can_add(self, dist): """Is distribution `dist` acceptable for this environment? The distribution must match the platform and python version requirements specified when this environment was created, or False is returned. """ return (self.python is None or dist.py_version is None or dist.py_version==self.python) \ and compatible_platforms(dist.platform, self.platform) def remove(self, dist): """Remove `dist` from the environment""" self._distmap[dist.key].remove(dist) def scan(self, search_path=None): """Scan `search_path` for distributions usable in this environment Any distributions found are added to the environment. `search_path` should be a sequence of ``sys.path`` items. If not supplied, ``sys.path`` is used. Only distributions conforming to the platform/python version defined at initialization are added. """ if search_path is None: search_path = sys.path for item in search_path: for dist in find_distributions(item): self.add(dist) def __getitem__(self, project_name): """Return a newest-to-oldest list of distributions for `project_name` Uses case-insensitive `project_name` comparison, assuming all the project's distributions use their project's name converted to all lowercase as their key. """ distribution_key = project_name.lower() return self._distmap.get(distribution_key, []) def add(self, dist): """Add `dist` if we ``can_add()`` it and it has not already been added """ if self.can_add(dist) and dist.has_version(): dists = self._distmap.setdefault(dist.key, []) if dist not in dists: dists.append(dist) dists.sort(key=operator.attrgetter('hashcmp'), reverse=True) def best_match(self, req, working_set, installer=None): """Find distribution best matching `req` and usable on `working_set` This calls the ``find(req)`` method of the `working_set` to see if a suitable distribution is already active. (This may raise ``VersionConflict`` if an unsuitable version of the project is already active in the specified `working_set`.) If a suitable distribution isn't active, this method returns the newest distribution in the environment that meets the ``Requirement`` in `req`. If no suitable distribution is found, and `installer` is supplied, then the result of calling the environment's ``obtain(req, installer)`` method will be returned. """ dist = working_set.find(req) if dist is not None: return dist for dist in self[req.key]: if dist in req: return dist # try to download/install return self.obtain(req, installer) def obtain(self, requirement, installer=None): """Obtain a distribution matching `requirement` (e.g. via download) Obtain a distro that matches requirement (e.g. via download). In the base ``Environment`` class, this routine just returns ``installer(requirement)``, unless `installer` is None, in which case None is returned instead. This method is a hook that allows subclasses to attempt other ways of obtaining a distribution before falling back to the `installer` argument.""" if installer is not None: return installer(requirement) def __iter__(self): """Yield the unique project names of the available distributions""" for key in self._distmap.keys(): if self[key]: yield key def __iadd__(self, other): """In-place addition of a distribution or environment""" if isinstance(other, Distribution): self.add(other) elif isinstance(other, Environment): for project in other: for dist in other[project]: self.add(dist) else: raise TypeError("Can't add %r to environment" % (other,)) return self def __add__(self, other): """Add an environment or distribution to an environment""" new = self.__class__([], platform=None, python=None) for env in self, other: new += env return new # XXX backward compatibility AvailableDistributions = Environment class ExtractionError(RuntimeError): """An error occurred extracting a resource The following attributes are available from instances of this exception: manager The resource manager that raised this exception cache_path The base directory for resource extraction original_error The exception instance that caused extraction to fail """ class ResourceManager: """Manage resource extraction and packages""" extraction_path = None def __init__(self): self.cached_files = {} def resource_exists(self, package_or_requirement, resource_name): """Does the named resource exist?""" return get_provider(package_or_requirement).has_resource(resource_name) def resource_isdir(self, package_or_requirement, resource_name): """Is the named resource an existing directory?""" return get_provider(package_or_requirement).resource_isdir( resource_name ) def resource_filename(self, package_or_requirement, resource_name): """Return a true filesystem path for specified resource""" return get_provider(package_or_requirement).get_resource_filename( self, resource_name ) def resource_stream(self, package_or_requirement, resource_name): """Return a readable file-like object for specified resource""" return get_provider(package_or_requirement).get_resource_stream( self, resource_name ) def resource_string(self, package_or_requirement, resource_name): """Return specified resource as a string""" return get_provider(package_or_requirement).get_resource_string( self, resource_name ) def resource_listdir(self, package_or_requirement, resource_name): """List the contents of the named resource directory""" return get_provider(package_or_requirement).resource_listdir( resource_name ) def extraction_error(self): """Give an error message for problems extracting file(s)""" old_exc = sys.exc_info()[1] cache_path = self.extraction_path or get_default_cache() tmpl = textwrap.dedent(""" Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: {old_exc} The Python egg cache directory is currently set to: {cache_path} Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory. """).lstrip() err = ExtractionError(tmpl.format(**locals())) err.manager = self err.cache_path = cache_path err.original_error = old_exc raise err def get_cache_path(self, archive_name, names=()): """Return absolute location in cache for `archive_name` and `names` The parent directory of the resulting path will be created if it does not already exist. `archive_name` should be the base filename of the enclosing egg (which may not be the name of the enclosing zipfile!), including its ".egg" extension. `names`, if provided, should be a sequence of path name parts "under" the egg's extraction location. This method should only be called by resource providers that need to obtain an extraction location, and only for names they intend to extract, as it tracks the generated names for possible cleanup later. """ extract_path = self.extraction_path or get_default_cache() target_path = os.path.join(extract_path, archive_name+'-tmp', *names) try: _bypass_ensure_directory(target_path) except: self.extraction_error() self._warn_unsafe_extraction_path(extract_path) self.cached_files[target_path] = 1 return target_path @staticmethod def _warn_unsafe_extraction_path(path): """ If the default extraction path is overridden and set to an insecure location, such as /tmp, it opens up an opportunity for an attacker to replace an extracted file with an unauthorized payload. Warn the user if a known insecure location is used. See Distribute #375 for more details. """ if os.name == 'nt' and not path.startswith(os.environ['windir']): # On Windows, permissions are generally restrictive by default # and temp directories are not writable by other users, so # bypass the warning. return mode = os.stat(path).st_mode if mode & stat.S_IWOTH or mode & stat.S_IWGRP: msg = ("%s is writable by group/others and vulnerable to attack " "when " "used with get_resource_filename. Consider a more secure " "location (set with .set_extraction_path or the " "PYTHON_EGG_CACHE environment variable)." % path) warnings.warn(msg, UserWarning) def postprocess(self, tempname, filename): """Perform any platform-specific postprocessing of `tempname` This is where Mac header rewrites should be done; other platforms don't have anything special they should do. Resource providers should call this method ONLY after successfully extracting a compressed resource. They must NOT call it on resources that are already in the filesystem. `tempname` is the current (temporary) name of the file, and `filename` is the name it will be renamed to by the caller after this routine returns. """ if os.name == 'posix': # Make the resource executable mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777 os.chmod(tempname, mode) def set_extraction_path(self, path): """Set the base path where resources will be extracted to, if needed. If you do not call this routine before any extractions take place, the path defaults to the return value of ``get_default_cache()``. (Which is based on the ``PYTHON_EGG_CACHE`` environment variable, with various platform-specific fallbacks. See that routine's documentation for more details.) Resources are extracted to subdirectories of this path based upon information given by the ``IResourceProvider``. You may set this to a temporary directory, but then you must call ``cleanup_resources()`` to delete the extracted files when done. There is no guarantee that ``cleanup_resources()`` will be able to remove all extracted files. (Note: you may not change the extraction path for a given resource manager once resources have been extracted, unless you first call ``cleanup_resources()``.) """ if self.cached_files: raise ValueError( "Can't change extraction path, files already extracted" ) self.extraction_path = path def cleanup_resources(self, force=False): """ Delete all extracted resource files and directories, returning a list of the file and directory names that could not be successfully removed. This function does not have any concurrency protection, so it should generally only be called when the extraction path is a temporary directory exclusive to a single process. This method is not automatically called; you must call it explicitly or register it as an ``atexit`` function if you wish to ensure cleanup of a temporary directory used for extractions. """ # XXX def get_default_cache(): """Determine the default cache location This returns the ``PYTHON_EGG_CACHE`` environment variable, if set. Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the "Application Data" directory. On all other systems, it's "~/.python-eggs". """ try: return os.environ['PYTHON_EGG_CACHE'] except KeyError: pass if os.name!='nt': return os.path.expanduser('~/.python-eggs') # XXX this may be locale-specific! app_data = 'Application Data' app_homes = [ # best option, should be locale-safe (('APPDATA',), None), (('USERPROFILE',), app_data), (('HOMEDRIVE','HOMEPATH'), app_data), (('HOMEPATH',), app_data), (('HOME',), None), # 95/98/ME (('WINDIR',), app_data), ] for keys, subdir in app_homes: dirname = '' for key in keys: if key in os.environ: dirname = os.path.join(dirname, os.environ[key]) else: break else: if subdir: dirname = os.path.join(dirname, subdir) return os.path.join(dirname, 'Python-Eggs') else: raise RuntimeError( "Please set the PYTHON_EGG_CACHE enviroment variable" ) def safe_name(name): """Convert an arbitrary string to a standard distribution name Any runs of non-alphanumeric/. characters are replaced with a single '-'. """ return re.sub('[^A-Za-z0-9.]+', '-', name) def safe_version(version): """ Convert an arbitrary string to a standard version string """ try: # normalize the version return str(packaging.version.Version(version)) except packaging.version.InvalidVersion: version = version.replace(' ','.') return re.sub('[^A-Za-z0-9.]+', '-', version) def safe_extra(extra): """Convert an arbitrary string to a standard 'extra' name Any runs of non-alphanumeric characters are replaced with a single '_', and the result is always lowercased. """ return re.sub('[^A-Za-z0-9.]+', '_', extra).lower() def to_filename(name): """Convert a project or version name to its filename-escaped form Any '-' characters are currently replaced with '_'. """ return name.replace('-','_') def invalid_marker(text): """ Validate text as a PEP 508 environment marker; return an exception if invalid or False otherwise. """ try: evaluate_marker(text) except SyntaxError as e: e.filename = None e.lineno = None return e return False def evaluate_marker(text, extra=None): """ Evaluate a PEP 508 environment marker. Return a boolean indicating the marker result in this environment. Raise SyntaxError if marker is invalid. This implementation uses the 'pyparsing' module. """ try: marker = packaging.markers.Marker(text) return marker.evaluate() except packaging.markers.InvalidMarker as e: raise SyntaxError(e) class NullProvider: """Try to implement resources and metadata for arbitrary PEP 302 loaders""" egg_name = None egg_info = None loader = None def __init__(self, module): self.loader = getattr(module, '__loader__', None) self.module_path = os.path.dirname(getattr(module, '__file__', '')) def get_resource_filename(self, manager, resource_name): return self._fn(self.module_path, resource_name) def get_resource_stream(self, manager, resource_name): return io.BytesIO(self.get_resource_string(manager, resource_name)) def get_resource_string(self, manager, resource_name): return self._get(self._fn(self.module_path, resource_name)) def has_resource(self, resource_name): return self._has(self._fn(self.module_path, resource_name)) def has_metadata(self, name): return self.egg_info and self._has(self._fn(self.egg_info, name)) if sys.version_info <= (3,): def get_metadata(self, name): if not self.egg_info: return "" return self._get(self._fn(self.egg_info, name)) else: def get_metadata(self, name): if not self.egg_info: return "" return self._get(self._fn(self.egg_info, name)).decode("utf-8") def get_metadata_lines(self, name): return yield_lines(self.get_metadata(name)) def resource_isdir(self, resource_name): return self._isdir(self._fn(self.module_path, resource_name)) def metadata_isdir(self, name): return self.egg_info and self._isdir(self._fn(self.egg_info, name)) def resource_listdir(self, resource_name): return self._listdir(self._fn(self.module_path, resource_name)) def metadata_listdir(self, name): if self.egg_info: return self._listdir(self._fn(self.egg_info, name)) return [] def run_script(self, script_name, namespace): script = 'scripts/'+script_name if not self.has_metadata(script): raise ResolutionError("No script named %r" % script_name) script_text = self.get_metadata(script).replace('\r\n', '\n') script_text = script_text.replace('\r', '\n') script_filename = self._fn(self.egg_info, script) namespace['__file__'] = script_filename if os.path.exists(script_filename): source = open(script_filename).read() code = compile(source, script_filename, 'exec') exec(code, namespace, namespace) else: from linecache import cache cache[script_filename] = ( len(script_text), 0, script_text.split('\n'), script_filename ) script_code = compile(script_text, script_filename,'exec') exec(script_code, namespace, namespace) def _has(self, path): raise NotImplementedError( "Can't perform this operation for unregistered loader type" ) def _isdir(self, path): raise NotImplementedError( "Can't perform this operation for unregistered loader type" ) def _listdir(self, path): raise NotImplementedError( "Can't perform this operation for unregistered loader type" ) def _fn(self, base, resource_name): if resource_name: return os.path.join(base, *resource_name.split('/')) return base def _get(self, path): if hasattr(self.loader, 'get_data'): return self.loader.get_data(path) raise NotImplementedError( "Can't perform this operation for loaders without 'get_data()'" ) register_loader_type(object, NullProvider) class EggProvider(NullProvider): """Provider based on a virtual filesystem""" def __init__(self, module): NullProvider.__init__(self, module) self._setup_prefix() def _setup_prefix(self): # we assume here that our metadata may be nested inside a "basket" # of multiple eggs; that's why we use module_path instead of .archive path = self.module_path old = None while path!=old: if _is_unpacked_egg(path): self.egg_name = os.path.basename(path) self.egg_info = os.path.join(path, 'EGG-INFO') self.egg_root = path break old = path path, base = os.path.split(path) class DefaultProvider(EggProvider): """Provides access to package resources in the filesystem""" def _has(self, path): return os.path.exists(path) def _isdir(self, path): return os.path.isdir(path) def _listdir(self, path): return os.listdir(path) def get_resource_stream(self, manager, resource_name): return open(self._fn(self.module_path, resource_name), 'rb') def _get(self, path): with open(path, 'rb') as stream: return stream.read() @classmethod def _register(cls): loader_cls = getattr(importlib_machinery, 'SourceFileLoader', type(None)) register_loader_type(loader_cls, cls) DefaultProvider._register() class EmptyProvider(NullProvider): """Provider that returns nothing for all requests""" _isdir = _has = lambda self, path: False _get = lambda self, path: '' _listdir = lambda self, path: [] module_path = None def __init__(self): pass empty_provider = EmptyProvider() class ZipManifests(dict): """ zip manifest builder """ @classmethod def build(cls, path): """ Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects. Use a platform-specific path separator (os.sep) for the path keys for compatibility with pypy on Windows. """ with ContextualZipFile(path) as zfile: items = ( ( name.replace('/', os.sep), zfile.getinfo(name), ) for name in zfile.namelist() ) return dict(items) load = build class MemoizedZipManifests(ZipManifests): """ Memoized zipfile manifests. """ manifest_mod = collections.namedtuple('manifest_mod', 'manifest mtime') def load(self, path): """ Load a manifest at path or return a suitable manifest already loaded. """ path = os.path.normpath(path) mtime = os.stat(path).st_mtime if path not in self or self[path].mtime != mtime: manifest = self.build(path) self[path] = self.manifest_mod(manifest, mtime) return self[path].manifest class ContextualZipFile(zipfile.ZipFile): """ Supplement ZipFile class to support context manager for Python 2.6 """ def __enter__(self): return self def __exit__(self, type, value, traceback): self.close() def __new__(cls, *args, **kwargs): """ Construct a ZipFile or ContextualZipFile as appropriate """ if hasattr(zipfile.ZipFile, '__exit__'): return zipfile.ZipFile(*args, **kwargs) return super(ContextualZipFile, cls).__new__(cls) class ZipProvider(EggProvider): """Resource support for zips and eggs""" eagers = None _zip_manifests = MemoizedZipManifests() def __init__(self, module): EggProvider.__init__(self, module) self.zip_pre = self.loader.archive+os.sep def _zipinfo_name(self, fspath): # Convert a virtual filename (full path to file) into a zipfile subpath # usable with the zipimport directory cache for our target archive if fspath.startswith(self.zip_pre): return fspath[len(self.zip_pre):] raise AssertionError( "%s is not a subpath of %s" % (fspath, self.zip_pre) ) def _parts(self, zip_path): # Convert a zipfile subpath into an egg-relative path part list. # pseudo-fs path fspath = self.zip_pre+zip_path if fspath.startswith(self.egg_root+os.sep): return fspath[len(self.egg_root)+1:].split(os.sep) raise AssertionError( "%s is not a subpath of %s" % (fspath, self.egg_root) ) @property def zipinfo(self): return self._zip_manifests.load(self.loader.archive) def get_resource_filename(self, manager, resource_name): if not self.egg_name: raise NotImplementedError( "resource_filename() only supported for .egg, not .zip" ) # no need to lock for extraction, since we use temp names zip_path = self._resource_to_zip(resource_name) eagers = self._get_eager_resources() if '/'.join(self._parts(zip_path)) in eagers: for name in eagers: self._extract_resource(manager, self._eager_to_zip(name)) return self._extract_resource(manager, zip_path) @staticmethod def _get_date_and_size(zip_stat): size = zip_stat.file_size # ymdhms+wday, yday, dst date_time = zip_stat.date_time + (0, 0, -1) # 1980 offset already done timestamp = time.mktime(date_time) return timestamp, size def _extract_resource(self, manager, zip_path): if zip_path in self._index(): for name in self._index()[zip_path]: last = self._extract_resource( manager, os.path.join(zip_path, name) ) # return the extracted directory name return os.path.dirname(last) timestamp, size = self._get_date_and_size(self.zipinfo[zip_path]) if not WRITE_SUPPORT: raise IOError('"os.rename" and "os.unlink" are not supported ' 'on this platform') try: real_path = manager.get_cache_path( self.egg_name, self._parts(zip_path) ) if self._is_current(real_path, zip_path): return real_path outf, tmpnam = _mkstemp(".$extract", dir=os.path.dirname(real_path)) os.write(outf, self.loader.get_data(zip_path)) os.close(outf) utime(tmpnam, (timestamp, timestamp)) manager.postprocess(tmpnam, real_path) try: rename(tmpnam, real_path) except os.error: if os.path.isfile(real_path): if self._is_current(real_path, zip_path): # the file became current since it was checked above, # so proceed. return real_path # Windows, del old file and retry elif os.name=='nt': unlink(real_path) rename(tmpnam, real_path) return real_path raise except os.error: # report a user-friendly error manager.extraction_error() return real_path def _is_current(self, file_path, zip_path): """ Return True if the file_path is current for this zip_path """ timestamp, size = self._get_date_and_size(self.zipinfo[zip_path]) if not os.path.isfile(file_path): return False stat = os.stat(file_path) if stat.st_size!=size or stat.st_mtime!=timestamp: return False # check that the contents match zip_contents = self.loader.get_data(zip_path) with open(file_path, 'rb') as f: file_contents = f.read() return zip_contents == file_contents def _get_eager_resources(self): if self.eagers is None: eagers = [] for name in ('native_libs.txt', 'eager_resources.txt'): if self.has_metadata(name): eagers.extend(self.get_metadata_lines(name)) self.eagers = eagers return self.eagers def _index(self): try: return self._dirindex except AttributeError: ind = {} for path in self.zipinfo: parts = path.split(os.sep) while parts: parent = os.sep.join(parts[:-1]) if parent in ind: ind[parent].append(parts[-1]) break else: ind[parent] = [parts.pop()] self._dirindex = ind return ind def _has(self, fspath): zip_path = self._zipinfo_name(fspath) return zip_path in self.zipinfo or zip_path in self._index() def _isdir(self, fspath): return self._zipinfo_name(fspath) in self._index() def _listdir(self, fspath): return list(self._index().get(self._zipinfo_name(fspath), ())) def _eager_to_zip(self, resource_name): return self._zipinfo_name(self._fn(self.egg_root, resource_name)) def _resource_to_zip(self, resource_name): return self._zipinfo_name(self._fn(self.module_path, resource_name)) register_loader_type(zipimport.zipimporter, ZipProvider) class FileMetadata(EmptyProvider): """Metadata handler for standalone PKG-INFO files Usage:: metadata = FileMetadata("/path/to/PKG-INFO") This provider rejects all data and metadata requests except for PKG-INFO, which is treated as existing, and will be the contents of the file at the provided location. """ def __init__(self, path): self.path = path def has_metadata(self, name): return name=='PKG-INFO' and os.path.isfile(self.path) def get_metadata(self, name): if name=='PKG-INFO': with io.open(self.path, encoding='utf-8') as f: try: metadata = f.read() except UnicodeDecodeError as exc: # add path context to error message tmpl = " in {self.path}" exc.reason += tmpl.format(self=self) raise return metadata raise KeyError("No metadata except PKG-INFO is available") def get_metadata_lines(self, name): return yield_lines(self.get_metadata(name)) class PathMetadata(DefaultProvider): """Metadata provider for egg directories Usage:: # Development eggs: egg_info = "/path/to/PackageName.egg-info" base_dir = os.path.dirname(egg_info) metadata = PathMetadata(base_dir, egg_info) dist_name = os.path.splitext(os.path.basename(egg_info))[0] dist = Distribution(basedir, project_name=dist_name, metadata=metadata) # Unpacked egg directories: egg_path = "/path/to/PackageName-ver-pyver-etc.egg" metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO')) dist = Distribution.from_filename(egg_path, metadata=metadata) """ def __init__(self, path, egg_info): self.module_path = path self.egg_info = egg_info class EggMetadata(ZipProvider): """Metadata provider for .egg files""" def __init__(self, importer): """Create a metadata provider from a zipimporter""" self.zip_pre = importer.archive+os.sep self.loader = importer if importer.prefix: self.module_path = os.path.join(importer.archive, importer.prefix) else: self.module_path = importer.archive self._setup_prefix() _declare_state('dict', _distribution_finders = {}) def register_finder(importer_type, distribution_finder): """Register `distribution_finder` to find distributions in sys.path items `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item handler), and `distribution_finder` is a callable that, passed a path item and the importer instance, yields ``Distribution`` instances found on that path item. See ``pkg_resources.find_on_path`` for an example.""" _distribution_finders[importer_type] = distribution_finder def find_distributions(path_item, only=False): """Yield distributions accessible via `path_item`""" importer = get_importer(path_item) finder = _find_adapter(_distribution_finders, importer) return finder(importer, path_item, only) def find_eggs_in_zip(importer, path_item, only=False): """ Find eggs in zip files; possibly multiple nested eggs. """ if importer.archive.endswith('.whl'): # wheels are not supported with this finder # they don't have PKG-INFO metadata, and won't ever contain eggs return metadata = EggMetadata(importer) if metadata.has_metadata('PKG-INFO'): yield Distribution.from_filename(path_item, metadata=metadata) if only: # don't yield nested distros return for subitem in metadata.resource_listdir('/'): if _is_unpacked_egg(subitem): subpath = os.path.join(path_item, subitem) for dist in find_eggs_in_zip(zipimport.zipimporter(subpath), subpath): yield dist register_finder(zipimport.zipimporter, find_eggs_in_zip) def find_nothing(importer, path_item, only=False): return () register_finder(object, find_nothing) def find_on_path(importer, path_item, only=False): """Yield distributions accessible on a sys.path directory""" path_item = _normalize_cached(path_item) if os.path.isdir(path_item) and os.access(path_item, os.R_OK): if _is_unpacked_egg(path_item): yield Distribution.from_filename( path_item, metadata=PathMetadata( path_item, os.path.join(path_item,'EGG-INFO') ) ) else: # scan for .egg and .egg-info in directory for entry in os.listdir(path_item): lower = entry.lower() if lower.endswith('.egg-info') or lower.endswith('.dist-info'): fullpath = os.path.join(path_item, entry) if os.path.isdir(fullpath): # egg-info directory, allow getting metadata metadata = PathMetadata(path_item, fullpath) else: metadata = FileMetadata(fullpath) yield Distribution.from_location( path_item, entry, metadata, precedence=DEVELOP_DIST ) elif not only and _is_unpacked_egg(entry): dists = find_distributions(os.path.join(path_item, entry)) for dist in dists: yield dist elif not only and lower.endswith('.egg-link'): with open(os.path.join(path_item, entry)) as entry_file: entry_lines = entry_file.readlines() for line in entry_lines: if not line.strip(): continue path = os.path.join(path_item, line.rstrip()) dists = find_distributions(path) for item in dists: yield item break register_finder(pkgutil.ImpImporter, find_on_path) if hasattr(importlib_machinery, 'FileFinder'): register_finder(importlib_machinery.FileFinder, find_on_path) _declare_state('dict', _namespace_handlers={}) _declare_state('dict', _namespace_packages={}) def register_namespace_handler(importer_type, namespace_handler): """Register `namespace_handler` to declare namespace packages `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item handler), and `namespace_handler` is a callable like this:: def namespace_handler(importer, path_entry, moduleName, module): # return a path_entry to use for child packages Namespace handlers are only called if the importer object has already agreed that it can handle the relevant path item, and they should only return a subpath if the module __path__ does not already contain an equivalent subpath. For an example namespace handler, see ``pkg_resources.file_ns_handler``. """ _namespace_handlers[importer_type] = namespace_handler def _handle_ns(packageName, path_item): """Ensure that named package includes a subpath of path_item (if needed)""" importer = get_importer(path_item) if importer is None: return None loader = importer.find_module(packageName) if loader is None: return None module = sys.modules.get(packageName) if module is None: module = sys.modules[packageName] = types.ModuleType(packageName) module.__path__ = [] _set_parent_ns(packageName) elif not hasattr(module,'__path__'): raise TypeError("Not a package:", packageName) handler = _find_adapter(_namespace_handlers, importer) subpath = handler(importer, path_item, packageName, module) if subpath is not None: path = module.__path__ path.append(subpath) loader.load_module(packageName) _rebuild_mod_path(path, packageName, module) return subpath def _rebuild_mod_path(orig_path, package_name, module): """ Rebuild module.__path__ ensuring that all entries are ordered corresponding to their sys.path order """ sys_path = [_normalize_cached(p) for p in sys.path] def position_in_sys_path(path): """ Return the ordinal of the path based on its position in sys.path """ path_parts = path.split(os.sep) module_parts = package_name.count('.') + 1 parts = path_parts[:-module_parts] return sys_path.index(_normalize_cached(os.sep.join(parts))) orig_path.sort(key=position_in_sys_path) module.__path__[:] = [_normalize_cached(p) for p in orig_path] def declare_namespace(packageName): """Declare that package 'packageName' is a namespace package""" _imp.acquire_lock() try: if packageName in _namespace_packages: return path, parent = sys.path, None if '.' in packageName: parent = '.'.join(packageName.split('.')[:-1]) declare_namespace(parent) if parent not in _namespace_packages: __import__(parent) try: path = sys.modules[parent].__path__ except AttributeError: raise TypeError("Not a package:", parent) # Track what packages are namespaces, so when new path items are added, # they can be updated _namespace_packages.setdefault(parent,[]).append(packageName) _namespace_packages.setdefault(packageName,[]) for path_item in path: # Ensure all the parent's path items are reflected in the child, # if they apply _handle_ns(packageName, path_item) finally: _imp.release_lock() def fixup_namespace_packages(path_item, parent=None): """Ensure that previously-declared namespace packages include path_item""" _imp.acquire_lock() try: for package in _namespace_packages.get(parent,()): subpath = _handle_ns(package, path_item) if subpath: fixup_namespace_packages(subpath, package) finally: _imp.release_lock() def file_ns_handler(importer, path_item, packageName, module): """Compute an ns-package subpath for a filesystem or zipfile importer""" subpath = os.path.join(path_item, packageName.split('.')[-1]) normalized = _normalize_cached(subpath) for item in module.__path__: if _normalize_cached(item)==normalized: break else: # Only return the path if it's not already there return subpath register_namespace_handler(pkgutil.ImpImporter, file_ns_handler) register_namespace_handler(zipimport.zipimporter, file_ns_handler) if hasattr(importlib_machinery, 'FileFinder'): register_namespace_handler(importlib_machinery.FileFinder, file_ns_handler) def null_ns_handler(importer, path_item, packageName, module): return None register_namespace_handler(object, null_ns_handler) def normalize_path(filename): """Normalize a file/dir name for comparison purposes""" return os.path.normcase(os.path.realpath(filename)) def _normalize_cached(filename, _cache={}): try: return _cache[filename] except KeyError: _cache[filename] = result = normalize_path(filename) return result def _is_unpacked_egg(path): """ Determine if given path appears to be an unpacked egg. """ return ( path.lower().endswith('.egg') ) def _set_parent_ns(packageName): parts = packageName.split('.') name = parts.pop() if parts: parent = '.'.join(parts) setattr(sys.modules[parent], name, sys.modules[packageName]) def yield_lines(strs): """Yield non-empty/non-comment lines of a string or sequence""" if isinstance(strs, six.string_types): for s in strs.splitlines(): s = s.strip() # skip blank lines/comments if s and not s.startswith('#'): yield s else: for ss in strs: for s in yield_lines(ss): yield s MODULE = re.compile(r"\w+(\.\w+)*$").match EGG_NAME = re.compile( r""" (?P<name>[^-]+) ( -(?P<ver>[^-]+) ( -py(?P<pyver>[^-]+) ( -(?P<plat>.+) )? )? )? """, re.VERBOSE | re.IGNORECASE, ).match class EntryPoint(object): """Object representing an advertised importable object""" def __init__(self, name, module_name, attrs=(), extras=(), dist=None): if not MODULE(module_name): raise ValueError("Invalid module name", module_name) self.name = name self.module_name = module_name self.attrs = tuple(attrs) self.extras = Requirement.parse(("x[%s]" % ','.join(extras))).extras self.dist = dist def __str__(self): s = "%s = %s" % (self.name, self.module_name) if self.attrs: s += ':' + '.'.join(self.attrs) if self.extras: s += ' [%s]' % ','.join(self.extras) return s def __repr__(self): return "EntryPoint.parse(%r)" % str(self) def load(self, require=True, *args, **kwargs): """ Require packages for this EntryPoint, then resolve it. """ if not require or args or kwargs: warnings.warn( "Parameters to load are deprecated. Call .resolve and " ".require separately.", DeprecationWarning, stacklevel=2, ) if require: self.require(*args, **kwargs) return self.resolve() def resolve(self): """ Resolve the entry point from its module and attrs. """ module = __import__(self.module_name, fromlist=['__name__'], level=0) try: return functools.reduce(getattr, self.attrs, module) except AttributeError as exc: raise ImportError(str(exc)) def require(self, env=None, installer=None): if self.extras and not self.dist: raise UnknownExtra("Can't require() without a distribution", self) reqs = self.dist.requires(self.extras) items = working_set.resolve(reqs, env, installer) list(map(working_set.add, items)) pattern = re.compile( r'\s*' r'(?P<name>.+?)\s*' r'=\s*' r'(?P<module>[\w.]+)\s*' r'(:\s*(?P<attr>[\w.]+))?\s*' r'(?P<extras>\[.*\])?\s*$' ) @classmethod def parse(cls, src, dist=None): """Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1, extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional """ m = cls.pattern.match(src) if not m: msg = "EntryPoint must be in 'name=module:attrs [extras]' format" raise ValueError(msg, src) res = m.groupdict() extras = cls._parse_extras(res['extras']) attrs = res['attr'].split('.') if res['attr'] else () return cls(res['name'], res['module'], attrs, extras, dist) @classmethod def _parse_extras(cls, extras_spec): if not extras_spec: return () req = Requirement.parse('x' + extras_spec) if req.specs: raise ValueError() return req.extras @classmethod def parse_group(cls, group, lines, dist=None): """Parse an entry point group""" if not MODULE(group): raise ValueError("Invalid group name", group) this = {} for line in yield_lines(lines): ep = cls.parse(line, dist) if ep.name in this: raise ValueError("Duplicate entry point", group, ep.name) this[ep.name]=ep return this @classmethod def parse_map(cls, data, dist=None): """Parse a map of entry point groups""" if isinstance(data, dict): data = data.items() else: data = split_sections(data) maps = {} for group, lines in data: if group is None: if not lines: continue raise ValueError("Entry points must be listed in groups") group = group.strip() if group in maps: raise ValueError("Duplicate group name", group) maps[group] = cls.parse_group(group, lines, dist) return maps def _remove_md5_fragment(location): if not location: return '' parsed = urllib.parse.urlparse(location) if parsed[-1].startswith('md5='): return urllib.parse.urlunparse(parsed[:-1] + ('',)) return location def _version_from_file(lines): """ Given an iterable of lines from a Metadata file, return the value of the Version field, if present, or None otherwise. """ is_version_line = lambda line: line.lower().startswith('version:') version_lines = filter(is_version_line, lines) line = next(iter(version_lines), '') _, _, value = line.partition(':') return safe_version(value.strip()) or None class Distribution(object): """Wrap an actual or potential sys.path entry w/metadata""" PKG_INFO = 'PKG-INFO' def __init__(self, location=None, metadata=None, project_name=None, version=None, py_version=PY_MAJOR, platform=None, precedence=EGG_DIST): self.project_name = safe_name(project_name or 'Unknown') if version is not None: self._version = safe_version(version) self.py_version = py_version self.platform = platform self.location = location self.precedence = precedence self._provider = metadata or empty_provider @classmethod def from_location(cls, location, basename, metadata=None, **kw): project_name, version, py_version, platform = [None]*4 basename, ext = os.path.splitext(basename) if ext.lower() in _distributionImpl: cls = _distributionImpl[ext.lower()] match = EGG_NAME(basename) if match: project_name, version, py_version, platform = match.group( 'name', 'ver', 'pyver', 'plat' ) return cls( location, metadata, project_name=project_name, version=version, py_version=py_version, platform=platform, **kw )._reload_version() def _reload_version(self): return self @property def hashcmp(self): return ( self.parsed_version, self.precedence, self.key, _remove_md5_fragment(self.location), self.py_version or '', self.platform or '', ) def __hash__(self): return hash(self.hashcmp) def __lt__(self, other): return self.hashcmp < other.hashcmp def __le__(self, other): return self.hashcmp <= other.hashcmp def __gt__(self, other): return self.hashcmp > other.hashcmp def __ge__(self, other): return self.hashcmp >= other.hashcmp def __eq__(self, other): if not isinstance(other, self.__class__): # It's not a Distribution, so they are not equal return False return self.hashcmp == other.hashcmp def __ne__(self, other): return not self == other # These properties have to be lazy so that we don't have to load any # metadata until/unless it's actually needed. (i.e., some distributions # may not know their name or version without loading PKG-INFO) @property def key(self): try: return self._key except AttributeError: self._key = key = self.project_name.lower() return key @property def parsed_version(self): if not hasattr(self, "_parsed_version"): self._parsed_version = parse_version(self.version) return self._parsed_version def _warn_legacy_version(self): LV = packaging.version.LegacyVersion is_legacy = isinstance(self._parsed_version, LV) if not is_legacy: return # While an empty version is technically a legacy version and # is not a valid PEP 440 version, it's also unlikely to # actually come from someone and instead it is more likely that # it comes from setuptools attempting to parse a filename and # including it in the list. So for that we'll gate this warning # on if the version is anything at all or not. if not self.version: return tmpl = textwrap.dedent(""" '{project_name} ({version})' is being parsed as a legacy, non PEP 440, version. You may find odd behavior and sort order. In particular it will be sorted as less than 0.0. It is recommended to migrate to PEP 440 compatible versions. """).strip().replace('\n', ' ') warnings.warn(tmpl.format(**vars(self)), PEP440Warning) @property def version(self): try: return self._version except AttributeError: version = _version_from_file(self._get_metadata(self.PKG_INFO)) if version is None: tmpl = "Missing 'Version:' header and/or %s file" raise ValueError(tmpl % self.PKG_INFO, self) return version @property def _dep_map(self): try: return self.__dep_map except AttributeError: dm = self.__dep_map = {None: []} for name in 'requires.txt', 'depends.txt': for extra, reqs in split_sections(self._get_metadata(name)): if extra: if ':' in extra: extra, marker = extra.split(':', 1) if invalid_marker(marker): # XXX warn reqs=[] elif not evaluate_marker(marker): reqs=[] extra = safe_extra(extra) or None dm.setdefault(extra,[]).extend(parse_requirements(reqs)) return dm def requires(self, extras=()): """List of Requirements needed for this distro if `extras` are used""" dm = self._dep_map deps = [] deps.extend(dm.get(None, ())) for ext in extras: try: deps.extend(dm[safe_extra(ext)]) except KeyError: raise UnknownExtra( "%s has no such extra feature %r" % (self, ext) ) return deps def _get_metadata(self, name): if self.has_metadata(name): for line in self.get_metadata_lines(name): yield line def activate(self, path=None): """Ensure distribution is importable on `path` (default=sys.path)""" if path is None: path = sys.path self.insert_on(path, replace=True) if path is sys.path: fixup_namespace_packages(self.location) for pkg in self._get_metadata('namespace_packages.txt'): if pkg in sys.modules: declare_namespace(pkg) def egg_name(self): """Return what this distribution's standard .egg filename should be""" filename = "%s-%s-py%s" % ( to_filename(self.project_name), to_filename(self.version), self.py_version or PY_MAJOR ) if self.platform: filename += '-' + self.platform return filename def __repr__(self): if self.location: return "%s (%s)" % (self, self.location) else: return str(self) def __str__(self): try: version = getattr(self, 'version', None) except ValueError: version = None version = version or "[unknown version]" return "%s %s" % (self.project_name, version) def __getattr__(self, attr): """Delegate all unrecognized public attributes to .metadata provider""" if attr.startswith('_'): raise AttributeError(attr) return getattr(self._provider, attr) @classmethod def from_filename(cls, filename, metadata=None, **kw): return cls.from_location( _normalize_cached(filename), os.path.basename(filename), metadata, **kw ) def as_requirement(self): """Return a ``Requirement`` that matches this distribution exactly""" if isinstance(self.parsed_version, packaging.version.Version): spec = "%s==%s" % (self.project_name, self.parsed_version) else: spec = "%s===%s" % (self.project_name, self.parsed_version) return Requirement.parse(spec) def load_entry_point(self, group, name): """Return the `name` entry point of `group` or raise ImportError""" ep = self.get_entry_info(group, name) if ep is None: raise ImportError("Entry point %r not found" % ((group, name),)) return ep.load() def get_entry_map(self, group=None): """Return the entry point map for `group`, or the full entry map""" try: ep_map = self._ep_map except AttributeError: ep_map = self._ep_map = EntryPoint.parse_map( self._get_metadata('entry_points.txt'), self ) if group is not None: return ep_map.get(group,{}) return ep_map def get_entry_info(self, group, name): """Return the EntryPoint object for `group`+`name`, or ``None``""" return self.get_entry_map(group).get(name) def insert_on(self, path, loc=None, replace=False): """Insert self.location in path before its nearest parent directory""" loc = loc or self.location if not loc: return nloc = _normalize_cached(loc) bdir = os.path.dirname(nloc) npath= [(p and _normalize_cached(p) or p) for p in path] for p, item in enumerate(npath): if item == nloc: break elif item == bdir and self.precedence == EGG_DIST: # if it's an .egg, give it precedence over its directory if path is sys.path: self.check_version_conflict() path.insert(p, loc) npath.insert(p, nloc) break else: if path is sys.path: self.check_version_conflict() if replace: path.insert(0, loc) else: path.append(loc) return # p is the spot where we found or inserted loc; now remove duplicates while True: try: np = npath.index(nloc, p+1) except ValueError: break else: del npath[np], path[np] # ha! p = np return def check_version_conflict(self): if self.key == 'setuptools': # ignore the inevitable setuptools self-conflicts :( return nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt')) loc = normalize_path(self.location) for modname in self._get_metadata('top_level.txt'): if (modname not in sys.modules or modname in nsp or modname in _namespace_packages): continue if modname in ('pkg_resources', 'setuptools', 'site'): continue fn = getattr(sys.modules[modname], '__file__', None) if fn and (normalize_path(fn).startswith(loc) or fn.startswith(self.location)): continue issue_warning( "Module %s was already imported from %s, but %s is being added" " to sys.path" % (modname, fn, self.location), ) def has_version(self): try: self.version except ValueError: issue_warning("Unbuilt egg for " + repr(self)) return False return True def clone(self,**kw): """Copy this distribution, substituting in any changed keyword args""" names = 'project_name version py_version platform location precedence' for attr in names.split(): kw.setdefault(attr, getattr(self, attr, None)) kw.setdefault('metadata', self._provider) return self.__class__(**kw) @property def extras(self): return [dep for dep in self._dep_map if dep] class EggInfoDistribution(Distribution): def _reload_version(self): """ Packages installed by distutils (e.g. numpy or scipy), which uses an old safe_version, and so their version numbers can get mangled when converted to filenames (e.g., 1.11.0.dev0+2329eae to 1.11.0.dev0_2329eae). These distributions will not be parsed properly downstream by Distribution and safe_version, so take an extra step and try to get the version number from the metadata file itself instead of the filename. """ md_version = _version_from_file(self._get_metadata(self.PKG_INFO)) if md_version: self._version = md_version return self class DistInfoDistribution(Distribution): """Wrap an actual or potential sys.path entry w/metadata, .dist-info style""" PKG_INFO = 'METADATA' EQEQ = re.compile(r"([\(,])\s*(\d.*?)\s*([,\)])") @property def _parsed_pkg_info(self): """Parse and cache metadata""" try: return self._pkg_info except AttributeError: metadata = self.get_metadata(self.PKG_INFO) self._pkg_info = email.parser.Parser().parsestr(metadata) return self._pkg_info @property def _dep_map(self): try: return self.__dep_map except AttributeError: self.__dep_map = self._compute_dependencies() return self.__dep_map def _compute_dependencies(self): """Recompute this distribution's dependencies.""" dm = self.__dep_map = {None: []} reqs = [] # Including any condition expressions for req in self._parsed_pkg_info.get_all('Requires-Dist') or []: reqs.extend(parse_requirements(req)) def reqs_for_extra(extra): for req in reqs: if not req.marker or req.marker.evaluate({'extra': extra}): yield req common = frozenset(reqs_for_extra(None)) dm[None].extend(common) for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []: extra = safe_extra(extra.strip()) dm[extra] = list(frozenset(reqs_for_extra(extra)) - common) return dm _distributionImpl = { '.egg': Distribution, '.egg-info': EggInfoDistribution, '.dist-info': DistInfoDistribution, } def issue_warning(*args,**kw): level = 1 g = globals() try: # find the first stack frame that is *not* code in # the pkg_resources module, to use for the warning while sys._getframe(level).f_globals is g: level += 1 except ValueError: pass warnings.warn(stacklevel=level + 1, *args, **kw) class RequirementParseError(ValueError): def __str__(self): return ' '.join(self.args) def parse_requirements(strs): """Yield ``Requirement`` objects for each specification in `strs` `strs` must be a string, or a (possibly-nested) iterable thereof. """ # create a steppable iterator, so we can handle \-continuations lines = iter(yield_lines(strs)) for line in lines: # Drop comments -- a hash without a space may be in a URL. if ' #' in line: line = line[:line.find(' #')] # If there is a line continuation, drop it, and append the next line. if line.endswith('\\'): line = line[:-2].strip() line += next(lines) yield Requirement(line) class Requirement(packaging.requirements.Requirement): def __init__(self, requirement_string): """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!""" try: super(Requirement, self).__init__(requirement_string) except packaging.requirements.InvalidRequirement as e: raise RequirementParseError(str(e)) self.unsafe_name = self.name project_name = safe_name(self.name) self.project_name, self.key = project_name, project_name.lower() self.specs = [ (spec.operator, spec.version) for spec in self.specifier] self.extras = tuple(map(safe_extra, self.extras)) self.hashCmp = ( self.key, self.specifier, frozenset(self.extras), str(self.marker) if self.marker else None, ) self.__hash = hash(self.hashCmp) def __eq__(self, other): return ( isinstance(other, Requirement) and self.hashCmp == other.hashCmp ) def __ne__(self, other): return not self == other def __contains__(self, item): if isinstance(item, Distribution): if item.key != self.key: return False item = item.version # Allow prereleases always in order to match the previous behavior of # this method. In the future this should be smarter and follow PEP 440 # more accurately. return self.specifier.contains(item, prereleases=True) def __hash__(self): return self.__hash def __repr__(self): return "Requirement.parse(%r)" % str(self) @staticmethod def parse(s): req, = parse_requirements(s) return req def _get_mro(cls): """Get an mro for a type or classic class""" if not isinstance(cls, type): class cls(cls, object): pass return cls.__mro__[1:] return cls.__mro__ def _find_adapter(registry, ob): """Return an adapter factory for `ob` from `registry`""" for t in _get_mro(getattr(ob, '__class__', type(ob))): if t in registry: return registry[t] def ensure_directory(path): """Ensure that the parent directory of `path` exists""" dirname = os.path.dirname(path) if not os.path.isdir(dirname): os.makedirs(dirname) def _bypass_ensure_directory(path): """Sandbox-bypassing version of ensure_directory()""" if not WRITE_SUPPORT: raise IOError('"os.mkdir" not supported on this platform.') dirname, filename = split(path) if dirname and filename and not isdir(dirname): _bypass_ensure_directory(dirname) mkdir(dirname, 0o755) def split_sections(s): """Split a string or iterable thereof into (section, content) pairs Each ``section`` is a stripped version of the section header ("[section]") and each ``content`` is a list of stripped lines excluding blank lines and comment-only lines. If there are any such lines before the first section header, they're returned in a first ``section`` of ``None``. """ section = None content = [] for line in yield_lines(s): if line.startswith("["): if line.endswith("]"): if section or content: yield section, content section = line[1:-1].strip() content = [] else: raise ValueError("Invalid section heading", line) else: content.append(line) # wrap up last segment yield section, content def _mkstemp(*args,**kw): old_open = os.open try: # temporarily bypass sandboxing os.open = os_open return tempfile.mkstemp(*args,**kw) finally: # and then put it back os.open = old_open # Silence the PEP440Warning by default, so that end users don't get hit by it # randomly just because they use pkg_resources. We want to append the rule # because we want earlier uses of filterwarnings to take precedence over this # one. warnings.filterwarnings("ignore", category=PEP440Warning, append=True) # from jaraco.functools 1.3 def _call_aside(f, *args, **kwargs): f(*args, **kwargs) return f @_call_aside def _initialize(g=globals()): "Set up global resource manager (deliberately not state-saved)" manager = ResourceManager() g['_manager'] = manager for name in dir(manager): if not name.startswith('_'): g[name] = getattr(manager, name) @_call_aside def _initialize_master_working_set(): """ Prepare the master working set and make the ``require()`` API available. This function has explicit effects on the global state of pkg_resources. It is intended to be invoked once at the initialization of this module. Invocation by other packages is unsupported and done at their own risk. """ working_set = WorkingSet._build_master() _declare_state('object', working_set=working_set) require = working_set.require iter_entry_points = working_set.iter_entry_points add_activation_listener = working_set.subscribe run_script = working_set.run_script # backward compatibility run_main = run_script # Activate all distributions already on sys.path, and ensure that # all distributions added to the working set in the future (e.g. by # calling ``require()``) will get activated as well. add_activation_listener(lambda dist: dist.activate()) working_set.entries=[] # match order list(map(working_set.add_entry, sys.path)) globals().update(locals())
[ "donald@stufft.io" ]
donald@stufft.io
1de4f9c41e3447d40f2cac71a2bf89f5d3c2737d
44cb69a5ea67e60289e33b3228b79d3c8fd36661
/core/migrations/0093_historique_cnl_fiches.py
5a81eb63bb8a302037b17b5b5d4185969dadb70a
[]
no_license
zedkaria-bel/ah_project
bc6d79acf3f419f9fdc45189d6b653ae84709e42
9dae7435ca6670006525eeda881fcea64c0557d1
refs/heads/master
2023-06-24T21:17:27.286727
2021-07-28T16:15:48
2021-07-28T16:15:48
381,800,444
0
0
null
null
null
null
UTF-8
Python
false
false
960
py
# Generated by Django 3.2 on 2021-06-13 12:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0092_historique_affect_quota'), ] operations = [ migrations.CreateModel( name='HISTORIQUE_CNL_FICHES', fields=[ ('date_last_cnl', models.DateTimeField(auto_now=True, db_column='DATE LAST CNL', primary_key=True, serialize=False)), ('fiches_from', models.PositiveIntegerField(blank=True, db_column='FROM', null=True)), ('fiches_until', models.PositiveIntegerField(blank=True, db_column='UNTIL', null=True)), ('cause', models.TextField(blank=True, db_column='CAUSE CNL', null=True)), ('obs', models.TextField(blank=True, db_column='OBS', null=True)), ], options={ 'db_table': 'HISTORIQUE_CNL_FICHES', }, ), ]
[ "zaki.198@outlook.fr" ]
zaki.198@outlook.fr
dbce952896039122cfae5c775eb8c254b577891b
706844227f31f23ac3d084992849921d57f8af6c
/tests/test_rosimport/subtests/test_rosmsg_importlib.py
c3de2e51d37f967478d1decfdcd7d2dc044aed7b
[ "MIT" ]
permissive
pyros-dev/rosimport
044375286b493f1adbcd10984e539b43db7f26bf
c63e4769650b1cf19f23fbaa65a356ffae20a536
refs/heads/master
2022-07-12T13:06:33.032573
2019-06-05T09:39:20
2019-06-05T09:39:20
95,618,041
5
0
MIT
2022-06-25T07:07:41
2017-06-28T01:57:22
Python
UTF-8
Python
false
false
22,007
py
from __future__ import absolute_import, division, print_function """ Testing dynamic import with importlib """ import os import sys import runpy import logging.config logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', } }, 'root': { 'handlers': ['console'], 'level': 'DEBUG', }, }) # Relying on basic unittest first, to be able to easily switch the test framework in case of import conflicts. import unittest # Ref : http://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path import importlib import site # Importing importer module from rosimport import RosImporter # importlib # https://pymotw.com/3/importlib/index.html # https://pymotw.com/2/importlib/index.html # # Note : we cannot assume anything about import implementation (different python version, different version of pytest) # => we need to test them all... # from ._utils import ( print_importers, BaseMsgSubTestCase, BaseSrvSubTestCase, ) class TestImportLibMsg(BaseMsgSubTestCase): rosdeps_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'rosdeps') # importer instance rosimporter = RosImporter() @classmethod def setUpClass(cls): # This is used for message definitions, not for python code site.addsitedir(cls.rosdeps_path) cls.rosimporter.__enter__() @classmethod def tearDownClass(cls): cls.rosimporter.__exit__(None, None, None) @unittest.skipIf(not hasattr(importlib, '__import__'), reason="importlib does not have attribute __import__") def test_importlib_import_absolute_msg(self): # Verify that files exists and are importable std_msgs = importlib.__import__('std_msgs.msg') std_msgs = std_msgs.msg self.assert_std_message_classes(std_msgs.Bool, std_msgs.Header) @unittest.skipIf(not hasattr(importlib, '__import__'), reason="importlib does not have attribute __import__") def test_importlib_import_absolute_class_raises(self): with self.assertRaises(ImportError): importlib.__import__('std_msgs.msg.Bool') # BROKEN 3.4 ? @unittest.skipIf(not hasattr(importlib, '__import__'), reason="importlib does not have attribute __import__") def test_importlib_import_relative_msg(self): # Verify that files exists and are importable subtest_msgs = importlib.__import__('msg', globals=globals(), level=1) test_msgs = importlib.__import__('test_rosimport.msg') test_msgs = test_msgs.msg self.assert_test_message_classes(subtest_msgs.SubTestMsg, subtest_msgs.SubTestMsgDeps, test_msgs.TestRosMsgDeps, test_msgs.TestRosMsg) # BROKEN 3.4 ? @unittest.skipIf(not hasattr(importlib, '__import__'), reason="importlib does not have attribute __import__") def test_importlib_import_relative_class_raises(self): assert __package__ with self.assertRaises(ImportError): importlib.__import__('msg.SubTestMsg', globals=globals(), level=1) # UNTESTED (do we care ?) # @unittest.skipIf(not hasattr(importlib, 'find_loader') or not hasattr(importlib, 'load_module'), # reason="importlib does not have attribute find_loader or load_module") # def test_importlib_loadmodule_absolute_msg(self): # # Verify that files exists and are dynamically importable # pkg_list = 'std_msgs.msg'.split('.')[:-1] # mod_list = 'std_msgs.msg'.split('.')[1:] # pkg = None # for pkg_name, mod_name in zip(pkg_list, mod_list): # pkg_loader = importlib.find_loader(pkg_name, pkg.__path__ if pkg else None) # pkg = pkg_loader.load_module(mod_name) # # std_msgs = pkg # # self.assert_std_message_classes(std_msgs.Bool, std_msgs.Header) # # # TODO : implement some differences and check we get them... # if hasattr(importlib, 'reload'): # recent version of importlib # # attempting to reload # importlib.reload(std_msgs) # else: # pass # # @unittest.skipIf(not hasattr(importlib, 'find_loader') or not hasattr(importlib, 'load_module'), # reason="importlib does not have attribute find_loader or load_module") # def test_importlib_loadmodule_absolute_class(self): # # Verify that files exists and are dynamically importable # pkg_list = 'std_msgs.msg.Bool'.split('.')[:-1] # mod_list = 'std_msgs.msg.Bool'.split('.')[1:] # pkg = None # for pkg_name, mod_name in zip(pkg_list, mod_list): # pkg_loader = importlib.find_loader(pkg_name, pkg.__path__ if pkg else None) # pkg = pkg_loader.load_module(mod_name) # # Bool = pkg # # self.assert_std_message_classes(Bool, Header) # # # TODO : implement some differences and check we get them... # if hasattr(importlib, 'reload'): # recent version of importlib # # attempting to reload # importlib.reload(Bool) # else: # pass # # @unittest.skipIf(not hasattr(importlib, 'find_loader') or not hasattr(importlib, 'load_module'), # reason="importlib does not have attribute find_loader or load_module") # def test_importlib_loadmodule_relative_msg(self): # # Verify that files exists and are dynamically importable # pkg_list = '.msg'.split('.')[:-1] # mod_list = '.msg'.split('.')[1:] # pkg = None # for pkg_name, mod_name in zip(pkg_list, mod_list): # pkg_loader = importlib.find_loader(pkg_name, pkg.__path__ if pkg else None) # pkg = pkg_loader.load_module(mod_name) # # test_msgs = pkg # # self.assertTrue(test_msgs is not None) # self.assertTrue(test_msgs.TestMsg is not None) # self.assertTrue(callable(test_msgs.TestMsg)) # self.assertTrue(test_msgs.TestMsg._type == 'rosimport/TestMsg') # careful between ros package name and python package name # # # use it ! # self.assertTrue(test_msgs.TestMsg(test_bool=True, test_string='Test').test_bool) # # # TODO : implement some differences and check we get them... # if hasattr(importlib, 'reload'): # recent version of importlib # # attempting to reload # importlib.reload(test_msgs) # else: # pass # # @unittest.skipIf(not hasattr(importlib, 'find_loader') or not hasattr(importlib, 'load_module'), # reason="importlib does not have attribute find_loader or load_module") # def test_importlib_loadmodule_relative_class(self): # # Verify that files exists and are dynamically importable # pkg_list = '.msg.TestMsg'.split('.')[:-1] # mod_list = '.msg.TestMsg'.split('.')[1:] # pkg = None # for pkg_name, mod_name in zip(pkg_list, mod_list): # pkg_loader = importlib.find_loader(pkg_name, pkg.__path__ if pkg else None) # pkg = pkg_loader.load_module(mod_name) # # TestMsg = pkg # # self.assert_test_message_classes(TestMsg, TestMsgDeps, TestRosMsgDeps, TestRosMsg) # # # TODO : implement some differences and check we get them... # if hasattr(importlib, 'reload'): # recent version of importlib # # attempting to reload # importlib.reload(TestMsg) # else: # pass # TODO : dynamic using module_spec (python 3.5) @unittest.skipIf(not hasattr(importlib, 'import_module'), reason="importlib does not have attribute import_module") def test_importlib_importmodule_absolute_msg(self): # Verify that files exists and are dynamically importable std_msgs = importlib.import_module('std_msgs.msg') self.assert_std_message_classes(std_msgs.Bool, std_msgs.Header) if hasattr(importlib, 'reload'): # recent version of importlib # attempting to reload importlib.reload(std_msgs) else: pass assert std_msgs is not None @unittest.skipIf(not hasattr(importlib, 'import_module'), reason="importlib does not have attribute import_module") def test_importlib_importmodule_absolute_class_raises(self): with self.assertRaises(ImportError): importlib.import_module('std_msgs.msg.Bool') @unittest.skipIf(not hasattr(importlib, 'import_module'), reason="importlib does not have attribute import_module") def test_importlib_importmodule_relative_msg(self): assert __package__ # Verify that files exists and are dynamically importable subtest_msgs = importlib.import_module('.msg', package=__package__) test_msgs = importlib.import_module('test_rosimport.msg', package=__package__) self.assert_test_message_classes(subtest_msgs.SubTestMsg, subtest_msgs.SubTestMsgDeps, test_msgs.TestRosMsgDeps, test_msgs.TestRosMsg) if hasattr(importlib, 'reload'): # recent version of importlib # attempting to reload importlib.reload(test_msgs) else: pass assert test_msgs is not None @unittest.skipIf(not hasattr(importlib, 'import_module'), reason="importlib does not have attribute import_module") def test_importlib_importmodule_relative_msg_from_absolute(self): assert __package__ # Verify that files exists and are dynamically importable subtest_msgs = importlib.import_module('test_rosimport.subtests.msg') test_msgs = importlib.import_module('test_rosimport.msg') self.assert_test_message_classes(subtest_msgs.SubTestMsg, subtest_msgs.SubTestMsgDeps, test_msgs.TestRosMsgDeps, test_msgs.TestRosMsg) if hasattr(importlib, 'reload'): # recent version of importlib # attempting to reload importlib.reload(test_msgs) else: pass assert test_msgs is not None @unittest.skipIf(not hasattr(importlib, 'import_module'), reason="importlib does not have attribute import_module") def test_importlib_importmodule_relative_class_raises(self): assert __package__ with self.assertRaises(ImportError): importlib.import_module('.msg.TestMsg', package=__package__) # TODO # def test_double_import_uses_cache(self): # # print_importers() # # Verify that files exists and are importable # import std_msgs.msg as std_msgs # # self.assertTrue(std_msgs.Bool is not None) # self.assertTrue(callable(std_msgs.Bool)) # self.assertTrue(std_msgs.Bool._type == 'std_msgs/Bool') # # import std_msgs.msg as std_msgs2 # # self.assertTrue(std_msgs == std_msgs2) class TestImportLibSrv(BaseSrvSubTestCase): ros_comm_msgs_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'rosdeps', 'ros_comm_msgs') # For dependencies rosdeps_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'rosdeps') rosimporter = RosImporter() @classmethod def setUpClass(cls): # This is used for message definitions, not for python code site.addsitedir(cls.rosdeps_path) site.addsitedir(cls.ros_comm_msgs_path) cls.rosimporter.__enter__() @classmethod def tearDownClass(cls): cls.rosimporter.__exit__(None, None, None) @unittest.skipIf(not hasattr(importlib, '__import__'), reason="importlib does not have attribute __import__") def test_importlib_import_absolute_srv(self): # Verify that files exists and are importable # __import__ checks sys.modules by itself # but the test is not reflecting anything if we use the already loaded module. if sys.modules.get('std_srvs.srv'): #TODO : EVERYWHERE ! raise unittest.SkipTest("module previously loaded".format('std_srvs.srv')) else: std_srvs = importlib.__import__('std_srvs.srv') std_srvs = std_srvs.srv self.assert_std_service_classes(std_srvs.SetBool, std_srvs.SetBoolRequest, std_srvs.SetBoolResponse) @unittest.skipIf(not hasattr(importlib, '__import__'), reason="importlib does not have attribute __import__") def test_importlib_import_absolute_class_raises(self): with self.assertRaises(ImportError): importlib.__import__('std_srvs.srv.SetBool') # BROKEN 3.4 ? @unittest.skipIf(not hasattr(importlib, '__import__'), reason="importlib does not have attribute __import__") def test_importlib_import_relative_srv(self): # Verify that files exists and are importable subtest_srvs = importlib.__import__('srv', globals=globals(), level=1) test_msgs = importlib.__import__('test_rosimport.msg') test_msgs = test_msgs.msg self.assert_test_service_classes(subtest_srvs.SubTestSrv, subtest_srvs.SubTestSrvRequest, subtest_srvs.SubTestSrvResponse, subtest_srvs.SubTestSrvDeps, subtest_srvs.SubTestSrvDepsRequest, subtest_srvs.SubTestSrvDepsResponse, test_msgs.TestRosMsgDeps, test_msgs.TestRosMsg) # UNTESTED : do we care ? # @unittest.skipIf(not hasattr(importlib, '__import__'), reason="importlib does not have attribute __import__") # def test_importlib_import_relative_class_raises(self): # assert __package__ # with self.assertRaises(ImportError): # importlib.__import__('srv.SetBool', globals=globals(), level=1) # # @unittest.skipIf(not hasattr(importlib, 'find_loader') or not hasattr(importlib, 'load_module'), # reason="importlib does not have attribute find_loader or load_module") # def test_importlib_loadmodule_absolute_srv(self): # # Verify that files exists and are dynamically importable # pkg_list = 'std_srvs.srv'.split('.')[:-1] # mod_list = 'std_srvs.srv'.split('.')[1:] # pkg = None # for pkg_name, mod_name in zip(pkg_list, mod_list): # pkg_loader = importlib.find_loader(pkg_name, pkg.__path__ if pkg else None) # pkg = pkg_loader.load_module(mod_name) # # std_srvs = pkg # # self.assert_std_service_classes(std_srvs.SetBool, std_srvs.SetBoolRequest, std_srvs.SetBoolResponse) # # # TODO : implement some differences and check we get them... # if hasattr(importlib, 'reload'): # recent version of importlib # # attempting to reload # importlib.reload(std_srvs) # else: # pass # # @unittest.skipIf(not hasattr(importlib, 'find_loader') or not hasattr(importlib, 'load_module'), # reason="importlib does not have attribute find_loader or load_module") # def test_importlib_loadmodule_absolute_class(self): # # Verify that files exists and are dynamically importable # pkg_list = 'std_srvs.srv.SetBool'.split('.')[:-1] # mod_list = 'std_srvs.srv.SetBool'.split('.')[1:] # pkg = None # for pkg_name, mod_name in zip(pkg_list, mod_list): # pkg_loader = importlib.find_loader(pkg_name, pkg.__path__ if pkg else None) # pkg = pkg_loader.load_module(mod_name) # # SetBool = pkg # # self.assert_test_service_classes(SetBool, SetBoolRequest, SetBoolResponse) # # # TODO : implement some differences and check we get them... # if hasattr(importlib, 'reload'): # recent version of importlib # # attempting to reload # importlib.reload(SetBool) # else: # pass # # @unittest.skipIf(not hasattr(importlib, 'find_loader') or not hasattr(importlib, 'load_module'), # reason="importlib does not have attribute find_loader or load_module") # def test_importlib_loadmodule_relative_srv(self): # # Verify that files exists and are dynamically importable # pkg_list = '.srv'.split('.')[:-1] # mod_list = '.srv'.split('.')[1:] # pkg = None # for pkg_name, mod_name in zip(pkg_list, mod_list): # pkg_loader = importlib.find_loader(pkg_name, pkg.__path__ if pkg else None) # pkg = pkg_loader.load_module(mod_name) # # test_srvs = pkg # # self.assert_test_service_classes() # # # TODO : implement some differences and check we get them... # if hasattr(importlib, 'reload'): # recent version of importlib # # attempting to reload # importlib.reload(test_msgs) # else: # pass # # @unittest.skipIf(not hasattr(importlib, 'find_loader') or not hasattr(importlib, 'load_module'), # reason="importlib does not have attribute find_loader or load_module") # def test_importlib_loadmodule_relative_class(self): # # Verify that files exists and are dynamically importable # pkg_list = '.srv.TestSrv'.split('.')[:-1] # mod_list = '.srv.TestSrv'.split('.')[1:] # pkg = None # for pkg_name, mod_name in zip(pkg_list, mod_list): # pkg_loader = importlib.find_loader(pkg_name, pkg.__path__ if pkg else None) # pkg = pkg_loader.load_module(mod_name) # # TestSrv = pkg # # self.assert_test_service_classes() # # # TODO : implement some differences and check we get them... # if hasattr(importlib, 'reload'): # recent version of importlib # # attempting to reload # importlib.reload(TestSrv) # else: # pass # TODO : dynamic using module_spec (python 3.5) @unittest.skipIf(not hasattr(importlib, 'import_module'), reason="importlib does not have attribute import_module") def test_importlib_importmodule_absolute_srv(self): # Verify that files exists and are dynamically importable std_srvs = importlib.import_module('std_srvs.srv') self.assert_std_service_classes(std_srvs.SetBool, std_srvs.SetBoolRequest, std_srvs.SetBoolResponse) if hasattr(importlib, 'reload'): # recent version of importlib # attempting to reload importlib.reload(std_srvs) else: pass assert std_srvs is not None @unittest.skipIf(not hasattr(importlib, 'import_module'), reason="importlib does not have attribute import_module") def test_importlib_importmodule_absolute_class_raises(self): with self.assertRaises(ImportError): importlib.import_module('std_srvs.srv.SetBool') @unittest.skipIf(not hasattr(importlib, 'import_module'), reason="importlib does not have attribute import_module") def test_importlib_importmodule_relative_srv(self): assert __package__ # Verify that files exists and are dynamically importable subtest_srvs = importlib.import_module('.srv', package=__package__) test_msgs = importlib.import_module('test_rosimport.msg', package=__package__) self.assert_test_service_classes(subtest_srvs.SubTestSrv, subtest_srvs.SubTestSrvRequest, subtest_srvs.SubTestSrvResponse, subtest_srvs.SubTestSrvDeps, subtest_srvs.SubTestSrvDepsRequest, subtest_srvs.SubTestSrvDepsResponse, test_msgs.TestRosMsgDeps, test_msgs.TestRosMsg) if hasattr(importlib, 'reload'): # recent version of importlib # attempting to reload importlib.reload(subtest_srvs) else: pass assert subtest_srvs is not None @unittest.skipIf(not hasattr(importlib, 'import_module'), reason="importlib does not have attribute import_module") def test_importlib_importmodule_relative_srv_from_absolute(self): assert __package__ # Verify that files exists and are dynamically importable subtest_srvs = importlib.import_module('test_rosimport.subtests.srv') test_msgs = importlib.import_module('test_rosimport.msg') self.assert_test_service_classes(subtest_srvs.SubTestSrv, subtest_srvs.SubTestSrvRequest, subtest_srvs.SubTestSrvResponse, subtest_srvs.SubTestSrvDeps, subtest_srvs.SubTestSrvDepsRequest, subtest_srvs.SubTestSrvDepsResponse, test_msgs.TestRosMsgDeps, test_msgs.TestRosMsg) if hasattr(importlib, 'reload'): # recent version of importlib # attempting to reload importlib.reload(subtest_srvs) else: pass assert subtest_srvs is not None @unittest.skipIf(not hasattr(importlib, 'import_module'), reason="importlib does not have attribute import_module") def test_importlib_importmodule_relative_class_raises(self): assert __package__ with self.assertRaises(ImportError): importlib.import_module('.srv.TestSrv', package=__package__) # TODO # def test_double_import_uses_cache(self): # # print_importers() # # Verify that files exists and are importable # import std_msgs.msg as std_msgs # # self.assertTrue(std_msgs.Bool is not None) # self.assertTrue(callable(std_msgs.Bool)) # self.assertTrue(std_msgs.Bool._type == 'std_msgs/Bool') # # import std_msgs.msg as std_msgs2 # # self.assertTrue(std_msgs == std_msgs2) if __name__ == '__main__': import pytest pytest.main(['-s', '-x', __file__, '--boxed'])
[ "asmodehn@gmail.com" ]
asmodehn@gmail.com
fe4fc0a2431cbdd855e0f89420f67a080e64d4f2
5b37d86af518b90cb848233c7f5f53befc15a5ed
/x_vectors/models/LDE.py
f4848fdfea56cd1b6a54cf8b55ef6c3bdae176a3
[ "MIT" ]
permissive
taalua/x-vector-pytorch
45fce3606eeb0b9a996179a1e0242d62e8393bcd
7d86f78a1a70974df490ef7d2629de2d71dd1558
refs/heads/master
2023-07-21T04:47:45.596582
2021-08-25T17:58:58
2021-08-25T17:58:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,154
py
import torch from torch import nn import torch.nn.functional as F class LDE(nn.Module): def __init__(self, D, input_dim, with_bias=False, distance_type='norm', network_type='att', pooling='mean'): """LDE layer """ super(LDE, self).__init__() self.dic = nn.Parameter(torch.randn(D, input_dim)) # input_dim by D (dictionary components) nn.init.uniform_(self.dic.data, -1, 1) self.wei = nn.Parameter(torch.ones(D)) # non-negative assigning weight in Eq(4) in LDE paper if with_bias: # Eq(4) in LDE paper self.bias = nn.Parameter(torch.zeros(D)) else: self.bias = 0 assert distance_type == 'norm' or distance_type == 'sqr' if distance_type == 'norm': self.dis = lambda x: torch.norm(x, p=2, dim=-1) else: self.dis = lambda x: torch.sum(x**2, dim=-1) assert network_type == 'att' or network_type == 'lde' if network_type == 'att': self.norm = lambda x: F.softmax(-self.dis(x) * self.wei + self.bias, dim = -2) else: self.norm = lambda x: F.softmax(-self.dis(x) * (self.wei ** 2) + self.bias, dim = -1) assert pooling == 'mean' or pooling == 'mean+std' self.pool = pooling def forward(self, x): #print(x.size()) # (B, T, F) #print(self.dic.size()) # (D, F) r = x.view(x.size(0), x.size(1), 1, x.size(2)) - self.dic # residaul vector #print(r.size()) # (B, T, D, F) w = self.norm(r).view(r.size(0), r.size(1), r.size(2), 1) # numerator without r in Eq(5) in LDE paper #print(self.norm(r).size()) # (B, T, D) #print(w.size()) # (B, T, D, 1) w = w / (torch.sum(w, dim=1, keepdim=True) + 1e-9) #batch_size, timesteps, component # denominator of Eq(5) in LDE paper if self.pool == 'mean': x = torch.sum(w * r, dim=1) # Eq(5) in LDE paper else: x1 = torch.sum(w * r, dim=1) # Eq(5) in LDE paper x2 = torch.sqrt(torch.sum(w * r ** 2, dim=1)+1e-8) # std vector x = torch.cat([x1, x2], dim=-1) return x.view(x.size(0), -1)
[ "ristohinno@gmail.com" ]
ristohinno@gmail.com
ed1eb2d435c7405e2a444c9f298c172791d36066
ed291071decb3514b7f9f321e68fd57fb3c11ebc
/Python/594_longest-harmonious-subsequence.py
8455403cb0f23ad8ecc904e97ec7756a470bb9ad
[]
no_license
antonylu/leetcode2
d7b1681cc9477bb01619be26461634edbb85a4e5
a57282895fb213b68e5d81db301903721a92d80f
refs/heads/master
2021-11-25T01:30:56.358849
2021-11-19T08:32:12
2021-11-19T08:32:12
130,139,831
0
0
null
null
null
null
UTF-8
Python
false
false
1,234
py
""" https://leetcode.com/problems/longest-harmonious-subsequence/description/ We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1. Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences. Example 1: Input: [1,3,2,2,5,2,3,7] Output: 5 Explanation: The longest harmonious subsequence is [3,2,2,2,3]. Note: The length of the input array will not exceed 20,000. """ class Solution(object): def findLHS(self, nums): """ :type nums: List[int] :rtype: int """ # Approach #1, use collections.Counter() # # find continuous pair (i and i+1) and add these two counts # find the largest sum # # O(n), 13% from collections import Counter c = Counter(nums) ans = 0 for k,v in c.items(): if k+1 in c: ans = max(ans, v+c[k+1]) return ans if __name__ == '__main__': s = Solution() tc = [ [1,3,2,2,5,2,3,7] ] ans = [ 5 ] for i in range(len(tc)): r = s.findLHS(tc[i]) print (r) assert(r == ans[i])
[ "w3back@gmail.com" ]
w3back@gmail.com
49d2f10073d062a79cd03a3fbbd8320f30ec6ca1
685a1e32643bdcc3d1ba1fbd60521b5de4935e46
/anillimaye/conftest.py
f5a93c9d28fd7088c06d2113c3f4b0671ec6b6fb
[]
no_license
beingtmk/anillimaye
40a3213ec0f14c2d29f4481c860e418068a0137d
7799b8b82c7e8c52301b29c8adf056767521f3bf
refs/heads/master
2020-08-13T17:17:47.473380
2019-12-05T11:48:26
2019-12-05T11:48:26
215,006,896
1
1
null
2019-10-17T11:01:51
2019-10-14T09:50:50
Python
UTF-8
Python
false
false
424
py
import pytest from django.conf import settings from django.test import RequestFactory from anillimaye.users.tests.factories import UserFactory @pytest.fixture(autouse=True) def media_storage(settings, tmpdir): settings.MEDIA_ROOT = tmpdir.strpath @pytest.fixture def user() -> settings.AUTH_USER_MODEL: return UserFactory() @pytest.fixture def request_factory() -> RequestFactory: return RequestFactory()
[ "beingtmk@gmail.com" ]
beingtmk@gmail.com
b930827b1fac2672459bbc2f93e7763e9622631d
72c90301d4753c3d1534473196c6cb0b2f923bc8
/tests/clientlib_test.py
8e85e6c445f6488cad4b3951ea4bbf206afda340
[ "MIT" ]
permissive
KevinHock/pre-commit
ec5ab3725fe6678b16abb0978a7414de9babba3f
ab47d08a38c67d6e974295fb58af753b4e8930ad
refs/heads/master
2021-05-06T23:49:28.970479
2017-11-09T02:04:13
2017-11-09T02:04:34
110,043,358
3
2
null
2017-11-08T23:42:14
2017-11-08T23:42:14
null
UTF-8
Python
false
false
6,418
py
from __future__ import unicode_literals import pytest from pre_commit import schema from pre_commit.clientlib import check_language from pre_commit.clientlib import check_type_tag from pre_commit.clientlib import CONFIG_HOOK_DICT from pre_commit.clientlib import CONFIG_SCHEMA from pre_commit.clientlib import is_local_repo from pre_commit.clientlib import MANIFEST_SCHEMA from pre_commit.clientlib import validate_config_main from pre_commit.clientlib import validate_manifest_main from testing.util import get_resource_path def is_valid_according_to_schema(obj, obj_schema): try: schema.validate(obj, obj_schema) return True except schema.ValidationError: return False @pytest.mark.parametrize('value', ('not a language', 'python3')) def test_check_language_failures(value): with pytest.raises(schema.ValidationError): check_language(value) @pytest.mark.parametrize('value', ('definitely-not-a-tag', 'fiel')) def test_check_type_tag_failures(value): with pytest.raises(schema.ValidationError): check_type_tag(value) @pytest.mark.parametrize('value', ('python', 'node', 'pcre')) def test_check_language_ok(value): check_language(value) def test_is_local_repo(): assert is_local_repo({'repo': 'local'}) @pytest.mark.parametrize( ('args', 'expected_output'), ( (['.pre-commit-config.yaml'], 0), (['non_existent_file.yaml'], 1), ([get_resource_path('valid_yaml_but_invalid_config.yaml')], 1), ([get_resource_path('non_parseable_yaml_file.notyaml')], 1), ), ) def test_validate_config_main(args, expected_output): assert validate_config_main(args) == expected_output @pytest.mark.parametrize( ('config_obj', 'expected'), ( ([], False), ( {'repos': [{ 'repo': 'git@github.com:pre-commit/pre-commit-hooks', 'sha': 'cd74dc150c142c3be70b24eaf0b02cae9d235f37', 'hooks': [{'id': 'pyflakes', 'files': '\\.py$'}], }]}, True, ), ( {'repos': [{ 'repo': 'git@github.com:pre-commit/pre-commit-hooks', 'sha': 'cd74dc150c142c3be70b24eaf0b02cae9d235f37', 'hooks': [ { 'id': 'pyflakes', 'files': '\\.py$', 'args': ['foo', 'bar', 'baz'], }, ], }]}, True, ), ( {'repos': [{ 'repo': 'git@github.com:pre-commit/pre-commit-hooks', 'sha': 'cd74dc150c142c3be70b24eaf0b02cae9d235f37', 'hooks': [ { 'id': 'pyflakes', 'files': '\\.py$', # Exclude pattern must be a string 'exclude': 0, 'args': ['foo', 'bar', 'baz'], }, ], }]}, False, ), ), ) def test_config_valid(config_obj, expected): ret = is_valid_according_to_schema(config_obj, CONFIG_SCHEMA) assert ret is expected def test_config_with_local_hooks_definition_fails(): config_obj = {'repos': [{ 'repo': 'local', 'sha': 'foo', 'hooks': [{ 'id': 'do_not_commit', 'name': 'Block if "DO NOT COMMIT" is found', 'entry': 'DO NOT COMMIT', 'language': 'pcre', 'files': '^(.*)$', }], }]} with pytest.raises(schema.ValidationError): schema.validate(config_obj, CONFIG_SCHEMA) @pytest.mark.parametrize( 'config_obj', ( {'repos': [{ 'repo': 'local', 'hooks': [{ 'id': 'arg-per-line', 'name': 'Args per line hook', 'entry': 'bin/hook.sh', 'language': 'script', 'files': '', 'args': ['hello', 'world'], }], }]}, {'repos': [{ 'repo': 'local', 'hooks': [{ 'id': 'arg-per-line', 'name': 'Args per line hook', 'entry': 'bin/hook.sh', 'language': 'script', 'files': '', 'args': ['hello', 'world'], }], }]}, ), ) def test_config_with_local_hooks_definition_passes(config_obj): schema.validate(config_obj, CONFIG_SCHEMA) def test_config_schema_does_not_contain_defaults(): """Due to the way our merging works, if this schema has any defaults they will clobber potentially useful values in the backing manifest. #227 """ for item in CONFIG_HOOK_DICT.items: assert not isinstance(item, schema.Optional) @pytest.mark.parametrize( ('args', 'expected_output'), ( (['.pre-commit-hooks.yaml'], 0), (['non_existent_file.yaml'], 1), ([get_resource_path('valid_yaml_but_invalid_manifest.yaml')], 1), ([get_resource_path('non_parseable_yaml_file.notyaml')], 1), ), ) def test_validate_manifest_main(args, expected_output): assert validate_manifest_main(args) == expected_output @pytest.mark.parametrize( ('manifest_obj', 'expected'), ( ([], False), ( [{ 'id': 'a', 'name': 'b', 'entry': 'c', 'language': 'python', 'files': r'\.py$', }], True, ), ( [{ 'id': 'a', 'name': 'b', 'entry': 'c', 'language': 'python', 'language_version': 'python3.4', 'files': r'\.py$', }], True, ), ( # A regression in 0.13.5: always_run and files are permissible # together (but meaningless). In a future version upgrade this to # an error [{ 'id': 'a', 'name': 'b', 'entry': 'c', 'language': 'python', 'files': '', 'always_run': True, }], True, ), ), ) def test_valid_manifests(manifest_obj, expected): ret = is_valid_according_to_schema(manifest_obj, MANIFEST_SCHEMA) assert ret is expected
[ "asottile@umich.edu" ]
asottile@umich.edu
26f846a4808ea2539e46aa74dfc6fe820f4912eb
f7a718425de1447836b547f831a120937f1fcf40
/plumbum/instance.py
e75a9509bad09a3ff1264a9471f21337dcfe71f4
[ "BSD-3-Clause" ]
permissive
coyotevz/plumbum-old-1
ad8ce697ffb4cbd0a6f238f66a1c546800e47024
c0f769ca525298ab190592d0997575d917a4bed4
refs/heads/master
2021-01-20T10:50:32.516766
2016-11-18T04:20:32
2016-11-18T04:20:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
18,351
py
# -*- coding: utf-8 -*- """Plumbum Instance model and related APIs.""" import hashlib import os import threading from plumbum import log from plumbum.api import IInstanceSetupParticipant, ISystemInfoProvider from plumbum.config import (ChoiceOption, ConfigSection, Configuration, ConfigurationError, Option, PathOption) from plumbum.core import (Component, ComponentManager, ExtensionPoint, PlumbumError, implements) from plumbum.loader import load_components from plumbum.util import as_bool, lazy from plumbum.util.file import create_file, read_file # Content of the VERSION file in the instance _VERSION = 'Plumbum Instance Version 1' class PlumbumInstance(Component, ComponentManager): """Plumbum instance manager. Plumbum stores instance information in a PlumbumInstance. It consists of a directory structure containing among other things: * a configuration file, * instance-specific templates and plugins, * the SQLite database file in case the database backend is sqlite """ implements(ISystemInfoProvider) required = True system_info_providers = ExtensionPoint(ISystemInfoProvider) setup_participants = ExtensionPoint(IInstanceSetupParticipant) components_section = ConfigSection('components', """This section is used to enable or disable components provided by plugins, as well as by Plumbum itself. The component to enable/disable is specified via the name of the option. Whether its enalbed is determined by the option value; setting the value to `enabled` or `on` will enable the component, any other value (typically `disabled` or `off`) will disable the component. The option name is either the fully qualified name of the components or the module/package prefix of the component. The former enabled/disables a specific component, while the latter enables/disables any component in the specified package/module. Consider the following configuration snippet: {{{ [components] pb.report.ReportModule = disabled acct_mgr.* = enabled }}} This first option tells Plumbum to disable the report module. The second option instruct Plumbum to enable all components in the `acct_mgr` package. Note that the trailing willcard is required for module/package matching. To view the list of active components, go to the ''Plugins'' page on ''About Plumbum'' (requires `CONFIG_VIEW` [wiki:PlumbumPermissions permissions]). See also: PlumbumPlugins """) shared_plugins_dir = PathOption('inherit', 'plugins_dir', '', """Path to the //shared plugins directory//. Plugins in that directory are loaded in addition to those in the directory of the instance `plugins`, with this one taking precedence. """) #base_url = Option('plumbum', 'base_url', '', # """Reference URL for the Plumbum deployment. # This is the base URL that will be used when producing documents that # will be used outside of the web browsing context, like for example when # inserting URLs pointing to Plumbum resources in notification # e-mails.""") instance_name = Option('instance', 'name', 'My Store', """Name of the instance.""") instance_description = Option('instance', 'descr', 'My example store', """Short description of the instance.""") instance_admin = Option('instance', 'admin', '', """E-mail address of the instance's administrator.""") log_type = ChoiceOption('logging', 'log_type', log.LOG_TYPES + log.LOG_TYPE_ALIASES, """Logging facility to use. Should be one of (`none`, `file`, `stderr`, `syslog`, `winlog`).""") log_file = Option('logging', 'log_file', 'plumbum.log', """If `log_type` is `file`, this should be a path to the log-file. Relative paths are resolved relative to the `log` directory of the instance.""") log_level = ChoiceOption('logging', 'log_level', tuple(reversed(log.LOG_LEVELS)) + log.LOG_LEVEL_ALIASES, """Level of verbosity in log. Should be one of (`CRITICAL`, `ERROR`, `WARNING`, `INFO`, `DEBUG`).""") log_format = Option('logging', 'log_format', None, """Custom logging format. If nothing is set, the folowing will be used: `Plumbum[$(module)s] $(levelname)s: $(message)s` In addition to regular key names supported by the [http://docs.python.org/library/logging.html Python logger library] one could use: - `$(path)s` the path for the current instance - `$(basename)s` the last path component of the current instance - `$(instance)s` the instance name Note the usage of `$(...)s` instead of `%(...)s` s the latter form would be interpreded by the !ConfigParser itself. Example: `($(thread)d) PB[$(basename)s:$(module)s] $(levelname)s: $(message)s` """) def __init__(self, path, create=False, options=[]): """Initialize the Plumbum instance. :param path: the absolute path to the Plumbum instance :param create: if `True`, the instance is created and populated with default data; otherwise, the instance is expected to already exists. :param options: A list of `(section, name, value)` tuples that define configuration options """ ComponentManager.__init__(self) self.path = os.path.normpath(os.path.normcase(path)) self.log = None self.config = None if create: self.create(options) for setup_participant in self.setup_participants: setup_participant.instance_created() else: self.verify() self.setup_config() @lazy def name(self): """The instance name.""" return os.path.basename(self.path) @property def instance(self): """Property returning the `Instance` object, which is often required for functions and methods that take a `Component` instance.""" return self @property def system_info(self): """List of `(name, version)` tuple describing the name and version information of external packages used by Plumbum and plugins.""" info = [] for provider in self.system_info_providers: info.extend(provider.get_system_info() or []) return sorted(set(info), key=lambda name, ver: (name != 'Plumbum', name.lower()) ) # ISystemInfoProvider methods def get_system_info(self): yield 'Plumbum', self.plumbum_version yield 'Python', sys.version yield 'setuptools', setuptools.__version__ if pytz is not None: yield 'pytz', pytz.__version__ if hasattr(self, 'webfrontend_version'): yield self.webfrontend, self.webfrontend_version def component_activated(self, component): """Initialize additional member variables for components. Every component activated through the `Instance` object gets three member variabled: `instance` (the instance object), `config` (the instance configuration) and `log` (a logger object).""" component.instance = self component.config = self.config component.log = self.log def _component_name(self, name_or_class): name = name_or_class if not isinstance(name_or_class, str): name = name_or_class.__module__ + '.' + name_or_class.__name__ return name.lower() @lazy def _component_rules(self): _rules = {} for name, value in self.components_section.options(): name = name.rstrip('.*').lower() _rules[name] = as_bool(value) return _rules def is_component_enabled(self, cls): """Implemented to only allow activation of components that are not disabled in the configuration. This is called by the `ComponentManager` base class when a component is about to be activated. If this method returns `False`, the component does not get activated. If it returns `None`, the component only gets activated if it is located in the `plugins` directory of the instance. """ component_name = self._component_name(cls) rules = self._component_rules cname = component_name while cname: enabled = rules.get(cname) if enabled is not None: return enabled idx = cname.rfind('.') if idx < 0: break cname = cname[:idx] # By default, all components in the plumbum package are enabled except # tests return component_name.startswith('plumbum.') and \ not component_name.startswith('plumbum.test.') and \ not component_name.startswith('plumbum.tests.') or None def enable_component(self, cls): """Enable a component or module.""" self._component_rules[self._component_name(cls)] = True super(PlumbumInstance, self).enable_component(cls) def verify(self): """Verify that the provided path points to a valid Plumbum instance directory.""" try: tag = read_file(os.path.join(self.path, 'VERSION')).splitlines()[0] if tag != _VERSION: raise Exception("Unknown Plumbum instance type '%(type)s'" %\ dict(type=tag)) except Exception as e: raise PlumbumError("No Plumbum instance found at %(path)s\n" "%(e)s" % dict(path=self.path, e=e)) def shutdown(self, tid=None): """Close the instance.""" # Must shutdown database manager, etc. if tid is None: log.shutdown(self.log) def create(self, options=[]): """Create the basic directory structure of the instance, initialize the database and populate the configuration file with default values. If options contains ('inherit', 'file'), default values will not be loaded; they are expected to be provided by that file or other options. """ # Create the directory structure if not os.path.exists(self.path): os.mkdir(self.path) os.mkdir(self.log_dir) #os.mkdir(self.htdocs_dir) os.mkdir(self.plugins_dir) # Create a few files create_file(os.path.join(self.path, 'VERSION'), _VERSION + '\n') create_file(os.path.join(self.path, 'README'), "This directory contains a Plumbum instance.\n" "Visit http://pb.rioplomo.com/ for more information.\n") # Setup the default configuration os.mkdir(self.conf_dir) create_file(self.config_file_path + '.sample') config = Configuration(self.config_file_path) for section, name, value in options: config.set(section, name, value) config.save() self.setup_config() if not any((section, option) == ('inherit', 'file') for section, option, value in options): self.config.set_defaults(self) self.config.save() # Create the database @lazy def database_version(self): """Returns the current version of the database.""" return False @lazy def plumbum_version(self): """Returns the version of Plumbum.""" from plumbum import __version__ return __version__ def setup_config(self): """Load the configuration file.""" self.config = Configuration(self.config_file_path, {'instname': self.name}) if not self.config.exists: raise PlumbumError("The configuration file is not found at " "%(path)s" % dict(path=self.config_file_path)) self.setup_log() plugins_dir = self.shared_plugins_dir load_components(self, plugins_dir and (plugins_dir,)) @lazy def config_file_path(self): """Path of the plumbum.cfg file.""" return os.path.join(self.conf_dir, 'plumbum.cfg') @lazy def log_file_path(self): """Path to the log file.""" if not os.path.isabs(self.log_file): return os.path.join(self.log_dir, self.log_file) return self.log_file def _build_path(self, *dirs): path = self.path for dir in dirs: path = os.path.join(path, dir) return os.path.realpath(path) @lazy def conf_dir(self): """Absolute path to the conf directory.""" return self._build_path('conf') @lazy def log_dir(self): """Absolute path to the log directory.""" return self._build_path('log') @lazy def plugins_dir(self): """Absolute path to the plugins directory.""" return self._build_path('plugins') @lazy def templates_dir(self): """Absolute path to the templates directory.""" return self._build_path('templates') def setup_log(self): """Initialize the logging sub-system.""" format = self.log_format if format: format = format.replace('$(', '%(') \ .replace('%(path)s', self.path) \ .replace('%(basename)s', self.name) \ .replace('%(name)s', self.instance_name) logid = 'Plumbum.%s' % hashlib.sha1(self.path.encode('utf-8')).hexdigest() self.log = log.logger_handler_factory( self.log_type, self.log_file_path, self.log_level, logid, format=format) self.log.info('-' * 32 + ' instance startup [Plumbum %s] ' + '-' * 32, self.plumbum_version) def needs_upgrade(self): """Return whether the instance needs to be upgraded.""" for participant in self.setup_participants: if participant.instance_needs_upgrade(): self.log.warn("Component %s requires instance upgrade" %\ participant) return True return False def upgrade(self, backup=False, backup_dest=None): """Upgrade instance.""" upgraders = [] for participant in self.setup_participants: if participant.instance_needs_upgrade(): upgraders.append(participant) if not upgraders: return for participant in upgraders: self.log.info("%s.%s upgrading..." % (participant.__module__, participant.__class__.__name__)) participant.upgrade_instance() # TODO: upgrade database return True class PlumbumInstanceSetup(Component): """Manage automatic instance upgrades.""" required = True implements(IInstanceSetupParticipant) # IInstanceSetupParticipant methods def instance_created(self): """Insert default data into the dataabse.""" # TODO: insert default data to db self._update_sample_config() def instance_needs_upgrade(self): # TODO: Check if db needs upgrade return False def upgrade_instance(self): # TODO: upgrade db self._update_sample_config() # Internal methods def _update_sample_config(self): filename = os.path.join(self.instance.config_file_path + '.sample') if not os.path.isfile(filename): return config = Configuration(filename) for (section, name), option in Option.get_registry().items(): config.set(section, name, option.dumps(option.default)) try: config.save() self.log.info("Wrote sample configuration file with the new " "settings and their default values: %s" % filename) except IOError as e: self.log.warn("Could't write sample configuration file (%s)", e, exc_info=True) inst_cache = {} inst_cache_lock = threading.Lock() def open_instance(path=None, use_cache=False): """Open an existing instance object, and verify that the database is up to date. :param path: absolute path to the instance directory; if omitted the value of the `PLUMBUM_INSTANCE` environment variable is used :param use_cache: whether the instance shoud be cached for subsequent invocations of the function :return: the `PlumbumInstance` object """ if not path: path = os.getenv('PLUMBUM_INSTANCE') if not path: raise PlumbumError('Missing environment variable `PLUMBUM_INSTANCE`.' 'Plumbum requires this variable to point to a valid Plumbum ' 'instance.') if use_cache: with inst_cache_lock: inst = inst_cache.get(path) if inst and inst.config.parse_if_needed(): # The instance configuration has changed, so shut it down and # remove it from the cache so that it gets reinitialized inst.log.info('Reloading instance due to configuration change') inst.shutdown() del inst_cache[path] inst = None if inst is None: inst = inst_cache.setdefault(path, open_instance(path)) else: CacheManager(inst).reset_metadata() else: inst = PlumbumInstance(path) needs_upgrade = False try: needs_upgrade = inst.needs_upgrade() except Exception as e: # e.g. no database connection inst.log.error('Exception cought while checking for upgrade: %s', str(e)) if needs_upgrade: raise PlumbumError('The Plumbum Instance needs to be upgraded.\n\n' 'Run "plumbum-admin %(path)s upgrade"' % \ dict(path=path)) return env
[ "augusto@rioplomo.com.ar" ]
augusto@rioplomo.com.ar
8e22fb42f90d570c97b11d0307980d6995e1e0d3
fbc29f0d9d0d6ba0c76c57d91cfad4a4cfa97932
/Utility Scripting and System Administration/Finding_Files_by_Name.py
b598b8cbb5d1378a4e37cc66ab01eb681e2ac70e
[]
no_license
Lisolo/Python-Cookbook
b453b309eb9d4b9af644d35e8ec9f8ad31c091c1
e9dd792c32624899bad43fa0f82bdb89f2422e0e
refs/heads/master
2016-09-06T02:15:33.729560
2014-10-24T14:00:24
2014-10-24T14:00:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,105
py
# coding=utf-8 """ Problem You need to write a script that involves finding files, like a file renaming script or a log archiver utility, but you’d rather not have to call shell utilities from within your Python script, or you want to provide specialized behavior not easily available by "shelling out." Solution To search for files, use the os.walk() function, supplying it with the top-level directory. Here is an example of a function that finds a specific filename and prints out the full path of all matches: """ #!/usr/bin/env python3.3 import os import sys def findfile(start, name): for relpath, dirs, files in os.walk(start): if name in files: full_path = os.path.join(start, relpath, name) print(os.path.normpath(os.path.abspath(full_path))) if __name__ == '__main__': findfile(sys.argv[1], sys.argv[2]) """ Save this script as findfile.py and run it from the command line, feeding in the starting point and the name as positional arguments, like this: bash % ./findfile.py . myfile.txt """ """ Discussion The os.walk() method traverses the directory hierarchy for us, and for each directory it enters, it returns a 3-tuple, containing the relative path to the directory it’s inspecting, a list containing all of the directory names in that directory, and a list of filenames in that directory. For each tuple, you simply check if the target filename is in the files list. If it is, os.path.join() is used to put together a path. To avoid the possibility of weird looking paths like ././foo//bar, two additional functions are used to fix the result. The first is os.path.abspath(), which takes a path that might be relative and forms the absolute path, and the second is os.path.normpath(), which will normalize the path, thereby resolving issues with double slashes, multiple references to the current directory, and so on. Although this script is pretty simple compared to the features of the find utility found on UNIX platforms, it has the benefit of being cross-platform. Furthermore, a lot of additional functionality can be added in a portable manner without much more work. To illustrate, here is a function that prints out all of the files that have a recent modification time: #!/usr/bin/env python3.3 import os import sys import time def modified_within(top, seconds): now = time.time() for path, dirs, files in os.walk(top): for name in files: fullpath = os.path.join(path, name) if os.path.exists(fullpath): mtime = os.path.getmtime(fullpath) if mtime > (now - seconds): print(fullpath) if __name__ == '__main__': import sys if len(sys.argv) != 3: print('Usage: {} dir seconds'.format(sys.argv[0])) raise SystemExit(1) modified_within(sys.argv[1], float(sys.argv[2])) """ """ It wouldn’t take long for you to build far more complex operations on top of this little function using various features of the os, os.path, glob, and similar modules. See Recipes and for related recipes. """
[ "iamsoloa@gmail.com" ]
iamsoloa@gmail.com
03551ff2e3a33c798cf03e45c710fb968170d466
b8630509b97621ddc3bbeaef8d1cd54ff77b3dde
/myvenv/lib/python3.5/site-packages/django/db/models/query.py
66e2216c00432236883ffabf69ca4a6f59745152
[]
no_license
ChibaUnppluged/BandMaker-ogi
c4080204d63495fed42e26306663e06df8ffb373
68a4a6eceb3f385b97afe8741fc538216800f893
refs/heads/master
2021-01-01T04:29:28.436614
2017-10-20T16:30:00
2017-10-20T16:30:00
97,184,844
0
0
null
null
null
null
UTF-8
Python
false
false
71,888
py
# coding:utf-8 """ The main QuerySet implementation. This provides the public API for the ORM. """ import copy import sys import warnings from collections import OrderedDict, deque from django.conf import settings from django.core import exceptions from django.db import ( DJANGO_VERSION_PICKLE_KEY, IntegrityError, connections, router, transaction, ) from django.db.models import DateField, DateTimeField, sql from django.db.models.constants import LOOKUP_SEP from django.db.models.deletion import Collector from django.db.models.expressions import F from django.db.models.fields import AutoField from django.db.models.functions import Trunc from django.db.models.query_utils import InvalidQuery, Q from django.db.models.sql.constants import CURSOR from django.utils import six, timezone from django.utils.deprecation import RemovedInDjango20Warning from django.utils.functional import cached_property, partition from django.utils.version import get_version # The maximum number of items to display in a QuerySet.__repr__ REPR_OUTPUT_SIZE = 20 # Pull into this namespace for backwards compatibility. EmptyResultSet = sql.EmptyResultSet class BaseIterable(object): def __init__(self, queryset, chunked_fetch=False): self.queryset = queryset self.chunked_fetch = chunked_fetch class ModelIterable(BaseIterable): """ Iterable that yields a model instance for each row. """ def __iter__(self): queryset = self.queryset db = queryset.db compiler = queryset.query.get_compiler(using=db) # Execute the query. This will also fill compiler.select, klass_info, # and annotations. results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) select, klass_info, annotation_col_map = (compiler.select, compiler.klass_info, compiler.annotation_col_map) model_cls = klass_info['model'] select_fields = klass_info['select_fields'] model_fields_start, model_fields_end = select_fields[0], select_fields[-1] + 1 init_list = [f[0].target.attname for f in select[model_fields_start:model_fields_end]] related_populators = get_related_populators(klass_info, select, db) for row in compiler.results_iter(results): obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end]) if related_populators: for rel_populator in related_populators: rel_populator.populate(row, obj) if annotation_col_map: for attr_name, col_pos in annotation_col_map.items(): setattr(obj, attr_name, row[col_pos]) # Add the known related objects to the model, if there are any if queryset._known_related_objects: for field, rel_objs in queryset._known_related_objects.items(): # Avoid overwriting objects loaded e.g. by select_related if hasattr(obj, field.get_cache_name()): continue pk = getattr(obj, field.get_attname()) try: rel_obj = rel_objs[pk] except KeyError: pass # may happen in qs1 | qs2 scenarios else: setattr(obj, field.name, rel_obj) yield obj class ValuesIterable(BaseIterable): """ Iterable returned by QuerySet.values() that yields a dict for each row. """ def __iter__(self): queryset = self.queryset query = queryset.query compiler = query.get_compiler(queryset.db) field_names = list(query.values_select) extra_names = list(query.extra_select) annotation_names = list(query.annotation_select) # extra(select=...) cols are always at the start of the row. names = extra_names + field_names + annotation_names for row in compiler.results_iter(): yield dict(zip(names, row)) class ValuesListIterable(BaseIterable): """ Iterable returned by QuerySet.values_list(flat=False) that yields a tuple for each row. """ def __iter__(self): queryset = self.queryset query = queryset.query compiler = query.get_compiler(queryset.db) if not query.extra_select and not query.annotation_select: for row in compiler.results_iter(): yield tuple(row) else: field_names = list(query.values_select) extra_names = list(query.extra_select) annotation_names = list(query.annotation_select) # extra(select=...) cols are always at the start of the row. names = extra_names + field_names + annotation_names if queryset._fields: # Reorder according to fields. fields = list(queryset._fields) + [f for f in annotation_names if f not in queryset._fields] else: fields = names for row in compiler.results_iter(): data = dict(zip(names, row)) yield tuple(data[f] for f in fields) class FlatValuesListIterable(BaseIterable): """ Iterable returned by QuerySet.values_list(flat=True) that yields single values. """ def __iter__(self): queryset = self.queryset compiler = queryset.query.get_compiler(queryset.db) for row in compiler.results_iter(): yield row[0] class QuerySet(object): """ Represents a lazy database lookup for a set of objects. """ def __init__(self, model=None, query=None, using=None, hints=None): self.model = model self._db = using self._hints = hints or {} self.query = query or sql.Query(self.model) self._result_cache = None self._sticky_filter = False self._for_write = False self._prefetch_related_lookups = () self._prefetch_done = False self._known_related_objects = {} # {rel_field: {pk: rel_obj}} self._iterable_class = ModelIterable self._fields = None def as_manager(cls): # Address the circular dependency between `Queryset` and `Manager`. from django.db.models.manager import Manager manager = Manager.from_queryset(cls)() manager._built_with_as_manager = True return manager as_manager.queryset_only = True as_manager = classmethod(as_manager) ######################## # PYTHON MAGIC METHODS # ######################## def __deepcopy__(self, memo): """ Deep copy of a QuerySet doesn't populate the cache """ obj = self.__class__() for k, v in self.__dict__.items(): if k == '_result_cache': obj.__dict__[k] = None else: obj.__dict__[k] = copy.deepcopy(v, memo) return obj def __getstate__(self): # Force the cache to be fully populated. self._fetch_all() obj_dict = self.__dict__.copy() obj_dict[DJANGO_VERSION_PICKLE_KEY] = get_version() return obj_dict def __setstate__(self, state): msg = None pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY) if pickled_version: current_version = get_version() if current_version != pickled_version: msg = ( "Pickled queryset instance's Django version %s does not " "match the current version %s." % (pickled_version, current_version) ) else: msg = "Pickled queryset instance's Django version is not specified." if msg: warnings.warn(msg, RuntimeWarning, stacklevel=2) self.__dict__.update(state) def __repr__(self): data = list(self[:REPR_OUTPUT_SIZE + 1]) if len(data) > REPR_OUTPUT_SIZE: data[-1] = "...(remaining elements truncated)..." return '<%s %r>' % (self.__class__.__name__, data) def __len__(self): self._fetch_all() return len(self._result_cache) def __iter__(self): """ The queryset iterator protocol uses three nested iterators in the default case: 1. sql.compiler:execute_sql() - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE) using cursor.fetchmany(). This part is responsible for doing some column masking, and returning the rows in chunks. 2. sql/compiler.results_iter() - Returns one row at time. At this point the rows are still just tuples. In some cases the return values are converted to Python values at this location. 3. self.iterator() - Responsible for turning the rows into model objects. """ self._fetch_all() return iter(self._result_cache) def __bool__(self): self._fetch_all() return bool(self._result_cache) def __nonzero__(self): # Python 2 compatibility return type(self).__bool__(self) def __getitem__(self, k): """ Retrieves an item or slice from the set of results. """ if not isinstance(k, (slice,) + six.integer_types): raise TypeError assert ((not isinstance(k, slice) and (k >= 0)) or (isinstance(k, slice) and (k.start is None or k.start >= 0) and (k.stop is None or k.stop >= 0))), \ "Negative indexing is not supported." if self._result_cache is not None: return self._result_cache[k] if isinstance(k, slice): qs = self._clone() if k.start is not None: start = int(k.start) else: start = None if k.stop is not None: stop = int(k.stop) else: stop = None qs.query.set_limits(start, stop) return list(qs)[::k.step] if k.step else qs qs = self._clone() qs.query.set_limits(k, k + 1) return list(qs)[0] def __and__(self, other): self._merge_sanity_check(other) if isinstance(other, EmptyQuerySet): return other if isinstance(self, EmptyQuerySet): return self combined = self._clone() combined._merge_known_related_objects(other) combined.query.combine(other.query, sql.AND) return combined def __or__(self, other): self._merge_sanity_check(other) if isinstance(self, EmptyQuerySet): return other if isinstance(other, EmptyQuerySet): return self combined = self._clone() combined._merge_known_related_objects(other) combined.query.combine(other.query, sql.OR) return combined #################################### # METHODS THAT DO DATABASE QUERIES # #################################### def iterator(self): """ An iterator over the results from applying this QuerySet to the database. """ use_chunked_fetch = not connections[self.db].settings_dict.get('DISABLE_SERVER_SIDE_CURSORS') return iter(self._iterable_class(self, chunked_fetch=use_chunked_fetch)) def aggregate(self, *args, **kwargs): """ Returns a dictionary containing the calculations (aggregation) over the current queryset If args is present the expression is passed as a kwarg using the Aggregate object's default alias. """ if self.query.distinct_fields: raise NotImplementedError("aggregate() + distinct(fields) not implemented.") for arg in args: # The default_alias property may raise a TypeError, so we use # a try/except construct rather than hasattr in order to remain # consistent between PY2 and PY3 (hasattr would swallow # the TypeError on PY2). try: arg.default_alias except (AttributeError, TypeError): raise TypeError("Complex aggregates require an alias") kwargs[arg.default_alias] = arg query = self.query.clone() for (alias, aggregate_expr) in kwargs.items(): query.add_annotation(aggregate_expr, alias, is_summary=True) if not query.annotations[alias].contains_aggregate: raise TypeError("%s is not an aggregate expression" % alias) return query.get_aggregation(self.db, kwargs.keys()) def count(self): """ Performs a SELECT COUNT() and returns the number of records as an integer. If the QuerySet is already fully cached this simply returns the length of the cached results set to avoid multiple SELECT COUNT(*) calls. """ if self._result_cache is not None: return len(self._result_cache) return self.query.get_count(using=self.db) def get(self, *args, **kwargs): """ Performs the query and returns a single object matching the given keyword arguments. """ clone = self.filter(*args, **kwargs) if self.query.can_filter() and not self.query.distinct_fields: clone = clone.order_by() num = len(clone) if num == 1: return clone._result_cache[0] if not num: raise self.model.DoesNotExist( "%s matching query does not exist." % self.model._meta.object_name ) raise self.model.MultipleObjectsReturned( "get() returned more than one %s -- it returned %s!" % (self.model._meta.object_name, num) ) def create(self, **kwargs): """ Creates a new object with the given kwargs, saving it to the database and returning the created object. """ obj = self.model(**kwargs) self._for_write = True obj.save(force_insert=True, using=self.db) return obj def _populate_pk_values(self, objs): for obj in objs: if obj.pk is None: obj.pk = obj._meta.pk.get_pk_value_on_save(obj) def bulk_create(self, objs, batch_size=None): """ Inserts each of the instances into the database. This does *not* call save() on each of the instances, does not send any pre/post save signals, and does not set the primary key attribute if it is an autoincrement field (except if features.can_return_ids_from_bulk_insert=True). Multi-table models are not supported. """ # When you bulk insert you don't get the primary keys back (if it's an # autoincrement, except if can_return_ids_from_bulk_insert=True), so # you can't insert into the child tables which references this. There # are two workarounds: # 1) This could be implemented if you didn't have an autoincrement pk # 2) You could do it by doing O(n) normal inserts into the parent # tables to get the primary keys back and then doing a single bulk # insert into the childmost table. # We currently set the primary keys on the objects when using # PostgreSQL via the RETURNING ID clause. It should be possible for # Oracle as well, but the semantics for extracting the primary keys is # trickier so it's not done yet. assert batch_size is None or batch_size > 0 # Check that the parents share the same concrete model with the our # model to detect the inheritance pattern ConcreteGrandParent -> # MultiTableParent -> ProxyChild. Simply checking self.model._meta.proxy # would not identify that case as involving multiple tables. for parent in self.model._meta.get_parent_list(): if parent._meta.concrete_model is not self.model._meta.concrete_model: raise ValueError("Can't bulk create a multi-table inherited model") if not objs: return objs self._for_write = True connection = connections[self.db] fields = self.model._meta.concrete_fields objs = list(objs) self._populate_pk_values(objs) with transaction.atomic(using=self.db, savepoint=False): objs_with_pk, objs_without_pk = partition(lambda o: o.pk is None, objs) if objs_with_pk: self._batched_insert(objs_with_pk, fields, batch_size) if objs_without_pk: fields = [f for f in fields if not isinstance(f, AutoField)] ids = self._batched_insert(objs_without_pk, fields, batch_size) if connection.features.can_return_ids_from_bulk_insert: assert len(ids) == len(objs_without_pk) for obj_without_pk, pk in zip(objs_without_pk, ids): obj_without_pk.pk = pk obj_without_pk._state.adding = False obj_without_pk._state.db = self.db return objs def get_or_create(self, defaults=None, **kwargs): """ Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created. """ lookup, params = self._extract_model_params(defaults, **kwargs) # The get() needs to be targeted at the write database in order # to avoid potential transaction consistency problems. self._for_write = True try: return self.get(**lookup), False except self.model.DoesNotExist: return self._create_object_from_params(lookup, params) def update_or_create(self, defaults=None, **kwargs): """ Looks up an object with the given kwargs, updating one with defaults if it exists, otherwise creates a new one. Returns a tuple (object, created), where created is a boolean specifying whether an object was created. """ defaults = defaults or {} lookup, params = self._extract_model_params(defaults, **kwargs) self._for_write = True with transaction.atomic(using=self.db): try: obj = self.select_for_update().get(**lookup) except self.model.DoesNotExist: obj, created = self._create_object_from_params(lookup, params) if created: return obj, created for k, v in six.iteritems(defaults): setattr(obj, k, v() if callable(v) else v) obj.save(using=self.db) return obj, False def _create_object_from_params(self, lookup, params): """ Tries to create an object using passed params. Used by get_or_create and update_or_create """ try: with transaction.atomic(using=self.db): params = {k: v() if callable(v) else v for k, v in params.items()} obj = self.create(**params) return obj, True except IntegrityError: exc_info = sys.exc_info() try: return self.get(**lookup), False except self.model.DoesNotExist: pass six.reraise(*exc_info) def _extract_model_params(self, defaults, **kwargs): """ Prepares `lookup` (kwargs that are valid model attributes), `params` (for creating a model instance) based on given kwargs; for use by get_or_create and update_or_create. """ defaults = defaults or {} lookup = kwargs.copy() for f in self.model._meta.fields: if f.attname in lookup: lookup[f.name] = lookup.pop(f.attname) params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k} params.update(defaults) property_names = self.model._meta._property_names invalid_params = [] for param in params: try: self.model._meta.get_field(param) except exceptions.FieldDoesNotExist: # It's okay to use a model's property if it has a setter. if not (param in property_names and getattr(self.model, param).fset): invalid_params.append(param) if invalid_params: raise exceptions.FieldError( "Invalid field name(s) for model %s: '%s'." % ( self.model._meta.object_name, "', '".join(sorted(invalid_params)), )) return lookup, params def _earliest_or_latest(self, field_name=None, direction="-"): """ Returns the latest object, according to the model's 'get_latest_by' option or optional given field_name. """ order_by = field_name or getattr(self.model._meta, 'get_latest_by') assert bool(order_by), "earliest() and latest() require either a "\ "field_name parameter or 'get_latest_by' in the model" assert self.query.can_filter(), \ "Cannot change a query once a slice has been taken." obj = self._clone() obj.query.set_limits(high=1) obj.query.clear_ordering(force_empty=True) obj.query.add_ordering('%s%s' % (direction, order_by)) return obj.get() def earliest(self, field_name=None): return self._earliest_or_latest(field_name=field_name, direction="") def latest(self, field_name=None): return self._earliest_or_latest(field_name=field_name, direction="-") def first(self): """ Returns the first object of a query, returns None if no match is found. """ objects = list((self if self.ordered else self.order_by('pk'))[:1]) if objects: return objects[0] return None def last(self): """ Returns the last object of a query, returns None if no match is found. """ objects = list((self.reverse() if self.ordered else self.order_by('-pk'))[:1]) if objects: return objects[0] return None def in_bulk(self, id_list=None): """ Returns a dictionary mapping each of the given IDs to the object with that ID. If `id_list` isn't provided, the entire QuerySet is evaluated. """ assert self.query.can_filter(), \ "Cannot use 'limit' or 'offset' with in_bulk" if id_list is not None: if not id_list: return {} qs = self.filter(pk__in=id_list).order_by() else: qs = self._clone() return {obj._get_pk_val(): obj for obj in qs} def delete(self): """ Deletes the records in the current QuerySet. """ assert self.query.can_filter(), \ "Cannot use 'limit' or 'offset' with delete." if self._fields is not None: raise TypeError("Cannot call delete() after .values() or .values_list()") del_query = self._clone() # The delete is actually 2 queries - one to find related objects, # and one to delete. Make sure that the discovery of related # objects is performed on the same database as the deletion. del_query._for_write = True # Disable non-supported fields. del_query.query.select_for_update = False del_query.query.select_related = False del_query.query.clear_ordering(force_empty=True) collector = Collector(using=del_query.db) collector.collect(del_query) deleted, _rows_count = collector.delete() # Clear the result cache, in case this QuerySet gets reused. self._result_cache = None return deleted, _rows_count delete.alters_data = True delete.queryset_only = True def _raw_delete(self, using): """ Deletes objects found from the given queryset in single direct SQL query. No signals are sent, and there is no protection for cascades. """ return sql.DeleteQuery(self.model).delete_qs(self, using) _raw_delete.alters_data = True def update(self, **kwargs): """ Updates all elements in the current QuerySet, setting all the given fields to the appropriate values. """ assert self.query.can_filter(), \ "Cannot update a query once a slice has been taken." self._for_write = True query = self.query.clone(sql.UpdateQuery) query.add_update_values(kwargs) # Clear any annotations so that they won't be present in subqueries. query._annotations = None with transaction.atomic(using=self.db, savepoint=False): rows = query.get_compiler(self.db).execute_sql(CURSOR) self._result_cache = None return rows update.alters_data = True def _update(self, values): """ A version of update that accepts field objects instead of field names. Used primarily for model saving and not intended for use by general code (it requires too much poking around at model internals to be useful at that level). """ assert self.query.can_filter(), \ "Cannot update a query once a slice has been taken." query = self.query.clone(sql.UpdateQuery) query.add_update_fields(values) self._result_cache = None return query.get_compiler(self.db).execute_sql(CURSOR) _update.alters_data = True _update.queryset_only = False def exists(self): if self._result_cache is None: return self.query.has_results(using=self.db) return bool(self._result_cache) def _prefetch_related_objects(self): # This method can only be called once the result cache has been filled. prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups) self._prefetch_done = True ################################################## # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS # ################################################## def raw(self, raw_query, params=None, translations=None, using=None): if using is None: using = self.db return RawQuerySet(raw_query, model=self.model, params=params, translations=translations, using=using) def _values(self, *fields, **expressions): clone = self._clone() if expressions: clone = clone.annotate(**expressions) clone._fields = fields clone.query.set_values(fields) return clone def values(self, *fields, **expressions): fields += tuple(expressions) clone = self._values(*fields, **expressions) clone._iterable_class = ValuesIterable return clone def values_list(self, *fields, **kwargs): flat = kwargs.pop('flat', False) if kwargs: raise TypeError('Unexpected keyword arguments to values_list: %s' % (list(kwargs),)) if flat and len(fields) > 1: raise TypeError("'flat' is not valid when values_list is called with more than one field.") _fields = [] expressions = {} for field in fields: if hasattr(field, 'resolve_expression'): field_id = str(id(field)) expressions[field_id] = field _fields.append(field_id) else: _fields.append(field) clone = self._values(*_fields, **expressions) clone._iterable_class = FlatValuesListIterable if flat else ValuesListIterable return clone def dates(self, field_name, kind, order='ASC'): """ Returns a list of date objects representing all available dates for the given field_name, scoped to 'kind'. """ assert kind in ("year", "month", "day"), \ "'kind' must be one of 'year', 'month' or 'day'." assert order in ('ASC', 'DESC'), \ "'order' must be either 'ASC' or 'DESC'." return self.annotate( datefield=Trunc(field_name, kind, output_field=DateField()), plain_field=F(field_name) ).values_list( 'datefield', flat=True ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datefield') def datetimes(self, field_name, kind, order='ASC', tzinfo=None): """ Returns a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'. """ assert kind in ("year", "month", "day", "hour", "minute", "second"), \ "'kind' must be one of 'year', 'month', 'day', 'hour', 'minute' or 'second'." assert order in ('ASC', 'DESC'), \ "'order' must be either 'ASC' or 'DESC'." if settings.USE_TZ: if tzinfo is None: tzinfo = timezone.get_current_timezone() else: tzinfo = None return self.annotate( datetimefield=Trunc(field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo), plain_field=F(field_name) ).values_list( 'datetimefield', flat=True ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield') def none(self): """ Returns an empty QuerySet. """ clone = self._clone() clone.query.set_empty() return clone ################################################################## # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET # ################################################################## def all(self): """ Returns a new QuerySet that is a copy of the current one. This allows a QuerySet to proxy for a model manager in some cases. """ return self._clone() def filter(self, *args, **kwargs): """ Returns a new QuerySet instance with the args ANDed to the existing set. """ return self._filter_or_exclude(False, *args, **kwargs) def exclude(self, *args, **kwargs): """ Returns a new QuerySet instance with NOT (args) ANDed to the existing set. """ return self._filter_or_exclude(True, *args, **kwargs) def _filter_or_exclude(self, negate, *args, **kwargs): if args or kwargs: assert self.query.can_filter(), \ "Cannot filter a query once a slice has been taken." clone = self._clone() if negate: clone.query.add_q(~Q(*args, **kwargs)) else: clone.query.add_q(Q(*args, **kwargs)) return clone def complex_filter(self, filter_obj): """ Returns a new QuerySet instance with filter_obj added to the filters. filter_obj can be a Q object (or anything with an add_to_query() method) or a dictionary of keyword lookup arguments. This exists to support framework features such as 'limit_choices_to', and usually it will be more natural to use other methods. """ if isinstance(filter_obj, Q) or hasattr(filter_obj, 'add_to_query'): clone = self._clone() clone.query.add_q(filter_obj) return clone else: return self._filter_or_exclude(None, **filter_obj) def _combinator_query(self, combinator, *other_qs, **kwargs): # Clone the query to inherit the select list and everything clone = self._clone() # Clear limits and ordering so they can be reapplied clone.query.clear_ordering(True) clone.query.clear_limits() clone.query.combined_queries = (self.query,) + tuple(qs.query for qs in other_qs) clone.query.combinator = combinator clone.query.combinator_all = kwargs.pop('all', False) return clone def union(self, *other_qs, **kwargs): if kwargs: unexpected_kwarg = next((k for k in kwargs.keys() if k != 'all'), None) if unexpected_kwarg: raise TypeError( "union() received an unexpected keyword argument '%s'" % (unexpected_kwarg,) ) # If the query is an EmptyQuerySet, combine all nonempty querysets. if isinstance(self, EmptyQuerySet): qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)] return qs[0]._combinator_query('union', *qs[1:], **kwargs) if qs else self return self._combinator_query('union', *other_qs, **kwargs) def intersection(self, *other_qs): # If any query is an EmptyQuerySet, return it. if isinstance(self, EmptyQuerySet): return self for other in other_qs: if isinstance(other, EmptyQuerySet): return other return self._combinator_query('intersection', *other_qs) def difference(self, *other_qs): # If the query is an EmptyQuerySet, return it. if isinstance(self, EmptyQuerySet): return self return self._combinator_query('difference', *other_qs) def select_for_update(self, nowait=False, skip_locked=False): """ Returns a new QuerySet instance that will select objects with a FOR UPDATE lock. """ if nowait and skip_locked: raise ValueError('The nowait option cannot be used with skip_locked.') obj = self._clone() obj._for_write = True obj.query.select_for_update = True obj.query.select_for_update_nowait = nowait obj.query.select_for_update_skip_locked = skip_locked return obj def select_related(self, *fields): """ Returns a new QuerySet instance that will select related objects. If fields are specified, they must be ForeignKey fields and only those related objects are included in the selection. If select_related(None) is called, the list is cleared. """ if self._fields is not None: raise TypeError("Cannot call select_related() after .values() or .values_list()") obj = self._clone() if fields == (None,): obj.query.select_related = False elif fields: obj.query.add_select_related(fields) else: obj.query.select_related = True return obj def prefetch_related(self, *lookups): """ Returns a new QuerySet instance that will prefetch the specified Many-To-One and Many-To-Many related objects when the QuerySet is evaluated. When prefetch_related() is called more than once, the list of lookups to prefetch is appended to. If prefetch_related(None) is called, the list is cleared. """ clone = self._clone() if lookups == (None,): clone._prefetch_related_lookups = () else: clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups return clone def annotate(self, *args, **kwargs): """ Return a query set in which the returned objects have been annotated with extra data or aggregations. """ annotations = OrderedDict() # To preserve ordering of args for arg in args: # The default_alias property may raise a TypeError, so we use # a try/except construct rather than hasattr in order to remain # consistent between PY2 and PY3 (hasattr would swallow # the TypeError on PY2). try: if arg.default_alias in kwargs: raise ValueError("The named annotation '%s' conflicts with the " "default name for another annotation." % arg.default_alias) except (AttributeError, TypeError): raise TypeError("Complex annotations require an alias") annotations[arg.default_alias] = arg annotations.update(kwargs) clone = self._clone() names = self._fields if names is None: names = {f.name for f in self.model._meta.get_fields()} for alias, annotation in annotations.items(): if alias in names: raise ValueError("The annotation '%s' conflicts with a field on " "the model." % alias) clone.query.add_annotation(annotation, alias, is_summary=False) for alias, annotation in clone.query.annotations.items(): if alias in annotations and annotation.contains_aggregate: if clone._fields is None: clone.query.group_by = True else: clone.query.set_group_by() break return clone def order_by(self, *field_names): """ Returns a new QuerySet instance with the ordering changed. """ assert self.query.can_filter(), \ "Cannot reorder a query once a slice has been taken." obj = self._clone() obj.query.clear_ordering(force_empty=False) obj.query.add_ordering(*field_names) return obj def distinct(self, *field_names): """ Returns a new QuerySet instance that will select only distinct results. """ assert self.query.can_filter(), \ "Cannot create distinct fields once a slice has been taken." obj = self._clone() obj.query.add_distinct_fields(*field_names) return obj def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None): """ Adds extra SQL fragments to the query. """ assert self.query.can_filter(), \ "Cannot change a query once a slice has been taken" clone = self._clone() clone.query.add_extra(select, select_params, where, params, tables, order_by) return clone def reverse(self): """ Reverses the ordering of the QuerySet. """ clone = self._clone() clone.query.standard_ordering = not clone.query.standard_ordering return clone def defer(self, *fields): """ Defers the loading of data for certain fields until they are accessed. The set of fields to defer is added to any existing set of deferred fields. The only exception to this is if None is passed in as the only parameter, in which case all deferrals are removed (None acts as a reset option). """ if self._fields is not None: raise TypeError("Cannot call defer() after .values() or .values_list()") clone = self._clone() if fields == (None,): clone.query.clear_deferred_loading() else: clone.query.add_deferred_loading(fields) return clone def only(self, *fields): """ Essentially, the opposite of defer. Only the fields passed into this method and that are not already specified as deferred are loaded immediately when the queryset is evaluated. """ if self._fields is not None: raise TypeError("Cannot call only() after .values() or .values_list()") if fields == (None,): # Can only pass None to defer(), not only(), as the rest option. # That won't stop people trying to do this, so let's be explicit. raise TypeError("Cannot pass None as an argument to only().") clone = self._clone() clone.query.add_immediate_loading(fields) return clone def using(self, alias): """ Selects which database this QuerySet should execute its query against. """ clone = self._clone() clone._db = alias return clone ################################### # PUBLIC INTROSPECTION ATTRIBUTES # ################################### @property def ordered(self): """ Returns True if the QuerySet is ordered -- i.e. has an order_by() clause or a default ordering on the model. """ if self.query.extra_order_by or self.query.order_by: return True elif self.query.default_ordering and self.query.get_meta().ordering: return True else: return False @property def db(self): "Return the database that will be used if this query is executed now" if self._for_write: return self._db or router.db_for_write(self.model, **self._hints) return self._db or router.db_for_read(self.model, **self._hints) ################### # PRIVATE METHODS # ################### def _insert(self, objs, fields, return_id=False, raw=False, using=None): """ Inserts a new record for the given model. This provides an interface to the InsertQuery class and is how Model.save() is implemented. """ self._for_write = True if using is None: using = self.db query = sql.InsertQuery(self.model) query.insert_values(fields, objs, raw=raw) return query.get_compiler(using=using).execute_sql(return_id) _insert.alters_data = True _insert.queryset_only = False def _batched_insert(self, objs, fields, batch_size): """ A little helper method for bulk_insert to insert the bulk one batch at a time. Inserts recursively a batch from the front of the bulk and then _batched_insert() the remaining objects again. """ if not objs: return ops = connections[self.db].ops batch_size = (batch_size or max(ops.bulk_batch_size(fields, objs), 1)) inserted_ids = [] for item in [objs[i:i + batch_size] for i in range(0, len(objs), batch_size)]: if connections[self.db].features.can_return_ids_from_bulk_insert: inserted_id = self._insert(item, fields=fields, using=self.db, return_id=True) if isinstance(inserted_id, list): inserted_ids.extend(inserted_id) else: inserted_ids.append(inserted_id) else: self._insert(item, fields=fields, using=self.db) return inserted_ids def _clone(self, **kwargs): query = self.query.clone() if self._sticky_filter: query.filter_is_sticky = True clone = self.__class__(model=self.model, query=query, using=self._db, hints=self._hints) clone._for_write = self._for_write clone._prefetch_related_lookups = self._prefetch_related_lookups clone._known_related_objects = self._known_related_objects clone._iterable_class = self._iterable_class clone._fields = self._fields clone.__dict__.update(kwargs) return clone def _fetch_all(self): if self._result_cache is None: self._result_cache = list(self._iterable_class(self)) if self._prefetch_related_lookups and not self._prefetch_done: self._prefetch_related_objects() def _next_is_sticky(self): """ Indicates that the next filter call and the one following that should be treated as a single filter. This is only important when it comes to determining when to reuse tables for many-to-many filters. Required so that we can filter naturally on the results of related managers. This doesn't return a clone of the current QuerySet (it returns "self"). The method is only used internally and should be immediately followed by a filter() that does create a clone. """ self._sticky_filter = True return self def _merge_sanity_check(self, other): """ Checks that we are merging two comparable QuerySet classes. """ if self._fields is not None and ( set(self.query.values_select) != set(other.query.values_select) or set(self.query.extra_select) != set(other.query.extra_select) or set(self.query.annotation_select) != set(other.query.annotation_select)): raise TypeError( "Merging '%s' classes must involve the same values in each case." % self.__class__.__name__ ) def _merge_known_related_objects(self, other): """ Keep track of all known related objects from either QuerySet instance. """ for field, objects in other._known_related_objects.items(): self._known_related_objects.setdefault(field, {}).update(objects) def _prepare_as_filter_value(self): if self._fields is None: queryset = self.values('pk') queryset.query._forced_pk = True else: # values() queryset can only be used as nested queries # if they are set up to select only a single field. if len(self._fields) > 1: raise TypeError('Cannot use multi-field values as a filter value.') queryset = self._clone() return queryset.query.as_subquery_filter(queryset._db) def _add_hints(self, **hints): """ Update hinting information for later use by Routers """ # If there is any hinting information, add it to what we already know. # If we have a new hint for an existing key, overwrite with the new value. self._hints.update(hints) def _has_filters(self): """ Checks if this QuerySet has any filtering going on. Note that this isn't equivalent for checking if all objects are present in results, for example qs[1:]._has_filters() -> False. """ return self.query.has_filters() class InstanceCheckMeta(type): def __instancecheck__(self, instance): return isinstance(instance, QuerySet) and instance.query.is_empty() class EmptyQuerySet(six.with_metaclass(InstanceCheckMeta)): """ Marker class usable for checking if a queryset is empty by .none(): isinstance(qs.none(), EmptyQuerySet) -> True """ def __init__(self, *args, **kwargs): raise TypeError("EmptyQuerySet can't be instantiated") class RawQuerySet(object): """ Provides an iterator which converts the results of raw SQL queries into annotated model instances. """ def __init__(self, raw_query, model=None, query=None, params=None, translations=None, using=None, hints=None): self.raw_query = raw_query self.model = model self._db = using self._hints = hints or {} self.query = query or sql.RawQuery(sql=raw_query, using=self.db, params=params) self.params = params or () self.translations = translations or {} def resolve_model_init_order(self): """ Resolve the init field names and value positions """ model_init_fields = [f for f in self.model._meta.fields if f.column in self.columns] annotation_fields = [(column, pos) for pos, column in enumerate(self.columns) if column not in self.model_fields] model_init_order = [self.columns.index(f.column) for f in model_init_fields] model_init_names = [f.attname for f in model_init_fields] return model_init_names, model_init_order, annotation_fields def __iter__(self): # Cache some things for performance reasons outside the loop. db = self.db compiler = connections[db].ops.compiler('SQLCompiler')( self.query, connections[db], db ) query = iter(self.query) try: model_init_names, model_init_pos, annotation_fields = self.resolve_model_init_order() # Find out which model's fields are not present in the query. skip = set() for field in self.model._meta.fields: if field.attname not in model_init_names: skip.add(field.attname) if skip: if self.model._meta.pk.attname in skip: raise InvalidQuery('Raw query must include the primary key') model_cls = self.model fields = [self.model_fields.get(c) for c in self.columns] converters = compiler.get_converters([ f.get_col(f.model._meta.db_table) if f else None for f in fields ]) for values in query: if converters: values = compiler.apply_converters(values, converters) # Associate fields to values model_init_values = [values[pos] for pos in model_init_pos] instance = model_cls.from_db(db, model_init_names, model_init_values) if annotation_fields: for column, pos in annotation_fields: setattr(instance, column, values[pos]) yield instance finally: # Done iterating the Query. If it has its own cursor, close it. if hasattr(self.query, 'cursor') and self.query.cursor: self.query.cursor.close() def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self.query) def __getitem__(self, k): return list(self)[k] @property def db(self): "Return the database that will be used if this query is executed now" return self._db or router.db_for_read(self.model, **self._hints) def using(self, alias): """ Selects which database this Raw QuerySet should execute its query against. """ return RawQuerySet( self.raw_query, model=self.model, query=self.query.clone(using=alias), params=self.params, translations=self.translations, using=alias, ) @cached_property def columns(self): """ A list of model field names in the order they'll appear in the query results. """ columns = self.query.get_columns() # Adjust any column names which don't match field names for (query_name, model_name) in self.translations.items(): try: index = columns.index(query_name) columns[index] = model_name except ValueError: # Ignore translations for non-existent column names pass return columns @cached_property def model_fields(self): """ A dict mapping column names to model field names. """ converter = connections[self.db].introspection.table_name_converter model_fields = {} for field in self.model._meta.fields: name, column = field.get_attname_column() model_fields[converter(column)] = field return model_fields class Prefetch(object): def __init__(self, lookup, queryset=None, to_attr=None): # `prefetch_through` is the path we traverse to perform the prefetch. self.prefetch_through = lookup # `prefetch_to` is the path to the attribute that stores the result. self.prefetch_to = lookup if queryset is not None and not issubclass(queryset._iterable_class, ModelIterable): raise ValueError('Prefetch querysets cannot use values().') if to_attr: self.prefetch_to = LOOKUP_SEP.join(lookup.split(LOOKUP_SEP)[:-1] + [to_attr]) self.queryset = queryset self.to_attr = to_attr def __getstate__(self): obj_dict = self.__dict__.copy() if self.queryset is not None: # Prevent the QuerySet from being evaluated obj_dict['queryset'] = self.queryset._clone( _result_cache=[], _prefetch_done=True, ) return obj_dict def add_prefix(self, prefix): self.prefetch_through = LOOKUP_SEP.join([prefix, self.prefetch_through]) self.prefetch_to = LOOKUP_SEP.join([prefix, self.prefetch_to]) def get_current_prefetch_to(self, level): return LOOKUP_SEP.join(self.prefetch_to.split(LOOKUP_SEP)[:level + 1]) def get_current_to_attr(self, level): parts = self.prefetch_to.split(LOOKUP_SEP) to_attr = parts[level] as_attr = self.to_attr and level == len(parts) - 1 return to_attr, as_attr def get_current_queryset(self, level): if self.get_current_prefetch_to(level) == self.prefetch_to: return self.queryset return None def __eq__(self, other): if isinstance(other, Prefetch): return self.prefetch_to == other.prefetch_to return False def __hash__(self): return hash(self.__class__) ^ hash(self.prefetch_to) def normalize_prefetch_lookups(lookups, prefix=None): """ Helper function that normalize lookups into Prefetch objects. """ ret = [] for lookup in lookups: if not isinstance(lookup, Prefetch): lookup = Prefetch(lookup) if prefix: lookup.add_prefix(prefix) ret.append(lookup) return ret def prefetch_related_objects(model_instances, *related_lookups): """ Populate prefetched object caches for a list of model instances based on the lookups/Prefetch instances given. """ if len(model_instances) == 0: return # nothing to do related_lookups = normalize_prefetch_lookups(related_lookups) # We need to be able to dynamically add to the list of prefetch_related # lookups that we look up (see below). So we need some book keeping to # ensure we don't do duplicate work. done_queries = {} # dictionary of things like 'foo__bar': [results] auto_lookups = set() # we add to this as we go through. followed_descriptors = set() # recursion protection all_lookups = deque(related_lookups) while all_lookups: lookup = all_lookups.popleft() if lookup.prefetch_to in done_queries: if lookup.queryset: raise ValueError("'%s' lookup was already seen with a different queryset. " "You may need to adjust the ordering of your lookups." % lookup.prefetch_to) continue # Top level, the list of objects to decorate is the result cache # from the primary QuerySet. It won't be for deeper levels. obj_list = model_instances through_attrs = lookup.prefetch_through.split(LOOKUP_SEP) for level, through_attr in enumerate(through_attrs): # Prepare main instances if len(obj_list) == 0: break prefetch_to = lookup.get_current_prefetch_to(level) if prefetch_to in done_queries: # Skip any prefetching, and any object preparation obj_list = done_queries[prefetch_to] continue # Prepare objects: good_objects = True for obj in obj_list: # Since prefetching can re-use instances, it is possible to have # the same instance multiple times in obj_list, so obj might # already be prepared. if not hasattr(obj, '_prefetched_objects_cache'): try: obj._prefetched_objects_cache = {} except (AttributeError, TypeError): # Must be an immutable object from # values_list(flat=True), for example (TypeError) or # a QuerySet subclass that isn't returning Model # instances (AttributeError), either in Django or a 3rd # party. prefetch_related() doesn't make sense, so quit. good_objects = False break if not good_objects: break # Descend down tree # We assume that objects retrieved are homogeneous (which is the premise # of prefetch_related), so what applies to first object applies to all. first_obj = obj_list[0] to_attr = lookup.get_current_to_attr(level)[0] prefetcher, descriptor, attr_found, is_fetched = get_prefetcher(first_obj, through_attr, to_attr) if not attr_found: raise AttributeError("Cannot find '%s' on %s object, '%s' is an invalid " "parameter to prefetch_related()" % (through_attr, first_obj.__class__.__name__, lookup.prefetch_through)) if level == len(through_attrs) - 1 and prefetcher is None: # Last one, this *must* resolve to something that supports # prefetching, otherwise there is no point adding it and the # developer asking for it has made a mistake. raise ValueError("'%s' does not resolve to an item that supports " "prefetching - this is an invalid parameter to " "prefetch_related()." % lookup.prefetch_through) if prefetcher is not None and not is_fetched: obj_list, additional_lookups = prefetch_one_level(obj_list, prefetcher, lookup, level) # We need to ensure we don't keep adding lookups from the # same relationships to stop infinite recursion. So, if we # are already on an automatically added lookup, don't add # the new lookups from relationships we've seen already. if not (lookup in auto_lookups and descriptor in followed_descriptors): done_queries[prefetch_to] = obj_list new_lookups = normalize_prefetch_lookups(additional_lookups, prefetch_to) auto_lookups.update(new_lookups) all_lookups.extendleft(new_lookups) followed_descriptors.add(descriptor) else: # Either a singly related object that has already been fetched # (e.g. via select_related), or hopefully some other property # that doesn't support prefetching but needs to be traversed. # We replace the current list of parent objects with the list # of related objects, filtering out empty or missing values so # that we can continue with nullable or reverse relations. new_obj_list = [] for obj in obj_list: if through_attr in getattr(obj, '_prefetched_objects_cache', ()): # If related objects have been prefetched, use the # cache rather than the object's through_attr. new_obj = list(obj._prefetched_objects_cache.get(through_attr)) else: try: new_obj = getattr(obj, through_attr) except exceptions.ObjectDoesNotExist: continue if new_obj is None: continue # We special-case `list` rather than something more generic # like `Iterable` because we don't want to accidentally match # user models that define __iter__. if isinstance(new_obj, list): new_obj_list.extend(new_obj) else: new_obj_list.append(new_obj) obj_list = new_obj_list def get_prefetcher(instance, through_attr, to_attr): """ For the attribute 'through_attr' on the given instance, finds an object that has a get_prefetch_queryset(). Returns a 4 tuple containing: (the object with get_prefetch_queryset (or None), the descriptor object representing this relationship (or None), a boolean that is False if the attribute was not found at all, a boolean that is True if the attribute has already been fetched) """ prefetcher = None is_fetched = False # For singly related objects, we have to avoid getting the attribute # from the object, as this will trigger the query. So we first try # on the class, in order to get the descriptor object. rel_obj_descriptor = getattr(instance.__class__, through_attr, None) if rel_obj_descriptor is None: attr_found = hasattr(instance, through_attr) else: attr_found = True if rel_obj_descriptor: # singly related object, descriptor object has the # get_prefetch_queryset() method. if hasattr(rel_obj_descriptor, 'get_prefetch_queryset'): prefetcher = rel_obj_descriptor if rel_obj_descriptor.is_cached(instance): is_fetched = True else: # descriptor doesn't support prefetching, so we go ahead and get # the attribute on the instance rather than the class to # support many related managers rel_obj = getattr(instance, through_attr) if hasattr(rel_obj, 'get_prefetch_queryset'): prefetcher = rel_obj if through_attr != to_attr: # Special case cached_property instances because hasattr # triggers attribute computation and assignment. if isinstance(getattr(instance.__class__, to_attr, None), cached_property): is_fetched = to_attr in instance.__dict__ else: is_fetched = hasattr(instance, to_attr) else: is_fetched = through_attr in instance._prefetched_objects_cache return prefetcher, rel_obj_descriptor, attr_found, is_fetched def prefetch_one_level(instances, prefetcher, lookup, level): """ Helper function for prefetch_related_objects Runs prefetches on all instances using the prefetcher object, assigning results to relevant caches in instance. The prefetched objects are returned, along with any additional prefetches that must be done due to prefetch_related lookups found from default managers. """ # prefetcher must have a method get_prefetch_queryset() which takes a list # of instances, and returns a tuple: # (queryset of instances of self.model that are related to passed in instances, # callable that gets value to be matched for returned instances, # callable that gets value to be matched for passed in instances, # boolean that is True for singly related objects, # cache name to assign to). # The 'values to be matched' must be hashable as they will be used # in a dictionary. rel_qs, rel_obj_attr, instance_attr, single, cache_name = ( prefetcher.get_prefetch_queryset(instances, lookup.get_current_queryset(level))) # We have to handle the possibility that the QuerySet we just got back # contains some prefetch_related lookups. We don't want to trigger the # prefetch_related functionality by evaluating the query. Rather, we need # to merge in the prefetch_related lookups. # Copy the lookups in case it is a Prefetch object which could be reused # later (happens in nested prefetch_related). additional_lookups = [ copy.copy(additional_lookup) for additional_lookup in getattr(rel_qs, '_prefetch_related_lookups', ()) ] if additional_lookups: # Don't need to clone because the manager should have given us a fresh # instance, so we access an internal instead of using public interface # for performance reasons. rel_qs._prefetch_related_lookups = () all_related_objects = list(rel_qs) rel_obj_cache = {} for rel_obj in all_related_objects: rel_attr_val = rel_obj_attr(rel_obj) rel_obj_cache.setdefault(rel_attr_val, []).append(rel_obj) to_attr, as_attr = lookup.get_current_to_attr(level) # Make sure `to_attr` does not conflict with a field. if as_attr and instances: # We assume that objects retrieved are homogeneous (which is the premise # of prefetch_related), so what applies to first object applies to all. model = instances[0].__class__ try: model._meta.get_field(to_attr) except exceptions.FieldDoesNotExist: pass else: msg = 'to_attr={} conflicts with a field on the {} model.' raise ValueError(msg.format(to_attr, model.__name__)) # Whether or not we're prefetching the last part of the lookup. leaf = len(lookup.prefetch_through.split(LOOKUP_SEP)) - 1 == level for obj in instances: instance_attr_val = instance_attr(obj) vals = rel_obj_cache.get(instance_attr_val, []) if single: val = vals[0] if vals else None to_attr = to_attr if as_attr else cache_name setattr(obj, to_attr, val) else: if as_attr: setattr(obj, to_attr, vals) else: manager = getattr(obj, to_attr) if leaf and lookup.queryset is not None: try: apply_rel_filter = manager._apply_rel_filters except AttributeError: warnings.warn( "The `%s.%s` class must implement a `_apply_rel_filters()` " "method that accepts a `QuerySet` as its single " "argument and returns an appropriately filtered version " "of it." % (manager.__class__.__module__, manager.__class__.__name__), RemovedInDjango20Warning, ) qs = manager.get_queryset() else: qs = apply_rel_filter(lookup.queryset) else: qs = manager.get_queryset() qs._result_cache = vals # We don't want the individual qs doing prefetch_related now, # since we have merged this into the current work. qs._prefetch_done = True obj._prefetched_objects_cache[cache_name] = qs return all_related_objects, additional_lookups class RelatedPopulator(object): """ RelatedPopulator is used for select_related() object instantiation. The idea is that each select_related() model will be populated by a different RelatedPopulator instance. The RelatedPopulator instances get klass_info and select (computed in SQLCompiler) plus the used db as input for initialization. That data is used to compute which columns to use, how to instantiate the model, and how to populate the links between the objects. The actual creation of the objects is done in populate() method. This method gets row and from_obj as input and populates the select_related() model instance. """ def __init__(self, klass_info, select, db): self.db = db # Pre-compute needed attributes. The attributes are: # - model_cls: the possibly deferred model class to instantiate # - either: # - cols_start, cols_end: usually the columns in the row are # in the same order model_cls.__init__ expects them, so we # can instantiate by model_cls(*row[cols_start:cols_end]) # - reorder_for_init: When select_related descends to a child # class, then we want to reuse the already selected parent # data. However, in this case the parent data isn't necessarily # in the same order that Model.__init__ expects it to be, so # we have to reorder the parent data. The reorder_for_init # attribute contains a function used to reorder the field data # in the order __init__ expects it. # - pk_idx: the index of the primary key field in the reordered # model data. Used to check if a related object exists at all. # - init_list: the field attnames fetched from the database. For # deferred models this isn't the same as all attnames of the # model's fields. # - related_populators: a list of RelatedPopulator instances if # select_related() descends to related models from this model. # - cache_name, reverse_cache_name: the names to use for setattr # when assigning the fetched object to the from_obj. If the # reverse_cache_name is set, then we also set the reverse link. select_fields = klass_info['select_fields'] from_parent = klass_info['from_parent'] if not from_parent: self.cols_start = select_fields[0] self.cols_end = select_fields[-1] + 1 self.init_list = [ f[0].target.attname for f in select[self.cols_start:self.cols_end] ] self.reorder_for_init = None else: model_init_attnames = [ f.attname for f in klass_info['model']._meta.concrete_fields ] reorder_map = [] for idx in select_fields: field = select[idx][0].target init_pos = model_init_attnames.index(field.attname) reorder_map.append((init_pos, field.attname, idx)) reorder_map.sort() self.init_list = [v[1] for v in reorder_map] pos_list = [row_pos for _, _, row_pos in reorder_map] def reorder_for_init(row): return [row[row_pos] for row_pos in pos_list] self.reorder_for_init = reorder_for_init self.model_cls = klass_info['model'] self.pk_idx = self.init_list.index(self.model_cls._meta.pk.attname) self.related_populators = get_related_populators(klass_info, select, self.db) field = klass_info['field'] reverse = klass_info['reverse'] self.reverse_cache_name = None if reverse: self.cache_name = field.remote_field.get_cache_name() self.reverse_cache_name = field.get_cache_name() else: self.cache_name = field.get_cache_name() if field.unique: self.reverse_cache_name = field.remote_field.get_cache_name() def populate(self, row, from_obj): if self.reorder_for_init: obj_data = self.reorder_for_init(row) else: obj_data = row[self.cols_start:self.cols_end] if obj_data[self.pk_idx] is None: obj = None else: obj = self.model_cls.from_db(self.db, self.init_list, obj_data) if obj and self.related_populators: for rel_iter in self.related_populators: rel_iter.populate(row, obj) setattr(from_obj, self.cache_name, obj) if obj and self.reverse_cache_name: setattr(obj, self.reverse_cache_name, from_obj) def get_related_populators(klass_info, select, db): iterators = [] related_klass_infos = klass_info.get('related_klass_infos', []) for rel_klass_info in related_klass_infos: rel_cls = RelatedPopulator(rel_klass_info, select, db) iterators.append(rel_cls) return iterators
[ "pochi.0226.ogi@gmail.com" ]
pochi.0226.ogi@gmail.com
9fc4afdce1677636caaab75e822230cf6fee86fa
abba8b8b92125735ebff2f5f783870f80c27bd1f
/restful/hawkeye/sqlaudit/migrations/0016_audit_job_order_by.py
f5771775bdf3af5e19c16127cc0d362596261fd1
[]
no_license
zsprn123/yunqu
25a5463aaece2d3f8749c6ef588ad4fcb3651360
af43f8b42129be5be82db2607c40480028057273
refs/heads/master
2022-12-22T04:37:59.989122
2018-08-30T07:59:41
2018-08-30T07:59:41
146,715,198
0
2
null
2022-12-08T00:45:43
2018-08-30T07:52:07
Roff
UTF-8
Python
false
false
747
py
# uncompyle6 version 3.2.3 # Python bytecode 3.6 (3379) # Decompiled from: Python 2.7.5 (default, Jul 13 2018, 13:06:57) # [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] # Embedded file name: ./sqlaudit/migrations/0016_audit_job_order_by.py # Compiled at: 2018-08-23 19:33:14 # Size of source mod 2**32: 482 bytes from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sqlaudit', '0015_audit_rule_modifiable')] operations = [ migrations.AddField(model_name='audit_job', name='order_by', field=models.CharField(blank=True, max_length=100, null=True))] # okay decompiling ./restful/hawkeye/sqlaudit/migrations/0016_audit_job_order_by.pyc
[ "you@example.com" ]
you@example.com
6921d1181168b4de55ad19a7812ef5295958887f
88994e2e840a70ec702cee09e1a13813aa6f800c
/cg/cli/compress/helpers.py
9197d3ccbcd0101568be05fddb32f471e48d25fd
[]
no_license
Clinical-Genomics/cg
1e9eb0852f742d555a48e8696914ebe177f7d436
d2ec6d25b577dd6938bbf92317aeff1d6b3c5b08
refs/heads/master
2023-09-01T02:04:04.229120
2023-08-31T13:50:31
2023-08-31T13:50:31
82,567,026
19
8
null
2023-09-14T15:24:13
2017-02-20T14:29:43
Python
UTF-8
Python
false
false
8,507
py
"""Helper functions for compress cli.""" import datetime as dt import logging import os from math import ceil from pathlib import Path from typing import Iterator, Optional, List from housekeeper.store.models import Version, Bundle from cg.apps.housekeeper.hk import HousekeeperAPI from cg.constants.compression import CASES_TO_IGNORE, MAX_READS_PER_GB, CRUNCHY_MIN_GB_PER_PROCESS from cg.constants.slurm import Slurm from cg.utils.date import get_date_days_ago from cg.exc import CaseNotFoundError from cg.meta.compress import CompressAPI from cg.meta.compress.files import get_spring_paths from cg.store import Store from cg.store.models import Family LOG = logging.getLogger(__name__) def get_cases_to_process( days_back: int, store: Store, case_id: Optional[str] = None ) -> Optional[List[Family]]: """Return cases to process.""" cases: List[Family] = [] if case_id: case: Family = store.get_case_by_internal_id(internal_id=case_id) if not case: LOG.warning(f"Could not find case {case_id}") return cases.append(case) else: date_threshold: dt.datetime = get_date_days_ago(days_ago=days_back) cases: List[Family] = store.get_cases_to_compress(date_threshold=date_threshold) return cases def get_fastq_individuals(store: Store, case_id: str = None) -> Iterator[str]: """Fetch individual ids from cases that are ready for SPRING compression""" case_obj = store.get_case_by_internal_id(internal_id=case_id) if not case_obj: LOG.error("Could not find case %s", case_id) raise CaseNotFoundError("") for link_obj in case_obj.links: yield link_obj.sample.internal_id def is_case_ignored(case_id: str) -> bool: """Check if case should be skipped.""" if case_id in CASES_TO_IGNORE: LOG.debug(f"Skipping case: {case_id}") return True return False def set_memory_according_to_reads( sample_id: str, sample_reads: Optional[int] = None, sample_process_mem: Optional[int] = None ) -> Optional[int]: """Set SLURM sample process memory depending on number of sample reads if sample_process_mem is not set.""" if sample_process_mem: return sample_process_mem if not sample_reads: LOG.debug(f"No reads recorded for sample: {sample_id}") return sample_process_mem: int = ceil((sample_reads / MAX_READS_PER_GB)) if sample_process_mem < CRUNCHY_MIN_GB_PER_PROCESS: return CRUNCHY_MIN_GB_PER_PROCESS if CRUNCHY_MIN_GB_PER_PROCESS <= sample_process_mem < Slurm.MAX_NODE_MEMORY.value: return sample_process_mem return Slurm.MAX_NODE_MEMORY.value def update_compress_api( compress_api: CompressAPI, dry_run: bool, hours: int = None, mem: int = None, ntasks: int = None ) -> None: """Update parameters in Compress API.""" compress_api.set_dry_run(dry_run=dry_run) if mem: LOG.info(f"Set Crunchy API SLURM mem to {mem}") compress_api.crunchy_api.slurm_memory = mem if hours: LOG.info(f"Set Crunchy API SLURM hours to {hours}") compress_api.crunchy_api.slurm_hours = hours if ntasks: LOG.info(f"Set Crunchy API SLURM number of tasks to {ntasks}") compress_api.crunchy_api.slurm_number_tasks = ntasks # Functions to fix problematic spring files def get_versions(hk_api: HousekeeperAPI, bundle_name: str = None) -> Iterator[Version]: """Generates versions from hk bundles. If no bundle name is given generate latest version for every bundle. """ if bundle_name: bundle: Bundle = hk_api.bundle(bundle_name) if not bundle: LOG.info(f"Could not find bundle {bundle_name}") return bundles: List[Bundle] = [bundle] else: bundles: List[Bundle] = hk_api.bundles() for bundle in bundles: LOG.debug(f"Check for versions in {bundle.name}") last_version: Version = hk_api.last_version(bundle.name) if not last_version: LOG.warning(f"No bundle found for {bundle.name} in Housekeeper") return yield last_version def get_true_dir(dir_path: Path) -> Optional[Path]: """Loop over the files in a directory, if any symlinks are found return the parent dir of the origin file.""" # Check if there are any links to fastq files in the directory for fastq_path in dir_path.rglob("*"): # Check if there are fastq symlinks that points to the directory where the spring # path is located if fastq_path.is_symlink(): return Path(os.readlink(fastq_path)).parent LOG.info("Could not find any symlinked files") return None def compress_sample_fastqs_in_cases( compress_api: CompressAPI, cases: List[Family], dry_run: bool, number_of_conversions: int, hours: int = None, mem: int = None, ntasks: int = None, ) -> None: """Compress sample FASTQs for samples in cases.""" case_conversion_count: int = 0 individuals_conversion_count: int = 0 for case in cases: case_converted = True if case_conversion_count >= number_of_conversions: break if is_case_ignored(case_id=case.internal_id): continue LOG.info(f"Searching for FASTQ files in case {case.internal_id}") if not case.links: continue for case_link in case.links: sample_process_mem: Optional[int] = set_memory_according_to_reads( sample_process_mem=mem, sample_id=case_link.sample.internal_id, sample_reads=case_link.sample.reads, ) update_compress_api( compress_api=compress_api, dry_run=dry_run, hours=hours, mem=sample_process_mem, ntasks=ntasks, ) case_converted: bool = compress_api.compress_fastq( sample_id=case_link.sample.internal_id ) if not case_converted: LOG.info(f"skipping individual {case_link.sample.internal_id}") continue individuals_conversion_count += 1 if case_converted: case_conversion_count += 1 LOG.info(f"Considering case {case.internal_id} converted") LOG.info( f"{individuals_conversion_count} individuals in {case_conversion_count} (completed) cases where compressed" ) def correct_spring_paths( hk_api: HousekeeperAPI, bundle_name: str = None, dry_run: bool = False ) -> None: """Function that will be used as a one off thing. There has been a problem when there are symlinked fastq files that are sent for compression. In these cases the spring archive has been created in the same place as that the symlinks are pointing to. This function will find those cases and move the spring archives to the correct place as specified in housekeeper. """ versions = get_versions(hk_api=hk_api, bundle_name=bundle_name) for version_obj in versions: spring_paths = get_spring_paths(version_obj) i = 0 for i, compression_obj in enumerate(spring_paths, 1): # We are interested in fixing the cases where spring paths are in wrong location spring_path = compression_obj.spring_path if spring_path.exists(): continue # true_dir is where the spring paths actually exists true_dir = get_true_dir(spring_path.parent) if not true_dir: LOG.info("Could not find location of spring files") continue true_spring_path = true_dir / spring_path.name true_spring_config_path = true_spring_path.with_suffix("").with_suffix(".json") if not (true_spring_path.exists() and true_spring_config_path.exists()): LOG.info("Could not find spring and/or spring metadata files, skipping") continue LOG.info( "Moving existing spring file (and config) %s to hk bundle path %s", true_spring_path, spring_path, ) if not dry_run: # We know from above that the spring path does not exist true_spring_path.replace(spring_path) true_spring_config_path.replace(compression_obj.spring_metadata_path) if i == 0: LOG.debug("Could not find any spring files")
[ "noreply@github.com" ]
Clinical-Genomics.noreply@github.com
cd22488a350f2b43cb16bd6a6f611cf67a94ffae
b39b0625795b0640a6a68151f2012ce139f423b8
/iaas/swagger_client/models/about.py
334b7e2cf81e71d74af5081dceae3c76a5550981
[]
no_license
darrylcauldwell/casCodegen
8e82b1f08e8260482996aec3d8be10934a65dd03
1f1ff9ab8a33102bcfcb8be276d51992d96bcb61
refs/heads/master
2020-07-27T14:42:28.550855
2019-09-17T18:30:28
2019-09-17T18:30:28
209,127,702
0
0
null
null
null
null
UTF-8
Python
false
false
4,599
py
# coding: utf-8 """ VMware Cloud Assembly IaaS API A multi-cloud IaaS API for Cloud Automation Services # noqa: E501 OpenAPI spec version: 2019-01-15 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from swagger_client.models.api_description import ApiDescription # noqa: F401,E501 class About(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'supported_apis': 'list[ApiDescription]', 'latest_api_version': 'str' } attribute_map = { 'supported_apis': 'supportedApis', 'latest_api_version': 'latestApiVersion' } def __init__(self, supported_apis=None, latest_api_version=None): # noqa: E501 """About - a model defined in Swagger""" # noqa: E501 self._supported_apis = None self._latest_api_version = None self.discriminator = None self.supported_apis = supported_apis self.latest_api_version = latest_api_version @property def supported_apis(self): """Gets the supported_apis of this About. # noqa: E501 A collection of all currently supported api versions. # noqa: E501 :return: The supported_apis of this About. # noqa: E501 :rtype: list[ApiDescription] """ return self._supported_apis @supported_apis.setter def supported_apis(self, supported_apis): """Sets the supported_apis of this About. A collection of all currently supported api versions. # noqa: E501 :param supported_apis: The supported_apis of this About. # noqa: E501 :type: list[ApiDescription] """ if supported_apis is None: raise ValueError("Invalid value for `supported_apis`, must not be `None`") # noqa: E501 self._supported_apis = supported_apis @property def latest_api_version(self): """Gets the latest_api_version of this About. # noqa: E501 The latest version of the API in yyyy-MM-dd format (UTC). # noqa: E501 :return: The latest_api_version of this About. # noqa: E501 :rtype: str """ return self._latest_api_version @latest_api_version.setter def latest_api_version(self, latest_api_version): """Sets the latest_api_version of this About. The latest version of the API in yyyy-MM-dd format (UTC). # noqa: E501 :param latest_api_version: The latest_api_version of this About. # noqa: E501 :type: str """ if latest_api_version is None: raise ValueError("Invalid value for `latest_api_version`, must not be `None`") # noqa: E501 self._latest_api_version = latest_api_version def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(About, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, About): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "dcauldwell@dcauldwell-a01.vmware.com" ]
dcauldwell@dcauldwell-a01.vmware.com
d53fe1614b6fb99c58bfcf7d574886de8ea4f545
8cb8bfd2dae516612251039e0632173ea1ea4c8a
/modules/analyzes/machineEngine/roomtype/models.py
8ad4ce9eb8cfffd190d4ad6c57654fa3fdbbccf6
[]
no_license
nyzsirt/lift-prod
563cc70700d26a5812a1bce0bd9795998dce6e99
9a5f28e49ad5e80e422a5d5efee77a2d0247aa2b
refs/heads/master
2020-04-22T01:05:42.262876
2019-02-09T13:31:15
2019-02-09T13:31:15
170,003,361
1
0
null
2019-02-10T17:11:50
2019-02-10T17:11:50
null
UTF-8
Python
false
false
690
py
import datetime from mongoengine import Document from mongoengine import StringField from mongoengine import DateTimeField from mongoengine import ObjectIdField from mongoengine import ReferenceField from modules.organization.models import Organization class EngineRoomType(Document): _created_date = DateTimeField(default=datetime.datetime.utcnow) _key_created_user = ObjectIdField() _last_modified_date = DateTimeField(default=datetime.datetime.utcnow) _key_last_modified_user = ObjectIdField() _key_owner_user = ObjectIdField() _key_organization = ReferenceField(Organization, required=True, reverse_delete_rule=2) room_type = StringField(required=True)
[ "mutlu.erdem@soft-nec.com" ]
mutlu.erdem@soft-nec.com
1778ed78624eff11d3904af6036e7ff72823d4e4
2354fbbc1b6497d3a5f78e12783fe760e43f99fb
/LeetCode Problems/Design/Insert Delete GetRandom.py
ea5730b4603d533c4ca4a9e6a4381eeeaf9d90af
[]
no_license
GZHOUW/Algorithm
34ee3650a5fad1478fb3922ea69ccafc134520c9
7eddbc93a237d1d5cabcdc67806b01ff55ea8562
refs/heads/master
2021-03-27T07:57:31.247576
2021-01-06T19:53:38
2021-01-06T19:53:38
247,803,659
0
0
null
null
null
null
UTF-8
Python
false
false
2,183
py
''' Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the set if not already present. remove(val): Removes an item val from the set if present. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. Example: // Init an empty set. RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomSet.insert(1); // Returns false as 2 does not exist in the set. randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. randomSet.insert(2); // getRandom should return either 1 or 2 randomly. randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2]. randomSet.remove(1); // 2 was already in the set, so return false. randomSet.insert(2); // Since 2 is the only number in the set, getRandom always return 2. randomSet.getRandom(); ''' class RandomizedSet: def __init__(self): """ Initialize your data structure here. """ self.s = set() def insert(self, val): """ Inserts a value to the set. Returns true if the set did not already contain the specified element. """ if val not in self.s: self.s.add(val) return True else: return False def remove(self, val): """ Removes a value from the set. Returns true if the set contained the specified element. """ if val in self.s: self.s.remove(val) return True else: return False def getRandom(self): """ Get a random element from the set. """ idx = 0 randIdx = random.randint(0, len(self.s)-1) # if only one number, randIdx must be 0 for number in self.s: if idx == randIdx: return number idx += 1 # Your RandomizedSet object will be instantiated and called as such: # obj = RandomizedSet() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()
[ "noreply@github.com" ]
GZHOUW.noreply@github.com
66d7e2a9ecbd1f2f21935027597070475f279214
2729999511025ae93a46a402e8611000e63fc5b8
/apps/useradmin/src/useradmin/organization.py
3f34820b743163d309a0ae770f5d94bf9d0b919d
[ "Apache-2.0" ]
permissive
happydentist/hue
19cb3abfa42e70844ef609b346c195e3a99a48b0
9928284e284f9a0586bd2080932f4b25bb5d8708
refs/heads/master
2020-12-27T10:40:28.312883
2020-01-31T03:14:18
2020-01-31T15:45:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,908
py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from crequest.middleware import CrequestMiddleware from desktop.conf import ENABLE_ORGANIZATIONS def default_organization(): from useradmin.models import Organization default_organization, created = Organization.objects.get_or_create(name='default', domain='default') return default_organization def get_user_request_organization(): request = CrequestMiddleware.get_request() return request.user.organization if request and hasattr(request, 'user') and request.user.is_authenticated() else default_organization() def _fitered_queryset(queryset, by_owner=False): request = CrequestMiddleware.get_request() # Avoid infinite recursion on very first retrieval of the user if ENABLE_ORGANIZATIONS.get() and \ request and hasattr(request, 'user') and hasattr(request.user, '_wrapped') and type(request.user._wrapped) is not object and \ request.user.is_authenticated(): if by_owner: filters = {'owner__organization': request.user.organization} else: filters = {'organization': request.user.organization} queryset = queryset.filter(**filters) return queryset
[ "romain.rigaux@gmail.com" ]
romain.rigaux@gmail.com
b5367669021499867b783804a735c7fee14b1986
90a1aa497ec53fa87bc31cd5101ad55adb22cddb
/cython/basic_demo/main.py
76bf101c1dca320a8313f60a8bac0c50e6eafd19
[]
no_license
ybdesire/pylearn
39821e3e5cb61c021afc7af2052e0de7077961e2
400e525c0529bea6da74aab9bc86fe5e26549d32
refs/heads/master
2023-02-04T02:08:44.352846
2023-01-28T09:28:34
2023-01-28T09:28:34
79,337,563
2
1
null
null
null
null
UTF-8
Python
false
false
246
py
# environment: linx import time import pyximport pyximport.install( reload_support=True) import calc start_time = time.time() for i in range(10000000): calc.fun(i) print('costed {} seconds'.format(time.time() - start_time))
[ "ybdesire@gmail.com" ]
ybdesire@gmail.com
ac01c55d0bebdd3d33f68faffffadc3fbd7e7962
60fedc4e31e70dfbec2542751aa0a02ba21a54a3
/tests/test_registrar_name/test_authenticate.py
56611d3122796d56549e0656e85ec682d4ccc038
[ "MIT" ]
permissive
Robpol86/UnofficialDDNSnix
791c2b1f801918c775e2ebc228a3385a253a66ae
de3e63927da5e76b685aeeabdb43ef36ecefbba5
refs/heads/master
2021-08-19T05:14:59.026176
2016-01-09T05:32:05
2016-01-09T05:32:05
15,039,836
3
3
MIT
2020-04-17T07:46:53
2013-12-09T06:25:00
Python
UTF-8
Python
false
false
7,437
py
#!/usr/bin/env python2.6 import textwrap import pytest import time from tests.test_registrar_name.test_request_json import initialize_simulation def _heavy_lifting(response, log_file, session, expected_exc, capsys, stdout_expected, stderr_expected, log_expected): initialize_simulation(response) with open(log_file.name, 'r') as f: f.seek(0, 2) log_before_pos = f.tell() with pytest.raises(session.RegistrarException) as e: session.authenticate() assert expected_exc == str(e.value) stdout_actual, stderr_actual = capsys.readouterr() assert stdout_expected == stdout_actual assert stderr_expected == stderr_actual with open(log_file.name, 'r') as f: f.seek(log_before_pos) log_actual = f.read(10240) assert log_expected == log_actual def test_authenticate_missing_json_key(session, log_file, capsys): response = '{"result":{"code":100,"message":"Command Successful"},"bar":["baz", null, 1.0, 2]}' json = "{u'bar': [u'baz', None, 1.0, 2], u'result': {u'message': u'Command Successful', u'code': 100}}" expected_exc = "'session_token' not in JSON." stdout_expected = textwrap.dedent("""\ Method authenticate start. Opening connection to {url} Response: {response} JSON: {json} """.format(url="http://127.0.0.1/login", response=response, json=json)) stderr_expected = '' timestamp = time.strftime("%Y-%m-%dT%H:%M:%S") log_expected = textwrap.dedent("""\ {ts} DEBUG registrar_base.authenticate Method authenticate start. {ts} DEBUG registrar_base._request_json Opening connection to {url} {ts} DEBUG registrar_base.authenticate Response: {response} {ts} DEBUG registrar_base.authenticate JSON: {json} """.format(url="http://127.0.0.1/login", response=response, json=json, ts=timestamp)) _heavy_lifting(response, log_file, session, expected_exc, capsys, stdout_expected, stderr_expected, log_expected) def test_authenticate_missing_json_value(session, log_file, capsys): response = '{"result":{"code":100,"message":"Command Successful"},"bar":["baz", null, 1.0, 2], "session_token":""}' json = "{u'bar': [u'baz', None, 1.0, 2], u'result': {u'message': u'Command Successful', u'code': 100}, u'session_token': u''}" expected_exc = "'session_token' is invalid." stdout_expected = textwrap.dedent("""\ Method authenticate start. Opening connection to {url} Response: {response} JSON: {json} """.format(url="http://127.0.0.1/login", response=response, json=json)) stderr_expected = '' timestamp = time.strftime("%Y-%m-%dT%H:%M:%S") log_expected = textwrap.dedent("""\ {ts} DEBUG registrar_base.authenticate Method authenticate start. {ts} DEBUG registrar_base._request_json Opening connection to {url} {ts} DEBUG registrar_base.authenticate Response: {response} {ts} DEBUG registrar_base.authenticate JSON: {json} """.format(url="http://127.0.0.1/login", response=response, json=json, ts=timestamp)) _heavy_lifting(response, log_file, session, expected_exc, capsys, stdout_expected, stderr_expected, log_expected) def test_authenticate_invalid_json_value(session, log_file, capsys): response = '{"result":{"code":100,"message":"Command Successful"},"bar":["baz", null, 1.0, 2], "session_token":"127..0.1"}' json = "{u'bar': [u'baz', None, 1.0, 2], u'result': {u'message': u'Command Successful', u'code': 100}, u'session_token': u'127..0.1'}" expected_exc = "'session_token' is invalid." stdout_expected = textwrap.dedent("""\ Method authenticate start. Opening connection to {url} Response: {response} JSON: {json} """.format(url="http://127.0.0.1/login", response=response, json=json)) stderr_expected = '' timestamp = time.strftime("%Y-%m-%dT%H:%M:%S") log_expected = textwrap.dedent("""\ {ts} DEBUG registrar_base.authenticate Method authenticate start. {ts} DEBUG registrar_base._request_json Opening connection to {url} {ts} DEBUG registrar_base.authenticate Response: {response} {ts} DEBUG registrar_base.authenticate JSON: {json} """.format(url="http://127.0.0.1/login", response=response, json=json, ts=timestamp)) _heavy_lifting(response, log_file, session, expected_exc, capsys, stdout_expected, stderr_expected, log_expected) def test_authenticate_bad_credentials(session, log_file, capsys): response = '{"result":{"code":221,"message":"Authorization Error - Username Or Ip Token Invalid"}}' json = "{u'result': {u'message': u'Authorization Error - Username Or Ip Token Invalid', u'code': 221}}" expected_exc = "Authorization Error or invalid username and/or password." stdout_expected = textwrap.dedent("""\ Method authenticate start. Opening connection to {url} Response: {response} JSON: {json} """.format(url="http://127.0.0.1/login", response=response, json=json)) stderr_expected = '' timestamp = time.strftime("%Y-%m-%dT%H:%M:%S") log_expected = textwrap.dedent("""\ {ts} DEBUG registrar_base.authenticate Method authenticate start. {ts} DEBUG registrar_base._request_json Opening connection to {url} {ts} DEBUG registrar_name._request_json Response: {response} {ts} DEBUG registrar_name._request_json JSON: {json} """.format(url="http://127.0.0.1/login", response=response, json=json, ts=timestamp)) _heavy_lifting(response, log_file, session, expected_exc, capsys, stdout_expected, stderr_expected, log_expected) # noinspection PyProtectedMember def test_authenticate_success(session, log_file, capsys): response = '{"result":{"code":100,"message":"Command Successful"},"session_token":"2352e5c5a0127d2155377664a5543f22a70be187"}' json = "{u'client_ip': u'127.0.0.1', u'service': u'Name.com API Test Server', u'language': u'en', u'version': u'2.0', u'result': {u'message': u'Command Successful', u'code': 100}, u'server_date': u'2013-12-28 04:46:38'}" expected_token = "2352e5c5a0127d2155377664a5543f22a70be187" stdout_expected = textwrap.dedent("""\ Method authenticate start. Opening connection to {url} Method authenticate end. """.format(url="http://127.0.0.1/login", response=response, json=json)) stderr_expected = '' timestamp = time.strftime("%Y-%m-%dT%H:%M:%S") log_expected = textwrap.dedent("""\ {ts} DEBUG registrar_base.authenticate Method authenticate start. {ts} DEBUG registrar_base._request_json Opening connection to {url} {ts} DEBUG registrar_base.authenticate Method authenticate end. """.format(url="http://127.0.0.1/login", response=response, json=json, ts=timestamp)) initialize_simulation(response) with open(log_file.name, 'r') as f: f.seek(0, 2) log_before_pos = f.tell() session.authenticate() assert expected_token == session._session_token stdout_actual, stderr_actual = capsys.readouterr() assert stdout_expected == stdout_actual assert stderr_expected == stderr_actual with open(log_file.name, 'r') as f: f.seek(log_before_pos) log_actual = f.read(10240) assert log_expected == log_actual
[ "robpol86@gmail.com" ]
robpol86@gmail.com
8d628b240c470b3b6d14c99e92892957c4e19fec
ac33e7a30131db58f0e72c9bf1f79cd34a38d335
/manufacturing/doctype/stability_study_report_child/stability_study_report_child.py
db1427f55fb00191d9423c79a8302e72878ad791
[]
no_license
mbhavesh95863/erpnext
395d545292c67cc5d6d7be3029d03245c754d984
d6c490e4a404235abe9b4d541de1bbb53ba32949
refs/heads/master
2020-03-26T20:03:45.620397
2018-08-19T12:46:43
2018-08-19T12:46:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
291
py
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class StabilityStudyReportChild(Document): pass
[ "erpnextdeveloper1@gmail.com" ]
erpnextdeveloper1@gmail.com
ad498b8d3ca18f5d619331ca3bb62c7b5c9be603
ca44cdd205d27fc5cfabaaa349e93afddd7c902b
/hm3/hw3_other_tasks.py
2462346a4756a4a7109758d5642e65012f7a255f
[]
no_license
SOFIAshyn/BaseProgramming_course_Basic_Python
8402b7c2eff570e7102ba1f9b0b6636a6f0b881a
cf4d0d204a836367ee51e329828a53072aef20e9
refs/heads/master
2021-10-21T08:02:35.611635
2019-03-03T15:46:59
2019-03-03T15:46:59
173,553,760
0
0
null
null
null
null
UTF-8
Python
false
false
2,384
py
def is_power_of_two(val): """ (int) -> bool Determine if a number is a power of two. >>> is_power_of_two([0]) >>> is_power_of_two("0") >>> is_power_of_two(0) False >>> is_power_of_two(1) True >>> is_power_of_two(2) True >>> is_power_of_two(15) False >>> is_power_of_two(16) True """ try: if val > 0 and val % 2 == 0 or val == 1: while val != 2: if val % 2 == 0: val /= 2 else: break if val == 2 or val == 1: return True else: return False else: return False except TypeError as err: return None print(is_power_of_two(24)) # # # def has_unique_chars(string): # """ # (str) -> bool # # An algorithm to determine if a string has all unique characters. # # >>> has_unique_chars(None) # False # >>> has_unique_chars('') # True # >>> has_unique_chars('foo') # False # >>> has_unique_chars('bar') # True # """ # if type(string) == str: # for letter in string: # if string.count(letter) > 1: # return False # return True # else: # return False # # print(has_unique_chars("foo")) # # def compress(string): # """ # (str) -> str # # Compress a string such that 'AAABCCDDDD' becomes 'A3BC2D4'. # Only compress the string if it saves space. # # >>> compress(None) # # >>> compress('') # '' # >>> compress('AABBCC') # 'AABBCC' # >>> compress('AAABCCDDDDE') # 'A3BC2D4E' # >>> compress('BAAACCDDDD') # 'BA3C2D4' # >>> compress('AAABAACCDDDD') # 'A3BA2C2D4' # """ # if type(string) == str: # prev = "" # count = 1 # new_str = "" # for letter in string + " ": # if letter == prev: # count += 1 # else: # if count != 1: # new_str += prev + str(count) # else: # new_str += prev # count = 1 # prev = letter # if len(new_str) == len(string): # new_str = string # return new_str # else: # return None # # print(compress(None)) # # import doctest doctest.testmod()
[ "sophiya2petryshyn@gmail.com" ]
sophiya2petryshyn@gmail.com
f857702b7d0e2829e1575beb8990cbe95f3afd23
1d103214adcd3d7834ec85308e14c160df14c5f0
/pykrylov/irlba.py
b901af8195e6411ff255e6994344609483800a65
[]
no_license
ericmjonas/pykrylov
c41a22d82c345d3223cac9bd85e5ddfd89d8fe92
b1022dbf07a9be601a2c23c285175281a2c48ded
refs/heads/master
2020-05-16T20:30:14.301575
2014-07-29T21:20:27
2014-07-29T21:20:27
22,395,012
2
0
null
null
null
null
UTF-8
Python
false
false
6,951
py
import numpy as np import scipy.linalg import util import lanczos from util import norm EPS = np.finfo(float).eps def ordered_svd(X): """ returns the svd ordered by singular value largest to smallest """ u, s, v = np.linalg.svd(X) if (np.sort(s) != s[::-1]).any(): raise Exception("NTO SORTED"); return u, s, v.T def irlba(A, K=6, largest=True, adjust = 3, aug=None, disps=0, maxit=1000, m_b=20, reorth_two = False, tol=1e-6, V0=None): """ This is a port of IRLBA.m following the code there very closely """ # FIXME do interchange stuff m, n = A.dims() # interchange m and n so that size(A*A) = min(m, n) # avoids finding zero values when searching for the smallest singular values interchange = False if n > m and largest == False: t = m m = n n = t interchange = True raise Exception("Don't do interchange yet") W = np.zeros((m, m_b)) F = np.zeros((n, 1)) V = np.zeros((n, m_b)) # Preallocate for V if V0 == None: V[:, 0] = np.arange(1, n+1) V[:, 0] = V[:, 0] / np.sum(V[:, 0]) # np.random.normal(0, 1, n) else: V[:, :V0.shape[1]] = V0 # increase the number of desired values by adjust to help increase convergence. # K is re-adjusted as vectors converged. This is only an initial value of K K_org = K K += adjust # sanity checking for input values if K <= 0: raise Exception("K must be a positive Value") if K > min(n, m): raise Exception("K must be less than min(n, m) + %d" % adjust) if m_b <= 1: raise Exception("M_B must be > 1") # FIXME clean up parameters A LOT if aug == None: if largest == True: aug = 'RITZ' else: aug = 'HARM' # set tolerance to machine precision tol = max(tol, EPS) # begin initialization B = [] Bsz = [] conv = False EPS23 = EPS**(2/3.0) iteration = 0 J = 0 mprod = 0 R_F = [] SQRTEPS = np.sqrt(EPS) Smax = 1 # holds the maximum value of all computed singular values of B est. ||A||_2 Smin = [] # holds the minimum value of all computed singular values of B est. cond(A) SVTol = min(SQRTEPS, tol) # tolerance to determine whether a singular value has converged S_B = [] # singular values of B U_B = [] # Left singular vectors of B V_B = [] # right singular vectors of B V_B_last = [] # holds the last row of the modified V_B S_B2 = [] # singular values of [B ||F||] U_B2 = [] # left singular vectors of [B ||F||] V_B2 = [] # right signular vectors of [b || F||] while iteration < maxit: V, W, F, B, mprod = lanczos.ablanzbd(A, V, W, F, B, K, interchange, m_b, n, m, SVTol*Smax, reorth_two, iteration) # determine the size of the bidiagonal matrix B Bsz = B.shape[0] # compute the norm of the vector F, and normalize F R_F = norm(F) F = F/R_F # compute singular triplets of B U_B, S_B, V_B = ordered_svd(B) # estimate ||A|| using the largest singular value ofer all # all iterations and estimate the cond(A) using approximations # to the largest and smallest singular values. If a small singular value # is less than sqrteps use only Rtiz vectors # to augment and require two-sided reorthogonalization if iteration == 0: Smax = S_B[0]; Smin = S_B[-1] else: Smax = max(Smax, S_B[0]) Smin = min(Smin, S_B[-1]) Smax = max(EPS23, Smax) if Smin/Smax < SQRTEPS: reorth_two = True aug = 'RITZ' # re-order the singular values if we're looking for the smallest ones if not largest: U_B = U_B[:, ::-1] S_B = S_B[::-1] V_B = V_B[:, ::-1] # compute the residuals R = np.dot(R_F, U_B[-1,:]) # convergest tests and displays conv, U_B, S_B, V_B, K = convtests(Bsz, disps, tol, K_org, U_B, S_B, V_B, abs(R), iteration, K, SVTol, Smax) if conv: # all singular values within tolerance, return ! break # yay if iteration > maxit: break # boo # compute starting vectors and first block: if aug == "HARM": # update the SVD of B to be the SVD of [B ||F||F E_m] U_B2, S_B, V_B2 = ordered_svd(np.c_[np.diag(S_B), R.T]) if not largest: # pick the last ones U_B2 = U_B2[:, :Bsz] V_B2 = V_B2[:, :Bsz] S_B = S_B[:Bsz] U_B2 = U_B2[:, ::-1] S_B = S_B[::-1] V_B2 = V_B2[:, ::-1] # jesus christ U_B = np.dot(U_B, U_B2) VB_D = np.zeros((V_B.shape[0]+1, V_B.shape[1]+1)) VB_D[:-1, :-1] = V_B VB_D[-1, -1] = 1.0 V_B = np.dot(VB_D, V_B2) V_B_last = V_B[-1, :K] # the last row of V_B int_v = scipy.linalg.solve(B, np.flipud(np.eye(Bsz, 1))) s = np.dot(R_F, int_v) V_B = V_B[:Bsz, :] + s*V_B[Bsz:, :] # vectors are not orthogonal VB_D = np.zeros((V_B.shape[0] +1, K+1)) VB_D[:-1, :K] = V_B[:, :K] VB_D[:-1, K] = -s.T VB_D[-1, -1] = 1.0 V_B, R = np.linalg.qr(VB_D) V[:, :(K+1)] = np.dot(np.c_[V, F], V_B) # upate and compute the K x K+1 part of B w0 = np.outer(R[:, K], V_B_last) w = np.triu((R[:K+1, :K] + w0).T) B = np.dot(np.diag(S_B[:K]), w) else: V[:, :K] = np.dot(V, V_B[:, :K]) V[:, K] = F B = np.c_[np.diag(S_B[:K]), R[:K]] # compute left approximate singular values W[:, :K] = np.dot(W, U_B[:, :K]) iteration += 1 # results if interchange: u = np.dot(V, V_B[:, :K_org]) s = S_B[:K_org] v = np.dot(W, U_B[:, :K_org]) else: u = np.dot(W, U_B[:, :K_org]) s = S_B[:K_org] v = np.dot(V, V_B[:, :K_org]) return u, s, v def convtests(Bsz, disps, tol, K_org, U_B, S_B, V_B, residuals, iter, K, SVTol, Smax): converged = False len_res = np.sum(residuals[:K_org] < (tol*Smax)) if len_res == K_org: return True, U_B[:, :K_org], S_B[:K_org], V_B[:, :K_org], K else: len_res = np.sum(residuals[:K_org] < (SVTol*Smax)) K = max(K, K_org + len_res) if K > Bsz-3: K = Bsz-3 return False, U_B, S_B, V_B, K
[ "jonas@ericjonas.com" ]
jonas@ericjonas.com
5d64acbbf9d0d37fdee9da3b3ce58c7512e93dd1
5d8ab8d8db69ce575e00b473fa1ad18960d9746f
/dcase_util/containers/metadata.py
a1ac1834b2bf237175ee782edfe98651069e0a1a
[ "MIT" ]
permissive
hunterhawk/dcase_util
cd9302d96b13cb79bc7c7753058e4a213b95d2d1
22d80d76233bd2a79fb652f20927bc5c9c3f3655
refs/heads/master
2020-05-03T08:32:34.210516
2019-03-12T18:49:22
2019-03-12T18:49:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
87,311
py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, absolute_import import six import sys import os import copy import numpy import csv import logging import io from dcase_util.containers import ListDictContainer from dcase_util.utils import posix_path, get_parameter_hash, FieldValidator, setup_logging, is_float, is_int, FileFormat from dcase_util.ui import FancyStringifier class MetaDataItem(dict): """Meta data item class, inherited from standard dict class.""" def __init__(self, *args, **kwargs): """Constructor Parameters ---------- dict """ dict.__init__(self, *args) # Compatibility with old field names used in DCASE baseline system implementations 2016 and 2017 if 'file' in self and 'filename' not in self: self['filename'] = self['file'] if 'event_onset' in self and 'onset' not in self: self['onset'] = self['event_onset'] if 'event_offset' in self and 'offset' not in self: self['offset'] = self['event_offset'] # Process meta data fields # File target for the meta data item if 'filename' in self and isinstance(self['filename'], six.string_types): if not os.path.isabs(self['filename']): # Force relative file paths into unix format even under Windows self['filename'] = posix_path(self['filename']) if 'filename_original' in self and isinstance(self['filename_original'], six.string_types): # Keep file paths in unix format even under Windows self['filename_original'] = posix_path(self['filename_original']) # Meta data item timestamps: onset and offset if 'onset' in self: if is_float(self['onset']): self['onset'] = float(self['onset']) else: self['onset'] = None if 'offset' in self: if is_float(self['offset']): self['offset'] = float(self['offset']) else: self['offset'] = None # Event label assigned to the meta data item if 'event_label' in self: self['event_label'] = self['event_label'].strip() if self['event_label'].lower() == 'none' or self['event_label'] == '': self['event_label'] = None # Acoustic scene label assigned to the meta data item if 'scene_label' in self and self.scene_label: self['scene_label'] = self['scene_label'].strip() if self['scene_label'].lower() == 'none': self['scene_label'] = None # Tag labels if 'tags' in self and self.tags: if isinstance(self['tags'], str): self['tags'] = self['tags'].strip() if self['tags'].lower() == 'none': self['tags'] = None if self['tags'] and '#' in self['tags']: self['tags'] = [x.strip() for x in self['tags'].split('#')] elif self['tags'] and ',' in self['tags']: self['tags'] = [x.strip() for x in self['tags'].split(',')] elif self['tags'] and ';' in self['tags']: self['tags'] = [x.strip() for x in self['tags'].split(';')] elif self['tags'] and ':' in self['tags']: self['tags'] = [x.strip() for x in self['tags'].split(':')] else: self['tags'] = [self['tags']] # Remove empty tags self['tags'] = list(filter(None, self['tags'])) # Sort tags self['tags'].sort() def __str__(self): ui = FancyStringifier() output = ui.title(text=self.__class__.__name__) + '\n' output += ui.line(field='Target') + '\n' if self.filename: output += ui.data(indent=4, field='filename', value=self.filename) + '\n' if self.filename_original: output += ui.data(indent=4, field='filename_original', value=self.filename_original) + '\n' if self.identifier: output += ui.data(indent=4, field='identifier', value=self.identifier) + '\n' if self.source_label: output += ui.data(indent=4, field='source_label', value=self.source_label) + '\n' if self.set_label: output += ui.data(indent=4, field='set_label', value=self.set_label) + '\n' if self.onset is not None: output += ui.data(indent=4, field='onset', value=self.onset, unit='sec') + '\n' if self.offset is not None: output += ui.data(indent=4, field='offset', value=self.offset, unit='sec') + '\n' if self.scene_label is not None or self.event_label is not None or self.tags is not None: output += ui.line(field='Meta data') + '\n' if self.scene_label: output += ui.data(indent=4, field='scene_label', value=self.scene_label) + '\n' if self.event_label: output += ui.data(indent=4, field='event_label', value=self.event_label) + '\n' if self.tags: output += ui.data(indent=4, field='tags', value=self.tags) + '\n' output += ui.line(field='Item') + '\n' output += ui.data(indent=4, field='id', value=self.id) + '\n' return output def show(self): """Print container content Returns ------- self """ print(self) def log(self, level='info'): """Log container content Parameters ---------- level : str Logging level, possible values [info, debug, warn, warning, error, critical] Default value "info" Returns ------- self """ from dcase_util.ui import FancyLogger FancyLogger().line(self.__str__(), level=level) @property def logger(self): logger = logging.getLogger(__name__) if not logger.handlers: setup_logging() return logger @property def id(self): """Unique item identifier ID is formed by taking MD5 hash of the item data. Returns ------- str Unique item id """ string = '' if self.filename: string += self.filename if self.scene_label: string += self.scene_label if self.event_label: string += self.event_label if self.identifier: string += self.identifier if self.source_label: string += self.source_label if self.set_label: string += self.set_label if self.tags: string += ','.join(self.tags) if self.onset: string += '{:8.4f}'.format(self.onset) if self.offset: string += '{:8.4f}'.format(self.offset) return get_parameter_hash(string) def get_list(self): """Return item values in a list with specified order. Returns ------- list """ fields = list(self.keys()) # Select only valid fields valid_fields = ['event_label', 'filename', 'offset', 'onset', 'scene_label', 'identifier', 'source_label', 'tags'] fields = list(set(fields).intersection(valid_fields)) fields.sort() if fields == ['filename']: return [self.filename] elif fields == ['event_label', 'filename', 'offset', 'onset', 'scene_label']: return [self.filename, self.scene_label, self.onset, self.offset, self.event_label] elif fields == ['offset', 'onset']: return [self.onset, self.offset] elif fields == ['event_label', 'offset', 'onset']: return [self.onset, self.offset, self.event_label] elif fields == ['filename', 'scene_label']: return [self.filename, self.scene_label] elif fields == ['filename', 'identifier', 'scene_label']: return [self.filename, self.scene_label, self.identifier] elif fields == ['event_label', 'filename']: return [self.filename, self.event_label] elif fields == ['event_label', 'filename', 'offset', 'onset']: return [self.filename, self.onset, self.offset, self.event_label] elif fields == ['event_label', 'filename', 'offset', 'onset', 'identifier', 'scene_label']: return [self.filename, self.scene_label, self.onset, self.offset, self.event_label, self.identifier] elif fields == ['event_label', 'filename', 'offset', 'onset', 'scene_label', 'source_label']: return [self.filename, self.scene_label, self.onset, self.offset, self.event_label, self.source_label] elif fields == ['event_label', 'filename', 'offset', 'onset', 'identifier', 'scene_label', 'source_label']: return [self.filename, self.scene_label, self.onset, self.offset, self.event_label, self.source_label, self.identifier] elif fields == ['filename', 'tags']: return [self.filename, ";".join(self.tags)+";"] elif fields == ['filename', 'identifier', 'tags']: return [self.filename, ";".join(self.tags)+";", self.identifier] elif fields == ['filename', 'scene_label', 'tags']: return [self.filename, self.scene_label, ";".join(self.tags)+";"] elif fields == ['filename', 'identifier', 'scene_label', 'tags']: return [self.filename, self.scene_label, ";".join(self.tags)+";", self.identifier] elif fields == ['filename', 'offset', 'onset', 'scene_label', 'tags']: return [self.filename, self.scene_label, self.onset, self.offset, ";".join(self.tags)+";"] else: message = '{name}: Invalid meta data format [{format}]'.format( name=self.__class__.__name__, format=str(fields) ) self.logger.exception(message) raise ValueError(message) @property def filename(self): """Filename Returns ------- str or None filename """ if 'filename' in self: return self['filename'] else: return None @filename.setter def filename(self, value): if not os.path.isabs(value): # Force relative file paths into unix format even under Windows value = posix_path(value) self['filename'] = value @property def filename_original(self): """Filename Returns ------- str or None filename """ if 'filename_original' in self: return self['filename_original'] else: return None @filename_original.setter def filename_original(self, value): # Keep paths in unix format even under Windows self['filename_original'] = posix_path(value) @property def scene_label(self): """Scene label Returns ------- str or None scene label """ if 'scene_label' in self: return self['scene_label'] else: return None @scene_label.setter def scene_label(self, value): self['scene_label'] = value @property def event_label(self): """Event label Returns ------- str or None event label """ if 'event_label' in self: return self['event_label'] else: return None @event_label.setter def event_label(self, value): self['event_label'] = value @property def onset(self): """Onset Returns ------- float or None onset """ if 'onset' in self: return self['onset'] else: return None @onset.setter def onset(self, value): self['onset'] = float(value) if 'event_onset' in self: # Mirror onset to event_onset self['event_onset'] = self['onset'] @property def offset(self): """Offset Returns ------- float or None offset """ if 'offset' in self: return self['offset'] else: return None @offset.setter def offset(self, value): self['offset'] = float(value) if 'event_offset' in self: # Mirror onset to event_onset self['event_offset'] = self['offset'] @property def identifier(self): """Identifier Returns ------- str or None location identifier """ if 'identifier' in self: return self['identifier'] else: return None @identifier.setter def identifier(self, value): self['identifier'] = value @property def source_label(self): """Source label Returns ------- str or None source label """ if 'source_label' in self: return self['source_label'] else: return None @source_label.setter def source_label(self, value): self['source_label'] = value @property def set_label(self): """Set label Returns ------- str or None set label """ if 'set_label' in self: return self['set_label'] else: return None @set_label.setter def set_label(self, value): self['set_label'] = value @property def tags(self): """Tags Returns ------- list or None tags """ if 'tags' in self: return self['tags'] else: return None @tags.setter def tags(self, value): if isinstance(value, str): value = value.strip() if value.lower() == 'none': value = None if value and '#' in value: value = [x.strip() for x in value.split('#')] elif value and ',' in value: value = [x.strip() for x in value.split(',')] elif value and ':' in value: value = [x.strip() for x in value.split(':')] elif value and ';' in value: value = [x.strip() for x in value.split(';')] self['tags'] = value # Remove empty tags self['tags'] = list(filter(None, self['tags'])) # Sort tags self['tags'].sort() def active_within_segment(self, start, stop): """Item active withing given segment. Parameters ---------- start : float Segment start time stop : float Segment stop time Returns ------- bool item activity """ if self.onset is not None and start <= self.onset <= stop: # item has onset within segment return True elif self.offset is not None and start <= self.offset <= stop: # item has offset within segment return True elif self.onset is not None and self.offset is not None and self.onset <= start and self.offset >= stop: # item starts and ends outside segment return True else: return False class MetaDataContainer(ListDictContainer): """Meta data container class, inherited from ListDictContainer.""" valid_formats = [FileFormat.CSV, FileFormat.TXT, FileFormat.ANN, FileFormat.CPICKLE] #: Valid file formats def __init__(self, *args, **kwargs): super(MetaDataContainer, self).__init__(*args, **kwargs) self.item_class = MetaDataItem # Convert all items in the list to MetaDataItems for item_id in range(0, len(self)): if not isinstance(self[item_id], self.item_class): self[item_id] = self.item_class(self[item_id]) from dcase_util.processors import ProcessingChain self.processing_chain = ProcessingChain() def __str__(self): return self.get_string() def __add__(self, other): return self.update(super(MetaDataContainer, self).__add__(other)) def append(self, item): """Append item to the meta data list Parameters ---------- item : MetaDataItem or dict Item to be appended. Raises ------ ValueError Item not correct type. """ if not isinstance(item, MetaDataItem) and not isinstance(item, dict): message = '{name}: Appending only MetaDataItem or dict allowed.'.format( name=self.__class__.__name__ ) self.logger.exception(message) raise ValueError(message) if isinstance(item, dict): item = MetaDataItem(item) super(MetaDataContainer, self).append(item) @property def file_count(self): """Number of files Returns ------- file_count: int > 0 """ return len(self.unique_files) @property def event_count(self): """Number of events Returns ------- event_count: int > 0 """ return len(self) @property def scene_label_count(self): """Number of unique scene labels Returns ------- scene_label_count: int >= 0 """ return len(self.unique_scene_labels) @property def event_label_count(self): """Number of unique event labels Returns ------- event_label_count: float >= 0 """ return len(self.unique_event_labels) @property def identifier_count(self): """Number of unique identifiers Returns ------- identifier_count: float >= 0 """ return len(self.unique_identifiers) @property def tag_count(self): """Number of unique tags Returns ------- tag_count: int >= 0 """ return len(self.unique_tags) @property def unique_files(self): """Unique files Returns ------- labels: list, shape=(n,) Unique labels in alphabetical order """ files = [] for item in self: if item.filename and item.filename not in files: files.append(item.filename) files.sort() return files @property def unique_event_labels(self): """Unique event labels Returns ------- labels: list, shape=(n,) Unique labels in alphabetical order """ labels = [] for item in self: if item.event_label and item.event_label not in labels: labels.append(item.event_label) labels.sort() return labels @property def unique_scene_labels(self): """Unique scene labels Returns ------- labels: list, shape=(n,) Unique labels in alphabetical order """ labels = [] for item in self: if item.scene_label and item.scene_label not in labels: labels.append(item.scene_label) labels.sort() return labels @property def unique_tags(self): """Unique tags Returns ------- tags: list, shape=(n,) Unique tags in alphabetical order """ tags = [] for item in self: if item.tags: for tag in item.tags: if tag not in tags: tags.append(tag) tags.sort() return tags @property def unique_identifiers(self): """Unique identifiers Returns ------- labels: list, shape=(n,) Unique identifier labels in alphabetical order """ labels = [] for item in self: if item.identifier and item.identifier not in labels: labels.append(item.identifier) labels.sort() return labels @property def unique_source_labels(self): """Unique source labels Returns ------- labels: list, shape=(n,) Unique labels in alphabetical order """ labels = [] for item in self: if item.source_label and item.source_label not in labels: labels.append(item.source_label) labels.sort() return labels @property def max_offset(self): """Find the offset (end-time) of last event Returns ------- max_offset: float > 0 maximum offset """ max_offset = 0 for item in self: if 'offset' in item and item.offset > max_offset: max_offset = item.offset return max_offset def update(self, data): """Replace content with given list Parameters ---------- data : list New content Returns ------- self """ super(MetaDataContainer, self).update(data=data) # Convert all items in the list to MetaDataItems for item_id in range(0, len(self)): if not isinstance(self[item_id], self.item_class): self[item_id] = self.item_class(self[item_id]) return self def log(self, level='info', show_data=False, show_stats=True): """Log container content Parameters ---------- level : str Logging level, possible values [info, debug, warn, warning, error, critical] show_data : bool Include data show_stats : bool Include scene and event statistics Returns ------- None """ self.ui.line(self.get_string(show_data=show_data, show_stats=show_stats), level=level) def log_all(self, level='info'): """Log container content with all meta data items. """ self.log(level=level, show_data=True, show_stats=True) def show(self, show_data=False, show_stats=True): """Print container content Parameters ---------- show_data : bool Include data Default value True show_stats : bool Include scene and event statistics Default value True Returns ------- Nothing """ print(self.get_string(show_data=show_data, show_stats=show_stats)) def show_all(self): """Print container content with all meta data items. """ self.show(show_data=True, show_stats=True) def load(self, filename=None, fields=None, csv_header=True, file_format=None, delimiter=None, decimal='point'): """Load event list from delimited text file (csv-formatted) Preferred delimiter is tab, however, other delimiters are supported automatically (they are sniffed automatically). Supported input formats: - [file(string)] - [file(string)][scene_label(string)] - [file(string)][scene_label(string)][identifier(string)] - [event_onset (float)][tab][event_offset (float)] - [event_onset (float)][tab][event_offset (float)][tab][event_label (string)] - [file(string)][tab][onset (float)][tab][offset (float)][tab][event_label (string)] - [file(string)[tab][scene_label(string)][tab][onset (float)][tab][offset (float)] - [file(string)[tab][scene_label(string)][tab][onset (float)][tab][offset (float)][tab][event_label (string)] - [file(string)[tab][scene_label(string)][tab][onset (float)][tab][offset (float)][tab][event_label (string)][tab][source(single character)] - [file(string)[tab][scene_label(string)][tab][onset (float)][tab][offset (float)][tab][event_label (string)][tab][source(string)] - [file(string)[tab][tags (list of strings, delimited with ;)] - [file(string)[tab][scene_label(string)][tab][tags (list of strings, delimited with ;)] - [file(string)[tab][scene_label(string)][tab][tags (list of strings, delimited with ;)][tab][event_onset (float)][tab][event_offset (float)] Parameters ---------- filename : str Path to the meta data in text format (csv). If none given, one given for class constructor is used. Default value None fields : list of str, optional List of column names. Used only for CSV formatted files. Default value None csv_header : bool, optional Read field names from first line (header). Used only for CSV formatted files. Default value True file_format : FileFormat, optional Forced file format, use this when there is a miss-match between file extension and file format. Default value None delimiter : str, optional Forced data delimiter for csv format. If None given, automatic delimiter sniffer used. Use this when sniffer does not work. Default value None decimal : str Decimal 'point' or 'comma' Default value 'point' Returns ------- data : list of event dicts List containing event dicts """ def validate(row_format, valid_formats): for valid_format in valid_formats: if row_format == valid_format: return True return False if filename: self.filename = filename if not file_format: self.detect_file_format() self.validate_format() if file_format and FileFormat.validate_label(label=file_format): self.format = file_format if self.exists(): if self.format in [FileFormat.TXT, FileFormat.ANN]: if delimiter is None: if decimal == 'comma': delimiter = self.delimiter(exclude_delimiters=[',']) else: delimiter = self.delimiter() data = [] field_validator = FieldValidator() f = io.open(self.filename, 'rt') try: for row in csv.reader(f, delimiter=delimiter): if row: row_format = [] for item in row: row_format.append(field_validator.process(item)) for item_id, item in enumerate(row): if row_format[item_id] == FieldValidator.NUMBER: # Translate decimal comma into decimal point row[item_id] = float(row[item_id].replace(',', '.')) elif row_format[item_id] in [FieldValidator.AUDIOFILE, FieldValidator.DATAFILE, FieldValidator.STRING, FieldValidator.ALPHA1, FieldValidator.ALPHA2, FieldValidator.LIST]: row[item_id] = row[item_id].strip() if validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE], [FieldValidator.DATAFILE], [FieldValidator.AUDIOFILE, FieldValidator.EMPTY], [FieldValidator.DATAFILE, FieldValidator.EMPTY] ]): # Format: [file] data.append( self.item_class({ 'filename': row[0] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.NUMBER, FieldValidator.NUMBER] ]): # Format: [onset offset] data.append( self.item_class({ 'onset': row[0], 'offset': row[1] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.STRING], [FieldValidator.DATAFILE, FieldValidator.STRING], ]): # Format: [file scene_label] data.append( self.item_class({ 'filename': row[0], 'scene_label': row[1] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.STRING, FieldValidator.AUDIOFILE], [FieldValidator.DATAFILE, FieldValidator.STRING, FieldValidator.DATAFILE], ]): # Format: [file scene_label file], filename mapping included data.append( self.item_class({ 'filename': row[0], 'scene_label': row[1], 'filename_original': row[2] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.STRING, FieldValidator.STRING], [FieldValidator.DATAFILE, FieldValidator.STRING, FieldValidator.STRING], ]): # Format: [file scene_label identifier] data.append( self.item_class({ 'filename': row[0], 'scene_label': row[1], 'identifier': row[2] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING], [FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.ALPHA2], ]): # Format: [onset offset event_label] data.append( self.item_class({ 'onset': row[0], 'offset': row[1], 'event_label': row[2] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING], [FieldValidator.AUDIOFILE, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING], [FieldValidator.DATAFILE, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING] ]): # Format: [file onset offset event_label] data.append( self.item_class({ 'filename': row[0], 'onset': row[1], 'offset': row[2], 'event_label': row[3] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER], [FieldValidator.DATAFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER] ]): # Format: [file scene_label onset offset] data.append( self.item_class({ 'filename': row[0], 'onset': row[2], 'offset': row[3], 'scene_label': row[1] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING, FieldValidator.STRING], [FieldValidator.DATAFILE, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING, FieldValidator.STRING] ]): # Format: [file onset offset event_label identifier] data.append( self.item_class({ 'filename': row[0], 'onset': row[1], 'offset': row[2], 'event_label': row[3], 'identifier': row[4] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER], [FieldValidator.DATAFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER] ]): # Format: [file scene_label onset offset] data.append( self.item_class({ 'filename': row[0], 'scene_label': row[1], 'onset': row[2], 'offset': row[3] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING], [FieldValidator.DATAFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING] ]): # Format: [file scene_label onset offset event_label] data.append( self.item_class({ 'filename': row[0], 'scene_label': row[1], 'onset': row[2], 'offset': row[3], 'event_label': row[4] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING, FieldValidator.ALPHA1], [FieldValidator.DATAFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING, FieldValidator.ALPHA1] ]): # Format: [file scene_label onset offset event_label source_label] data.append( self.item_class({ 'filename': row[0], 'scene_label': row[1], 'onset': row[2], 'offset': row[3], 'event_label': row[4], 'source_label': row[5] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING, FieldValidator.STRING], [FieldValidator.DATAFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING, FieldValidator.STRING] ]): # Format: [file scene_label onset offset event_label source_label] data.append( self.item_class({ 'filename': row[0], 'scene_label': row[1], 'onset': row[2], 'offset': row[3], 'event_label': row[4], 'source_label': row[5] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING, FieldValidator.ALPHA1, FieldValidator.STRING], [FieldValidator.DATAFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING, FieldValidator.ALPHA1, FieldValidator.STRING] ]): # Format: [file scene_label onset offset event_label source_label identifier] data.append( self.item_class({ 'filename': row[0], 'scene_label': row[1], 'onset': row[2], 'offset': row[3], 'event_label': row[4], 'source_label': row[5], 'identifier': row[6] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING, FieldValidator.STRING, FieldValidator.STRING], [FieldValidator.DATAFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.STRING, FieldValidator.STRING, FieldValidator.STRING] ]): # Format: [file scene_label onset offset event_label source_label identifier] data.append( self.item_class({ 'filename': row[0], 'scene_label': row[1], 'onset': row[2], 'offset': row[3], 'event_label': row[4], 'source_label': row[5], 'identifier': row[6] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.STRING, FieldValidator.LIST], [FieldValidator.DATAFILE, FieldValidator.STRING, FieldValidator.LIST] ]): # Format: [file scene_label tags] data.append( self.item_class({ 'filename': row[0], 'scene_label': row[1], 'tags': row[2] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.STRING, FieldValidator.LIST, FieldValidator.STRING], [FieldValidator.DATAFILE, FieldValidator.STRING, FieldValidator.LIST, FieldValidator.STRING] ]): # Format: [file scene_label tags identifier] data.append( self.item_class({ 'filename': row[0], 'scene_label': row[1], 'tags': row[2], 'identifier': row[3] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.LIST], [FieldValidator.DATAFILE, FieldValidator.LIST] ]): # Format: [file tags] data.append( self.item_class({ 'filename': row[0], 'tags': row[1] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.LIST, FieldValidator.STRING], [FieldValidator.DATAFILE, FieldValidator.LIST, FieldValidator.STRING] ]): # Format: [file tags identifier] data.append( self.item_class({ 'filename': row[0], 'tags': row[1], 'identifier': row[2] }) ) elif validate(row_format=row_format, valid_formats=[ [FieldValidator.AUDIOFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.LIST], [FieldValidator.DATAFILE, FieldValidator.STRING, FieldValidator.NUMBER, FieldValidator.NUMBER, FieldValidator.LIST] ]): # Format: [file scene_label onset offset tags] data.append( self.item_class({ 'filename': row[0], 'scene_label': row[1], 'onset': row[2], 'offset': row[3], 'tags': row[4] }) ) else: message = '{name}: Unknown row format [{format}], row [{row}]'.format( name=self.__class__.__name__, format=row_format, row=row ) self.logger.exception(message) raise IOError(message) finally: f.close() self.update(data=data) elif self.format == FileFormat.CSV: if fields is None and csv_header is None: message = '{name}: Parameters fields or csv_header has to be set for CSV files.'.format( name=self.__class__.__name__ ) self.logger.exception(message) raise ValueError(message) if not delimiter: if decimal == 'comma': delimiter = self.delimiter(exclude_delimiters=[',']) else: delimiter = self.delimiter() data = [] with open(self.filename, 'r') as f: csv_reader = csv.reader(f, delimiter=delimiter) if csv_header: csv_fields = next(csv_reader) if fields is None: fields = csv_fields for row in csv_reader: if row: for cell_id, cell_data in enumerate(row): if decimal == 'comma': # Translate decimal comma into decimal point cell_data = float(cell_data.replace(',', '.')) if is_int(cell_data): row[cell_id] = int(cell_data) elif is_float(cell_data): row[cell_id] = float(cell_data) data.append(dict(zip(fields, row))) self.update(data=data) elif self.format == FileFormat.CPICKLE: from dcase_util.files import Serializer self.update( data=Serializer.load_cpickle(filename=self.filename) ) else: message = '{name}: Unknown format [{format}]'.format(name=self.__class__.__name__, format=self.filename) self.logger.exception(message) raise IOError(message) else: message = '{name}: File not found [{filename}]'.format( name=self.__class__.__name__, filename=self.filename ) self.logger.exception(message) raise IOError(message) return self def save(self, filename=None, fields=None, csv_header=True, file_format=None, delimiter='\t', **kwargs): """Save content to csv file Parameters ---------- filename : str Filename. If none given, one given for class constructor is used. Default value None fields : list of str Fields in correct order, if none given all field in alphabetical order will be outputted. Used only for CSV formatted files. Default value None csv_header : bool In case of CSV formatted file, first line will contain field names. Names are taken from fields parameter. Default value True file_format : FileFormat, optional Forced file format, use this when there is a miss-match between file extension and file format. Default value None delimiter : str Delimiter to be used when saving data. Default value '\t' Returns ------- self """ if filename: self.filename = filename if not file_format: self.detect_file_format() self.validate_format() if file_format and FileFormat.validate_label(label=file_format): self.format = file_format if self.format in [FileFormat.TXT, FileFormat.ANN]: # Make sure writing is using correct line endings to avoid extra empty lines if sys.version_info[0] == 2: f = open(self.filename, 'wbt') elif sys.version_info[0] == 3: f = open(self.filename, 'wt', newline='') try: writer = csv.writer(f, delimiter=delimiter) for item in self: writer.writerow(item.get_list()) finally: f.close() elif self.format == FileFormat.CSV: if fields is None: fields = set() for item in self: fields.update(list(item.keys())) fields = sorted(list(fields)) # Make sure writing is using correct line endings to avoid extra empty lines if sys.version_info[0] == 2: csv_file = open(self.filename, 'wb') elif sys.version_info[0] == 3: csv_file = open(self.filename, 'w', newline='') try: csv_writer = csv.writer(csv_file, delimiter=delimiter) if csv_header: csv_writer.writerow(fields) for item in self: item_values = [] for field in fields: value = item[field] if isinstance(value, list): value = ";".join(value)+";" item_values.append(value) csv_writer.writerow(item_values) finally: csv_file.close() elif self.format == FileFormat.CPICKLE: from dcase_util.files import Serializer Serializer.save_cpickle(filename=self.filename, data=self) else: message = '{name}: Unknown format [{format}]'.format(name=self.__class__.__name__, format=self.filename) self.logger.exception(message) raise IOError(message) return self def get_string(self, show_data=True, show_stats=True): """Get content in string format Parameters ---------- show_data : bool Include data Default value True show_stats : bool Include scene and event statistics Default value True Returns ------- str Multi-line string """ ui = FancyStringifier() string_data = '' string_data += ui.class_name(self.__class__.__name__) + '\n' if hasattr(self, 'filename') and self.filename: string_data += ui.data( field='Filename', value=self.filename ) + '\n' string_data += ui.data(field='Items', value=len(self)) + '\n' string_data += ui.line(field='Unique') + '\n' string_data += ui.data(indent=4, field='Files', value=len(self.unique_files)) + '\n' string_data += ui.data(indent=4, field='Scene labels', value=len(self.unique_scene_labels)) + '\n' string_data += ui.data(indent=4, field='Event labels', value=len(self.unique_event_labels)) + '\n' string_data += ui.data(indent=4, field='Tags', value=len(self.unique_tags)) + '\n' string_data += ui.data(indent=4, field='Identifiers', value=len(self.unique_identifiers)) + '\n' string_data += ui.data(indent=4, field='Source labels', value=len(self.unique_source_labels)) + '\n' string_data += '\n' if show_data: string_data += ui.line('Meta data', indent=2) + '\n' cell_data = [[], [], [], [], [], [], []] for row_id, item in enumerate(self): cell_data[0].append(item.filename) cell_data[1].append(item.onset) cell_data[2].append(item.offset) cell_data[3].append(item.scene_label) cell_data[4].append(item.event_label) cell_data[5].append(','.join(item.tags) if item.tags else '-') cell_data[6].append(item.identifier if item.tags else '-') string_data += ui.table( cell_data=cell_data, column_headers=['Source', 'Onset', 'Offset', 'Scene', 'Event', 'Tags', 'Identifier'], column_types=['str20', 'float2', 'float2', 'str15', 'str15', 'str15', 'str5'], indent=8 ) string_data += '\n' if show_stats: stats = self.stats() if 'scenes' in stats and 'scene_label_list' in stats['scenes'] and stats['scenes']['scene_label_list']: string_data += ui.line('Scene statistics', indent=2) + '\n' cell_data = [[], [], []] for scene_id, scene_label in enumerate(stats['scenes']['scene_label_list']): cell_data[0].append(scene_label) cell_data[1].append(int(stats['scenes']['count'][scene_id])) cell_data[2].append(int(stats['scenes']['identifiers'][scene_id])) string_data += ui.table( cell_data=cell_data, column_headers=['Scene label', 'Count', 'Identifiers'], column_types=['str20', 'int', 'int'], indent=8 ) string_data += '\n' if 'events' in stats and 'event_label_list' in stats['events'] and stats['events']['event_label_list']: string_data += ui.line('Event statistics', indent=2) + '\n' cell_data = [[], [], [], []] for event_id, event_label in enumerate(stats['events']['event_label_list']): cell_data[0].append(event_label) cell_data[1].append(int(stats['events']['count'][event_id])) cell_data[2].append(stats['events']['length'][event_id]) cell_data[3].append(stats['events']['avg_length'][event_id]) string_data += ui.table( cell_data=cell_data, column_headers=['Event label', 'Count', 'Tot. Length', 'Avg. Length'], column_types=['str20', 'int', 'float2', 'float2'], indent=8 ) + '\n' if 'tags' in stats and 'tag_list' in stats['tags'] and stats['tags']['tag_list']: string_data += ui.line('Tag statistics', indent=2) + '\n' cell_data = [[], []] for tag_id, tag in enumerate(stats['tags']['tag_list']): cell_data[0].append(tag) cell_data[1].append(int(stats['tags']['count'][tag_id])) string_data += ui.table( cell_data=cell_data, column_headers=['Tag', 'Count'], column_types=['str20', 'int'], indent=8 ) + '\n' return string_data def filter(self, filename=None, file_list=None, scene_label=None, scene_list=None, event_label=None, event_list=None, tag=None, tag_list=None, identifier=None, identifier_list=None, source_label=None, source_label_list=None, **kwargs ): """Filter content Parameters ---------- filename : str, optional Filename to be matched Default value None file_list : list, optional List of filenames to be matched Default value None scene_label : str, optional Scene label to be matched Default value None scene_list : list of str, optional List of scene labels to be matched Default value None event_label : str, optional Event label to be matched Default value None event_list : list of str, optional List of event labels to be matched Default value None tag : str, optional Tag to be matched Default value None tag_list : list of str, optional List of tags to be matched Default value None identifier : str, optional Identifier to be matched Default value None identifier_list : list of str, optional List of identifiers to be matched Default value None source_label : str, optional Source label to be matched Default value None source_label_list : list of str, optional List of source labels to be matched Default value None Returns ------- MetaDataContainer """ # Inject parameters back to kwargs, and use parent filter method if filename is not None: kwargs['filename'] = filename if scene_label is not None: kwargs['scene_label'] = scene_label if event_label is not None: kwargs['event_label'] = event_label if identifier is not None: kwargs['identifier'] = identifier if source_label is not None: kwargs['source_label'] = source_label if file_list is not None: kwargs['filename'] = list(file_list) if scene_list is not None: kwargs['scene_label'] = list(scene_list) if event_list is not None: kwargs['event_label'] = list(event_list) if identifier_list is not None: kwargs['identifier'] = list(identifier_list) if source_label_list is not None: kwargs['source_label'] = list(source_label_list) result = MetaDataContainer(super(MetaDataContainer, self).filter(**kwargs)) # Handle tags separately if tag is not None or tag_list is not None: data = [] if tag_list: tag_list = set(tag_list) for item in result: matched = [] if tag: if item.tags and tag in item.tags: matched.append(True) else: matched.append(False) if tag_list: if item.tags and tag_list.intersection(item.tags): matched.append(True) else: matched.append(False) if all(matched): data.append(copy.deepcopy(item)) return MetaDataContainer(data) else: return result def process_events(self, minimum_event_length=None, minimum_event_gap=None): """Process event content Makes sure that minimum event length and minimum event gap conditions are met per event label class. Parameters ---------- minimum_event_length : float > 0.0 Minimum event length in seconds, shorten than given are filtered out from the output. Default value None minimum_event_gap : float > 0.0 Minimum allowed gap between events in seconds from same event label class. Default value None Returns ------- MetaDataContainer """ processed_events = [] files = self.unique_files if not files: files = [None] for filename in files: for event_label in self.unique_event_labels: current_events_items = self.filter(filename=filename, event_label=event_label) # Sort events current_events_items = sorted(current_events_items, key=lambda k: k.onset) # 1. remove short events event_results_1 = [] for event in current_events_items: if minimum_event_length is not None: if event.offset - event.onset >= minimum_event_length: event_results_1.append(event) else: event_results_1.append(event) if len(event_results_1) and minimum_event_gap is not None: # 2. remove small gaps between events event_results_2 = [] # Load first event into event buffer buffered_event_onset = event_results_1[0].onset buffered_event_offset = event_results_1[0].offset for i in range(1, len(event_results_1)): if event_results_1[i].onset - buffered_event_offset > minimum_event_gap: # The gap between current event and the buffered is bigger than minimum event gap, # store event, and replace buffered event current_event = copy.deepcopy(event_results_1[i]) current_event.onset = buffered_event_onset current_event.offset = buffered_event_offset event_results_2.append(current_event) buffered_event_onset = event_results_1[i].onset buffered_event_offset = event_results_1[i].offset else: # The gap between current event and the buffered is smaller than minimum event gap, # extend the buffered event until the current offset buffered_event_offset = event_results_1[i].offset # Store last event from buffer current_event = copy.copy(event_results_1[len(event_results_1) - 1]) current_event.onset = buffered_event_onset current_event.offset = buffered_event_offset event_results_2.append(current_event) processed_events += event_results_2 else: processed_events += event_results_1 return MetaDataContainer(processed_events) def map_events(self, target_event_label, source_event_labels=None): """Map events with varying event labels into single target event label Parameters ---------- target_event_label : str Target event label source_event_labels : list of str Event labels to be processed. If none given, all events are merged Default value None Returns ------- MetaDataContainer """ processed_events = MetaDataContainer() files = self.unique_files if not files: files = [None] if source_event_labels is None: source_event_labels = self.unique_event_labels for filename in files: for event_label in source_event_labels: current_events_items = self.filter(filename=filename, event_label=event_label) # Sort events current_events_items = sorted(current_events_items, key=lambda k: k.onset) for item in current_events_items: item.event_label = target_event_label processed_events += current_events_items return processed_events def event_inactivity(self, event_label='inactivity', source_event_labels=None, duration_list=None): """Get inactivity segments between events as event list Parameters ---------- event_label : str Event label used for inactivity source_event_labels : list of str Event labels to be taken into account. If none given, all events are considered. Default value None Returns ------- MetaDataContainer """ meta_flatten = self.map_events(target_event_label='activity', source_event_labels=source_event_labels) meta_flatten = meta_flatten.process_events( minimum_event_gap=numpy.spacing(1), minimum_event_length=numpy.spacing(1) ) inactivity_events = MetaDataContainer() files = meta_flatten.unique_files if not files: files = [None] if duration_list is None: duration_list = {} for filename in files: current_events_items = meta_flatten.filter(filename=filename) current_inactivity_events = MetaDataContainer() onset = 0.0 for item in current_events_items: current_onset = onset current_offset = item.onset current_inactivity_events.append( { 'filename': filename, 'onset': current_onset, 'offset': current_offset, 'event_label': event_label } ) onset = item.offset if filename in duration_list: file_duration = duration_list[filename] else: file_duration = current_events_items.max_offset current_inactivity_events.append( { 'filename': filename, 'onset': onset, 'offset': file_duration, 'event_label': event_label } ) current_inactivity_events = current_inactivity_events.process_events( minimum_event_gap=numpy.spacing(1), minimum_event_length=numpy.spacing(1) ) current_inactivity_events = sorted(current_inactivity_events, key=lambda k: k.onset) inactivity_events += current_inactivity_events return inactivity_events def add_time(self, time): """Add time offset to event onset and offset timestamps Parameters ---------- time : float Offset to be added to the onset and offsets Returns ------- self """ for item in self: if item.onset: item.onset += time if item.offset: item.offset += time return self def filter_time_segment(self, start=None, stop=None, duration=None, filename=None, zero_time=True, trim=True): """Filter time segment Parameters ---------- start : float > 0.0 Segment start, seconds Default value None stop : float > 0.0 Segment end, seconds Default value None duration : float Segment duration, seconds Default value None filename : str Filename to filter Default value None zero_time : bool Convert timestamps in respect to the segment start Default value True trim : bool Trim event onsets and offset according to segment start and stop times. Default value True Returns ------- MetaDataContainer """ if len(self.unique_files) > 1 and filename is None: message = '{name}: Meta data contains items for multiple files. Please specify filename parameter.'.format( name=self.__class__.__name__ ) self.logger.exception(message) raise ValueError(message) elif filename is not None and filename not in self.unique_files: message = '{name}: Filename is not used in meta data items.'.format( name=self.__class__.__name__ ) self.logger.exception(message) raise ValueError(message) if filename is not None and filename in self.unique_files: data = self.filter(filename=filename) else: data = copy.deepcopy(self) if stop is None and duration is not None: stop = start + duration filtered_data = MetaDataContainer() for item in data: if item.active_within_segment(start=start, stop=stop): item_ = copy.deepcopy(item) if zero_time: # Slice start time is new zero time item_.onset -= start item_.offset -= start if trim: # Trim negative onsets to 0 and trim offsets going over slice stop to slice stop. if item_.onset < 0: item_.onset = 0 if item_.offset > stop-start: item_.offset = stop - start elif trim: if item_.onset < start: item_.onset = start if item_.offset > stop: item_.offset = stop if item_.onset != item_.offset: filtered_data.append(item_) return filtered_data def stats(self, event_label_list=None, scene_label_list=None, tag_list=None): """Statistics of the container content Parameters ---------- event_label_list : list of str List of event labels to be included in the statistics. If none given, all unique labels used Default value None scene_label_list : list of str List of scene labels to be included in the statistics. If none given, all unique labels used Default value None tag_list : list of str List of tags to be included in the statistics. If none given, all unique tags used Default value None Returns ------- dict """ if event_label_list is None: event_label_list = self.unique_event_labels if scene_label_list is None: scene_label_list = self.unique_scene_labels if tag_list is None: tag_list = self.unique_tags scene_counts = numpy.zeros(len(scene_label_list)) scene_unique_identifiers = numpy.zeros(len(scene_label_list)) for scene_id, scene_label in enumerate(scene_label_list): scene_data = self.filter(scene_label=scene_label) scene_counts[scene_id] = len(scene_data) scene_unique_identifiers[scene_id] = len(scene_data.unique_identifiers) event_lengths = numpy.zeros(len(event_label_list)) event_counts = numpy.zeros(len(event_label_list)) for event_id, event_label in enumerate(event_label_list): for item in self: if item.onset is not None and item.offset is not None and item.event_label == event_label: event_lengths[event_id] += item.offset - item.onset if item.event_label == event_label: event_counts[event_id] += 1 tag_counts = numpy.zeros(len(tag_list)) for tag_id, tag in enumerate(tag_list): for item in self: if item.tags and tag in item.tags: tag_counts[tag_id] += 1 return { 'scenes': { 'scene_label_list': scene_label_list, 'count': scene_counts, 'identifiers': scene_unique_identifiers }, 'events': { 'event_label_list': event_label_list, 'length': event_lengths, 'count': event_counts, 'avg_length': event_lengths/(event_counts + numpy.spacing(1)) }, 'tags': { 'tag_list': tag_list, 'count': tag_counts } } def scene_stat_counts(self): """Scene count statistics Returns ------- dict """ stats = {} for scene_label in self.unique_scene_labels: stats[scene_label] = len(self.filter(scene_label=scene_label)) return stats def event_stat_counts(self): """Event count statistics Returns ------- dict """ stats = {} for event_label in self.unique_event_labels: stats[event_label] = len(self.filter(event_label=event_label)) return stats def tag_stat_counts(self): """Tag count statistics Returns ------- dict """ stats = {} for tag in self.unique_tags: stats[tag] = len(self.filter(tag=tag)) return stats def to_event_roll(self, label_list=None, time_resolution=0.01, label='event_label', length_seconds=None): """Event roll Event roll is binary matrix indicating event activity withing time segment defined by time_resolution. Parameters ---------- label_list : list List of labels in correct order Default value None time_resolution : float > 0.0 Time resolution used when converting event into event roll. Default value 0.01 label : str Meta data field used to create event roll Default value 'event_label' length_seconds : float Event roll length in seconds Default value None Returns ------- numpy.ndarray [shape=(math.ceil(data_length * 1 / time_resolution), amount of classes)] """ if label_list is None: label_list = self.unique_event_labels if len(self.unique_files) <= 1: from dcase_util.data import EventRollEncoder event_roll = EventRollEncoder( label_list=label_list, time_resolution=time_resolution, ).encode( metadata_container=self, label=label, length_seconds=length_seconds ) return event_roll else: message = '{name}: Meta data contains items for multiple files.'.format(name=self.__class__.__name__) self.logger.exception(message) raise ValueError(message) def intersection(self, second_metadata): """Intersection of two meta containers Parameters ---------- second_metadata : MetaDataContainer Second meta data container Returns ------- MetaDataContainer Container with intersecting items """ # Get unique IDs for current meta data container id1 = [] for item1 in self: id1.append(item1.id) # Get unique IDs for second meta data container id2 = [] for item2 in second_metadata: id2.append(item2.id) # Find intersection of IDs id_intersect = list(set(id1).intersection(set(id2))) # Collect intersecting items intersection = MetaDataContainer() for id in id_intersect: intersection.append(self[id1.index(id)]) return intersection def intersection_report(self, second_metadata): """Intersection report for two meta containers Parameters ---------- second_metadata : MetaDataContainer Second meta data container Returns ------- dict Dict with intersection data ['items', 'files', 'identifiers', 'scene_labels', 'event_labels' ,'tags'] """ return { 'items': self.intersection(second_metadata=second_metadata), 'files': list(set(self.unique_files).intersection(set(second_metadata.unique_files))), 'identifiers': list(set(self.unique_identifiers).intersection(set(second_metadata.unique_identifiers))), 'scene_labels': list(set(self.unique_scene_labels).intersection(set(second_metadata.unique_scene_labels))), 'event_labels': list(set(self.unique_event_labels).intersection(set(second_metadata.unique_event_labels))), 'tags': list(set(self.unique_tags).intersection(set(second_metadata.unique_tags))) } def difference(self, second_metadata): """Difference of two meta containers Parameters ---------- second_metadata : MetaDataContainer Second meta data container Returns ------- MetaDataContainer Container with difference items """ # Get unique IDs for current meta data container id1 = [] for item1 in self: id1.append(item1.id) # Get unique IDs for second meta data container id2 = [] for item2 in second_metadata: id2.append(item2.id) # Find difference of IDs id_difference = list(set(id1).symmetric_difference(set(id2))) # Collect difference items difference = MetaDataContainer() for id in id_difference: difference.append(self[id1.index(id)]) return difference def push_processing_chain_item(self, processor_name, init_parameters=None, process_parameters=None, preprocessing_callbacks=None, input_type=None, output_type=None): """Push processing chain item Parameters ---------- processor_name : str Processor name init_parameters : dict, optional Initialization parameters for the processors Default value None process_parameters : dict, optional Parameters for the process method of the Processor Default value None input_type : ProcessingChainItemType Input data type Default value None output_type : ProcessingChainItemType Output data type Default value None Returns ------- self """ self.processing_chain.push_processor( processor_name=processor_name, init_parameters=init_parameters, process_parameters=process_parameters, preprocessing_callbacks=preprocessing_callbacks, input_type=input_type, output_type=output_type, ) return self
[ "toni.heittola@gmail.com" ]
toni.heittola@gmail.com
f4936ca835895113cefad9aea979f1f903045068
f68732bc40a7a90c3a1082e4b3a4154518acafbb
/script/dbus/systemBus/appsLaunchedRecorder/002_markLaunched.py
838803454ac39531735ca298607c545687acf651
[]
no_license
lizhouquan1017/dbus_demo
94238a2307e44dabde9f4a4dd0cf8ec217260867
af8442845e722b258a095e9a1afec9dddfb175bf
refs/heads/master
2023-02-11T19:46:27.884936
2021-01-08T05:27:18
2021-01-08T05:27:18
327,162,635
0
0
null
null
null
null
UTF-8
Python
false
false
2,329
py
# -*- coding: utf-8 -*- # *************************************************** # @Test Case ID: 002_markLaunched # @Test Description: MarkLaunched(string desktopFile) # 标记某个应用是否启动过 # 参数 # desktopFile: 标记该应用启动过,标记以后该应用的id就不会出现在GetNew函数返回的结构中 # 返回 # 无 # @Test Condition: 1.无 # @Test Step: 1.调用 GetNew 函数,获取已经安装但从未打开使用过的应用列表 # 2.存在从未打开过应用,调用MarkLaunched标记第一个应用,不存在则标记任意一个已存在应用,如:dde-file-manager # @Test Result: 2.调用 GetNew 函数,获取已经安装但从未打开使用过的应用列表,被标记应用不在列表中或调用成功无报错 # @Test Remark: 只有通过launcher卸载的应用再次安装才会在从未打开使用过的应用列表中,暂无方案通过代码模拟这一过程,200901 # @Author: ut001627 # *************************************************** import time import pytest from frame.base import OSBase from aw.dbus.systemBus import appsLaunchedRecorder class TestCase(OSBase): def setUp(self): self.Step("预制条件1:无") @pytest.mark.public def test_step(self): self.Step("步骤1:调用 GetNew 函数,获取已经安装但从未打开使用过的应用列表") apps_list = appsLaunchedRecorder.get_all_new_apps() self.Step("步骤2:存在从未打开过应用,调用MarkLaunched标记第一个应用,不存在则标记任意一个已存在应用,如:dde-file-manager") if apps_list: appsLaunchedRecorder.markLaunched(apps_list[0]) time.sleep(5) self.CheckPoint("调用 GetNew 函数,获取已经安装但从未打开使用过的应用列表,被标记应用不在列表中") assert appsLaunchedRecorder.is_new_apps(apps_list[0], target=False) else: self.CheckPoint("调用成功无报错") appsLaunchedRecorder.markLaunched('/usr/share/applications/dde-file-manager.desktop') def tearDown(self): self.Step("收尾:无")
[ "lizhouquan@uniontech.com" ]
lizhouquan@uniontech.com
9c51cf3d66f1cbc81907c80eb29c81a8f1ffddfe
3af8bd42cbf1f3a6f275cc7f5299a643511b56ff
/sentiment_analysis/bert/scripts/main.py
41e2bc53361220044c117ee01f7a1306b2b0d166
[]
no_license
shravanc/msc_project
d54fbf6fda764038ca52d113ec5b582212f9a5bd
9d815e2130a9c4c2ad9286a8f3471c2bf860ca93
refs/heads/master
2022-12-13T21:59:51.269615
2020-09-08T10:50:55
2020-09-08T10:50:55
276,747,991
0
0
null
null
null
null
UTF-8
Python
false
false
5,291
py
import os import math import datetime from tqdm import tqdm import pandas as pd import numpy as np import tensorflow as tf from tensorflow import keras import bert from bert import BertModelLayer from bert.loader import StockBertConfig, map_stock_config_to_params, load_stock_weights from bert.tokenization.bert_tokenization import FullTokenizer import seaborn as sns os.environ['CUDA_VISIBLE_DEVICES'] = '-1' train_base_dir = "/home/shravan/Downloads/train/" valid_base_dir = "/home/shravan/Downloads/valid/" train_count = 11 def load_datasets(): train_df = pd.DataFrame() for name in os.listdir(train_base_dir): file_path = os.path.join(train_base_dir, name) train_df = pd.concat([train_df, pd.read_csv(file_path, sep=',', names=["sentences", "polarity"])], ignore_index=True ) valid_df = pd.DataFrame() for name in os.listdir(valid_base_dir): file_path = os.path.join(valid_base_dir, name) valid_df = pd.concat([valid_df, pd.read_csv(file_path, sep=',', names=["sentences", "polarity"])], ignore_index=True ) return train_df, valid_df train, test = load_datasets() bert_abs_path = '/home/shravan/Downloads/' bert_model_name = 'multi_cased_L-12_H-768_A-12' bert_ckpt_dir = os.path.join(bert_abs_path, bert_model_name) bert_ckpt_file = os.path.join(bert_ckpt_dir, "bert_model.ckpt") bert_config_file = os.path.join(bert_ckpt_dir, "bert_config.json") # Preprocessing class IntentDetectionData: DATA_COLUMN = 'sentences' LABEL_COLUMN = 'polarity' def __init__(self, train, test, tokenizer: FullTokenizer, classes, max_seq_len): self.tokenizer = tokenizer self.max_seq_len = 0 self.classes = classes # print(train[IntentDetectionData.DATA_COLUMN].str.len().sort_values().index()) train, test = map(lambda df: df.reindex(df[IntentDetectionData.DATA_COLUMN].str.len().sort_values().index), [train, test]) ((self.train_x, self.train_y), (self.test_x, self.test_y)) = map(self._prepare, [train, test]) print("max seq_len", self.max_seq_len) self.max_seq_len = min(self.max_seq_len, max_seq_len) self.train_x, self.test_x = map(self._pad, [self.train_x, self.test_x]) def _prepare(self, df): x, y = [], [] for _, row in tqdm(df.iterrows()): text, label = row[IntentDetectionData.DATA_COLUMN], row[IntentDetectionData.LABEL_COLUMN] tokens = self.tokenizer.tokenize(text) tokens = ['[CLS]'] + tokens + ['[SEP]'] token_ids = self.tokenizer.convert_tokens_to_ids(tokens) self.max_seq_len = max(self.max_seq_len, len(token_ids)) x.append(token_ids) y.append(self.classes.index(label)) return np.array(x), np.array(y) def _pad(self, ids): x = [] for input_ids in ids: input_ids = input_ids[:min(len(input_ids), self.max_seq_len - 2)] input_ids = input_ids + [0] * (self.max_seq_len - len(input_ids)) x.append(np.array(input_ids)) return np.array(x) tokenizer = FullTokenizer(vocab_file=os.path.join(bert_ckpt_dir, 'vocab.txt')) t = tokenizer.tokenize('ಶುಭ ದಿನ') print(t) ds = tokenizer.convert_tokens_to_ids(t) print(ds) def create_model(max_seq_len, bert_ckpt_file): with tf.io.gfile.GFile(bert_config_file, 'r') as reader: bc = StockBertConfig.from_json_string(reader.read()) bert_params = map_stock_config_to_params(bc) bert_params.adapter_size = None bert = BertModelLayer.from_params(bert_params, name='bert') input_ids = keras.layers.Input(shape=(max_seq_len,), dtype='int32', name='input_ids') bert_output = bert(input_ids) cls_out = keras.layers.Lambda(lambda seq: seq[:, 0, :])(bert_output) cls_out = keras.layers.Dropout(0.5)(cls_out) logits = keras.layers.Dense(units=768, activation='tanh')(cls_out) logits = keras.layers.Dropout(0.5)(logits) logits = keras.layers.Dense(units=len(classes), activation='softmax')(logits) model = keras.Model(inputs=input_ids, outputs=logits) model.build(input_shape=(None, max_seq_len)) load_stock_weights(bert, bert_ckpt_file) return model classes = train.polarity.unique().tolist() data = IntentDetectionData(train, test, tokenizer, classes, max_seq_len=128) print(data.train_x.shape) # Training: model = create_model(data.max_seq_len, bert_ckpt_file) print(model.summary()) model.compile( optimizer=keras.optimizers.Adam(1e-5), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=[keras.metrics.SparseCategoricalAccuracy(name='acc')] ) log_dir = 'log/intent_detection' + datetime.datetime.now().strftime("%Y%m%d-%H%M%s") tensorboard_callback = keras.callbacks.TensorBoard(log_dir=log_dir) history = model.fit( x=data.train_x, y=data.train_y, validation_split=0.1, batch_size=16, shuffle=True, epochs=5, ) check_point_path = '/home/shravan/dissertation/bert_model' tf.saved_model.save(model, check_point_path) # model.save(check_point_path)
[ "shravan007.c@gmail.com" ]
shravan007.c@gmail.com
fd17bac5687007bfef66049ef53312bd0aee968b
0725ed7ab6be91dfc0b16fef12a8871c08917465
/graphs/prims_heapq.py
8882c5d0bb2a707a4563a2ecdda177d65089d3bd
[]
no_license
siddhism/leetcode
8cb194156893fd6e9681ef50c84f0355d09e9026
877933424e6d2c590d6ac53db18bee951a3d9de4
refs/heads/master
2023-03-28T08:14:12.927995
2021-03-24T10:46:20
2021-03-24T10:46:20
212,151,205
0
0
null
null
null
null
UTF-8
Python
false
false
867
py
from collections import defaultdict import heapq def create_spanning_tree(graph, starting_vertex): mst = defaultdict(set) visited = set([starting_vertex]) edges = [ (cost, starting_vertex, to) for to, cost in graph[starting_vertex].items() ] heapq.heapify(edges) while edges: cost, frm, to = heapq.heappop(edges) if to not in visited: visited.add(to) mst[frm].add(to) for to_next, cost in graph[to].items(): if to_next not in visited: heapq.heappush(edges, (cost, to, to_next)) return mst example_graph = { 'A': {'B': 2, 'C': 3}, 'B': {'A': 2, 'C': 1, 'D': 1, 'E': 4}, 'C': {'A': 3, 'B': 1, 'F': 5}, 'D': {'B': 1, 'E': 1}, 'E': {'B': 4, 'D': 1, 'F': 1}, 'F': {'C': 5, 'E': 1, 'G': 1}, 'G': {'F': 1}, }
[ "siddhesh@hackerearth.com" ]
siddhesh@hackerearth.com
89595e2d0b2b80743d056cee641271a2bf19bc41
a560269290749e10466b1a29584f06a2b8385a47
/Notebooks/py/shivamb/bot-generated-baseline-kernel-id-26988/bot-generated-baseline-kernel-id-26988.py
e69a1c1da4d2e8dcf936c469ed28d0b8741ccc02
[]
no_license
nischalshrestha/automatic_wat_discovery
c71befad1aa358ae876d5494a67b0f4aa1266f23
982e700d8e4698a501afffd6c3a2f35346c34f95
refs/heads/master
2022-04-07T12:40:24.376871
2020-03-15T22:27:39
2020-03-15T22:27:39
208,379,586
2
1
null
null
null
null
UTF-8
Python
false
false
15,341
py
#!/usr/bin/env python # coding: utf-8 # ## Baseline Model Pipeline # # Hi, This kernel is automatically generated by the [Aster](https://github.com/shivam5992/aster) - The kaggle bot to generate baseline kernels for a variety of datasets / competitions. In this kernel, I am using the given dataset for exploration, preprocessing, modelling purposes. Let me walk you through the contents of this kernel: # # ### Contents # # 1. Environment Preparation # 2. Quick Exploration # &nbsp;&nbsp;&nbsp;&nbsp; 2.1 Dataset Preparation # &nbsp;&nbsp;&nbsp;&nbsp; 2.2 Dataset Snapshot and Summary # &nbsp;&nbsp;&nbsp;&nbsp; 2.3 Target Variable Distribution # &nbsp;&nbsp;&nbsp;&nbsp; 2.4 Missing Values # &nbsp;&nbsp;&nbsp;&nbsp; 2.5 Variable Types # &nbsp;&nbsp;&nbsp;&nbsp; 2.6 Variable Correlations # 3. Preprocessing # &nbsp;&nbsp;&nbsp;&nbsp; 3.1 Label Encoding # &nbsp;&nbsp;&nbsp;&nbsp; 3.2 Missing Values Treatment # &nbsp;&nbsp;&nbsp;&nbsp; 3.3 Feature Engineering (text fields) # &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3.3.1 TF-IDF Vectorizor # &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3.3.2 Top Keywords - Wordcloud # &nbsp;&nbsp;&nbsp;&nbsp; 3.4 Train Test Split # 4. Modelling # &nbsp;&nbsp;&nbsp;&nbsp; 4.1 Logistic Regression # &nbsp;&nbsp;&nbsp;&nbsp; 4.2 Decision Tree # &nbsp;&nbsp;&nbsp;&nbsp; 4.3 Random Forest # &nbsp;&nbsp;&nbsp;&nbsp; 4.4 ExtraTrees Classifier # &nbsp;&nbsp;&nbsp;&nbsp; 4.5 Extereme Gradient Boosting # 5. Feature Importance # 6. Model Ensembling # &nbsp;&nbsp;&nbsp;&nbsp; 6.1 A simple Blender # 7. Creating Submission # ## Step 1: Prepare Environment # As the first step, lets load all the required libraries to be used in the kernel # In[ ]: ## modelling libraries from sklearn.metrics import confusion_matrix, roc_auc_score, roc_curve, auc from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split, KFold from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier import xgboost as xgb ## preprocessing libraries from sklearn.preprocessing import LabelEncoder from collections import Counter import pandas as pd import numpy as np import itertools import os ## visualization libraries from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt import seaborn as sns print ("all libraries imported successfully") # ## Step 2: Quick Exploration # In the next step, lets load the dataset into my memory and perform a quick exploratory analysis # # ### 2.1 Dataset Preparation # In[ ]: ## read dataset train_path = "../input/train.csv" train_df = pd.read_csv(train_path) train_copy = train_df.copy() test_path = "../input/test.csv" test_df = pd.DataFrame() if os.path.exists(test_path): test_df = pd.read_csv(test_path) print ("dataset loaded") # In[ ]: ## separate predictors and target variables _target = "Survived" Y = train_df[_target] distinct_Y = Y.value_counts().index ## separate the id column _id = "PassengerId" if _id == "": ## if id is not present, create a dummy _id = "id" train_df[_id] = 1 test_df[_id] = 1 if _id not in list(test_df.columns): test_df[_id] = 1 ## drop the target and id columns train_df = train_df.drop([_target, _id], axis=1) test_id = test_df[_id] test_df = test_df.drop([_id], axis=1) # In[ ]: ## flag variables (used by bot to write the relevant code) textcol = "" tag = "num" # ### 2.2 Dataset snapshot and summary # # Lets look at the dataset snapshot and the summary # In[ ]: ## snapshot of train and test train_df.head() # In[ ]: ## summary of train and test train_df.describe() # ### 2.3 Target variable distribution # # Lets plot the distribution of target variable # In[ ]: tar_dist = dict(Counter(Y.values)) xx = list(tar_dist.keys()) yy = list(tar_dist.values()) plt.figure(figsize=(5,3)) sns.set(style="whitegrid") ax = sns.barplot(x=xx, y=yy, palette="rocket") ax.set_title('Distribution of Target') ax.set_ylabel('count'); ax.set_xlabel(_target); # lets generate some plots related to dataset # In[ ]: if tag == "doc": txts = [] for i, y in enumerate(distinct_Y): txt = " ".join(train_copy[train_copy[_target] == y]["text"]).lower() txts.append(txt) for j, text in enumerate(txts): wc = WordCloud(background_color="black", max_words=2000, stopwords=STOPWORDS) wc.generate(text) plt.figure(figsize=(9,8)) plt.axis("off") plt.title("Most frequent words - " + distinct_Y[j], fontsize=20) plt.imshow(wc.recolor(colormap= 'cool' , random_state=17), alpha=0.95) plt.show() # ### 2.4 Missing Value Counts # # Lets check the count of missing values in the datasets # In[ ]: mcount = train_df.isna().sum() xx = mcount.index yy = mcount.values missing_cols = 0 for each in yy: if each > 0: missing_cols += 1 print ("there are " + str(missing_cols) + " columns in the dataset having missing values") if missing_cols > 0: plt.figure(figsize=(12,5)) sns.set(style="whitegrid") ax = sns.barplot(x=xx, y=yy, palette="gist_rainbow") ax.set_title('Number of Missing Values') ax.set_ylabel('Number of Columns'); # ### 2.5 Variable Types # # Lets count the number of numerical and categorical columns in the dataset # In[ ]: ## find categorical columns in the dataset num_cols = train_df._get_numeric_data().columns cat_cols = list(set(train_df.columns) - set(num_cols)) print ("There are " + str(len(num_cols)) + " numerical columns in the dataset") print ("There are " + str(len(cat_cols)) + " object type columns in the dataset") # ### 2.6 Variable Correlations (Only Numerical Fields) # # Lets plot the correlations among the variables. The generated graph can give an idea about features which are highly, moderately or least correlated with one another. # In[ ]: get_corr = False corr = train_df.corr() if len(corr) > 0: get_corr = True colormap = plt.cm.BrBG plt.figure(figsize=(10,10)); plt.title('Pearson Correlation of Features', y=1.05, size=15); sns.heatmap(corr, linewidths=0.1,vmax=1.0, square=True, cmap=colormap, linecolor='white', annot=True); else: print ("No variables available for correlation") # ## Step 3: Data Preprocessing # # In the data preprocessing step, we will perform label encoding of categorical variables and handle missing values. # # ### 3.1 Label Encoding # In this step, convert the categorical variables into label encoded forms # In[ ]: columns = train_df.columns num_cols = train_df._get_numeric_data().columns cat_cols = list(set(columns) - set(num_cols)) if tag == "doc": print ("No columns available for label encoding") elif len(cat_cols) > 0: for col in cat_cols: le = LabelEncoder() if col in list(test_df.columns): le.fit(list(train_df[col].values) + list(test_df[col].values)) else: le.fit(list(train_df[col].values)) train_df[col] = le.transform(list(train_df[col].values)) try: test_df[col] = le.transform(list(test_df[col].values)) except: pass ## label encode the target variable (if object type) if Y.dtype.name == "object": le = LabelEncoder() Y = le.fit_transform(Y.values) # ### 3.2 Missing Values Treatment # # Handle the missing values, for continuous variables, replace by mean. For categorical variables, replace by mode # In[ ]: if tag == "doc": train_df[textcol] = train_df[textcol].fillna("") if textcol in test_df: test_df[textcol] = test_df[textcol].fillna("") else: ## for numerical columns, replace the missing values by mean train_df[num_cols] = train_df[num_cols].fillna(train_df[num_cols].mean()) try: test_df[num_cols] = test_df[num_cols].fillna(test_df[num_cols].mean()) except: pass ## for categorical columns, replace the missing values by mode train_df[cat_cols] = train_df[cat_cols].fillna(train_df[cat_cols].mode()) try: test_df[cat_cols] = test_df[cat_cols].fillna(test_df[cat_cols].mode()) except: pass print ("Treated missing values in the dataset") # ### 3.3 Feature Engineering (only for text fields) # # In this section, we will create relevant features which can be used in the modelling # # #### 3.3.1 Tf IDF features # In[ ]: if tag == "doc": tfidf = TfidfVectorizer(min_df=3, max_features=None, analyzer='word', token_pattern=r'\w{1,}', stop_words = 'english') tfidf.fit(list(train_df[textcol].values)) xtrain = tfidf.transform(train_df[textcol].values) if textcol in test_df.columns: xtest = tfidf.transform(test_df[textcol].values) else: xtrain = train_df xtest = test_df # In[ ]: if tag != "doc": print ("Lets plot the dataset distributions after preprocessing step ... ") ## pair plots sns.pairplot(train_df, palette="cool") ## distributions columns=train_df.columns plt.subplots(figsize=(18,15)) length=len(columns) for i,j in itertools.zip_longest(columns,range(length)): plt.subplot((length/2),3,j+1) plt.subplots_adjust(wspace=0.2,hspace=0.5) train_df[i].hist(bins=20, edgecolor='white') plt.title(i) plt.show() # ### 3.4 Train and Validation sets split # # Create the training and validation sets for training the model and validating it # In[ ]: X_train, X_valid, y_train, y_valid = train_test_split(xtrain, Y, test_size=0.20, random_state=2018) # ### 3.4 Train and Validation sets split # # Create the training and validation sets for training the model and validating it # In[ ]: X_train, X_valid, y_train, y_valid = train_test_split(xtrain, Y, test_size=0.20, random_state=2018) # ## Step 4 : Create baseline model # # Next step is the modelling step, lets start with the simple linear model # # ### 4.1 : Logistic Regression # # Train a binary classifier logistic regression # In[ ]: model1 = LogisticRegression() model1.fit(X_train, y_train) valp = model1.predict(X_valid) def generate_auc(y_valid, valp, model_name): auc_scr = roc_auc_score(y_valid, valp) print('The AUC for ' +model_name+ ' is :', auc_scr) fpr, tpr, thresholds = roc_curve(y_valid, valp) roc_auc = auc(fpr, tpr) plt.figure(figsize=(6,5)) plt.title('Receiver Operating Characteristic') plt.plot(fpr, tpr, 'purple', label = 'AUC = %0.2f' % roc_auc) plt.legend(loc = 'upper left') plt.plot([0, 1], [0, 1],'r--') plt.xlim([0, 1]) plt.ylim([0, 1]) plt.ylabel('True Positive Rate') plt.xlabel('False Positive Rate') plt.show() if len(distinct_Y) == 2: generate_auc(y_valid, valp, model_name="logistic regression") # In[ ]: def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] plt.figure(figsize=(6,5)); plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) plt.grid(False) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') cnf_matrix = confusion_matrix(y_valid, valp) np.set_printoptions(precision=2) plt.figure(figsize=(8,8)) plot_confusion_matrix(cnf_matrix, classes=distinct_Y, title='Confusion matrix Validation Set') plt.show() # ### 4.2 : Decision Tree Classifier # # Lets train a decision tree classifier # In[ ]: model2 = DecisionTreeClassifier() model2.fit(X_train, y_train) valp = model2.predict(X_valid) if len(distinct_Y) == 2: generate_auc(y_valid,valp, model_name="decision tree classifier") # In[ ]: cnf_matrix = confusion_matrix(y_valid, valp) np.set_printoptions(precision=2) plt.figure(figsize=(6,5)); plot_confusion_matrix(cnf_matrix, classes=distinct_Y, title='Confusion matrix Validation Set'); plt.show(); # ### 4.3 : Random Forest Classifier # # Now, lets train a tree based model : random forest # In[ ]: model3 = RandomForestClassifier() model3.fit(X_train, y_train) valp = model3.predict(X_valid) if len(distinct_Y) == 2: generate_auc(y_valid,valp, model_name="random forest classifier") # In[ ]: cnf_matrix = confusion_matrix(y_valid, valp) np.set_printoptions(precision=2) plt.figure(figsize=(6,5)); plot_confusion_matrix(cnf_matrix, classes=distinct_Y, title='Confusion matrix Validation Set'); plt.show(); # ### 4.4 : ExtraTrees Classifier # # Now, lets train another tree based model : extra trees classifier # In[ ]: model4 = ExtraTreesClassifier() model4.fit(X_train, y_train) valp = model4.predict(X_valid) if len(distinct_Y) == 2: generate_auc(y_valid,valp, model_name="extratrees classifier") # In[ ]: cnf_matrix = confusion_matrix(y_valid, valp) np.set_printoptions(precision=2) plt.figure(figsize=(6,5)); plot_confusion_matrix(cnf_matrix, classes=distinct_Y, title='Confusion matrix Validation Set'); plt.show(); # ### 4.5 : xgBoost Classifier # # Lets train the extereme gradient boosting : xgboost classifier # In[ ]: model5 = xgb.XGBClassifier(n_estimators=300, learning_rate=0.01) model5.fit(X_train, y_train) valp = model5.predict(X_valid) if len(distinct_Y) == 2: generate_auc(y_valid,valp, model_name="xgboost") # In[ ]: cnf_matrix = confusion_matrix(y_valid, valp) np.set_printoptions(precision=2) plt.figure(figsize=(6,5)) plot_confusion_matrix(cnf_matrix, classes=distinct_Y, title='Confusion matrix Validation Set') plt.show() # ## Step 5: Feature Importance # # Lets look at some of the important features from the dataset # In[ ]: plt.figure(figsize=(12,8)) xgb.plot_importance(model5, max_num_features=10); # ## Step 6 : Model Ensembling # # Lets create a simple blender. Other options to extend are stacking / majority voting / rank averaging etc. # In[ ]: models = [model1, model2, model3, model4, model5] preds = np.zeros(shape=(xtest.shape[0],)) if len(xtest) == 0: print ("this is a dataset kernel, no test data for predictions") else: for model in models: pred = model.predict(xtest)/ len(models) preds += pred print (preds[:100]) # ## Step 7 : Create Submission File # # Finally, create the submission file from the extereme graident boosting model # In[ ]: if len(xtest) == 0: print ("This is a dataset kernel, no need to create a submission file :)") else: pred = model5.predict(xtest) sub = pd.DataFrame() sub[_id] = test_id sub[_target] = pred sub.to_csv("baseline_submission.csv", index=False) print ("Submission File Generated, here is the snapshot: ") print (sub.head(10)) # Thanks for viewing this kernel, hopefully you can get ideas to start your own kernel.
[ "bitsorific@gmail.com" ]
bitsorific@gmail.com
31334dfe43dc21861f4f854b4f48d4afdc22a0a7
25a417859ab448c5aa4ac4722203d57c01c71ec3
/piecrust/app.py
93a84c36fd9969c283f58aa1de23ec2cd4009ebe
[ "Apache-2.0" ]
permissive
zaxebo1/PieCrust2
d7bd29f96b4217de3b38c0157567e6012fa450cf
a76ff11441a055d0a58b3e3283af88ba18bbf6bc
refs/heads/master
2020-03-26T13:09:19.821998
2018-06-06T05:08:51
2018-06-06T05:08:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,879
py
import time import os.path import logging import urllib.parse from werkzeug.utils import cached_property from piecrust import ( RESOURCES_DIR, CACHE_DIR, TEMPLATES_DIR, ASSETS_DIR, THEME_DIR, PLUGINS_DIR, CONFIG_PATH, THEME_CONFIG_PATH) from piecrust.appconfig import PieCrustConfiguration from piecrust.cache import ExtensibleCache, NullExtensibleCache from piecrust.configuration import ConfigurationError from piecrust.environment import StandardEnvironment from piecrust.page import Page from piecrust.plugins.base import PluginLoader from piecrust.routing import Route from piecrust.sources.base import REALM_THEME from piecrust.uriutil import multi_replace logger = logging.getLogger(__name__) class PieCrust(object): def __init__(self, root_dir, cache=True, debug=False, theme_site=False, env=None, cache_key=None): self.root_dir = root_dir self.debug = debug self.theme_site = theme_site self.plugin_loader = PluginLoader(self) self.cache_key = cache_key or 'default' if cache: self.cache = ExtensibleCache(self.cache_dir) else: self.cache = NullExtensibleCache() if env is None: env = StandardEnvironment() self.env = env env.initialize(self) stats = env.stats stats.registerTimer('SiteConfigLoad') stats.registerTimer('PageLoad') stats.registerTimer("BuildRenderData") stats.registerTimer("BuildLazyPageData") stats.registerTimer("PageRender") stats.registerTimer("PageRenderSegments") stats.registerTimer("PageRenderLayout") stats.registerTimer("PageSerialize") stats.registerCounter('PageLoads') stats.registerCounter('PageRenderSegments') stats.registerCounter('PageRenderLayout') @cached_property def config(self): logger.debug("Creating site configuration...") start_time = time.perf_counter() if not self.theme_site: path = os.path.join(self.root_dir, CONFIG_PATH) else: path = os.path.join(self.root_dir, THEME_CONFIG_PATH) theme_path = None if not self.theme_site and self.theme_dir: theme_path = os.path.join(self.theme_dir, THEME_CONFIG_PATH) config_cache = self.cache.getCache('app') config = PieCrustConfiguration( path=path, theme_path=theme_path, cache=config_cache, theme_config=self.theme_site) local_path = os.path.join( self.root_dir, 'configs', 'local.yml') config.addVariant(local_path, raise_if_not_found=False) if self.theme_site: variant_path = os.path.join( self.root_dir, 'configs', 'theme_preview.yml') config.addVariant(variant_path, raise_if_not_found=False) self.env.stats.stepTimer('SiteConfigLoad', time.perf_counter() - start_time) return config @cached_property def assets_dirs(self): assets_dirs = self._get_configurable_dirs( ASSETS_DIR, 'site/assets_dirs') # Also add the theme directory, if any. if self.theme_dir: default_theme_dir = os.path.join(self.theme_dir, ASSETS_DIR) if os.path.isdir(default_theme_dir): assets_dirs.append(default_theme_dir) return assets_dirs @cached_property def templates_dirs(self): templates_dirs = self._get_configurable_dirs( TEMPLATES_DIR, 'site/templates_dirs') # Also, add the theme directory, if any. if self.theme_dir: default_theme_dir = os.path.join(self.theme_dir, TEMPLATES_DIR) if os.path.isdir(default_theme_dir): templates_dirs.append(default_theme_dir) return templates_dirs @cached_property def theme_dir(self): # No theme if the curent site is already a theme. if self.theme_site: return None # See if there's a theme we absolutely want. td = os.path.join(self.root_dir, THEME_DIR) if os.path.isdir(td): return td # Try to load a theme specified in the configuration. from piecrust.themes.base import ThemeLoader loader = ThemeLoader(self.root_dir) theme_dir = loader.getThemeDir() if theme_dir is not None: return theme_dir # Nothing... use the default theme. return os.path.join(RESOURCES_DIR, 'theme') @cached_property def plugins_dirs(self): return self._get_configurable_dirs(PLUGINS_DIR, 'site/plugins_dirs') @cached_property def cache_dir(self): return os.path.join(self.root_dir, CACHE_DIR, self.cache_key) @cached_property def sources(self): defs = {} for cls in self.plugin_loader.getSources(): defs[cls.SOURCE_NAME] = cls sources = [] for n, s in self.config.get('site/sources').items(): cls = defs.get(s['type']) if cls is None: raise ConfigurationError("No such page source type: %s" % s['type']) src = cls(self, n, s) sources.append(src) return sources @cached_property def routes(self): routes = [] for r in self.config.get('site/routes'): rte = Route(self, r) routes.append(rte) routes = sorted(routes, key=lambda r: r.pass_num) return routes @cached_property def publishers(self): defs_by_name = {} defs_by_scheme = {} for cls in self.plugin_loader.getPublishers(): defs_by_name[cls.PUBLISHER_NAME] = cls if cls.PUBLISHER_SCHEME: defs_by_scheme[cls.PUBLISHER_SCHEME] = cls tgts = [] publish_config = self.config.get('publish') if publish_config is None: return tgts for n, t in publish_config.items(): pub_class = None if isinstance(t, dict): pub_type = t.get('type') pub_class = defs_by_name[pub_type] pub_cfg = t elif isinstance(t, str): comps = urllib.parse.urlparse(t) pub_type = comps.scheme pub_class = defs_by_scheme[pub_type] pub_cfg = None if pub_class is None: raise ConfigurationError("No such publisher: %s" % pub_type) tgt = pub_class(self, n, pub_cfg) if pub_cfg is None: tgt.parseUrlTarget(comps) tgts.append(tgt) return tgts def getSource(self, source_name): for source in self.sources: if source.name == source_name: return source from piecrust.sources.base import SourceNotFoundError raise SourceNotFoundError(source_name) def getSourceRoute(self, source_name): for route in self.routes: if route.source_name == source_name: return route from piecrust.routing import RouteNotFoundError raise RouteNotFoundError(source_name) def getPublisher(self, target_name): for pub in self.publishers: if pub.target == target_name: return pub return None def getPage(self, source, content_item): cache_key = '%s@%s' % (source.name, content_item.spec) return self.env.page_repository.get( cache_key, lambda: Page(source, content_item)) def resolvePath(self, path): path = multi_replace(path, {'%theme_dir%': self.theme_dir}) return os.path.join(self.root_dir, path) def _get_configurable_dirs(self, default_rel_dir, conf_name): dirs = [] # Add custom directories from the configuration. conf_dirs = self.config.get(conf_name) if conf_dirs is not None: if isinstance(conf_dirs, str): dirs.append(self.resolvePath(conf_dirs)) else: dirs += [self.resolvePath(p) for p in conf_dirs] # Add the default directory if it exists. default_dir = os.path.join(self.root_dir, default_rel_dir) if os.path.isdir(default_dir): dirs.append(default_dir) return dirs def apply_variants_and_values(app, config_variants=None, config_values=None): if config_variants is not None: for value in config_variants: logger.debug("Adding configuration variant '%s'." % value) variant_path = os.path.join( app.root_dir, 'configs', '%s.yml' % value) app.config.addVariant(variant_path) if config_values is not None: for name, value in config_values: logger.debug("Adding configuration override '%s': %s" % (name, value)) app.config.addVariantValue(name, value) class PieCrustFactory(object): """ A class that builds a PieCrust app instance. """ def __init__( self, root_dir, *, cache=True, cache_key=None, config_variants=None, config_values=None, debug=False, theme_site=False): self.root_dir = root_dir self.cache = cache self.cache_key = cache_key self.config_variants = config_variants self.config_values = config_values self.debug = debug self.theme_site = theme_site def create(self): app = PieCrust( self.root_dir, cache=self.cache, cache_key=self.cache_key, debug=self.debug, theme_site=self.theme_site) apply_variants_and_values( app, self.config_variants, self.config_values) return app
[ "ludovic@chabant.com" ]
ludovic@chabant.com
990ac94bfab38143c21c6c8fe7fece6484ba3172
b19c9fe62eaa309851dc11f6fd7a05bda463fb58
/bigfish/apps/collection/admin.py
f3c73d16026c10bd38e07e8404f79a8c0c14d24d
[]
no_license
hyu9999/bigfish
3ff3b025982e71bd6dd80f60ad6c70e735e98936
4189fdcacc20795a4778b53c9d47d6fdd3e71811
refs/heads/master
2022-07-08T13:55:12.908583
2019-03-22T09:36:12
2019-03-22T09:36:12
177,055,829
0
0
null
null
null
null
UTF-8
Python
false
false
386
py
from django.contrib import admin from bigfish.apps.collection.models import UserVoice, UserPhoto from bigfish.utils.functions import format_admin_list @admin.register(UserVoice) class UserVoiceAdmin(admin.ModelAdmin): list_display = format_admin_list(UserVoice) @admin.register(UserPhoto) class UserPhotoAdmin(admin.ModelAdmin): list_display = format_admin_list(UserPhoto)
[ "757147959@qq.com" ]
757147959@qq.com
0ed67d205313018188b78a8c3edc3641f2c5e5c0
fc610db81d5cf434ecb348aff2e7b90ea65d2e39
/tests/core/test_utils.py
2cfcefb97a62635e28838f4915bb25256f957200
[ "MIT" ]
permissive
hungphamvn/django-spectator
fd8971942b1cfe7fe3d3358f66291dbce3dedb44
32a3297d206f9a2cb58a28d1b895b468cfbf62df
refs/heads/master
2020-05-26T00:09:44.035364
2019-05-05T18:41:30
2019-05-05T18:41:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,617
py
from django.test import TestCase from spectator.core.utils import chartify from spectator.core.factories import IndividualCreatorFactory class ChartifyTestCase(TestCase): def setUp(self): super().setUp() self.creators = IndividualCreatorFactory.create_batch(5) self.creators[0].num_readings = 10 self.creators[1].num_readings = 8 self.creators[2].num_readings = 8 self.creators[3].num_readings = 6 self.creators[4].num_readings = 0 def test_default_list(self): chart = chartify(self.creators, 'num_readings') self.assertEqual(len(chart), 4) self.assertEqual(chart[0].chart_position, 1) self.assertEqual(chart[1].chart_position, 2) self.assertEqual(chart[2].chart_position, 2) self.assertEqual(chart[3].chart_position, 4) def test_cutoff_is_none(self): "Should include the 0-scoring item." chart = chartify(self.creators, 'num_readings', cutoff=None) self.assertEqual(len(chart), 5) self.assertEqual(chart[0].chart_position, 1) self.assertEqual(chart[1].chart_position, 2) self.assertEqual(chart[2].chart_position, 2) self.assertEqual(chart[3].chart_position, 4) self.assertEqual(chart[4].chart_position, 5) def test_cutoff_value(self): "Should be possible to set a custom cutoff value." chart = chartify(self.creators, 'num_readings', cutoff=6) self.assertEqual(len(chart), 3) self.assertEqual(chart[0].chart_position, 1) self.assertEqual(chart[1].chart_position, 2) self.assertEqual(chart[2].chart_position, 2) def test_ensure_chartiness(self): "By default list should be empty if all objects have the same score." creators = IndividualCreatorFactory.create_batch(3) for c in creators: c.num_readings = 10 chart = chartify(creators, 'num_readings') self.assertEqual(len(chart), 0) def test_ensure_chartiness_false(self): "Should be possible to disable the behaviour." creators = IndividualCreatorFactory.create_batch(3) for c in creators: c.num_readings = 10 chart = chartify(creators, 'num_readings', ensure_chartiness=False) self.assertEqual(len(chart), 3) def test_handle_empty_chart(self): "There was an error if all items in chart met the cutoff value." creator = IndividualCreatorFactory() creator.num_readings = 1 chart = chartify([creator], 'num_readings', cutoff=1) self.assertEqual(len(chart), 0)
[ "phil@gyford.com" ]
phil@gyford.com
cea0b060e4b40cedac41313e5ec52386551b8b1a
3c0cfa2e88c8779c435ac161882acac5a9254816
/virasana/analises/image_ratio.py
ff74291c55c6ee7bde5ca41ea3dc52d0cbcf12b5
[]
no_license
IvanBrasilico/virasana
fc22191ecfcf97f5857027a73ce845e01bc8e8ca
58954b7d36fe02f16b7f2f34190b43b84835effd
refs/heads/master
2023-08-31T07:04:44.953661
2023-08-25T21:00:22
2023-08-25T21:00:22
120,934,545
0
3
null
2021-01-29T13:08:43
2018-02-09T17:21:43
Jupyter Notebook
UTF-8
Python
false
false
1,207
py
""""Análise do ratio de imagens por Recinto/Escâner. Extrai e sumariza relação largura/altura de imagens agrupando por por Recinto/Escâner para permitir a detecção de imagens que estão sendo geradas com poucos pulsos de X-Ray/pouca informação e consequentemente terão a qualidade prejudicada. """ import io import sys import time from collections import defaultdict sys.path.insert(0, '.') sys.path.insert(0, '../ajna_docs/commons') from virasana.db import mongodb as db from ajna_commons.utils.images import mongo_image from PIL import Image def do(): print('Iniciando...') s0 = time.time() sizes_recinto = defaultdict(list) cursor = db.fs.files.find({'metadata.contentType': 'image/jpeg', 'metadata.recinto': {'$exists': True}}, {'_id': 1, 'metadata.recinto': 1}).limit(100) for doc in cursor: _id = doc['_id'] image = Image.open(io.BytesIO(mongo_image(db, _id))) # print(image.size) sizes_recinto[doc['metadata']['recinto']].append(image.size) s1 = time.time() print('{:0.2f} segundos'.format(s1 - s0)) print(sizes_recinto) if __name__ == '__main__': do()
[ "brasilico.ivan@gmail.com" ]
brasilico.ivan@gmail.com
b9a580a0bcfb3b64cee62d98e9208fbe92e05f9a
316b99c6046ff58c8499e0c214e9b81d9c3132b0
/beartype/_util/text/utiltextprefix.py
85f2da32d290220547f451da0925cc9a7f594490
[ "MIT", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference" ]
permissive
beartype/beartype
fb6417b3dc2e08c065f0d907f43411c33d883a7d
0cfd53391eb4de2f8297a4632aa5895b8d82a5b7
refs/heads/main
2023-08-15T13:17:47.095732
2023-08-15T05:25:54
2023-08-15T05:25:54
252,646,465
1,992
51
MIT
2023-07-28T04:13:08
2020-04-03T06:06:22
Python
UTF-8
Python
false
false
4,726
py
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2023 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **text prefix utilities** (i.e., low-level callables creating and returning human-readable strings describing prominent objects or types and *always* suffixed by exactly one space character, intended to prefix human-readable error messages). This private submodule is *not* intended for importation by downstream callers. ''' # ....................{ IMPORTS }.................... from beartype._data.func.datafuncarg import ARG_NAME_RETURN from beartype._data.hint.datahinttyping import BeartypeableT from beartype._util.text.utiltextlabel import ( label_callable, label_type, ) from collections.abc import Callable # ....................{ PREFIXERS ~ beartypeable }.................... #FIXME: Unit test this function with respect to classes, please. def prefix_beartypeable( obj: BeartypeableT, # pyright: ignore[reportInvalidTypeVarUse] ) -> str: ''' Human-readable label describing the passed **beartypeable** (i.e., object that is currently being or has already been decorated by the :func:`beartype.beartype` decorator) suffixed by delimiting whitespace. Parameters ---------- obj : BeartypeableT Beartypeable to be labelled. All remaining keyword parameters are passed as is to the lower-level :func:`.label_beartypeable_kind` function transitively called by this higher-level function. Returns ---------- str Human-readable label describing this beartypeable. ''' # Return either... return ( # If this beartypeable is a class, a label describing this class; f'{label_type(obj)} ' if isinstance(obj, type) else # Else, this beartypeable is a callable. In this case, a label # describing this callable. f'{label_callable(obj)} ' # type: ignore[arg-type] ) # ....................{ PREFIXERS ~ beartypeable : pith }.................... def prefix_beartypeable_pith(func: Callable, pith_name: str) -> str: ''' Human-readable label describing either the parameter with the passed name *or* return value if this name is ``return`` of the passed **beartypeable callable** (i.e., callable wrapped by the :func:`beartype.beartype` decorator with a wrapper function type-checking that callable) suffixed by delimiting whitespace. Parameters ---------- func : Callable Decorated callable to be labelled. pith_name : str Name of the parameter or return value of this callable to be labelled. Returns ---------- str Human-readable label describing either the name of this parameter *or* this return value. ''' assert isinstance(pith_name, str), f'{repr(pith_name)} not string.' # Return a human-readable label describing either... return ( # If this name is "return", the return value of this callable. prefix_beartypeable_return(func) if pith_name == ARG_NAME_RETURN else # Else, the parameter with this name of this callable. prefix_beartypeable_arg(func=func, arg_name=pith_name) ) def prefix_beartypeable_arg(func: Callable, arg_name: str) -> str: ''' Human-readable label describing the parameter with the passed name of the passed **beartypeable callable** (i.e., callable wrapped by the :func:`beartype.beartype` decorator with a wrapper function type-checking that callable) suffixed by delimiting whitespace. Parameters ---------- func : Callable Decorated callable to be labelled. arg_name : str Name of the parameter of this callable to be labelled. Returns ---------- str Human-readable label describing this parameter's name. ''' assert isinstance(arg_name, str), f'{repr(arg_name)} not string.' # Create and return this label. return f'{prefix_beartypeable(func)}parameter "{arg_name}" ' def prefix_beartypeable_return(func: Callable) -> str: ''' Human-readable label describing the return of the passed **decorated callable** (i.e., callable wrapped by the :func:`beartype.beartype` decorator with a wrapper function type-checking that callable) suffixed by delimiting whitespace. Parameters ---------- func : Callable Decorated callable to be labelled. Returns ---------- str Human-readable label describing this return. ''' # Create and return this label. return f'{prefix_beartypeable(func)}return '
[ "leycec@gmail.com" ]
leycec@gmail.com
b51ab4341c846ab28a3ed1eb491f3abae5fb8ba9
3b60e6f4bbc011003ac4929f01eb7409918deb79
/Analysis_v1/ANGenStudy/plots/Plot.py
d1505841e50b3add2dd72d925c3fec7db7ba56c8
[]
no_license
uzzielperez/Analyses
d1a64a4e8730325c94e2bc8461544837be8a179d
1d66fa94763d7847011ea551ee872936c4c401be
refs/heads/master
2023-02-09T04:54:01.854209
2020-09-07T14:57:54
2020-09-07T14:57:54
120,850,137
0
0
null
2020-06-17T16:48:16
2018-02-09T03:14:04
C++
UTF-8
Python
false
false
4,425
py
#!/usr/bin/python import ROOT from ROOT import TClass,TKey, TIter,TCanvas, TPad,TFile, TPaveText, TColor, TGaxis, TH1F, TPad, TH1D, TLegend #from ROOT import kBlack, kBlue, kRed, kGreen, kMagenta, kCyan, kOrange, kViolet, kSpring from ROOT import kBlue, kOrange, kCyan, kRed, kMagenta, kGreen, kViolet, kSpring, kPink, kAzure from ROOT import gBenchmark, gStyle, gROOT, gDirectory #from legend import * #from plotsHelpercomp import * import re import sys CMSlumiPath = '/uscms_data/d3/cuperez/CMSSW_8_0_25/src/scripts/pyroot' sys.path.append(CMSlumiPath) from CMSlumi import CMS_lumi, set_CMS_lumi import argparse sw = ROOT.TStopwatch() sw.Start() LambdaT = "ALL" SMPythia8 = True SM = False ADD = True tag = "b" zoom = False #drawstyle = "hist, same" drawstyle = "same" intlumi = 130 BKG = [] path = "/uscms_data/d3/cuperez/CMSSW_8_0_25/src/scripts/Analysis_v1/UnparticlesSplitStudy" BKG.append("%s/Unparticles_SM_M_500-2000.root" %(path)) BKG.append("%s/Unparticles_SM_M-2000.root" %(path)) BKG.append("../processed/GGJetsAN_M-1000.root") DATASET = [] DATASET.append("../MkClassScripts/OUTTestSTest1p1Unp1500p0_spin-0_M_500-2000_py_GEN.root") DATASET.append("../MkClassScripts/OUTTestSTest1p1Unp1500p0_spin-2_M_500-2000_py_GEN.root") DATASET.append("../MkClassScripts/OUTTestSTest1p1Unp2500p0_spin-0_M_500-2000_py_GEN.root") DATASET.append("../MkClassScripts/OUTTestSTest1p1Unp2500p0_spin-2_M_500-2000_py_GEN.root") DATASET.append("../MkClassScripts/OUTTestSTest1p1Unp4000p0_spin-0_M_500-2000_py_GEN.root") DATASET.append("../MkClassScripts/OUTTestSTest1p1Unp4000p0_spin-2_M_2000_py_GEN.root") # # Draw Options DrawAsHi = False gStyle.SetOptStat(0) bkgf = [] for fi in BKG: bkgf.append(ROOT.TFile(fi, "READ")) uf = [] for datafile in DATASET: uf.append(ROOT.TFile(datafile, "READ")) canvas = ROOT.TCanvas() canvas.SetLogy() obj = "gendiphotonMinv" uh = [] bkgh = [] for ofile in bkgf: bkgh.append(ofile.Get(obj)) for openfile in uf: uh.append(openfile.Get(obj)) xtitle = r"m_{#gamma#gamma}#scale[1.0]{(GeV)}" ytitle = r"#scale[1.0]{Nevents}" xmin, xmax = 500, 13000 if zoom: xmin, xmax = 1000, 2500 x_range = "%s-%s" %(str(xmin), str(xmax)) xpos1, ypos1, xpos2, ypos2 = .55, 0.58, .85, .88 leg = TLegend(xpos1, ypos1, xpos2, ypos2) leg.SetBorderSize(0) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextFont(42) leg.SetTextSize(0.035) if SMPythia8: tag = tag + "SM" histSM = bkgh[0].Clone("histSM") histSM.Add(bkgh[1], 1.0) histSM.SetFillStyle(3144) histSM.SetFillColor(7) histSM.Scale(intlumi) histSM.Draw("hist") label = "SM" leg.AddEntry(histSM, "%s" %(label), "f") print "Drawn", label if SM: tag = tag + "SM" histSM = bkgh[3].Clone("histSM") #histSM.Add(bkgh[1], 1.0) histSM.SetFillStyle(3144) histSM.SetFillColor(7) histSM.Scale(intlumi) #histSM.Draw("hist") label = "SM" leg.AddEntry(histSM, "%s" %(label), "f") print "Drawn", label colorlist = [kBlue, kOrange, kCyan, kRed, kMagenta, kGreen, kViolet, kSpring, kPink, kAzure, kOrange+8, kGreen+8, kRed+8, kViolet+8, kMagenta+5] labels = [] histClones = [] iset = 0 icolor = 0 i = 0 while iset < len(DATASET): pattern = "TestADD_NI-1_([^(]*)_M-1000.root" label = re.findall(pattern, DATASET[iset]) labels.append(label[0]) tag = tag + label[0] #histClone.delete iset = iset + 1 while i < len(DATASET): histClone = uh[i].Clone("histdu%s" %(labels[i])) #histClone.Add(uh[i+1], 1.0) histClones.append(histClone) i = i + 1 j = 0 for histclone in histClones: histclone.SetLineColor(colorlist[icolor]) histclone.Scale(intlumi) histclone.Draw(drawstyle) print labels[j] leglabel = r"d#Lambda_{T} = %s" %(labels[j]) leg.AddEntry(histclone, "%s" %(leglabel), "l") j = j+1 icolor = icolor + 1 #iclone = 0 #while iclone < len(histClones): # histClones[iclone].Add(uh[iclone+1], 1.0) # iclone.SetLineColor(colorlist[icolor]) # iclone.Scale(intlumi) # iclone.Draw(drawstyle) # leglabel = r"du = %s, #Lambda_{U} = %s" %(label) # leg.AddEntry(histClone, "%s" %(leglabel), "l") # histClone.delete # # icolor = icolor + 1 print tag histSM.GetYaxis().SetTitle(ytitle) histSM.GetYaxis().SetTitleOffset(1.0) histSM.GetXaxis().SetTitle(xtitle) histSM.GetXaxis().SetRangeUser(xmin, xmax) leg.Draw() set_CMS_lumi(canvas, 4, 11, intlumi) canvas.Update() canvas.Draw() canvas.Print("LOG%s_SMvsADD_%sfb-1_%s_%s.pdf" %(intlumi, LambdaT, obj,tag))
[ "uzzie.perez@cern.ch" ]
uzzie.perez@cern.ch
a60d525dcf91219404c259df8956699c19f69cff
bfd41fc543f6dbfc821341522cf8e7a9d2e34ce8
/venv/bin/xhtml2pdf
de9af05ac590655a7ef64f3ce643a5f9be0576b6
[]
no_license
MaraKovalcik/Flask
783243560ead637a381f76d3893da2b212eff898
1ff8413f3551b051f8e6c76db6cf402fc7428188
refs/heads/master
2021-01-22T09:09:16.165734
2015-02-24T16:57:14
2015-02-24T16:57:14
31,268,626
1
0
null
null
null
null
UTF-8
Python
false
false
363
#!/home/mara/Dokumenty/PycharmProjects/flask-skeleton/venv/bin/python # EASY-INSTALL-ENTRY-SCRIPT: 'xhtml2pdf==0.0.6','console_scripts','xhtml2pdf' __requires__ = 'xhtml2pdf==0.0.6' import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.exit( load_entry_point('xhtml2pdf==0.0.6', 'console_scripts', 'xhtml2pdf')() )
[ "mara.kovalcik@gmail.com" ]
mara.kovalcik@gmail.com
d57a1672ca8cc1d7d86cde2c960bab5c824c62a4
77311ad9622a7d8b88707d7cee3f44de7c8860cb
/res/scripts/client/gui/scaleform/daapi/view/meta/customizationfilterspopovermeta.py
5b2d5a5854daef6458e0c2117852d24bd8aa65ae
[]
no_license
webiumsk/WOT-0.9.14-CT
9b193191505a4560df4e872e022eebf59308057e
cfe0b03e511d02c36ce185f308eb48f13ecc05ca
refs/heads/master
2021-01-10T02:14:10.830715
2016-02-14T11:59:59
2016-02-14T11:59:59
51,606,676
0
0
null
null
null
null
WINDOWS-1250
Python
false
false
1,264
py
# 2016.02.14 12:40:16 Střední Evropa (běžný čas) # Embedded file name: scripts/client/gui/Scaleform/daapi/view/meta/CustomizationFiltersPopoverMeta.py from gui.Scaleform.daapi.view.lobby.popover.SmartPopOverView import SmartPopOverView class CustomizationFiltersPopoverMeta(SmartPopOverView): def changeFilter(self, groupId, itemId): self._printOverrideError('changeFilter') def setDefaultFilter(self): self._printOverrideError('setDefaultFilter') def as_setInitDataS(self, data): if self._isDAAPIInited(): return self.flashObject.as_setInitData(data) def as_setStateS(self, data): if self._isDAAPIInited(): return self.flashObject.as_setState(data) def as_enableDefBtnS(self, value): if self._isDAAPIInited(): return self.flashObject.as_enableDefBtn(value) def as_enableGroupFilterS(self, value): if self._isDAAPIInited(): return self.flashObject.as_enableGroupFilter(value) # okay decompyling c:\Users\PC\wotsources\files\originals\res\scripts\client\gui\scaleform\daapi\view\meta\customizationfilterspopovermeta.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2016.02.14 12:40:16 Střední Evropa (běžný čas)
[ "info@webium.sk" ]
info@webium.sk
7e439da3b100e153179f8cab56a740cc09a6d15e
f15ba8cdc7074692acadb5aa40f0647e27901c0f
/backend/driver/migrations/0001_initial.py
24750369ddd51e15f0a9cf127bd27a98dd62bb67
[]
no_license
crowdbotics-apps/mexican-18491
5f964019aa1d6a1848ff9e9ca4ddff533ef6ceaa
dffd7c9f02ebca9439bb26ee19ec6fdd689b4c94
refs/heads/master
2022-11-11T09:17:11.959916
2020-06-29T19:23:08
2020-06-29T19:23:08
275,906,006
0
0
null
null
null
null
UTF-8
Python
false
false
1,674
py
# Generated by Django 2.2.13 on 2020-06-29 19:22 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('delivery_order', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='DriverProfile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('photo', models.URLField()), ('timestamp_created', models.DateTimeField(auto_now_add=True)), ('last_updated', models.DateTimeField(auto_now=True)), ('details', models.TextField(blank=True, null=True)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='driverprofile_user', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='DriverOrder', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('timestamp_created', models.DateTimeField(auto_now_add=True)), ('driver', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='driverorder_driver', to='driver.DriverProfile')), ('order', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='driverorder_order', to='delivery_order.Order')), ], ), ]
[ "team@crowdbotics.com" ]
team@crowdbotics.com
5e8515ccebe8461c731142db75dd9aa8e3c753fe
2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02
/PyTorch/contrib/cv/detection/s3fd_for_PyTorch/data/factory.py
d27ba99ebd8bf87a32b5f964e2ba145d9e67fea1
[ "GPL-1.0-or-later", "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Ascend/ModelZoo-PyTorch
4c89414b9e2582cef9926d4670108a090c839d2d
92acc188d3a0f634de58463b6676e70df83ef808
refs/heads/master
2023-07-19T12:40:00.512853
2023-07-17T02:48:18
2023-07-17T02:48:18
483,502,469
23
6
Apache-2.0
2022-10-15T09:29:12
2022-04-20T04:11:18
Python
UTF-8
Python
false
false
2,486
py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ # Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import division from __future__ import absolute_import from __future__ import print_function from .widerface import WIDERDetection from .config import cfg import torch def dataset_factory(dataset): """ dataset_factory """ if dataset == 'face': train_dataset = WIDERDetection(cfg.FACE.TRAIN_FILE, mode='train') val_dataset = WIDERDetection(cfg.FACE.VAL_FILE, mode='val') return train_dataset, val_dataset def detection_collate(batch): """Custom collate fn for dealing with batches of images that have a different number of associated object annotations (bounding boxes). Arguments: batch: (tuple) A tuple of tensor images and lists of annotations Return: A tuple containing: 1) (tensor) batch of images stacked on their 0 dim 2) (list of tensors) annotations for a given image are stacked on 0 dim """ targets = [] imgs = [] for sample in batch: imgs.append(sample[0]) targets.append(torch.FloatTensor(sample[1])) return torch.stack(imgs, 0), targets
[ "wangjiangben@huawei.com" ]
wangjiangben@huawei.com
30d87a4b7451160fb6db181e5d913dcfaad1dbb9
0dca69b51629f06e66b2d3263f287cccf2f08fc4
/src/dungeonbot/models/highlights.py
30494bc281d3f8a0b98029876bb57dcfdc5917aa
[ "MIT" ]
permissive
DungeonBot/dungeonbot
c30bb433a25b8a69b346e9b900674d64b5ddace5
715c14d3a06d8a7a8771572371b67cc87c7e17fb
refs/heads/master
2021-06-22T18:34:05.270805
2017-04-03T22:40:56
2017-04-04T02:26:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,008
py
from dungeonbot.models import db from datetime import datetime class HighlightModel(db.Model): """Model for campaign highlights.""" __table_args__ = {"extend_existing": True} id = db.Column(db.Integer, primary_key=True) text = db.Column(db.String(256)) created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow()) @classmethod def new(cls, args=None, session=None): """Create and store new Highlight.""" if not args: return if session is None: session = db.session instance = cls(text=args) session.add(instance) session.commit() return instance @classmethod def list(cls, how_many=10, session=None): """Retrieve stored highlights, limited by 'how_many'.""" if session is None: session = db.session return ( session.query(cls). order_by('created desc'). limit(how_many). all() )
[ "tanner.lake@gmail.com" ]
tanner.lake@gmail.com
0f4f218d5415925d9816306417dabc6360e29595
4c45f5bbd42bda74acb304e9f178bda93df01f8b
/simple_password.py
073228b41cfc962ca4ce9d1d55ef3d0b57bb9572
[]
no_license
bpavankumar5656/coderbyte
d39bd6657a810758489eebc4f025e82bdbbc7bf1
7455ce6d9a92b46eb21dcd5d353c48da9f4e5455
refs/heads/master
2023-03-17T22:47:16.867478
2019-07-22T01:45:15
2019-07-22T01:45:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,286
py
""" Have the function SimplePassword(str) take the str parameter being passed and determine if it passes as a valid password that follows the list of constraints: 1. It must have a capital letter. 2. It must contain at least one number. 3. It must contain a punctuation mark. 4. It cannot have the word "password" in the string. 5. It must be longer than 7 characters and shorter than 31 characters. If all the above constraints are met within the string, the your program should return the string true, otherwise your program should return the string false. For example: if str is "apple!M7" then your program should return "true". Use the Parameter Testing feature in the box below to test your code with different arguments. """ import re def SimplePassword(str): upper = False number = False mark = False if 'password' in str.lower(): return "false" if len(str) < 7 or len(str) > 31: return "false" for char in str: upper = upper if not char.isupper() else True number = number if not char.isdigit() else True mark = mark if not re.match(r'\W', char) else True return "true" if (upper and number and mark) else "false" # keep this function call here print (SimplePassword(raw_input()))
[ "luismiguel.mopa@gmail.com" ]
luismiguel.mopa@gmail.com
b04cfcf235cf8701e45fd7b18703a018bd407ec4
be12916ec075c76469946f6da2cdde4857141702
/771_3.py
03c1bf738765f51107f25690d14671aafa1a7d09
[]
no_license
goodsosbva/algorithm
7b2f9b1a899e43c7d120ab9d40e672be336a23d9
0bc44e9466d2d32a4b4e126e073badc60172da6e
refs/heads/main
2023-08-06T19:34:40.630006
2021-09-20T10:34:41
2021-09-20T10:34:41
334,918,056
3
0
null
null
null
null
UTF-8
Python
false
false
174
py
def numJewelsInStones(J: str, S: str) -> int: return sum(s in J for s in S) jew = "aA" stone = "aAAbbbbaa" jcount = numJewelsInStones(jew, stone) print(jcount)
[ "noreply@github.com" ]
goodsosbva.noreply@github.com
66abb4d2ef1586a2f3a282777ffe748d4596aa7c
a951bcce35dfa63db7a812bd27c1863f286e37cf
/tests/testflows/ldap/role_mapping/regression.py
a2c70d8bd4149a454b754f8058e1b2d2bafdf73a
[ "Apache-2.0" ]
permissive
nikitamikhaylov/ClickHouse
294be1c43cbb0e6100145ce4cc5d3fb1191c0de2
88629657ca54f92c7fe1bf3f055e3389668ded3c
refs/heads/master
2022-03-02T09:35:26.300566
2022-01-27T10:09:17
2022-01-27T10:09:17
197,409,528
1
3
Apache-2.0
2021-11-10T16:03:27
2019-07-17T14:50:45
C++
UTF-8
Python
false
false
1,576
py
#!/usr/bin/env python3 import os import sys from testflows.core import * append_path(sys.path, "..", "..") from helpers.cluster import Cluster from helpers.argparser import argparser from ldap.role_mapping.requirements import * # Cross-outs of known fails xfails = { "mapping/roles removed and added in parallel": [(Fail, "known bug")], "user dn detection/mapping/roles removed and added in parallel": [(Fail, "known bug")] } @TestFeature @Name("role mapping") @ArgumentParser(argparser) @Specifications( SRS_014_ClickHouse_LDAP_Role_Mapping ) @Requirements( RQ_SRS_014_LDAP_RoleMapping("1.0") ) @XFails(xfails) def regression(self, local, clickhouse_binary_path, stress=None, parallel=None): """ClickHouse LDAP role mapping regression module. """ nodes = { "clickhouse": ("clickhouse1", "clickhouse2", "clickhouse3"), } if stress is not None: self.context.stress = stress if parallel is not None: self.context.parallel = parallel with Cluster(local, clickhouse_binary_path, nodes=nodes, docker_compose_project_dir=os.path.join(current_dir(), "ldap_role_mapping_env")) as cluster: self.context.cluster = cluster Scenario(run=load("ldap.authentication.tests.sanity", "scenario"), name="ldap sanity") Feature(run=load("ldap.role_mapping.tests.server_config", "feature")) Feature(run=load("ldap.role_mapping.tests.mapping", "feature")) #Feature(run=load("ldap.role_mapping.tests.user_dn_detection", "feature")) if main(): regression()
[ "vzakaznikov@protonmail.com" ]
vzakaznikov@protonmail.com
f7c56aacf296c9ad4d9e8c15ecc668aba8f15f1a
d554b1aa8b70fddf81da8988b4aaa43788fede88
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4140/codes/1585_2895.py
5e22707faebf5f16a8466dd9e4340a2bc99377ee
[]
no_license
JosephLevinthal/Research-projects
a3bc3ca3b09faad16f5cce5949a2279cf14742ba
60d5fd6eb864a5181f4321e7a992812f3c2139f9
refs/heads/master
2022-07-31T06:43:02.686109
2020-05-23T00:24:26
2020-05-23T00:24:26
266,199,309
1
0
null
null
null
null
UTF-8
Python
false
false
97
py
var1=float(input()); var2=float(input()); var3=float(input()); var4=var1*var2+var3; print(var4);
[ "jvlo@icomp.ufam.edu.br" ]
jvlo@icomp.ufam.edu.br
da59520dd091280c17c50e446feb08a2e5b97db6
55c250525bd7198ac905b1f2f86d16a44f73e03a
/Python/pygame/pygameweb/pygameweb/project/models.py
b6b610b87e3c83391214fcd286c9756c9b1a504a
[ "BSD-2-Clause" ]
permissive
NateWeiler/Resources
213d18ba86f7cc9d845741b8571b9e2c2c6be916
bd4a8a82a3e83a381c97d19e5df42cbababfc66c
refs/heads/master
2023-09-03T17:50:31.937137
2023-08-28T23:50:57
2023-08-28T23:50:57
267,368,545
2
1
null
2022-09-08T15:20:18
2020-05-27T16:18:17
null
UTF-8
Python
false
false
129
py
version https://git-lfs.github.com/spec/v1 oid sha256:30636a4eef22c0481f5af61e690f051065e2a438fd56ed9ba2af78c5d3611faa size 6807
[ "nateweiler84@gmail.com" ]
nateweiler84@gmail.com
65ee71e2a040f4b139d52b292639fd03162a1bbe
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03135/s054462587.py
f91946780c8335b77dd825693541d5290828bcf4
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
55
py
inp=list(map(int,input().split())) print(inp[0]/inp[1])
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
1c7a659445f9609b12a3b52e85abebe758640fb3
129d0272314aae880c88280008b4ce01049e34ef
/randori/socialnet/models/old/revision.py
9db6fc56aeff436c81a527005cfa4757017a1713
[]
no_license
fstakem/Amphora
4eacab3c3af33dd8e3dd0121f3d05dce81abeddb
f4164e583db18e8947a5f5f79ca13d861c351694
refs/heads/master
2021-01-15T20:38:11.169657
2014-02-05T14:31:31
2014-02-05T14:31:31
13,034,852
0
0
null
null
null
null
UTF-8
Python
false
false
1,054
py
# +++---+++---+++---+++---+++---+++---+++---+++---+++---+++---+++---+++---+++---+++---+++---+++ # # File: revision.py # By: Fred Stakem # For: Private Research # Date: 12.5.13 # # +++---+++---+++---+++---+++---+++---+++---+++---+++---+++---+++---+++---+++---+++---+++---+++ # Librarys from django.db import models # App imports # Main class Revision(models.Model): class Meta(): app_label = 'socialnet' # Attributes # Relationships # Add later tree # -> parent # -> children # Add later # -> owner version = models.ForeignKey('Version', related_name='in_revision') project = models.ForeignKey('Project', blank=True, null=True, related_name='previous_revision') software_stack = models.ManyToManyField('SoftwareStack', blank=True, null=True, related_name='used_for_revision') def __unicode__(self): return self.version.__unicode__() def name(self): return self.version.name() def dotName(self): return self.version.dotName()
[ "fstakem@gmail.com" ]
fstakem@gmail.com
52bbd2da5f16e2e45882054dd53968aeab863bb1
f5de47cb74b1f29e0d13be198e4b0b510ec027de
/mb_api/request.py
30bd762513c7705b94dee5b2b7d053c5c19fca63
[]
no_license
kahihia/planIt---ride-sharing-app
f15efc119eb1c81fb0f1b5b6ef8edc41ecb509b4
9dd3b34ba8ee077bd7c2ed8f2dfc3d8156829d93
refs/heads/master
2020-04-24T22:27:17.141110
2016-11-05T17:02:44
2016-11-05T17:02:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
14,561
py
""" The Request class is used as a wrapper around the standard request object. The wrapped request then offers a richer API, in particular : - content automatically parsed according to `Content-Type` header, and available as `request.DATA` - full support of PUT method, including support for file uploads - form overloading of HTTP method, content type and content """ from __future__ import unicode_literals from django.conf import settings from django.http import QueryDict from django.http.multipartparser import parse_header from django.utils.datastructures import MultiValueDict from mb_api import HTTP_HEADER_ENCODING from mb_api import exceptions from mb_api.compat import BytesIO from mb_api.settings import api_settings def is_form_media_type(media_type): """ Return True if the media type is a valid form media type. """ base_media_type, params = parse_header(media_type.encode(HTTP_HEADER_ENCODING)) return (base_media_type == 'application/x-www-form-urlencoded' or base_media_type == 'multipart/form-data') class override_method(object): """ A context manager that temporarily overrides the method on a request, additionally setting the `view.request` attribute. Usage: with override_method(view, request, 'POST') as request: ... # Do stuff with `view` and `request` """ def __init__(self, view, request, method): self.view = view self.request = request self.method = method self.action = getattr(view, 'action', None) def __enter__(self): self.view.request = clone_request(self.request, self.method) if self.action is not None: # For viewsets we also set the `.action` attribute. action_map = getattr(self.view, 'action_map', {}) self.view.action = action_map.get(self.method.lower()) return self.view.request def __exit__(self, *args, **kwarg): self.view.request = self.request if self.action is not None: self.view.action = self.action class Empty(object): """ Placeholder for unset attributes. Cannot use `None`, as that may be a valid value. """ pass def _hasattr(obj, name): return not getattr(obj, name) is Empty def clone_request(request, method): """ Internal helper method to clone a request, replacing with a different HTTP method. Used for checking permissions against other methods. """ ret = Request(request=request._request, parsers=request.parsers, authenticators=request.authenticators, negotiator=request.negotiator, parser_context=request.parser_context) ret._data = request._data ret._files = request._files ret._content_type = request._content_type ret._stream = request._stream ret._method = method if hasattr(request, '_user'): ret._user = request._user if hasattr(request, '_auth'): ret._auth = request._auth if hasattr(request, '_authenticator'): ret._authenticator = request._authenticator return ret class ForcedAuthentication(object): """ This authentication class is used if the test client or request factory forcibly authenticated the request. """ def __init__(self, force_user, force_token): self.force_user = force_user self.force_token = force_token def authenticate(self, request): return (self.force_user, self.force_token) class Request(object): """ Wrapper allowing to enhance a standard `HttpRequest` instance. Kwargs: - request(HttpRequest). The original request instance. - parsers_classes(list/tuple). The parsers to use for parsing the request content. - authentication_classes(list/tuple). The authentications used to try authenticating the request's user. """ _METHOD_PARAM = api_settings.FORM_METHOD_OVERRIDE _CONTENT_PARAM = api_settings.FORM_CONTENT_OVERRIDE _CONTENTTYPE_PARAM = api_settings.FORM_CONTENTTYPE_OVERRIDE def __init__(self, request, parsers=None, authenticators=None, negotiator=None, parser_context=None): self._request = request self.parsers = parsers or () self.authenticators = authenticators or () self.negotiator = negotiator or self._default_negotiator() self.parser_context = parser_context self._data = Empty self._files = Empty self._method = Empty self._content_type = Empty self._stream = Empty if self.parser_context is None: self.parser_context = {} self.parser_context['request'] = self self.parser_context['encoding'] = request.encoding or settings.DEFAULT_CHARSET force_user = getattr(request, '_force_auth_user', None) force_token = getattr(request, '_force_auth_token', None) if (force_user is not None or force_token is not None): forced_auth = ForcedAuthentication(force_user, force_token) self.authenticators = (forced_auth,) def _default_negotiator(self): return api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS() @property def method(self): """ Returns the HTTP method. This allows the `method` to be overridden by using a hidden `form` field on a form POST request. """ if not _hasattr(self, '_method'): self._load_method_and_content_type() return self._method @property def content_type(self): """ Returns the content type header. This should be used instead of `request.META.get('HTTP_CONTENT_TYPE')`, as it allows the content type to be overridden by using a hidden form field on a form POST request. """ if not _hasattr(self, '_content_type'): self._load_method_and_content_type() return self._content_type @property def stream(self): """ Returns an object that may be used to stream the request content. """ if not _hasattr(self, '_stream'): self._load_stream() return self._stream @property def QUERY_PARAMS(self): """ More semantically correct name for request.GET. """ return self._request.GET @property def DATA(self): """ Parses the request body and returns the data. Similar to usual behaviour of `request.POST`, except that it handles arbitrary parsers, and also works on methods other than POST (eg PUT). """ if not _hasattr(self, '_data'): self._load_data_and_files() return self._data @property def FILES(self): """ Parses the request body and returns any files uploaded in the request. Similar to usual behaviour of `request.FILES`, except that it handles arbitrary parsers, and also works on methods other than POST (eg PUT). """ if not _hasattr(self, '_files'): self._load_data_and_files() return self._files @property def user(self): """ Returns the user associated with the current request, as authenticated by the authentication classes provided to the request. """ if not hasattr(self, '_user'): self._authenticate() return self._user @user.setter def user(self, value): """ Sets the user on the current request. This is necessary to maintain compatibility with django.contrib.auth where the user property is set in the login and logout functions. """ self._user = value @property def auth(self): """ Returns any non-user authentication information associated with the request, such as an authentication token. """ if not hasattr(self, '_auth'): self._authenticate() return self._auth @auth.setter def auth(self, value): """ Sets any non-user authentication information associated with the request, such as an authentication token. """ self._auth = value @property def successful_authenticator(self): """ Return the instance of the authentication instance class that was used to authenticate the request, or `None`. """ if not hasattr(self, '_authenticator'): self._authenticate() return self._authenticator def _load_data_and_files(self): """ Parses the request content into self.DATA and self.FILES. """ if not _hasattr(self, '_content_type'): self._load_method_and_content_type() if not _hasattr(self, '_data'): self._data, self._files = self._parse() def _load_method_and_content_type(self): """ Sets the method and content_type, and then check if they've been overridden. """ self._content_type = self.META.get('HTTP_CONTENT_TYPE', self.META.get('CONTENT_TYPE', '')) self._perform_form_overloading() if not _hasattr(self, '_method'): self._method = self._request.method # Allow X-HTTP-METHOD-OVERRIDE header if 'HTTP_X_HTTP_METHOD_OVERRIDE' in self.META: self._method = self.META['HTTP_X_HTTP_METHOD_OVERRIDE'].upper() def _load_stream(self): """ Return the content body of the request, as a stream. """ try: content_length = int( self.META.get( 'CONTENT_LENGTH', self.META.get('HTTP_CONTENT_LENGTH') ) ) except (ValueError, TypeError): content_length = 0 if content_length == 0: self._stream = None elif hasattr(self._request, 'read'): self._stream = self._request else: self._stream = BytesIO(self.raw_post_data) def _perform_form_overloading(self): """ If this is a form POST request, then we need to check if the method and content/content_type have been overridden by setting them in hidden form fields or not. """ USE_FORM_OVERLOADING = ( self._METHOD_PARAM or (self._CONTENT_PARAM and self._CONTENTTYPE_PARAM) ) # We only need to use form overloading on form POST requests. if ( not USE_FORM_OVERLOADING or self._request.method != 'POST' or not is_form_media_type(self._content_type) ): return # At this point we're committed to parsing the request as form data. self._data = self._request.POST self._files = self._request.FILES # Method overloading - change the method and remove the param from the content. if ( self._METHOD_PARAM and self._METHOD_PARAM in self._data ): self._method = self._data[self._METHOD_PARAM].upper() # Content overloading - modify the content type, and force re-parse. if ( self._CONTENT_PARAM and self._CONTENTTYPE_PARAM and self._CONTENT_PARAM in self._data and self._CONTENTTYPE_PARAM in self._data ): self._content_type = self._data[self._CONTENTTYPE_PARAM] self._stream = BytesIO(self._data[self._CONTENT_PARAM].encode(self.parser_context['encoding'])) self._data, self._files = (Empty, Empty) def _parse(self): """ Parse the request content, returning a two-tuple of (data, files) May raise an `UnsupportedMediaType`, or `ParseError` exception. """ stream = self.stream media_type = self.content_type if stream is None or media_type is None: empty_data = QueryDict('', encoding=self._request._encoding) empty_files = MultiValueDict() return (empty_data, empty_files) parser = self.negotiator.select_parser(self, self.parsers) if not parser: raise exceptions.UnsupportedMediaType(media_type) try: parsed = parser.parse(stream, media_type, self.parser_context) except: # If we get an exception during parsing, fill in empty data and # re-raise. Ensures we don't simply repeat the error when # attempting to render the browsable renderer response, or when # logging the request or similar. self._data = QueryDict('', encoding=self._request._encoding) self._files = MultiValueDict() raise # Parser classes may return the raw data, or a # DataAndFiles object. Unpack the result as required. try: return (parsed.data, parsed.files) except AttributeError: empty_files = MultiValueDict() return (parsed, empty_files) def _authenticate(self): """ Attempt to authenticate the request using each authentication instance in turn. Returns a three-tuple of (authenticator, user, authtoken). """ for authenticator in self.authenticators: try: user_auth_tuple = authenticator.authenticate(self) except exceptions.APIException: self._not_authenticated() raise if user_auth_tuple is not None: self._authenticator = authenticator self._user, self._auth = user_auth_tuple return self._not_authenticated() def _not_authenticated(self): """ Return a three-tuple of (authenticator, user, authtoken), representing an unauthenticated request. By default this will be (None, AnonymousUser, None). """ self._authenticator = None if api_settings.UNAUTHENTICATED_USER: self._user = api_settings.UNAUTHENTICATED_USER() else: self._user = None if api_settings.UNAUTHENTICATED_TOKEN: self._auth = api_settings.UNAUTHENTICATED_TOKEN() else: self._auth = None def __getattr__(self, attr): """ Proxy other attributes to the underlying HttpRequest object. """ return getattr(self._request, attr)
[ "Aakash Tyagi" ]
Aakash Tyagi
8e480d623a40f3dba37d571a29668dc0047c4345
b16d94254ad16565e1d197e74fa2c24d9a8506ba
/src-distributed-qanda-alt/utils.py
247ccbaa085453fad197bfc5128122ee28d35066
[ "LGPL-2.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "CC0-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "Python-2.0", "MIT" ]
permissive
data-science-on-aws/data-science-on-aws
438455319f05e18e9d154777a474db26cd73005f
2e2405f2968c454065447a0ef9aa1dcc2c05b477
refs/heads/generative
2023-07-22T16:55:38.372524
2023-05-03T03:31:04
2023-05-03T03:31:04
244,029,618
687
231
Apache-2.0
2023-04-12T17:01:11
2020-02-29T19:33:58
Jupyter Notebook
UTF-8
Python
false
false
5,245
py
import argparse from contextlib import contextmanager import torch import os import json from transformers import ( MODEL_MAPPING, SchedulerType ) # Distributed training helper methods. def wait_for_everyone(): #deepspeed.comm.barrier torch.distributed.barrier() def is_main_process(rank): if rank == 0: return True else: return False def _goes_first(is_main): if not is_main: wait_for_everyone() yield if is_main: wait_for_everyone() @contextmanager def main_process_first(rank): """ Lets the main process go first inside a with block. The other processes will enter the with block after the main process exits. """ yield from _goes_first(is_main_process(rank)) def is_local_main_process(local_rank): return local_rank == 0 # args parsing MODEL_CONFIG_CLASSES = list(MODEL_MAPPING.keys()) MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) def parse_args(): parser = argparse.ArgumentParser(description="Finetune a FLAN T5 model on a Seq2Seq task") parser.add_argument( "--train_file", type=str, default=None, help="A csv or a json file containing the training data." ) parser.add_argument( "--validation_file", type=str, default=None, help="A csv or a json file containing the validation data." ) parser.add_argument( "--model_name_or_path", type=str, help="Path to pretrained model or model identifier from huggingface.co/models.", required=False, ) parser.add_argument( "--config_name", type=str, default=None, help="Pretrained config name or path if not the same as model_name", ) parser.add_argument( "--tokenizer_name", type=str, default=None, help="Pretrained tokenizer name or path if not the same as model_name", ) parser.add_argument( "--use_slow_tokenizer", action="store_true", help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).", ) parser.add_argument( "--per_device_train_batch_size", type=int, default=1, help="Batch size (per device) for the training dataloader.", ) parser.add_argument( "--per_device_eval_batch_size", type=int, default=1, help="Batch size (per device) for the evaluation dataloader.", ) parser.add_argument( "--learning_rate", type=float, default=5e-5, help="Initial learning rate (after the potential warmup period) to use.", ) parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.") parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.") parser.add_argument( "--max_train_steps", type=int, default=500, help="Total number of training steps to perform. If provided, overrides num_train_epochs.", ) parser.add_argument( "--gradient_accumulation_steps", type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.", ) parser.add_argument( "--lr_scheduler_type", type=SchedulerType, default="linear", help="The scheduler type to use.", choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"], ) parser.add_argument( "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler." ) parser.add_argument("--seed", type=int, default=100, help="A seed for reproducible training.") parser.add_argument( "--block_size", type=int, default=None, help=( "Optional input sequence length after tokenization. The training dataset will be truncated in block of" " this size for training. Default to the model max input length for single sentence inputs (take into" " account special tokens)." ), ) parser.add_argument( "--preprocessing_num_workers", type=int, default=None, help="The number of processes to use for the preprocessing.", ) parser.add_argument("--group_texts",default=False,help="Whether to group texts together when tokenizing") # TODO: Add -- to these 2: parser.add_argument("checkpoint_dir", type=str, default="/opt/ml/checkpoints") parser.add_argument("model_dir", type=str, default="/opt/ml/model") args,_ = parser.parse_known_args() # Sanity checks if args.train_file is None and args.validation_file is None: raise ValueError("Need training/validation file.") else: if args.train_file is not None: extension = args.train_file.split(".")[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or json file." if args.validation_file is not None: extension = args.validation_file.split(".")[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or json file." return args
[ "chris@fregly.com" ]
chris@fregly.com
87163c6d533958ad48dd7f695826f2d527faa969
e7ba8d27898fbd4fe396da19f82ab9317b3518cf
/goods/urls.py
8074753fd953bf5de7316547db5db75f237ac077
[]
no_license
LYblogs/fresh_shop
8c135d9f7c59800c1409375854e1941f24d5c60e
2eafcb355d049f47de2c45c68e733bf2759706b9
refs/heads/master
2020-04-17T18:00:19.775074
2019-04-04T04:10:18
2019-04-04T04:10:18
166,807,683
0
0
null
null
null
null
UTF-8
Python
false
false
340
py
from django.urls import path from goods import views urlpatterns = [ path('index/', views.index, name='index'), path('detail/<int:id>/', views.detail, name='detail'), # 查看更多 path('my_list/<int:id>/', views.my_list, name='my_list'), # 搜索 path('goods_search/', views.goods_search, name='goods_search') ]
[ "2271032145@qq.com" ]
2271032145@qq.com
522e61f62558044453ae1ab3f13b44f3bc194901
94e7c790d17ba08e8a2a74077dd8b75e7ac120b0
/chapter04/Exercise21_04.py
b3ce562574e71019474672c8bd23fea44b4b7cce
[]
no_license
lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python
9632e515428685dcaa7d057cf52f0e191e9f7ae0
d037475316e6c6b7c6a7a7023318ef4ab4ed3f8d
refs/heads/master
2020-09-02T09:04:44.990668
2018-10-20T00:50:12
2018-10-20T00:50:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,596
py
''' **4.21 (Science: day of the week) Zeller’s congruence is an algorithm developed by Christian Zeller to calculate the day of the week. The formula is where ■ h is the day of the week (0: Saturday, 1: Sunday, 2: Monday, 3: Tuesday, 4: Wednesday, 5: Thursday, 6: Friday). ■ q is the day of the month. ■ m is the month (3: March, 4: April, ..., 12: December). January and February are counted as months 13 and 14 of the previous year. ■ j is the century (i.e., ). ■ k is the year of the century (i.e., year % 100). Write a program that prompts the user to enter a year, month, and day of the month, and then it displays the name of the day of the week. /** * @author BASSAM FARAMAWI * @email tiodaronzi3@yahoo.com * @since 2018 */ ''' # Asking for entering year year = eval(input("Enter year: (e.g., 2012): ")) # Asking for entering m m = eval(input("Enter month: 1-12: ")) # Convert input from 1 to 13 and from 2 to 14 if m == 1: m = 13 year = year - 1 elif m == 2: m = 14 year = year - 1 # Asking for entering day of the m q = eval(input("Enter the day of the month: 1-31: ")) j = year // 100 # Compute the century k = year % 100 # Compute the year of the century # Calculate day of the week h = (q + 26 * (m + 1) / 10 + k + k / 4 + j / 4 + 5 * j) % 7 // 1 # Display the result print("Day of the week is", end=' ') if h == 0: print("Saturday") elif h == 1: print("Sunday") elif h == 2: print("Monday") elif h == 3: print("Tuesday") elif h == 4: print("Wednesday") elif h == 5: print("Thursday") elif h == 6: print("Friday")
[ "tiodaronzi3@yahoo.com" ]
tiodaronzi3@yahoo.com
4c5d6e989081cc3b302391a9eb76888559576fbe
30ab9750e6ca334941934d1727c85ad59e6b9c8a
/tests/santa/test_rule_engine.py
100c2b71cf7e159f9a5e58a444c40445b19c9fbf
[ "Apache-2.0" ]
permissive
ankurvaishley/zentral
57e7961db65278a0e614975e484927f0391eeadd
a54769f18305c3fc71bae678ed823524aaa8bb06
refs/heads/main
2023-05-31T02:56:40.309854
2021-07-01T07:51:31
2021-07-01T14:15:34
382,346,360
1
0
Apache-2.0
2021-07-02T12:55:47
2021-07-02T12:55:47
null
UTF-8
Python
false
false
23,871
py
import uuid from django.db.models import F from django.test import TestCase from django.utils.crypto import get_random_string from zentral.contrib.inventory.models import EnrollmentSecret, MetaBusinessUnit, Tag from zentral.contrib.santa.models import (Bundle, Configuration, EnrolledMachine, Enrollment, MachineRule, Rule, Target, translate_rule_policy) def new_sha256(): return get_random_string(length=64, allowed_chars='abcdef0123456789') class SantaRuleEngineTestCase(TestCase): @classmethod def setUpTestData(cls): cls.configuration = Configuration.objects.create(name=get_random_string(256), batch_size=5) cls.meta_business_unit = MetaBusinessUnit.objects.create(name=get_random_string(64)) cls.enrollment_secret = EnrollmentSecret.objects.create(meta_business_unit=cls.meta_business_unit) cls.enrollment = Enrollment.objects.create(configuration=cls.configuration, secret=cls.enrollment_secret) cls.machine_serial_number = get_random_string(64) cls.enrolled_machine = EnrolledMachine.objects.create(enrollment=cls.enrollment, hardware_uuid=uuid.uuid4(), serial_number=cls.machine_serial_number, client_mode=Configuration.MONITOR_MODE, santa_version="1.17") cls.machine_serial_number2 = get_random_string(64) cls.enrolled_machine2 = EnrolledMachine.objects.create(enrollment=cls.enrollment, hardware_uuid=uuid.uuid4(), serial_number=cls.machine_serial_number2, client_mode=Configuration.MONITOR_MODE, santa_version="1.17") def create_rule(self, target_type=Target.BINARY, policy=Rule.ALLOWLIST, configuration=None): target = Target.objects.create(type=target_type, sha256=new_sha256()) if configuration is None: configuration = self.configuration rule = Rule.objects.create(configuration=configuration, target=target, policy=policy) return target, rule def create_bundle_rule(self, policy=Rule.ALLOWLIST): bundle_target = Target.objects.create(type=Target.BUNDLE, sha256=new_sha256()) bundle = Bundle.objects.create( target=bundle_target, path=get_random_string(78), executable_rel_path=get_random_string(89), name=get_random_string(13), version=get_random_string(13), version_str=get_random_string(12), binary_count=3, ) for _ in range(bundle.binary_count): binary_target = Target.objects.create(type=Target.BINARY, sha256=new_sha256()) bundle.binary_targets.add(binary_target) bundle_rule = Rule.objects.create( configuration=self.configuration, target=bundle_target, policy=policy ) return bundle_target, bundle, bundle_rule def create_and_serialize_for_iter_rule(self, target_type=Target.BINARY, policy=Rule.ALLOWLIST, configuration=None): target, rule = self.create_rule(target_type, policy, configuration) result = { "target_id": target.pk, "policy": rule.policy, "rule_type": target.type, "sha256": target.sha256, "custom_msg": "", "version": rule.version, } return target, rule, result def create_and_serialize_rule(self, target_type=Target.BINARY, policy=Rule.ALLOWLIST, configuration=None): target, rule = self.create_rule(target_type, policy, configuration) serialized_rule = { "rule_type": target.type, "sha256": target.sha256, "policy": translate_rule_policy(rule.policy), } if rule.custom_msg: serialized_rule["custom_msg"] = rule.custom_msg return target, rule, serialized_rule def test_iter_new_rules(self): # create rule target, rule, result = self.create_and_serialize_for_iter_rule() self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [])), [result]) # sync rule machine_rule = MachineRule.objects.create( enrolled_machine=self.enrolled_machine, target=target, policy=rule.policy, version=rule.version, cursor=get_random_string(8), ) self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [])), []) # update rule rule.custom_msg = "New message" rule.version = F("version") + 1 rule.save() rule.refresh_from_db() result2 = result.copy() result2["custom_msg"] = rule.custom_msg result2["version"] = 2 self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [])), [result2]) # delete rule rule.delete() result3 = result.copy() result3["policy"] = 4 # REMOVE result3.pop("custom_msg", None) result3["version"] = 1 self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [])), [result3]) # sync rule machine_rule.delete() self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [])), []) def test_iter_new_rules_second_machine(self): # create rule target, rule, result = self.create_and_serialize_for_iter_rule() self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [])), [result]) # sync rule MachineRule.objects.create( enrolled_machine=self.enrolled_machine, target=target, policy=rule.policy, version=rule.version, cursor=get_random_string(8), ) self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine2, [])), [result]) def test_iter_serial_number_new_rules(self): target, rule, result = self.create_and_serialize_for_iter_rule() rule.serial_numbers = [get_random_string(13)] rule.save() self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [])), []) rule.serial_numbers.append(self.enrolled_machine.serial_number) rule.save() self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [])), [result]) def test_iter_primary_user_new_rules(self): target, rule, result = self.create_and_serialize_for_iter_rule() rule.primary_users = [get_random_string(14)] rule.save() self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [])), []) primary_user = get_random_string(15) rule.primary_users.append(primary_user) rule.save() self.enrolled_machine.primary_user = primary_user self.enrolled_machine.save() self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [])), [result]) def test_iter_tag_new_rules(self): target, rule, result = self.create_and_serialize_for_iter_rule() tags = [Tag.objects.create(name=get_random_string(32)) for _ in range(3)] rule.tags.set(tags) self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [])), []) self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [tags[0].pk])), [result]) def test_iter_bundle_new_rules(self): bundle_target, bundle, bundle_rule = self.create_bundle_rule() results = [{ "target_id": binary_target.pk, "policy": bundle_rule.policy, "rule_type": binary_target.type, "sha256": binary_target.sha256, "custom_msg": "", "version": bundle_rule.version, "file_bundle_hash": bundle_target.sha256, "file_bundle_binary_count": bundle.binary_count, } for binary_target in bundle.binary_targets.all().order_by("sha256")] self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [])), results) # simulate acknowleged sync for binary_target in bundle.binary_targets.all(): MachineRule.objects.create( enrolled_machine=self.enrolled_machine, target=binary_target, policy=bundle_rule.policy, version=bundle_rule.version, ) self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [])), []) # delete the rule bundle_rule.delete() new_results = [] for r in results: nr = r.copy() nr["policy"] = MachineRule.REMOVE nr.pop("custom_msg") nr.pop("file_bundle_hash") nr.pop("file_bundle_binary_count") new_results.append(nr) self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [])), new_results) def test_configuration_leakage(self): configuration2 = Configuration.objects.create(name=get_random_string(256)) target, rule, _ = self.create_and_serialize_for_iter_rule(configuration=configuration2) self.assertEqual(list(MachineRule.objects._iter_new_rules(self.enrolled_machine, [])), []) def test_one_next_rule(self): target, rule, serialized_rule = self.create_and_serialize_rule() for _ in range(2): rule_batch, response_cursor = MachineRule.objects.get_next_rule_batch(self.enrolled_machine, []) self.assertIsNotNone(response_cursor) self.assertEqual(rule_batch, [serialized_rule]) machine_rule_qs = self.enrolled_machine.machinerule_set.all() self.assertEqual(machine_rule_qs.count(), 1) machine_rule = machine_rule_qs.first() self.assertEqual(machine_rule.target, target) self.assertEqual(machine_rule.policy, rule.policy) self.assertEqual(machine_rule.version, rule.version) self.assertEqual(machine_rule.cursor, response_cursor) def test_next_rule_batch_pagination(self): serialized_rules = [] for _ in range(6): _, _, serialized_rule = self.create_and_serialize_rule() serialized_rules.append(serialized_rule) serialized_rules.sort(key=lambda r: r["sha256"]) i = 0 response_cursor = None for batch_len in (5, 1): rule_batch, response_cursor = MachineRule.objects.get_next_rule_batch( self.enrolled_machine, [], response_cursor ) self.assertIsNotNone(response_cursor) self.assertEqual(MachineRule.objects.filter(enrolled_machine=self.enrolled_machine, cursor=response_cursor).count(), batch_len) self.assertEqual(rule_batch, serialized_rules[i: i + batch_len]) i += batch_len machine_rule_qs = self.enrolled_machine.machinerule_set.all() self.assertEqual(machine_rule_qs.count(), 6) self.assertEqual(machine_rule_qs.filter(cursor__isnull=True).count(), 5) rule_batch, response_cursor = MachineRule.objects.get_next_rule_batch( self.enrolled_machine, [], response_cursor ) self.assertEqual(len(rule_batch), 0) self.assertIsNone(response_cursor) self.assertEqual(machine_rule_qs.filter(cursor__isnull=True).count(), 6) def test_lost_response_batch_pagination(self): serialized_rules = [] for _ in range(11): _, _, serialized_rule = self.create_and_serialize_rule() serialized_rules.append(serialized_rule) serialized_rules.sort(key=lambda r: r["sha256"]) response_cursor = None machine_rule_qs = self.enrolled_machine.machinerule_set.all() i = 0 # first client request, first 5 rules batch_len = 5 rule_batch, response_cursor1 = MachineRule.objects.get_next_rule_batch( self.enrolled_machine, [], response_cursor ) self.assertIsNotNone(response_cursor1) self.assertEqual(machine_rule_qs.filter(cursor__isnull=True).count(), 0) self.assertEqual(machine_rule_qs.filter(cursor=response_cursor1).count(), batch_len) self.assertEqual(machine_rule_qs.filter(cursor__isnull=False).exclude(cursor=response_cursor1).count(), 0) self.assertEqual(rule_batch, serialized_rules[i: i + batch_len]) i += batch_len # second client request, next 5 rules rule_batch, response_cursor2 = MachineRule.objects.get_next_rule_batch( self.enrolled_machine, [], response_cursor1 ) self.assertIsNotNone(response_cursor2) self.assertEqual(machine_rule_qs.filter(cursor__isnull=True).count(), batch_len) self.assertEqual(machine_rule_qs.filter(cursor=response_cursor2).count(), batch_len) self.assertEqual(machine_rule_qs.filter(cursor__isnull=False).exclude(cursor=response_cursor2).count(), 0) self.assertEqual(rule_batch, serialized_rules[i: i + batch_len]) i += batch_len # third client request, with first cursor. # the client has never received a response for the second request, and is retrying it. i -= batch_len rule_batch, response_cursor3 = MachineRule.objects.get_next_rule_batch( self.enrolled_machine, [], response_cursor1 ) self.assertIsNotNone(response_cursor3) self.assertEqual(machine_rule_qs.filter(cursor__isnull=True).count(), batch_len) self.assertEqual(machine_rule_qs.filter(cursor=response_cursor3).count(), batch_len) self.assertEqual(machine_rule_qs.filter(cursor__isnull=False).exclude(cursor=response_cursor3).count(), 0) self.assertEqual(rule_batch, serialized_rules[i: i + batch_len]) i += batch_len # the client received the last batch and makes another request batch_len = 1 rule_batch, response_cursor4 = MachineRule.objects.get_next_rule_batch( self.enrolled_machine, [], response_cursor3 ) self.assertIsNotNone(response_cursor4) self.assertEqual(machine_rule_qs.filter(cursor__isnull=True).count(), 10) self.assertEqual(machine_rule_qs.filter(cursor=response_cursor4).count(), batch_len) self.assertEqual(machine_rule_qs.filter(cursor__isnull=False).exclude(cursor=response_cursor4).count(), 0) self.assertEqual(rule_batch, serialized_rules[i: i + batch_len]) i += batch_len # last batch rule_batch, response_cursor5 = MachineRule.objects.get_next_rule_batch( self.enrolled_machine, [], response_cursor4 ) self.assertIsNone(response_cursor5) self.assertEqual(machine_rule_qs.filter(cursor__isnull=True).count(), 11) self.assertEqual(machine_rule_qs.filter(cursor__isnull=False).count(), 0) self.assertEqual(rule_batch, []) def test_reset_batch_pagination(self): serialized_rules = [] for _ in range(6): _, _, serialized_rule = self.create_and_serialize_rule() serialized_rules.append(serialized_rule) serialized_rules.sort(key=lambda r: r["sha256"]) machine_rule_qs = self.enrolled_machine.machinerule_set.all() # first 2 requests OK i = 0 response_cursor = None for batch_len in (5, 1): rule_batch, response_cursor = MachineRule.objects.get_next_rule_batch( self.enrolled_machine, [], response_cursor ) self.assertIsNotNone(response_cursor) self.assertEqual(machine_rule_qs.filter(cursor=response_cursor).count(), batch_len) self.assertEqual(rule_batch, serialized_rules[i: i + batch_len]) i += batch_len self.assertEqual(machine_rule_qs.count(), 6) self.assertEqual(machine_rule_qs.filter(cursor__isnull=True).count(), 5) # last batch, never acknowleged, the client keeps making new requests without cursor # and getting the last unacknowlegded rule for i in range(2): rule_batch, response_cursor_post_reset = MachineRule.objects.get_next_rule_batch( self.enrolled_machine, [] ) self.assertIsNotNone(response_cursor_post_reset) self.assertEqual(rule_batch, [serialized_rules[-1]]) self.assertEqual(machine_rule_qs.count(), 6) self.assertEqual(machine_rule_qs.filter(cursor__isnull=True).count(), 5) self.assertEqual(machine_rule_qs.filter(cursor=response_cursor_post_reset).count(), 1) # the client acknowleges the last rule rule_batch, final_response_cursor = MachineRule.objects.get_next_rule_batch( self.enrolled_machine, [], response_cursor_post_reset ) self.assertEqual(machine_rule_qs.count(), 6) self.assertEqual(machine_rule_qs.filter(cursor__isnull=True).count(), 6) self.assertEqual(rule_batch, []) def test_updated_rule(self): target, rule, serialized_rule = self.create_and_serialize_rule() _, response_cursor = MachineRule.objects.get_next_rule_batch(self.enrolled_machine, []) MachineRule.objects.get_next_rule_batch(self.enrolled_machine, [], response_cursor) rule.custom_msg = "YOLO" rule.version = F("version") + 1 rule.save() serialized_rule["custom_msg"] = rule.custom_msg rule_batch, response_cursor = MachineRule.objects.get_next_rule_batch(self.enrolled_machine, []) self.assertIsNotNone(response_cursor) self.assertEqual(rule_batch, [serialized_rule]) machine_rule_qs = self.enrolled_machine.machinerule_set.all() self.assertEqual(machine_rule_qs.count(), 1) machine_rule = machine_rule_qs.first() self.assertEqual(machine_rule.target, target) self.assertEqual(machine_rule.policy, rule.policy) self.assertEqual(machine_rule.version, 2) MachineRule.objects.get_next_rule_batch(self.enrolled_machine, [], response_cursor) self.assertEqual(machine_rule_qs.count(), 1) self.assertEqual(machine_rule.pk, machine_rule_qs.first().pk) machine_rule.refresh_from_db() self.assertIsNone(machine_rule.cursor) rule_batch2, response_cursor = MachineRule.objects.get_next_rule_batch(self.enrolled_machine, []) self.assertEqual(rule_batch2, []) self.assertEqual(response_cursor, None) def test_deleted_rule(self): target, rule, serialized_rule = self.create_and_serialize_rule() _, response_cursor = MachineRule.objects.get_next_rule_batch(self.enrolled_machine, []) MachineRule.objects.get_next_rule_batch(self.enrolled_machine, [], response_cursor) rule.delete() serialized_rule.pop("custom_msg", None) serialized_rule["policy"] = "REMOVE" response_cursor = None for i in range(2): rule_batch, response_cursor = MachineRule.objects.get_next_rule_batch(self.enrolled_machine, []) self.enrolled_machine.refresh_from_db() self.assertIsNotNone(response_cursor) self.assertEqual(rule_batch, [serialized_rule]) machine_rule_qs = self.enrolled_machine.machinerule_set.all() self.assertEqual(machine_rule_qs.count(), 1) machine_rule = machine_rule_qs.first() self.assertEqual(machine_rule.target, target) self.assertEqual(machine_rule.policy, MachineRule.REMOVE) self.assertEqual(machine_rule.cursor, response_cursor) MachineRule.objects.get_next_rule_batch(self.enrolled_machine, [], response_cursor) self.assertEqual(machine_rule_qs.count(), 0) def test_bundle_rules(self): # all bundle binary rules with extra attributes bundle_target, bundle, bundle_rule = self.create_bundle_rule() serialized_rules = [{ "policy": translate_rule_policy(bundle_rule.policy), "rule_type": binary_target.type, "sha256": binary_target.sha256, "file_bundle_hash": bundle_target.sha256, "file_bundle_binary_count": bundle.binary_count, } for binary_target in bundle.binary_targets.all().order_by("sha256")] rule_batch, response_cursor = MachineRule.objects.get_next_rule_batch(self.enrolled_machine, []) self.assertEqual(rule_batch, serialized_rules) # noop MachineRule.objects.get_next_rule_batch(self.enrolled_machine, [], response_cursor) rule_batch, response_cursor = MachineRule.objects.get_next_rule_batch(self.enrolled_machine, []) self.assertEqual(rule_batch, []) self.assertIsNone(response_cursor) # delete rule bundle_rule.delete() serialized_remove_rules = [] # all bundle binary remove rules without extra attributes for sr in serialized_rules: srr = sr.copy() srr["policy"] = "REMOVE" srr.pop("file_bundle_hash") srr.pop("file_bundle_binary_count") serialized_remove_rules.append(srr) rule_batch, response_cursor = MachineRule.objects.get_next_rule_batch(self.enrolled_machine, []) self.assertEqual(rule_batch, serialized_remove_rules) # noop MachineRule.objects.get_next_rule_batch(self.enrolled_machine, [], response_cursor) rule_batch, response_cursor = MachineRule.objects.get_next_rule_batch(self.enrolled_machine, []) self.assertEqual(rule_batch, []) self.assertIsNone(response_cursor) def test_scoped_rule(self): # rule without restrictions target, rule, serialized_rule = self.create_and_serialize_rule() _, response_cursor = MachineRule.objects.get_next_rule_batch(self.enrolled_machine, []) MachineRule.objects.get_next_rule_batch(self.enrolled_machine, [], response_cursor) # scope rule with some tags tags = [Tag.objects.create(name=get_random_string(32)) for _ in range(3)] rule.tags.set(tags) # rule not in scope anymore, needs to be removed rule_batch, response_cursor = MachineRule.objects.get_next_rule_batch(self.enrolled_machine, []) serialized_remove_rule = serialized_rule.copy() serialized_remove_rule.pop("custom_msg", None) serialized_remove_rule["policy"] = "REMOVE" self.assertEqual(rule_batch, [serialized_remove_rule]) MachineRule.objects.get_next_rule_batch(self.enrolled_machine, [], response_cursor) # rule removed, noop rule_batch, _ = MachineRule.objects.get_next_rule_batch(self.enrolled_machine, []) self.assertEqual(rule_batch, []) # machine tagged, rule needs to be added rule_batch, response_cursor = MachineRule.objects.get_next_rule_batch(self.enrolled_machine, [tags[0].pk]) self.assertEqual(rule_batch, [serialized_rule]) MachineRule.objects.get_next_rule_batch(self.enrolled_machine, [tags[0].pk], response_cursor) # rule added, noop rule_batch, _ = MachineRule.objects.get_next_rule_batch(self.enrolled_machine, [tags[0].pk]) self.assertEqual(rule_batch, [])
[ "eric.falconnier@112hz.com" ]
eric.falconnier@112hz.com
a10b2a412fcd9de3437f75d4632df9421ff257d4
ba2717fd81a20e7479ea710153a3a9cea5fcbed5
/societegeneralelu/spiders/spider.py
0e1468bde2a01c9e5b3ec953701f6ae38f5f08b8
[]
no_license
hristo-grudev/societegeneralelu
52d30f1a942945539ce29d7eee952f69d476fef9
166ad7ae8425ffbed5fee2f7d75c7a1dceb0a469
refs/heads/main
2023-03-25T16:18:04.997663
2021-03-23T09:13:25
2021-03-23T09:13:25
350,647,656
0
0
null
null
null
null
UTF-8
Python
false
false
2,946
py
import scrapy from scrapy.loader import ItemLoader from ..items import SocietegeneraleluItem from itemloaders.processors import TakeFirst import requests url = "https://www.societegenerale.lu/fr/societe-generale-luxembourg/communiques-presse-actualites/" base_payload = "tx_bisgsummary_pi2%5Bpage%5D={}&tx_bisgsummary_pi2%5Btext%5D=&tx_bisgsummary_pi2%5Byear%5D=0&tx_bisgsummary_pi2%5BremoveWrapperToListing%5D=true&no_cache=true&tx_bisgsummary_pi2%5BajaxCall%5D=true&tx_bisgsummary_pi2%5BajaxMethod%5D=refreshResults&tx_bisgsummary_pi2%5BforceConf%5D=&tx_bisgsummary_pi2%5BidContent%5D=13134" headers = { 'authority': 'www.societegenerale.lu', 'pragma': 'no-cache', 'cache-control': 'no-cache', 'sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"', 'accept': 'text/html, */*; q=0.01', 'x-requested-with': 'XMLHttpRequest', 'sec-ch-ua-mobile': '?0', 'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36', 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 'origin': 'https://www.societegenerale.lu', 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'https://www.societegenerale.lu/fr/societe-generale-luxembourg/communiques-presse-actualites/', 'accept-language': 'en-US,en;q=0.9,bg;q=0.8', 'cookie': 'civicAllowCookies=yes; _ga=GA1.2.781032923.1616422955; _gid=GA1.2.1248201824.1616422955; _pk_ses.186.cb62=1; _pk_id.186.cb62=be2f692b2d249855.1616422955.1.1616422993.1616422955.; SERVERID=f0' } class SocietegeneraleluSpider(scrapy.Spider): name = 'societegeneralelu' start_urls = ['https://www.societegenerale.lu/fr/societe-generale-luxembourg/communiques-presse-actualites/'] page = 1 def parse(self, response): payload = base_payload.format(self.page) data = requests.request("POST", url, headers=headers, data=payload) raw_data = scrapy.Selector(text=data.text) post_links = raw_data.xpath('//div[contains(@id, "card2")]/@data-ref').getall() for post in post_links: link = 'https://www.societegenerale.lu/fr/type/1234/ajaxsid/' + post yield response.follow(link, self.parse_post) if post_links: self.page += 1 yield response.follow(response.url, self.parse, dont_filter=True) def parse_post(self, response): title = response.xpath('//h1/text()').get() description = response.xpath('//div[@class="intro" or @class="sgnews_single_content"]//text()[normalize-space()]').getall() description = [p.strip() for p in description] description = ' '.join(description).strip() date = response.xpath('//div[@class="sgnews_single_date"]/text()').get() item = ItemLoader(item=SocietegeneraleluItem(), response=response) item.default_output_processor = TakeFirst() item.add_value('title', title) item.add_value('description', description) item.add_value('date', date) return item.load_item()
[ "hr.grudev@gmail.com" ]
hr.grudev@gmail.com
c120e49f4f9c35c388c6951b0c0ce3df24e343ce
3d16bcf91c546dfc638bf9e48d7690e8aed37ee2
/tests/Cpl/Io/File/_0test/ansi/linux/gcc/tca.py
6128bb6427c8ac96434fb081af2c6a6d7466e4b4
[]
no_license
johnttaylor/colony.core
7c3aa43abdd564689e1540795b8044228b97271c
e00902d33c9224a34e9f68edb02c18eb9571b09f
refs/heads/master
2023-07-24T08:34:04.956247
2023-06-20T00:02:55
2023-06-20T00:02:55
31,176,673
2
2
null
2023-06-17T21:56:08
2015-02-22T19:38:07
C
UTF-8
Python
false
false
378
py
#!/usr/bin/python3 """Invokes NQBP's tca_base.py script""" import os import sys # Make sure the environment is properly set NQBP_BIN = os.environ.get('NQBP_BIN') if ( NQBP_BIN == None ): sys.exit( "ERROR: The environment variable NQBP_BIN is not set!" ) sys.path.append( NQBP_BIN ) # Find the Package & Workspace root from other import tca_base tca_base.run( sys.argv )
[ "john.t.taylor@gmail.com" ]
john.t.taylor@gmail.com
0d9b15ea3c7bec732cb0284bec313aeb007f2744
30fe7671b60825a909428a30e3793bdf16eaaf29
/.metadata/.plugins/org.eclipse.core.resources/.history/7b/b0003d536ee000161581bdbc63c32924
8542d9d0d0a25cefdc1e28b41a9026d4a97d1dc3
[]
no_license
abigdream84/PythonStudy
0fc7a3b6b4a03a293b850d0ed12d5472483c4fb1
059274d3ba6f34b62ff111cda3fb263bd6ca8bcb
refs/heads/master
2021-01-13T04:42:04.306730
2017-03-03T14:54:16
2017-03-03T14:54:16
79,123,274
0
0
null
null
null
null
UTF-8
Python
false
false
406
#!/usr/bin/env python #coding:UTF-8 from ebank.ui.ui import ui from ebank.model.account import account def main(): while True: ui_handle = ui() ui_handle.welcome() user = ui_handle.login() user_id = user[0] print(type(user_id)) user_pwd = user[1] print(account.chkUser(user_id)) if __name__ == '__main__': main()
[ "abigdream@hotmail.com" ]
abigdream@hotmail.com
0c3795f1b60250200e5641ae38455ed69ba6b028
ad13583673551857615498b9605d9dcab63bb2c3
/output/instances/nistData/list/boolean/Schema+Instance/NISTXML-SV-IV-list-boolean-minLength-1-5.py
08d968ec0e7c26b5c3c3a9b5afb4d3332bc7d2c7
[ "MIT" ]
permissive
tefra/xsdata-w3c-tests
397180205a735b06170aa188f1f39451d2089815
081d0908382a0e0b29c8ee9caca6f1c0e36dd6db
refs/heads/main
2023-08-03T04:25:37.841917
2023-07-29T17:10:13
2023-07-30T12:11:13
239,622,251
2
0
MIT
2023-07-25T14:19:04
2020-02-10T21:59:47
Python
UTF-8
Python
false
false
344
py
from output.models.nist_data.list_pkg.boolean.schema_instance.nistschema_sv_iv_list_boolean_min_length_1_xsd.nistschema_sv_iv_list_boolean_min_length_1 import NistschemaSvIvListBooleanMinLength1 obj = NistschemaSvIvListBooleanMinLength1( value=[ True, True, True, True, True, True, ] )
[ "tsoulloftas@gmail.com" ]
tsoulloftas@gmail.com
bf24287583961e4c538864c3af193fc013674e75
facbdbdadacd23f6c83d266116dc14744741070f
/Core_Python/Day-3/18.py
f90ce556bdf1517938aadd4db1dfb9a62703a507
[]
no_license
Yogesh-Singh-Gadwal/YSG_Python
51b6b53fe34567bf066b6e487c00da766b47ac6b
f0d6841e1f92d1d2b27d8ecdd332d40b49a5ca69
refs/heads/master
2023-06-06T04:40:12.004713
2021-07-06T19:59:26
2021-07-06T19:59:26
292,482,586
1
0
null
null
null
null
UTF-8
Python
false
false
84
py
# conversion v1 = float(input('Enter user Salary : ')) print(type(v1))
[ "noreply@github.com" ]
Yogesh-Singh-Gadwal.noreply@github.com
b53833d0fd7b2ce36c12b4d5ff05d56d55e5b29b
b08d42933ac06045905d7c005ca9c114ed3aecc0
/src/coefSubset/evaluate/ranks/tenPercent/rank_4k5a_D.py
1d00ee9ff3c2d98200407082e30375e8ad9f8b7f
[]
no_license
TanemuraKiyoto/PPI-native-detection-via-LR
d148d53f5eb60a4dda5318b371a3048e3f662725
897e7188b0da94e87126a4acc0c9a6ff44a64574
refs/heads/master
2022-12-05T11:59:01.014309
2020-08-10T00:41:17
2020-08-10T00:41:17
225,272,083
1
0
null
null
null
null
UTF-8
Python
false
false
3,386
py
# 9 July 2019 # Kiyoto Aramis Tanemura # Several metrics are used to assess the performance of the trained RF model, notably native ranking. This script returns a ranking of the native protein-protein complex among a decoy set. For convenience, I will define as a function and will call in a general performance assessment script. # Modified 11 July 2019 by Kiyoto Aramis Tanemura. To parallelize the process, I will replace the for loop for the testFileList to a multiprocessing pool. # Modified 9 September 2019 by Kiyoto Aramis Tanemura. I will use the function to perform the calculation on one CSV file only. Thus instead of a function to import in other scripts, they will be individual jobs parallelized as individual jobs in the queue. import os import pandas as pd import numpy as np import pickle os.chdir('/mnt/scratch/tanemur1/') # Read the model and trainFile testFile = '4k5a.csv' identifier = 'D' coefFrac = 0.1 testFilePath = '/mnt/scratch/tanemur1/CASF-PPI/nonb_descriptors/complete/' modelPath = '/mnt/home/tanemur1/6May2019/2019-11-11/results/coefSubset/tenPercent/' outputPath = '/mnt/home/tanemur1/6May2019/2019-11-11/results/coefSubset/evaluate/tenPercent/ranks/' pdbID = testFile[:4] with open(modelPath + 'model' + identifier + '.pkl', 'rb') as f: clf = pickle.load(f) result = pd.DataFrame() scoreList = [] df1 = pd.read_csv(testFilePath + testFile) dropList = ['Unnamed: 0', 'Unnamed: 0.1', 'ref'] df1 = df1.drop(dropList, axis = 1) df1 = df1.set_index('Pair_name') df1 = pd.DataFrame(df1.values.T, columns = df1.index, index = df1.columns) df1.fillna(0.0, inplace = True) #df1 = df1.reindex(sorted(df1.columns), axis = 1) # Keep coefficients within the given fraction when ordered by decreasing order of coefficient magnitude coefs = pd.read_csv('/mnt/home/tanemur1/6May2019/2019-11-11/results/medianCoefs.csv', index_col = 0, header = None, names = ['coefficients']) coefs['absVal'] = np.abs(coefs['coefficients']) coefs.sort_values(by = 'absVal', ascending = False, inplace = True) coefs = coefs[:int(14028 * coefFrac + 0.5)] keepList = list(coefs.index) del coefs df1 = df1[keepList] df1 = df1.reindex(sorted(df1.columns), axis = 1) with open(modelPath + 'standardScaler' + identifier + '.pkl', 'rb') as g: scaler = pickle.load(g) for i in range(len(df1)): # subtract from one row each row of the dataframe, then remove the trivial row[[i]] - row[[i]]. Also some input files have 'class' column. This is erroneous and is removed. df2 = pd.DataFrame(df1.iloc[[i]].values - df1.values, index = df1.index, columns = df1.columns) df2 = df2.drop(df1.iloc[[i]].index[0], axis = 0) # Standardize inut DF using the standard scaler used for training data. df2 = scaler.transform(df2) # Predict class of each comparison descriptor and sum the classes to obtain score. Higher score corresponds to more native-like complex predictions = clf.predict(df2) score = sum(predictions) scoreList.append(score) # Make a new DataFrame to store the score and corresponding descriptorID. Add rank as column. Note: lower rank corresponds to more native-like complex result = pd.DataFrame(data = {'score': scoreList}, index = df1.index.tolist()).sort_values(by = 'score', ascending = False) result['rank'] = range(1, len(result) + 1) with open(outputPath + pdbID + identifier + '.csv', 'w') as h: result.to_csv(h)
[ "tanemur1@msu.edu" ]
tanemur1@msu.edu
d34e775ac8013ebec76c1305b47bb894ae4f6049
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2645486_0/Python/plam/b.py
cdc42c6429eb2ac1a36ffb3671d185e9df7da650
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
762
py
#!/usr/bin/python import sys data = file( sys.argv[1] ).read().splitlines() l = data.pop( 0 ) N = int(l) CACHE = {} def MAX( i, CURE ): max = 0 if i >= N: return 0 if CURE <= 0: return 0 if CURE > E: CURE = E for e in range(0, CURE+1): if CURE-e+R < 0: continue m = V[i]*e + MAX(i+1,CURE-e+R) if m > max: # print 'max is',i,e,m max = m return max for CASE in range(1,N+1): print 'Case #%d:' % CASE, l = data.pop( 0 ) E, R, N = l.split(' ') E = int(E) R = int(R) N = int(N) # print E, R, N l = data.pop( 0 ) VT = l.split(' ') V = [] for v in VT: V.append( int(v)) # print V ans = MAX(0,E) print ans
[ "eewestman@gmail.com" ]
eewestman@gmail.com
310da1a7f93ce7516e25d63143c848e4ff876c3d
199c19abc71108b4507d1689537a632ccb1a76f9
/session4/ss4_intro.py
69e34330da24254fe7ef169654a3e559bcac2aef
[]
no_license
VetKira/daotrongcuong-fundamentals-c4e23
15d1932c95574462540088b3abba7fed6631c03f
ea1da093146ef5c69640bb57cb13aee7f568cfcd
refs/heads/master
2020-04-02T17:18:49.342412
2018-11-01T13:29:34
2018-11-01T13:29:34
154,652,387
0
0
null
null
null
null
UTF-8
Python
false
false
681
py
# person = ["Kira","Hai Phong","WRU",22,4,257,False] # person={} # neu co ngoac{} python se hieu day la dictionary # print(person) # print(type(person)) # person={ # "name": "kira" #key:value # } # print(person) # print(type(person)) person={ "name":"kira", "place":"hai phong", "age": 22, } # print(person) # person["girlfriend"] = 257 #[key]=value # print(person) # print(person["name"]) # hoac dat i = " name " r thay i vao # key = " name" # if key in person: # print(person[key]) # else: # print("not found") #update : # person["age"] = 23 # print(person) #xoa : del person["age"] print(person) #list thi theo index , con diction thi theo key
[ "doanxem.ml@gmail.com" ]
doanxem.ml@gmail.com
ed838a8ef2fb1149ebf50badc8a41115bf5450e8
1f84e6428dea4a17a8e2df15fa6f1ec3404ec0a5
/test/integrationTests.py
8bf2cc868e0ce631d3ce7cacdd80667d5ac2fa4e
[]
no_license
hejibo/pythonTranslator
cf332ee8ff29300fada215fe5e794f8579516fb1
c5586d6ea186311a930507f0d827069b9fef805f
refs/heads/master
2020-12-24T10:24:22.002897
2013-03-23T16:59:57
2013-03-23T16:59:57
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,989
py
#!/usr/bin/env python # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # author: terry.yinzhe@gmail.com # import unittest from subprocess import Popen, PIPE import os import dub.resource as resource from .testData import typeOFTranslatedLineInList, WELCOME import sys decode = [lambda x:x, lambda x:x.decode('UTF-8')][sys.version_info.major>2] class testDubForPythonInInteractiveMode(unittest.TestCase): def setUp(self): env = os.environ.copy() env["PYTHONSTARTUP"] = "dubShell.py" self.shell = Popen("python -i".split(), stdin = PIPE, stdout = PIPE, stderr = PIPE, env = env) def testShouldSeeWelcomeInformation(self): stdout, stderr = self.shell.communicate("") self.assertIn(WELCOME + resource.VERSION, decode(stderr)) self.assertEqual('', decode(stdout)) def testShouldSeeTranslatedSyntaxError(self): stdout, stderr = self.shell.communicate("1+\n".encode("UTF-8")) self.assertTrue(typeOFTranslatedLineInList('SyntaxError', decode(stderr).splitlines())) self.assertEqual('', decode(stdout)) def testShouldNotSeeTranslatedSyntaxErrorWhenNoInput(self): stdout, stderr = self.shell.communicate("") self.assertFalse(typeOFTranslatedLineInList('SyntaxError', decode(stderr).splitlines())) self.assertEqual('', decode(stdout)) class testDubForPythonInProgramMode(unittest.TestCase): def testShouldSeeNoErrorWhenEverythingIsOK(self): self.shell = Popen("python example.py".split(), stdin = PIPE, stdout = PIPE, stderr = PIPE) stdout, stderr = self.shell.communicate("") self.assertEqual([], decode(stderr).splitlines()) def testShouldSeeTranslationOfTheError(self): self.shell = Popen("python example.py 1+\n".split(), stdin = PIPE, stdout = PIPE, stderr = PIPE) stdout, stderr = self.shell.communicate("") self.assertTrue(typeOFTranslatedLineInList('SyntaxError', decode(stderr).splitlines())) class testDubForProgramUsingTraceback(unittest.TestCase): def testShouldGetDualLanguageTraceback(self): import dub import traceback import sys try: eval("1+\n") except: etype, value, tb = sys.exc_info() traceList = traceback.format_exception(etype, value, tb) self.assertTrue(typeOFTranslatedLineInList('SyntaxError', traceList)) if __name__ == '__main__': unittest.main()
[ "terry@odd-e.com" ]
terry@odd-e.com
2087b9e600595db1a0b6a7ba440d1bbb94384897
886f8474f63e5cc98378f5194ae396e9860918f3
/translatie/ssh.py
69d0322c935ef94c12a40836115b7ebd4a353153
[]
no_license
flybetter/Translate
9b4b1d9ceaefe243997d31bff1dfee3944b4d394
fb0adeda489ff5dd6785d0625e7b246828d25445
refs/heads/master
2021-07-12T17:30:53.776441
2017-10-15T00:57:13
2017-10-15T00:57:13
106,973,657
0
0
null
null
null
null
UTF-8
Python
false
false
701
py
#!/usr/bin/python # -*- coding: utf-8 -*- """ @project= Translate @file= ssh @author= wubingyu @create_time= 2017/10/8 下午7:38 """ from pexpect import pxssh import re def send_command(s, cmd): s.sendline(cmd) s.prompt() # print s.before return s.before def connect(host, user, password): try: s = pxssh.pxssh() s.login(host, user, password) return s except: print "error" exit(0) def main(): s = connect("10.245.250.38", "root", "cmsroot") result = send_command(s, "ps -ef|grep java") line = result.split('\r')[4] print line print re.findall(r"\S\w*/\w*/java", line) if __name__ == '__main__': main()
[ "flybetter@163.com" ]
flybetter@163.com
15b6788139fa3b39fcd6773b7d7961abeba4492e
64d16fbfaa6061add61ba82ec7428fde79ce07cb
/devel/lib/python2.7/dist-packages/uuv_thruster_manager/srv/_GetThrusterManagerConfig.py
1866b2d8e69059377d96eed78d1cb656e74d39b5
[]
no_license
bnb15/clearpath_ros
519da6013eff041896695416a5411b1ba07b1532
2ec03826bf44e17def364784636838a1b3fc64fe
refs/heads/master
2020-05-31T21:35:26.359260
2019-06-06T02:15:56
2019-06-06T02:15:56
190,498,514
0
1
null
null
null
null
UTF-8
Python
false
false
14,031
py
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from uuv_thruster_manager/GetThrusterManagerConfigRequest.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class GetThrusterManagerConfigRequest(genpy.Message): _md5sum = "d41d8cd98f00b204e9800998ecf8427e" _type = "uuv_thruster_manager/GetThrusterManagerConfigRequest" _has_header = False #flag to mark the presence of a Header object _full_text = """ """ __slots__ = [] _slot_types = [] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(GetThrusterManagerConfigRequest, self).__init__(*args, **kwds) def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: pass except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ try: end = 0 return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: pass except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ try: end = 0 return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I(): global _struct_I return _struct_I # This Python file uses the following encoding: utf-8 """autogenerated by genpy from uuv_thruster_manager/GetThrusterManagerConfigResponse.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class GetThrusterManagerConfigResponse(genpy.Message): _md5sum = "b5a2d9d3bb510dd91fdb03f95e95b8de" _type = "uuv_thruster_manager/GetThrusterManagerConfigResponse" _has_header = False #flag to mark the presence of a Header object _full_text = """string tf_prefix string base_link string thruster_frame_base string thruster_topic_prefix string thruster_topic_suffix float64 timeout float64 max_thrust int32 n_thrusters float64[] allocation_matrix """ __slots__ = ['tf_prefix','base_link','thruster_frame_base','thruster_topic_prefix','thruster_topic_suffix','timeout','max_thrust','n_thrusters','allocation_matrix'] _slot_types = ['string','string','string','string','string','float64','float64','int32','float64[]'] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: tf_prefix,base_link,thruster_frame_base,thruster_topic_prefix,thruster_topic_suffix,timeout,max_thrust,n_thrusters,allocation_matrix :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(GetThrusterManagerConfigResponse, self).__init__(*args, **kwds) #message fields cannot be None, assign default values for those that are if self.tf_prefix is None: self.tf_prefix = '' if self.base_link is None: self.base_link = '' if self.thruster_frame_base is None: self.thruster_frame_base = '' if self.thruster_topic_prefix is None: self.thruster_topic_prefix = '' if self.thruster_topic_suffix is None: self.thruster_topic_suffix = '' if self.timeout is None: self.timeout = 0. if self.max_thrust is None: self.max_thrust = 0. if self.n_thrusters is None: self.n_thrusters = 0 if self.allocation_matrix is None: self.allocation_matrix = [] else: self.tf_prefix = '' self.base_link = '' self.thruster_frame_base = '' self.thruster_topic_prefix = '' self.thruster_topic_suffix = '' self.timeout = 0. self.max_thrust = 0. self.n_thrusters = 0 self.allocation_matrix = [] def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: _x = self.tf_prefix length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self.base_link length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self.thruster_frame_base length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self.thruster_topic_prefix length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self.thruster_topic_suffix length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self buff.write(_get_struct_2di().pack(_x.timeout, _x.max_thrust, _x.n_thrusters)) length = len(self.allocation_matrix) buff.write(_struct_I.pack(length)) pattern = '<%sd'%length buff.write(struct.pack(pattern, *self.allocation_matrix)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ try: end = 0 start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.tf_prefix = str[start:end].decode('utf-8') else: self.tf_prefix = str[start:end] start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.base_link = str[start:end].decode('utf-8') else: self.base_link = str[start:end] start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.thruster_frame_base = str[start:end].decode('utf-8') else: self.thruster_frame_base = str[start:end] start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.thruster_topic_prefix = str[start:end].decode('utf-8') else: self.thruster_topic_prefix = str[start:end] start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.thruster_topic_suffix = str[start:end].decode('utf-8') else: self.thruster_topic_suffix = str[start:end] _x = self start = end end += 20 (_x.timeout, _x.max_thrust, _x.n_thrusters,) = _get_struct_2di().unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) pattern = '<%sd'%length start = end end += struct.calcsize(pattern) self.allocation_matrix = struct.unpack(pattern, str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: _x = self.tf_prefix length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self.base_link length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self.thruster_frame_base length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self.thruster_topic_prefix length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self.thruster_topic_suffix length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) buff.write(struct.pack('<I%ss'%length, length, _x)) _x = self buff.write(_get_struct_2di().pack(_x.timeout, _x.max_thrust, _x.n_thrusters)) length = len(self.allocation_matrix) buff.write(_struct_I.pack(length)) pattern = '<%sd'%length buff.write(self.allocation_matrix.tostring()) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ try: end = 0 start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.tf_prefix = str[start:end].decode('utf-8') else: self.tf_prefix = str[start:end] start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.base_link = str[start:end].decode('utf-8') else: self.base_link = str[start:end] start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.thruster_frame_base = str[start:end].decode('utf-8') else: self.thruster_frame_base = str[start:end] start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.thruster_topic_prefix = str[start:end].decode('utf-8') else: self.thruster_topic_prefix = str[start:end] start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) start = end end += length if python3: self.thruster_topic_suffix = str[start:end].decode('utf-8') else: self.thruster_topic_suffix = str[start:end] _x = self start = end end += 20 (_x.timeout, _x.max_thrust, _x.n_thrusters,) = _get_struct_2di().unpack(str[start:end]) start = end end += 4 (length,) = _struct_I.unpack(str[start:end]) pattern = '<%sd'%length start = end end += struct.calcsize(pattern) self.allocation_matrix = numpy.frombuffer(str[start:end], dtype=numpy.float64, count=length) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I(): global _struct_I return _struct_I _struct_2di = None def _get_struct_2di(): global _struct_2di if _struct_2di is None: _struct_2di = struct.Struct("<2di") return _struct_2di class GetThrusterManagerConfig(object): _type = 'uuv_thruster_manager/GetThrusterManagerConfig' _md5sum = 'b5a2d9d3bb510dd91fdb03f95e95b8de' _request_class = GetThrusterManagerConfigRequest _response_class = GetThrusterManagerConfigResponse
[ "bnb15@my.fsu.edu" ]
bnb15@my.fsu.edu
f2e5ced4d7d2a4b27cf1cc0ca62b21664d0e2e42
96dcea595e7c16cec07b3f649afd65f3660a0bad
/tests/components/upcloud/__init__.py
543ee65c713f03f795624219b93306406c977566
[ "Apache-2.0" ]
permissive
home-assistant/core
3455eac2e9d925c92d30178643b1aaccf3a6484f
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
refs/heads/dev
2023-08-31T15:41:06.299469
2023-08-31T14:50:53
2023-08-31T14:50:53
12,888,993
35,501
20,617
Apache-2.0
2023-09-14T21:50:15
2013-09-17T07:29:48
Python
UTF-8
Python
false
false
41
py
"""Tests for the UpCloud integration."""
[ "noreply@github.com" ]
home-assistant.noreply@github.com
aaa0047af98a795f9cec78bad8b8c1e5d46a56d5
1254745d2062d2d5475e209c269f9c9c68f04084
/bin/sclrq.py
8b2d15521871f3389ff34b6d0c266ffca82845db
[]
no_license
noobermin/lspplot
99d2f9f748be91ed90690c76460edc44cf398da0
15822c5502f42b590403058e5a2244af3063478f
refs/heads/master
2022-11-06T02:47:51.161575
2022-10-27T04:45:59
2022-10-27T04:45:59
56,020,778
0
0
null
null
null
null
UTF-8
Python
false
false
4,388
py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Just render something. Usage: ./sclrq.py [options] (--show|-s) <i> ./sclrq.py [options] <i> <outname> Options: --help -h --show -s Show --nozip -U sclr/flds are NOT gzipped. --zip -Z sclr/flds are gzipped. If neither of these two are set, guess based on name. --log10 -l Log it. --lims=LIM Set lims [default: (1e18,1e23)] --highlight=H Set highlight. --quantity=Q -Q Q Render this quantity [default: RhoN10] --dir=D -D D Read from this dir [default: .] --restrict=R Restrict it. --x-restrict=R Restrict by positions as a 4 tuple. --t-offset=T Set time offset in fs. [default: 0]. --title=T Set the title [default: Electron density] --units=U Set the colorbar units [default: number/cc] --laser Plot contours of the laser poyting vector. --intensity=I -I I Make a contour of this intensity [default: 3e18] --equal -E Make spatial dimensions equal. --cmap=CMAP Set the colormap. [default: viridis] --nofloor Raise an error if there are no positive values for log. --flip -F Flip instead rotate (ie., flip x axis) as in older versions. --no-ticks Don't include ticks. --orientation=V "V" for vertical or "H" for horizontal [default: V] ''' from docopt import docopt; import numpy as np; import numpy.linalg as lin; from pys import parse_ftuple, parse_ituple; from lspreader.flds import read_indexed, restrict; from lspplot.sclr import S; from lspplot.pc import pc,highlight,timelabel; from lspplot.physics import c,mu0,e0; opts = docopt(__doc__,help=True); quantity = opts['--quantity']; fvar=['E','B'] if opts['--laser'] else None; titlestr=opts['--title'] units=opts['--units']; svar=[quantity]; if opts['--nozip']: gzip = False; elif opts['--zip']: gzip = True; else: gzip = 'guess'; ##################################### #reading data d = read_indexed(int(opts['<i>']), flds=fvar,sclr=svar, gzip=gzip,dir=opts['--dir'], gettime=True,vector_norms=False); #choosing positions ylabel = 'z' if np.isclose(d['y'].max(),d['y'].min()) else 'y'; if opts['--x-restrict']: res = parse_ftuple(opts['--x-restrict'], length=4); res[:2] = [ np.abs(d['x'][:,0]*1e4 - ires).argmin() for ires in res[:2] ]; res[2:] = [ np.abs(d[ylabel][0,:]*1e4 - ires).argmin() for ires in res[2:] ]; #including the edges res[1]+=1; res[3]+=1; restrict(d,res); elif opts['--restrict']: res = parse_ituple(opts['--restrict'],length=None); restrict(d,res); x,y = d['x']*1e4, d[ylabel]*1e4; #massaging data t = d['t']; q = d[quantity]; ##################################### #plotting #getting options from user mn,mx = parse_ftuple(opts['--lims'],length=2); if opts['--flip']: rot,flip = False, True; else: rot,flip = True, False; #plot the density #orientation of colorbar if opts['--orientation'] == "V": orient = "vertical" elif opts['--orientation'] == "H": orient = "horizontal" else: print('orientation must be either "V" or "H"'); print(__doc__); quit(); r=pc( q,(x,y), lims=(mn,mx),log=opts['--log10'], clabel=units, title=titlestr, agg=not opts['--show'], flip=flip, rotate=rot, orient=orient, nofloor=opts['--nofloor'], cmap=opts['--cmap'], ); if opts['--highlight'] and opts['--highlight'] != "None" and opts['--highlight'] != 'none': myhi = float(opts['--highlight']); highlight( r, myhi, color="lightyellow", alpha=0.5); if opts['--laser']: laser = S(d); print(laser.shape); I = float(opts['--intensity']); highlight(r, I, q=laser, color="red", alpha=0.15); import matplotlib.pyplot as plt; toff=float(opts['--t-offset']); timelabel( r, 'time={:.2f} fs'.format(t*1e6+toff), size=11, color='white'); if opts['--equal']: plt.axis('equal'); r['axes'].autoscale(tight=True); if opts['--no-ticks']: plt.tick_params( axis='both', which='both', bottom='off', top='off', right='off', left='off'); if opts['--show']: plt.show(); else: plt.savefig(opts['<outname>']);
[ "ngirmang.1@osu.edu" ]
ngirmang.1@osu.edu
eeda3980822e8716c6c500124cb43778dd7b264c
570233f90e10dcfae793c01af1b2318c2b237775
/pg58.py
21d378f224565101eb5ba14bddb335be2e0664ab
[]
no_license
aarthisandhiya/codekata_player-py-
90218d4f010caa688547aa90a6faf7d74121e6a3
38220ee5e2ad7764ab49514b1351339da534618a
refs/heads/master
2020-05-29T15:16:42.306444
2019-05-08T06:42:50
2019-05-08T06:42:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
130
py
sen=str(input()) sen=sen.split() string=str(input()) c=0 for i in range(0,len(sen)): if(sen[i]==string): c=c+1 print(c)
[ "noreply@github.com" ]
aarthisandhiya.noreply@github.com
878ce48ea1742673841e76d7844c45d81e62b156
bd08d0532f20b7285b437c9bf620de1bbcd5b9ea
/aalh_iit_tiedtkes_001/populate-decades-column.py
02035ea25507a06e561210d718069c09883ba5c2
[ "Unlicense" ]
permissive
johndewees/iitmigration
a9e8a31ba6ceb541ce12c22fd612596cc243dbca
4dadfbecda719d6e7d60af076a231aedec3c862f
refs/heads/main
2023-03-14T17:06:58.777683
2021-03-27T20:44:58
2021-03-27T20:44:58
320,086,321
0
0
null
null
null
null
UTF-8
Python
false
false
3,317
py
from openpyxl import load_workbook filename = 'aalh_iit_tiedtkes_001.xlsx' wb = load_workbook(filename) ws = wb['Metadata Template'] minimumcol = 15 maximumcol = 15 minimumrow = 7 maximumrow = 154 iterationrow = 7 targetcol = 15 decadescol = 14 for row in ws.iter_rows(min_row=minimumrow, min_col=minimumcol, max_row=maximumrow, max_col=maximumcol): for cell in row: testvar = str(ws.cell(row=iterationrow, column=targetcol).value) if testvar == None: ws.cell(row=iterationrow, column=decadescol).value = None elif testvar.find('180') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1800s' elif testvar.find('181') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1810s' elif testvar.find('182') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1820s' elif testvar.find('183') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1830s' elif testvar.find('184') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1840s' elif testvar.find('185') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1850s' elif testvar.find('186') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1860s' elif testvar.find('187') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1870s' elif testvar.find('188') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1880s' elif testvar.find('189') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1890s' elif testvar.find('190') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1900s' elif testvar.find('191') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1910s' elif testvar.find('192') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1920s' elif testvar.find('193') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1930s' elif testvar.find('194') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1940s' elif testvar.find('195') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1950s' elif testvar.find('196') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1960s' elif testvar.find('197') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1970s' elif testvar.find('198') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1980s' elif testvar.find('199') != -1: ws.cell(row=iterationrow, column=decadescol).value = '1990s' elif testvar.find('200') != -1: ws.cell(row=iterationrow, column=decadescol).value = '2000s' elif testvar.find('201') != -1: ws.cell(row=iterationrow, column=decadescol).value = '2010s' elif testvar.find('202') != -1: ws.cell(row=iterationrow, column=decadescol).value = '2020s' print(iterationrow,'|',testvar,'|',ws.cell(row=iterationrow, column=decadescol).value) iterationrow = iterationrow + 1 wb.save('aalh_iit_tiedtkes_001.xlsx')
[ "noreply@github.com" ]
johndewees.noreply@github.com
eb5559ff8572a28b8cf7bc89c5975776da33d495
544cfadc742536618168fc80a5bd81a35a5f2c99
/tools/asuite/atest/test_runners/regression_test_runner.py
b71634fb8be8fc3a0f62d9a949cd439fe1cf8465
[]
no_license
ZYHGOD-1/Aosp11
0400619993b559bf4380db2da0addfa9cccd698d
78a61ca023cbf1a0cecfef8b97df2b274ac3a988
refs/heads/main
2023-04-21T20:13:54.629813
2021-05-22T05:28:21
2021-05-22T05:28:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,415
py
# Copyright 2018, The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Regression Detection test runner class. """ import constants from test_runners import test_runner_base class RegressionTestRunner(test_runner_base.TestRunnerBase): """Regression Test Runner class.""" NAME = 'RegressionTestRunner' EXECUTABLE = 'tradefed.sh' _RUN_CMD = '{exe} run commandAndExit regression -n {args}' _BUILD_REQ = {'tradefed-core', constants.ATEST_TF_MODULE} def __init__(self, results_dir): """Init stuff for base class.""" super(RegressionTestRunner, self).__init__(results_dir) self.run_cmd_dict = {'exe': self.EXECUTABLE, 'args': ''} # pylint: disable=unused-argument def run_tests(self, test_infos, extra_args, reporter): """Run the list of test_infos. Args: test_infos: List of TestInfo. extra_args: Dict of args to add to regression detection test run. reporter: A ResultReporter instance. Returns: Return code of the process for running tests. """ run_cmds = self.generate_run_commands(test_infos, extra_args) proc = super(RegressionTestRunner, self).run(run_cmds[0], output_to_stdout=True) proc.wait() return proc.returncode # pylint: disable=unnecessary-pass # Please keep above disable flag to ensure host_env_check is overriden. def host_env_check(self): """Check that host env has everything we need. We actually can assume the host env is fine because we have the same requirements that atest has. Update this to check for android env vars if that changes. """ pass def get_test_runner_build_reqs(self): """Return the build requirements. Returns: Set of build targets. """ return self._BUILD_REQ # pylint: disable=unused-argument def generate_run_commands(self, test_infos, extra_args, port=None): """Generate a list of run commands from TestInfos. Args: test_infos: A set of TestInfo instances. extra_args: A Dict of extra args to append. port: Optional. An int of the port number to send events to. Subprocess reporter in TF won't try to connect if it's None. Returns: A list that contains the string of atest tradefed run command. Only one command is returned. """ pre = extra_args.pop(constants.PRE_PATCH_FOLDER) post = extra_args.pop(constants.POST_PATCH_FOLDER) args = ['--pre-patch-metrics', pre, '--post-patch-metrics', post] self.run_cmd_dict['args'] = ' '.join(args) run_cmd = self._RUN_CMD.format(**self.run_cmd_dict) return [run_cmd]
[ "rick_tan@qq.com" ]
rick_tan@qq.com
4d4ea052f312f76a8e371c23b614d640aaf2acc4
fc3bdcbe68de7fce51b7b63158597ee70e03b3cc
/database.py
b0481854957bf4d62009c63176545192dca1bb8b
[]
no_license
claraj/peewee_tree_unittest
70381ebfe6baee92c85539078855188da8b769d3
e312f45fa73376c05288d604ee3b273d095a4f27
refs/heads/main
2021-09-26T16:39:14.219177
2021-09-22T23:03:40
2021-09-22T23:03:40
244,816,502
0
1
null
null
null
null
UTF-8
Python
false
false
503
py
from peewee import IntegrityError from models import Tree def add_tree(name, max_height): try: Tree(name=name, max_height=max_height).save() except IntegrityError as e: raise TreeError('Error adding tree because ' + str(e)) def get_all_trees(): result = Tree.select().execute() return list(result) def delete_tree_by_name(name): trees_deleted = Tree.delete().where(Tree.name==name).execute() return trees_deleted > 0 class TreeError(Exception): pass
[ "10088152+claraj@users.noreply.github.com" ]
10088152+claraj@users.noreply.github.com
42b387187d177114e02e33bc0d8ccc6dbde81012
5c83c974b36505af76e97ecd7115e1437044c9f3
/src/collections/nijl/createCollectionFromLocalJson.py
d51a43e579976e407deac725beba17da0c9bc93b
[ "CC0-1.0" ]
permissive
otani0083/iiif
ac6cf617ea79e5088ee8d49cbe69b3164e9706b6
358d91aef10d366ebb54a64990bde51debeee1f1
refs/heads/master
2021-05-21T07:33:05.411522
2020-04-03T01:08:12
2020-04-03T01:08:12
252,602,479
0
0
CC0-1.0
2020-04-03T01:18:58
2020-04-03T01:18:58
null
UTF-8
Python
false
false
2,406
py
import json import argparse import sys import glob import time collection_name = "nijl" input_dir = "../../../json/collections/" + collection_name output_path = "../../../docs/data/collection/collections/" + collection_name + ".json" files = glob.glob(input_dir + "/*.json") manifests = [] license_check = {} for i in range(len(files)): if i % 100 == 0: print(str(i+1)+"/"+str(len(files))) file = files[i] with open(file, 'r') as f: data = json.load(f) if "@type" in data and data["@type"] == "sc:Manifest": manifest = data["@id"] print(manifest) label = "" if "label" in data: label = data["label"] manifest_obj = dict() manifest_obj["@id"] = manifest manifest_obj["@type"] = "sc:Manifest" manifest_obj["label"] = label canvases = data["sequences"][0]["canvases"] # canvasが空 if len(canvases) == 0: continue canvas = canvases[0] resource = canvas["images"][0]["resource"] thumbnail = "" if "service" in resource: thumbnail = resource["service"]["@id"] + \ "/full/200,/0/default.jpg" else: thumbnail = canvas["thumbnail"]["@id"] if thumbnail != "": manifest_obj["thumbnail"] = thumbnail flg = False license = data["license"] manifest_obj["license"] = license if license != "http://kotenseki.nijl.ac.jp/page/usage.html": flg = True if license not in license_check: license_check[license] = 0 license_check[license] += 1 if flg: manifests.append(manifest_obj) print(license_check) collection = dict() collection["@context"] = "http://iiif.io/api/presentation/2/context.json" collection["@id"] = "https://nakamura196.github.io/iiif/data/collection/collections/" + collection_name + ".json" collection["@type"] = "sc:Collection" collection["vhint"] = "use-thumb" collection["manifests"] = manifests fw = open(output_path, 'w') json.dump(collection, fw, ensure_ascii=False, indent=4, sort_keys=True, separators=(',', ': '))
[ "na.kamura.1263@gmail.com" ]
na.kamura.1263@gmail.com
30f0f0d0a7e276bc44314c6d5123bdbc0f1685d0
1d91df48bfb43f15c1e567f8c8f2de6eef2b1dea
/test.py
27d1ad5489789d8c33458bc2bd93d712c8a194df
[ "MIT" ]
permissive
dtekluva/Simple-Currency-recognition
513cabcd6b30d43bb516d747992d81596d604e03
2bdb56d752b8b37aca62732cfbbffeb11beaed94
refs/heads/master
2021-05-12T11:29:22.023463
2018-01-15T23:31:03
2018-01-15T23:31:03
117,387,748
1
1
null
null
null
null
UTF-8
Python
false
false
2,148
py
"""**Test memory data against input data""" import mem_io as write from functools import reduce def resolve(imageArray): import vectorize as vectorize newarr = imageArray newimg = [] targ = [] for pix in imageArray: newimg.append(vectorize.scale(pix)) for pix in newimg: targ.append(vectorize.further_reduce(pix)) return targ def deviation(test_img): mem = write.io() deviated_copy = mem newimg = resolve(test_img) for key in mem: i = 0 mean_dev = [] for val in newimg: dev = newimg[i][0] - mem[key][i][0] mean_dev.append(dev) i+=1 deviated_copy[key] = mean_dev return deviated_copy def test(newarr, mem): mem = "" newarr = deviation(newarr) result = newarr #copying newarr so thet result can maintain a similar dict structure as newarr for easy compilation for key in newarr: i = 0 for item in range(len(newarr[key])): if newarr[key][i] < 0: newarr[key][i] = newarr[key][i] * -1 i +=1 tot_dev = reduce(lambda x, y: x + y,newarr[key]) newarr[key] = (1-((2284800 - tot_dev)/2284800)) decision = min(result.items(),key = lambda x:x[1]) if "20" in decision[0]: print("20 Naira note, " + " decision confidence "+ confidence(decision[1]) + "%") elif "100" in decision[0]: print("100 Naira note, " + " decision confidence "+ confidence(decision[1]) + "%") elif "200" in decision[0]: print("200 Naira note, " + " decision confidence "+ confidence(decision[1]) + "%") elif "500" in decision[0]: print("500 Naira note, " + " decision confidence "+ confidence(decision[1]) + "%") elif "1000" in decision[0]: print("1000 Naira note, " + " decision confidence "+ confidence(decision[1]) + "%") elif "50" in decision[0]: print("50 Naira note, " + " decision confidence "+ confidence(decision[1]) + "%" ) def confidence(val): if val > 1: val = int(val) conf = (1 - val) * 100 return str(conf)
[ "31896598+dtekluva@users.noreply.github.com" ]
31896598+dtekluva@users.noreply.github.com
6dbf49b1e7581c9482c56f08401812a37b784272
f1614f3531701a29a33d90c31ab9dd6211c60c6b
/menu_sun_api/domain/model/order/order_repository.py
7c755dc5edbe830e08bff96acd76103012b915aa
[]
no_license
pfpacheco/menu-sun-api
8a1e11543b65db91d606b2f3098847e3cc5f2092
9bf2885f219b8f75d39e26fd61bebcaddcd2528b
refs/heads/master
2022-12-29T13:59:11.644409
2020-10-16T03:41:54
2020-10-16T03:41:54
304,511,679
0
0
null
null
null
null
UTF-8
Python
false
false
4,193
py
from sqlalchemy import and_ from menu_sun_api.domain.db_repository import DBRepository from menu_sun_api.domain.model.order.order import Order, OrderStatus, OrderStatusType import logging from menu_sun_api.shared.specification import Specification logger = logging.getLogger() class OrderRepository(DBRepository): def __init__(self, session=None): super().__init__(Order, session) def get_order(self, seller_id, order_id): query = self.session.query(Order). \ filter( and_( Order.seller_id == seller_id, Order.order_id == order_id)) order = query.one_or_none() return order def get_order_not_seller_id(self, order_id): query = self.session.query(Order). \ filter( and_( Order.order_id == order_id)) order = query.one_or_none() return order def load_order_status(self, seller_id, order_id): query = self.session.query(OrderStatus). \ outerjoin(Order). \ filter(and_(Order.seller_id == seller_id, Order.order_id == order_id)). \ order_by(OrderStatus.id) statuses = query.all() return statuses def append_status(self, status): self.session.add(status) def load_pending_orders(self, seller_id): orders = self.session.query(Order). \ filter( and_( Order.order_queue_date.is_(None), Order.seller_id == seller_id)).all() ls = [] for order in orders: logger.info('Filtering order: [{}]'.format(order.order_id)) status = order.status if status: logger.info('Order status: [{}]'.format(status.status)) if status.status == OrderStatusType.APPROVED: ls.append(order) return ls def mark_as_integrated(self, seller_id, order_id): from datetime import datetime order = self.get_order(seller_id=seller_id, order_id=order_id) order.integration_date = datetime.utcnow() def load_orders_on_wms(self, seller_id): orders = self.session.query(Order). \ filter(and_(Order.integration_date is not None, Order.seller_id == seller_id)). \ filter(and_(Order.created_date >= '2020-02-01')). \ all() ls = [] for order in orders: if order.on_wms(): logger.info('Filtering order: [{}]'.format(order.order_id)) ls.append(order) return ls def load_order_by_order_id(self, seller_id, order_id): orders = self.session.query(Order). \ filter(and_(Order.integration_date is not None, Order.seller_id == seller_id)). \ filter(and_(Order.order_id == order_id)). \ limit(1) ls = [] for order in orders: if order.on_wms(): logger.info('Filtering order: [{}]'.format(order.order_id)) ls.append(order) return ls def list_orders_with_unpublished_status(self, seller_id): stmt = self.session.query(OrderStatus.order_id). \ join(Order). \ filter(and_(OrderStatus.published_date is None, Order.seller_id == seller_id)).distinct() statuses = self.session.query(Order). \ filter(Order.id.in_(stmt)).all() return statuses def filter_by_specification(self, seller_id: int, specification: Specification): query = self.session.query(Order) return query.filter(specification.is_satisfied_by(seller_id)).all() def list_orders_by_status(self, seller_id, status_filter): orders = self.session.query(Order). \ filter(Order.seller_id == seller_id).all() logger.info('Filtering order by status: [{}]'.format(status_filter)) logger.info('Filtering all orders: {}'.format(list(map(lambda x: str(x), orders)))) result = [order for order in orders if order.status.status == status_filter] logger.info('Filtered orders: {}'.format(list(map(lambda x: str(x), result)))) return result
[ "pfpacheco@gmail.com" ]
pfpacheco@gmail.com
31ce100735578008d5eacc8a2d850897b2864889
810305a5f4d9592e81381c252ab24be43d33817e
/aishack/migrations/0002_auto__add_field_tutorial_author.py
2d4216657dffd04b8ced32271fc7a5d0f0891b78
[]
no_license
awal123/aishack
9dbfcbb329b35674c6f0a15c6dfc9de39ba34d05
5a16efca42899f3ec1495a509fe801348f3933ac
refs/heads/master
2021-01-22T21:23:11.168117
2014-08-31T05:02:36
2014-08-31T05:02:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,076
py
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Tutorial.author' db.add_column(u'aishack_tutorial', 'author', self.gf('django.db.models.fields.related.ForeignKey')(default=0, to=orm['auth.User']), keep_default=False) def backwards(self, orm): # Deleting field 'Tutorial.author' db.delete_column(u'aishack_tutorial', 'author_id') models = { u'aishack.category': { 'Meta': {'object_name': 'Category'}, 'desc': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '256'}) }, u'aishack.quiz': { 'Meta': {'object_name': 'Quiz'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '128'}) }, u'aishack.track': { 'Meta': {'object_name': 'Track'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '256'}) }, u'aishack.tracktutorials': { 'Meta': {'object_name': 'TrackTutorials'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'track': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['aishack.Track']"}), 'tutorial': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['aishack.Tutorial']"}) }, u'aishack.tutorial': { 'Meta': {'object_name': 'Tutorial'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['aishack.Category']"}), 'content': ('django.db.models.fields.TextField', [], {}), 'date': ('django.db.models.fields.DateField', [], {}), 'excerpt': ('django.db.models.fields.CharField', [], {'max_length': '512'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'post_image': ('django.db.models.fields.URLField', [], {'max_length': '256'}), 'slug': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}) }, u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['aishack']
[ "sinha.utkarsh1990@gmail.com" ]
sinha.utkarsh1990@gmail.com
693933d07fc47fcbfe96c3cef05720885ce398ed
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/28/usersdata/109/8524/submittedfiles/serie1.py
a5b0d2c43f8323230a99f28b4d2d20ff6ee4445b
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
238
py
# -*- coding: utf-8 -*- from __future__ import division import math n=input('Digite o valor de n:') x=1 Cont=0 for i in range (0,n+1,1): if x%2==0: x=(x*(-1)) a=x//(x**2) cont=cont+a i=i+1 print ('%.5f'%cont)
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
e5e8a66a4d5db35873d8ab76575a05bd8dd038cd
2687b15ecde22e25a3ec89abb4e380af283cd31d
/CMGTools/H2TauTau/python/proto/samples/run2011/tauMu_ColinOct23_Down.py
f2802c9d00cbbc85be154efa0acdfa86c1d528c0
[]
no_license
francescobrivio/cmg-cmssw
bbd60e0dafece3caf83ab969b67b636541dac3d9
2b3d8444249ac00c769d2974d604a5e6a698d6ff
refs/heads/CMGTools-from-CMSSW_7_2_3
2020-12-31T06:22:11.695970
2015-04-08T07:40:23
2015-04-08T07:40:23
33,541,974
0
0
null
2015-04-07T12:32:40
2015-04-07T12:32:39
null
UTF-8
Python
false
false
2,958
py
import itertools import copy from CMGTools.RootTools.fwlite.Config import printComps from CMGTools.RootTools.utils.connect import connect from CMGTools.RootTools.utils.splitFactor import splitFactor from CMGTools.H2TauTau.proto.samples.run2011.data import * from CMGTools.H2TauTau.proto.samples.run2011.embed import * from CMGTools.H2TauTau.proto.samples.run2011.ewk import * from CMGTools.H2TauTau.proto.samples.run2011.diboson import * from CMGTools.H2TauTau.proto.samples.run2011.higgs import * from CMGTools.H2TauTau.proto.samples.run2011.triggers_tauMu import data_triggers_2011A, data_triggers_2011B, mc_triggers aliases = { '/VBF_HToTauTau.*START42.*':'HiggsVBF', '/GluGluToHToTauTau.*START42.*':'HiggsGGH', '/WH_ZH_TTH_HToTauTau.*START42.*':'HiggsVH', '/DYJets.*START42.*':'DYJets', ## '/WJetsToLNu.*START42.*':'WJets', ## '/W1Jet.*START42.*':'W1Jets', ## '/W2Jets.*START42.*':'W2Jets', ## '/W3Jets.*START42.*':'W3Jets', ## '/W4Jets.*START42.*':'W4Jets', ## '/TTJets.*START42.*':'TTJets', ## '/T_TuneZ2_tW-channel.*START42.*':'T_tW', ## '/Tbar_TuneZ2_tW-channel.*START42.*':'Tbar_tW', ## '/TauPlusX/Run2011A-03Oct2011-v1.*':'data_Run2011A_03Oct2011_v1', ## '/TauPlusX/Run2011A-05Aug2011-v1.*':'data_Run2011A_05Aug2011_v1', ## '/TauPlusX/Run2011A-May10ReReco-v1.*':'data_Run2011A_May10ReReco_v1', ## '/TauPlusX/Run2011A-PromptReco-v4.*':'data_Run2011A_PromptReco_v4', ## '/TauPlusX/Run2011B-PromptReco-v1':'data_Run2011B_PromptReco_v1', '/DoubleMu/StoreResults-DoubleMu_2011A_03Oct2011_v1.*':'embed_Run2011A_03Oct2011_v1', '/DoubleMu/StoreResults-DoubleMu_2011A_05Aug2011_v1.*':'embed_Run2011A_05Aug2011_v1', '/DoubleMu/StoreResults-DoubleMu_2011A_10May2011_v1.*':'embed_Run2011A_May10ReReco_v1', '/DoubleMu/StoreResults-DoubleMu_2011A_PR_v4.*':'embed_Run2011A_PromptReco_v4', '/DoubleMu/StoreResults-DoubleMu_2011B_PR_v1.*':'embed_Run2011B_PromptReco_v1', ## '/WW_TuneZ2.*START42.*':'WW', ## '/WZ_TuneZ2.*START42.*':'WZ', ## '/ZZ_TuneZ2.*START42.*':'ZZ', ## '/WWJetsTo2L2Nu.*START42.*':'WWJetsTo2L2Nu', ## '/WZJetsTo2L2Q.*START42.*':'WZJetsTo2L2Q', ## '/WZJetsTo3LNu.*START42.*':'WZJetsTo3LNu', ## '/ZZJetsTo2L2Nu.*START42.*':'ZZJetsTo2L2Nu', ## '/ZZJetsTo2L2Q.*START42.*':'ZZJetsTo2L2Q', ## '/ZZJetsTo4L.*START42.*':'ZZJetsTo4L', } MC_list = copy.copy( mc_ewk ) MC_list.extend( mc_higgs ) MC_list.extend( mc_diboson ) for sam in MC_list: sam.triggers = mc_triggers for data in data_list_2011A: data.triggers = data_triggers_2011A for data in data_list_2011B: data.triggers = data_triggers_2011B allsamples = copy.copy(MC_list) allsamples.extend( data_list_2011 ) allsamples.extend( embed_list_2011 ) connect( allsamples, '%TAUMU_Down_ColinOct30', 'tauMu.*root', aliases, cache=True, verbose=False) Tbar_tW.nGenEvents = 809984. for c in allsamples: c.splitFactor = splitFactor(c)
[ "jan.steggemann@cern.ch" ]
jan.steggemann@cern.ch
e0a1e53b3edd3865eab6b41b6d5486a7c4f7520b
372e299709a70e30a8487dbaa669a4f572d99df0
/2015/src/day_06/part_1.py
20caf305073a30a2c72c51e8e72822fe24fd49bc
[]
no_license
mkierc/advent-of-code
e806e30cbed5bb8224b28583b8943c58ba0f80e0
f5115403fcff0082e1cd33308a0259b234c58229
refs/heads/master
2021-12-25T05:43:24.673107
2021-12-17T07:56:20
2021-12-17T07:56:20
76,584,172
0
1
null
null
null
null
UTF-8
Python
false
false
2,037
py
import re import matplotlib.pyplot as plt import numpy with open('data.txt') as file: input_data = file.read().splitlines() def turn_on(screen, x_1, y_1, x_2, y_2): for row in range(x_1, x_2): for column in range(y_1, y_2): screen[column][row] = 1 def turn_off(screen, x_1, y_1, x_2, y_2): for row in range(x_1, x_2): for column in range(y_1, y_2): screen[column][row] = 0 def toggle(screen, x_1, y_1, x_2, y_2): for row in range(x_1, x_2): for column in range(y_1, y_2): if screen[column][row] == 0: screen[column][row] = 1 elif screen[column][row] == 1: screen[column][row] = 0 else: raise NotImplementedError(screen[column][row]) def parse_instruction(instruction): x_1, y_1, x_2, y_2 = re.search(r'(\d+),(\d+) through (\d+),(\d+)', instruction).groups() if instruction.startswith('turn on'): return turn_on, int(x_1), int(y_1), int(x_2) + 1, int(y_2) + 1 elif instruction.startswith('turn off'): return turn_off, int(x_1), int(y_1), int(x_2) + 1, int(y_2) + 1 elif instruction.startswith('toggle'): return toggle, int(x_1), int(y_1), int(x_2) + 1, int(y_2) + 1 else: raise NotImplementedError def deploy_lights(instruction_list): screen = [[0 for _ in range(1000)] for _ in range(1000)] # process instructions and apply functions for instruction in instruction_list: _function, x_1, y_1, x_2, y_2 = parse_instruction(instruction) _function(screen, x_1, y_1, x_2, y_2) # count the lights lights_count = 0 for row in screen: lights_count += row.count(1) # draw the image to satisfy my curiosity numpy_array = numpy.array([numpy.array(row) for row in screen]) plt.imsave('image_1.png', numpy_array, cmap='Greys') return lights_count def main(): answer = deploy_lights(input_data) print('answer:', answer) if __name__ == '__main__': main()
[ "urban.pl@gmail.com" ]
urban.pl@gmail.com