uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
e3db116a1607f4d3fe151c84
train
class
class Layers( KicadObj ): def __init__( self, name ): KicadObj.__init__( self, name ) self.layers = {} self.names = {} self.internal_layer_count = 0 def clone( self ): obj = Layers( self.obj_name ) obj.layers = self.layers.copy() obj.names = self.names.copy() for layer in self.layers.values(): se...
class Layers( KicadObj ):
def __init__( self, name ): KicadObj.__init__( self, name ) self.layers = {} self.names = {} self.internal_layer_count = 0 def clone( self ): obj = Layers( self.obj_name ) obj.layers = self.layers.copy() obj.names = self.names.copy() for layer in self.layers.values(): self.layer_added( layer ) r...
params" ) ) writer.newline() writer.end() class Layer( KicadObj ): def __init__( self, nr, name=None, kind=None, hide=None ): KicadObj.__init__( self, nr ) self.nr = int(nr) self.name = name self.kind = kind self.hide = hide def tag_value( self, factory, value ): if self.name == None: self.na...
197
197
658
9
188
BuysDB/splitflap
thirdparty/panelize.py
Python
Layers
Layers
1,701
1,773
1,701
1,702
f7422563d47c0949c0e69953cdd13bb0c22b9ca9
bigcode/the-stack
train
3e1a8461297cc755796960e2
train
class
class Module( KicadFatObj ): def __init__( self, name ): self.graphics = [] self.pads = [] KicadFatObj.__init__( self, name, ( Text( "layer" ), Text( "tedit" ), Text( "tstamp" ), VectorAngle( "at" ), Text( "descr" ), Text( "tags" ), Text( "path" ), Float( "solder_mask_margin" ), Float...
class Module( KicadFatObj ):
def __init__( self, name ): self.graphics = [] self.pads = [] KicadFatObj.__init__( self, name, ( Text( "layer" ), Text( "tedit" ), Text( "tstamp" ), VectorAngle( "at" ), Text( "descr" ), Text( "tags" ), Text( "path" ), Float( "solder_mask_margin" ), Float( "clearance" ), Text( "att...
( KicadFatObj ): def __init__( self, name ): KicadFatObj.__init__( self, name, ( Vector3D( "xyz" ), ) ) class Model( KicadFatObj ): def __init__( self, name ): KicadFatObj.__init__( self, name, ( NamedVector3D( "at" ), NamedVector3D( "scale" ), NamedVector3D( "rotate" ), ) ) self.filename = ...
256
256
857
10
245
BuysDB/splitflap
thirdparty/panelize.py
Python
Module
Module
1,325
1,424
1,325
1,326
959e09a5ad79118164d9bd9e3f7f44a34cec1498
bigcode/the-stack
train
da09a2244467ec7698c52a17
train
class
class YesNo( KicadObj ): def __init__( self, name ): KicadObj.__init__( self, name ) self.value = None def tag_value( self, factory, value ): if value == "yes": self.value = True elif value == "no": self.value = False else: factory.parse_error( "invalid value '%s' for bool '%s'" % ( value, self.o...
class YesNo( KicadObj ):
def __init__( self, name ): KicadObj.__init__( self, name ) self.value = None def tag_value( self, factory, value ): if value == "yes": self.value = True elif value == "no": self.value = False else: factory.parse_error( "invalid value '%s' for bool '%s'" % ( value, self.obj_name ) ) def clone( s...
"true" ) else: writer.write_text( "false" ) def __str__( self ): if self.value == None: return "<<<NONE>>>" if self.value: return "true" else: return "false" class YesNo( KicadObj ):
64
64
212
10
54
BuysDB/splitflap
thirdparty/panelize.py
Python
YesNo
YesNo
278
312
278
279
f752f23cac47ace7a4acda3285e169bd4dc27ce5
bigcode/the-stack
train
b8a6bd354b920cb130223c27
train
class
class Setup( KicadFatObj ): def __init__( self, name ): self.user_trace_width = [] self.user_via = [] KicadFatObj.__init__( self, name, ( Float( "last_trace_width" ), ( "user_trace_width", self.user_trace_width, Float ), ( "user_via", self.user_via, Vector ), Float( "trace_clearance" ), Float( "z...
class Setup( KicadFatObj ):
def __init__( self, name ): self.user_trace_width = [] self.user_via = [] KicadFatObj.__init__( self, name, ( Float( "last_trace_width" ), ( "user_trace_width", self.user_trace_width, Float ), ( "user_via", self.user_via, Vector ), Float( "trace_clearance" ), Float( "zone_clearance" ), YesNo( "...
.padsonsilk.value = False self.subtractmaskfromsilk.value = False self.outputformat.value = 1.0 self.mirror.value = False self.drillshape.value = 0 self.scaleselection.value = 1.0 self.outputdirectory.value = "production" def write( self, writer ): writer.begin( self ) writer.newline() self.write_ob...
256
256
1,056
10
246
BuysDB/splitflap
thirdparty/panelize.py
Python
Setup
Setup
1,579
1,672
1,579
1,580
724df1eade27c9f4189ada87c442eb4bcd39a2f8
bigcode/the-stack
train
5ca6bb6d69dd755b83b765df
train
class
class Vector3D( Vector ): def __init__( self, name, x=None, y=None, z=None ): Vector.__init__( self, name, x, y ) self.z = z def tag_value( self, factory, value ): if self.x == None: self.x = float(value) elif self.y == None: self.y = float(value) elif self.z == None: self.z = float(value) else...
class Vector3D( Vector ):
def __init__( self, name, x=None, y=None, z=None ): Vector.__init__( self, name, x, y ) self.z = z def tag_value( self, factory, value ): if self.x == None: self.x = float(value) elif self.y == None: self.y = float(value) elif self.z == None: self.z = float(value) else: factory.parse_error( "...
# # +++ sin/cos??? # raise Exception( "unsupported angle" ) #return Vector( self.obj_name, x, y ) return self.rotate( self.a ) def get_angle( self ): return self.a or 0 class Vector3D( Vector ):
66
66
221
8
57
BuysDB/splitflap
thirdparty/panelize.py
Python
Vector3D
Vector3D
441
469
441
442
ed522edd3b8be02277258899647c4f908bf4d675
bigcode/the-stack
train
1ea39fc0768faf6272966b0a
train
class
class KicadPcb( KicadFatObj ): def __init__( self, name, template=None ): self.nets = NetsList() self.net_classes = [] self.modules = [] self.graphics = [] self.segments = [] self.zones = [] if template == None: version = Int( "version" ) host = List( "host" ) general = General( "general" ) ...
class KicadPcb( KicadFatObj ):
def __init__( self, name, template=None ): self.nets = NetsList() self.net_classes = [] self.modules = [] self.graphics = [] self.segments = [] self.zones = [] if template == None: version = Int( "version" ) host = List( "host" ) general = General( "general" ) page = List( "page" ) title_b...
writer.begin( self ) writer.newline() self.write_objects( writer, ( "links", "no_connects", "area", "thickness", "drawings", "tracks", "zones", "modules", "nets" ) ) writer.newline() writer.end() writer.newline() class NetsList: def __init__( self ): self.by_nr = {} self.by_name = {} self.max_nr = ...
255
255
853
14
241
BuysDB/splitflap
thirdparty/panelize.py
Python
KicadPcb
KicadPcb
1,877
1,977
1,877
1,878
9807cc385bbf803b0bea7d828eac48b172a7ee80
bigcode/the-stack
train
8eea9bd4ab6e85b1e3a67033
train
class
class NetClass( KicadFatObj ): def __init__( self, name ): self.nets = [] KicadFatObj.__init__( self, name, ( Float( "clearance" ), Float( "trace_width" ), Float( "via_dia" ), Float( "via_drill" ), Float( "uvia_dia" ), Float( "uvia_drill" ), Float( "diff_pair_gap" ), # after 4.0.5 Float( "...
class NetClass( KicadFatObj ):
def __init__( self, name ): self.nets = [] KicadFatObj.__init__( self, name, ( Float( "clearance" ), Float( "trace_width" ), Float( "via_dia" ), Float( "via_drill" ), Float( "uvia_dia" ), Float( "uvia_drill" ), Float( "diff_pair_gap" ), # after 4.0.5 Float( "diff_pair_width" ), # after 4.0....
edit.clone() ) obj.set( "tstamp", self.tstamp.clone() ) obj.set( "at", trans.vector( self.at ) ) obj.set( "descr", self.descr.clone() ) obj.set( "tags", self.tags.clone() ) obj.set( "path", self.path.clone() ) for graphic in self.graphics: obj.graphics.append( graphic.copy( trans ) ) for pad in self.pa...
122
122
407
11
110
BuysDB/splitflap
thirdparty/panelize.py
Python
NetClass
NetClass
1,427
1,472
1,427
1,428
dec1880075279b611450eceb419cab6425984306
bigcode/the-stack
train
f0739ae54db67e6c90b16858
train
function
def get_similars(data, target, threshold): G = NGram(target) return G.search(data, threshold=threshold)[0][0]
def get_similars(data, target, threshold):
G = NGram(target) return G.search(data, threshold=threshold)[0][0]
://pythonhosted.org/ngram/ngram.html def get_similar(data, target): G = NGram(target) return G.find(data) #A améliorer pour que le match soit l'élément qui partage le plus long ngramm def get_similars(data, target, threshold):
64
64
32
11
52
ulbstic/ugescovalidator
ugfunctions/suggest_wikipedia.py
Python
get_similars
get_similars
12
14
12
12
4bf3b1675ce874266e42929813b9268d5d14643a
bigcode/the-stack
train
aa3dee10b30e12af1fb6d8c3
train
class
class Cache( object ): def __init__(self, fn): self.fn = fn self._cache = {} functools.update_wrapper(self, fn) def __call__(self, *args, **kwargs): key = str(args) + str(kwargs) if key in self._cache: ret = self._cache[key] else: ret = s...
class Cache( object ):
def __init__(self, fn): self.fn = fn self._cache = {} functools.update_wrapper(self, fn) def __call__(self, *args, **kwargs): key = str(args) + str(kwargs) if key in self._cache: ret = self._cache[key] else: ret = self._cache[key] = self.f...
return G.find(data) #A améliorer pour que le match soit l'élément qui partage le plus long ngramm def get_similars(data, target, threshold): G = NGram(target) return G.search(data, threshold=threshold)[0][0] class Cache( object ):
64
64
110
6
58
ulbstic/ugescovalidator
ugfunctions/suggest_wikipedia.py
Python
Cache
Cache
17
34
17
18
0aba8901ffe1d1d0dde86b2500d38ae748a23bbc
bigcode/the-stack
train
f2c2d476e5186517fa31beac
train
function
@Cache def gsrsearch(query, lang, results=10): ''' Do a Wikipedia search for `query` and return a list of tuples (page title, url). Use ngram module to get the best match Keyword arguments: * lang : language iso code : en, fr, etc. * results - the maximum number of results returned '...
@Cache def gsrsearch(query, lang, results=10):
''' Do a Wikipedia search for `query` and return a list of tuples (page title, url). Use ngram module to get the best match Keyword arguments: * lang : language iso code : en, fr, etc. * results - the maximum number of results returned ''' search_params = { 'action': 'qu...
call__(self, *args, **kwargs): key = str(args) + str(kwargs) if key in self._cache: ret = self._cache[key] else: ret = self._cache[key] = self.fn(*args, **kwargs) return ret def clear_cache(self): self._cache = {} @Cache def gsrsearch(query, lang, re...
87
88
295
15
72
ulbstic/ugescovalidator
ugfunctions/suggest_wikipedia.py
Python
gsrsearch
gsrsearch
37
81
37
38
a918baa22445b29bedc0bf26c1dbdd579d0f44f5
bigcode/the-stack
train
10d5c77b746dc2eabb71a138
train
function
def get_similar(data, target): G = NGram(target) return G.find(data)
def get_similar(data, target):
G = NGram(target) return G.find(data)
import functools import requests from ngram import NGram # https://pythonhosted.org/ngram/ngram.html def get_similar(data, target):
34
64
21
8
25
ulbstic/ugescovalidator
ugfunctions/suggest_wikipedia.py
Python
get_similar
get_similar
7
9
7
7
0fede03cdce4b93586c86e26080df88ea8f214a9
bigcode/the-stack
train
28ccafc50ea1633bb30b4c01
train
class
class DirectoryServiceBackend(BaseBackend): """Implementation of DirectoryService APIs.""" def __init__(self, region_name, account_id): super().__init__(region_name, account_id) self.directories = {} self.tagger = TaggingService() @staticmethod def default_vpc_endpoint_service(...
class DirectoryServiceBackend(BaseBackend):
"""Implementation of DirectoryService APIs.""" def __init__(self, region_name, account_id): super().__init__(region_name, account_id) self.directories = {} self.tagger = TaggingService() @staticmethod def default_vpc_endpoint_service(service_region, zones): """List of d...
new_state def to_dict(self): """Create a dictionary of attributes for Directory.""" attributes = { "AccessUrl": self.access_url, "Alias": self.alias, "DirectoryId": self.directory_id, "DesiredNumberOfDomainControllers": self.desired_number_of_domain_...
256
256
2,517
7
248
andormarkus/moto
moto/ds/models.py
Python
DirectoryServiceBackend
DirectoryServiceBackend
180
502
180
180
c96b7dc37e00ded0a28b43ee210d8f9bc3681b6f
bigcode/the-stack
train
9f94cce01608e4d377689251
train
class
class Directory(BaseModel): # pylint: disable=too-many-instance-attributes """Representation of a Simple AD Directory. When the "create" API for a Simple AD or a Microsoft AD directory is invoked, two domain controllers and a DNS server are supposed to be created. That is NOT done for the fake direct...
class Directory(BaseModel): # pylint: disable=too-many-instance-attributes
"""Representation of a Simple AD Directory. When the "create" API for a Simple AD or a Microsoft AD directory is invoked, two domain controllers and a DNS server are supposed to be created. That is NOT done for the fake directories. However, the DnsIpAddrs attribute is supposed to contain the IP ...
"""DirectoryServiceBackend class with methods for supported APIs.""" from datetime import datetime, timezone from moto.core import BaseBackend, BaseModel from moto.core.utils import get_random_hex, BackendDict from moto.ds.exceptions import ( ClientException, DirectoryLimitExceededException, EntityAlreadyE...
160
256
1,293
17
142
andormarkus/moto
moto/ds/models.py
Python
Directory
Directory
23
177
23
23
ea381e980e32a6c78f196f688686c0697a94858a
bigcode/the-stack
train
68ffa44bf087c1bddef1a952
train
class
class SyncStore: # Whether or not we are syncing sync_mode: bool long_sync: bool peak_to_peer: Dict[bytes32, Set[bytes32]] # Header hash : peer node id peer_to_peak: Dict[bytes32, Tuple[bytes32, uint32, uint128]] # peer node id : [header_hash, height, weight] sync_target_header_hash: Optional[...
class SyncStore: # Whether or not we are syncing
sync_mode: bool long_sync: bool peak_to_peer: Dict[bytes32, Set[bytes32]] # Header hash : peer node id peer_to_peak: Dict[bytes32, Tuple[bytes32, uint32, uint128]] # peer node id : [header_hash, height, weight] sync_target_header_hash: Optional[bytes32] # Peak hash we are syncing towards sync...
import asyncio import logging from typing import Dict, List, Optional, Set, Tuple from flax.types.blockchain_format.sized_bytes import bytes32 from flax.util.ints import uint32, uint128 log = logging.getLogger(__name__) class SyncStore: # Whether or not we are syncing
65
256
1,111
13
52
amuDev/flax-blockchain
flax/full_node/sync_store.py
Python
SyncStore
SyncStore
11
136
11
12
711c77622554b19adbbd612fe40a52ebb94d9df2
bigcode/the-stack
train
59d788120b96e3ab52b84889
train
function
def main(filename, password): security.encrypt_json(filename, password)
def main(filename, password):
security.encrypt_json(filename, password)
import argparse import getpass from pyspark_ingestion.utils import security def main(filename, password):
22
64
14
6
15
gianmarcodonetti/pyspark-ingestion
bin/security/encrypt_settings.py
Python
main
main
7
8
7
7
ae75e82171986821e0d47457bb2ab049045f90dd
bigcode/the-stack
train
3826ddc9f9fc3506d98d6613
train
function
def create_parser(): prs = argparse.ArgumentParser(description="Encrypting settings file.") prs.add_argument('filename', type=str, nargs='?', help="Filename of the file to encrypt.", default='settings.json') return prs
def create_parser():
prs = argparse.ArgumentParser(description="Encrypting settings file.") prs.add_argument('filename', type=str, nargs='?', help="Filename of the file to encrypt.", default='settings.json') return prs
import argparse import getpass from pyspark_ingestion.utils import security def main(filename, password): security.encrypt_json(filename, password) def create_parser():
34
64
49
4
30
gianmarcodonetti/pyspark-ingestion
bin/security/encrypt_settings.py
Python
create_parser
create_parser
11
15
11
11
386d6be9132191ba4d0ee0a9ae6a84fff4c66dbc
bigcode/the-stack
train
f032e9e8fe489b09e19770e7
train
function
def sync_model(src_model, tgt_model): print('==> synchronizing the model weights.') params = {} for l in src_model.layers: params['{}'.format(l.name)] = l.get_weights() for l in tgt_model.layers: if len(l.get_weights()) > 0: l.set_weights(params['{}'.format(l.name)]) ret...
def sync_model(src_model, tgt_model):
print('==> synchronizing the model weights.') params = {} for l in src_model.layers: params['{}'.format(l.name)] = l.get_weights() for l in tgt_model.layers: if len(l.get_weights()) > 0: l.set_weights(params['{}'.format(l.name)]) return tgt_model
_label=1) eer = brentq(lambda x: 1. - x - interp1d(fpr, tpr)(x), 0., 1.) thresh = interp1d(fpr, thresholds)(eer) return eer, thresh def sync_model(src_model, tgt_model):
64
64
80
9
54
widdiot/VGG-Speaker-Recognition
tool/toolkits.py
Python
sync_model
sync_model
180
189
180
180
51c376bb0c0036705b2d67a46e6b9be1be3445f3
bigcode/the-stack
train
9ac6405f7ba2a4c138537f04
train
function
def get_chunks(l, n): # For item i in a range that is a length of l, for i in range(0, len(l), n): # Create an index range for l of n items: yield l[i:i + n]
def get_chunks(l, n): # For item i in a range that is a length of l,
for i in range(0, len(l), n): # Create an index range for l of n items: yield l[i:i + n]
os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu config = tf.ConfigProto() config.gpu_options.allow_growth = True session = tf.Session(config=config) return session def get_chunks(l, n): # For item i in a range that is a length of l,
64
64
55
22
41
widdiot/VGG-Speaker-Recognition
tool/toolkits.py
Python
get_chunks
get_chunks
74
78
74
75
85306a415e62610ffbc2de7875407dac485a3452
bigcode/the-stack
train
fa81a6858a5cb4b54c850ae4
train
function
def get_vggface2_imglist(args): def get_datalist(s): file = open('{}'.format(s), 'r') datalist = file.readlines() imglist = [] labellist = [] for i in datalist: linesplit = i.split(' ') imglist.append(linesplit[0]) labellist.append(int(line...
def get_vggface2_imglist(args):
def get_datalist(s): file = open('{}'.format(s), 'r') datalist = file.readlines() imglist = [] labellist = [] for i in datalist: linesplit = i.split(' ') imglist.append(linesplit[0]) labellist.append(int(linesplit[1][:-1])) return i...
.signal(signal.SIGINT, signal.SIG_IGN) global pool try: pool.terminate() except: pass if processes: pool = mp.Pool(processes=processes, initializer=init_worker) else: pool = None return pool # vggface2 dataset def get_vggface2_imglist(args):
80
80
268
10
69
widdiot/VGG-Speaker-Recognition
tool/toolkits.py
Python
get_vggface2_imglist
get_vggface2_imglist
113
138
113
113
f3ab3e80d0e6cf6719d632010fdefee2068613ac
bigcode/the-stack
train
6a7f3b4522b32faeac4a3659
train
function
def set_mp(processes=8): import multiprocessing as mp def init_worker(): import signal signal.signal(signal.SIGINT, signal.SIG_IGN) global pool try: pool.terminate() except: pass if processes: pool = mp.Pool(processes=processes, initializer=init_worker)...
def set_mp(processes=8):
import multiprocessing as mp def init_worker(): import signal signal.signal(signal.SIGINT, signal.SIG_IGN) global pool try: pool.terminate() except: pass if processes: pool = mp.Pool(processes=processes, initializer=init_worker) else: pool =...
, img in enumerate(G[0]): path = '../sample/{}.jpg'.format(i) img = np.asarray(img[:, :, ::-1] + 128.0, dtype='uint8') cv2.imwrite(path, img) # set up multiprocessing def set_mp(processes=8):
64
64
88
8
55
widdiot/VGG-Speaker-Recognition
tool/toolkits.py
Python
set_mp
set_mp
92
109
92
92
9c8040efe6d21b4f0cf5ab4dcf20e7e8fedbf670
bigcode/the-stack
train
c64b6b161ae82a48abf67d3d
train
function
def load_from_kaldi_dir(args, part, min_len=200, label2idx=None): utt2num_frames = {} with open(os.path.join(args.data_path, part, 'utt2num_frames'), 'r') as f: lines = f.read().splitlines() for l in lines: utt2num_frames[l.split()[0]] = int(l.split()[1]) utt2feat_path = {} w...
def load_from_kaldi_dir(args, part, min_len=200, label2idx=None):
utt2num_frames = {} with open(os.path.join(args.data_path, part, 'utt2num_frames'), 'r') as f: lines = f.read().splitlines() for l in lines: utt2num_frames[l.split()[0]] = int(l.split()[1]) utt2feat_path = {} with open(os.path.join(args.data_path, part, 'feats.scp'), 'r') as ...
import os import numpy as np # trnlist, trnlb = toolkits.get_voxceleb2_datalist(args, path='../meta/voxlb2_train.txt') # vallist, vallb = toolkits.get_voxceleb2_datalist(args, path='../meta/voxlb2_val.txt') def load_from_kaldi_dir(args, part, min_len=200, label2idx=None):
88
177
592
20
68
widdiot/VGG-Speaker-Recognition
tool/toolkits.py
Python
load_from_kaldi_dir
load_from_kaldi_dir
9
61
9
9
cdb9bf08e8c4c0a54146e2973d58c5d5daca90a6
bigcode/the-stack
train
dabf13c0953103f9d9edb2e2
train
function
def initialize_GPU(args): # Initialize GPUs import tensorflow as tf os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu config = tf.ConfigProto() config.gpu_options.allow_growth = True session = tf.Session(config=config) return session
def initialize_GPU(args): # Initialize GPUs
import tensorflow as tf os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu config = tf.ConfigProto() config.gpu_options.allow_growth = True session = tf.Session(config=config) return session
_path[i],utt2post_path[i])) labels.append(label2idx[utt2label[i]]) print("head(X):",data[:4],"\nhead(Y):",labels[:4]) return data, np.array(labels), label2idx def initialize_GPU(args): # Initialize GPUs
64
64
59
10
53
widdiot/VGG-Speaker-Recognition
tool/toolkits.py
Python
initialize_GPU
initialize_GPU
64
71
64
65
cd17d7d2239588529dddef70edf57b70533bc26f
bigcode/the-stack
train
1186ad639f6f46bf2ddeaea8
train
function
def debug_generator(generator): import cv2 import pdb G = generator.next() for i, img in enumerate(G[0]): path = '../sample/{}.jpg'.format(i) img = np.asarray(img[:, :, ::-1] + 128.0, dtype='uint8') cv2.imwrite(path, img)
def debug_generator(generator):
import cv2 import pdb G = generator.next() for i, img in enumerate(G[0]): path = '../sample/{}.jpg'.format(i) img = np.asarray(img[:, :, ::-1] + 128.0, dtype='uint8') cv2.imwrite(path, img)
return session def get_chunks(l, n): # For item i in a range that is a length of l, for i in range(0, len(l), n): # Create an index range for l of n items: yield l[i:i + n] def debug_generator(generator):
64
64
74
5
59
widdiot/VGG-Speaker-Recognition
tool/toolkits.py
Python
debug_generator
debug_generator
81
88
81
81
028ba780abbfdd2bcba74f10d2c9922a97b3af49
bigcode/the-stack
train
f30cd657b97c291367226f69
train
function
def get_imagenet_imglist(args, trn_meta_path='', val_meta_path=''): with open(trn_meta_path) as f: strings = f.readlines() trn_list = np.array([os.path.join(args.data_path, '/'.join(string.split()[0].split(os.sep)[-4:])) for string in strings]) trn_lb = np.array(...
def get_imagenet_imglist(args, trn_meta_path='', val_meta_path=''):
with open(trn_meta_path) as f: strings = f.readlines() trn_list = np.array([os.path.join(args.data_path, '/'.join(string.split()[0].split(os.sep)[-4:])) for string in strings]) trn_lb = np.array([int(string.split()[1]) for string in strings]) f.close() ...
] imgs_list_val = np.array(imgs_list_val) lbs_list_val = np.array(lbs_list_val) return imgs_list_trn, lbs_list_trn, imgs_list_val, lbs_list_val def get_imagenet_imglist(args, trn_meta_path='', val_meta_path=''):
64
64
186
19
44
widdiot/VGG-Speaker-Recognition
tool/toolkits.py
Python
get_imagenet_imglist
get_imagenet_imglist
141
155
141
141
c66c9d15917fdce778fad5889136bec11b3526e4
bigcode/the-stack
train
e592e0d88feecdab37f4fff8
train
function
def calculate_eer(y, y_score): # y denotes groundtruth scores, # y_score denotes the prediction scores. from scipy.optimize import brentq from sklearn.metrics import roc_curve from scipy.interpolate import interp1d fpr, tpr, thresholds = roc_curve(y, y_score, pos_label=1) eer = brentq(lambd...
def calculate_eer(y, y_score): # y denotes groundtruth scores, # y_score denotes the prediction scores.
from scipy.optimize import brentq from sklearn.metrics import roc_curve from scipy.interpolate import interp1d fpr, tpr, thresholds = roc_curve(y, y_score, pos_label=1) eer = brentq(lambda x: 1. - x - interp1d(fpr, tpr)(x), 0., 1.) thresh = interp1d(fpr, thresholds)(eer) return eer, thresh
]) for string in strings]) labellist = np.array([int(string.split()[1]) for string in strings]) f.close() return audiolist, labellist def calculate_eer(y, y_score): # y denotes groundtruth scores, # y_score denotes the prediction scores.
64
64
124
26
37
widdiot/VGG-Speaker-Recognition
tool/toolkits.py
Python
calculate_eer
calculate_eer
167
177
167
169
f7361aeefec74a9aac484921c773f24e128ef5f0
bigcode/the-stack
train
bddb105b5e0aa4045b8455fa
train
function
def get_voxceleb2_datalist(args, path): with open(path) as f: strings = f.readlines() audiolist = np.array([os.path.join(args.data_path, string.split()[0]) for string in strings]) labellist = np.array([int(string.split()[1]) for string in strings]) f.close() return audiolist, lab...
def get_voxceleb2_datalist(args, path):
with open(path) as f: strings = f.readlines() audiolist = np.array([os.path.join(args.data_path, string.split()[0]) for string in strings]) labellist = np.array([int(string.split()[1]) for string in strings]) f.close() return audiolist, labellist
split(os.sep)[-4:])) for string in strings]) val_lb = np.array([int(string.split()[1]) for string in strings]) f.close() return trn_list, trn_lb, val_list, val_lb def get_voxceleb2_datalist(args, path):
64
64
82
12
51
widdiot/VGG-Speaker-Recognition
tool/toolkits.py
Python
get_voxceleb2_datalist
get_voxceleb2_datalist
158
164
158
158
4c760e2a6fead0f4698c5d0b37ff8b5cb7e1c54d
bigcode/the-stack
train
048e12b85a34a60ccbd21236
train
class
class Migration(migrations.Migration): dependencies = [ ('users', '0009_abusereport'), ] operations = [ migrations.RunPython(migrate_is_spam_flag, backwards) ]
class Migration(migrations.Migration):
dependencies = [ ('users', '0009_abusereport'), ] operations = [ migrations.RunPython(migrate_is_spam_flag, backwards) ]
am=True): kwargs = { 'type': 'spam', 'reporter': None, 'profile': profile, 'is_akismet': True } AbuseReport.objects.create(**kwargs) def backwards(apps, schema_editor): pass class Migration(migrations.Migration):
64
64
44
7
56
akatsoulas/vouched-mozillians
mozillians/users/migrations/0010_auto_20160915_0905.py
Python
Migration
Migration
25
33
25
26
0cba0934d4669e7804e93d7f18c5e351e4ba6bba
bigcode/the-stack
train
0a4fd7c9e7fa5fa5b6d51eda
train
function
def migrate_is_spam_flag(apps, schema_editor): UserProfile = apps.get_model('users', 'UserProfile') AbuseReport = apps.get_model('users', 'AbuseReport') for profile in UserProfile.objects.filter(is_spam=True): kwargs = { 'type': 'spam', 'reporter': None, 'profile...
def migrate_is_spam_flag(apps, schema_editor):
UserProfile = apps.get_model('users', 'UserProfile') AbuseReport = apps.get_model('users', 'AbuseReport') for profile in UserProfile.objects.filter(is_spam=True): kwargs = { 'type': 'spam', 'reporter': None, 'profile': profile, 'is_akismet': True ...
# -*- coding: utf-8 -*- from django.db import migrations, models def migrate_is_spam_flag(apps, schema_editor):
29
64
97
12
16
akatsoulas/vouched-mozillians
mozillians/users/migrations/0010_auto_20160915_0905.py
Python
migrate_is_spam_flag
migrate_is_spam_flag
7
18
7
7
581dc8d4a90062109ec772d0d8585dc0c260fc03
bigcode/the-stack
train
2733d733c7c5cae2c2eb7cee
train
function
def backwards(apps, schema_editor): pass
def backwards(apps, schema_editor):
pass
for profile in UserProfile.objects.filter(is_spam=True): kwargs = { 'type': 'spam', 'reporter': None, 'profile': profile, 'is_akismet': True } AbuseReport.objects.create(**kwargs) def backwards(apps, schema_editor):
64
64
11
8
56
akatsoulas/vouched-mozillians
mozillians/users/migrations/0010_auto_20160915_0905.py
Python
backwards
backwards
21
22
21
21
301df2eb244180e17d056ffdba1d5df15f8bbb3d
bigcode/the-stack
train
3d7e302f829cb7ace3b383f5
train
class
class PostgresBaseModel(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) @property def insert_sql_str(self): qry = """ insert into %(table_name)s (%(table_columns)s) values (%(place_holder)s) returning %(key_name)s; """ place_h...
class PostgresBaseModel(object):
def __init__(self, **kwargs): self.__dict__.update(kwargs) @property def insert_sql_str(self): qry = """ insert into %(table_name)s (%(table_columns)s) values (%(place_holder)s) returning %(key_name)s; """ place_holder = ','.join(['%%(%s)s' % x for x ...
class PostgresBaseModel(object):
8
221
739
8
0
greeness/SmartTypes
smarttypes/model/postgres_base_model.py
Python
PostgresBaseModel
PostgresBaseModel
3
93
3
4
873aae075e1f2df0f3dad5499f8be4bccd92bd5c
bigcode/the-stack
train
50e6effa64843586c2dbd89c
train
class
class ProtoClassifier(): def __init__(self, n_way, n_support, n_query): self.n_way = n_way self.n_support = n_support self.n_query = n_query def __call__(self, z_support, y_support, z_query): # Copied from methods/protonet.py "ProtoNet.set_forward()" # y_support is ignor...
class ProtoClassifier():
def __init__(self, n_way, n_support, n_query): self.n_way = n_way self.n_support = n_support self.n_query = n_query def __call__(self, z_support, y_support, z_query): # Copied from methods/protonet.py "ProtoNet.set_forward()" # y_support is ignored (only for compatibilit...
(1) #the shape of z is [n_data, n_dim] # Interpretation of ProtoNet as linear layer (see Snell et al. (2017)) self._set_params(weight=2*z_proto, bias=-torch.norm(z_proto, dim=-1)**2) class ProtoClassifier():
64
64
180
4
60
ojss/c3lr
unsupervised_meta_learning/cdfsl-benchmark/finetune.py
Python
ProtoClassifier
ProtoClassifier
52
67
52
52
d86e35ea329009ffff53fc357da2a39f79725c11
bigcode/the-stack
train
d5b199fc317ad329791395e3
train
function
def finetune(novel_loader, n_query = 15, freeze_backbone = False, n_way = 5, n_support = 5, loadpath = '', adaptation = False, pretrained_dataset = 'miniImagenet', proto_init = False): correct = 0 count = 0 iter_num = len(novel_loader) acc_all = [] with tqdm(enumera...
def finetune(novel_loader, n_query = 15, freeze_backbone = False, n_way = 5, n_support = 5, loadpath = '', adaptation = False, pretrained_dataset = 'miniImagenet', proto_init = False):
correct = 0 count = 0 iter_num = len(novel_loader) acc_all = [] with tqdm(enumerate(novel_loader), total=len(novel_loader)) as pbar: for _, (x, y) in pbar:#, position=1, #leave=False): #######################################################...
set_params(weight=2*z_proto, bias=-torch.norm(z_proto, dim=-1)**2) class ProtoClassifier(): def __init__(self, n_way, n_support, n_query): self.n_way = n_way self.n_support = n_support self.n_query = n_query def __call__(self, z_support, y_support, z_query): # Copied from meth...
256
256
1,260
55
200
ojss/c3lr
unsupervised_meta_learning/cdfsl-benchmark/finetune.py
Python
finetune
finetune
70
218
70
72
9757dd3248bd8cbce9a9d5cd2d5fb834af9f751d
bigcode/the-stack
train
6234b33c8953a7e73c518fdb
train
class
class Classifier(nn.Module): def __init__(self, dim, n_way): super(Classifier, self).__init__() self.fc = nn.Linear(dim, n_way) def forward(self, x): x = self.fc(x) return x def _set_params(self, weight, bias): state_dict = dict(weight=weight, bias=bias) ...
class Classifier(nn.Module):
def __init__(self, dim, n_way): super(Classifier, self).__init__() self.fc = nn.Linear(dim, n_way) def forward(self, x): x = self.fc(x) return x def _set_params(self, weight, bias): state_dict = dict(weight=weight, bias=bias) self.fc.load_state_dict...
from utils import * from datasets import ISIC_few_shot, EuroSAT_few_shot, CropDisease_few_shot, Chest_few_shot from tqdm import tqdm import sys sys.path.append('..') from methods.protonet import euclidean_dist class Classifier(nn.Module):
64
64
214
6
57
ojss/c3lr
unsupervised_meta_learning/cdfsl-benchmark/finetune.py
Python
Classifier
Classifier
29
49
29
29
5a9c3ef879d9102128af48818746682c65713fea
bigcode/the-stack
train
f1fada489a1aa08dee682b6c
train
class
class Solution: """ @param heights: a list of integers @return: a integer """ def trapRainWater(self, heights): # write your code here if not heights: return 0 left, right = 0, len(heights) - 1 leftMax, rightMax = 0, 0 result = 0 while le...
class Solution:
""" @param heights: a list of integers @return: a integer """ def trapRainWater(self, heights): # write your code here if not heights: return 0 left, right = 0, len(heights) - 1 leftMax, rightMax = 0, 0 result = 0 while left < right: ...
class Solution:
3
64
163
3
0
Zhenye-Na/LxxxCode
Medium/363. Trapping Rain Water/Solution.py
Python
Solution
Solution
1
25
1
1
6eefb5cc2bb4a69368871c5dd399e08b9d72b5ee
bigcode/the-stack
train
3b165695dcd039f775803a2b
train
class
class EC2Checker(RemoteMachineChecker): def __init__(self, host: str, port: Union[str, int]): super(EC2Checker, self).__init__() return self.ping_nlp(host, int(port))[host] is not None def ping_nlp( self, hostname: str, port: int = 9000, timeout: float = 1.0 ) -> Dict[str, Optional[...
class EC2Checker(RemoteMachineChecker):
def __init__(self, host: str, port: Union[str, int]): super(EC2Checker, self).__init__() return self.ping_nlp(host, int(port))[host] is not None def ping_nlp( self, hostname: str, port: int = 9000, timeout: float = 1.0 ) -> Dict[str, Optional[float]]: start = timer() ...
# coding=utf-8 """ EC2 machine checker based on RemoteMachineChecker class """ import socket from typing import Dict, Optional, Union from is_it_up.remote_machine import RemoteMachineChecker _ = Dict, Union, Optional class EC2Checker(RemoteMachineChecker):
59
64
200
9
49
eng1nerd/is_it_up
is_it_up/ec2.py
Python
EC2Checker
EC2Checker
13
36
13
13
fef0d4f61c5936fcd538adfdfa062d2bba7cfe62
bigcode/the-stack
train
d247e63ecf08351f1e52cbe0
train
class
class BoothModel(Document): """ 부스에 관한 정보가 담겨있는 Collection """ meta = { "collection": "booth" } game: GameModel = ReferenceField( document_type=GameModel, required=True, reverse_delete_rule=CASCADE ) booth_name = StringField( primary_key=True...
class BoothModel(Document):
""" 부스에 관한 정보가 담겨있는 Collection """ meta = { "collection": "booth" } game: GameModel = ReferenceField( document_type=GameModel, required=True, reverse_delete_rule=CASCADE ) booth_name = StringField( primary_key=True, required=True ...
from mongoengine import * from datetime import datetime from model.game import GameModel from model.team import TeamModel class BoothModel(Document):
29
64
131
5
23
DSM-Undefined/Get-Terra-Server
Server/model/booth.py
Python
BoothModel
BoothModel
8
34
8
8
543576ad4de8bc7172285911890fea6b5c49ce05
bigcode/the-stack
train
c14dd27eab4086a9296a30a7
train
class
class AvailableResourceGroupDelegationsOperations(object): """AvailableResourceGroupDelegationsOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deser...
class AvailableResourceGroupDelegationsOperations(object):
"""AvailableResourceGroupDelegationsOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. :ivar api_version: Client API version. Constan...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
113
240
802
9
103
JonathanGailliez/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2018_10_01/operations/available_resource_group_delegations_operations.py
Python
AvailableResourceGroupDelegationsOperations
AvailableResourceGroupDelegationsOperations
19
109
19
19
f2544651a1e8fedc2e0634c572d4040e79002d4b
bigcode/the-stack
train
7badf177a84b7c8ef1c9ac52
train
function
def generate_random_spacings(nodes, length=25, alpha=2): """ Generates random spacing according to Dirichlet distribution. The Dirichlet alpha parameter sets how close spacings are to 1/N; higher alpha values are more evenly spaced, while lower alpha values are less evenly spaced (more random). Thi...
def generate_random_spacings(nodes, length=25, alpha=2):
""" Generates random spacing according to Dirichlet distribution. The Dirichlet alpha parameter sets how close spacings are to 1/N; higher alpha values are more evenly spaced, while lower alpha values are less evenly spaced (more random). This algorithm defaults to alpha = 2. The length parame...
/wiki/Dirichlet_distribution#String_cutting for an example of how the Dirichlet distribution is used. .. moduleauthor:: Scott Griffiths <stgriffi@ra.rockwell.com> """ import numpy as np def generate_random_spacings(nodes, length=25, alpha=2):
64
64
205
16
47
SPE-MD/SPMD-Simulations
Rockwell_Automation/generate_random_node_spacings.py
Python
generate_random_spacings
generate_random_spacings
18
36
18
18
5ac01718997824bb3ed742658408160575bce7f5
bigcode/the-stack
train
63eecc277850f5449b7e88d9
train
class
class AlipayIserviceCognitiveInvoicesInferenceQueryModel(object): def __init__(self): self._img_content = None @property def img_content(self): return self._img_content @img_content.setter def img_content(self, value): self._img_content = value def to_alipay_dict(sel...
class AlipayIserviceCognitiveInvoicesInferenceQueryModel(object):
def __init__(self): self._img_content = None @property def img_content(self): return self._img_content @img_content.setter def img_content(self, value): self._img_content = value def to_alipay_dict(self): params = dict() if self.img_content: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.constant.ParamConstants import * class AlipayIserviceCognitiveInvoicesInferenceQueryModel(object):
44
64
190
13
31
articuly/alipay-sdk-python-all
alipay/aop/api/domain/AlipayIserviceCognitiveInvoicesInferenceQueryModel.py
Python
AlipayIserviceCognitiveInvoicesInferenceQueryModel
AlipayIserviceCognitiveInvoicesInferenceQueryModel
8
38
8
9
b8099b99aec08f026a6d755ae38cf2c7269e6bd1
bigcode/the-stack
train
31692fa45dcdde17cabb4367
train
function
def fill_map_counts(counts_map, events): """Fill events into a counts map. This method handles sky coordinates automatically. For all other map axes, an event list table column with the same name has to be present (case-insensitive compare), or a KeyError will be raised. Note that this function is...
def fill_map_counts(counts_map, events):
"""Fill events into a counts map. This method handles sky coordinates automatically. For all other map axes, an event list table column with the same name has to be present (case-insensitive compare), or a KeyError will be raised. Note that this function is just a thin wrapper around the sky map ...
# Licensed under a 3-clause BSD style license - see LICENSE.rst from astropy.units import Quantity __all__ = ["fill_map_counts"] def fill_map_counts(counts_map, events):
43
176
588
10
33
watsonjj/gammapy
gammapy/cube/counts.py
Python
fill_map_counts
fill_map_counts
7
63
7
7
dea78cc6580fb5909902bdcc614ebb82d9007e6f
bigcode/the-stack
train
593b197f1f4350d19533841d
train
class
class ScrollContainerApp(toga.App): vscrolling = True hscrolling = False scroller = None def startup(self): box = toga.Box() box.style.direction = COLUMN box.style.padding = 10 self.scroller = toga.ScrollContainer(horizontal=self.hscrolling, vertical=self.vscrolling) ...
class ScrollContainerApp(toga.App):
vscrolling = True hscrolling = False scroller = None def startup(self): box = toga.Box() box.style.direction = COLUMN box.style.padding = 10 self.scroller = toga.ScrollContainer(horizontal=self.hscrolling, vertical=self.vscrolling) switch_box = toga.Box(style=Pac...
oga.Box): def __init__(self, text): super().__init__(style=Pack(direction=COLUMN)) row = toga.Box(style=Pack(direction=ROW)) for x in range(10): label = toga.Label(text+", "+str(x), style=Pack(padding_right=10)) row.add(label) self.add(row) class ScrollContai...
82
82
275
8
74
rknuus/toga
examples/scrollcontainer/scrollcontainer/app.py
Python
ScrollContainerApp
ScrollContainerApp
17
48
17
17
dd4bb3e9b8022bb023e786f9fc99414ac871c2fb
bigcode/the-stack
train
69862429450b4b8e48478331
train
class
class Item(toga.Box): def __init__(self, text): super().__init__(style=Pack(direction=COLUMN)) row = toga.Box(style=Pack(direction=ROW)) for x in range(10): label = toga.Label(text+", "+str(x), style=Pack(padding_right=10)) row.add(label) self.add(row)
class Item(toga.Box):
def __init__(self, text): super().__init__(style=Pack(direction=COLUMN)) row = toga.Box(style=Pack(direction=ROW)) for x in range(10): label = toga.Label(text+", "+str(x), style=Pack(padding_right=10)) row.add(label) self.add(row)
import toga from toga.constants import COLUMN, ROW from toga.style import Pack class Item(toga.Box):
23
64
77
6
16
rknuus/toga
examples/scrollcontainer/scrollcontainer/app.py
Python
Item
Item
6
14
6
6
511279b4f1a2cb02f776745df2aacf18b26616c8
bigcode/the-stack
train
0a3a4785e0781f3a64fc3da7
train
function
def main(): return ScrollContainerApp('ScrollContainer', 'org.beeware.widgets.scrollcontainer')
def main():
return ScrollContainerApp('ScrollContainer', 'org.beeware.widgets.scrollcontainer')
def handle_hscrolling(self, widget): self.hscrolling = widget.is_on self.scroller.horizontal = self.hscrolling def handle_vscrolling(self, widget): self.vscrolling = widget.is_on self.scroller.vertical = self.vscrolling def main():
64
64
21
3
60
rknuus/toga
examples/scrollcontainer/scrollcontainer/app.py
Python
main
main
51
52
51
51
ed9767038f944aaa17a73592532590c8ba0fe03e
bigcode/the-stack
train
a4e84a710e6e295634ae37c6
train
class
class TypeWithDefault(type): def __init__(cls, name, bases, dct): super(TypeWithDefault, cls).__init__(name, bases, dct) cls._default = None def __call__(cls): if cls._default is None: cls._default = type.__call__(cls) return copy.copy(cls._default) def set_defa...
class TypeWithDefault(type):
def __init__(cls, name, bases, dct): super(TypeWithDefault, cls).__init__(name, bases, dct) cls._default = None def __call__(cls): if cls._default is None: cls._default = type.__call__(cls) return copy.copy(cls._default) def set_default(cls, default): cl...
.1.3 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import copy import logging import multiprocessing import sys import urllib3 import six from six.moves import http_client as httplib class TypeWithDefault(type):
64
64
95
6
57
solvice/solvice-routing-client
clients/python/SolviceRoutingClient/configuration.py
Python
TypeWithDefault
TypeWithDefault
25
36
25
25
1a93fb8d1c9116f1d902e5db717c8d6ea6f93373
bigcode/the-stack
train
50b4f5c56400e5e206305b5e
train
class
class Configuration(six.with_metaclass(TypeWithDefault, object)): """NOTE: This class is auto generated by the swagger code generator program. Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. """ def __init__(self): """Constructor""" # Default Bas...
class Configuration(six.with_metaclass(TypeWithDefault, object)):
"""NOTE: This class is auto generated by the swagger code generator program. Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. """ def __init__(self): """Constructor""" # Default Base url self.host = "https://api.solvice.io/" # Temp...
# coding: utf-8 """ OnRoute API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 1.1.3 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import cop...
214
256
1,482
13
201
solvice/solvice-routing-client
clients/python/SolviceRoutingClient/configuration.py
Python
Configuration
Configuration
39
244
39
39
c9f7eed01c5c211be6a3842fcf0d7d42565a1a12
bigcode/the-stack
train
6b537c174a7e06259b8c8a9d
train
function
def main(): if not opengl_init(): return # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) glfw.set_cursor_pos(window, 1024/2, 768/2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0,0.0,0.4,0.0) ...
def main():
if not opengl_init(): return # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) glfw.set_cursor_pos(window, 1024/2, 768/2) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0,0.0,0.4,0.0) # Enable dep...
im.size[0], im.size[1], im.tostring("raw", "RGBA", 0, -1) except SystemError: width,height,image = im.size[0], im.size[1], im.tostring("raw", "RGBX", 0, -1) texture_id = glGenTextures(1) # To use OpenGL 4.2 ARB_texture_storage to automatically generate a single mipmap layer # uncomment the 3...
256
256
2,263
3
252
geraldzakwan/ITBMaps
tutorial6.py
Python
main
main
120
308
120
120
b31077e473ea5e0e22750592586d641eb74868a7
bigcode/the-stack
train
53d18ce499c3da21d7cff435
train
function
def load_image(file_name): im = pil_open(file_name) try: width,height,image = im.size[0], im.size[1], im.tostring("raw", "RGBA", 0, -1) except SystemError: width,height,image = im.size[0], im.size[1], im.tostring("raw", "RGBX", 0, -1) texture_id = glGenTextures(1) # To use OpenGL ...
def load_image(file_name):
im = pil_open(file_name) try: width,height,image = im.size[0], im.size[1], im.tostring("raw", "RGBA", 0, -1) except SystemError: width,height,image = im.size[0], im.size[1], im.tostring("raw", "RGBX", 0, -1) texture_id = glGenTextures(1) # To use OpenGL 4.2 ARB_texture_storage to ...
_TEXTURE_BASE_LEVEL, 0) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0) else: glBindTexture(GL_TEXTURE_2D, texture_id) glPixelStorei(GL_UNPACK_ALIGNMENT,1) # Generate mipmaps? Doesn't seem to work glGenerateMipmap(GL_TEXTURE_2D) def load_image(file_name):
82
82
275
6
76
geraldzakwan/ITBMaps
tutorial6.py
Python
load_image
load_image
97
118
97
97
c576456ed0d89c782e25f11b26ac6f1c97f982fc
bigcode/the-stack
train
46ccb293d1990361a12e5815
train
function
def opengl_init(): global window # Initialize the library if not glfw.init(): print("Failed to initialize GLFW\n",file=sys.stderr) return False # Open Window and create its OpenGL context window = glfw.create_window(1024, 768, "Tutorial 06", None, None) #(in the accompanying source ...
def opengl_init():
global window # Initialize the library if not glfw.init(): print("Failed to initialize GLFW\n",file=sys.stderr) return False # Open Window and create its OpenGL context window = glfw.create_window(1024, 768, "Tutorial 06", None, None) #(in the accompanying source code this variable ...
* from OpenGL.GLU import * from OpenGL.GLUT import * from OpenGL.GLUT.special import * from OpenGL.GL.shaders import * from glew_wish import * from csgl import * from PIL.Image import open as pil_open import common import glfw import sys import os import controls # Global window window = None null = c_void_p(0) def ...
89
89
298
5
84
geraldzakwan/ITBMaps
tutorial6.py
Python
opengl_init
opengl_init
28
57
28
28
c9b1e975e3f3741f0540d76acd4dd8ef07bfea5f
bigcode/the-stack
train
5a3c45df0e91162fb01429cc
train
function
def bind_texture(texture_id,mode): """ Bind texture_id using several different modes Notes: Without mipmapping the texture is incomplete and requires additional constraints on OpenGL to properly render said texture. Use 'MIN_FILTER" or 'MAX_LEVEL' to render ...
def bind_texture(texture_id,mode):
""" Bind texture_id using several different modes Notes: Without mipmapping the texture is incomplete and requires additional constraints on OpenGL to properly render said texture. Use 'MIN_FILTER" or 'MAX_LEVEL' to render a generic texture with ...
2.1 version of the tutorials.\n",file=sys.stderr) glfw.terminate() return False # Initialize GLEW glfw.make_context_current(window) glewExperimental = True # GLEW is a framework for testing extension availability. Please see tutorial notes for # more information including why can ...
119
119
397
8
110
geraldzakwan/ITBMaps
tutorial6.py
Python
bind_texture
bind_texture
59
95
59
59
1a17e4508ea884ccfe7f5c542a714954ee52cd72
bigcode/the-stack
train
90cc3b99b677019aa56e0189
train
class
class LearnManipulation: def __init__(self, args): # --------------- Setup options --------------- self.is_sim = args.is_sim sim_port = args.sim_port obj_mesh_dir = os.path.abspath(args.obj_mesh_dir) if self.is_sim else None num_obj = args.num_obj if self.is_sim else None ...
class LearnManipulation:
def __init__(self, args): # --------------- Setup options --------------- self.is_sim = args.is_sim sim_port = args.sim_port obj_mesh_dir = os.path.abspath(args.obj_mesh_dir) if self.is_sim else None num_obj = args.num_obj if self.is_sim else None # Cols: min max, Row...
#!/usr/bin/env python import argparse import concurrent.futures import logging import os import re import threading import time import cv2 import numpy as np import tensorboardX import torch from scipy import ndimage from robot import SimRobot from trainer import Trainer from utils import utils, viz from utils.logge...
81
256
6,411
5
75
skumra/romannet
main.py
Python
LearnManipulation
LearnManipulation
23
633
23
23
376c6c84e6dbae6666c3d0355c3e835ec43bf8df
bigcode/the-stack
train
5c5ae5d915b2f620eab72dc6
train
function
def condition_document_creation_access(context, resolved_object): AccessControlList = apps.get_model( app_label='acls', model_name='AccessControlList' ) DocumentType = apps.get_model( app_label='documents', model_name='DocumentType' ) Source = apps.get_model( app_label='sourc...
def condition_document_creation_access(context, resolved_object):
AccessControlList = apps.get_model( app_label='acls', model_name='AccessControlList' ) DocumentType = apps.get_model( app_label='documents', model_name='DocumentType' ) Source = apps.get_model( app_label='sources', model_name='Source' ) document_type_access = AccessC...
permission_sources_view ) logger = logging.getLogger(name=__name__) def factory_conditional_active_by_source(source): def conditional_active_by_source(context, resolved_link): return context.get('source', None) == source return conditional_active_by_source def condition_document_creation_access(con...
64
64
158
10
53
bonitobonita24/Mayan-EDMS
mayan/apps/sources/links.py
Python
condition_document_creation_access
condition_document_creation_access
31
52
31
31
2045c27a449ed848c64878dccf5ea3f63e5f7d23
bigcode/the-stack
train
91bf5a8db04ff4f9077b220e
train
function
def factory_conditional_active_by_source(source): def conditional_active_by_source(context, resolved_link): return context.get('source', None) == source return conditional_active_by_source
def factory_conditional_active_by_source(source):
def conditional_active_by_source(context, resolved_link): return context.get('source', None) == source return conditional_active_by_source
_backend_selection, icon_source_test, icon_source_delete, icon_source_edit, icon_source_list, ) from .permissions import ( permission_sources_create, permission_sources_delete, permission_sources_edit, permission_sources_view ) logger = logging.getLogger(name=__name__) def factory_conditional_active_by_sou...
64
64
39
9
55
bonitobonita24/Mayan-EDMS
mayan/apps/sources/links.py
Python
factory_conditional_active_by_source
factory_conditional_active_by_source
24
28
24
24
dffca25e3d2897e1a2d945c0349e37a5cdc6120b
bigcode/the-stack
train
f8b7e586fc805bc031d22a22
train
function
def condition_source_is_not_interactive(context, resolved_object): source = context.get('resolved_object', None) if source: return not getattr(source.get_backend(), 'is_interactive', False)
def condition_source_is_not_interactive(context, resolved_object):
source = context.get('resolved_object', None) if source: return not getattr(source.get_backend(), 'is_interactive', False)
).exists() source_access = AccessControlList.objects.restrict_queryset( permission=permission_document_file_new, queryset=Source.objects.all(), user=context.request.user ).exists() return new_document_files_allowed and document_access and source_access def condition_so...
64
64
42
12
51
bonitobonita24/Mayan-EDMS
mayan/apps/sources/links.py
Python
condition_source_is_not_interactive
condition_source_is_not_interactive
101
104
101
101
ca3efac8859932529ede630f11d073b593fd38f0
bigcode/the-stack
train
3561bda149868373159f2eed
train
function
def condition_document_new_files_allowed(context, resolved_object): if resolved_object: AccessControlList = apps.get_model( app_label='acls', model_name='AccessControlList' ) Document = apps.get_model( app_label='documents', model_name='Document' ) Doc...
def condition_document_new_files_allowed(context, resolved_object):
if resolved_object: AccessControlList = apps.get_model( app_label='acls', model_name='AccessControlList' ) Document = apps.get_model( app_label='documents', model_name='Document' ) DocumentFile = apps.get_model( app_label='documents', model...
List.objects.restrict_queryset( permission=permission_document_create, queryset=DocumentType.objects.all(), user=context.request.user ).exists() source_access = AccessControlList.objects.restrict_queryset( permission=permission_document_create, queryset=Source.objects.all(), use...
85
85
284
11
73
bonitobonita24/Mayan-EDMS
mayan/apps/sources/links.py
Python
condition_document_new_files_allowed
condition_document_new_files_allowed
55
98
55
55
40ec5e6054a3c5229b57dfcd3321b6ae44bed515
bigcode/the-stack
train
1f2ae2be5c7a354613b8fc83
train
class
class DatesTests(TestCase): def test_related_model_traverse(self): a1 = Article.objects.create( title="First one", pub_date=datetime(2005, 7, 28), ) a2 = Article.objects.create( title="Another one", pub_date=datetime(2010, 7, 28), ) ...
class DatesTests(TestCase):
def test_related_model_traverse(self): a1 = Article.objects.create( title="First one", pub_date=datetime(2005, 7, 28), ) a2 = Article.objects.create( title="Another one", pub_date=datetime(2010, 7, 28), ) a3 = Article.objects.cr...
from __future__ import absolute_import from datetime import datetime from django.test import TestCase from .models import Article, Comment, Category class DatesTests(TestCase):
36
170
567
6
29
kix/django
tests/regressiontests/dates/tests.py
Python
DatesTests
DatesTests
10
83
10
10
235bf4af9438ddb58a0076789f5c7846ead0a234
bigcode/the-stack
train
1b7642120f014fcb44e11d29
train
class
class TestTruncatedNormalUpperArray(BaseTestDistribution): pymc_dist = pm.TruncatedNormal lower, upper, mu, tau = ( np.array([-np.inf, -np.inf]), np.array([3, 2]), np.array([0, 0]), np.array( [ 1, 1, ] ), ) s...
class TestTruncatedNormalUpperArray(BaseTestDistribution):
pymc_dist = pm.TruncatedNormal lower, upper, mu, tau = ( np.array([-np.inf, -np.inf]), np.array([3, 2]), np.array([0, 0]), np.array( [ 1, 1, ] ), ) size = (15, 2) tau, sigma = get_tau_sigma(tau=tau, sigma...
"upper": upper} expected_rv_op_params = {"mu": mu, "sigma": sigma, "lower": lower, "upper": upper} tests_to_run = [ "check_pymc_params_match_rv_op", ] class TestTruncatedNormalUpperArray(BaseTestDistribution):
63
64
173
11
52
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestTruncatedNormalUpperArray
TestTruncatedNormalUpperArray
669
688
669
669
29b188cf7cd62b7170bafd9e238dae18a20f2449
bigcode/the-stack
train
fcbabbb2c7833468190e0dd7
train
class
class TestNestedRandom(SeededTest): def build_model(self, distribution, shape, nested_rvs_info): with pm.Model() as model: nested_rvs = {} for rv_name, info in nested_rvs_info.items(): try: value, nested_shape = info loc = 0.0 ...
class TestNestedRandom(SeededTest):
def build_model(self, distribution, shape, nested_rvs_info): with pm.Model() as model: nested_rvs = {} for rv_name, info in nested_rvs_info.items(): try: value, nested_shape = info loc = 0.0 except ValueError: ...
observed=np.random.randn(100), initval=0, ) idata = pm.sample(tune=50, draws=100, cores=1, step=pm.Metropolis()) samples = 500 with pytest.raises(NotImplementedError): pm.sample_posterior_predictive(idata, samples=samples, model=model,...
255
256
2,007
9
246
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestNestedRandom
TestNestedRandom
1,893
2,176
1,893
1,893
ed8b6c0e84a3d3e7f1b65779d5a85a9d96dd83bd
bigcode/the-stack
train
ca4d8566c3853e8461fe5fde
train
function
@pytest.mark.parametrize("sparse", [True, False]) def test_car_rng_fn(sparse): delta = 0.05 # limit for KS p-value n_fails = 20 # Allows the KS fails a certain number of times size = (100,) W = np.array( [[0.0, 1.0, 1.0, 0.0], [1.0, 0.0, 0.0, 1.0], [1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 1.0, 0.0]] ...
@pytest.mark.parametrize("sparse", [True, False]) def test_car_rng_fn(sparse):
delta = 0.05 # limit for KS p-value n_fails = 20 # Allows the KS fails a certain number of times size = (100,) W = np.array( [[0.0, 1.0, 1.0, 0.0], [1.0, 0.0, 0.0, 1.0], [1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 1.0, 0.0]] ) tau = 2 alpha = 0.5 mu = np.array([1, 1, 1, 1]) D = W.s...
(1.0, shape=3) chol, corr, stds = pm.LKJCholeskyCov( "chol_cov", n=3, eta=2, sd_dist=sd_dist, compute_corr=True ) mv = pm.MvGaussianRandomWalk("mv", mu, cov=pm.math.dot(chol, chol.T), shape=dist_shape) prior = pm.sample_prior_predictive(samples=sample_shap...
131
131
437
20
110
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
test_car_rng_fn
test_car_rng_fn
2,360
2,397
2,360
2,361
8d4e302c285f789ad160c29038b03bd0fbc706fc
bigcode/the-stack
train
e8228a06f30f5c98aa5a94ef
train
class
class TestWaldMuPhi(BaseTestDistribution): pymc_dist = pm.Wald mu, phi, alpha = 1.0, 3.0, 0.0 mu_rv, lam_rv, phi_rv = pm.Wald.get_mu_lam_phi(mu=mu, lam=None, phi=phi) pymc_dist_params = {"mu": mu, "phi": phi, "alpha": alpha} expected_rv_op_params = {"mu": mu_rv, "lam": lam_rv, "alpha": alpha} te...
class TestWaldMuPhi(BaseTestDistribution):
pymc_dist = pm.Wald mu, phi, alpha = 1.0, 3.0, 0.0 mu_rv, lam_rv, phi_rv = pm.Wald.get_mu_lam_phi(mu=mu, lam=None, phi=phi) pymc_dist_params = {"mu": mu, "phi": phi, "alpha": alpha} expected_rv_op_params = {"mu": mu_rv, "lam": lam_rv, "alpha": alpha} tests_to_run = [ "check_pymc_params_m...
_run: getattr(self, check_name)() def check_pymc_draws_match_reference(self): assert_array_almost_equal( self.pymc_rv.eval(), self.reference_dist_draws + self.alpha, decimal=self.decimal ) class TestWaldMuPhi(BaseTestDistribution):
64
64
140
10
54
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestWaldMuPhi
TestWaldMuPhi
721
729
721
721
38453f40a6680503dfced3efff6c890b3ae43314
bigcode/the-stack
train
aa4fcf34aa6a1d2d31e9619e
train
class
class TestLogistic(BaseTestDistribution): pymc_dist = pm.Logistic pymc_dist_params = {"mu": 1.0, "s": 2.0} expected_rv_op_params = {"mu": 1.0, "s": 2.0} tests_to_run = ["check_pymc_params_match_rv_op"]
class TestLogistic(BaseTestDistribution):
pymc_dist = pm.Logistic pymc_dist_params = {"mu": 1.0, "s": 2.0} expected_rv_op_params = {"mu": 1.0, "s": 2.0} tests_to_run = ["check_pymc_params_match_rv_op"]
reference_dist_params = expected_rv_op_params reference_dist = seeded_numpy_distribution_builder("hypergeometric") tests_to_run = [ "check_pymc_params_match_rv_op", "check_pymc_draws_match_reference", ] class TestLogistic(BaseTestDistribution):
63
64
78
8
55
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestLogistic
TestLogistic
1,267
1,271
1,267
1,267
a6faf423a74093413578517d2798fda8807a8757
bigcode/the-stack
train
44df710f79311e7782353f3c
train
class
class TestFlat(BaseTestDistribution): pymc_dist = pm.Flat pymc_dist_params = {} expected_rv_op_params = {} tests_to_run = [ "check_pymc_params_match_rv_op", "check_rv_size", "check_not_implemented", ] def check_not_implemented(self): with pytest.raises(NotImpleme...
class TestFlat(BaseTestDistribution):
pymc_dist = pm.Flat pymc_dist_params = {} expected_rv_op_params = {} tests_to_run = [ "check_pymc_params_match_rv_op", "check_rv_size", "check_not_implemented", ] def check_not_implemented(self): with pytest.raises(NotImplementedError): self.pymc_rv.e...
getattr(st, dist_name).rvs, random_state=self.get_random_state() ) def seeded_numpy_distribution_builder(dist_name: str) -> Callable: return lambda self: functools.partial( getattr(np.random.RandomState, dist_name), self.get_random_state() ) class TestFlat(BaseTestDistribution):
64
64
89
7
57
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestFlat
TestFlat
421
433
421
421
2de6d0d245cfddec4bf367944726db571efb9a09
bigcode/the-stack
train
8d62fce7754dc3e102a88431
train
class
class TestKumaraswamy(BaseTestDistribution): def kumaraswamy_rng_fn(self, a, b, size, uniform_rng_fct): return (1 - (1 - uniform_rng_fct(size=size)) ** (1 / b)) ** (1 / a) def seeded_kumaraswamy_rng_fn(self): uniform_rng_fct = functools.partial( getattr(np.random.RandomState, "unifo...
class TestKumaraswamy(BaseTestDistribution):
def kumaraswamy_rng_fn(self, a, b, size, uniform_rng_fct): return (1 - (1 - uniform_rng_fct(size=size)) ** (1 / b)) ** (1 / a) def seeded_kumaraswamy_rng_fn(self): uniform_rng_fct = functools.partial( getattr(np.random.RandomState, "uniform"), self.get_random_state() ) ...
0, "scale": 1.0} reference_dist = seeded_scipy_distribution_builder("moyal") tests_to_run = [ "check_pymc_params_match_rv_op", "check_pymc_draws_match_reference", "check_rv_size", ] class TestKumaraswamy(BaseTestDistribution):
73
74
249
11
62
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestKumaraswamy
TestKumaraswamy
595
614
595
595
b121fe52d10506bde218eb9a8f0ac638b7d2815a
bigcode/the-stack
train
8ed533d1f72964bc331b9376
train
function
@pytest.mark.xfail(reason="This distribution has not been refactored for v4") def test_matrix_normal_random_with_random_variables(): """ This test checks for shape correctness when using MatrixNormal distribution with parameters as random variables. Originally reported - https://github.com/pymc-devs/pym...
@pytest.mark.xfail(reason="This distribution has not been refactored for v4") def test_matrix_normal_random_with_random_variables():
""" This test checks for shape correctness when using MatrixNormal distribution with parameters as random variables. Originally reported - https://github.com/pymc-devs/pymc/issues/3585 """ K = 3 D = 15 mu_0 = np.zeros((D, K)) lambd = 1.0 with pm.Model() as model: sd_dist ...
, shape=2) y = pm.Deterministic("y", pm.math.dot(X, betas)) prior_pred = pm.sample_prior_predictive(1) assert prior_pred["X"].shape == (1, N, 2) @pytest.mark.xfail(reason="This distribution has not been refactored for v4") def test_matrix_normal_random_with_random_variables():
79
79
266
27
52
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
test_matrix_normal_random_with_random_variables
test_matrix_normal_random_with_random_variables
2,285
2,306
2,285
2,286
a1329d13d5d084c5b7fc6ed71577d9a516bff61b
bigcode/the-stack
train
6848e8baaec0f22ae96037f1
train
class
class TestChiSquared(BaseTestDistribution): pymc_dist = pm.ChiSquared pymc_dist_params = {"nu": 2.0} expected_rv_op_params = {"nu": 2.0} reference_dist_params = {"df": 2.0} reference_dist = seeded_numpy_distribution_builder("chisquare") tests_to_run = [ "check_pymc_params_match_rv_op", ...
class TestChiSquared(BaseTestDistribution):
pymc_dist = pm.ChiSquared pymc_dist_params = {"nu": 2.0} expected_rv_op_params = {"nu": 2.0} reference_dist_params = {"df": 2.0} reference_dist = seeded_numpy_distribution_builder("chisquare") tests_to_run = [ "check_pymc_params_match_rv_op", "check_pymc_draws_match_reference", ...
=pymc_dist_params["mu"], sigma=pymc_dist_params["sigma"], ) expected_rv_op_params = {"alpha": expected_alpha, "beta": expected_beta} tests_to_run = ["check_pymc_params_match_rv_op"] class TestChiSquared(BaseTestDistribution):
63
64
110
8
55
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestChiSquared
TestChiSquared
983
993
983
983
80680cd50e7c547c17e0d012ae8f0cdeec25677d
bigcode/the-stack
train
9352208d98ec224f08ce4182
train
class
class TestMvStudentTCov(BaseTestDistribution): def mvstudentt_rng_fn(self, size, nu, mu, cov, rng): chi2_samples = rng.chisquare(nu, size=size) mv_samples = rng.multivariate_normal(np.zeros_like(mu), cov, size=size) return (mv_samples / np.sqrt(chi2_samples[:, None] / nu)) + mu pymc_dis...
class TestMvStudentTCov(BaseTestDistribution):
def mvstudentt_rng_fn(self, size, nu, mu, cov, rng): chi2_samples = rng.chisquare(nu, size=size) mv_samples = rng.multivariate_normal(np.zeros_like(mu), cov, size=size) return (mv_samples / np.sqrt(chi2_samples[:, None] / nu)) + mu pymc_dist = pm.MvStudentT pymc_dist_params = { ...
([1.0, 2.0]), "tau": np.array([[2.0, 0.0], [0.0, 3.5]]), } expected_rv_op_params = { "mu": np.array([1.0, 2.0]), "cov": quaddist_matrix(tau=pymc_dist_params["tau"]).eval(), } tests_to_run = ["check_pymc_params_match_rv_op"] class TestMvStudentTCov(BaseTestDistribution):
111
112
374
10
101
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestMvStudentTCov
TestMvStudentTCov
1,099
1,130
1,099
1,099
9ddeffe4b63fa770bcfaf599ac8f1cce3fcdd7cd
bigcode/the-stack
train
e04310c20d74f179d5db3023
train
class
class TestWald(BaseTestDistribution): pymc_dist = pm.Wald mu, lam, alpha = 1.0, 1.0, 0.0 mu_rv, lam_rv, phi_rv = pm.Wald.get_mu_lam_phi(mu=mu, lam=lam, phi=None) pymc_dist_params = {"mu": mu, "lam": lam, "alpha": alpha} expected_rv_op_params = {"mu": mu_rv, "lam": lam_rv, "alpha": alpha} referen...
class TestWald(BaseTestDistribution):
pymc_dist = pm.Wald mu, lam, alpha = 1.0, 1.0, 0.0 mu_rv, lam_rv, phi_rv = pm.Wald.get_mu_lam_phi(mu=mu, lam=lam, phi=None) pymc_dist_params = {"mu": mu, "lam": lam, "alpha": alpha} expected_rv_op_params = {"mu": mu_rv, "lam": lam_rv, "alpha": alpha} reference_dist_params = [mu, lam_rv] refe...
get_tau_sigma(tau=tau, sigma=None) pymc_dist_params = {"mu": mu, "tau": tau, "upper": upper} expected_rv_op_params = {"mu": mu, "sigma": sigma, "lower": lower, "upper": upper} tests_to_run = [ "check_pymc_params_match_rv_op", ] class TestWald(BaseTestDistribution):
87
88
296
8
79
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestWald
TestWald
691
718
691
691
ce466c57fbf72308e47e5291e56175701df77dd8
bigcode/the-stack
train
f1f0a7cab036466a62617a9d
train
class
class TestHalfFlat(BaseTestDistribution): pymc_dist = pm.HalfFlat pymc_dist_params = {} expected_rv_op_params = {} tests_to_run = [ "check_pymc_params_match_rv_op", "check_rv_size", "check_not_implemented", ] def check_not_implemented(self): with pytest.raises(No...
class TestHalfFlat(BaseTestDistribution):
pymc_dist = pm.HalfFlat pymc_dist_params = {} expected_rv_op_params = {} tests_to_run = [ "check_pymc_params_match_rv_op", "check_rv_size", "check_not_implemented", ] def check_not_implemented(self): with pytest.raises(NotImplementedError): self.pymc_...
_run = [ "check_pymc_params_match_rv_op", "check_rv_size", "check_not_implemented", ] def check_not_implemented(self): with pytest.raises(NotImplementedError): self.pymc_rv.eval() class TestHalfFlat(BaseTestDistribution):
64
64
92
8
56
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestHalfFlat
TestHalfFlat
436
448
436
436
2518a92d3dd35d9bd5f4250240f51fcdf77036a9
bigcode/the-stack
train
a1cbde5599326fb138ab77e1
train
class
@pytest.mark.xfail(reason="This distribution has not been refactored for v4") class TestGaussianRandomWalk(BaseTestCases.BaseTestCase): distribution = pm.GaussianRandomWalk params = {"mu": 1.0, "sigma": 1.0} default_shape = (1,)
@pytest.mark.xfail(reason="This distribution has not been refactored for v4") class TestGaussianRandomWalk(BaseTestCases.BaseTestCase):
distribution = pm.GaussianRandomWalk params = {"mu": 1.0, "sigma": 1.0} default_shape = (1,)
assert ( expected == actual ), f"Sample size {size} from {shape}-shaped RV had shape {actual}. Expected: {expected}" @pytest.mark.xfail(reason="This distribution has not been refactored for v4") class TestGaussianRandomWalk(BaseTestCases.BaseTestCase):
63
64
66
30
33
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestGaussianRandomWalk
TestGaussianRandomWalk
251
255
251
252
59f81ec37892060d51c1f1613a753dc0b5834679
bigcode/the-stack
train
22bcd3ef7d49f67b65dce0f3
train
class
class TestNegativeBinomial(BaseTestDistribution): pymc_dist = pm.NegativeBinomial pymc_dist_params = {"n": 100, "p": 0.33} expected_rv_op_params = {"n": 100, "p": 0.33} tests_to_run = ["check_pymc_params_match_rv_op"]
class TestNegativeBinomial(BaseTestDistribution):
pymc_dist = pm.NegativeBinomial pymc_dist_params = {"n": 100, "p": 0.33} expected_rv_op_params = {"n": 100, "p": 0.33} tests_to_run = ["check_pymc_params_match_rv_op"]
_dist_params = {"n": 100, "p": 0.33} expected_rv_op_params = {"n": 100, "p": 0.33} tests_to_run = ["check_pymc_params_match_rv_op"] class TestNegativeBinomial(BaseTestDistribution):
63
64
78
9
54
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestNegativeBinomial
TestNegativeBinomial
1,003
1,007
1,003
1,003
04c34bf951fa787de70446dc17d3866da8e7366f
bigcode/the-stack
train
c58a8feb5933a8c7ba167fc5
train
class
class TestRice(BaseTestDistribution): pymc_dist = pm.Rice b, sigma = 1, 2 pymc_dist_params = {"b": b, "sigma": sigma} expected_rv_op_params = {"b": b, "sigma": sigma} reference_dist_params = {"b": b, "scale": sigma} reference_dist = seeded_scipy_distribution_builder("rice") tests_to_run = [ ...
class TestRice(BaseTestDistribution):
pymc_dist = pm.Rice b, sigma = 1, 2 pymc_dist_params = {"b": b, "sigma": sigma} expected_rv_op_params = {"b": b, "sigma": sigma} reference_dist_params = {"b": b, "scale": sigma} reference_dist = seeded_scipy_distribution_builder("rice") tests_to_run = [ "check_pymc_params_match_rv_op...
tau": tau, "alpha": 5.0} expected_rv_op_params = {"mu": 0.0, "sigma": sigma, "alpha": 5.0} tests_to_run = ["check_pymc_params_match_rv_op"] class TestRice(BaseTestDistribution):
63
64
126
7
56
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestRice
TestRice
753
764
753
753
d940a48ee9eb10d0310c6c591135bd9322d38477
bigcode/the-stack
train
56c0609ffc46503f271c0eeb
train
class
class TestBetaBinomial(BaseTestDistribution): pymc_dist = pm.BetaBinomial pymc_dist_params = {"alpha": 2.0, "beta": 1.0, "n": 5} expected_rv_op_params = {"n": 5, "alpha": 2.0, "beta": 1.0} reference_dist_params = {"n": 5, "a": 2.0, "b": 1.0} reference_dist = seeded_scipy_distribution_builder("betabi...
class TestBetaBinomial(BaseTestDistribution):
pymc_dist = pm.BetaBinomial pymc_dist_params = {"alpha": 2.0, "beta": 1.0, "n": 5} expected_rv_op_params = {"n": 5, "alpha": 2.0, "beta": 1.0} reference_dist_params = {"n": 5, "a": 2.0, "b": 1.0} reference_dist = seeded_scipy_distribution_builder("betabinom") tests_to_run = [ "check_pymc...
2.0} reference_dist = seeded_weibul_rng_fn tests_to_run = [ "check_pymc_params_match_rv_op", "check_pymc_draws_match_reference", "check_rv_size", ] class TestBetaBinomial(BaseTestDistribution):
63
64
157
9
54
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestBetaBinomial
TestBetaBinomial
1,337
1,347
1,337
1,337
5b73b83d4cf41272270fe9560d4dfc9f659beb69
bigcode/the-stack
train
ea67479cc0d244c3faeadeb4
train
function
def seeded_scipy_distribution_builder(dist_name: str) -> Callable: return lambda self: functools.partial( getattr(st, dist_name).rvs, random_state=self.get_random_state() )
def seeded_scipy_distribution_builder(dist_name: str) -> Callable:
return lambda self: functools.partial( getattr(st, dist_name).rvs, random_state=self.get_random_state() )
v.shape.eval()) assert actual == expected def validate_tests_list(self): assert len(self.tests_to_run) == len( set(self.tests_to_run) ), "There are duplicates in the list of tests_to_run" def seeded_scipy_distribution_builder(dist_name: str) -> Callable:
64
64
42
15
49
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
seeded_scipy_distribution_builder
seeded_scipy_distribution_builder
409
412
409
409
526d933d0add422f7fc5f4ea40610aed1e4670da
bigcode/the-stack
train
3766c6a47fbbf97ebcbb8ffc
train
class
@pytest.mark.xfail(reason="This distribution has not been refactored for v4") class TestZeroInflatedNegativeBinomial(BaseTestCases.BaseTestCase): distribution = pm.ZeroInflatedNegativeBinomial params = {"mu": 1.0, "alpha": 1.0, "psi": 0.3}
@pytest.mark.xfail(reason="This distribution has not been refactored for v4") class TestZeroInflatedNegativeBinomial(BaseTestCases.BaseTestCase):
distribution = pm.ZeroInflatedNegativeBinomial params = {"mu": 1.0, "alpha": 1.0, "psi": 0.3}
ussianRandomWalk params = {"mu": 1.0, "sigma": 1.0} default_shape = (1,) @pytest.mark.xfail(reason="This distribution has not been refactored for v4") class TestZeroInflatedNegativeBinomial(BaseTestCases.BaseTestCase):
63
64
71
33
30
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestZeroInflatedNegativeBinomial
TestZeroInflatedNegativeBinomial
258
261
258
259
cde07ed9bb70f52972f1c9b99fe515944aa419ac
bigcode/the-stack
train
d78f8bf7d4c7d39351dbabc8
train
class
class TestInterpolated(BaseTestDistribution): def interpolated_rng_fn(self, size, mu, sigma, rng): return st.norm.rvs(loc=mu, scale=sigma, size=size) pymc_dist = pm.Interpolated # Dummy values for RV size testing mu = sigma = 1 x_points = pdf_points = np.linspace(1, 100, 100) pymc_dis...
class TestInterpolated(BaseTestDistribution):
def interpolated_rng_fn(self, size, mu, sigma, rng): return st.norm.rvs(loc=mu, scale=sigma, size=size) pymc_dist = pm.Interpolated # Dummy values for RV size testing mu = sigma = 1 x_points = pdf_points = np.linspace(1, 100, 100) pymc_dist_params = {"x_points": x_points, "pdf_points"...
3), colcov=np.eye(3), ) with pytest.raises(TypeError): logpt(matrixnormal, aesara.tensor.ones((3, 3, 3))) with pm.Model(): with pytest.warns(FutureWarning): matrixnormal = pm.MatrixNormal( "matnormal", ...
107
107
358
8
99
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestInterpolated
TestInterpolated
1,647
1,688
1,647
1,647
d92887735920908f51881b1e856dacfe8860865c
bigcode/the-stack
train
cb3456d21ab21ae3a4c091f3
train
class
class TestPoisson(BaseTestDistribution): pymc_dist = pm.Poisson pymc_dist_params = {"mu": 4.0} expected_rv_op_params = {"mu": 4.0} tests_to_run = ["check_pymc_params_match_rv_op"]
class TestPoisson(BaseTestDistribution):
pymc_dist = pm.Poisson pymc_dist_params = {"mu": 4.0} expected_rv_op_params = {"mu": 4.0} tests_to_run = ["check_pymc_params_match_rv_op"]
pm.Bernoulli pymc_dist_params = {"logit_p": 1.0} expected_rv_op_params = {"p": expit(1.0)} tests_to_run = ["check_pymc_params_match_rv_op"] class TestPoisson(BaseTestDistribution):
63
64
63
8
55
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestPoisson
TestPoisson
1,042
1,046
1,042
1,042
d4c7200ebca1009cc41205f0c1c4a954af7945cf
bigcode/the-stack
train
37467f4a402270a4b7a2ebb7
train
class
class TestInverseGammaMuSigma(BaseTestDistribution): pymc_dist = pm.InverseGamma pymc_dist_params = {"mu": 0.5, "sigma": 0.25} expected_alpha, expected_beta = pm.InverseGamma._get_alpha_beta( alpha=None, beta=None, mu=pymc_dist_params["mu"], sigma=pymc_dist_params["sigma"], ...
class TestInverseGammaMuSigma(BaseTestDistribution):
pymc_dist = pm.InverseGamma pymc_dist_params = {"mu": 0.5, "sigma": 0.25} expected_alpha, expected_beta = pm.InverseGamma._get_alpha_beta( alpha=None, beta=None, mu=pymc_dist_params["mu"], sigma=pymc_dist_params["sigma"], ) expected_rv_op_params = {"alpha": expected_a...
scale": 5.0} reference_dist = seeded_scipy_distribution_builder("invgamma") tests_to_run = [ "check_pymc_params_match_rv_op", "check_pymc_draws_match_reference", ] class TestInverseGammaMuSigma(BaseTestDistribution):
63
64
123
10
53
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestInverseGammaMuSigma
TestInverseGammaMuSigma
970
980
970
970
9bc481b059e3a43928bfec312fc81840b2546d8c
bigcode/the-stack
train
f2339e4d80ec45b95a081a77
train
class
class TestLogitNormal(BaseTestDistribution): def logit_normal_rng_fn(self, rng, size, loc, scale): return expit(st.norm.rvs(loc=loc, scale=scale, size=size, random_state=rng)) pymc_dist = pm.LogitNormal pymc_dist_params = {"mu": 5.0, "sigma": 10.0} expected_rv_op_params = {"mu": 5.0, "sigma": 1...
class TestLogitNormal(BaseTestDistribution):
def logit_normal_rng_fn(self, rng, size, loc, scale): return expit(st.norm.rvs(loc=loc, scale=scale, size=size, random_state=rng)) pymc_dist = pm.LogitNormal pymc_dist_params = {"mu": 5.0, "sigma": 10.0} expected_rv_op_params = {"mu": 5.0, "sigma": 10.0} reference_dist_params = {"loc": 5.0,...
size = 15 reference_dist = seeded_numpy_distribution_builder("normal") tests_to_run = [ "check_pymc_params_match_rv_op", "check_pymc_draws_match_reference", "check_rv_size", ] class TestLogitNormal(BaseTestDistribution):
63
64
190
9
54
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestLogitNormal
TestLogitNormal
799
814
799
799
8011a257086a29c5b0590304ac79bca4018c75fe
bigcode/the-stack
train
e56943866ac9259744ca36fe
train
class
class TestStudentTLam(BaseTestDistribution): pymc_dist = pm.StudentT lam, sigma = get_tau_sigma(tau=2.0) pymc_dist_params = {"nu": 5.0, "mu": -1.0, "lam": lam} expected_rv_op_params = {"nu": 5.0, "mu": -1.0, "lam": sigma} reference_dist_params = {"df": 5.0, "loc": -1.0, "scale": sigma} reference...
class TestStudentTLam(BaseTestDistribution):
pymc_dist = pm.StudentT lam, sigma = get_tau_sigma(tau=2.0) pymc_dist_params = {"nu": 5.0, "mu": -1.0, "lam": lam} expected_rv_op_params = {"nu": 5.0, "mu": -1.0, "lam": sigma} reference_dist_params = {"df": 5.0, "loc": -1.0, "scale": sigma} reference_dist = seeded_scipy_distribution_builder("t"...
2 pymc_dist_params = {"nu": nu, "sigma": sigma} expected_rv_op_params = {"b": nu / sigma, "sigma": sigma} tests_to_run = ["check_pymc_params_match_rv_op"] class TestStudentTLam(BaseTestDistribution):
63
64
143
9
54
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestStudentTLam
TestStudentTLam
775
782
775
775
a2d549877287b2ca798144c551040d1e735396ca
bigcode/the-stack
train
999f193fca04aa069774032b
train
class
class TestLogitNormalTau(BaseTestDistribution): pymc_dist = pm.LogitNormal tau, sigma = get_tau_sigma(tau=25.0) pymc_dist_params = {"mu": 1.0, "tau": tau} expected_rv_op_params = {"mu": 1.0, "sigma": sigma} tests_to_run = ["check_pymc_params_match_rv_op"]
class TestLogitNormalTau(BaseTestDistribution):
pymc_dist = pm.LogitNormal tau, sigma = get_tau_sigma(tau=25.0) pymc_dist_params = {"mu": 1.0, "tau": tau} expected_rv_op_params = {"mu": 1.0, "sigma": sigma} tests_to_run = ["check_pymc_params_match_rv_op"]
self.logit_normal_rng_fn, rng=self.get_random_state() ) tests_to_run = [ "check_pymc_params_match_rv_op", "check_pymc_draws_match_reference", "check_rv_size", ] class TestLogitNormalTau(BaseTestDistribution):
63
64
90
10
53
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestLogitNormalTau
TestLogitNormalTau
817
822
817
817
ffac227ad1bdcfac6c1cc0deb22d5f74ae65f8bf
bigcode/the-stack
train
a749728839ec5a32b823c516
train
class
class TestDiscreteWeibull(BaseTestDistribution): def discrete_weibul_rng_fn(self, size, q, beta, uniform_rng_fct): return np.ceil(np.power(np.log(1 - uniform_rng_fct(size=size)) / np.log(q), 1.0 / beta)) - 1 def seeded_discrete_weibul_rng_fn(self): uniform_rng_fct = functools.partial( ...
class TestDiscreteWeibull(BaseTestDistribution):
def discrete_weibul_rng_fn(self, size, q, beta, uniform_rng_fct): return np.ceil(np.power(np.log(1 - uniform_rng_fct(size=size)) / np.log(q), 1.0 / beta)) - 1 def seeded_discrete_weibul_rng_fn(self): uniform_rng_fct = functools.partial( getattr(np.random.RandomState, "uniform"), sel...
expected_rv_op_params = {} tests_to_run = [ "check_pymc_params_match_rv_op", "check_rv_size", "check_not_implemented", ] def check_not_implemented(self): with pytest.raises(NotImplementedError): self.pymc_rv.eval() class TestDiscreteWeibull(BaseTestDistribution)...
76
76
255
10
66
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestDiscreteWeibull
TestDiscreteWeibull
451
470
451
451
94bdd73950a57e736bf25e41696af720864add81
bigcode/the-stack
train
79bf94a8b05d73b0316ad49e
train
class
class TestGeometric(BaseTestDistribution): pymc_dist = pm.Geometric pymc_dist_params = {"p": 0.9} expected_rv_op_params = {"p": 0.9} tests_to_run = ["check_pymc_params_match_rv_op"]
class TestGeometric(BaseTestDistribution):
pymc_dist = pm.Geometric pymc_dist_params = {"p": 0.9} expected_rv_op_params = {"p": 0.9} tests_to_run = ["check_pymc_params_match_rv_op"]
expected_rv_op_params = {"p": np.array([0.28, 0.62, 0.10])} tests_to_run = [ "check_pymc_params_match_rv_op", "check_rv_size", ] class TestGeometric(BaseTestDistribution):
63
64
62
8
55
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestGeometric
TestGeometric
1,244
1,248
1,244
1,244
69135f4bc84b2b6f023907de71c75821d6dff54b
bigcode/the-stack
train
52dc69a9aa8b7375697da345
train
class
class TestLognormalSd(BaseTestDistribution): pymc_dist = pm.Lognormal pymc_dist_params = {"mu": 1.0, "sd": 5.0} expected_rv_op_params = {"mu": 1.0, "sigma": 5.0} tests_to_run = ["check_pymc_params_match_rv_op"]
class TestLognormalSd(BaseTestDistribution):
pymc_dist = pm.Lognormal pymc_dist_params = {"mu": 1.0, "sd": 5.0} expected_rv_op_params = {"mu": 1.0, "sigma": 5.0} tests_to_run = ["check_pymc_params_match_rv_op"]
_params = {"mu": 1.0, "tau": 25.0} expected_rv_op_params = {"mu": 1.0, "sigma": sigma} tests_to_run = ["check_pymc_params_match_rv_op"] class TestLognormalSd(BaseTestDistribution):
63
64
80
9
54
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestLognormalSd
TestLognormalSd
1,289
1,293
1,289
1,289
67a08acee832bc082e83f83f5e7f340ce4099132
bigcode/the-stack
train
7c91fda4473d6fd2b30bee16
train
class
class TestMvNormalTau(BaseTestDistribution): pymc_dist = pm.MvNormal pymc_dist_params = { "mu": np.array([1.0, 2.0]), "tau": np.array([[2.0, 0.0], [0.0, 3.5]]), } expected_rv_op_params = { "mu": np.array([1.0, 2.0]), "cov": quaddist_matrix(tau=pymc_dist_params["tau"]).eva...
class TestMvNormalTau(BaseTestDistribution):
pymc_dist = pm.MvNormal pymc_dist_params = { "mu": np.array([1.0, 2.0]), "tau": np.array([[2.0, 0.0], [0.0, 3.5]]), } expected_rv_op_params = { "mu": np.array([1.0, 2.0]), "cov": quaddist_matrix(tau=pymc_dist_params["tau"]).eval(), } tests_to_run = ["check_pymc_pa...
"mu": np.array([1.0, 2.0]), "cov": quaddist_matrix(chol=pymc_dist_params["chol"]).eval(), } tests_to_run = ["check_pymc_params_match_rv_op"] class TestMvNormalTau(BaseTestDistribution):
63
64
133
9
54
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestMvNormalTau
TestMvNormalTau
1,086
1,096
1,086
1,086
b4ab6cd2752af8a8462214768be419af4e42e44f
bigcode/the-stack
train
1e9c4ef5f72724c8c2297435
train
function
def seeded_numpy_distribution_builder(dist_name: str) -> Callable: return lambda self: functools.partial( getattr(np.random.RandomState, dist_name), self.get_random_state() )
def seeded_numpy_distribution_builder(dist_name: str) -> Callable:
return lambda self: functools.partial( getattr(np.random.RandomState, dist_name), self.get_random_state() )
duplicates in the list of tests_to_run" def seeded_scipy_distribution_builder(dist_name: str) -> Callable: return lambda self: functools.partial( getattr(st, dist_name).rvs, random_state=self.get_random_state() ) def seeded_numpy_distribution_builder(dist_name: str) -> Callable:
64
64
38
13
51
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
seeded_numpy_distribution_builder
seeded_numpy_distribution_builder
415
418
415
415
f1b9886456015637ae509ae736cb8b66e57fa7ec
bigcode/the-stack
train
669b7afb2b601c727d12a872
train
function
@pytest.mark.xfail(reason="This distribution has not been refactored for v4") def test_mixture_random_shape_fast(): # test the shape broadcasting in mixture random y = np.concatenate([nr.poisson(5, size=10), nr.poisson(9, size=10)]) with pm.Model() as m: comp0 = pm.Poisson.dist(mu=np.ones(2)) ...
@pytest.mark.xfail(reason="This distribution has not been refactored for v4") def test_mixture_random_shape_fast(): # test the shape broadcasting in mixture random
y = np.concatenate([nr.poisson(5, size=10), nr.poisson(9, size=10)]) with pm.Model() as m: comp0 = pm.Poisson.dist(mu=np.ones(2)) w0 = pm.Dirichlet("w0", a=np.ones(2), shape=(2,)) like0 = pm.Mixture("like0", w=w0, comp_dists=comp0, observed=y) comp1 = pm.Poisson.dist(mu=np.ones(...
assert rand3.shape == (100, 20) with m: ppc = pm.sample_posterior_predictive([m.initial_point], samples=200) assert ppc["like0"].shape == (200, 20) assert ppc["like1"].shape == (200, 20) assert ppc["like2"].shape == (200, 20) assert ppc["like3"].shape == (200, 20) @pytest.mark.xfail(reason...
135
135
453
36
99
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
test_mixture_random_shape_fast
test_mixture_random_shape_fast
1,811
1,839
1,811
1,813
25685e0ed56c5ba61d9a59af5d0f356a7354f42a
bigcode/the-stack
train
f45015cdbf25cdcae6ca1892
train
class
class TestScalarParameterSamples(SeededTest): @pytest.mark.xfail(reason="This distribution has not been refactored for v4") def test_lkj(self): for n in [2, 10, 50]: # pylint: disable=cell-var-from-loop shape = n * (n - 1) // 2 def ref_rand(size, eta): ...
class TestScalarParameterSamples(SeededTest): @pytest.mark.xfail(reason="This distribution has not been refactored for v4")
def test_lkj(self): for n in [2, 10, 50]: # pylint: disable=cell-var-from-loop shape = n * (n - 1) // 2 def ref_rand(size, eta): beta = eta - 1 + n / 2 return (st.beta.rvs(size=(size, shape), a=beta, b=beta) - 0.5) * 2 class T...
, (1,), 5, (4, 5), (2, 4, 2)] sizes_expected = [(N,), (N,), (1, N), (1, N), (5, N), (4, 5, N), (2, 4, 2, N)] reference_dist = lambda self: functools.partial( self.kronecker_rng_fn, rng=self.get_random_state() ) tests_to_run = [ "check_pymc_draws_match_reference", "check_rv_size"...
148
149
498
30
118
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestScalarParameterSamples
TestScalarParameterSamples
1,720
1,770
1,720
1,721
9aab2a79b93c68987faddfdeafdb2b9547d09f94
bigcode/the-stack
train
17b89b29d918819a97851537
train
class
class TestZeroInflatedNegativeBinomial(BaseTestDistribution): def zero_inflated_negbinomial_rng_fn( self, size, psi, n, p, negbinomial_rng_fct, random_rng_fct ): return negbinomial_rng_fct(n, p, size=size) * (random_rng_fct(size=size) < psi) def seeded_zero_inflated_negbinomial_rng_fn(self)...
class TestZeroInflatedNegativeBinomial(BaseTestDistribution):
def zero_inflated_negbinomial_rng_fn( self, size, psi, n, p, negbinomial_rng_fct, random_rng_fct ): return negbinomial_rng_fct(n, p, size=size) * (random_rng_fct(size=size) < psi) def seeded_zero_inflated_negbinomial_rng_fn(self): negbinomial_rng_fct = functools.partial( ...
, "n": 12, "p": 0.7} reference_dist_params = {"psi": 0.9, "n": 12, "p": 0.7} reference_dist = seeded_zero_inflated_binomial_rng_fn tests_to_run = [ "check_pymc_params_match_rv_op", "check_pymc_draws_match_reference", "check_rv_size", ] class TestZeroInflatedNegativeBinomial(BaseT...
106
107
357
12
94
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestZeroInflatedNegativeBinomial
TestZeroInflatedNegativeBinomial
1,470
1,502
1,470
1,470
7897caf98b54c500301cd281f7e8c7261855101b
bigcode/the-stack
train
2258f28fe4d98bbafea85e82
train
class
class TestMatrixNormal(BaseTestDistribution): pymc_dist = pm.MatrixNormal mu = np.random.random((3, 3)) row_cov = np.eye(3) col_cov = np.eye(3) shape = None size = None pymc_dist_params = {"mu": mu, "rowcov": row_cov, "colcov": col_cov} expected_rv_op_params = {"mu": mu, "rowcov": row_...
class TestMatrixNormal(BaseTestDistribution):
pymc_dist = pm.MatrixNormal mu = np.random.random((3, 3)) row_cov = np.eye(3) col_cov = np.eye(3) shape = None size = None pymc_dist_params = {"mu": mu, "rowcov": row_cov, "colcov": col_cov} expected_rv_op_params = {"mu": mu, "rowcov": row_cov, "colcov": col_cov} tests_to_run = ["c...
V = np.eye(3) pymc_dist_params = {"nu": 4, "V": V} reference_dist_params = {"nu": 4, "V": V} expected_rv_op_params = {"nu": 4, "V": V} sizes_to_check = [None, 1, (4, 5)] sizes_expected = [ (3, 3), (1, 3, 3), (4, 5, 3, 3), ] reference_dist = lambda self: functools.par...
184
185
619
8
176
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestMatrixNormal
TestMatrixNormal
1,566
1,644
1,566
1,567
2ed24e0bd5f255bb552b8ba64beeea351a606afe
bigcode/the-stack
train
b2bb241080f30975c50213eb
train
class
class TestOrderedMultinomial(BaseTestDistribution): pymc_dist = _OrderedMultinomial pymc_dist_params = {"eta": 0, "cutpoints": np.array([-2, 0, 2]), "n": 1000} sizes_to_check = [None, (1), (4,), (3, 2)] sizes_expected = [(4,), (1, 4), (4, 4), (3, 2, 4)] expected_rv_op_params = { "n": 1000, ...
class TestOrderedMultinomial(BaseTestDistribution):
pymc_dist = _OrderedMultinomial pymc_dist_params = {"eta": 0, "cutpoints": np.array([-2, 0, 2]), "n": 1000} sizes_to_check = [None, (1), (4,), (3, 2)] sizes_expected = [(4,), (1, 4), (4, 4), (3, 2, 4)] expected_rv_op_params = { "n": 1000, "p": np.array([0.11920292, 0.38079708, 0.3807...
02275013, 0.47724987, 0.47724987, 0.02275013])} tests_to_run = [ "check_pymc_params_match_rv_op", "check_rv_size", ] class TestOrderedMultinomial(BaseTestDistribution):
63
64
182
10
53
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestOrderedMultinomial
TestOrderedMultinomial
1,525
1,537
1,525
1,525
9e6d9785f1fcac8f0a25d06a49738e6775fe182f
bigcode/the-stack
train
f072da3ba0e6d4702576fa00
train
class
class TestTruncatedNormalTau(BaseTestDistribution): pymc_dist = pm.TruncatedNormal lower, upper, mu, tau = -2.0, 2.0, 0, 1.0 tau, sigma = get_tau_sigma(tau=tau, sigma=None) pymc_dist_params = {"mu": mu, "tau": tau, "lower": lower, "upper": upper} expected_rv_op_params = {"mu": mu, "sigma": sigma, "l...
class TestTruncatedNormalTau(BaseTestDistribution):
pymc_dist = pm.TruncatedNormal lower, upper, mu, tau = -2.0, 2.0, 0, 1.0 tau, sigma = get_tau_sigma(tau=tau, sigma=None) pymc_dist_params = {"mu": mu, "tau": tau, "lower": lower, "upper": upper} expected_rv_op_params = {"mu": mu, "sigma": sigma, "lower": lower, "upper": upper} tests_to_run = [ ...
reference_dist = seeded_scipy_distribution_builder("truncnorm") tests_to_run = [ "check_pymc_params_match_rv_op", "check_pymc_draws_match_reference", "check_rv_size", ] class TestTruncatedNormalTau(BaseTestDistribution):
63
64
136
10
53
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestTruncatedNormalTau
TestTruncatedNormalTau
636
644
636
636
4e907d81b05ca8f590200505474cc38ecf0fb9d5
bigcode/the-stack
train
7e4c654bf7062f0050ae9440
train
class
class TestDirichlet(BaseTestDistribution): pymc_dist = pm.Dirichlet pymc_dist_params = {"a": np.array([1.0, 2.0])} expected_rv_op_params = {"a": np.array([1.0, 2.0])} sizes_to_check = [None, (1), (4,), (3, 4)] sizes_expected = [(2,), (1, 2), (4, 2), (3, 4, 2)] reference_dist_params = {"alpha": n...
class TestDirichlet(BaseTestDistribution):
pymc_dist = pm.Dirichlet pymc_dist_params = {"a": np.array([1.0, 2.0])} expected_rv_op_params = {"a": np.array([1.0, 2.0])} sizes_to_check = [None, (1), (4,), (3, 4)] sizes_expected = [(2,), (1, 2), (4, 2), (3, 4, 2)] reference_dist_params = {"alpha": np.array([1.0, 2.0])} reference_dist = s...
"mu": np.array([1.0, 2.0]), "cov": quaddist_matrix(tau=pymc_dist_params["tau"]).eval(), } tests_to_run = ["check_pymc_params_match_rv_op"] class TestDirichlet(BaseTestDistribution):
63
64
184
9
54
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestDirichlet
TestDirichlet
1,163
1,175
1,163
1,163
9920479db5cb7c1fc19ebc3acaf521af082c029a
bigcode/the-stack
train
7df1bd9abb2d599d68fe25c8
train
function
def generate_shapes(include_params=False): # fmt: off mudim_as_event = [ [None, 1, 3, 10, (10, 3), 100], [(3,)], [(1,), (3,)], ["cov", "chol", "tau"] ] # fmt: on mudim_as_dist = [ [None, 1, 3, 10, (10, 3), 100], [(10, 3)], [(1,), (3,), (1, 1), ...
def generate_shapes(include_params=False): # fmt: off
mudim_as_event = [ [None, 1, 3, 10, (10, 3), 100], [(3,)], [(1,), (3,)], ["cov", "chol", "tau"] ] # fmt: on mudim_as_dist = [ [None, 1, 3, 10, (10, 3), 100], [(10, 3)], [(1,), (3,), (1, 1), (1, 3), (10, 1), (10, 3)], ["cov", "chol", "tau"],...
pm.Triangular, shape=shape, nested_rvs_info=dict(c=c, lower=lower, upper=upper), prior_samples=prior_samples, ) assert prior["target"].shape == (prior_samples,) + shape def generate_shapes(include_params=False): # fmt: off
64
64
202
13
50
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
generate_shapes
generate_shapes
2,179
2,198
2,179
2,180
2106d5feb564f9ee8d07a8be10be71283e6686ec
bigcode/the-stack
train
fb8af026a58254bf4d2afaca
train
class
class TestWishart(BaseTestDistribution): def wishart_rng_fn(self, size, nu, V, rng): return st.wishart.rvs(np.int(nu), V, size=size, random_state=rng) pymc_dist = pm.Wishart V = np.eye(3) pymc_dist_params = {"nu": 4, "V": V} reference_dist_params = {"nu": 4, "V": V} expected_rv_op_para...
class TestWishart(BaseTestDistribution):
def wishart_rng_fn(self, size, nu, V, rng): return st.wishart.rvs(np.int(nu), V, size=size, random_state=rng) pymc_dist = pm.Wishart V = np.eye(3) pymc_dist_params = {"nu": 4, "V": V} reference_dist_params = {"nu": 4, "V": V} expected_rv_op_params = {"nu": 4, "V": V} sizes_to_check...
p": np.array([0.11920292, 0.38079708, 0.38079708, 0.11920292]), } tests_to_run = [ "check_pymc_params_match_rv_op", "check_rv_size", ] class TestWishart(BaseTestDistribution):
69
70
234
8
61
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestWishart
TestWishart
1,540
1,563
1,540
1,540
1127bf4772c1f57dba88fcb4c65fd958cc73729f
bigcode/the-stack
train
503af8afad4c208e21134bd0
train
class
class TestGumbel(BaseTestDistribution): pymc_dist = pm.Gumbel pymc_dist_params = {"mu": 1.5, "beta": 3.0} expected_rv_op_params = {"mu": 1.5, "beta": 3.0} reference_dist_params = {"loc": 1.5, "scale": 3.0} reference_dist = seeded_scipy_distribution_builder("gumbel_r") tests_to_run = [ "c...
class TestGumbel(BaseTestDistribution):
pymc_dist = pm.Gumbel pymc_dist_params = {"mu": 1.5, "beta": 3.0} expected_rv_op_params = {"mu": 1.5, "beta": 3.0} reference_dist_params = {"loc": 1.5, "scale": 3.0} reference_dist = seeded_scipy_distribution_builder("gumbel_r") tests_to_run = [ "check_pymc_params_match_rv_op", "...
1.0} reference_dist = seeded_exgaussian_rng_fn tests_to_run = [ "check_pymc_params_match_rv_op", "check_pymc_draws_match_reference", "check_rv_size", ] class TestGumbel(BaseTestDistribution):
63
64
132
9
54
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestGumbel
TestGumbel
557
566
557
557
06dc66190198f2fe5c0e3773c95bd80056a0810a
bigcode/the-stack
train
be5cbacbb04b29949697c63a
train
class
class TestTriangular(BaseTestDistribution): pymc_dist = pm.Triangular pymc_dist_params = {"lower": 0, "upper": 1, "c": 0.5} expected_rv_op_params = {"lower": 0, "c": 0.5, "upper": 1} reference_dist_params = {"left": 0, "mode": 0.5, "right": 1} reference_dist = seeded_numpy_distribution_builder("tria...
class TestTriangular(BaseTestDistribution):
pymc_dist = pm.Triangular pymc_dist_params = {"lower": 0, "upper": 1, "c": 0.5} expected_rv_op_params = {"lower": 0, "c": 0.5, "upper": 1} reference_dist_params = {"left": 0, "mode": 0.5, "right": 1} reference_dist = seeded_numpy_distribution_builder("triangular") tests_to_run = [ "check...
{"mu": 1.0, "sd": 5.0} expected_rv_op_params = {"mu": 1.0, "sigma": 5.0} tests_to_run = ["check_pymc_params_match_rv_op"] class TestTriangular(BaseTestDistribution):
63
64
139
8
55
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestTriangular
TestTriangular
1,296
1,305
1,296
1,296
4cce5326579b798b06bd9c1a8f80ee6eff20f7e2
bigcode/the-stack
train
bf9815dfbcb8a441a057c02b
train
class
class TestDiscreteUniform(BaseTestDistribution): def discrete_uniform_rng_fn(self, size, lower, upper, rng): return st.randint.rvs(lower, upper + 1, size=size, random_state=rng) pymc_dist = pm.DiscreteUniform pymc_dist_params = {"lower": -1, "upper": 9} expected_rv_op_params = {"lower": -1, "up...
class TestDiscreteUniform(BaseTestDistribution):
def discrete_uniform_rng_fn(self, size, lower, upper, rng): return st.randint.rvs(lower, upper + 1, size=size, random_state=rng) pymc_dist = pm.DiscreteUniform pymc_dist_params = {"lower": -1, "upper": 9} expected_rv_op_params = {"lower": -1, "upper": 9} reference_dist_params = {"lower": -1...
( self.polyagamma_rng_fn, rng=self.get_random_state() ) tests_to_run = [ "check_pymc_params_match_rv_op", "check_pymc_draws_match_reference", "check_rv_size", ] class TestDiscreteUniform(BaseTestDistribution):
63
64
173
8
55
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestDiscreteUniform
TestDiscreteUniform
1,372
1,387
1,372
1,372
3e537049824a3f8d137026f55fb058ce5e7cff33
bigcode/the-stack
train
3f11ecfca88a170103777033
train
class
class TestVonMises(BaseTestDistribution): pymc_dist = pm.VonMises pymc_dist_params = {"mu": -2.1, "kappa": 5} expected_rv_op_params = {"mu": -2.1, "kappa": 5} tests_to_run = ["check_pymc_params_match_rv_op"]
class TestVonMises(BaseTestDistribution):
pymc_dist = pm.VonMises pymc_dist_params = {"mu": -2.1, "kappa": 5} expected_rv_op_params = {"mu": -2.1, "kappa": 5} tests_to_run = ["check_pymc_params_match_rv_op"]
0.5, "right": 1} reference_dist = seeded_numpy_distribution_builder("triangular") tests_to_run = [ "check_pymc_params_match_rv_op", "check_pymc_draws_match_reference", ] class TestVonMises(BaseTestDistribution):
63
64
79
9
54
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestVonMises
TestVonMises
1,308
1,312
1,308
1,308
9dfebf5b82c166198b4bb09b3cd67a9c955c51f9
bigcode/the-stack
train
644ca9bfe6f07650ef981144
train
class
@pytest.mark.skipif( condition=_polyagamma_not_installed, reason="`polyagamma package is not available/installed.", ) class TestPolyaGamma(BaseTestDistribution): def polyagamma_rng_fn(self, size, h, z, rng): return random_polyagamma(h, z, size=size, random_state=rng._bit_generator) pymc_dist = ...
@pytest.mark.skipif( condition=_polyagamma_not_installed, reason="`polyagamma package is not available/installed.", ) class TestPolyaGamma(BaseTestDistribution):
def polyagamma_rng_fn(self, size, h, z, rng): return random_polyagamma(h, z, size=size, random_state=rng._bit_generator) pymc_dist = pm.PolyaGamma pymc_dist_params = {"h": 1.0, "z": 0.0} expected_rv_op_params = {"h": 1.0, "z": 0.0} reference_dist_params = {"h": 1.0, "z": 0.0} reference_...
_match_rv_op", "check_pymc_draws_match_reference", "check_rv_size", ] @pytest.mark.skipif( condition=_polyagamma_not_installed, reason="`polyagamma package is not available/installed.", ) class TestPolyaGamma(BaseTestDistribution):
64
65
218
39
25
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestPolyaGamma
TestPolyaGamma
1,350
1,369
1,350
1,354
333f3ea82220c70ff70c80c52d19fb9352dba3d4
bigcode/the-stack
train
77e69dc646f61ea65862a1e0
train
class
class TestNegativeBinomialMuSigma(BaseTestDistribution): pymc_dist = pm.NegativeBinomial pymc_dist_params = {"mu": 5.0, "alpha": 8.0} expected_n, expected_p = pm.NegativeBinomial.get_n_p( mu=pymc_dist_params["mu"], alpha=pymc_dist_params["alpha"], n=None, p=None, ) ex...
class TestNegativeBinomialMuSigma(BaseTestDistribution):
pymc_dist = pm.NegativeBinomial pymc_dist_params = {"mu": 5.0, "alpha": 8.0} expected_n, expected_p = pm.NegativeBinomial.get_n_p( mu=pymc_dist_params["mu"], alpha=pymc_dist_params["alpha"], n=None, p=None, ) expected_rv_op_params = {"n": expected_n, "p": expected_p} ...
= {"n": 100, "p": 0.33} expected_rv_op_params = {"n": 100, "p": 0.33} tests_to_run = ["check_pymc_params_match_rv_op"] class TestNegativeBinomialMuSigma(BaseTestDistribution):
63
64
127
11
52
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestNegativeBinomialMuSigma
TestNegativeBinomialMuSigma
1,010
1,020
1,010
1,010
37601299ed69448c8877e136e05ce5a931ef262d
bigcode/the-stack
train
49c67e2ed208fab1773568fc
train
class
class TestHalfNormalTau(BaseTestDistribution): pymc_dist = pm.Normal tau, sigma = get_tau_sigma(tau=25.0) pymc_dist_params = {"tau": tau} expected_rv_op_params = {"mu": 0.0, "sigma": sigma} tests_to_run = ["check_pymc_params_match_rv_op"]
class TestHalfNormalTau(BaseTestDistribution):
pymc_dist = pm.Normal tau, sigma = get_tau_sigma(tau=25.0) pymc_dist_params = {"tau": tau} expected_rv_op_params = {"mu": 0.0, "sigma": sigma} tests_to_run = ["check_pymc_params_match_rv_op"]
"scale": 10.0} reference_dist = seeded_scipy_distribution_builder("halfnorm") tests_to_run = [ "check_pymc_params_match_rv_op", "check_pymc_draws_match_reference", ] class TestHalfNormalTau(BaseTestDistribution):
63
64
79
9
54
MarcoGorelli/pymc
pymc/tests/test_distributions_random.py
Python
TestHalfNormalTau
TestHalfNormalTau
859
864
859
859
3efad454c5c45b393f7762132ba43c177e8b6c6c
bigcode/the-stack
train