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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3da9e8b536f45ba3c453b68a | train | class | class BaseWTruncNorm(BaseW):
def __init__(self, lower_bound, upper_bound, K, N):
super().__init__(lower_bound, upper_bound, K, N)
def _calc_mu_sigma(self, mean_noise, mean_hyperpriors, noise_H_sq_sum,
prod_mix):
""" Calculates mu and sigma squared for a k'th feature acro... | class BaseWTruncNorm(BaseW):
| def __init__(self, lower_bound, upper_bound, K, N):
super().__init__(lower_bound, upper_bound, K, N)
def _calc_mu_sigma(self, mean_noise, mean_hyperpriors, noise_H_sq_sum,
prod_mix):
""" Calculates mu and sigma squared for a k'th feature across all
observation... | , shape (K) or (K,D)
OUTPUT
======
- elbo_part: float
"""
# we utilize broadcasting (but it requires a transpositions)
# this is safe, also if hyperpriors has shape (K)
transposed_tmp = ln_mean_hyperprior.T\
- self.mean.T*mean_hyperp... | 136 | 136 | 456 | 9 | 126 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | BaseWTruncNorm | BaseWTruncNorm | 306 | 354 | 306 | 307 | 9d5da47794a941e466eec5972ef66fb6b27202ca | bigcode/the-stack | train |
a85e6865c0b0af7c8c214a02 | train | class | class HyperpriorExponSparsityWithShared(HyperpriorExponWSparsity):
""" Class governing hyperprior for factor W alone.
Model places a hyperprior on each element in W - thus being
sparsity-promoting.
ADDITIONAL CONDITION: a hyperprior, shared between W and H, and
... | class HyperpriorExponSparsityWithShared(HyperpriorExponWSparsity):
| """ Class governing hyperprior for factor W alone.
Model places a hyperprior on each element in W - thus being
sparsity-promoting.
ADDITIONAL CONDITION: a hyperprior, shared between W and H, and
placed on each feature is required.
... | , mean_lambda_shared):
self.beta = self.hyperprior_beta + 0.5*(mean_sq_W
*mean_lambda_shared.reshape(self.K,1))
self.moments(self.alpha, self.beta)
class HyperpriorExponSparsityWithShared(HyperpriorExponWSparsity):
| 64 | 64 | 198 | 19 | 45 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | HyperpriorExponSparsityWithShared | HyperpriorExponSparsityWithShared | 707 | 729 | 707 | 707 | 0a7a6f1268d42f62108cc6ffe9a47cee95c16e45 | bigcode/the-stack | train |
dc3d10942646cc9ca4f4366c | train | class | class FactorWTruncNorm(BaseWTruncNorm, BaseFactorW): # BaseFactorW has to be last!!
def __init__(self, lower_bound, upper_bound, K, N):
super().__init__(lower_bound, upper_bound, K, N)
| class FactorWTruncNorm(BaseWTruncNorm, BaseFactorW): # BaseFactorW has to be last!!
| def __init__(self, lower_bound, upper_bound, K, N):
super().__init__(lower_bound, upper_bound, K, N)
| __init__(self, lower_bound, upper_bound, K, N): # BaseFactorW has to be last!!
super().__init__(lower_bound, upper_bound, K, N)
class FactorWTruncNorm(BaseWTruncNorm, BaseFactorW): # BaseFactorW has to be last!!
| 64 | 64 | 57 | 25 | 39 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | FactorWTruncNorm | FactorWTruncNorm | 361 | 364 | 361 | 362 | a2d0a744603f8c042c541e37ca85fe4b440f1e91 | bigcode/the-stack | train |
85ae3a5f0c16d9825ea7b968 | train | class | class FactorWExpon(BaseWExpon, BaseFactorW):
def __init__(self, lower_bound, upper_bound, K, N): # BaseFactorW has to be last!!
super().__init__(lower_bound, upper_bound, K, N)
| class FactorWExpon(BaseWExpon, BaseFactorW):
| def __init__(self, lower_bound, upper_bound, K, N): # BaseFactorW has to be last!!
super().__init__(lower_bound, upper_bound, K, N)
| (-0.5*np.log(2*np.pi) + 0.5*transposed_tmp
+ np.log(2))
entropy_elbo = np.sum(self.etrpy)
return prior_elbo + entropy_elbo
class FactorWExpon(BaseWExpon, BaseFactorW):
| 64 | 64 | 55 | 14 | 49 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | FactorWExpon | FactorWExpon | 356 | 359 | 356 | 357 | d6363f68a6bdab58b5f5bf1e7008b01ee2df5130 | bigcode/the-stack | train |
cdd2bf85503592210a5183cf | train | class | class HyperpriorTruncNormSparsityWithShared(HyperpriorTruncNormWSparsity):
""" Class governing hyperprior for factor W alone.
Model places a hyperprior on each element in W - thus being
sparsity-promoting.
ADDITIONAL CONDITION: a hyperprior, shared between W and H, and
... | class HyperpriorTruncNormSparsityWithShared(HyperpriorTruncNormWSparsity):
| """ Class governing hyperprior for factor W alone.
Model places a hyperprior on each element in W - thus being
sparsity-promoting.
ADDITIONAL CONDITION: a hyperprior, shared between W and H, and
placed on each feature is required.
... | init__(alpha, beta)
self.alpha = alpha + 1
def update(self, mean_W):
self.beta = self.hyperprior_beta + mean_W
self.moments(self.alpha, self.beta)
class HyperpriorTruncNormSparsityWithShared(HyperpriorTruncNormWSparsity):
| 67 | 67 | 225 | 21 | 46 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | HyperpriorTruncNormSparsityWithShared | HyperpriorTruncNormSparsityWithShared | 682 | 705 | 682 | 682 | 89db4120ab59a14c3de730b6aac3f10c78a3a9ef | bigcode/the-stack | train |
21a8ec9095008750fb7d31e9 | train | class | class HyperpriorTruncNormSharedWithSparsity(HyperpriorTruncNormShared):
""" Class governing hyperprior for factor W alone.
Model places a hyperprior on each element in W - thus being
sparsity-promoting.
PRIOR ON W: W ~ TruncatedNormal(mu=0, var=hyperprior,
... | class HyperpriorTruncNormSharedWithSparsity(HyperpriorTruncNormShared):
| """ Class governing hyperprior for factor W alone.
Model places a hyperprior on each element in W - thus being
sparsity-promoting.
PRIOR ON W: W ~ TruncatedNormal(mu=0, var=hyperprior,
lower_bound=0,upper_bound=infity)
"""
de... | self.beta = self.hyperprior_beta + (np.sum(mean_H, axis=0)
+ np.sum(mean_W*mean_sparse_lambda,
axis=1))
self.moments(self.alpha, self.beta)
class HyperpriorTruncNormSharedWithSparsity(HyperpriorTruncNormShared):
| 64 | 64 | 200 | 19 | 45 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | HyperpriorTruncNormSharedWithSparsity | HyperpriorTruncNormSharedWithSparsity | 639 | 658 | 639 | 639 | e819160bc0228dce87893f99e6638069fabf18c2 | bigcode/the-stack | train |
71049717d44213906aecd9dc | train | class | class HyperpriorHTruncNorm(BaseHyperprior):
""" Class governing hyperprior for factor H alone.
Model places a hyperprior on each feature k, which is shared across
D observed features. This hyperprior is NOT shared with W.
"""
def __init__(self, alpha, beta, D):
super().__ini... | class HyperpriorHTruncNorm(BaseHyperprior):
| """ Class governing hyperprior for factor H alone.
Model places a hyperprior on each feature k, which is shared across
D observed features. This hyperprior is NOT shared with W.
"""
def __init__(self, alpha, beta, D):
super().__init__(alpha, beta)
self.alpha = alpha ... | super().__init__(alpha, beta)
self.alpha = alpha + D
def update(self, mean_H):
self.beta = self.hyperprior_beta + np.sum(mean_H, axis=0)
self.moments(self.alpha, self.beta)
class HyperpriorHTruncNorm(BaseHyperprior):
| 64 | 64 | 132 | 11 | 53 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | HyperpriorHTruncNorm | HyperpriorHTruncNorm | 567 | 579 | 567 | 567 | 20afa0216c8c60d7f463212d6cd6a3f2194407bd | bigcode/the-stack | train |
408c8f17f30db9beecc1efec | train | class | class BaseWExpon(BaseW):
def __init__(self, lower_bound, upper_bound, K, N):
super().__init__(lower_bound, upper_bound, K, N)
def _calc_mu_sigma(self, mean_noise, mean_hyperpriors, noise_H_sq_sum,
prod_mix):
""" Calculates mu and sigma squared for a k'th feature across a... | class BaseWExpon(BaseW):
| def __init__(self, lower_bound, upper_bound, K, N):
super().__init__(lower_bound, upper_bound, K, N)
def _calc_mu_sigma(self, mean_noise, mean_hyperpriors, noise_H_sq_sum,
prod_mix):
""" Calculates mu and sigma squared for a k'th feature across all
observation... | [k], prod_mix)
moments = self.moments(mu, sigma_sq)
new_mean, new_var, new_etrpy, new_mean_sq = moments
self.mean[k,:] = new_mean
self.var[k,:] = new_var
self.etrpy[k,:] = new_etrpy
self.mean_sq[k,:] = new_mean_sq
def _calc_mu_sigma(self, mean... | 118 | 118 | 395 | 8 | 109 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | BaseWExpon | BaseWExpon | 259 | 303 | 259 | 260 | f8232fdfbe144e034050d92761999d596e5268f1 | bigcode/the-stack | train |
7e581f1c47c8bf8ded5b09f5 | train | class | class BaseFactorW(BaseW):
def __init__(self, lower_bound, upper_bound, K, N):
super().__init__(lower_bound, upper_bound, K, N)
def update(self, X, mean_H, mean_sq_H, mean_hyperpriors, mean_noise):
""" Updates the mean, variance, entropy and mean_sq
INPUTS:
=======
... | class BaseFactorW(BaseW):
| def __init__(self, lower_bound, upper_bound, K, N):
super().__init__(lower_bound, upper_bound, K, N)
def update(self, X, mean_H, mean_sq_H, mean_hyperpriors, mean_noise):
""" Updates the mean, variance, entropy and mean_sq
INPUTS:
=======
- X: array-... | init_mean = np.empty([self.K, self.N])
init_var = np.empty_like(init_mean)
init_etrpy = np.empty_like(init_mean)
from npbNMF.datatools import sample_init_factor_expon
for n in range(self.N):
for k in range(self.K):
estimates = self._sample_estimates(... | 165 | 165 | 552 | 7 | 157 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | BaseFactorW | BaseFactorW | 205 | 257 | 205 | 206 | 1a47c2ce609e92bdda473b084d676a11a1e0b820 | bigcode/the-stack | train |
aeab4e9f7f77113212389407 | train | class | class NPBFactorWTruncNorm(BaseWTruncNorm, BaseNPBW): # BaseNPBW HAS TO BE LAST!
def __init__(self, lower_bound, upper_bound, K, N):
super().__init__(lower_bound, upper_bound, K, N)
| class NPBFactorWTruncNorm(BaseWTruncNorm, BaseNPBW): # BaseNPBW HAS TO BE LAST!
| def __init__(self, lower_bound, upper_bound, K, N):
super().__init__(lower_bound, upper_bound, K, N)
| HAS TO BE LAST!
def __init__(self, lower_bound, upper_bound, K, N):
super().__init__(lower_bound, upper_bound, K, N)
class NPBFactorWTruncNorm(BaseWTruncNorm, BaseNPBW): # BaseNPBW HAS TO BE LAST!
| 64 | 64 | 59 | 27 | 37 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | NPBFactorWTruncNorm | NPBFactorWTruncNorm | 407 | 410 | 407 | 408 | c45d3bb5b3502c253c446cb5d81fb0df068ddb66 | bigcode/the-stack | train |
ed40e1f3e65a0d960d0f60c5 | train | class | class BaseH(FactorTruncNormVB):
def __init__(self, lower_bound, upper_bound, K, D):
super().__init__(lower_bound, upper_bound, K)
self.D = D
self.mean = np.empty([D, K])
self.mean_sq = np.empty_like(self.mean)
self.var = np.empty_like(self.mean)
self.etrpy = np.empty... | class BaseH(FactorTruncNormVB):
| def __init__(self, lower_bound, upper_bound, K, D):
super().__init__(lower_bound, upper_bound, K)
self.D = D
self.mean = np.empty([D, K])
self.mean_sq = np.empty_like(self.mean)
self.var = np.empty_like(self.mean)
self.etrpy = np.empty_like(self.mean)
def initial... | class FactorTruncNormVB:
def __init__(self, lower_bound, upper_bound, K):
self.lower_bound = lower_bound
self.upper_bound = upper_bound
self.K = K
self.etrpy = None
def initialize_preset(self, init_mean, init_var):
self.mean = init_mean
self.var = init_var
... | 178 | 178 | 594 | 10 | 167 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | BaseH | BaseH | 39 | 101 | 39 | 40 | da82b430b1d2184e0eb94697b482b0f4292282fb | bigcode/the-stack | train |
51feacecce225ac5d6f3b934 | train | class | class HyperpriorTruncNormShared(BaseHyperprior):
""" Class governing hyperprior for factor H and W.
Model places a hyperprior on each feature k, and jointly shared
across D observed features and N observations. This hyperprior IS
shared with W.
PRIOR ON W: W ~ Trunc... | class HyperpriorTruncNormShared(BaseHyperprior):
| """ Class governing hyperprior for factor H and W.
Model places a hyperprior on each feature k, and jointly shared
across D observed features and N observations. This hyperprior IS
shared with W.
PRIOR ON W: W ~ TruncatedNormal(mu=0,var=hyperprior,
... |
def update(self, mean_H, mean_W):
self.beta = self.hyperprior_beta + (np.sum(mean_H, axis=0)
+ np.sum(mean_W, axis=1))
self.moments(self.alpha, self.beta)
class HyperpriorTruncNormShared(BaseHyperprior):
| 64 | 64 | 188 | 11 | 53 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | HyperpriorTruncNormShared | HyperpriorTruncNormShared | 600 | 618 | 600 | 600 | 8b09e429be81a61ca9620b91256785c1969d408b | bigcode/the-stack | train |
cf25015f812b20e5212b064a | train | class | class FactorTruncNormVB:
def __init__(self, lower_bound, upper_bound, K):
self.lower_bound = lower_bound
self.upper_bound = upper_bound
self.K = K
self.etrpy = None
def initialize_preset(self, init_mean, init_var):
self.mean = init_mean
self.var = init_var
... | class FactorTruncNormVB:
| def __init__(self, lower_bound, upper_bound, K):
self.lower_bound = lower_bound
self.upper_bound = upper_bound
self.K = K
self.etrpy = None
def initialize_preset(self, init_mean, init_var):
self.mean = init_mean
self.var = init_var
self.mean_sq = mean_sq... | means_factor_prod,\
gamma_moments, gamma_prior_elbo, \
beta_moments, bernoulli_moments, \
expon_moments, mean_sq, mean_X_LR_error_fast
##############################################################################
# factor objects... | 64 | 64 | 168 | 7 | 57 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | FactorTruncNormVB | FactorTruncNormVB | 14 | 36 | 14 | 15 | b5c25be24c3050ac230b4c13e12ab4ece6233f7c | bigcode/the-stack | train |
9b366d36e2a3db961493523c | train | class | class NoiseGamma:
def __init__(self, X, noise_alpha, noise_beta, data_size):
self.noise_alpha = noise_alpha
self.noise_beta = noise_beta
self.X = X
self.alpha = noise_alpha + 0.5*data_size
def update(self, mean_H, mean_sq_H, mean_R, mean_sq_R):
mean_sq_sum_H = np.sum(me... | class NoiseGamma:
| def __init__(self, X, noise_alpha, noise_beta, data_size):
self.noise_alpha = noise_alpha
self.noise_beta = noise_beta
self.X = X
self.alpha = noise_alpha + 0.5*data_size
def update(self, mean_H, mean_sq_H, mean_R, mean_sq_R):
mean_sq_sum_H = np.sum(mean_sq_H, axis=0)
... | py)
return prior_elbo + entropy_elbo
def moments(self, pi):
new_mean, new_var, new_etrpy = bernoulli_moments(pi)
new_mean_sq = mean_sq(new_mean, new_var)
return new_mean, new_var, new_etrpy, new_mean_sq
#############################################################################... | 84 | 84 | 280 | 4 | 80 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | NoiseGamma | NoiseGamma | 496 | 524 | 496 | 497 | 25473d0c58b05586984bb8f44130f45cb29fb910 | bigcode/the-stack | train |
d823496ee5661edf84accc48 | train | class | class BetaPrior:
def __init__(self, N, K, pi_alpha, pi_beta):
self.N = N
self.K = K
# prior alpha and beta values
self.prior_alpha = pi_alpha/self.K
self.prior_beta = pi_beta*(1 - 1.0/self.K)
self.ln_B = gammaln(self.prior_alpha) + gammaln(self.prior_beta)\
... | class BetaPrior:
| def __init__(self, N, K, pi_alpha, pi_beta):
self.N = N
self.K = K
# prior alpha and beta values
self.prior_alpha = pi_alpha/self.K
self.prior_beta = pi_beta*(1 - 1.0/self.K)
self.ln_B = gammaln(self.prior_alpha) + gammaln(self.prior_beta)\
- gamm... | init__(alpha, beta)
self.K = K
self.moments(np.full((K, N), alpha),
np.full((K, N),beta))
def update(self, mean_W, mean_lambda_shared):
self.beta = self.hyperprior_beta + (mean_W
*mean_lambda_shared.reshape(self.K,1))
se... | 87 | 87 | 291 | 4 | 83 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | BetaPrior | BetaPrior | 732 | 760 | 732 | 733 | 81b3770d8216a6e12999114d27cb3952506430b2 | bigcode/the-stack | train |
813c960f6132f1a015fb9a58 | train | class | class FactorHTruncNorm(BaseH):
def __init__(self, lower_bound, upper_bound, K, D):
super().__init__(lower_bound, upper_bound, K, D)
def _calc_mu_sigma(self, mean_noise, mean_hyperpriors, noise_R_sq_sum,
prod_mix):
sigma_sq = np.reciprocal(noise_R_sq_sum + mean_hyperprior... | class FactorHTruncNorm(BaseH):
| def __init__(self, lower_bound, upper_bound, K, D):
super().__init__(lower_bound, upper_bound, K, D)
def _calc_mu_sigma(self, mean_noise, mean_hyperpriors, noise_R_sq_sum,
prod_mix):
sigma_sq = np.reciprocal(noise_R_sq_sum + mean_hyperpriors)
mu = sigma_sq*mean_n... | pass
def moments(self, mu, sigma_sq):
new_mean, new_var, new_etrpy = trunc_moments(
self.lower_bound,
self.upper_bound,
mu,
... | 86 | 86 | 288 | 9 | 76 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | FactorHTruncNorm | FactorHTruncNorm | 103 | 134 | 103 | 104 | 282efc09e99a273bec42db240aae7ee09245db0c | bigcode/the-stack | train |
c584bfbb4e0b47b76d27d440 | train | class | class HyperpriorHExpon(BaseHyperprior):
""" Class governing hyperprior for factor H alone.
Model places a hyperprior on each feature k, which is shared across
D observed features. This hyperprior is NOT shared with W.
"""
def __init__(self, alpha, beta, D):
super().__init__(... | class HyperpriorHExpon(BaseHyperprior):
| """ Class governing hyperprior for factor H alone.
Model places a hyperprior on each feature k, which is shared across
D observed features. This hyperprior is NOT shared with W.
"""
def __init__(self, alpha, beta, D):
super().__init__(alpha, beta)
self.alpha = alpha ... | (self.etrpy)
return prior_elbo + entropy_elbo
def moments(self, alpha, beta):
moments = gamma_moments(alpha, beta)
self.mean, self.var, self.ln_mean, self.etrpy = moments
class HyperpriorHExpon(BaseHyperprior):
| 64 | 64 | 120 | 10 | 53 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | HyperpriorHExpon | HyperpriorHExpon | 553 | 565 | 553 | 553 | 6f5010519bd56f44be34ddf4e31dc29831c8f675 | bigcode/the-stack | train |
50b4321abd3a79ed5ced4d03 | train | class | class HyperpriorExponWSparsity(BaseHyperprior):
def __init__(self, alpha, beta):
super().__init__(alpha, beta)
self.alpha = alpha + 1
def update(self, mean_W):
self.beta = self.hyperprior_beta + mean_W
self.moments(self.alpha, self.beta)
| class HyperpriorExponWSparsity(BaseHyperprior):
| def __init__(self, alpha, beta):
super().__init__(alpha, beta)
self.alpha = alpha + 1
def update(self, mean_W):
self.beta = self.hyperprior_beta + mean_W
self.moments(self.alpha, self.beta)
| , beta)
self.alpha = alpha + 0.5
def update(self, mean_sq_W):
self.beta = self.hyperprior_beta + 0.5*mean_sq_W
self.moments(self.alpha, self.beta)
class HyperpriorExponWSparsity(BaseHyperprior):
| 64 | 64 | 72 | 12 | 52 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | HyperpriorExponWSparsity | HyperpriorExponWSparsity | 671 | 680 | 671 | 672 | d1c1beee4438c5ad9b423795f87dbace8c978abc | bigcode/the-stack | train |
6ffb508f9fc451f879077470 | train | class | class NPBFactorWExpon(BaseWExpon, BaseNPBW): # BaseNPBW HAS TO BE LAST!
def __init__(self, lower_bound, upper_bound, K, N):
super().__init__(lower_bound, upper_bound, K, N)
| class NPBFactorWExpon(BaseWExpon, BaseNPBW): # BaseNPBW HAS TO BE LAST!
| def __init__(self, lower_bound, upper_bound, K, N):
super().__init__(lower_bound, upper_bound, K, N)
| .mean_sq[k,:] = new_mean_sq
def _calc_mu_sigma(self, mean_noise, mean_hyperpriors, noise_H_sq_sum,
prod_mix):
pass
class NPBFactorWExpon(BaseWExpon, BaseNPBW): # BaseNPBW HAS TO BE LAST!
| 64 | 64 | 57 | 25 | 38 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | NPBFactorWExpon | NPBFactorWExpon | 402 | 405 | 402 | 403 | cedddde0541dce77224010084d64c78da7fef884 | bigcode/the-stack | train |
e6e5bc50717f84f29da84e11 | train | class | class BaseHyperprior:
"""
HYPERPRIOR FOR lambda: lambda ~ Gamma(alpha, beta)
"""
def __init__(self, alpha, beta):
""" Initialize hyperpriors for the factors H and W
INPUTS:
- alpha: float
- beta: float
"""
self.hyperprior_... | class BaseHyperprior:
| """
HYPERPRIOR FOR lambda: lambda ~ Gamma(alpha, beta)
"""
def __init__(self, alpha, beta):
""" Initialize hyperpriors for the factors H and W
INPUTS:
- alpha: float
- beta: float
"""
self.hyperprior_alpha = alpha
... | _beta)
entropy_elbo = self.etrpy
return prior_elbo + entropy_elbo
def moments(self):
moments = gamma_moments(self.alpha, self.beta)
self.mean, self.var, self.ln_mean, self.etrpy = moments
class BaseHyperprior:
| 64 | 64 | 183 | 5 | 58 | ammunk/Bayesian-Non-Parametric-NMF | npbNMF/variational_distributions.py | Python | BaseHyperprior | BaseHyperprior | 526 | 551 | 526 | 526 | 83f522857de3a5af9ed6a04497907fba544cc7a5 | bigcode/the-stack | train |
fe4e8eeaa599758f72b697c4 | train | function | def mutation_wrap_string_in_function(content, state):
# utils.dbg_msg("Mutation operation: Wrap string in function")
tagging.add_tag(Tag.MUTATION_WRAP_STRING_IN_FUNCTION1)
positions_of_strings = testcase_mutators_helpers.get_positions_of_all_strings_in_testcase(content)
if len(positions_of_strings) == ... | def mutation_wrap_string_in_function(content, state):
# utils.dbg_msg("Mutation operation: Wrap string in function")
| tagging.add_tag(Tag.MUTATION_WRAP_STRING_IN_FUNCTION1)
positions_of_strings = testcase_mutators_helpers.get_positions_of_all_strings_in_testcase(content)
if len(positions_of_strings) == 0:
tagging.add_tag(Tag.MUTATION_WRAP_STRING_IN_FUNCTION2_DO_NOTHING)
return content, state # nothing to ... | (() => "foobar")()
import utils
import tagging_engine.tagging as tagging
from tagging_engine.tagging import Tag
import mutators.testcase_mutators_helpers as testcase_mutators_helpers
def mutation_wrap_string_in_function(content, state):
# utils.dbg_msg("Mutation operation: Wrap string in function")
| 64 | 64 | 197 | 25 | 38 | freingruber/JavaScript-Raider | mutators/implementations/mutation_wrap_string_in_function.py | Python | mutation_wrap_string_in_function | mutation_wrap_string_in_function | 38 | 55 | 38 | 39 | 4a2c284e7c51a55bfd89aa723691f568b1d3fdee | bigcode/the-stack | train |
99b5d44edbcce5292b796da7 | train | class | class TestBase(TestCase):
def test_check(self):
provider = Reference()
@account_check
def test(self, account):
pass
provider.test = test
provider.test(provider, PaymentAccount(provider=PROVIDER_REFERENCE))
with self.assertRaises(ValueError):
... | class TestBase(TestCase):
| def test_check(self):
provider = Reference()
@account_check
def test(self, account):
pass
provider.test = test
provider.test(provider, PaymentAccount(provider=PROVIDER_REFERENCE))
with self.assertRaises(ValueError):
provider.test(provider, Pa... | self.addCleanup(generic_patcher.stop)
class TestSetup(TestCase):
def test_multiple(self):
with self.settings(PAYMENT_PROVIDERS=['bango', 'reference'],
DEFAULT_PAYMENT_PROVIDER='bango'):
eq_(get_provider().name, 'bango')
class TestBase(TestCase):
| 64 | 64 | 73 | 6 | 58 | Witia1/zamboni | mkt/developers/tests/test_providers.py | Python | TestBase | TestBase | 72 | 84 | 72 | 73 | d0b7e8ce07095f4abc7bc1d06fac06bdb88a7cc4 | bigcode/the-stack | train |
25904a55a427416ab6ded30e | train | class | class Patcher(object):
"""
This class patch your test case so that any attempt to call solitude
from zamboni through these classes will use the mock.
Use this class as mixin on any tests that alter payment accounts.
If you override setUp or tearDown be sure to call super.
"""
def setUp(se... | class Patcher(object):
| """
This class patch your test case so that any attempt to call solitude
from zamboni through these classes will use the mock.
Use this class as mixin on any tests that alter payment accounts.
If you override setUp or tearDown be sure to call super.
"""
def setUp(self, *args, **kw):
... | from datetime import datetime
from django.core.exceptions import ObjectDoesNotExist
from mock import ANY, Mock, patch
from nose.tools import eq_, ok_
from mkt.constants.payments import PROVIDER_BANGO, PROVIDER_REFERENCE
from mkt.developers.models import PaymentAccount, SolitudeSeller
from mkt.developers.providers im... | 125 | 130 | 435 | 5 | 119 | Witia1/zamboni | mkt/developers/tests/test_providers.py | Python | Patcher | Patcher | 18 | 61 | 18 | 18 | 6068e4e1a9f47c2df7eee22ccde745c4e37d1027 | bigcode/the-stack | train |
f1f15bbe4def9baf4d86f19c | train | class | class TestSetup(TestCase):
def test_multiple(self):
with self.settings(PAYMENT_PROVIDERS=['bango', 'reference'],
DEFAULT_PAYMENT_PROVIDER='bango'):
eq_(get_provider().name, 'bango')
| class TestSetup(TestCase):
| def test_multiple(self):
with self.settings(PAYMENT_PROVIDERS=['bango', 'reference'],
DEFAULT_PAYMENT_PROVIDER='bango'):
eq_(get_provider().name, 'bango')
| atcher = patch('mkt.developers.providers.Provider.generic',
name='test_providers.Patcher.generic_patcher')
self.generic_patcher = generic_patcher.start()
self.generic_patcher.patcher = generic_patcher
self.addCleanup(generic_patcher.stop)
class TestSetup(TestCase)... | 64 | 64 | 49 | 6 | 58 | Witia1/zamboni | mkt/developers/tests/test_providers.py | Python | TestSetup | TestSetup | 64 | 69 | 64 | 65 | f8321ee96c9f0f3ad4c85402dc6f3cf37362c482 | bigcode/the-stack | train |
9785f038b39bacaf09056c40 | train | class | class TestReference(Patcher, TestCase):
fixtures = fixture('user_999')
def setUp(self, *args, **kw):
super(TestReference, self).setUp(*args, **kw)
self.user = UserProfile.objects.get(pk=999)
self.ref = Reference()
def test_setup_seller(self):
self.ref.setup_seller(self.user... | class TestReference(Patcher, TestCase):
| fixtures = fixture('user_999')
def setUp(self, *args, **kw):
super(TestReference, self).setUp(*args, **kw)
self.user = UserProfile.objects.get(pk=999)
self.ref = Reference()
def test_setup_seller(self):
self.ref.setup_seller(self.user)
ok_(SolitudeSeller.objects.fil... | _uri': 'gpuri'}
self.bango_patcher.product.get_object_or_404.return_value = {
'resource_uri': 'bpruri', 'bango_id': 'bango#', 'seller': 'selluri'
}
uri = self.bango.product_create(self.account, self.app)
eq_(uri, 'bpruri')
def test_create_new(self):
self.bango_p... | 255 | 256 | 1,028 | 9 | 247 | Witia1/zamboni | mkt/developers/tests/test_providers.py | Python | TestReference | TestReference | 134 | 257 | 134 | 134 | 1133106d3dba0c8ebca66a2ae1d37f07e91475a1 | bigcode/the-stack | train |
deea71b6238071fb3e0aa6d0 | train | class | class TestBango(Patcher, TestCase):
fixtures = fixture('user_999')
def setUp(self):
super(TestBango, self).setUp()
self.user = UserProfile.objects.filter()[0]
self.app = app_factory()
self.make_premium(self.app)
self.seller = SolitudeSeller.objects.create(
r... | class TestBango(Patcher, TestCase):
| fixtures = fixture('user_999')
def setUp(self):
super(TestBango, self).setUp()
self.user = UserProfile.objects.filter()[0]
self.app = app_factory()
self.make_premium(self.app)
self.seller = SolitudeSeller.objects.create(
resource_uri='sellerres', user=self.u... | def test_multiple(self):
with self.settings(PAYMENT_PROVIDERS=['bango', 'reference'],
DEFAULT_PAYMENT_PROVIDER='bango'):
eq_(get_provider().name, 'bango')
class TestBase(TestCase):
def test_check(self):
provider = Reference()
@account_check
... | 126 | 126 | 421 | 10 | 116 | Witia1/zamboni | mkt/developers/tests/test_providers.py | Python | TestBango | TestBango | 87 | 131 | 87 | 87 | 4791900a3d66f08276f47772cf00a32313b44c4b | bigcode/the-stack | train |
b9a1611740c5f268ff6725cb | train | class | class MetadataSyncTest(TestCase):
SYNC_BASE = "/{0}sync/".format(DJANGO_BASE)
INVENTORY_URL = SYNC_BASE
# static variables to be initialized in setUpClass():
syncuser_login = None
normal_login = None
editor_login = None
def extract_inventory(self, response):
with ZipFile(String... | class MetadataSyncTest(TestCase):
| SYNC_BASE = "/{0}sync/".format(DJANGO_BASE)
INVENTORY_URL = SYNC_BASE
# static variables to be initialized in setUpClass():
syncuser_login = None
normal_login = None
editor_login = None
def extract_inventory(self, response):
with ZipFile(StringIO(response.content), 'r') as inzi... | import datetime
import os
import json
import logging
from xml.etree.ElementTree import fromstring
from StringIO import StringIO
from zipfile import ZipFile
from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User, Group, Permission
from django.core.management ... | 175 | 256 | 3,055 | 7 | 168 | hpusset/ELRI | metashare/sync/tests.py | Python | MetadataSyncTest | MetadataSyncTest | 26 | 342 | 26 | 26 | d1389d33d2d4da50b1734162668a05d593817812 | bigcode/the-stack | train |
19ef164e5f9ae5b1b1d40a26 | train | class | class ColoredFormater(logging.Formatter):
""" Support terminal's colored output. """
def format(self, record):
s = logging.Formatter.format(self, record)
# Debug
if record.levelno <= logging.DEBUG:
return s
# INFO
if record.levelno <= logging.INFO:
... | class ColoredFormater(logging.Formatter):
| """ Support terminal's colored output. """
def format(self, record):
s = logging.Formatter.format(self, record)
# Debug
if record.levelno <= logging.DEBUG:
return s
# INFO
if record.levelno <= logging.INFO:
return COLORS.green(s)
# WARN... | OLORS, 33)
COLORS.blue = partial(COLORS, 34)
COLORS.magenta = partial(COLORS, 35)
COLORS.cyan = partial(COLORS, 36)
COLORS.white = partial(COLORS, 37)
class ColoredFormater(logging.Formatter):
| 64 | 64 | 101 | 8 | 56 | movermeyer/starter | starter/log.py | Python | ColoredFormater | ColoredFormater | 20 | 40 | 20 | 21 | aa4c050d9fd91a239a463aae07c8858759613d48 | bigcode/the-stack | train |
60d63b89506e0d58fb6111f5 | train | function | def setup_logging(level):
""" Setup logger. """
logging.root.setLevel(level)
logging.root.addHandler(STREAM_HANDLER)
| def setup_logging(level):
| """ Setup logger. """
logging.root.setLevel(level)
logging.root.addHandler(STREAM_HANDLER)
| .green(s)
# WARN
if record.levelno <= logging.WARN:
return COLORS.yellow(s)
# ERROR
return COLORS.red(s)
STREAM_HANDLER = logging.StreamHandler(sys.stdout)
if sys.stdout.isatty():
STREAM_HANDLER.setFormatter(ColoredFormater())
def setup_logging(level):
| 64 | 64 | 27 | 5 | 59 | movermeyer/starter | starter/log.py | Python | setup_logging | setup_logging | 48 | 51 | 48 | 48 | 4197c3e87b68bd61f240d6822c7de225e6f6daca | bigcode/the-stack | train |
a1a4a14beb7ab4b0ad005db6 | train | function | def create_model(model_builder, model, enable_tensor_core, float16_compute, loss_scale=1.0):
"""Creates one model replica.
:param obj model_builder: A model instance that contains `forward_pass_builder` method.
:param model: Caffe2's model helper class instances.
:type model: :py:class:`caffe2.python.m... | def create_model(model_builder, model, enable_tensor_core, float16_compute, loss_scale=1.0):
| """Creates one model replica.
:param obj model_builder: A model instance that contains `forward_pass_builder` method.
:param model: Caffe2's model helper class instances.
:type model: :py:class:`caffe2.python.model_helper.ModelHelper`
:param bool enable_tensor_core: If true, Volta's tensor core ops... | _batches):
start_time = timeit.default_timer()
workspace.RunNet(net_name, 1)
batch_times[i] = timeit.default_timer() - start_time
return batch_times
def create_model(model_builder, model, enable_tensor_core, float16_compute, loss_scale=1.0):
| 64 | 64 | 216 | 23 | 40 | tfindlay-au/dlcookbook-dlbs | python/caffe2_benchmarks/benchmarks.py | Python | create_model | create_model | 94 | 111 | 94 | 94 | ad890f66cd833768eb0b7d22bbfb0bebc27214d2 | bigcode/the-stack | train |
59cb8b2765ee7491ba39f9f7 | train | function | def benchmark_inference(model, opts):
""" Runs N inferences and returns array of batch times in seconds.
:param model: Caffe2's model helper class instances.
:type model: :py:class:`caffe2.python.model_helper.ModelHelper`
:param dict opts: Options for the inference benchmark. Must contain `device`,\
... | def benchmark_inference(model, opts):
| """ Runs N inferences and returns array of batch times in seconds.
:param model: Caffe2's model helper class instances.
:type model: :py:class:`caffe2.python.model_helper.ModelHelper`
:param dict opts: Options for the inference benchmark. Must contain `device`,\
`num_gpus` if devi... | nn': opts['use_cudnn'],
'cudnn_exhaustive_search': opts['cudnn_exhaustive_search'],
'ws_nbytes_limit': (opts['cudnn_workspace_limit_mb'] * 1024 * 1024)
}
model = model_helper.ModelHelper(name=opts['model'], arg_scope=arg_scope)
else:
print("[WARNING] Creating ModelHel... | 153 | 153 | 511 | 8 | 145 | tfindlay-au/dlcookbook-dlbs | python/caffe2_benchmarks/benchmarks.py | Python | benchmark_inference | benchmark_inference | 185 | 225 | 185 | 185 | 124ebfff55ca6581f2a36cfe45957e035ddf7df2 | bigcode/the-stack | train |
74bf9594e0f322ad437cf987 | train | function | def benchmark(opts):
"""Runs inference or training benchmarks depending on **opts['phase']** value.
You may want to call **workspace.ResetWorkspace()** to clear everything once
this method has exited.
:param dict opts: Options for a benchmark. Must contain `model` and 'phase'.\
O... | def benchmark(opts):
| """Runs inference or training benchmarks depending on **opts['phase']** value.
You may want to call **workspace.ResetWorkspace()** to clear everything once
this method has exited.
:param dict opts: Options for a benchmark. Must contain `model` and 'phase'.\
Other options are opti... | newwer versions of Caffe support this
print("[INFO] Building FP16 SGD optimizer.")
opt = optimizer.build_fp16_sgd(
model, 0.1, momentum=0.9, policy='step', gamma=0.1, weight_decay=1e-4
)
else:
optimizer.add_weight_decay(model, 1e-4)
try:
opt_builder =... | 178 | 178 | 595 | 4 | 173 | tfindlay-au/dlcookbook-dlbs | python/caffe2_benchmarks/benchmarks.py | Python | benchmark | benchmark | 134 | 183 | 134 | 134 | b88db5de4ada4859fe17cdfa15d56d9c29716d8c | bigcode/the-stack | train |
bf6d7606f408e968f004d359 | train | function | def build_optimizer(model, float16_compute=False):
if False: # float16_compute: # A newwer versions of Caffe support this
print("[INFO] Building FP16 SGD optimizer.")
opt = optimizer.build_fp16_sgd(
model, 0.1, momentum=0.9, policy='step', gamma=0.1, weight_decay=1e-4
)
els... | def build_optimizer(model, float16_compute=False):
| if False: # float16_compute: # A newwer versions of Caffe support this
print("[INFO] Building FP16 SGD optimizer.")
opt = optimizer.build_fp16_sgd(
model, 0.1, momentum=0.9, policy='step', gamma=0.1, weight_decay=1e-4
)
else:
optimizer.add_weight_decay(model, 1e-4)
... | .conv, brew.fc],
WeightInitializer=initializer,
BiasInitializer=initializer,
enable_tensor_core=enable_tensor_core,
float16_compute=float16_compute):
outputs = model_builder.forward_pass_builder(model, loss_scale=los... | 64 | 64 | 196 | 10 | 53 | tfindlay-au/dlcookbook-dlbs | python/caffe2_benchmarks/benchmarks.py | Python | build_optimizer | build_optimizer | 114 | 131 | 114 | 114 | c89b88ee5621a61bdcdb58776bf9c09a5643a85f | bigcode/the-stack | train |
71f8524e020d07f264e7bc9d | train | function | def benchmark_training(model, opts):
""" Runs N training batches and returns array of batch times in seconds.
For some impl details see https://caffe2.ai/docs/SynchronousSGD.html.
:param model: Caffe2's model helper class instances.
:type model: :py:class:`caffe2.python.model_helper.ModelHelper`
:... | def benchmark_training(model, opts):
| """ Runs N training batches and returns array of batch times in seconds.
For some impl details see https://caffe2.ai/docs/SynchronousSGD.html.
:param model: Caffe2's model helper class instances.
:type model: :py:class:`caffe2.python.model_helper.ModelHelper`
:param dict opts: Options for the infe... | db_type=opts['data_backend'], # (str, 'lmdb' or 'leveldb')
num_shards=1, # (int, number of machines)
shard_id=0, # (int, machine id)
)
with core.DeviceScope(dev_opt):
if reader is None:
print("[INFO] Adding synthetic data i... | 232 | 233 | 778 | 7 | 225 | tfindlay-au/dlcookbook-dlbs | python/caffe2_benchmarks/benchmarks.py | Python | benchmark_training | benchmark_training | 228 | 306 | 228 | 228 | 27c4571bc4582924654f7fb7d129a1d1be6f677b | bigcode/the-stack | train |
183943fbd98350226d8a0292 | train | function | def run_n_times(model, num_warmup_batches, num_batches):
""" Runs **model** multiple times (**num_warmup_batches** + **num_batches**).
:param model: Caffe2's model helper class instances.
:type model: :py:class:`caffe2.python.model_helper.ModelHelper`
:param int num_warmup_batches: Number of warmup bat... | def run_n_times(model, num_warmup_batches, num_batches):
| """ Runs **model** multiple times (**num_warmup_batches** + **num_batches**).
:param model: Caffe2's model helper class instances.
:type model: :py:class:`caffe2.python.model_helper.ModelHelper`
:param int num_warmup_batches: Number of warmup batches to process (do not contribute to computing average b... | .python import core
from caffe2.python import brew
from caffe2.python import model_helper
from caffe2.python import optimizer
from caffe2.python import data_parallel_model as dpm
from caffe2.python.modeling.initializers import Initializer, pFP16Initializer
from caffe2_benchmarks.models.model import Model
from caffe2_be... | 93 | 93 | 311 | 15 | 77 | tfindlay-au/dlcookbook-dlbs | python/caffe2_benchmarks/benchmarks.py | Python | run_n_times | run_n_times | 68 | 91 | 68 | 68 | 912344fe3c96c0dadee6024764ea98697bbe9a86 | bigcode/the-stack | train |
fc2040767209f4159c8accce | train | class | class coordinateDescent(object):
def __init__(self, X, Y, **kwargs):
self.X = X
self.Y = Y
self.theta = None
self.features = X.shape[1]
self.samples = X.shape[0]
try:
self.iterations = kwargs['iterations']
except:
self.iterations = 100
... | class coordinateDescent(object):
| def __init__(self, X, Y, **kwargs):
self.X = X
self.Y = Y
self.theta = None
self.features = X.shape[1]
self.samples = X.shape[0]
try:
self.iterations = kwargs['iterations']
except:
self.iterations = 100
def training_loss(s... | import torch
from .errors import MSE_torch, SSE_torch
class coordinateDescent(object):
| 22 | 148 | 496 | 6 | 15 | sahitpj/MachineLearning | regression/cordinate.py | Python | coordinateDescent | coordinateDescent | 4 | 71 | 4 | 4 | adc4dabea6217c8d91d389f62420c99e1cad9a2d | bigcode/the-stack | train |
95d0ed13ac5e2d685a31ee0e | train | class | @magics_class
class MatlabMagics(Magics):
"""
A set of magics for interactive work with Matlab(R).
"""
def __init__(self, shell,
matlab='matlab',
maxtime=60,
pyconverter=np.asarray):
"""
Parameters
----------
shell : IPy... | @magics_class
class MatlabMagics(Magics):
| """
A set of magics for interactive work with Matlab(R).
"""
def __init__(self, shell,
matlab='matlab',
maxtime=60,
pyconverter=np.asarray):
"""
Parameters
----------
shell : IPython shell
matlab : str
... | lab_magic
============
Magic command interface for interactive work with Matlab(R) via the pymatbridge
"""
from shutil import rmtree
import numpy as np
import IPython
from IPython.core.displaypub import publish_display_data
from IPython.core.magic import (Magics, magics_class,
line_... | 255 | 256 | 1,084 | 13 | 242 | blink1073/python-matlab-bridge | pymatbridge/matlab_magic.py | Python | MatlabMagics | MatlabMagics | 47 | 202 | 47 | 48 | f77171fbc55c36c97f02d19eae5d99b3301b0c0e | bigcode/the-stack | train |
73a7037288946afbf6baf9f7 | train | class | class MatlabInterperterError(RuntimeError):
"""
Some error occurs while matlab is running
"""
def __init__(self, line, err):
self.line = line
self.err = err
def __unicode__(self):
s = "Failed to parse and evaluate line %r.\n Matlab error message: %r"%\
(self.... | class MatlabInterperterError(RuntimeError):
| """
Some error occurs while matlab is running
"""
def __init__(self, line, err):
self.line = line
self.err = err
def __unicode__(self):
s = "Failed to parse and evaluate line %r.\n Matlab error message: %r"%\
(self.line, self.err)
return s
if PY3... | _cell_magic, needs_local_scope)
from IPython.core.magic_arguments import (argument, magic_arguments,
parse_argstring)
from IPython.utils.py3compat import unicode_to_str, PY3
import pymatbridge as pymat
from .compat import text_type
class MatlabInterperterError(RuntimeError):
| 64 | 64 | 123 | 9 | 54 | blink1073/python-matlab-bridge | pymatbridge/matlab_magic.py | Python | MatlabInterperterError | MatlabInterperterError | 26 | 43 | 26 | 26 | 8249224ed71e64386ee86e5c4d0d61d98ebb9316 | bigcode/the-stack | train |
928f1408f795abe341c50f47 | train | function | def unload_ipython_extension(ip):
global _loaded
if _loaded:
magic = ip.magics_manager.registry.pop('MatlabMagics')
magic.Matlab.stop()
_loaded = False
| def unload_ipython_extension(ip):
| global _loaded
if _loaded:
magic = ip.magics_manager.registry.pop('MatlabMagics')
magic.Matlab.stop()
_loaded = False
| (output)})
_loaded = False
def load_ipython_extension(ip, **kwargs):
"""Load the extension in IPython."""
global _loaded
if not _loaded:
ip.register_magics(MatlabMagics(ip, **kwargs))
_loaded = True
def unload_ipython_extension(ip):
| 64 | 64 | 45 | 7 | 56 | blink1073/python-matlab-bridge | pymatbridge/matlab_magic.py | Python | unload_ipython_extension | unload_ipython_extension | 213 | 218 | 213 | 213 | 02d8785aa73d4d105f7ebb0ad0be09b7eeaa3384 | bigcode/the-stack | train |
400da593fdd7f878fbe94e7b | train | function | def load_ipython_extension(ip, **kwargs):
"""Load the extension in IPython."""
global _loaded
if not _loaded:
ip.register_magics(MatlabMagics(ip, **kwargs))
_loaded = True
| def load_ipython_extension(ip, **kwargs):
| """Load the extension in IPython."""
global _loaded
if not _loaded:
ip.register_magics(MatlabMagics(ip, **kwargs))
_loaded = True
| files created by matlab:
if len(data_dir):
rmtree(data_dir)
if args.output:
for output in ','.join(args.output).split(','):
self.shell.push({output:self.Matlab.get_variable(output)})
_loaded = False
def load_ipython_extension(ip, **kwargs):
| 64 | 64 | 50 | 10 | 53 | blink1073/python-matlab-bridge | pymatbridge/matlab_magic.py | Python | load_ipython_extension | load_ipython_extension | 206 | 211 | 206 | 206 | d290fa045b4990759daa3bc3ccf2431627aad332 | bigcode/the-stack | train |
f62c931d1750653b789f8e2f | train | class | class BUCHook(HookBase):
def __init__(self, cfg, train_set):
super().__init__()
self.iters_per_epoch = len(train_set) // cfg.SOLVER.IMS_PER_BATCH
self.loops = 0
self.step_iter = (2 * self.loops + 20) * self.iters_per_epoch
self.train_set = train_set
num_train_ids = le... | class BUCHook(HookBase):
| def __init__(self, cfg, train_set):
super().__init__()
self.iters_per_epoch = len(train_set) // cfg.SOLVER.IMS_PER_BATCH
self.loops = 0
self.step_iter = (2 * self.loops + 20) * self.iters_per_epoch
self.train_set = train_set
num_train_ids = len(np.unique(np.array(self... | import numpy as np
import torch
from fastreid.data.build import fast_batch_collator
from fastreid.data.samplers import InferenceSampler
from fastreid.engine.train_loop import HookBase
from fastreid.evaluation.evaluator import inference_context
from .exloss import ExLoss
class BUCHook(HookBase):
| 71 | 256 | 1,217 | 8 | 62 | weleen/MGH.pytorch | projects/BUC/bucreid/hooks.py | Python | BUCHook | BUCHook | 11 | 127 | 11 | 11 | 4277ec55edbbf72253332231c128a4d2f6d2abfb | bigcode/the-stack | train |
03770ae1c97be6cea66dd87c | train | function | def check(path):
with open(path) as f:
original = f.read()
formatted = subprocess.check_output(["clang-format", "-assume-filename", path],
input=original, text=True)
diff = difflib.unified_diff(original.splitlines(keepends=True),
... | def check(path):
| with open(path) as f:
original = f.read()
formatted = subprocess.check_output(["clang-format", "-assume-filename", path],
input=original, text=True)
diff = difflib.unified_diff(original.splitlines(keepends=True),
formatted.split... | #!/usr/bin/env python3
import difflib
import logging
import subprocess
import sys
import _utils as utils
def check(path):
| 31 | 64 | 142 | 4 | 26 | kiwixz/shapes_riot | check_clang_format.py | Python | check | check | 11 | 31 | 11 | 11 | bccfba116853056473a00e93d7fb53a4aba367c8 | bigcode/the-stack | train |
dfb0c9038aeb32499bfc969d | train | class | class Bfdv4Interface(Base):
"""BFDv4 Interface (Device) level Configuration
The Bfdv4Interface class encapsulates a list of bfdv4Interface resources that are managed by the user.
A list of resources can be retrieved from the server using the Bfdv4Interface.find() method.
The list can be managed by u... | class Bfdv4Interface(Base):
| """BFDv4 Interface (Device) level Configuration
The Bfdv4Interface class encapsulates a list of bfdv4Interface resources that are managed by the user.
A list of resources can be retrieved from the server using the Bfdv4Interface.find() method.
The list can be managed by using the Bfdv4Interface.add()... | 7 - 2020 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribut... | 256 | 256 | 9,326 | 8 | 247 | rfrye-github/ixnetwork_restpy | uhd_restpy/testplatform/sessions/ixnetwork/topology/bfdv4interface_91b557a3f744baf442dbe21ac75e8f2e.py | Python | Bfdv4Interface | Bfdv4Interface | 26 | 903 | 26 | 26 | c056fddf8d2652fbc67b483e5c2ee5e1d88e07d0 | bigcode/the-stack | train |
39d0401a0ff0424cdd70206f | train | function | def test_get_attribute_name():
assert (models.SqlRun.get_attribute_name("artifact_uri") == "artifact_uri")
assert (models.SqlRun.get_attribute_name("status") == "status")
assert (models.SqlRun.get_attribute_name("start_time") == "start_time")
assert (models.SqlRun.get_attribute_name("end_time") == "end_... | def test_get_attribute_name():
| assert (models.SqlRun.get_attribute_name("artifact_uri") == "artifact_uri")
assert (models.SqlRun.get_attribute_name("status") == "status")
assert (models.SqlRun.get_attribute_name("start_time") == "start_time")
assert (models.SqlRun.get_attribute_name("end_time") == "end_time")
# we want this to b... | ):
mock_store = mock.Mock(SqlAlchemyStore)
mock_store.db_type = MSSQL
SqlAlchemyStore._unset_zero_value_insertion_for_autoincrement_column(mock_store,
mock_session)
mock_session.execute.assert_called_with("SET I... | 64 | 64 | 132 | 6 | 58 | msabramo/mlflow | tests/store/tracking/test_sqlalchemy_store.py | Python | test_get_attribute_name | test_get_attribute_name | 1,714 | 1,723 | 1,714 | 1,714 | 9ce78929096ed8d1026c843c19ddb1f66ada7827 | bigcode/the-stack | train |
5a44b6740562347f86df92f3 | train | class | @pytest.mark.release
class TestSqlAlchemyStoreMysqlDb(TestSqlAlchemyStoreSqlite):
"""
Run tests against a MySQL database
"""
DEFAULT_MYSQL_PORT = 3306
def setUp(self):
os.environ[MLFLOW_SQLALCHEMYSTORE_POOL_SIZE] = "2"
os.environ[MLFLOW_SQLALCHEMYSTORE_MAX_OVERFLOW] = "1"
db... | @pytest.mark.release
class TestSqlAlchemyStoreMysqlDb(TestSqlAlchemyStoreSqlite):
| """
Run tests against a MySQL database
"""
DEFAULT_MYSQL_PORT = 3306
def setUp(self):
os.environ[MLFLOW_SQLALCHEMYSTORE_POOL_SIZE] = "2"
os.environ[MLFLOW_SQLALCHEMYSTORE_MAX_OVERFLOW] = "1"
db_username = os.environ.get("MYSQL_TEST_USERNAME")
db_password = os.environ... | then migrates their DB. TODO: update this test in MLflow 1.1 to use InitialBase from
mlflow.store.db.initial_models.
"""
def setUp(self):
fd, self.temp_dbfile = tempfile.mkstemp()
os.close(fd)
self.db_url = "%s%s" % (DB_URI, self.temp_dbfile)
engine = sqlalchemy.create_e... | 161 | 161 | 538 | 18 | 143 | msabramo/mlflow | tests/store/tracking/test_sqlalchemy_store.py | Python | TestSqlAlchemyStoreMysqlDb | TestSqlAlchemyStoreMysqlDb | 1,641 | 1,682 | 1,641 | 1,642 | 3ebe6767f182e35d948bc01c88805a19b80366b8 | bigcode/the-stack | train |
946e5a1675f897fea4a9e6ba | train | class | class TestSqlAlchemyStoreSqlite(unittest.TestCase, AbstractStoreTest):
def _get_store(self, db_uri=''):
return SqlAlchemyStore(db_uri, ARTIFACT_URI)
def create_test_run(self):
return self._run_factory()
def setUp(self):
self.maxDiff = None # print all differences on assert failur... | class TestSqlAlchemyStoreSqlite(unittest.TestCase, AbstractStoreTest):
| def _get_store(self, db_uri=''):
return SqlAlchemyStore(db_uri, ARTIFACT_URI)
def create_test_run(self):
return self._run_factory()
def setUp(self):
self.maxDiff = None # print all differences on assert failures
fd, self.temp_dbfile = tempfile.mkstemp()
# Close han... | )
# try each of the popular drivers (per SQLAlchemy's dialect pages)
for driver in drivers:
uri = "%s+%s://..." % (target_db_type, driver)
parsed_db_type = extract_db_type_from_uri(uri)
self.assertEqual(target_db_type, parsed_db_type)
def _db_... | 256 | 256 | 17,569 | 15 | 241 | msabramo/mlflow | tests/store/tracking/test_sqlalchemy_store.py | Python | TestSqlAlchemyStoreSqlite | TestSqlAlchemyStoreSqlite | 82 | 1,618 | 82 | 83 | 90a8355858a30df538e5e05839016ed0bd08b4e9 | bigcode/the-stack | train |
7a10bda3f93f64064da4ba94 | train | class | class TestSqlAlchemyStoreSqliteMigratedDB(TestSqlAlchemyStoreSqlite):
"""
Test case where user has an existing DB with schema generated before MLflow 1.0,
then migrates their DB. TODO: update this test in MLflow 1.1 to use InitialBase from
mlflow.store.db.initial_models.
"""
def setUp(self):
... | class TestSqlAlchemyStoreSqliteMigratedDB(TestSqlAlchemyStoreSqlite):
| """
Test case where user has an existing DB with schema generated before MLflow 1.0,
then migrates their DB. TODO: update this test in MLflow 1.1 to use InitialBase from
mlflow.store.db.initial_models.
"""
def setUp(self):
fd, self.temp_dbfile = tempfile.mkstemp()
os.close(fd)
... | value="1"))
run_results = self.store.search_runs([experiment_id],
None,
ViewType.ALL, max_results=1000, order_by=["tag.t1"])
assert len(run_results) == 2
class TestSqlAlchemyStoreSqliteMigratedDB(TestSqlAlchemySt... | 64 | 64 | 182 | 17 | 46 | msabramo/mlflow | tests/store/tracking/test_sqlalchemy_store.py | Python | TestSqlAlchemyStoreSqliteMigratedDB | TestSqlAlchemyStoreSqliteMigratedDB | 1,621 | 1,638 | 1,621 | 1,621 | 2d2790df5c78909273bcff42bd24eee3701f5d65 | bigcode/the-stack | train |
5ff883fa20523ceb41b15001 | train | class | @mock.patch('sqlalchemy.orm.session.Session', spec=True)
class TestZeroValueInsertion(unittest.TestCase):
def test_set_zero_value_insertion_for_autoincrement_column_MYSQL(self, mock_session):
mock_store = mock.Mock(SqlAlchemyStore)
mock_store.db_type = MYSQL
SqlAlchemyStore._set_zero_value_i... | @mock.patch('sqlalchemy.orm.session.Session', spec=True)
class TestZeroValueInsertion(unittest.TestCase):
| def test_set_zero_value_insertion_for_autoincrement_column_MYSQL(self, mock_session):
mock_store = mock.Mock(SqlAlchemyStore)
mock_store.db_type = MYSQL
SqlAlchemyStore._set_zero_value_insertion_for_autoincrement_column(mock_store, mock_session)
mock_session.execute.assert_called_wit... | .Metric("key", i, i * 2, i * 3))
self.store.log_param(run.info.run_id, entities.Param("pkey-%s" % i, "pval-%s" % i))
self.store.set_tag(run.info.run_id, entities.RunTag("tkey-%s" % i, "tval-%s" % i))
@mock.patch('sqlalchemy.orm.session.Session', spec=True)
class TestZeroValueInsertion(unittest.T... | 100 | 100 | 335 | 22 | 78 | msabramo/mlflow | tests/store/tracking/test_sqlalchemy_store.py | Python | TestZeroValueInsertion | TestZeroValueInsertion | 1,685 | 1,711 | 1,685 | 1,686 | 2afc0420f6f142d9f5e78993b3ee7b2e58be6106 | bigcode/the-stack | train |
638d76daa8bb3d42cd04babb | train | class | class TestParseDbUri(unittest.TestCase):
def test_correct_db_type_from_uri(self):
# try each the main drivers per supported database type
target_db_type_uris = {
'sqlite': ('pysqlite', 'pysqlcipher'),
'postgresql': ('psycopg2', 'pg8000', 'psycopg2cffi',
... | class TestParseDbUri(unittest.TestCase):
| def test_correct_db_type_from_uri(self):
# try each the main drivers per supported database type
target_db_type_uris = {
'sqlite': ('pysqlite', 'pysqlcipher'),
'postgresql': ('psycopg2', 'pg8000', 'psycopg2cffi',
'pypostgresql', 'pygresql', 'zxjdbc'... | _POOL_SIZE
from mlflow.store.tracking.dbmodels import models
from mlflow.store.db.db_types import MYSQL, MSSQL
from mlflow import entities
from mlflow.exceptions import MlflowException
from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore
from mlflow.utils import mlflow_tags
from mlflow.utils.file_utils im... | 143 | 143 | 477 | 9 | 134 | msabramo/mlflow | tests/store/tracking/test_sqlalchemy_store.py | Python | TestParseDbUri | TestParseDbUri | 42 | 79 | 42 | 43 | eeebf09436d892c6f3a170d71efa215952ac3f19 | bigcode/the-stack | train |
569c0127c5630ff626d64938 | train | function | def traverse(x, N, stack, F, X, R, FP):
stack.append(x)
d = len(stack)
N[x] = d
F[x] = FP(x)
rel = R(x)
for y in rel:
if N[y] == 0:
traverse(y, N, stack, F, X, R, FP)
N[x] = min(N[x], N[y])
for a in F.get(y, []):
if a not in F[x]:
... | def traverse(x, N, stack, F, X, R, FP):
| stack.append(x)
d = len(stack)
N[x] = d
F[x] = FP(x)
rel = R(x)
for y in rel:
if N[y] == 0:
traverse(y, N, stack, F, X, R, FP)
N[x] = min(N[x], N[y])
for a in F.get(y, []):
if a not in F[x]:
F[x].append(a)
if N[x] == d:
... | (X, 0)
stack = []
F = {}
for x in X:
if N[x] == 0:
traverse(x, N, stack, F, X, R, FP)
return F
def traverse(x, N, stack, F, X, R, FP):
| 64 | 64 | 186 | 16 | 47 | rcarmo/rss2imap-gae | lib/rply/parsergenerator.py | Python | traverse | traverse | 255 | 276 | 255 | 255 | 711bb15c4d132e4da5ec4bb05cb33b17a5005cd2 | bigcode/the-stack | train |
59ac149c37c5e98b07210943 | train | function | def digraph(X, R, FP):
N = dict.fromkeys(X, 0)
stack = []
F = {}
for x in X:
if N[x] == 0:
traverse(x, N, stack, F, X, R, FP)
return F
| def digraph(X, R, FP):
| N = dict.fromkeys(X, 0)
stack = []
F = {}
for x in X:
if N[x] == 0:
traverse(x, N, stack, F, X, R, FP)
return F
| d reduce/reduce conflict%s" % (len(table.rr_conflicts), "s" if len(table.rr_conflicts) > 1 else ""),
ParserGeneratorWarning,
stacklevel=2,
)
return LRParser(table, self.error_handler)
def digraph(X, R, FP):
| 64 | 64 | 63 | 9 | 55 | rcarmo/rss2imap-gae | lib/rply/parsergenerator.py | Python | digraph | digraph | 245 | 252 | 245 | 245 | 47d815d6d868b3595e46f59ee38570a6d33807dc | bigcode/the-stack | train |
8211fcfaaa078d975a05c078 | train | class | class ParserGenerator(object):
"""
A ParserGenerator represents a set of production rules, that define a
sequence of terminals and non-terminals to be replaced with a non-terminal,
which can be turned into a parser.
:param tokens: A list of token (non-terminal) names.
:param precedence: A list ... | class ParserGenerator(object):
| """
A ParserGenerator represents a set of production rules, that define a
sequence of terminals and non-terminals to be replaced with a non-terminal,
which can be turned into a parser.
:param tokens: A list of token (non-terminal) names.
:param precedence: A list of tuples defining the order of... | import os
import hashlib
import json
import random
import stat
import string
import sys
import tempfile
import warnings
from rply.errors import ParserGeneratorError, ParserGeneratorWarning
from rply.grammar import Grammar
from rply.parser import LRParser
from rply.utils import IdentityDict, Counter, iteritems, iterval... | 133 | 256 | 1,778 | 5 | 127 | rcarmo/rss2imap-gae | lib/rply/parsergenerator.py | Python | ParserGenerator | ParserGenerator | 27 | 242 | 27 | 27 | ecd2a30d0e5042644fb4a14215fd9afb88ba6e0f | bigcode/the-stack | train |
7054ea5888d5821b1efac5bd | train | class | class LRTable(object):
def __init__(self, grammar, lr_action, lr_goto, default_reductions, sr_conflicts, rr_conflicts):
self.grammar = grammar
self.lr_action = lr_action
self.lr_goto = lr_goto
self.default_reductions = default_reductions
self.sr_conflicts = sr_conflicts
... | class LRTable(object):
| def __init__(self, grammar, lr_action, lr_goto, default_reductions, sr_conflicts, rr_conflicts):
self.grammar = grammar
self.lr_action = lr_action
self.lr_goto = lr_goto
self.default_reductions = default_reductions
self.sr_conflicts = sr_conflicts
self.rr_conflicts = ... | _handler)
def digraph(X, R, FP):
N = dict.fromkeys(X, 0)
stack = []
F = {}
for x in X:
if N[x] == 0:
traverse(x, N, stack, F, X, R, FP)
return F
def traverse(x, N, stack, F, X, R, FP):
stack.append(x)
d = len(stack)
N[x] = d
F[x] = FP(x)
rel = R(x)
fo... | 256 | 256 | 2,913 | 5 | 251 | rcarmo/rss2imap-gae | lib/rply/parsergenerator.py | Python | LRTable | LRTable | 279 | 619 | 279 | 279 | 12de576a29a24e4293235a3d2e5ff90275fc691c | bigcode/the-stack | train |
fa6961d226494f8cde9d2faf | train | function | def normalize_tags(tags, sort=False):
# The base class ensures the Agent receives bytes, so to avoid
# prefacing our asserted tags like b'foo:bar' we'll convert back.
if tags:
if sort:
return sorted(ensure_unicode(tag) for tag in tags)
else:
return [ensure_unicode(tag... | def normalize_tags(tags, sort=False):
# The base class ensures the Agent receives bytes, so to avoid
# prefacing our asserted tags like b'foo:bar' we'll convert back.
| if tags:
if sort:
return sorted(ensure_unicode(tag) for tag in tags)
else:
return [ensure_unicode(tag) for tag in tags]
return tags
| .base.stubs.similar import build_similar_elements_msg
from ..utils.common import ensure_unicode, to_string
def normalize_tags(tags, sort=False):
# The base class ensures the Agent receives bytes, so to avoid
# prefacing our asserted tags like b'foo:bar' we'll convert back.
| 64 | 64 | 81 | 41 | 22 | glasser/integrations-core | datadog_checks_base/datadog_checks/base/stubs/aggregator.py | Python | normalize_tags | normalize_tags | 16 | 24 | 16 | 18 | 33ccaff55662690968b3caa20bd229f083cf1ceb | bigcode/the-stack | train |
a135360ec0f01cd7e8c6dcf5 | train | class | class AggregatorStub(object):
"""
Mainly used for unit testing checks, this stub makes possible to execute
a check without a running Agent.
"""
# Replicate the Enum we have on the Agent
METRIC_ENUM_MAP = OrderedDict(
(
('gauge', 0),
('rate', 1),
('cou... | class AggregatorStub(object):
| """
Mainly used for unit testing checks, this stub makes possible to execute
a check without a running Agent.
"""
# Replicate the Enum we have on the Agent
METRIC_ENUM_MAP = OrderedDict(
(
('gauge', 0),
('rate', 1),
('count', 2),
('monoton... | # (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from __future__ import division
from collections import OrderedDict, defaultdict
from six import binary_type, iteritems
from datadog_checks.base.stubs.common import HistogramBucketStub, MetricStub, ServiceCheck... | 194 | 256 | 3,063 | 6 | 187 | glasser/integrations-core | datadog_checks_base/datadog_checks/base/stubs/aggregator.py | Python | AggregatorStub | AggregatorStub | 27 | 428 | 27 | 27 | 873e6b8bb15ec2f990a3c236c210b11b28ab9b6c | bigcode/the-stack | train |
8d866ace96e7e0ca17e1bc22 | train | class | class Solution:
def addStrings(self, a: str, b: str) -> str:
# 字符串转数字的方法
def str_to_num(strs):
n = len(strs) - 1
num = 0
for i in strs:
num += hash[i] * 10**n
n -= 1
return num
# 直接调用即可
hash = {
... | class Solution:
| def addStrings(self, a: str, b: str) -> str:
# 字符串转数字的方法
def str_to_num(strs):
n = len(strs) - 1
num = 0
for i in strs:
num += hash[i] * 10**n
n -= 1
return num
# 直接调用即可
hash = {
"0": 0,
... | # 执行用时 : 576 ms
# 内存消耗 : 28.9 MB
# 方案:字符串转数字
class Solution:
| 34 | 64 | 189 | 3 | 30 | IYoreI/Algorithm | Codes/Liam/415_add_strings.py | Python | Solution | Solution | 7 | 33 | 7 | 7 | 5e1825cc9625b7eb12bf08122ec78a02e6f2db37 | bigcode/the-stack | train |
6637d7da4a926a7d5413193d | train | function | def bmi(weight, height):
b = weight / height ** 2
p = "Slim"
if b > 30: p = "Obese"
elif b > 25: p = "Overweight"
elif b > 18.5: p = "Normal"
else: p = "Underweight"
return p
| def bmi(weight, height):
| b = weight / height ** 2
p = "Slim"
if b > 30: p = "Obese"
elif b > 25: p = "Overweight"
elif b > 18.5: p = "Normal"
else: p = "Underweight"
return p
| body mass index (bmi = weight / height2).
if bmi <= 18.5 return "Underweight"
if bmi <= 25.0 return "Normal"
if bmi <= 30.0 return "Overweight"
if bmi > 30 return "Obese"
'''
def bmi(weight, height):
| 64 | 64 | 79 | 6 | 58 | sirken/coding-practice | codewars/8 kyu/calculate-bmi.py | Python | bmi | bmi | 15 | 22 | 15 | 15 | b334645f21e38f2c2e2d9f3949b1797c9d45096a | bigcode/the-stack | train |
9bd1e648fd3512d1ee210f92 | train | function | @pytest.mark.unit
def test_from_instance_defaults():
c = from_instance({'url': 'http://example.com'})
assert c.admin_forwarder is False
assert c.pshard_stats is False
assert c.pshard_graceful_to is False
assert c.cluster_stats is False
assert c.detailed_index_stats is False
assert c.index_s... | @pytest.mark.unit
def test_from_instance_defaults():
| c = from_instance({'url': 'http://example.com'})
assert c.admin_forwarder is False
assert c.pshard_stats is False
assert c.pshard_graceful_to is False
assert c.cluster_stats is False
assert c.detailed_index_stats is False
assert c.index_stats is False
assert c.service_check_tags == ['ho... | og_checks.elastic.config import from_instance
@pytest.mark.unit
def test_from_instance_invalid():
# missing url
with pytest.raises(ConfigurationError):
from_instance({})
# empty url
with pytest.raises(ConfigurationError):
from_instance({'url': ''})
@pytest.mark.unit
def test_from_insta... | 64 | 64 | 131 | 10 | 54 | mindovermiles262/integrations-core | elastic/tests/test_config.py | Python | test_from_instance_defaults | test_from_instance_defaults | 20 | 33 | 20 | 21 | 73b147c637f4d9a1c69a2ad32b27f376b9125d18 | bigcode/the-stack | train |
d0eb6c7216cfd2f2e42e0635 | train | function | @pytest.mark.unit
def test_from_instance_cluster_stats():
c = from_instance({'url': 'http://example.com', 'is_external': True})
assert c.cluster_stats is True
| @pytest.mark.unit
def test_from_instance_cluster_stats():
| c = from_instance({'url': 'http://example.com', 'is_external': True})
assert c.cluster_stats is True
| is False
assert c.service_check_tags == ['host:example.com', 'port:None']
assert c.tags == ['url:http://example.com']
assert c.url == 'http://example.com'
assert c.pending_task_stats is True
@pytest.mark.unit
def test_from_instance_cluster_stats():
| 64 | 64 | 39 | 11 | 52 | mindovermiles262/integrations-core | elastic/tests/test_config.py | Python | test_from_instance_cluster_stats | test_from_instance_cluster_stats | 36 | 39 | 36 | 37 | 54567c1c5751ac2324efe513da943c6148ab98f9 | bigcode/the-stack | train |
8d92210ab012dc6ace077287 | train | function | @pytest.mark.unit
def test_from_instance_detailed_index_stats():
c = from_instance({'url': 'http://example.com', 'detailed_index_stats': True})
assert c.detailed_index_stats is True
| @pytest.mark.unit
def test_from_instance_detailed_index_stats():
| c = from_instance({'url': 'http://example.com', 'detailed_index_stats': True})
assert c.detailed_index_stats is True
| example.com'
assert c.pending_task_stats is True
@pytest.mark.unit
def test_from_instance_cluster_stats():
c = from_instance({'url': 'http://example.com', 'is_external': True})
assert c.cluster_stats is True
@pytest.mark.unit
def test_from_instance_detailed_index_stats():
| 64 | 64 | 45 | 13 | 50 | mindovermiles262/integrations-core | elastic/tests/test_config.py | Python | test_from_instance_detailed_index_stats | test_from_instance_detailed_index_stats | 42 | 45 | 42 | 43 | 7ce8e3aab75ad36303e5982c4599ec9e2ec18103 | bigcode/the-stack | train |
9812735834f2809fbd7ca618 | train | function | @pytest.mark.unit
def test_from_instance_invalid():
# missing url
with pytest.raises(ConfigurationError):
from_instance({})
# empty url
with pytest.raises(ConfigurationError):
from_instance({'url': ''})
| @pytest.mark.unit
def test_from_instance_invalid():
# missing url
| with pytest.raises(ConfigurationError):
from_instance({})
# empty url
with pytest.raises(ConfigurationError):
from_instance({'url': ''})
| 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import pytest
from datadog_checks.base import ConfigurationError
from datadog_checks.elastic.config import from_instance
@pytest.mark.unit
def test_from_instance_invalid():
# missing url
| 64 | 64 | 46 | 15 | 48 | mindovermiles262/integrations-core | elastic/tests/test_config.py | Python | test_from_instance_invalid | test_from_instance_invalid | 10 | 17 | 10 | 12 | 0e7f36cd3c2c59303dbbe4147732b5e8ef7e86a3 | bigcode/the-stack | train |
07b2b42cd87f0119525c028c | train | function | @pytest.mark.unit
def test_from_instance():
instance = {
"username": "user",
"password": "pass",
"is_external": "yes",
"detailed_index_stats": "yes",
"url": "http://foo.bar",
"tags": ["a", "b:c"],
}
c = from_instance(instance)
assert c.admin_forwarder is F... | @pytest.mark.unit
def test_from_instance():
| instance = {
"username": "user",
"password": "pass",
"is_external": "yes",
"detailed_index_stats": "yes",
"url": "http://foo.bar",
"tags": ["a", "b:c"],
}
c = from_instance(instance)
assert c.admin_forwarder is False
assert c.cluster_stats is True
... | assert c.tags == ['url:http://example.com']
assert c.url == 'http://example.com'
assert c.pending_task_stats is True
@pytest.mark.unit
def test_from_instance_cluster_stats():
c = from_instance({'url': 'http://example.com', 'is_external': True})
assert c.cluster_stats is True
@pytest.mark.unit
de... | 125 | 125 | 417 | 9 | 115 | mindovermiles262/integrations-core | elastic/tests/test_config.py | Python | test_from_instance | test_from_instance | 48 | 88 | 48 | 49 | 91a223c323ae83d95b505592dc817b00c090041c | bigcode/the-stack | train |
fe6921b3e3eca2c6ec8f5185 | train | function | def home(request):
response = {'home':'active'}
return render(request, "Main/home.html", response)
| def home(request):
| response = {'home':'active'}
return render(request, "Main/home.html", response)
| from django.shortcuts import render
def home(request):
| 10 | 64 | 24 | 4 | 5 | CherBoon/Cloudtopus | ICA-1-(Cat Proj)/ICA/Main/views.py | Python | home | home | 3 | 5 | 3 | 3 | bff5ac374f2f5a3c49f7e3fbc6e140fde23cff2d | bigcode/the-stack | train |
27187ea6a6a08dd29b027861 | train | class | class PhaseFlow(Animation):
CONFIG = {
"virtual_time": 1,
"rate_func": linear,
"suspend_mobject_updating": False,
}
def __init__(self, function, mobject, **kwargs):
self.function = function
super().__init__(mobject, **kwargs)
def interpolate_mobject(self, alpha)... | class PhaseFlow(Animation):
| CONFIG = {
"virtual_time": 1,
"rate_func": linear,
"suspend_mobject_updating": False,
}
def __init__(self, function, mobject, **kwargs):
self.function = function
super().__init__(mobject, **kwargs)
def interpolate_mobject(self, alpha):
if hasattr(self, "... | def homotopy(x, y, z, t):
c = complex_homotopy(complex(x, y), t)
return (c.real, c.imag, z)
Homotopy.__init__(self, homotopy, mobject, **kwargs)
class PhaseFlow(Animation):
| 64 | 64 | 125 | 5 | 59 | mz71/manim | manim/animation/movement.py | Python | PhaseFlow | PhaseFlow | 48 | 63 | 48 | 48 | 617033c76029ac91fda01db705f3c704c5b81250 | bigcode/the-stack | train |
a1604d474e8a7917560b0c33 | train | class | class Homotopy(Animation):
CONFIG = {
"run_time": 3,
"apply_function_kwargs": {},
}
def __init__(self, homotopy, mobject, **kwargs):
"""
Homotopy is a function from
(x, y, z, t) to (x', y', z')
"""
self.homotopy = homotopy
super().__init__(mob... | class Homotopy(Animation):
| CONFIG = {
"run_time": 3,
"apply_function_kwargs": {},
}
def __init__(self, homotopy, mobject, **kwargs):
"""
Homotopy is a function from
(x, y, z, t) to (x', y', z')
"""
self.homotopy = homotopy
super().__init__(mobject, **kwargs)
def fu... | from ..animation.animation import Animation
from ..utils.rate_functions import linear
class Homotopy(Animation):
| 21 | 64 | 167 | 6 | 14 | mz71/manim | manim/animation/movement.py | Python | Homotopy | Homotopy | 5 | 26 | 5 | 5 | 28b281ef7168cd66886df9718dce9fcf75dee3cd | bigcode/the-stack | train |
b2ad309bd13c67c84e4e3fef | train | class | class MoveAlongPath(Animation):
CONFIG = {
"suspend_mobject_updating": False,
}
def __init__(self, mobject, path, **kwargs):
self.path = path
super().__init__(mobject, **kwargs)
def interpolate_mobject(self, alpha):
point = self.path.point_from_proportion(alpha)
... | class MoveAlongPath(Animation):
| CONFIG = {
"suspend_mobject_updating": False,
}
def __init__(self, mobject, path, **kwargs):
self.path = path
super().__init__(mobject, **kwargs)
def interpolate_mobject(self, alpha):
point = self.path.point_from_proportion(alpha)
self.mobject.move_to(point)
| kwargs)
def interpolate_mobject(self, alpha):
if hasattr(self, "last_alpha"):
dt = self.virtual_time * (alpha - self.last_alpha)
self.mobject.apply_function(lambda p: p + dt * self.function(p))
self.last_alpha = alpha
class MoveAlongPath(Animation):
| 64 | 64 | 83 | 6 | 57 | mz71/manim | manim/animation/movement.py | Python | MoveAlongPath | MoveAlongPath | 66 | 77 | 66 | 66 | 1def76aaa3170d0152b8d9a34c7494f239a26eee | bigcode/the-stack | train |
f13077e9ddeef353317d8c61 | train | class | class SmoothedVectorizedHomotopy(Homotopy):
def interpolate_submobject(self, submob, start, alpha):
Homotopy.interpolate_submobject(self, submob, start, alpha)
submob.make_smooth()
| class SmoothedVectorizedHomotopy(Homotopy):
| def interpolate_submobject(self, submob, start, alpha):
Homotopy.interpolate_submobject(self, submob, start, alpha)
submob.make_smooth()
| opy(*p, t)
def interpolate_submobject(self, submob, start, alpha):
submob.points = start.points
submob.apply_function(
self.function_at_time_t(alpha), **self.apply_function_kwargs
)
class SmoothedVectorizedHomotopy(Homotopy):
| 64 | 64 | 52 | 13 | 51 | mz71/manim | manim/animation/movement.py | Python | SmoothedVectorizedHomotopy | SmoothedVectorizedHomotopy | 29 | 32 | 29 | 29 | ce45b377b516d9addbd365bd4b59d5d3f54e925b | bigcode/the-stack | train |
ba870ff087e322a3ed3e5328 | train | class | class ComplexHomotopy(Homotopy):
def __init__(self, complex_homotopy, mobject, **kwargs):
"""
Complex Hootopy a function Cx[0, 1] to C
"""
def homotopy(x, y, z, t):
c = complex_homotopy(complex(x, y), t)
return (c.real, c.imag, z)
Homotopy.__init__(s... | class ComplexHomotopy(Homotopy):
| def __init__(self, complex_homotopy, mobject, **kwargs):
"""
Complex Hootopy a function Cx[0, 1] to C
"""
def homotopy(x, y, z, t):
c = complex_homotopy(complex(x, y), t)
return (c.real, c.imag, z)
Homotopy.__init__(self, homotopy, mobject, **kwargs)... | )
class SmoothedVectorizedHomotopy(Homotopy):
def interpolate_submobject(self, submob, start, alpha):
Homotopy.interpolate_submobject(self, submob, start, alpha)
submob.make_smooth()
class ComplexHomotopy(Homotopy):
| 64 | 64 | 110 | 10 | 54 | mz71/manim | manim/animation/movement.py | Python | ComplexHomotopy | ComplexHomotopy | 35 | 45 | 35 | 35 | 3522a86e1b67aba3d67166f29cc9c350eab6a3ca | bigcode/the-stack | train |
99fc5d091c1f86ed34bfa054 | train | function | def generate(env):
add_all_to_env(env)
add_f95_to_env(env)
fcomp = env.Detect(compilers) or 'f95'
env['F95'] = fcomp
env['SHF95'] = fcomp
env['FORTRAN'] = fcomp
env['SHFORTRAN'] = fcomp
| def generate(env):
| add_all_to_env(env)
add_f95_to_env(env)
fcomp = env.Detect(compilers) or 'f95'
env['F95'] = fcomp
env['SHF95'] = fcomp
env['FORTRAN'] = fcomp
env['SHFORTRAN'] = fcomp
| 9/01/13 06:45:54 scons"
import SCons.Defaults
import SCons.Tool
import SCons.Util
import fortran
from SCons.Tool.FortranCommon import add_all_to_env, add_f95_to_env
compilers = ['f95']
def generate(env):
| 64 | 64 | 80 | 4 | 60 | rwatson/chromium-capsicum | third_party/scons/scons-local/SCons/Tool/f95.py | Python | generate | generate | 44 | 53 | 44 | 44 | cc90f1b6e0489fdbe59d608e35601b094f952c32 | bigcode/the-stack | train |
925dad062dbd85a5be10e7db | train | function | def exists(env):
return env.Detect(compilers)
| def exists(env):
| return env.Detect(compilers)
| fcomp = env.Detect(compilers) or 'f95'
env['F95'] = fcomp
env['SHF95'] = fcomp
env['FORTRAN'] = fcomp
env['SHFORTRAN'] = fcomp
def exists(env):
| 64 | 64 | 12 | 4 | 59 | rwatson/chromium-capsicum | third_party/scons/scons-local/SCons/Tool/f95.py | Python | exists | exists | 56 | 57 | 56 | 56 | 44dc07665e1a7464f7849ce29bab97cfeeb66112 | bigcode/the-stack | train |
2eab64fcb724b3bca912cad7 | train | function | def main(port):
f = open("services", "r")
lines = f.read().split("\n")
port = "\t" + port + "/"
for line in lines:
if port in line:
word = line.split("\t")[0]
return word
return "unknown"
| def main(port):
| f = open("services", "r")
lines = f.read().split("\n")
port = "\t" + port + "/"
for line in lines:
if port in line:
word = line.split("\t")[0]
return word
return "unknown"
| def main(port):
| 4 | 64 | 66 | 4 | 0 | redeye-framework/Redeye | Tools/get_service.py | Python | main | main | 2 | 10 | 2 | 2 | 60d41d5ac386e10c3986d9cb582aae7ad569b136 | bigcode/the-stack | train |
67fda2e01be86150e6acef81 | train | class | class CshMill(LineMill):
names = ["csh"]
def __init__(self):
LineMill.__init__(self, "#", "#!/bin/csh")
return
| class CshMill(LineMill):
| names = ["csh"]
def __init__(self):
LineMill.__init__(self, "#", "#!/bin/csh")
return
| California Institute of Technology
# (C) 1998-2005 All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
from pythia.pyre.weaver.components.LineMill import LineMill
class CshMill(LineMill):
| 64 | 64 | 42 | 8 | 55 | willic3/pythia | pythia/pyre/weaver/mills/CshMill.py | Python | CshMill | CshMill | 17 | 25 | 17 | 19 | bd1ad71dca4b204174218abf8aa1903ef4d501df | bigcode/the-stack | train |
07cc29baa8028d81dfffd863 | train | class | class UnionExpression(Expression, ABC):
"""Union of expressions
"""
def __init__(self, *children):
"""Init
"""
self._children = [] # type: List[Expression]
for c in children:
self.append(c)
def __len__(self) -> int:
"""__len__()
"""
... | class UnionExpression(Expression, ABC):
| """Union of expressions
"""
def __init__(self, *children):
"""Init
"""
self._children = [] # type: List[Expression]
for c in children:
self.append(c)
def __len__(self) -> int:
"""__len__()
"""
return len(self._children)
def __i... | """
self._field = field
self._arg = arg
class FieldOperatorExpression(Expression, ABC):
"""Field operator expression
"""
def __init__(self, arg: FieldExpression):
"""Init
"""
if not isinstance(arg, FieldExpression):
raise TypeError(f'Instance of {Field... | 89 | 89 | 298 | 7 | 81 | ashep/qubu | qubu/contract/_expression.py | Python | UnionExpression | UnionExpression | 71 | 128 | 71 | 71 | d2c3fa0074e17c03f19a48472e4273521bf4eead | bigcode/the-stack | train |
84e723f549be3fee9067d352 | train | class | class FieldExpression(Expression, ABC):
"""Field expression
"""
@property
def field(self) -> str:
"""Get field's name
"""
return self._field
def __init__(self, field: str, arg: Any):
"""Init
"""
self._field = field
self._arg = arg
| class FieldExpression(Expression, ABC):
| """Field expression
"""
@property
def field(self) -> str:
"""Get field's name
"""
return self._field
def __init__(self, field: str, arg: Any):
"""Init
"""
self._field = field
self._arg = arg
| # pragma: no cover
def __str__(self) -> str:
"""__str__()
"""
return str(self.compile())
def __eq__(self, other) -> bool:
"""__eq__()
"""
return self.compile() == other.compile()
class FieldExpression(Expression, ABC):
| 64 | 64 | 76 | 7 | 57 | ashep/qubu | qubu/contract/_expression.py | Python | FieldExpression | FieldExpression | 41 | 55 | 41 | 41 | e439f6f261681a0388f3ccd44262253f21058f00 | bigcode/the-stack | train |
3f5700c6605820a344a2a306 | train | class | class FieldOperatorExpression(Expression, ABC):
"""Field operator expression
"""
def __init__(self, arg: FieldExpression):
"""Init
"""
if not isinstance(arg, FieldExpression):
raise TypeError(f'Instance of {FieldExpression} expected, not ')
self._arg = arg
| class FieldOperatorExpression(Expression, ABC):
| """Field operator expression
"""
def __init__(self, arg: FieldExpression):
"""Init
"""
if not isinstance(arg, FieldExpression):
raise TypeError(f'Instance of {FieldExpression} expected, not ')
self._arg = arg
| field(self) -> str:
"""Get field's name
"""
return self._field
def __init__(self, field: str, arg: Any):
"""Init
"""
self._field = field
self._arg = arg
class FieldOperatorExpression(Expression, ABC):
| 64 | 64 | 67 | 8 | 55 | ashep/qubu | qubu/contract/_expression.py | Python | FieldOperatorExpression | FieldOperatorExpression | 58 | 68 | 58 | 58 | f64ee2d4a17ae6ae8a694640082878ea09682a6b | bigcode/the-stack | train |
d3f9d16940b0c7927ff9fa69 | train | class | class Expression(ABC):
"""Base Expression
"""
@property
@abstractmethod
def name(self) -> str:
"""Get name of the expression
"""
pass # pragma: no cover
@abstractmethod
def compile(self) -> Any:
"""Compile the expression
"""
pass # pragma... | class Expression(ABC):
| """Base Expression
"""
@property
@abstractmethod
def name(self) -> str:
"""Get name of the expression
"""
pass # pragma: no cover
@abstractmethod
def compile(self) -> Any:
"""Compile the expression
"""
pass # pragma: no cover
def __s... | petko'
__email__ = 'a@shepetko.com'
__license__ = 'MIT'
__all__ = ['Expression', 'FieldOperatorExpression', 'FieldExpression', 'UnionExpression']
from typing import Any, Iterator, List
from abc import ABC, abstractmethod
class Expression(ABC):
| 64 | 64 | 129 | 5 | 58 | ashep/qubu | qubu/contract/_expression.py | Python | Expression | Expression | 13 | 38 | 13 | 13 | 0d1ff601776171a2c84cfe19cd35900c5dbf58eb | bigcode/the-stack | train |
9b25d512e3cdcdc68f96ae7d | train | function | def main(args):
rospy.init_node('semantic_cloud', anonymous=True)
sem_cloud = SemanticCloud()
try:
rospy.spin()
except KeyboardInterrupt:
print("Semantic cloud shutting down!")
| def main(args):
| rospy.init_node('semantic_cloud', anonymous=True)
sem_cloud = SemanticCloud()
try:
rospy.spin()
except KeyboardInterrupt:
print("Semantic cloud shutting down!")
| 0],size=np.count_nonzero(error_mask))
error_mask = np.repeat(error_mask[:,:,None],repeats=3,axis=2)
np.place(semantic_img, error_mask, self.class_colors[random_classes, :])
return noisy_depth_img, semantic_img
def main(args):
| 63 | 64 | 42 | 4 | 58 | ExistentialRobotics/SSMI | S2MI-Mapping/scripts/semantic_sensor_node.py | Python | main | main | 130 | 136 | 130 | 130 | 26454bacd41acf74f5bd6974a4515274d450b352 | bigcode/the-stack | train |
d7d5d958c24e18ff390a5128 | train | class | class SemanticCloud:
"""
Class for ros node to take in a color image (bgr) and a semantic segmentation image (bgr)
Then produce point cloud based on depth information
"""
def __init__(self):
# Get point type
point_type = rospy.get_param('/semantic_pcl/point_type')
if point_ty... | class SemanticCloud:
| """
Class for ros node to take in a color image (bgr) and a semantic segmentation image (bgr)
Then produce point cloud based on depth information
"""
def __init__(self):
# Get point type
point_type = rospy.get_param('/semantic_pcl/point_type')
if point_type == 0:
... | #!/usr/bin/env python
from __future__ import division
from __future__ import print_function
import sys
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import numpy as np
from sensor_msgs.msg import PointCloud2
from semantic_sensor import PointType, SemanticPclGenerator
im... | 86 | 256 | 1,329 | 4 | 81 | ExistentialRobotics/SSMI | S2MI-Mapping/scripts/semantic_sensor_node.py | Python | SemanticCloud | SemanticCloud | 20 | 127 | 20 | 20 | 2c06b3104321658390e031fdb23517dfc864989e | bigcode/the-stack | train |
b2a0fe98699fd6de36cefac8 | train | class | class Channel:
def __init__(self, channel_id, dest_url=None,
url='https://api.thingspeak.com', read_key='', write_key=''):
self.channel_id = channel_id
self.url = url.rstrip('/')
self.read_key = read_key
self.write_key = write_key
self.dest_url = dest_url
... | class Channel:
| def __init__(self, channel_id, dest_url=None,
url='https://api.thingspeak.com', read_key='', write_key=''):
self.channel_id = channel_id
self.url = url.rstrip('/')
self.read_key = read_key
self.write_key = write_key
self.dest_url = dest_url
def get_chann... | # Gets data from the ThingSpeak API
import requests
import json
class Channel:
| 18 | 230 | 768 | 3 | 14 | raddevon/pyspeak | pyspeak/__init__.py | Python | Channel | Channel | 7 | 106 | 7 | 8 | 859dc6180e237e8d31318696eb3a0cd2622f31bd | bigcode/the-stack | train |
dcac6a53dd58ecb5c04502a2 | train | class | class MessageKind:
"""JSON-RPC Message types."""
REQUEST = 1
RESPONSE = 2
NOTIFICATION = 3
| class MessageKind:
| """JSON-RPC Message types."""
REQUEST = 1
RESPONSE = 2
NOTIFICATION = 3
| # -*- coding: utf-8 -*-
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
class MessageKind:
| 42 | 64 | 31 | 4 | 38 | Earthman100/spyder | spyder/plugins/completion/providers/languageserver/transport/__init__.py | Python | MessageKind | MessageKind | 8 | 12 | 8 | 8 | bc89f500046424699c254d14f24575cf7ddf952e | bigcode/the-stack | train |
44e1688f8b7fb35049d5105e | train | class | class JointDistributionSamplePathMixin(object):
"""Mixin endowing a JointDistribution with sample-path semantics.
This class provides alternate vectorization semantics for
`tfd.JointDistribution`, which in many cases eliminate the need to
explicitly account for batch shapes in the model specification.
Instea... | class JointDistributionSamplePathMixin(object):
| """Mixin endowing a JointDistribution with sample-path semantics.
This class provides alternate vectorization semantics for
`tfd.JointDistribution`, which in many cases eliminate the need to
explicitly account for batch shapes in the model specification.
Instead of simply summing the `log_prob`s of component... | in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either... | 256 | 256 | 1,995 | 8 | 248 | PavanKishore21/probability | tensorflow_probability/python/distributions/joint_distribution_sample_path_mixin.py | Python | JointDistributionSamplePathMixin | JointDistributionSamplePathMixin | 37 | 243 | 37 | 37 | ad06d760cccf90e27256228790116e5d8e409dee | bigcode/the-stack | train |
6339ca79b52510e141a43373 | train | function | def _get_reduction_axes(x, nd):
"""Enumerates the final `nd` axis indices of `x`."""
x_rank = prefer_static.rank_from_shape(prefer_static.shape(x))
return prefer_static.range(x_rank - 1, x_rank - nd -1, -1)
| def _get_reduction_axes(x, nd):
| """Enumerates the final `nd` axis indices of `x`."""
x_rank = prefer_static.rank_from_shape(prefer_static.shape(x))
return prefer_static.range(x_rank - 1, x_rank - nd -1, -1)
|
import functools
import tensorflow.compat.v2 as tf
from tensorflow_probability.python import math as tfp_math
from tensorflow_probability.python.distributions import joint_distribution as jd_lib
from tensorflow_probability.python.internal import assert_util
from tensorflow_probability.python.internal import prefer_... | 64 | 64 | 62 | 10 | 53 | PavanKishore21/probability | tensorflow_probability/python/distributions/joint_distribution_sample_path_mixin.py | Python | _get_reduction_axes | _get_reduction_axes | 31 | 34 | 31 | 31 | 002f333894adbfd8dd6dda9d9c13fbfdeea3d715 | bigcode/the-stack | train |
1b2ac5d524e55fccef24d6fc | train | class | class MyController(Resource):
def get(self):
return {'message': 'Hello World!'} | class MyController(Resource):
| def get(self):
return {'message': 'Hello World!'} | from flask_restful import Resource
class MyController(Resource):
| 12 | 64 | 20 | 5 | 6 | perogeremmer/latihan-flask | part_2-mvc_structures/app/controllers/MyController.py | Python | MyController | MyController | 3 | 5 | 3 | 3 | 9e1aa72df817c14a14439d4746996126b0228038 | bigcode/the-stack | train |
f596593703e309f23342a958 | train | class | class SecondaryAmino(GenericFunctionalGroup):
"""
Represents a secondary amino functional group.
The structure of the functional group is given by the pseudo-SMILES
``[atom1][nitrogen]([hydrogen])[atom2]``.
"""
def __init__(
self,
nitrogen,
hydrogen,
atom1,
... | class SecondaryAmino(GenericFunctionalGroup):
| """
Represents a secondary amino functional group.
The structure of the functional group is given by the pseudo-SMILES
``[atom1][nitrogen]([hydrogen])[atom2]``.
"""
def __init__(
self,
nitrogen,
hydrogen,
atom1,
atom2,
bonders,
deleters,... | """
Secondary Amino
===============
"""
from .generic_functional_group import GenericFunctionalGroup
class SecondaryAmino(GenericFunctionalGroup):
| 27 | 244 | 816 | 8 | 18 | stevenbennett96/stk | src/stk/molecular/functional_groups/functional_groups/secondary_amino.py | Python | SecondaryAmino | SecondaryAmino | 10 | 154 | 10 | 10 | 97e3e9ed3572a1cf10179a5e7c15d8200cbdae48 | bigcode/the-stack | train |
1c6d386d8bd62b4860f9b49a | train | function | def test_essential_imports():
import wx
import numpy
import scipy
import matplotlib
#import pygame # soft dependency only
import pyglet
import OpenGL
import openpyxl
import pandas
| def test_essential_imports():
| import wx
import numpy
import scipy
import matplotlib
#import pygame # soft dependency only
import pyglet
import OpenGL
import openpyxl
import pandas
| import sys
import pytest
def test_essential_imports():
| 13 | 64 | 53 | 7 | 5 | mintzer/pupillometry-rf-back | venv/Lib/site-packages/psychopy/tests/test_Installation.py | Python | test_essential_imports | test_essential_imports | 4 | 13 | 4 | 4 | 592dd84c68686398271797b0220f084d1a6f7057 | bigcode/the-stack | train |
2bc1f71cd424d42f3964a03f | train | function | def test_extra_imports():
# only Jon needs to run this, so test first if you are him!
import os
if sys.platform=='win32':
import win32api
user=win32api.GetUserName()
else:
import pwd
user = pwd.getpwuid(os.getuid()).pw_name
if user not in ['jwp','lpzjwp']:
pyt... | def test_extra_imports():
# only Jon needs to run this, so test first if you are him!
| import os
if sys.platform=='win32':
import win32api
user=win32api.GetUserName()
else:
import pwd
user = pwd.getpwuid(os.getuid()).pw_name
if user not in ['jwp','lpzjwp']:
pytest.skip('Testing extra imports is only needed for building Standalone distributions')
... |
import pytest
def test_essential_imports():
import wx
import numpy
import scipy
import matplotlib
#import pygame # soft dependency only
import pyglet
import OpenGL
import openpyxl
import pandas
def test_extra_imports():
# only Jon needs to run this, so test first if you are hi... | 80 | 80 | 267 | 23 | 56 | mintzer/pupillometry-rf-back | venv/Lib/site-packages/psychopy/tests/test_Installation.py | Python | test_extra_imports | test_extra_imports | 15 | 48 | 15 | 16 | ff07d1eff652eaef9e21df42adc5ce60573f4a48 | bigcode/the-stack | train |
4da224248818304fe430ef81 | train | function | def _run_benchmark(func, num_iters, execution_mode=None):
with context.execution_mode(execution_mode):
# call func to warm up
func()
if execution_mode == context.ASYNC:
get_executor().wait()
start = time.time()
for _ in range(num_iters):
func()
if execution_mode == context.ASYNC:
... | def _run_benchmark(func, num_iters, execution_mode=None):
| with context.execution_mode(execution_mode):
# call func to warm up
func()
if execution_mode == context.ASYNC:
get_executor().wait()
start = time.time()
for _ in range(num_iters):
func()
if execution_mode == context.ASYNC:
get_executor().wait()
end = time.time()
retu... | division
from __future__ import print_function
import tensorflow.compat.v2 as tf
import time
import six
from tensorflow.python.eager import context
from tensorflow.python.eager.context import get_executor
from keras.utils import tf_inspect
def _run_benchmark(func, num_iters, execution_mode=None):
| 64 | 64 | 93 | 14 | 49 | shantanusharma/keras | keras/benchmarks/eager_microbenchmarks_test.py | Python | _run_benchmark | _run_benchmark | 30 | 43 | 30 | 30 | fad960bd7ad4d1f99327e03c38bef1e005e4ede5 | bigcode/the-stack | train |
93127c364c4d41931d5026a3 | train | class | class MicroBenchmarksBase(tf.test.Benchmark):
"""Run and report benchmark results."""
def run_report(self, run_benchmark, func, num_iters, execution_mode=None):
"""Run and report benchmark results."""
total_time = run_benchmark(func, num_iters, execution_mode)
mean_us = total_time * 1e6 / num_iters
... | class MicroBenchmarksBase(tf.test.Benchmark):
| """Run and report benchmark results."""
def run_report(self, run_benchmark, func, num_iters, execution_mode=None):
"""Run and report benchmark results."""
total_time = run_benchmark(func, num_iters, execution_mode)
mean_us = total_time * 1e6 / num_iters
metrics = [{
"name": "exp_per_sec",
... | 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.
# ==============================================================================
"""Microbenchmar... | 224 | 224 | 748 | 10 | 213 | shantanusharma/keras | keras/benchmarks/eager_microbenchmarks_test.py | Python | MicroBenchmarksBase | MicroBenchmarksBase | 46 | 146 | 46 | 46 | aaf90da59ebfd0313c9aff9009e10ed390c532a6 | bigcode/the-stack | train |
01eec0746076c8d12918a562 | train | class | class KerasLayerCallOverheadBenchmarks(
six.with_metaclass(tf.__internal__.test.ParameterizedBenchmark, MicroBenchmarksBase)):
# The set of layers for benchmarking. To add benchmarks for new layers,
# please add the parameter configs to "_benchmark_paramters".
# The parameter of each layer benchmark is a tu... | class KerasLayerCallOverheadBenchmarks(
six.with_metaclass(tf.__internal__.test.ParameterizedBenchmark, MicroBenchmarksBase)):
# The set of layers for benchmarking. To add benchmarks for new layers,
# please add the parameter configs to "_benchmark_paramters".
# The parameter of each layer benchmark is a tu... | _benchmark_parameters = [
("advanced_activations_leaky_relu", tf.keras.layers.LeakyReLU(),
(1, 1)),
("advanced_activations_prelu", tf.keras.layers.PReLU(), (1, 1)),
("advanced_activations_elu", tf.keras.layers.ELU(), (1, 1)),
("advanced_activations_thresholded_relu",
tf.keras.lay... | )
def benchmark_layers_embeddings_embedding_overhead(self):
layer = tf.keras.layers.Embedding(1, 1)
x = tf.zeros((1, 1), dtype="int32")
def fn():
layer(x)
self._run(fn, 10000)
class KerasLayerCallOverheadBenchmarks(
six.with_metaclass(tf.__internal__.test.ParameterizedBenchmark, MicroBen... | 223 | 223 | 744 | 164 | 59 | shantanusharma/keras | keras/benchmarks/eager_microbenchmarks_test.py | Python | KerasLayerCallOverheadBenchmarks | KerasLayerCallOverheadBenchmarks | 149 | 204 | 149 | 161 | a1407564c0f719d995e8762ce484922d128fec5c | bigcode/the-stack | train |
5d7cb633624dda5033d96c99 | train | class | class YOLOXHead(nn.Module):
def __init__(
self,
num_classes,
width=1.0,
strides=[8, 16, 32],
in_channels=[256, 512, 1024],
act="silu",
depthwise=False,
):
"""
Args:
act (str): activation type of conv. Defalut value: "silu".
... | class YOLOXHead(nn.Module):
| def __init__(
self,
num_classes,
width=1.0,
strides=[8, 16, 32],
in_channels=[256, 512, 1024],
act="silu",
depthwise=False,
):
"""
Args:
act (str): activation type of conv. Defalut value: "silu".
depthwise (bool): wh... | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
import math
import numpy as np
from loguru import logger
import torch
import torch as T
import torch.nn as nn
import torch.nn.functional as F
from mmdet.utils import bboxes_iou, bboxes_iou_batch
from mmdet.model... | 122 | 256 | 10,968 | 8 | 113 | jie311/miemiedetection | mmdet/models/heads/yolox_head_fast.py | Python | YOLOXHead | YOLOXHead | 20 | 751 | 20 | 20 | fd6be22156489a1aaf61a616de4d71cd96217414 | bigcode/the-stack | train |
246fc86949b9c582aab7f151 | train | class | class ShelveComputeManagerTestCase(test_compute.BaseTestCase):
def _shelve_instance(self, shelved_offload_time, clean_shutdown=True):
CONF.set_override('shelved_offload_time', shelved_offload_time)
host = 'fake-mini'
instance = self._create_fake_instance_obj(params={'host': host})
im... | class ShelveComputeManagerTestCase(test_compute.BaseTestCase):
| def _shelve_instance(self, shelved_offload_time, clean_shutdown=True):
CONF.set_override('shelved_offload_time', shelved_offload_time)
host = 'fake-mini'
instance = self._create_fake_instance_obj(params={'host': host})
image_id = 'fake_image_id'
host = 'fake-mini'
sel... | 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.
import mock
from mox3 import mox
from oslo_config import cfg
from oslo_utils import fixture as ... | 256 | 256 | 3,836 | 13 | 242 | bopopescu/nova-19 | nova/tests/unit/compute/test_shelve.py | Python | ShelveComputeManagerTestCase | ShelveComputeManagerTestCase | 45 | 448 | 45 | 45 | b5b41cdf0adbb60747ede1e8f847740274ebf73c | bigcode/the-stack | train |
5cb893deb3a6ef8dcf31695c | train | class | class ShelveComputeAPITestCase(test_compute.BaseTestCase):
def test_shelve(self):
# Ensure instance can be shelved.
fake_instance = self._create_fake_instance_obj(
{'display_name': 'vm01'})
instance = fake_instance
self.assertIsNone(instance['task_state'])
def f... | class ShelveComputeAPITestCase(test_compute.BaseTestCase):
| def test_shelve(self):
# Ensure instance can be shelved.
fake_instance = self._create_fake_instance_obj(
{'display_name': 'vm01'})
instance = fake_instance
self.assertIsNone(instance['task_state'])
def fake_init(self2):
# In original _FakeImageServic... | True
instance = self._create_fake_instance_obj()
instance.task_state = None
instance.vm_state = vm_states.SHELVED
instance.host = self.compute.host
instance.system_metadata = {'shelved_at': ''}
instance.save()
def fake_parse_hook(timestring):
instanc... | 142 | 142 | 474 | 13 | 129 | bopopescu/nova-19 | nova/tests/unit/compute/test_shelve.py | Python | ShelveComputeAPITestCase | ShelveComputeAPITestCase | 451 | 505 | 451 | 451 | 748232199f7ae365b58e82f8ad9cda96bb42d387 | bigcode/the-stack | train |
bb307a553eb2b7a609ca5efe | train | function | def _fake_resources():
resources = {
'memory_mb': 2048,
'memory_mb_used': 0,
'free_ram_mb': 2048,
'local_gb': 20,
'local_gb_used': 0,
'free_disk_gb': 20,
'vcpus': 2,
'vcpus_used': 0
}
return resources
| def _fake_resources():
| resources = {
'memory_mb': 2048,
'memory_mb_used': 0,
'free_ram_mb': 2048,
'local_gb': 20,
'local_gb_used': 0,
'free_disk_gb': 20,
'vcpus': 2,
'vcpus_used': 0
}
return resources
| from nova.compute import vm_states
from nova import db
from nova import objects
from nova.tests.unit.compute import test_compute
from nova.tests.unit.image import fake as fake_image
CONF = cfg.CONF
CONF.import_opt('shelved_offload_time', 'nova.compute.manager')
def _fake_resources():
| 64 | 64 | 91 | 5 | 59 | bopopescu/nova-19 | nova/tests/unit/compute/test_shelve.py | Python | _fake_resources | _fake_resources | 31 | 42 | 31 | 31 | 3a54f8f58bb185b6adbd9f6a9606d6b7d6230574 | bigcode/the-stack | train |
939c677a2b758f4b931498f1 | train | function | def get_terms(desc, geneset, assoc, obo_dag, log):
"""Get the terms in the study group
"""
term2itemids = defaultdict(set)
genes = [g for g in geneset if g in assoc]
for gene in genes:
for x in assoc[gene]:
if x in obo_dag:
term2itemids[obo_dag[x].id].add(gene)
... | def get_terms(desc, geneset, assoc, obo_dag, log):
| """Get the terms in the study group
"""
term2itemids = defaultdict(set)
genes = [g for g in geneset if g in assoc]
for gene in genes:
for x in assoc[gene]:
if x in obo_dag:
term2itemids[obo_dag[x].id].add(gene)
log.write("{N:>6,} out of {M:>6,} {DESC} items fo... | for g in geneset if g in assoc):
for x in assoc[gene]:
if x in obo_dag:
term_cnt[obo_dag[x].id] += 1
return term_cnt
def get_terms(desc, geneset, assoc, obo_dag, log):
| 64 | 64 | 146 | 17 | 46 | ezequieljsosa/goatools | goatools/ratio.py | Python | get_terms | get_terms | 21 | 32 | 21 | 21 | a15e8ce7e40c4cce0b7b129b2b7f9bd1bdadf988 | bigcode/the-stack | train |
9bd0145dee8f3d83b9e2ec5f | train | function | def count_terms(geneset, assoc, obo_dag):
"""count the number of terms in the study group
"""
term_cnt = Counter()
for gene in (g for g in geneset if g in assoc):
for x in assoc[gene]:
if x in obo_dag:
term_cnt[obo_dag[x].id] += 1
return term_cnt
| def count_terms(geneset, assoc, obo_dag):
| """count the number of terms in the study group
"""
term_cnt = Counter()
for gene in (g for g in geneset if g in assoc):
for x in assoc[gene]:
if x in obo_dag:
term_cnt[obo_dag[x].id] += 1
return term_cnt
| python
# -*- coding: UTF-8 -*-
__copyright__ = "Copyright (C) 2010-2016, H Tang et al., All rights reserved."
__author__ = "various"
from collections import defaultdict, Counter
def count_terms(geneset, assoc, obo_dag):
| 64 | 64 | 87 | 14 | 49 | ezequieljsosa/goatools | goatools/ratio.py | Python | count_terms | count_terms | 10 | 19 | 10 | 10 | e620545b0c7738a62437123a775934d121f465e0 | bigcode/the-stack | train |
0c888ba2589e0cea7c949e15 | train | function | def is_ratio_different(min_ratio, study_go, study_n, pop_go, pop_n):
"""
check if the ratio go /n is different between the study group and
the population
"""
if min_ratio is None:
return True
s = float(study_go) / study_n
p = float(pop_go) / pop_n
if s > p:
return s / p >... | def is_ratio_different(min_ratio, study_go, study_n, pop_go, pop_n):
| """
check if the ratio go /n is different between the study group and
the population
"""
if min_ratio is None:
return True
s = float(study_go) / study_n
p = float(pop_go) / pop_n
if s > p:
return s / p > min_ratio
return p / s > min_ratio
| } out of {M:>6,} {DESC} items found in association\n".format(
DESC=desc, N=len(genes), M=len(geneset)))
return term2itemids
def is_ratio_different(min_ratio, study_go, study_n, pop_go, pop_n):
| 64 | 64 | 102 | 20 | 43 | ezequieljsosa/goatools | goatools/ratio.py | Python | is_ratio_different | is_ratio_different | 34 | 45 | 34 | 34 | da014502e4b762a778431046df0b6a65aea33a36 | bigcode/the-stack | train |
5a2c408483fd27a1310bc205 | train | class | class MyTimestampAssigner(TimestampAssigner):
def extract_timestamp(self, value, record_timestamp) -> int:
return int(value[1])
| class MyTimestampAssigner(TimestampAssigner):
| def extract_timestamp(self, value, record_timestamp) -> int:
return int(value[1])
| Types, WatermarkStrategy, Time, Encoder
from pyflink.common.watermark_strategy import TimestampAssigner
from pyflink.datastream import StreamExecutionEnvironment, ProcessWindowFunction
from pyflink.datastream.window import SlidingEventTimeWindows, TimeWindow
class MyTimestampAssigner(TimestampAssigner):
| 64 | 64 | 31 | 10 | 53 | huyuanfeng2018/flink | flink-python/pyflink/examples/datastream/windowing/sliding_time_window.py | Python | MyTimestampAssigner | MyTimestampAssigner | 31 | 33 | 31 | 31 | 662f4469d7e26f048f9cd5c96f90847c7e3d88f8 | bigcode/the-stack | train |
e07c5e4e45e29e221ffb4545 | train | class | class CountWindowProcessFunction(ProcessWindowFunction[tuple, tuple, str, TimeWindow]):
def process(self,
key: str,
context: ProcessWindowFunction.Context[TimeWindow],
elements: Iterable[tuple]) -> Iterable[tuple]:
return [(key, context.window().start, context... | class CountWindowProcessFunction(ProcessWindowFunction[tuple, tuple, str, TimeWindow]):
| def process(self,
key: str,
context: ProcessWindowFunction.Context[TimeWindow],
elements: Iterable[tuple]) -> Iterable[tuple]:
return [(key, context.window().start, context.window().end, len([e for e in elements]))]
def clear(self, context: ProcessWindowF... | pyflink.datastream.window import SlidingEventTimeWindows, TimeWindow
class MyTimestampAssigner(TimestampAssigner):
def extract_timestamp(self, value, record_timestamp) -> int:
return int(value[1])
class CountWindowProcessFunction(ProcessWindowFunction[tuple, tuple, str, TimeWindow]):
| 64 | 64 | 93 | 18 | 46 | huyuanfeng2018/flink | flink-python/pyflink/examples/datastream/windowing/sliding_time_window.py | Python | CountWindowProcessFunction | CountWindowProcessFunction | 36 | 44 | 36 | 36 | 814c8eb17f5994387310c3ce4ee12e1ed8a47f60 | bigcode/the-stack | train |
ca3b41ce658b607a5630bd37 | train | class | class Dataset(object):
def __init__(self, entry=SWORD_BOOTSTRAP, dataverse=None, edit_uri=None,
edit_media_uri=None, statement_uri=None, **kwargs):
"""
Datasets must have a title, description, and author.
This can be specified in the atom entry or as kwargs
"""
... | class Dataset(object):
| def __init__(self, entry=SWORD_BOOTSTRAP, dataverse=None, edit_uri=None,
edit_media_uri=None, statement_uri=None, **kwargs):
"""
Datasets must have a title, description, and author.
This can be specified in the atom entry or as kwargs
"""
self.dataverse = dat... | import os
import StringIO
from zipfile import ZipFile
from lxml import etree
import requests
from exceptions import (
NoContainerError, OperationFailedError,
ConnectionError, MetadataNotFoundError, VersionJsonNotFoundError
)
from file import DataverseFile
from settings import SWORD_BOOTSTRAP
from utils import... | 86 | 256 | 2,092 | 4 | 81 | rliebz/dataverse-client-python | dataverse/dataset.py | Python | Dataset | Dataset | 17 | 315 | 17 | 17 | aa3b58258dcfd99c764677c20b48c3bdd8142de9 | bigcode/the-stack | train |
0adf4c205f4e9331b453d823 | train | class | class bitpanda(Exchange):
def describe(self):
return self.deep_extend(super(bitpanda, self).describe(), {
'id': 'bitpanda',
'name': 'Bitpanda Pro',
'countries': ['AT'], # Austria
'rateLimit': 300,
'version': 'v1',
# new metainfo inter... | class bitpanda(Exchange):
| def describe(self):
return self.deep_extend(super(bitpanda, self).describe(), {
'id': 'bitpanda',
'name': 'Bitpanda Pro',
'countries': ['AT'], # Austria
'rateLimit': 300,
'version': 'v1',
# new metainfo interface
'has': {
... | # -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import Authenticatio... | 174 | 256 | 17,895 | 7 | 166 | myhlcb/ccxt | python/ccxt/async_support/bitpanda.py | Python | bitpanda | bitpanda | 20 | 1,668 | 20 | 21 | 167ac6f011332a7524043e75140bcfecb58df6f1 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.