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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f9b093c3b272d41ab94049c5 | train | class | class CosLR(object):
def __init__(self, period):
self.period = period
def __call__(self, lr):
return optimizers.schedules.CosineDecay(lr, self.period, lr * 0.001)
| class CosLR(object):
| def __init__(self, period):
self.period = period
def __call__(self, lr):
return optimizers.schedules.CosineDecay(lr, self.period, lr * 0.001)
| class PolyLR(object):
def __init__(self, cutoff, power):
self.cutoff = cutoff
self.power = power
def __call__(self, lr):
return optimizers.schedules.PolynomialDecay(lr, self.cutoff, power=self.power)
class CosLR(object):
| 64 | 64 | 51 | 5 | 59 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | CosLR | CosLR | 1,254 | 1,259 | 1,254 | 1,254 | 3ee59516e53306596ebe159cb8ebe23befc79991 | bigcode/the-stack | train |
c6192df56303c49490638cd9 | train | class | class SftmXE(Craft):
def __init__(self, is_one_hot, scope='SFTMXE'):
super(SftmXE, self).__init__(scope)
if is_one_hot:
self.cost = losses.CategoricalCrossentropy(from_logits=True, reduction=losses.Reduction.SUM)
else:
self.cost = losses.SparseCategoricalCrossentropy(... | class SftmXE(Craft):
| def __init__(self, is_one_hot, scope='SFTMXE'):
super(SftmXE, self).__init__(scope)
if is_one_hot:
self.cost = losses.CategoricalCrossentropy(from_logits=True, reduction=losses.Reduction.SUM)
else:
self.cost = losses.SparseCategoricalCrossentropy(from_logits=True, red... | XE, self).__init__(scope)
self.cost = losses.BinaryCrossentropy(from_logits=True, reduction=losses.Reduction.SUM)
def run(self, x, y):
z = self.cost(y, x)
return z/x.shape[0]
class SftmXE(Craft):
| 63 | 64 | 120 | 8 | 55 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | SftmXE | SftmXE | 1,169 | 1,179 | 1,169 | 1,169 | cb47d908b7974bbefcecb224fc8c1a026fe51509 | bigcode/the-stack | train |
05fa0eb27e813d3fd0ac6cff | train | class | class Retroact(Craft):
def __init__(self, scope='RETROACT'):
super(Retroact, self).__init__(scope)
if backend.image_data_format() == 'channels_first':
self.paxis = [2, 3]
self.caxis = 1
else:
self.paxis = [1, 2]
self.caxis = -1
def run(sel... | class Retroact(Craft):
| def __init__(self, scope='RETROACT'):
super(Retroact, self).__init__(scope)
if backend.image_data_format() == 'channels_first':
self.paxis = [2, 3]
self.caxis = 1
else:
self.paxis = [1, 2]
self.caxis = -1
def run(self, i, o, pb):
i... |
else:
return craft.__dict[paths[-1]]
def __setitem__(self, key, value):
self.hull.__dict[key] = value
def __call__(self, *args, **kwargs):
return self.hull(*args, **kwargs)
class Retroact(Craft):
| 67 | 67 | 224 | 6 | 61 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Retroact | Retroact | 498 | 521 | 498 | 498 | 363ae857d56c48c61b1d40c8d03f941010576639 | bigcode/the-stack | train |
39661175cdb0f5aba2522a41 | train | class | class Mean(Craft):
def __init__(self, scope='MEAN'):
super(Mean, self).__init__(scope)
def run(self, x, axis=None):
if axis is None:
y = tf.reduce_mean(x)
else:
y = tf.reduce_mean(x, axis=axis)
return y
| class Mean(Craft):
| def __init__(self, scope='MEAN'):
super(Mean, self).__init__(scope)
def run(self, x, axis=None):
if axis is None:
y = tf.reduce_mean(x)
else:
y = tf.reduce_mean(x, axis=axis)
return y
| else:
self.clipper = tf.clip_by_value
def run(self, x, ranges):
if isinstance(ranges, tuple):
assert len(ranges)==2
else:
ranges = (-ranges, ranges)
return self.clipper(x, *ranges)
class Mean(Craft):
| 64 | 64 | 71 | 5 | 59 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Mean | Mean | 600 | 609 | 600 | 600 | 0e207bd61d7ddc8534b76345b5d31f9d45afa89f | bigcode/the-stack | train |
d68e133f32d77291399dfc9b | train | class | class MaxPool(Craft):
def __init__(self, kernel: tuple, stride=2, padding=0, scope='MPOOL'):
super(MaxPool, self).__init__(scope)
dim = len(kernel)
is_global = True if kernel[-1] < 0 else False
if is_global:
assert padding == 0
if dim == 1:
if is_glob... | class MaxPool(Craft):
| def __init__(self, kernel: tuple, stride=2, padding=0, scope='MPOOL'):
super(MaxPool, self).__init__(scope)
dim = len(kernel)
is_global = True if kernel[-1] < 0 else False
if is_global:
assert padding == 0
if dim == 1:
if is_global:
se... | 2:
self.pool = layers.GlobalMaxPool2D()
elif dim == 3:
self.pool = layers.GlobalMaxPool3D()
def call(self, x):
if backend.image_data_format() == 'channels_first':
return tf.expand_dims(tf.expand_dims(self.pool(x), axis=-1), axis=-1)
else:
retu... | 99 | 99 | 330 | 6 | 93 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | MaxPool | MaxPool | 773 | 811 | 773 | 773 | 0874befc1b4d8d9f317c1585b2da4989b8f9784e | bigcode/the-stack | train |
8e94e021f24b6a146712e594 | train | class | class Sqrt(Craft):
def __init__(self, scope='SQRT'):
super(Sqrt, self).__init__(scope)
def run(self, t):
y = tf.sqrt(t)
return y
| class Sqrt(Craft):
| def __init__(self, scope='SQRT'):
super(Sqrt, self).__init__(scope)
def run(self, t):
y = tf.sqrt(t)
return y
| ) # pull negative values up to zero
hmap /= tf.reduce_max(hmap, axis=[1, 2, 3], keepdims=True) + 1e-6
del i_grad
return hmap
# ----------------------------------- Mathmatic -------------------------------------- #
class Sqrt(Craft):
| 64 | 64 | 47 | 6 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Sqrt | Sqrt | 527 | 533 | 527 | 527 | 2a27c3e6661e32de93302e4848eeb8f78b468a51 | bigcode/the-stack | train |
4916e1ff75fb656c9dd6a8da | train | class | class PolyLR(object):
def __init__(self, cutoff, power):
self.cutoff = cutoff
self.power = power
def __call__(self, lr):
return optimizers.schedules.PolynomialDecay(lr, self.cutoff, power=self.power)
| class PolyLR(object):
| def __init__(self, cutoff, power):
self.cutoff = cutoff
self.power = power
def __call__(self, lr):
return optimizers.schedules.PolynomialDecay(lr, self.cutoff, power=self.power)
| ()
class StepLR(object):
def __init__(self, period, factor):
self.period = period
self.factor = factor
def __call__(self, lr):
return optimizers.schedules.ExponentialDecay(lr, self.period, self.factor, staircase=True)
class PolyLR(object):
| 64 | 64 | 59 | 5 | 59 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | PolyLR | PolyLR | 1,244 | 1,250 | 1,244 | 1,244 | 298e4539164a0e4d4cb35b0b048bf66cbefe6df6 | bigcode/the-stack | train |
83651484cfa9f671627f9f8b | train | class | class Max(Craft):
def __init__(self, scope='MAX'):
super(Max, self).__init__(scope)
def run(self, x, axis=None):
if axis is None:
y = tf.reduce_max(x)
else:
y = tf.reduce_max(x, axis=axis)
return y
| class Max(Craft):
| def __init__(self, scope='MAX'):
super(Max, self).__init__(scope)
def run(self, x, axis=None):
if axis is None:
y = tf.reduce_max(x)
else:
y = tf.reduce_max(x, axis=axis)
return y
| scope='MEAN'):
super(Mean, self).__init__(scope)
def run(self, x, axis=None):
if axis is None:
y = tf.reduce_mean(x)
else:
y = tf.reduce_mean(x, axis=axis)
return y
class Max(Craft):
| 64 | 64 | 69 | 5 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Max | Max | 613 | 622 | 613 | 613 | d4502ba67d6fe71c4e02db0ed859e2febffd6fa5 | bigcode/the-stack | train |
686116c62d5aa322991c3ea2 | train | class | class Void(object):
def __init__(self):
self.iniz = 'ConstantV2'
| class Void(object):
| def __init__(self):
self.iniz = 'ConstantV2'
| self):
super(Prober, self).__init__(persistent=True)
class Nozzle(object):
def __init__(self):
pass
def __enter__(self):
return False
def __exit__(self, *args):
pass
# -------------------------------------- Layer --------------------------------------- #
class Void(obje... | 64 | 64 | 21 | 4 | 60 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Void | Void | 190 | 192 | 190 | 190 | bc3511882ba26ac8ad599f8fa939477947a9fa33 | bigcode/the-stack | train |
aa592df9dad9c6f36f71b663 | train | class | class Relu(Craft):
def __init__(self, scope='RELU'):
super(Relu, self).__init__(scope)
self.actv = layers.ReLU()
def run(self, x):
y = self.actv(x)
return y
| class Relu(Craft):
| def __init__(self, scope='RELU'):
super(Relu, self).__init__(scope)
self.actv = layers.ReLU()
def run(self, x):
y = self.actv(x)
return y
| ], padding[2*d+1]) for d in range(dim-1, -1, -1)]
self.pad = pad_fn(padding)
def run(self, x):
y = self.pool(self.pad(x))
return y
# ------------------------------------ Activation ------------------------------------ #
class Relu(Craft):
| 64 | 64 | 57 | 6 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Relu | Relu | 875 | 882 | 875 | 875 | 441c4dc6c7f80339e9952dbf42faf0eca54d6958 | bigcode/the-stack | train |
3ff181fc4e62529694e7f057 | train | class | class Grad(Craft):
def __init__(self, scope='GRAD'):
super(Grad, self).__init__(scope)
def run(self, i, o, pb):
g = pb.gradient(o, i)
return g
| class Grad(Craft):
| def __init__(self, scope='GRAD'):
super(Grad, self).__init__(scope)
def run(self, i, o, pb):
g = pb.gradient(o, i)
return g
| axis=axis)
return y
class Dot(Craft):
def __init__(self, scope='DOT'):
super(Dot, self).__init__(scope)
def run(self, x, y, in_batch=False):
z = x @ y
return z
class Grad(Craft):
| 64 | 64 | 52 | 5 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Grad | Grad | 662 | 668 | 662 | 662 | 5b4571e14509b35c2f344678433ceaf335c4eac3 | bigcode/the-stack | train |
247d680d05ca049633587bb3 | train | class | class Embed(Craft):
def __init__(self, ntoken, token_dim, scope='EMBED'):
super(Embed, self).__init__(scope)
self.embd = layers.Embedding(ntoken, token_dim, embeddings_regularizer=regularizers.l2(1))
def run(self, x):
y = self.embd(x)
return y
| class Embed(Craft):
| def __init__(self, ntoken, token_dim, scope='EMBED'):
super(Embed, self).__init__(scope)
self.embd = layers.Embedding(ntoken, token_dim, embeddings_regularizer=regularizers.l2(1))
def run(self, x):
y = self.embd(x)
return y
| )
y = self.fc(x)
permuted = [i for i in range(dim)]
permuted = permuted[:self.axis] + [dim - 1] + permuted[self.axis:-1]
y = y.transpose(*permuted)
return y
class Embed(Craft):
| 64 | 64 | 78 | 5 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Embed | Embed | 411 | 418 | 411 | 411 | 40635676d14cbccc842f0f8a9ff59f9b5f0d25e4 | bigcode/the-stack | train |
4f0f73a125cef08d03d2ae86 | train | class | class Upscale(Craft):
def __init__(self, scale: tuple, interp=NEAREST, scope='UPS'):
super(Upscale, self).__init__(scope)
dim = len(scale)
if dim == 1:
self.fn = layers.UpSampling1D(scale_factor=scale, mode=TF_INTERP[interp])
elif dim == 2:
self.fn = layers.Up... | class Upscale(Craft):
| def __init__(self, scale: tuple, interp=NEAREST, scope='UPS'):
super(Upscale, self).__init__(scope)
dim = len(scale)
if dim == 1:
self.fn = layers.UpSampling1D(scale_factor=scale, mode=TF_INTERP[interp])
elif dim == 2:
self.fn = layers.UpSampling2D(scale_facto... | )
return y
class Permute(Craft):
def __init__(self, scope='PERMUTE'):
super(Permute, self).__init__(scope)
def run(self, x, order):
y = tf.transpose(x, order)
return y
class Upscale(Craft):
| 64 | 64 | 177 | 6 | 57 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Upscale | Upscale | 738 | 753 | 738 | 738 | c5819ff04e068f678d140b64e0901f96f4b78ea9 | bigcode/the-stack | train |
a23ab30a1d501e9ef253df89 | train | class | class RMSProp(Craft):
def __init__(self, hull, lr, mmnt=0., wd=0, lr_decay=None, warmup=0,
grad_limit=-1, grad_accum=1, update_scope=None, scope='RMSPROP'):
super(RMSProp, self).__init__(scope)
self.hull = hull
self.wd = wd / 2.
self.update_scope = update_scope
... | class RMSProp(Craft):
| def __init__(self, hull, lr, mmnt=0., wd=0, lr_decay=None, warmup=0,
grad_limit=-1, grad_accum=1, update_scope=None, scope='RMSPROP'):
super(RMSProp, self).__init__(scope)
self.hull = hull
self.wd = wd / 2.
self.update_scope = update_scope
self.grad_accum = ... | _var'):
self._getVar()
target += tf.add_n(self.hull.losses)
curr_grads = self.hull._rudder.gradient(target + self.wd*tf.add_n(self.hull.losses), self.update_var)
# curr_grads = [g if g is not None else tf.zeros_like(v) for g, v in zip(curr_grads, self.update_var)]
if self.cnt... | 179 | 180 | 602 | 6 | 173 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | RMSProp | RMSProp | 1,406 | 1,462 | 1,406 | 1,406 | aea3a6899aaf541f64183579745ccb56bb8339ca | bigcode/the-stack | train |
4ea9e03f5f6fe876662856d0 | train | class | class Eigen(Craft):
def __init__(self, scope='EIGEN'):
super(Eigen, self).__init__(scope)
def run(self, m, in_pair=True):
if in_pair:
return tf.linalg.eig(m)
else:
return tf.linalg.eigvals(m)
| class Eigen(Craft):
| def __init__(self, scope='EIGEN'):
super(Eigen, self).__init__(scope)
def run(self, m, in_pair=True):
if in_pair:
return tf.linalg.eig(m)
else:
return tf.linalg.eigvals(m)
| (Craft):
def __init__(self, scope='QR'):
super(QR, self).__init__(scope)
def run(self, m, reduced=False):
q, r = tf.linalg.qr(m, full_matrices=not reduced)
return q, r
class Eigen(Craft):
| 64 | 64 | 65 | 5 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Eigen | Eigen | 684 | 692 | 684 | 684 | 91ece9e896505c37eccaa2cd285182dbbca8f735 | bigcode/the-stack | train |
8707aeefcb694ba78fc21a7a | train | class | class AccCls(Craft):
def __init__(self, multi_class, is_one_hot, scope='ACCCLS'):
super(AccCls, self).__init__(scope)
if multi_class:
assert not is_one_hot
self.mulcls = multi_class
self.ioh = is_one_hot
def run(self, x, y):
data_type = x.dtype
if sel... | class AccCls(Craft):
| def __init__(self, multi_class, is_one_hot, scope='ACCCLS'):
super(AccCls, self).__init__(scope)
if multi_class:
assert not is_one_hot
self.mulcls = multi_class
self.ioh = is_one_hot
def run(self, x, y):
data_type = x.dtype
if self.mulcls: # include b... | self.cost = losses.SparseCategoricalCrossentropy(from_logits=True, reduction=losses.Reduction.SUM)
def run(self, x, y):
z = self.cost(y, x)
return z/x.shape[0]
# ------------------------------------ Metric ------------------------------------ #
class AccCls(Craft):
| 64 | 64 | 191 | 6 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | AccCls | AccCls | 1,185 | 1,204 | 1,185 | 1,185 | 606fc6ecfb5343695a33ea109efc43dc50a28298 | bigcode/the-stack | train |
a7bf745eeffc8366656eb7c2 | train | class | class Sftm(Craft):
def __init__(self, axis=-1, scope='SFTM'):
super(Sftm, self).__init__(scope)
self.actv = layers.Softmax(axis)
def run(self, x):
y = self.actv(x)
return y
| class Sftm(Craft):
| def __init__(self, axis=-1, scope='SFTM'):
super(Sftm, self).__init__(scope)
self.actv = layers.Softmax(axis)
def run(self, x):
y = self.actv(x)
return y
| .tanh(x)
return y
class Sigm(Craft):
def __init__(self, scope='SIGM'):
super(Sigm, self).__init__(scope)
def run(self, x):
y = tf.math.sigmoid(x)
return y
class Sftm(Craft):
| 64 | 64 | 66 | 7 | 56 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Sftm | Sftm | 917 | 924 | 917 | 917 | 7c6cc51dc952de8c272b1f1616ab2ab0b9faf80c | bigcode/the-stack | train |
40dc49c32d1914edfb268b96 | train | class | class Adam(Craft):
def __init__(self, hull, lr, mmnt1=0.9, mmnt2=0.999, wd=0, lr_decay=None, warmup=0,
grad_limit=-1, grad_accum=1, update_scope=None, scope='ADAM'):
super(Adam, self).__init__(scope)
self.hull = hull
self.wd = wd / 2.
self.update_scope = update_scop... | class Adam(Craft):
| def __init__(self, hull, lr, mmnt1=0.9, mmnt2=0.999, wd=0, lr_decay=None, warmup=0,
grad_limit=-1, grad_accum=1, update_scope=None, scope='ADAM'):
super(Adam, self).__init__(scope)
self.hull = hull
self.wd = wd / 2.
self.update_scope = update_scope
self.grad... | not hasattr(self, 'update_var'):
self._getVar()
target += tf.add_n(self.hull.losses)
curr_grads = self.hull._rudder.gradient(target + self.wd*tf.add_n(self.hull.losses), self.update_var)
# curr_grads = [g if g is not None else tf.zeros_like(v) for g, v in zip(curr_grads, self.update... | 184 | 185 | 617 | 5 | 179 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Adam | Adam | 1,466 | 1,522 | 1,466 | 1,466 | 866809299042cada6e585771e3a696f08799e972 | bigcode/the-stack | train |
5cc157cc6d9c45bf97147e06 | train | class | class Prober(tf.GradientTape):
def __init__(self):
super(Prober, self).__init__(persistent=True)
| class Prober(tf.GradientTape):
| def __init__(self):
super(Prober, self).__init__(persistent=True)
| :
return craft.__dict[paths[-1]]
def __setitem__(self, key, value):
self.__dict[key] = value
class Rudder(tf.GradientTape):
def __init__(self):
super(Rudder, self).__init__()
class Prober(tf.GradientTape):
| 64 | 64 | 27 | 8 | 57 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Prober | Prober | 172 | 174 | 172 | 172 | dea4b198da059b07c22f8a82e643ad73b7cb2be7 | bigcode/the-stack | train |
610450f315bbfd6b9991937e | train | class | class WavyLR(object):
def __init__(self, period, dampen):
self.period = period
self.dampen = dampen
def __call__(self, lr):
return optimizers.schedules.CosineDecayRestarts(lr, self.period // 2, t_mul=1, m_mul=self.dampen)
| class WavyLR(object):
| def __init__(self, period, dampen):
self.period = period
self.dampen = dampen
def __call__(self, lr):
return optimizers.schedules.CosineDecayRestarts(lr, self.period // 2, t_mul=1, m_mul=self.dampen)
| .001)
class ExpLR(object):
def __init__(self, period, factor):
self.period = period
self.factor = factor
def __call__(self, lr):
return optimizers.schedules.ExponentialDecay(lr, self.period, self.factor)
class WavyLR(object):
| 64 | 64 | 72 | 6 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | WavyLR | WavyLR | 1,273 | 1,279 | 1,273 | 1,273 | 1dbee1723596828ae529f50010d43ebec3ed5aaf | bigcode/the-stack | train |
d43db1d7c64a28fce6bf4c3f | train | class | class Ones(object):
def __init__(self):
self.iniz = 'OnesV2'
| class Ones(object):
| def __init__(self):
self.iniz = 'OnesV2'
| init__(self):
self.iniz = 'RandomNormalV2'
class Uniform(object):
def __init__(self):
self.iniz = 'RandomUniformV2'
class Orthog(object):
def __init__(self):
self.iniz = 'OrthogonalV2'
class Ones(object):
| 64 | 64 | 22 | 4 | 60 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Ones | Ones | 214 | 216 | 214 | 214 | 60a776475c5a9b96a031689d93cf464be6ad6a6c | bigcode/the-stack | train |
6824f7a48399e06a7c9e8cbc | train | class | class ExpLR(object):
def __init__(self, period, factor):
self.period = period
self.factor = factor
def __call__(self, lr):
return optimizers.schedules.ExponentialDecay(lr, self.period, self.factor)
| class ExpLR(object):
| def __init__(self, period, factor):
self.period = period
self.factor = factor
def __call__(self, lr):
return optimizers.schedules.ExponentialDecay(lr, self.period, self.factor)
| self.cutoff, power=self.power)
class CosLR(object):
def __init__(self, period):
self.period = period
def __call__(self, lr):
return optimizers.schedules.CosineDecay(lr, self.period, lr * 0.001)
class ExpLR(object):
| 64 | 64 | 55 | 5 | 59 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | ExpLR | ExpLR | 1,263 | 1,269 | 1,263 | 1,263 | a5019424fde839896c420d4fdda22a69ce3a228e | bigcode/the-stack | train |
4d337c3ce2a1161b30e02317 | train | class | class Sigm(Craft):
def __init__(self, scope='SIGM'):
super(Sigm, self).__init__(scope)
def run(self, x):
y = tf.math.sigmoid(x)
return y
| class Sigm(Craft):
| def __init__(self, scope='SIGM'):
super(Sigm, self).__init__(scope)
def run(self, x):
y = tf.math.sigmoid(x)
return y
| .actv(x)
return y
class Tanh(Craft):
def __init__(self, scope='TANH'):
super(Tanh, self).__init__(scope)
def run(self, x):
y = tf.math.tanh(x)
return y
class Sigm(Craft):
| 64 | 64 | 49 | 6 | 57 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Sigm | Sigm | 907 | 913 | 907 | 907 | 4a80a1920caef599e6b68349bb50a4b23fd949ac | bigcode/the-stack | train |
95894a9aa1bea45197bf5973 | train | class | class _MP(layers.Layer):
def __init__(self, dim):
super(_MP, self).__init__()
if dim == 1:
self.pool = layers.GlobalMaxPool1D()
elif dim == 2:
self.pool = layers.GlobalMaxPool2D()
elif dim == 3:
self.pool = layers.GlobalMaxPool3D()
def call(se... | class _MP(layers.Layer):
| def __init__(self, dim):
super(_MP, self).__init__()
if dim == 1:
self.pool = layers.GlobalMaxPool1D()
elif dim == 2:
self.pool = layers.GlobalMaxPool2D()
elif dim == 3:
self.pool = layers.GlobalMaxPool3D()
def call(self, x):
if backen... | =scale, mode=TF_INTERP[interp])
else:
raise Exception('NEBULAE ERROR ⨷ %d-d upscaling is not supported.' % dim)
def run(self, x):
y = self.fn(x)
return y
class _MP(layers.Layer):
| 64 | 64 | 141 | 7 | 56 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | _MP | _MP | 757 | 771 | 757 | 757 | 15a862012c424892bcf44532e0dbe171db630ebe | bigcode/the-stack | train |
74817ee443730817a0395638 | train | class | class QR(Craft):
def __init__(self, scope='QR'):
super(QR, self).__init__(scope)
def run(self, m, reduced=False):
q, r = tf.linalg.qr(m, full_matrices=not reduced)
return q, r
| class QR(Craft):
| def __init__(self, scope='QR'):
super(QR, self).__init__(scope)
def run(self, m, reduced=False):
q, r = tf.linalg.qr(m, full_matrices=not reduced)
return q, r
| Grad(Craft):
def __init__(self, scope='GRAD'):
super(Grad, self).__init__(scope)
def run(self, i, o, pb):
g = pb.gradient(o, i)
return g
# ---------------------------------- Linear Algebra ---------------------------------- #
class QR(Craft):
| 64 | 64 | 61 | 5 | 59 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | QR | QR | 674 | 680 | 674 | 674 | 2eb83cf06a171b840bad19b9613af0c4a05353aa | bigcode/the-stack | train |
9d0b5ad2b21d3418227d4a6b | train | class | class _Interpad(layers.Layer):
def __init__(self, stride: list):
super(_Interpad, self).__init__()
self.stride = stride
def call(self, x):
dim = len(x.shape)
size = x.shape[2:]
assert len(size) == len(self.stride)
for d in range(dim-2):
step = list(x.... | class _Interpad(layers.Layer):
| def __init__(self, stride: list):
super(_Interpad, self).__init__()
self.stride = stride
def call(self, x):
dim = len(x.shape)
size = x.shape[2:]
assert len(size) == len(self.stride)
for d in range(dim-2):
step = list(x.shape[0:2]) + [1 if i==d else s... | , bias_initializer=b_init.iniz,
kernel_regularizer=regularizers.l2(1), bias_regularizer=regularizers.l2(1))
def run(self, x):
x = self.pad(x)
y = self.conv(x)
return y
class _Interpad(layers.Layer):
| 64 | 64 | 185 | 8 | 55 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | _Interpad | _Interpad | 278 | 295 | 278 | 278 | a41b875cf74ae48411c2979fd22b28d918c9ee83 | bigcode/the-stack | train |
2c9a4639e7e13ed2a2ccb785 | train | class | class Nozzle(object):
def __init__(self):
pass
def __enter__(self):
return False
def __exit__(self, *args):
pass
| class Nozzle(object):
| def __init__(self):
pass
def __enter__(self):
return False
def __exit__(self, *args):
pass
| self.__dict[key] = value
class Rudder(tf.GradientTape):
def __init__(self):
super(Rudder, self).__init__()
class Prober(tf.GradientTape):
def __init__(self):
super(Prober, self).__init__(persistent=True)
class Nozzle(object):
| 64 | 64 | 39 | 5 | 59 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Nozzle | Nozzle | 176 | 184 | 176 | 176 | 1a4843027dec92d4efbf311076a541d4af96d898 | bigcode/the-stack | train |
64d8d19f789277b2bc10c4b2 | train | class | class Normal(object):
def __init__(self):
self.iniz = 'RandomNormalV2'
| class Normal(object):
| def __init__(self):
self.iniz = 'RandomNormalV2'
| self.iniz = 'ConstantV2'
class XavierNorm(object):
def __init__(self):
self.iniz = 'GlorotNormalV2'
class XavierUnif(object):
def __init__(self):
self.iniz = 'GlorotUniformV2'
class Normal(object):
| 64 | 64 | 22 | 4 | 60 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Normal | Normal | 202 | 204 | 202 | 202 | e063b7254cc1d97157ef36b3a77b8b1f6013ab06 | bigcode/the-stack | train |
473645c7995e2da99ae713f3 | train | class | class Conv(Craft):
def __init__(self, in_chs, out_chs, kernel: tuple, stride=1, padding=0, dilation=1, group=1,
w_init=XavierNorm(), b_init=Zeros(), scope='CONV'):
'''
Args:
- in_chs: input channel
- out_chs: output channel
- kernel: kernel size (must be a tu... | class Conv(Craft):
| def __init__(self, in_chs, out_chs, kernel: tuple, stride=1, padding=0, dilation=1, group=1,
w_init=XavierNorm(), b_init=Zeros(), scope='CONV'):
'''
Args:
- in_chs: input channel
- out_chs: output channel
- kernel: kernel size (must be a tuple)
- stri... | GlorotNormalV2'
class XavierUnif(object):
def __init__(self):
self.iniz = 'GlorotUniformV2'
class Normal(object):
def __init__(self):
self.iniz = 'RandomNormalV2'
class Uniform(object):
def __init__(self):
self.iniz = 'RandomUniformV2'
class Orthog(object):
def __init__(self)... | 149 | 150 | 501 | 5 | 144 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Conv | Conv | 224 | 274 | 224 | 224 | 2851d96367b5ea3991bc9d08fc209621c42f7034 | bigcode/the-stack | train |
2457c18054fc28244dfb42e9 | train | class | class Sum(Craft):
def __init__(self, scope='SUM'):
super(Sum, self).__init__(scope)
def run(self, x, axis=None):
if axis is None:
y = tf.reduce_sum(x)
else:
y = tf.reduce_sum(x, axis=axis)
return y
| class Sum(Craft):
| def __init__(self, scope='SUM'):
super(Sum, self).__init__(scope)
def run(self, x, axis=None):
if axis is None:
y = tf.reduce_sum(x)
else:
y = tf.reduce_sum(x, axis=axis)
return y
| , scope='MIN'):
super(Min, self).__init__(scope)
def run(self, x, axis=None):
if axis is None:
y = tf.reduce_min(x)
else:
y = tf.reduce_min(x, axis=axis)
return y
class Sum(Craft):
| 64 | 64 | 70 | 5 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Sum | Sum | 639 | 648 | 639 | 639 | 8a1075d35fc96ffd64eb730f66863cceedc1b9fa | bigcode/the-stack | train |
651c73226e3996c2cbc29542 | train | class | class EMA(object):
def __init__(self, hull, decay_fn=lambda x: 0.9, scope='EMA'):
self.scope = scope
self.step = 0
self.decay_fn = decay_fn
self.hull = hull
self.hull.swapped = False
self.hull._in_ema_mode = True
self._subcraft = []
self._collect(self.... | class EMA(object):
| def __init__(self, hull, decay_fn=lambda x: 0.9, scope='EMA'):
self.scope = scope
self.step = 0
self.decay_fn = decay_fn
self.hull = hull
self.hull.swapped = False
self.hull._in_ema_mode = True
self._subcraft = []
self._collect(self.hull)
def _col... | [self.axis:-1]
y = y.transpose(*permuted)
return y
class Embed(Craft):
def __init__(self, ntoken, token_dim, scope='EMBED'):
super(Embed, self).__init__(scope)
self.embd = layers.Embedding(ntoken, token_dim, embeddings_regularizer=regularizers.l2(1))
def run(self, x):
... | 148 | 148 | 496 | 4 | 144 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | EMA | EMA | 433 | 494 | 433 | 433 | c6a13aecf04fdbc608128381825df7dc5a918ad1 | bigcode/the-stack | train |
374478e34508dfd9c32e1365 | train | class | class Dot(Craft):
def __init__(self, scope='DOT'):
super(Dot, self).__init__(scope)
def run(self, x, y, in_batch=False):
z = x @ y
return z
| class Dot(Craft):
| def __init__(self, scope='DOT'):
super(Dot, self).__init__(scope)
def run(self, x, y, in_batch=False):
z = x @ y
return z
| , scope='SUM'):
super(Sum, self).__init__(scope)
def run(self, x, axis=None):
if axis is None:
y = tf.reduce_sum(x)
else:
y = tf.reduce_sum(x, axis=axis)
return y
class Dot(Craft):
| 64 | 64 | 51 | 5 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Dot | Dot | 652 | 658 | 652 | 652 | 99cb53004b21d66f035c52726ad3d9afc85831b9 | bigcode/the-stack | train |
170adfe8c366fb55466ac8cf | train | class | class RetrieveInvalidEmailsInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the RetrieveInvalidEmails
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_APIKey(self, value):
"""
Set the valu... | class RetrieveInvalidEmailsInputSet(InputSet):
| """
An InputSet with methods appropriate for specifying the inputs to the RetrieveInvalidEmails
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_APIKey(self, value):
"""
Set the value of the APIKey input for this Choreo. ((requir... | ###############################################################################
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class RetrieveInvalidEm... | 217 | 217 | 725 | 9 | 208 | jordanemedlock/psychtruths | temboo/core/Library/SendGrid/WebAPI/InvalidEmails/RetrieveInvalidEmails.py | Python | RetrieveInvalidEmailsInputSet | RetrieveInvalidEmailsInputSet | 53 | 107 | 53 | 53 | 73772b15485c60bfff8ad17e7649c8f586261716 | bigcode/the-stack | train |
646cb29f74c984820266fced | train | class | class RetrieveInvalidEmailsChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return RetrieveInvalidEmailsResultSet(response, path)
| class RetrieveInvalidEmailsChoreographyExecution(ChoreographyExecution):
| def _make_result_set(self, response, path):
return RetrieveInvalidEmailsResultSet(response, path)
| """
Retrieve the value for the "Response" output from this Choreo execution. (The response from SendGrid. The format corresponds to the ResponseFormat input. Default is json.)
"""
return self._output.get('Response', None)
class RetrieveInvalidEmailsChoreographyExecution(ChoreographyExecution):
... | 64 | 64 | 37 | 14 | 50 | jordanemedlock/psychtruths | temboo/core/Library/SendGrid/WebAPI/InvalidEmails/RetrieveInvalidEmails.py | Python | RetrieveInvalidEmailsChoreographyExecution | RetrieveInvalidEmailsChoreographyExecution | 125 | 128 | 125 | 126 | 58fd00173a2862da304f0e8e65506b462145adc5 | bigcode/the-stack | train |
acd002eadef323daa79c828b | train | class | class RetrieveInvalidEmailsResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the RetrieveInvalidEmails Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
de... | class RetrieveInvalidEmailsResultSet(ResultSet):
| """
A ResultSet with methods tailored to the values returned by the RetrieveInvalidEmails Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Response(self):
"""
Retriev... | the date range for which blocks are to be retireved. The specified date must be in YYYY-MM-DD format, and must be earlier than the EndDate variable value.)
"""
super(RetrieveInvalidEmailsInputSet, self)._set_input('StartDate', value)
class RetrieveInvalidEmailsResultSet(ResultSet):
| 64 | 64 | 122 | 9 | 55 | jordanemedlock/psychtruths | temboo/core/Library/SendGrid/WebAPI/InvalidEmails/RetrieveInvalidEmails.py | Python | RetrieveInvalidEmailsResultSet | RetrieveInvalidEmailsResultSet | 110 | 123 | 110 | 110 | db92a20b465683fcc8e864eb31111f310e5f5126 | bigcode/the-stack | train |
dbb96f10f5d2bf512cf0c3d7 | train | class | class RetrieveInvalidEmails(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the RetrieveInvalidEmails Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(RetrieveInvalidEmails, self).__init... | class RetrieveInvalidEmails(Choreography):
| def __init__(self, temboo_session):
"""
Create a new instance of the RetrieveInvalidEmails Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(RetrieveInvalidEmails, self).__init__(temboo_session, '/Library/SendGrid/WebAPI... | .
#
#
###############################################################################
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class RetrieveInva... | 64 | 64 | 156 | 9 | 54 | jordanemedlock/psychtruths | temboo/core/Library/SendGrid/WebAPI/InvalidEmails/RetrieveInvalidEmails.py | Python | RetrieveInvalidEmails | RetrieveInvalidEmails | 34 | 51 | 34 | 35 | 6e434e936f3017aba7de31c6851ade62c3d1a9f3 | bigcode/the-stack | train |
f5a47914c291af7c2da59eb0 | train | function | def test():
runner = unittest.TextTestRunner()
return runner.run(suite())
| def test():
| runner = unittest.TextTestRunner()
return runner.run(suite())
| a.none()
a.none(1,2)
a.none(1,2,3,4)
a.none(1,2,3,4,foo=12)
def suite():
return unittest.TestSuite([
unittest.makeSuite(IntrospectTests),
])
def test():
| 64 | 64 | 18 | 3 | 61 | rsms/smisk | lib/smisk/test/util/introspect.py | Python | test | test | 155 | 157 | 155 | 155 | 589522ab25f1f9f5778103ec1bfdb60e63f8d22b | bigcode/the-stack | train |
0522bfba78e9e10b01dcd2f4 | train | class | class IntrospectTests(TestCase):
def setUp(self):
self.expect_hello_info = {
'name': 'hello',
'args': (
('one', Undefined),
('two', Undefined),
('three', None),
('four', 123),
('five', 'internets')
),
'varargs': False,
'varkw': False,
'm... | class IntrospectTests(TestCase):
| def setUp(self):
self.expect_hello_info = {
'name': 'hello',
'args': (
('one', Undefined),
('two', Undefined),
('three', None),
('four', 123),
('five', 'internets')
),
'varargs': False,
'varkw': False,
'method': True
}
def tes... | #!/usr/bin/env python
# encoding: utf-8
from smisk.test import *
from smisk.util.introspect import *
from smisk.util.type import Undefined
class A(object):
def __call__(self):
pass
def hello(self, one, two, three=None, four=123, five='internets'):
foo = 'oof'
bar = 'rab'
two = 14
for baz in foo... | 151 | 256 | 976 | 8 | 142 | rsms/smisk | lib/smisk/test/util/introspect.py | Python | IntrospectTests | IntrospectTests | 26 | 147 | 26 | 26 | d4700613edc12253d639fec35cddb781180169bd | bigcode/the-stack | train |
ed5d99df6e50191518e38d56 | train | class | class B(object):
def foo(self):
pass
| class B(object):
| def foo(self):
pass
| foo = 'oof'
bar = 'rab'
two = 14
for baz in foo:
pass
return locals()
def ping(self, filter=None, *argz, **kwargz):
pass
def none(self):
pass
class B(object):
| 64 | 64 | 12 | 4 | 59 | rsms/smisk | lib/smisk/test/util/introspect.py | Python | B | B | 22 | 24 | 22 | 22 | a130ce7f29229584b57bed26879a64366597cb19 | bigcode/the-stack | train |
c505977b4a9937e92d3c5678 | train | function | def suite():
return unittest.TestSuite([
unittest.makeSuite(IntrospectTests),
])
| def suite():
| return unittest.TestSuite([
unittest.makeSuite(IntrospectTests),
])
| This should not raise an exception
a.none = introspect.ensure_va_kwa(a.none)
a.none()
a.none(1,2)
a.none(1,2,3,4)
a.none(1,2,3,4,foo=12)
def suite():
| 63 | 64 | 20 | 3 | 60 | rsms/smisk | lib/smisk/test/util/introspect.py | Python | suite | suite | 150 | 153 | 150 | 150 | bdfddbcad37e2c86bfedb6994237b692eef2ad6d | bigcode/the-stack | train |
c713895d940547c112e8682f | train | class | class A(object):
def __call__(self):
pass
def hello(self, one, two, three=None, four=123, five='internets'):
foo = 'oof'
bar = 'rab'
two = 14
for baz in foo:
pass
return locals()
def ping(self, filter=None, *argz, **kwargz):
pass
def none(self):
pass
| class A(object):
| def __call__(self):
pass
def hello(self, one, two, three=None, four=123, five='internets'):
foo = 'oof'
bar = 'rab'
two = 14
for baz in foo:
pass
return locals()
def ping(self, filter=None, *argz, **kwargz):
pass
def none(self):
pass
| #!/usr/bin/env python
# encoding: utf-8
from smisk.test import *
from smisk.util.introspect import *
from smisk.util.type import Undefined
class A(object):
| 40 | 64 | 95 | 4 | 35 | rsms/smisk | lib/smisk/test/util/introspect.py | Python | A | A | 7 | 20 | 7 | 7 | 21ef017f9041176e1726b00fb8ada434eda3c52c | bigcode/the-stack | train |
b07559f2a77cc044391988e5 | train | class | class policy_pred(object):
def __init__(self, agent_class, model_type=None):
self.X = None # nn input
self.y = None # nn output
self.input_dim = None
self.action_space = None
self.model = None
# Create the directory for this particular model
self.path = os... | class policy_pred(object):
| def __init__(self, agent_class, model_type=None):
self.X = None # nn input
self.y = None # nn output
self.input_dim = None
self.action_space = None
self.model = None
# Create the directory for this particular model
self.path = os.path.join("model", agent_c... | # Developed by Lorenzo Mambretti, Justin Wang
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://github.com/jtwwang/hanabi/blob/master/LICENSE
#
# Unless required by applicable law... | 230 | 256 | 872 | 5 | 225 | MBlogs/hanabi-learning-environment | hanabi_learning_environment/agents/ref_mcts/wang/policy_pred.py | Python | policy_pred | policy_pred | 26 | 155 | 26 | 26 | d89cb6fbdd4b54556635023f1c00afafc4b0c0d8 | bigcode/the-stack | train |
d9b2145be8fb7b932c5f1e16 | train | class | class Vertice:
def __init__(self,rotulo):
self.rotulo = rotulo
self.visitado = False
self.predecessor = ""
self.cor = 0
self.raiz = False
self.distancia = 0
def igualA(self,r):
return r == self.rotulo
def foiVisitado(self):
return self.visit... | class Vertice:
| def __init__(self,rotulo):
self.rotulo = rotulo
self.visitado = False
self.predecessor = ""
self.cor = 0
self.raiz = False
self.distancia = 0
def igualA(self,r):
return r == self.rotulo
def foiVisitado(self):
return self.visitado
def re... | #Bruno Marchi Pires
class Vertice:
| 12 | 64 | 137 | 4 | 7 | Brunokrk/TEG | trabalho1/Vertice.py | Python | Vertice | Vertice | 2 | 27 | 2 | 2 | 9231798829d2d46aa8a33b31c092fc915d819a13 | bigcode/the-stack | train |
37bd9de2c8330b3a53d2beb8 | train | class | class KSLoader():
'''
Class used for creating data loaders for the burgers equation
'''
def __init__(self, shuffle=True):
self.shuffle = shuffle
def createTrainingLoader(self, data_dir, cases, n_init, dt=0.1, batch_size=64):
'''
Loads in training data from matlab simulat... | class KSLoader():
| '''
Class used for creating data loaders for the burgers equation
'''
def __init__(self, shuffle=True):
self.shuffle = shuffle
def createTrainingLoader(self, data_dir, cases, n_init, dt=0.1, batch_size=64):
'''
Loads in training data from matlab simulator
Args:
... | from torch.utils.data import DataLoader, TensorDataset
import torch
import numpy as np
class KSLoader():
| 23 | 256 | 1,085 | 4 | 18 | tailintalent/ar-pde-cnn | ONED_KS_SWAG/utils/ksLoader.py | Python | KSLoader | KSLoader | 5 | 114 | 5 | 5 | 61891fdbfd89e7df32ac98af3cdf3f083968d0c8 | bigcode/the-stack | train |
ad689e3670080170a12dad5e | train | class | @test_util.run_all_without_tensor_float_32(
"XLA QR op calls matmul. Also, matmul used for verification. Also with "
'TensorFloat-32, mysterious "Unable to launch cuBLAS gemm" error '
"occasionally occurs")
# TODO(b/165435566): Fix "Unable to launch cuBLAS gemm" error
class QrOpTest(xla_test.XLATestCase, pa... | @test_util.run_all_without_tensor_float_32(
"XLA QR op calls matmul. Also, matmul used for verification. Also with "
'TensorFloat-32, mysterious "Unable to launch cuBLAS gemm" error '
"occasionally occurs")
# TODO(b/165435566): Fix "Unable to launch cuBLAS gemm" error
class QrOpTest(xla_test.XLATestCase, pa... | def AdjustedNorm(self, x):
"""Computes the norm of matrices in 'x', adjusted for dimension and type."""
norm = np.linalg.norm(x, axis=(-2, -1))
return norm / (max(x.shape[-2:]) * np.finfo(x.dtype).eps)
def CompareOrthogonal(self, x, y, rank):
# We only compare the first 'rank' orthogonal vectors si... | required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==========... | 256 | 256 | 1,312 | 96 | 159 | ming-hu427/tensorflow | tensorflow/compiler/tests/qr_op_test.py | Python | QrOpTest | QrOpTest | 34 | 142 | 34 | 40 | f59081e5e3148e36e173e26c0e435b061f45e312 | bigcode/the-stack | train |
180a5867f8116752b01e9232 | train | class | class AttributeInconsistencyException(Exception):
"""
Raised when the attributes in a Description are inconsistent.
Inconsistency is defined when values do not meet their respective schema, or if the values
are not of an allowed type.
"""
pass
| class AttributeInconsistencyException(Exception):
| """
Raised when the attributes in a Description are inconsistent.
Inconsistency is defined when values do not meet their respective schema, or if the values
are not of an allowed type.
"""
pass
| return self.latitude == other.latitude and self.longitude == other.longitude
"""
The allowable types that an Attribute can have
"""
ATTRIBUTE_TYPES = Union[float, str, bool, int, Location]
ALLOWED_ATTRIBUTE_TYPES = [float, str, bool, int, Location]
class AttributeInconsistencyException(Exception):
| 64 | 64 | 54 | 8 | 56 | ejfitzgerald/agents-aea | aea/helpers/search/models.py | Python | AttributeInconsistencyException | AttributeInconsistencyException | 75 | 83 | 75 | 75 | 11ae0c5754f8c807457953daf9abc6e9a7247572 | bigcode/the-stack | train |
00615d4fe88c5fad00ec19ca | train | class | class Location:
"""Data structure to represent locations (i.e. a pair of latitude and longitude)."""
def __init__(self, latitude: float, longitude: float):
"""
Initialize a location.
:param latitude: the latitude of the location.
:param longitude: the longitude of the location.... | class Location:
| """Data structure to represent locations (i.e. a pair of latitude and longitude)."""
def __init__(self, latitude: float, longitude: float):
"""
Initialize a location.
:param latitude: the latitude of the location.
:param longitude: the longitude of the location.
"""
... | # nosec
from abc import ABC, abstractmethod
from copy import deepcopy
from enum import Enum
from math import asin, cos, radians, sin, sqrt
from typing import Any, Dict, List, Mapping, Optional, Tuple, Type, Union, cast
logger = logging.getLogger(__name__)
class Location:
| 67 | 67 | 226 | 3 | 64 | ejfitzgerald/agents-aea | aea/helpers/search/models.py | Python | Location | Location | 33 | 65 | 33 | 33 | 472aec3f7737c5e39c176d4b29113ccfdc9907a1 | bigcode/the-stack | train |
506814ba95fcd2c976dfdaf7 | train | class | class Query:
"""This class lets you build a query for the OEF."""
def __init__(
self, constraints: List[ConstraintExpr], model: Optional[DataModel] = None
) -> None:
"""
Initialize a query.
:param constraints: a list of constraint expressions.
:param model: the data... | class Query:
| """This class lets you build a query for the OEF."""
def __init__(
self, constraints: List[ConstraintExpr], model: Optional[DataModel] = None
) -> None:
"""
Initialize a query.
:param constraints: a list of constraint expressions.
:param model: the data model that t... | set,
} and not isinstance(value, type(self.constraint_type.value)):
return False
# dispatch the check to the right implementation for the concrete constraint type.
return self.constraint_type.check(value)
def is_valid(self, data_model: DataModel) -> bool:
"""
C... | 229 | 229 | 764 | 3 | 226 | ejfitzgerald/agents-aea | aea/helpers/search/models.py | Python | Query | Query | 759 | 855 | 759 | 759 | d0dadc20b6ad9d6778ba8233a61fc971f040b3c0 | bigcode/the-stack | train |
9a5b53b3acfca945cec30596 | train | class | class Or(ConstraintExpr):
"""Implementation of the 'Or' constraint expression."""
def __init__(self, constraints: List[ConstraintExpr]):
"""
Initialize an 'Or' expression.
:param constraints: the list of constraints expressions (in disjunction).
"""
self.constraints = c... | class Or(ConstraintExpr):
| """Implementation of the 'Or' constraint expression."""
def __init__(self, constraints: List[ConstraintExpr]):
"""
Initialize an 'Or' expression.
:param constraints: the list of constraints expressions (in disjunction).
"""
self.constraints = constraints
def check(... | ) < 2: # pragma: nocover # TODO: do we need this check?
raise ValueError(
"Invalid input value for type '{}': number of "
"subexpression must be at least 2.".format(type(self).__name__)
)
for constraint in self.constraints:
constraint.check_v... | 113 | 113 | 379 | 6 | 106 | ejfitzgerald/agents-aea | aea/helpers/search/models.py | Python | Or | Or | 576 | 622 | 576 | 576 | 13c0609a7816f3f03217866658e69f86ebed5028 | bigcode/the-stack | train |
53793918421bdf440971bd46 | train | class | class Constraint(ConstraintExpr):
"""The atomic component of a constraint expression."""
def __init__(self, attribute_name: str, constraint_type: ConstraintType):
"""
Initialize a constraint.
:param attribute_name: the name of the attribute to be constrained.
:param constraint_... | class Constraint(ConstraintExpr):
| """The atomic component of a constraint expression."""
def __init__(self, attribute_name: str, constraint_type: ConstraintType):
"""
Initialize a constraint.
:param attribute_name: the name of the attribute to be constrained.
:param constraint_type: the constraint type.
... | and self.constraints == other.constraints
class Not(ConstraintExpr):
"""Implementation of the 'Not' constraint expression."""
def __init__(self, constraint: ConstraintExpr):
"""
Initialize a 'Not' expression.
:param constraint: the constraint expression to negate.
"""
... | 256 | 256 | 877 | 6 | 249 | ejfitzgerald/agents-aea | aea/helpers/search/models.py | Python | Constraint | Constraint | 659 | 756 | 659 | 659 | 3dc9b6ce056bef053c8d2a3596f4634f1fda9bfb | bigcode/the-stack | train |
926eb77f10bf6631e88d4add | train | class | class Not(ConstraintExpr):
"""Implementation of the 'Not' constraint expression."""
def __init__(self, constraint: ConstraintExpr):
"""
Initialize a 'Not' expression.
:param constraint: the constraint expression to negate.
"""
self.constraint = constraint
def check... | class Not(ConstraintExpr):
| """Implementation of the 'Not' constraint expression."""
def __init__(self, constraint: ConstraintExpr):
"""
Initialize a 'Not' expression.
:param constraint: the constraint expression to negate.
"""
self.constraint = constraint
def check(self, description: Descrip... | expression must be at least 2.".format(type(self).__name__)
)
for constraint in self.constraints:
constraint.check_validity()
def __eq__(self, other): # pragma: nocover
"""Compare with another object."""
return isinstance(other, Or) and self.constraints == other.con... | 72 | 72 | 243 | 6 | 65 | ejfitzgerald/agents-aea | aea/helpers/search/models.py | Python | Not | Not | 625 | 656 | 625 | 625 | b97df663ff533f0336dd98ac9285a631fd3107ec | bigcode/the-stack | train |
f25225fe19c876c76a202636 | train | class | class Attribute:
"""Implements an attribute for an OEF data model."""
def __init__(
self,
name: str,
type_: Type[ATTRIBUTE_TYPES],
is_required: bool,
description: str = "",
):
"""
Initialize an attribute.
:param name: the name of the attribut... | class Attribute:
| """Implements an attribute for an OEF data model."""
def __init__(
self,
name: str,
type_: Type[ATTRIBUTE_TYPES],
is_required: bool,
description: str = "",
):
"""
Initialize an attribute.
:param name: the name of the attribute.
:param... | , bool, int, Location]
class AttributeInconsistencyException(Exception):
"""
Raised when the attributes in a Description are inconsistent.
Inconsistency is defined when values do not meet their respective schema, or if the values
are not of an allowed type.
"""
pass
class Attribute:
| 64 | 64 | 193 | 3 | 60 | ejfitzgerald/agents-aea | aea/helpers/search/models.py | Python | Attribute | Attribute | 86 | 116 | 86 | 86 | 969dbfd8729d51f0fdfc14e0ba3dbf1d53be232d | bigcode/the-stack | train |
714c809a077a939277610ba6 | train | class | class Description:
"""Implements an OEF description."""
def __init__(
self,
values: Mapping[str, ATTRIBUTE_TYPES],
data_model: Optional[DataModel] = None,
data_model_name: str = "",
):
"""
Initialize the description object.
:param values: the values ... | class Description:
| """Implements an OEF description."""
def __init__(
self,
values: Mapping[str, ATTRIBUTE_TYPES],
data_model: Optional[DataModel] = None,
data_model_name: str = "",
):
"""
Initialize the description object.
:param values: the values in the description.... | _check_validity(self):
# check if there are duplicated attribute names
attribute_names = [attribute.name for attribute in self.attributes]
if len(attribute_names) != len(set(attribute_names)):
raise ValueError(
"Invalid input value for type '{}': duplicated attribute... | 256 | 256 | 954 | 3 | 253 | ejfitzgerald/agents-aea | aea/helpers/search/models.py | Python | Description | Description | 175 | 298 | 175 | 175 | 1f40ffcbc3b39eea846715c0de5d6f6d0bee6891 | bigcode/the-stack | train |
60b7b3ee0655a91768dd1c80 | train | class | class ConstraintTypes(Enum):
"""Types of constraint."""
EQUAL = "=="
NOT_EQUAL = "!="
LESS_THAN = "<"
LESS_THAN_EQ = "<="
GREATER_THAN = ">"
GREATER_THAN_EQ = ">="
WITHIN = "within"
IN = "in"
NOT_IN = "not_in"
DISTANCE = "distance"
def __str__(self): # pragma: nocover
... | class ConstraintTypes(Enum):
| """Types of constraint."""
EQUAL = "=="
NOT_EQUAL = "!="
LESS_THAN = "<"
LESS_THAN_EQ = "<="
GREATER_THAN = ">"
GREATER_THAN_EQ = ">="
WITHIN = "within"
IN = "in"
NOT_IN = "not_in"
DISTANCE = "distance"
def __str__(self): # pragma: nocover
"""Get the string rep... | corresponds with this class.
:return: A new instance of this class that matches the protocol buffer object in the 'description_protobuf_object' argument.
"""
service_description = pickle.loads( # nosec
description_protobuf_object.description
)
return service_descrip... | 64 | 64 | 108 | 5 | 58 | ejfitzgerald/agents-aea | aea/helpers/search/models.py | Python | ConstraintTypes | ConstraintTypes | 301 | 317 | 301 | 301 | f5eba8a610090a9a2710d78002aa1b0b90b3b0d9 | bigcode/the-stack | train |
91ab6f2f6f5fcc054e0965e0 | train | function | def haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""
Compute the Haversine distance between two locations (i.e. two pairs of latitude and longitude).
:param lat1: the latitude of the first location.
:param lon1: the longitude of the first location.
:param lat2: the latitu... | def haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
| """
Compute the Haversine distance between two locations (i.e. two pairs of latitude and longitude).
:param lat1: the latitude of the first location.
:param lon1: the longitude of the first location.
:param lat2: the latitude of the second location.
:param lon2: the longitude of the second loca... | this class.
:return: A new instance of this class that matches the protocol buffer object in the 'query_protobuf_object' argument.
"""
query = pickle.loads(query_protobuf_object.query_bytes) # nosec
return query
def haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float... | 79 | 79 | 266 | 27 | 51 | ejfitzgerald/agents-aea | aea/helpers/search/models.py | Python | haversine | haversine | 858 | 877 | 858 | 858 | 3a1f35ede3c2b235e46ba556db27929545af39d2 | bigcode/the-stack | train |
348a070f8cf941e70340fec0 | train | class | class ConstraintExpr(ABC):
"""Implementation of the constraint language to query the OEF node."""
@abstractmethod
def check(self, description: Description) -> bool:
"""
Check if a description satisfies the constraint expression.
:param description: the description to check.
... | class ConstraintExpr(ABC):
| """Implementation of the constraint language to query the OEF node."""
@abstractmethod
def check(self, description: Description) -> bool:
"""
Check if a description satisfies the constraint expression.
:param description: the description to check.
:return: True if the descr... | ) <= distance
else: # pragma: nocover
raise ValueError("Constraint type not recognized.")
def __eq__(self, other):
"""Check equality with another object."""
return (
isinstance(other, ConstraintType)
and self.value == other.value
and self.typ... | 75 | 75 | 251 | 6 | 69 | ejfitzgerald/agents-aea | aea/helpers/search/models.py | Python | ConstraintExpr | ConstraintExpr | 493 | 524 | 493 | 493 | 321487a94217dd4cdbd9f14d900b1eae84f9034b | bigcode/the-stack | train |
eee85f80248970815c3ff9c5 | train | class | class DataModel:
"""Implements an OEF data model."""
def __init__(self, name: str, attributes: List[Attribute], description: str = ""):
"""
Initialize a data model.
:param name: the name of the data model.
:param attributes: the attributes of the data model.
"""
... | class DataModel:
| """Implements an OEF data model."""
def __init__(self, name: str, attributes: List[Attribute], description: str = ""):
"""
Initialize a data model.
:param name: the name of the data model.
:param attributes: the attributes of the data model.
"""
self.name: str ... | self.type = type_
self.is_required = is_required
self.description = description
def __eq__(self, other):
"""Compare with another object."""
return (
isinstance(other, Attribute)
and self.name == other.name
and self.type == other.type
... | 76 | 76 | 255 | 4 | 72 | ejfitzgerald/agents-aea | aea/helpers/search/models.py | Python | DataModel | DataModel | 119 | 153 | 119 | 119 | 48cb787eb8b21239bf2acdba2cc6545a89b28f91 | bigcode/the-stack | train |
a49dddd8c8468a0b9e54a2ad | train | function | def generate_data_model(
model_name: str, attribute_values: Mapping[str, ATTRIBUTE_TYPES]
) -> DataModel:
"""
Generate a data model that matches the values stored in this description.
That is, for each attribute (name, value), generate an Attribute.
It is assumed that each attribute is required.
... | def generate_data_model(
model_name: str, attribute_values: Mapping[str, ATTRIBUTE_TYPES]
) -> DataModel:
| """
Generate a data model that matches the values stored in this description.
That is, for each attribute (name, value), generate an Attribute.
It is assumed that each attribute is required.
:param model_name: the name of the model.
:param attribute_values: the values of each attribute
:re... | ) -> bool:
"""Compare with another object."""
return (
isinstance(other, DataModel)
and self.name == other.name
and self.attributes == other.attributes
)
def generate_data_model(
model_name: str, attribute_values: Mapping[str, ATTRIBUTE_TYPES]
) -> DataMod... | 64 | 64 | 135 | 25 | 39 | ejfitzgerald/agents-aea | aea/helpers/search/models.py | Python | generate_data_model | generate_data_model | 156 | 172 | 156 | 158 | 5883add48023f3c2029251e89835d50ebd6110e1 | bigcode/the-stack | train |
529cae97b7a5a499ba955fd3 | train | class | class And(ConstraintExpr):
"""Implementation of the 'And' constraint expression."""
def __init__(self, constraints: List[ConstraintExpr]):
"""
Initialize an 'And' expression.
:param constraints: the list of constraints expression (in conjunction).
"""
self.constraints =... | class And(ConstraintExpr):
| """Implementation of the 'And' constraint expression."""
def __init__(self, constraints: List[ConstraintExpr]):
"""
Initialize an 'And' expression.
:param constraints: the list of constraints expression (in conjunction).
"""
self.constraints = constraints
def check... | _model: the data model used to check the validity of the constraint expression.
:return: ``True`` if the constraint expression is valid wrt the data model, ``False`` otherwise.
"""
def check_validity(self) -> None: # pylint: disable=no-self-use # pragma: nocover
"""
Check whether ... | 113 | 113 | 379 | 6 | 106 | ejfitzgerald/agents-aea | aea/helpers/search/models.py | Python | And | And | 527 | 573 | 527 | 527 | 621ec34319c51e62fa274f8b923c58f7790a818f | bigcode/the-stack | train |
f273e7938b5405d676fafed6 | train | class | class ConstraintType:
"""
Type of constraint.
Used with the Constraint class, this class allows to specify constraint over attributes.
Examples:
Equal to three
>>> equal_3 = ConstraintType(ConstraintTypes.EQUAL, 3)
You can also specify a type of constraint by using its string repr... | class ConstraintType:
| """
Type of constraint.
Used with the Constraint class, this class allows to specify constraint over attributes.
Examples:
Equal to three
>>> equal_3 = ConstraintType(ConstraintTypes.EQUAL, 3)
You can also specify a type of constraint by using its string representation, e.g.:
... | .description = description_from_message_bytes
@classmethod
def decode(cls, description_protobuf_object) -> "Description":
"""
Decode a protocol buffer object that corresponds with this class into an instance of this class.
A new instance of this class must be created that matches the p... | 256 | 256 | 1,487 | 4 | 252 | ejfitzgerald/agents-aea | aea/helpers/search/models.py | Python | ConstraintType | ConstraintType | 320 | 490 | 320 | 320 | b9f4a2252d298e146220d8e429e7edab9f0ea085 | bigcode/the-stack | train |
122a9c0cab505e0f158c19c4 | train | function | def NovosphingobiumAromaticivorans(
directed: bool = False,
verbose: int = 2,
cache_path: str = "graphs/string",
**additional_graph_kwargs: Dict
) -> EnsmallenGraph:
"""Return new instance of the Novosphingobium aromaticivorans graph.
The graph is automatically retrieved from the STRING reposit... | def NovosphingobiumAromaticivorans(
directed: bool = False,
verbose: int = 2,
cache_path: str = "graphs/string",
**additional_graph_kwargs: Dict
) -> EnsmallenGraph:
| """Return new instance of the Novosphingobium aromaticivorans graph.
The graph is automatically retrieved from the STRING repository.
Parameters
-------------------
directed: bool = False,
Wether to load the graph as directed or undirected.
By default false.
verbose: int = ... | need to run a link prediction task with validation,
# you can split the graph using a connected holdout as follows:
train_graph, validation_graph = graph.connected_holdout(
# You can use an 80/20 split the holdout, for example.
train_size=0.8,
# The random state is used to reproduce the... | 256 | 256 | 933 | 52 | 203 | caufieldjh/ensmallen_graph | bindings/python/ensmallen_graph/datasets/string/novosphingobiumaromaticivorans.py | Python | NovosphingobiumAromaticivorans | NovosphingobiumAromaticivorans | 84 | 190 | 84 | 89 | 532c60eec6c332acb59bc28a87216feb53e051a6 | bigcode/the-stack | train |
e2a73885093b3cf4431d62dc | train | class | class TestSqsProvider:
def test_list_queues(self, sqs_client, sqs_create_queue):
queue_names = [
"a-test-queue-" + short_uid(),
"a-test-queue-" + short_uid(),
"b-test-queue-" + short_uid(),
]
# create three queues with prefixes and collect their urls
... | class TestSqsProvider:
| def test_list_queues(self, sqs_client, sqs_create_queue):
queue_names = [
"a-test-queue-" + short_uid(),
"a-test-queue-" + short_uid(),
"b-test-queue-" + short_uid(),
]
# create three queues with prefixes and collect their urls
queue_urls = []
... | _LAMBDA_LIBS, TEST_LAMBDA_PYTHON
TEST_QUEUE_NAME = "TestQueue"
TEST_POLICY = """
{
"Version":"2012-10-17",
"Statement":[
{
"Effect": "Allow",
"Principal": { "AWS": "*" },
"Action": "sqs:SendMessage",
"Resource": "'$sqs_queue_arn'",
"Condition":{
"ArnEquals":{
"aws... | 256 | 256 | 14,444 | 6 | 250 | rubencosta/localstack | tests/integration/test_sqs.py | Python | TestSqsProvider | TestSqsProvider | 59 | 1,524 | 59 | 59 | aac55d6e39db4694fd121281b7456e1da6f860d6 | bigcode/the-stack | train |
957e734d61dae0ed42536a14 | train | class | class TestSqsLambdaIntegration:
pass
| class TestSqsLambdaIntegration:
| pass
| MD5OfBody")
def get_region():
return os.environ.get("AWS_DEFAULT_REGION") or TEST_REGION
# TODO: test visibility timeout (with various ways to set them: queue attributes, receive parameter, update call)
# TODO: test message attributes and message system attributes
class TestSqsLambdaIntegration:
| 64 | 64 | 10 | 7 | 56 | rubencosta/localstack | tests/integration/test_sqs.py | Python | TestSqsLambdaIntegration | TestSqsLambdaIntegration | 1,535 | 1,536 | 1,535 | 1,535 | 7bd91969f85ea363bf66ccbdcac717a400205a77 | bigcode/the-stack | train |
95fbd1f822312cc257759d32 | train | function | def get_region():
return os.environ.get("AWS_DEFAULT_REGION") or TEST_REGION
| def get_region():
| return os.environ.get("AWS_DEFAULT_REGION") or TEST_REGION
| _duplicate.get("MessageId") == result_receive_duplicate.get("Messages")[
0
].get("MessageId")
assert result_send_duplicate.get("MD5OfMessageBody") == result_receive_duplicate.get(
"Messages"
)[0].get("MD5OfBody")
def get_region():
| 64 | 64 | 18 | 4 | 60 | rubencosta/localstack | tests/integration/test_sqs.py | Python | get_region | get_region | 1,527 | 1,528 | 1,527 | 1,527 | 4f57bddb46a3892e267d29145170db6f63be69d7 | bigcode/the-stack | train |
0d24f8974c25082d77788de2 | train | class | class HyperDTEstimator(BaseEstimator):
def __init__(self, task, reward_metric, max_trials=30, epochs=100, earlystop_rounds=30, time_limit=3600,
expected_reward=None, **kwargs):
super(HyperDTEstimator, self).__init__(task)
self.name = 'HyperDT'
self.kwargs = kwargs
se... | class HyperDTEstimator(BaseEstimator):
| def __init__(self, task, reward_metric, max_trials=30, epochs=100, earlystop_rounds=30, time_limit=3600,
expected_reward=None, **kwargs):
super(HyperDTEstimator, self).__init__(task)
self.name = 'HyperDT'
self.kwargs = kwargs
self.estimator = None
self.max_tr... | # -*- coding:utf-8 -*-
__author__ = 'yangjian'
"""
"""
import numpy as np
from deeptables.models.hyper_dt import HyperDT
from deeptables.models.hyper_dt import mini_dt_space
from hypernets.core import EarlyStoppingCallback
from hypernets.core.searcher import OptimizeDirection
from hypernets.searchers import EvolutionS... | 97 | 121 | 404 | 9 | 87 | Enpen/Hypernets | hypernets/tabular/evaluator/hyperdt.py | Python | HyperDTEstimator | HyperDTEstimator | 17 | 57 | 17 | 17 | e83918e08f556ac9aa61ed0a4e2a317553daf27c | bigcode/the-stack | train |
604987dafb1df459e6f635e1 | train | class | class TechnicalAnalysis(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type... | class TechnicalAnalysis(object):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The... | # coding: utf-8
"""
Finnhub API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
fro... | 97 | 238 | 795 | 5 | 91 | gavinjay/finnhub-python | finnhub/models/technical_analysis.py | Python | TechnicalAnalysis | TechnicalAnalysis | 21 | 148 | 21 | 21 | 3c181e12fe05d8f7eca1acf1065bd6a98719c866 | bigcode/the-stack | train |
0d0b6308a0798bb5349157c4 | train | function | @bp.route("/<int:user_id>/roles", methods=["GET"])
@utils.auth_required
async def fetch_user_roles(user_id: int):
"""Fetch the specific users roles"""
query = """
SELECT json_agg(json_build_object(
'name', r.name,
'base', r.base,
'id', r.id::TEXT,
'color', r.color,
... | @bp.route("/<int:user_id>/roles", methods=["GET"])
@utils.auth_required
async def fetch_user_roles(user_id: int):
| """Fetch the specific users roles"""
query = """
SELECT json_agg(json_build_object(
'name', r.name,
'base', r.base,
'id', r.id::TEXT,
'color', r.color,
'position', r.position,
'permissions', r.permissions::TEXT
))
FROM roles r WHERE r.id IN... | from quart import request, jsonify
import time
from api.models import User
from .. import bp
import utils
request: utils.Request
@bp.route("/<int:user_id>/roles", methods=["GET"])
@utils.auth_required
async def fetch_user_roles(user_id: int):
| 59 | 64 | 149 | 30 | 28 | mohamed040406/API | api/blueprints/users/views/roles.py | Python | fetch_user_roles | fetch_user_roles | 11 | 29 | 11 | 13 | 0f5b57f114f86afd9efc6dfd15c6f4c374124d6f | bigcode/the-stack | train |
9722bd3d920c6ce1e5499772 | train | class | class InstanceMetaGrokker(MetaGrokker):
component(InstanceGrokker)
| class InstanceMetaGrokker(MetaGrokker):
| component(InstanceGrokker)
| ker = multi_grokker
def grok(self, name, obj, **kw):
self.multi_grokker.register(obj())
return True
class ClassMetaGrokker(MetaGrokker):
component(ClassGrokker)
class InstanceMetaGrokker(MetaGrokker):
| 64 | 64 | 20 | 12 | 52 | cjwatson/martian | src/martian/core.py | Python | InstanceMetaGrokker | InstanceMetaGrokker | 253 | 254 | 253 | 253 | 3c17c94ebc3447c3ff29a83b786eb58c71094724 | bigcode/the-stack | train |
e519c424e0fd588407107dde | train | class | class ClassMetaGrokker(MetaGrokker):
component(ClassGrokker)
| class ClassMetaGrokker(MetaGrokker):
| component(ClassGrokker)
| ker - the grokker to register grokkers with.
"""
self.multi_grokker = multi_grokker
def grok(self, name, obj, **kw):
self.multi_grokker.register(obj())
return True
class ClassMetaGrokker(MetaGrokker):
| 64 | 64 | 19 | 12 | 51 | cjwatson/martian | src/martian/core.py | Python | ClassMetaGrokker | ClassMetaGrokker | 249 | 250 | 249 | 249 | 862d4aab569f28f70477c4f004211ac463476403 | bigcode/the-stack | train |
acef38fbf4ad56dcd17aea48 | train | function | def grok_package(module_info, grokker, **kw):
grok_module(module_info, grokker, **kw)
for sub_module_info in module_info.getSubModuleInfos():
grok_package(sub_module_info, grokker, **kw)
| def grok_package(module_info, grokker, **kw):
| grok_module(module_info, grokker, **kw)
for sub_module_info in module_info.getSubModuleInfos():
grok_package(sub_module_info, grokker, **kw)
| exclude_filter=None,
ignore_nonsource=True, **kw):
module_info = scan.module_info_from_dotted_name(
dotted_name, exclude_filter, ignore_nonsource)
grok_package(module_info, grokker, **kw)
def grok_package(module_info, grokker, **kw):
| 64 | 64 | 53 | 13 | 51 | cjwatson/martian | src/martian/core.py | Python | grok_package | grok_package | 224 | 227 | 224 | 224 | b7419b752e578e1d9c23a1e30f5c12246aa18041 | bigcode/the-stack | train |
347eeee37c3c7e0270315e3f | train | class | class MetaMultiGrokker(MultiGrokker):
"""Multi grokker which comes pre-registered with meta-grokkers.
"""
def clear(self):
super(MetaMultiGrokker, self).clear()
# bootstrap the meta-grokkers
self.register(ClassMetaGrokker(self))
self.register(InstanceMetaGrokker(self))
... | class MetaMultiGrokker(MultiGrokker):
| """Multi grokker which comes pre-registered with meta-grokkers.
"""
def clear(self):
super(MetaMultiGrokker, self).clear()
# bootstrap the meta-grokkers
self.register(ClassMetaGrokker(self))
self.register(InstanceMetaGrokker(self))
self.register(GlobalMetaGrokker(sel... | kkers(name, obj)
elif isinstance(obj, types.ModuleType):
return self._multi_global_grokker.grokkers(name, obj)
else:
return self._multi_instance_grokker.grokkers(name, obj)
class MetaMultiGrokker(MultiGrokker):
| 64 | 64 | 90 | 12 | 52 | cjwatson/martian | src/martian/core.py | Python | MetaMultiGrokker | MetaMultiGrokker | 205 | 214 | 205 | 205 | ef4d1278fc87dbbce5570b77777d978a9c12cf4d | bigcode/the-stack | train |
ea7dc02d4354692faaa6e016 | train | class | class MultiGrokker(MultiGrokkerBase):
def __init__(self):
self.clear()
def register(self, grokker):
if isinstance(grokker, InstanceGrokker):
self._multi_instance_grokker.register(grokker)
elif isinstance(grokker, ClassGrokker):
self._multi_class_grokker.register... | class MultiGrokker(MultiGrokkerBase):
| def __init__(self):
self.clear()
def register(self, grokker):
if isinstance(grokker, InstanceGrokker):
self._multi_instance_grokker.register(grokker)
elif isinstance(grokker, ClassGrokker):
self._multi_class_grokker.register(grokker)
elif isinstance(grokk... | class__ is g.__class__:
return
self._grokkers.append(grokker)
def clear(self):
self._grokkers = []
def grokkers(self, name, module):
for grokker in self._grokkers:
yield grokker, name, module
class MultiGrokker(MultiGrokkerBase):
| 78 | 78 | 260 | 12 | 65 | cjwatson/martian | src/martian/core.py | Python | MultiGrokker | MultiGrokker | 176 | 202 | 176 | 177 | cac19af874fb002d32d3bcb25068165a7f821b3c | bigcode/the-stack | train |
4ae24da67206d0f87569506b | train | class | class MultiInstanceOrClassGrokkerBase(MultiGrokkerBase):
def __init__(self):
self.clear()
def register(self, grokker):
key = component.bind().get(grokker)
grokkers = self._grokkers.setdefault(key, [])
for g in grokkers:
if g.__class__ is grokker.__class__:
... | class MultiInstanceOrClassGrokkerBase(MultiGrokkerBase):
| def __init__(self):
self.clear()
def register(self, grokker):
key = component.bind().get(grokker)
grokkers = self._grokkers.setdefault(key, [])
for g in grokkers:
if g.__class__ is grokker.__class__:
return
grokkers.append(grokker)
def cl... | )
if not util.defined_locally(obj, module.__name__):
continue
if util.is_baseclass(obj):
continue
for t in grokker.grokkers(name, obj):
yield t
class MultiInstanceOrClassGrokkerBase(MultiGrokkerBase):
| 64 | 64 | 201 | 16 | 47 | cjwatson/martian | src/martian/core.py | Python | MultiInstanceOrClassGrokkerBase | MultiInstanceOrClassGrokkerBase | 115 | 140 | 115 | 116 | f7ff7c747fde54e335b694d1daf6b17d26bb34d1 | bigcode/the-stack | train |
0104ca14cc886db6b40e39b3 | train | class | class MetaGrokker(ClassGrokker):
def __init__(self, multi_grokker):
"""multi_grokker - the grokker to register grokkers with.
"""
self.multi_grokker = multi_grokker
def grok(self, name, obj, **kw):
self.multi_grokker.register(obj())
return True
| class MetaGrokker(ClassGrokker):
| def __init__(self, multi_grokker):
"""multi_grokker - the grokker to register grokkers with.
"""
self.multi_grokker = multi_grokker
def grok(self, name, obj, **kw):
self.multi_grokker.register(obj())
return True
| module_info.getModule(),
module_info=module_info, **kw)
# deep meta mode here - we define grokkers that can pick up the
# three kinds of grokker: ClassGrokker, InstanceGrokker and ModuleGrokker
class MetaGrokker(ClassGrokker):
| 64 | 64 | 79 | 10 | 53 | cjwatson/martian | src/martian/core.py | Python | MetaGrokker | MetaGrokker | 237 | 246 | 237 | 238 | a99ddf49aeded6ba8bc111c110969b46d2e9239e | bigcode/the-stack | train |
0338abcb80cfbb9afbc5979f | train | function | def grok_module(module_info, grokker, **kw):
grokker.grok(module_info.dotted_name, module_info.getModule(),
module_info=module_info, **kw)
| def grok_module(module_info, grokker, **kw):
| grokker.grok(module_info.dotted_name, module_info.getModule(),
module_info=module_info, **kw)
| k_package(module_info, grokker, **kw):
grok_module(module_info, grokker, **kw)
for sub_module_info in module_info.getSubModuleInfos():
grok_package(sub_module_info, grokker, **kw)
def grok_module(module_info, grokker, **kw):
| 64 | 64 | 39 | 13 | 51 | cjwatson/martian | src/martian/core.py | Python | grok_module | grok_module | 230 | 232 | 230 | 230 | 6019a67fd6c25ba22a101b8071fb74b84bf93ead | bigcode/the-stack | train |
91ff3c8a06bd09d130919df5 | train | class | class MultiInstanceGrokker(MultiInstanceOrClassGrokkerBase):
def get_bases(self, obj):
return inspect.getmro(obj.__class__)
| class MultiInstanceGrokker(MultiInstanceOrClassGrokkerBase):
| def get_bases(self, obj):
return inspect.getmro(obj.__class__)
| ers is None:
continue
for grokker in grokkers:
if grokker not in used_grokkers:
yield grokker, name, obj
used_grokkers.add(grokker)
class MultiInstanceGrokker(MultiInstanceOrClassGrokkerBase):
| 64 | 64 | 35 | 16 | 48 | cjwatson/martian | src/martian/core.py | Python | MultiInstanceGrokker | MultiInstanceGrokker | 143 | 146 | 143 | 144 | ffcffbeb1f98501d11fb6d1f9a4fd38e7248e23a | bigcode/the-stack | train |
ffe311dae68cb50455b6a78d | train | class | class ModuleGrokker(MultiGrokkerBase):
def __init__(self, grokker=None, prepare=None, finalize=None):
if grokker is None:
grokker = MultiGrokker()
self._grokker = grokker
self.prepare = prepare
self.finalize = finalize
def register(self, grokker):
self._grok... | class ModuleGrokker(MultiGrokkerBase):
| def __init__(self, grokker=None, prepare=None, finalize=None):
if grokker is None:
grokker = MultiGrokker()
self._grokker = grokker
self.prepare = prepare
self.finalize = finalize
def register(self, grokker):
self._grokker.register(grokker)
def clear(sel... | )
if grokked not in (True, False):
raise GrokError(
"%r returns %r instead of True or False." %
(g, grokked), None)
if grokked:
grokked_status = True
return grokked_status
def clear(self):
raise NotImpl... | 146 | 146 | 489 | 12 | 134 | cjwatson/martian | src/martian/core.py | Python | ModuleGrokker | ModuleGrokker | 49 | 112 | 49 | 50 | ae775d3f6ee1fde91b56460c0d9fe055cb0c5036 | bigcode/the-stack | train |
070cba14d6eb92bd67c611ce | train | function | def _grokker_sort_key(args):
"""Helper function to calculate sort order of grokker.
"""
grokker, name, obj = args
return priority.bind().get(grokker)
| def _grokker_sort_key(args):
| """Helper function to calculate sort order of grokker.
"""
grokker, name, obj = args
return priority.bind().get(grokker)
| grokked), None)
if grokked:
grokked_status = True
return grokked_status
def clear(self):
raise NotImplementedError
def grokkers(self, name, obj):
raise NotImplementedError
def _grokker_sort_key(args):
| 64 | 64 | 43 | 9 | 54 | cjwatson/martian | src/martian/core.py | Python | _grokker_sort_key | _grokker_sort_key | 42 | 46 | 42 | 42 | 6483dd884f2044baf804e0df72dc2e238c19a908 | bigcode/the-stack | train |
ecaba118a00754ca0418d3cf | train | function | def grok_dotted_name(dotted_name, grokker, exclude_filter=None,
ignore_nonsource=True, **kw):
module_info = scan.module_info_from_dotted_name(
dotted_name, exclude_filter, ignore_nonsource)
grok_package(module_info, grokker, **kw)
| def grok_dotted_name(dotted_name, grokker, exclude_filter=None,
ignore_nonsource=True, **kw):
| module_info = scan.module_info_from_dotted_name(
dotted_name, exclude_filter, ignore_nonsource)
grok_package(module_info, grokker, **kw)
| meta-grokkers
self.register(ClassMetaGrokker(self))
self.register(InstanceMetaGrokker(self))
self.register(GlobalMetaGrokker(self))
def grok_dotted_name(dotted_name, grokker, exclude_filter=None,
ignore_nonsource=True, **kw):
| 64 | 64 | 64 | 27 | 37 | cjwatson/martian | src/martian/core.py | Python | grok_dotted_name | grok_dotted_name | 217 | 221 | 217 | 218 | 99fe7c6013491bb4dd67d71f3870a715a9c676f3 | bigcode/the-stack | train |
62862e978471a42f1717ef24 | train | class | @implementer(IMultiGrokker)
class MultiGrokkerBase(GrokkerBase):
def register(self, grokker):
raise NotImplementedError
def grok(self, name, obj, **kw):
grokked_status = False
for g, name, obj in self.grokkers(name, obj):
grokked = g.grok(name, obj, **kw)
if gr... | @implementer(IMultiGrokker)
class MultiGrokkerBase(GrokkerBase):
| def register(self, grokker):
raise NotImplementedError
def grok(self, name, obj, **kw):
grokked_status = False
for g, name, obj in self.grokkers(name, obj):
grokked = g.grok(name, obj, **kw)
if grokked not in (True, False):
raise GrokError(
... | rokker
from martian.components import GlobalGrokker
from martian.error import GrokError
from martian.martiandirective import component, priority
from martian.compat3 import CLASS_TYPES
@implementer(IMultiGrokker)
class MultiGrokkerBase(GrokkerBase):
| 64 | 64 | 177 | 20 | 43 | cjwatson/martian | src/martian/core.py | Python | MultiGrokkerBase | MultiGrokkerBase | 15 | 39 | 15 | 17 | c824c926d24be17fb9d29c2be7a103cbaeb0cd32 | bigcode/the-stack | train |
535670f5a9b9e5b58fb04f04 | train | class | class GlobalMetaGrokker(MetaGrokker):
component(GlobalGrokker)
| class GlobalMetaGrokker(MetaGrokker):
| component(GlobalGrokker)
| self.multi_grokker.register(obj())
return True
class ClassMetaGrokker(MetaGrokker):
component(ClassGrokker)
class InstanceMetaGrokker(MetaGrokker):
component(InstanceGrokker)
class GlobalMetaGrokker(MetaGrokker):
| 64 | 64 | 19 | 12 | 52 | cjwatson/martian | src/martian/core.py | Python | GlobalMetaGrokker | GlobalMetaGrokker | 257 | 258 | 257 | 257 | e94132618980e68442ebdbb640b7748d0f31f0da | bigcode/the-stack | train |
51f52cd8a7ef0eaeabdcd127 | train | class | class MultiClassGrokker(MultiInstanceOrClassGrokkerBase):
def get_bases(self, obj):
if isinstance(obj, types.ModuleType):
return []
return inspect.getmro(obj)
| class MultiClassGrokker(MultiInstanceOrClassGrokkerBase):
| def get_bases(self, obj):
if isinstance(obj, types.ModuleType):
return []
return inspect.getmro(obj)
| obj
used_grokkers.add(grokker)
class MultiInstanceGrokker(MultiInstanceOrClassGrokkerBase):
def get_bases(self, obj):
return inspect.getmro(obj.__class__)
class MultiClassGrokker(MultiInstanceOrClassGrokkerBase):
| 64 | 64 | 46 | 16 | 48 | cjwatson/martian | src/martian/core.py | Python | MultiClassGrokker | MultiClassGrokker | 149 | 154 | 149 | 150 | f09cebaffaaa368e83acf8e2f95ed6f5d74f6037 | bigcode/the-stack | train |
67ca1f57964125827098b580 | train | class | class MultiGlobalGrokker(MultiGrokkerBase):
def __init__(self):
self.clear()
def register(self, grokker):
for g in self._grokkers:
if grokker.__class__ is g.__class__:
return
self._grokkers.append(grokker)
def clear(self):
self._grokkers = []
... | class MultiGlobalGrokker(MultiGrokkerBase):
| def __init__(self):
self.clear()
def register(self, grokker):
for g in self._grokkers:
if grokker.__class__ is g.__class__:
return
self._grokkers.append(grokker)
def clear(self):
self._grokkers = []
def grokkers(self, name, module):
... | ro(obj.__class__)
class MultiClassGrokker(MultiInstanceOrClassGrokkerBase):
def get_bases(self, obj):
if isinstance(obj, types.ModuleType):
return []
return inspect.getmro(obj)
class MultiGlobalGrokker(MultiGrokkerBase):
| 64 | 64 | 113 | 13 | 51 | cjwatson/martian | src/martian/core.py | Python | MultiGlobalGrokker | MultiGlobalGrokker | 157 | 173 | 157 | 158 | 39fc5782cb196580bf52fd0bd5c90002668f5203 | bigcode/the-stack | train |
12af3dff18de4e6c439ec1fa | train | class | class GrokkerRegistry(ModuleGrokker):
def __init__(self):
super(GrokkerRegistry, self).__init__(MetaMultiGrokker())
| class GrokkerRegistry(ModuleGrokker):
| def __init__(self):
super(GrokkerRegistry, self).__init__(MetaMultiGrokker())
| Grokker(MetaGrokker):
component(ClassGrokker)
class InstanceMetaGrokker(MetaGrokker):
component(InstanceGrokker)
class GlobalMetaGrokker(MetaGrokker):
component(GlobalGrokker)
class GrokkerRegistry(ModuleGrokker):
| 64 | 64 | 33 | 9 | 55 | cjwatson/martian | src/martian/core.py | Python | GrokkerRegistry | GrokkerRegistry | 261 | 264 | 261 | 262 | 2dc17ae1d63185bce5b82525ab12623f54251d04 | bigcode/the-stack | train |
91395cb02cfd1596a1439615 | train | function | def weight_neighbors(data_frame):
scale = preprocessing.MinMaxScaler(feature_range=(0.1, 1))
data_frame['weight'] = scale.fit_transform(data_frame[['weight']])
return data_frame
| def weight_neighbors(data_frame):
| scale = preprocessing.MinMaxScaler(feature_range=(0.1, 1))
data_frame['weight'] = scale.fit_transform(data_frame[['weight']])
return data_frame
| _rec, top_k=20):
topk_hotels = data_rec.sort_values(
by=('predict_rating'), ascending=False).head(top_k)
return topk_hotels['hotel_name']
#--- Change Rank's Neighbors(Ordinal) Into Weight's Neighbors ---#
def weight_neighbors(data_frame):
| 64 | 64 | 44 | 6 | 58 | 9Ten/Hotel-Recommender-System- | imp_main.py | Python | weight_neighbors | weight_neighbors | 225 | 228 | 225 | 225 | fed3bce4e9ab55af4ccd108a9d22c4a7576cfb47 | bigcode/the-stack | train |
0cca72acf8ed12d3d3d176cf | train | function | def cal_corr(target_id, group_user_rank):
target = pd.Series(group_user_rank['target'][target_id][1])
others = sorted(list(group_user_rank['others'].keys()))
list_user = []
list_corr = []
for user in others:
other = pd.Series(group_user_rank['others'][user][1])
corr = target.corr(oth... | def cal_corr(target_id, group_user_rank):
| target = pd.Series(group_user_rank['target'][target_id][1])
others = sorted(list(group_user_rank['others'].keys()))
list_user = []
list_corr = []
for user in others:
other = pd.Series(group_user_rank['others'][user][1])
corr = target.corr(other, method='spearman')
list_user.a... | return regr.coef_
#--- Ordered Weight ---#
def get_rank_weight(weight):
rank = pd.Series(list(weight)).rank(ascending=False)
rank_f = rank.values.tolist()
return rank_f
#--- Cal Spearman's Rank ---#
def cal_corr(target_id, group_user_rank):
| 64 | 64 | 122 | 10 | 54 | 9Ten/Hotel-Recommender-System- | imp_main.py | Python | cal_corr | cal_corr | 110 | 122 | 110 | 110 | 0b84194363114c61462207872a72afb6d736c2d8 | bigcode/the-stack | train |
f2479d76b2081f7b2931a8dc | train | function | def get_weight(df):
x = df[['price', 'near_station', 'restaurant', 'entertain',
'shopping_mall', 'convenience_store']].values.tolist()
y = df['rating'].values.tolist()
# Create linear regression object
regr = linear_model.LinearRegression(fit_intercept=False)
regr.fit(x, y)
return re... | def get_weight(df):
| x = df[['price', 'near_station', 'restaurant', 'entertain',
'shopping_mall', 'convenience_store']].values.tolist()
y = df['rating'].values.tolist()
# Create linear regression object
regr = linear_model.LinearRegression(fit_intercept=False)
regr.fit(x, y)
return regr.coef_
| return data_out
# {
# 'target': {'user_id': [weight, rank_f]},
# 'others': {'user_id': [weight, rank_f]},
# 'neighbors': [[user_id], [corr]]
# }
#--- Cal Regression ---#
def get_weight(df):
| 64 | 64 | 85 | 5 | 59 | 9Ten/Hotel-Recommender-System- | imp_main.py | Python | get_weight | get_weight | 94 | 101 | 94 | 94 | 5dbed042e7f2573a1e1975e18d1d07645ba93b70 | bigcode/the-stack | train |
65e97405368ad7caab688977 | train | function | def check_input(trip_type, companion):
# default = leisure
check_type = ["business", "leisure", None]
check_com = ["solo", "couple", "friend", "family", None]
ok = True
try:
check_type.remove(trip_type)
except:
ok = False
print("Trip_type is not valid")
try:
c... | def check_input(trip_type, companion):
# default = leisure
| check_type = ["business", "leisure", None]
check_com = ["solo", "couple", "friend", "family", None]
ok = True
try:
check_type.remove(trip_type)
except:
ok = False
print("Trip_type is not valid")
try:
check_com.remove(companion)
except:
ok = False
... | #--- Import Libraries ---#
import pandas as pd
from sklearn import linear_model
from sklearn import preprocessing
#--- Check Trip_type, Companion ---#
def check_input(trip_type, companion):
# default = leisure
| 46 | 64 | 111 | 15 | 31 | 9Ten/Hotel-Recommender-System- | imp_main.py | Python | check_input | check_input | 7 | 22 | 7 | 8 | a6958ca950364d0a47d414a12e8b64d06053dbe4 | bigcode/the-stack | train |
bf27a9a4185c4d35af4f1c48 | train | function | def prediction_rating(data_raw, data_frame, **kwargs):
data_frame = weight_neighbors(data_frame)
data_rec = pd.DataFrame()
neighbors = list(data_frame['user_id'])
# print('Bug ties data: {}'.format(neighbors))
# Limit Data 25 records
#--- Rec No Context ---#
if (kwargs['trip_type'] is None)... | def prediction_rating(data_raw, data_frame, **kwargs):
| data_frame = weight_neighbors(data_frame)
data_rec = pd.DataFrame()
neighbors = list(data_frame['user_id'])
# print('Bug ties data: {}'.format(neighbors))
# Limit Data 25 records
#--- Rec No Context ---#
if (kwargs['trip_type'] is None) & (kwargs['companion'] is None):
for neighbor ... | sup_data = other_data[:rows_o + 1]
else:
sup_data = other_data[:supply + 1]
#--- Supplement Into Target_user data---#
buff_data = buff_data.append(sup_data)
#--- Recal ---#
new_weight = get_weight(buff_data)
new_rank = get_rank_weight(new_weight)
data_main['... | 139 | 139 | 465 | 12 | 127 | 9Ten/Hotel-Recommender-System- | imp_main.py | Python | prediction_rating | prediction_rating | 171 | 216 | 171 | 171 | b51dee978827267581532977a2ec64cea8baec56 | bigcode/the-stack | train |
34227cfa9124e3077f2f9086 | train | function | def get_rank_weight(weight):
rank = pd.Series(list(weight)).rank(ascending=False)
rank_f = rank.values.tolist()
return rank_f
| def get_rank_weight(weight):
| rank = pd.Series(list(weight)).rank(ascending=False)
rank_f = rank.values.tolist()
return rank_f
| _store']].values.tolist()
y = df['rating'].values.tolist()
# Create linear regression object
regr = linear_model.LinearRegression(fit_intercept=False)
regr.fit(x, y)
return regr.coef_
#--- Ordered Weight ---#
def get_rank_weight(weight):
| 64 | 64 | 32 | 6 | 58 | 9Ten/Hotel-Recommender-System- | imp_main.py | Python | get_rank_weight | get_rank_weight | 104 | 107 | 104 | 104 | 5f06564425d2e490d20c979dd452eb66bd403632 | bigcode/the-stack | train |
389e683209ab43e75e34453b | train | function | def recommendation(target_id, data_rec, top_k=20):
topk_hotels = data_rec.sort_values(
by=('predict_rating'), ascending=False).head(top_k)
return topk_hotels['hotel_name']
| def recommendation(target_id, data_rec, top_k=20):
| topk_hotels = data_rec.sort_values(
by=('predict_rating'), ascending=False).head(top_k)
return topk_hotels['hotel_name']
| )
result2 .append(predict_rating)
hotel_rec = pd.DataFrame(
data={'hotel_name': result1, 'predict_rating': result2})
return hotel_rec
#--- Rec Top k hotel Ordered By predict_rating ---#
def recommendation(target_id, data_rec, top_k=20):
| 64 | 64 | 47 | 13 | 51 | 9Ten/Hotel-Recommender-System- | imp_main.py | Python | recommendation | recommendation | 219 | 222 | 219 | 219 | d162a694f4532da3bcce8673a53bdc7d5e904c18 | bigcode/the-stack | train |
5cb24febe33085653eedd870 | train | function | def get_neighbor(group_user_rank):
corr = pd.Series(group_user_rank['neighbors'][1]).rank(ascending=True)
neighbor = corr.values.tolist()
group_user_rank['neighbors'].append(neighbor)
return group_user_rank
| def get_neighbor(group_user_rank):
| corr = pd.Series(group_user_rank['neighbors'][1]).rank(ascending=True)
neighbor = corr.values.tolist()
group_user_rank['neighbors'].append(neighbor)
return group_user_rank
| corr = target.corr(other, method='spearman')
list_user.append(user)
list_corr.append(corr)
result = [list_user, list_corr]
group_user_rank.update({'neighbors': result})
return group_user_rank
#--- Before Recommendation ---#
def get_neighbor(group_user_rank):
| 64 | 64 | 49 | 7 | 57 | 9Ten/Hotel-Recommender-System- | imp_main.py | Python | get_neighbor | get_neighbor | 125 | 129 | 125 | 125 | a9a80fa564716aaf2e6398a42e767a25f92684a3 | bigcode/the-stack | train |
de69650eed2d11da3272ab9c | train | function | def get_main(target_id, target, other, trip_type, companion, status):
#--- Cal Filter By trip_type, companion ---#
if status == 1:
target = target.loc[(target['trip_type'] == trip_type)
& (target['companion'] == companion)]
#--- Cal Not Filter By trip_type, companion ---#... | def get_main(target_id, target, other, trip_type, companion, status):
#--- Cal Filter By trip_type, companion ---#
| if status == 1:
target = target.loc[(target['trip_type'] == trip_type)
& (target['companion'] == companion)]
#--- Cal Not Filter By trip_type, companion ---#
elif (status == -1) | (status == 0):
pass
target_weight = get_weight(target)
target_rank = get_ran... | , trip_type, companion, status[0])
data_out, buff_data = re_get_main(
data_out, target_id, user_data, trip_type, companion)
del data_out['others']
return data_out, status[1]
def get_main(target_id, target, other, trip_type, companion, status):
#---... | 81 | 81 | 273 | 29 | 52 | 9Ten/Hotel-Recommender-System- | imp_main.py | Python | get_main | get_main | 61 | 86 | 61 | 62 | 0ec7578218d25fd8929c8b4ae3a5deb00d14cda5 | bigcode/the-stack | train |
d949d7279080109905a8f975 | train | function | def re_get_main(data_main, target_id, user_data, trip_type, companion):
target_data = user_data.loc[(user_data['user_id'] == target_id) & (
user_data['trip_type'] == trip_type) & (user_data['companion'] == companion)]
other_id = data_main['neighbors'][0]
other_rank = data_main['neighbors'][2]
ne... | def re_get_main(data_main, target_id, user_data, trip_type, companion):
| target_data = user_data.loc[(user_data['user_id'] == target_id) & (
user_data['trip_type'] == trip_type) & (user_data['companion'] == companion)]
other_id = data_main['neighbors'][0]
other_rank = data_main['neighbors'][2]
neighbors = pd.DataFrame({'user_id': other_id, 'rank': other_rank})
ne... | list_corr.append(corr)
result = [list_user, list_corr]
group_user_rank.update({'neighbors': result})
return group_user_rank
#--- Before Recommendation ---#
def get_neighbor(group_user_rank):
corr = pd.Series(group_user_rank['neighbors'][1]).rank(ascending=True)
neighbor = corr.values.tolist... | 114 | 114 | 383 | 18 | 96 | 9Ten/Hotel-Recommender-System- | imp_main.py | Python | re_get_main | re_get_main | 132 | 168 | 132 | 132 | a0044501ff4491bc8bf7d8bbdd5ef6f6686da7f2 | bigcode/the-stack | train |
4115e6d7c1309a43a6070800 | train | function | def check_case(target_id, trip_type, companion, file_loc):
user_data = pd.read_csv(file_loc)
group_user = user_data.drop('hotel_name', axis=1)
target_user = group_user.loc[group_user['user_id'] == target_id]
if len(target_user) == 0:
print("Target_user is not valid")
#--- Check Target_user d... | def check_case(target_id, trip_type, companion, file_loc):
| user_data = pd.read_csv(file_loc)
group_user = user_data.drop('hotel_name', axis=1)
target_user = group_user.loc[group_user['user_id'] == target_id]
if len(target_user) == 0:
print("Target_user is not valid")
#--- Check Target_user data ---#
else:
other_user = group_user.loc[gro... | ", "leisure", None]
check_com = ["solo", "couple", "friend", "family", None]
ok = True
try:
check_type.remove(trip_type)
except:
ok = False
print("Trip_type is not valid")
try:
check_com.remove(companion)
except:
ok = False
print("Companion is not ... | 111 | 111 | 373 | 14 | 97 | 9Ten/Hotel-Recommender-System- | imp_main.py | Python | check_case | check_case | 25 | 59 | 25 | 25 | 118b3e02966e1a5ecb58b2ebfb6cab3ed9f62fde | bigcode/the-stack | train |
6a31b41a35837c11a2b17989 | train | class | class Insight(BaseModel):
"""
enable: bool, default True
Whether to create this element
duplicates__threshold: int, default 1
Warn if the percent of duplicated values is above this threshold
similar_distribution__threshold:float, default 0.05
The significance level for Kolmogorov... | class Insight(BaseModel):
| """
enable: bool, default True
Whether to create this element
duplicates__threshold: int, default 1
Warn if the percent of duplicated values is above this threshold
similar_distribution__threshold:float, default 0.05
The significance level for Kolmogorov–Smirnov test
uniform_... | Value Table": "value_table",
}
# This dictionary map is used for session control in create_report
DISPLAY_REPORT_MAP = {
"Overview": "overview",
"Variables": "variables",
"Interactions": "interactions",
"Correlations": "correlations",
"Missing Values": "missingvalues",
}
class Plot(BaseModel):
... | 219 | 219 | 733 | 5 | 213 | Waterpine/dataprep-1 | dataprep/eda/configs.py | Python | Insight | Insight | 96 | 156 | 96 | 96 | c022c8ffaa9368685b192d5dbf1b2fde36b06b26 | bigcode/the-stack | train |
a2ec148b4433ee57aace1fce | train | class | class Pie(BaseModel):
"""
enable: bool, default True
Whether to create this element
slices: int, default 10
Maximum number of pie slices to display
sort_descending: bool, default True
Whether to sort the slices in descending order of frequency
colors: Optional[List[str]], def... | class Pie(BaseModel):
| """
enable: bool, default True
Whether to create this element
slices: int, default 10
Maximum number of pie slices to display
sort_descending: bool, default True
Whether to sort the slices in descending order of frequency
colors: Optional[List[str]], default None
List... | ]]:
"""
how-to guide for plot(df, continuous, continuous)
"""
vals = [self.bins, height, width]
names = ["box.bins", "height", "width"]
descs = ["Number of bins", "Height of the plot", "Width of the plot"]
return [(f"'{name}': {val}", desc) for name, val, desc in ... | 98 | 99 | 332 | 5 | 93 | Waterpine/dataprep-1 | dataprep/eda/configs.py | Python | Pie | Pie | 415 | 451 | 415 | 415 | 578c5b79b30d9270c8428eb07789cf2be9324e1b | bigcode/the-stack | train |
4d0fe9eaf4cb9eac713f05fa | train | class | class Pearson(BaseModel):
"""
enable: bool, default True
Whether to create this element
height: int, default "auto"
Height of the plot
width: int, default "auto"
Width of the plot
"""
enable: bool = True
height: Union[int, None] = None
width: Union[int, None] = N... | class Pearson(BaseModel):
| """
enable: bool, default True
Whether to create this element
height: int, default "auto"
Height of the plot
width: int, default "auto"
Width of the plot
"""
enable: bool = True
height: Union[int, None] = None
width: Union[int, None] = None
def how_to_guide(... | height, width]
names = ["height", "width"]
descs = ["Height of the plot", "Width of the plot"]
return [(f"'{name}': {val}", desc) for name, val, desc in zip(names, vals, descs)]
class Pearson(BaseModel):
| 63 | 64 | 178 | 5 | 58 | Waterpine/dataprep-1 | dataprep/eda/configs.py | Python | Pearson | Pearson | 876 | 897 | 876 | 876 | f25d1ec5f10abf1903588a829806f682ef52d68f | bigcode/the-stack | train |
a390991d82952a54f017b59c | train | class | class Dendrogram(BaseModel):
"""
enable: bool, default True
Whether to create this element
height: int, default "auto"
Height of the plot
width: int, default "auto"
Width of the plot
"""
enable: bool = True
height: Union[int, None] = None
width: Union[int, None] ... | class Dendrogram(BaseModel):
| """
enable: bool, default True
Whether to create this element
height: int, default "auto"
Height of the plot
width: int, default "auto"
Width of the plot
"""
enable: bool = True
height: Union[int, None] = None
width: Union[int, None] = None
def how_to_guide(... | "height", "width"]
descs = ["Number of bins", "Height of the plot", "Width of the plot"]
return [(f"'{name}': {val}", desc) for name, val, desc in zip(names, vals, descs)]
class Dendrogram(BaseModel):
| 63 | 64 | 180 | 7 | 56 | Waterpine/dataprep-1 | dataprep/eda/configs.py | Python | Dendrogram | Dendrogram | 973 | 994 | 973 | 973 | 9f89bafbeb704bcac7a1f986618c5c564fab536f | bigcode/the-stack | train |
896233e92e92a10364ce8fae | train | class | class Line(BaseModel):
"""
enable: bool, default True
Whether to create this element
bins: int, default 50
Number of bins
ngroups: int, default 10
Maximum number of groups to display
sort_descending: bool, default True
Whether to sort the groups in descending order of... | class Line(BaseModel):
| """
enable: bool, default True
Whether to create this element
bins: int, default 50
Number of bins
ngroups: int, default 10
Maximum number of groups to display
sort_descending: bool, default True
Whether to sort the groups in descending order of frequency
yscale: ... | """
how-to guide for plot(df, x)
"""
vals = [self.bins, self.yscale, self.color, height, width]
names = ["wordlen.bins", "wordlen.yscale", "wordlen.color", "height", "width"]
descs = [
"Number of bins in the histogram",
'Y-axis scale ("linear" or "log")',... | 143 | 144 | 483 | 5 | 138 | Waterpine/dataprep-1 | dataprep/eda/configs.py | Python | Line | Line | 590 | 639 | 590 | 590 | 4aa9febd71231ebffe6bd1f5f29f1c5a93cba06b | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.