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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2d3d8d36ef6553b1de9a8544 | train | function | def getData(file):
text = codecs.open(file, "r", "utf-8").read()
text = re.sub(r"/\*[\S\s]*?\*/", "", text)
text = re.sub(r"//[^\t\n]*", "", text)
enumDefs = enumP.findall(text)
for enumDef in enumDefs:
#print(enumStrs)
enumStrs = enumItem.findall(enumDef)
for enumStr in enu... | def getData(file):
| text = codecs.open(file, "r", "utf-8").read()
text = re.sub(r"/\*[\S\s]*?\*/", "", text)
text = re.sub(r"//[^\t\n]*", "", text)
enumDefs = enumP.findall(text)
for enumDef in enumDefs:
#print(enumStrs)
enumStrs = enumItem.findall(enumDef)
for enumStr in enumStrs:
... | )
for func in funcs:
funcName = func[0]
args = re.sub(r",[\n\r\s]+", ",", func[1])
args = re.sub(r"\s+", "_", args)
signature = funcName + ":" + args
table[signature] = {}
table[signature]["funcName"] = funcName
table[signature]["args"] = args
def getData(file... | 91 | 91 | 305 | 5 | 85 | 06wj/lf2 | src/res/build.py | Python | getData | getData | 137 | 171 | 137 | 137 | 192eba2628e3c043f283ff027784690d8385b0d4 | bigcode/the-stack | train |
62490da29054e25582cb9f66 | train | function | def cleanDir( Dir ):
print("cleanDir:", Dir)
if os.path.isdir( Dir ):
paths = os.listdir( Dir )
for path in paths:
filePath = os.path.join( Dir, path )
if os.path.isfile( filePath ):
try:
os.remove( filePath )
except os.... | def cleanDir( Dir ):
| print("cleanDir:", Dir)
if os.path.isdir( Dir ):
paths = os.listdir( Dir )
for path in paths:
filePath = os.path.join( Dir, path )
if os.path.isfile( filePath ):
try:
os.remove( filePath )
except os.error:
... | )[\s]+([\w]+)[\s\\t]')
frames = frameP.findall(template)
for frame in frames:
print("----------frame------------")
props = framePropP.findall(frame)
for prop in props:
print("---prop---")
print(prop)
def cleanDir( Dir ):
| 64 | 64 | 122 | 6 | 58 | 06wj/lf2 | src/res/build.py | Python | cleanDir | cleanDir | 29 | 43 | 29 | 29 | 8857674c95d342094513b002388c137a7acae602 | bigcode/the-stack | train |
6ba4a5eb7d664997bce2b57a | train | function | def saveFuncSignature(table, funcStr, reg):
funcs = reg.findall(funcStr)
for func in funcs:
funcName = func[0]
args = re.sub(r",[\n\r\s]+", ",", func[1])
args = re.sub(r"\s+", "_", args)
signature = funcName + ":" + args
table[signature] = {}
table[signature]["fun... | def saveFuncSignature(table, funcStr, reg):
| funcs = reg.findall(funcStr)
for func in funcs:
funcName = func[0]
args = re.sub(r",[\n\r\s]+", ",", func[1])
args = re.sub(r"\s+", "_", args)
signature = funcName + ":" + args
table[signature] = {}
table[signature]["funcName"] = funcName
table[signature][... | Val)
tpl = tpl.replace("%argHint", argHint)
return tpl
def getSuperKlass(str):
if str == "":
return []
else:
return re.sub(r"\s*public\s*", "", str).split(",")
def saveFuncSignature(table, funcStr, reg):
| 64 | 64 | 104 | 11 | 53 | 06wj/lf2 | src/res/build.py | Python | saveFuncSignature | saveFuncSignature | 126 | 135 | 126 | 126 | d92a4fc790578c0dc6b445a917df069ba5f2a432 | bigcode/the-stack | train |
3fba0eba418848c722f82c1b | train | function | def outputFunAPI(tree):
contentStr = ""
for klass in tree:
contentStr = contentStr + outputKclass(klass,tree[klass])
contentStr = contentStr + "\n"
if len(contentStr) > 3:
contentStr = contentStr[:-3]
tpl = templateCompletion
tpl = tpl.replace("%content",contentStr)
ff = ... | def outputFunAPI(tree):
| contentStr = ""
for klass in tree:
contentStr = contentStr + outputKclass(klass,tree[klass])
contentStr = contentStr + "\n"
if len(contentStr) > 3:
contentStr = contentStr[:-3]
tpl = templateCompletion
tpl = tpl.replace("%content",contentStr)
ff = codecs.open(os.path.join... | contentStr = contentStr[:-2]
tpl = tpl.replace("%content",contentStr)
ff = codecs.open(os.path.join(snippetsDir, "enum.sublime-completions"), "w", "utf-8")
ff.write(tpl)
ff.close()
def outputFunAPI(tree):
| 64 | 64 | 120 | 6 | 58 | 06wj/lf2 | src/res/build.py | Python | outputFunAPI | outputFunAPI | 69 | 80 | 69 | 69 | daa06f8cc7fc38401eee20abd157018e3c4ff828 | bigcode/the-stack | train |
f01726e5e61256dc4195e0f3 | train | function | def outDict():
tpl = templateCompletion
contentStr = ""
for str in dictStr:
contentStr = contentStr + '\t\t"' + str + '"' + ",\n"
if len(contentStr) > 2:
contentStr = contentStr[:-2]
tpl = tpl.replace("%content",contentStr)
ff = codecs.open(os.path.join(snippetsDir, "enum.sublime... | def outDict():
| tpl = templateCompletion
contentStr = ""
for str in dictStr:
contentStr = contentStr + '\t\t"' + str + '"' + ",\n"
if len(contentStr) > 2:
contentStr = contentStr[:-2]
tpl = tpl.replace("%content",contentStr)
ff = codecs.open(os.path.join(snippetsDir, "enum.sublime-completions"),... | )
# typedef enum {}typename;
enumP = re.compile('\s*enum[\s\S]*?{([\s\S]*?)}', re.S)
enumItem = re.compile('\s+([_a-zA-Z][_a-zA-Z0-9]*)', re.S)
def outDict():
| 64 | 64 | 111 | 4 | 60 | 06wj/lf2 | src/res/build.py | Python | outDict | outDict | 57 | 67 | 57 | 57 | 03fdda1ef679838e50e7b8349fe2d973c0044d8f | bigcode/the-stack | train |
88e7621ff765c9eff4df0a77 | train | function | def outputKclass(className, classData):
contentStr = ""
for sign in classData["func"]:
funcData = classData["func"][sign]
str = outPut(className, funcData["funcName"], funcData["args"], False)
contentStr = contentStr + '\t\t' + str + ",\n"
if "static_func" in classData:
for ... | def outputKclass(className, classData):
| contentStr = ""
for sign in classData["func"]:
funcData = classData["func"][sign]
str = outPut(className, funcData["funcName"], funcData["args"], False)
contentStr = contentStr + '\t\t' + str + ",\n"
if "static_func" in classData:
for sign in classData["static_func"]:
... | Completion
tpl = tpl.replace("%content",contentStr)
ff = codecs.open(os.path.join(snippetsDir, "api.sublime-completions"), "w", "utf-8")
ff.write(tpl)
ff.close()
def outputKclass(className, classData):
| 62 | 64 | 152 | 10 | 52 | 06wj/lf2 | src/res/build.py | Python | outputKclass | outputKclass | 84 | 95 | 84 | 84 | 809b86b4bfab53185ef384983f3d45f925b7b61d | bigcode/the-stack | train |
213b3abcc86a556132cac548 | train | function | def outPut(klass, func, args, is_static):
#print("write:", klass,func)
tpl = templateCompletionItem
if is_static == False:
tpl = tpl.replace("%class:", "")
tpl = tpl.replace("%class", klass)
tpl = tpl.replace("%func", func)
argList = args.split(",")
argVal = ""
argHint = ""
... | def outPut(klass, func, args, is_static):
#print("write:", klass,func)
| tpl = templateCompletionItem
if is_static == False:
tpl = tpl.replace("%class:", "")
tpl = tpl.replace("%class", klass)
tpl = tpl.replace("%func", func)
argList = args.split(",")
argVal = ""
argHint = ""
i = 1
if args == "" or argList[0]=="void":
argVal = ""
e... | Put(className, funcData["funcName"], funcData["args"], True)
contentStr = contentStr + '\t\t' + str + ",\n"
return contentStr
def outPut(klass, func, args, is_static):
#print("write:", klass,func)
| 64 | 64 | 188 | 23 | 40 | 06wj/lf2 | src/res/build.py | Python | outPut | outPut | 97 | 118 | 97 | 98 | c8aa482e34cf3ba03b80b8a1a6d14a7d0cde9c5c | bigcode/the-stack | train |
1ee57253a7f68dec6c0b9f92 | train | function | def getSuperKlass(str):
if str == "":
return []
else:
return re.sub(r"\s*public\s*", "", str).split(",")
| def getSuperKlass(str):
| if str == "":
return []
else:
return re.sub(r"\s*public\s*", "", str).split(",")
| + arg + "}" + ","
argHint += arg + ","
i+=1
argVal = argVal[:-1]
tpl = tpl.replace("%args", argVal)
tpl = tpl.replace("%argHint", argHint)
return tpl
def getSuperKlass(str):
| 64 | 64 | 35 | 7 | 56 | 06wj/lf2 | src/res/build.py | Python | getSuperKlass | getSuperKlass | 120 | 124 | 120 | 120 | a64e247df958a247fa84fa0fa3eba5119988d1c4 | bigcode/the-stack | train |
a12904c7035e121cfc92aa9e | train | function | def extends(childKlassData, superKlass):
if superKlass not in data:
tree[superKlass] = {
"klass":superKlass,
"func":"",
"super":[]
}
if superKlass not in tree and len(data[superKlass]["super"]) == 0:
tree[superKlass] = data[superKlass]
if superKlas... | def extends(childKlassData, superKlass):
| if superKlass not in data:
tree[superKlass] = {
"klass":superKlass,
"func":"",
"super":[]
}
if superKlass not in tree and len(data[superKlass]["super"]) == 0:
tree[superKlass] = data[superKlass]
if superKlass in tree:
for func in tree[super... | ,funcStr,funcSP)
funcStr = funcSP.sub("",funcStr)
funcData = klassData["func"] = {}
saveFuncSignature(funcData,funcStr,funcP)
data[klassName] = klassData
def extends(childKlassData, superKlass):
| 63 | 64 | 200 | 11 | 51 | 06wj/lf2 | src/res/build.py | Python | extends | extends | 175 | 192 | 175 | 175 | fd4ccb7fee7f63daf31cd4c646fbde0a10057956 | bigcode/the-stack | train |
2e6beffa48cdc2aa8c4a5ece | train | function | def execute_bash_shell():
process = subprocess.Popen(['/bin/sh'], stdout=subprocess.PIPE)
while True:
out = process.stdout.readline()
print(out.decode('utf-8'))
| def execute_bash_shell():
| process = subprocess.Popen(['/bin/sh'], stdout=subprocess.PIPE)
while True:
out = process.stdout.readline()
print(out.decode('utf-8'))
| import subprocess
def execute_bash_shell():
| 9 | 64 | 39 | 6 | 2 | unheardof/Serpent | experimental_shell.py | Python | execute_bash_shell | execute_bash_shell | 3 | 8 | 3 | 3 | dbb05d069dc2f63b533e84027c6f2b6635dc1252 | bigcode/the-stack | train |
1668bd6704f0c4d151e96f1f | train | function | def generate_all_subset(list_, toggles, i):
if i == len(list_):
res = []
for idx in range(len(toggles)):
if toggles[idx] == 1:
res.append(list_[idx])
print(res)
else:
toggles[i] = 0
generate_all_subset(list_, toggles, i + 1)
toggles[i... | def generate_all_subset(list_, toggles, i):
| if i == len(list_):
res = []
for idx in range(len(toggles)):
if toggles[idx] == 1:
res.append(list_[idx])
print(res)
else:
toggles[i] = 0
generate_all_subset(list_, toggles, i + 1)
toggles[i] = 1
generate_all_subset(list_, tog... | def generate_all_subset(list_, toggles, i):
| 11 | 64 | 103 | 11 | 0 | fajarmuslim/competitive_programming | temp.py | Python | generate_all_subset | generate_all_subset | 1 | 14 | 1 | 1 | 4eee876bf3e877d92d5c1c0c87e5c1b3a9c31648 | bigcode/the-stack | train |
261434f528fed3961a7ff393 | train | function | def sgd(learning_rate, momentum=0., nesterov=False):
return chain(
trace(decay=momentum, nesterov=nesterov),
scale(-learning_rate))
| def sgd(learning_rate, momentum=0., nesterov=False):
| return chain(
trace(decay=momentum, nesterov=nesterov),
scale(-learning_rate))
| params`.
Returns:
Updated parameters, with same structure and shape as `params`.
"""
return tree_multimap(lambda p, u: p + u, params, updates)
### Aliases for popular optimizers. ###
def sgd(learning_rate, momentum=0., nesterov=False):
| 63 | 64 | 41 | 16 | 47 | jvmncs/jax | jax/experimental/optix.py | Python | sgd | sgd | 381 | 384 | 381 | 381 | 6b76f95c62c680d1e7b106ab48fafa192cb869df | bigcode/the-stack | train |
f4078404e112c2641dd19665 | train | function | def chain(*args):
"""Applies a list of chainable update transformations.
Given a sequence of chainable transforms, `chain` returns an `init_fn`
that constructs a `state` by concatenating the states of the individual
transforms, and returns an `update_fn` which chains the update transformations
feeding the ap... | def chain(*args):
| """Applies a list of chainable update transformations.
Given a sequence of chainable transforms, `chain` returns an `init_fn`
that constructs a `state` by concatenating the states of the individual
transforms, and returns an `update_fn` which chains the update transformations
feeding the appropriate state to... | g, n: g + variance * n, updates, noise)
return updates, AddNoiseState(count=state.count + 1, rng_key=all_keys[0])
return InitUpdate(init_fn, update_fn)
### Utilities for building and using custom optimizers. ###
def chain(*args):
| 63 | 64 | 208 | 5 | 58 | jvmncs/jax | jax/experimental/optix.py | Python | chain | chain | 330 | 357 | 330 | 330 | d920b05882eac47f3571c307645fd3f8cceb0a29 | bigcode/the-stack | train |
a52efa03e4407ab754e6eccb | train | function | def scale(step_size):
"""Scale updates by some fixed scalar `step_size`.
Args:
step_size: a scalar corresponding to a fixed scaling factor for updates.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
return ScaleState()
def update_fn(updates, state):
updates = tree_multimap(l... | def scale(step_size):
| """Scale updates by some fixed scalar `step_size`.
Args:
step_size: a scalar corresponding to a fixed scaling factor for updates.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
return ScaleState()
def update_fn(updates, state):
updates = tree_multimap(lambda g: step_size * g... | np.sqrt(v) + eps), mu_hat, nu_hat)
return updates, ScaleByAdamState(count=state.count + 1, mu=mu, nu=nu)
return InitUpdate(init_fn, update_fn)
ScaleState = collections.namedtuple("ScaleState", "")
def scale(step_size):
| 63 | 64 | 103 | 5 | 58 | jvmncs/jax | jax/experimental/optix.py | Python | scale | scale | 246 | 263 | 246 | 246 | 480df631c623fbc53b5a8c0fc451e615ebe28f66 | bigcode/the-stack | train |
020ef5e92bf23b8eee25a569 | train | function | def scale_by_rms(decay=0.9, eps=1e-8):
"""Rescale updates by the root of the exp. moving avg of the square.
References:
[Hinton](www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
Args:
decay: decay rate for the exponentially weighted average of squared grads.
eps: term added to the d... | def scale_by_rms(decay=0.9, eps=1e-8):
| """Rescale updates by the root of the exp. moving avg of the square.
References:
[Hinton](www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
Args:
decay: decay rate for the exponentially weighted average of squared grads.
eps: term added to the denominator to improve numerical stabili... | "nu")
def _update_moment(updates, moments, decay, order):
return tree_multimap(
lambda g, t: (1 - decay) * (g ** order) + decay * t, updates, moments)
def scale_by_rms(decay=0.9, eps=1e-8):
| 68 | 68 | 227 | 19 | 49 | jvmncs/jax | jax/experimental/optix.py | Python | scale_by_rms | scale_by_rms | 150 | 173 | 150 | 150 | 8e98ab3104697ce4eaeaf81746f484f92ff4f2d6 | bigcode/the-stack | train |
bf4afd1e9c060c4329e41963 | train | function | def add_noise(eta, gamma, seed):
"""Add gradient noise.
References:
[Neelakantan et al, 2014](https://arxiv.org/abs/1511.06807)
Args:
eta: base variance of the gaussian noise added to the gradient.
gamma: decay exponent for annealing of the variance.
seed: seed for random number generation.
R... | def add_noise(eta, gamma, seed):
| """Add gradient noise.
References:
[Neelakantan et al, 2014](https://arxiv.org/abs/1511.06807)
Args:
eta: base variance of the gaussian noise added to the gradient.
gamma: decay exponent for annealing of the variance.
seed: seed for random number generation.
Returns:
An (init_fn, update_f... | .zeros([], jnp.int32))
def update_fn(updates, state):
updates = tree_multimap(lambda g: step_size_fn(state.count) * g, updates)
return updates, ScaleByScheduleState(count=state.count + 1)
return InitUpdate(init_fn, update_fn)
AddNoiseState = collections.namedtuple("AddNoiseState", "count rng_key")
def a... | 89 | 89 | 297 | 10 | 79 | jvmncs/jax | jax/experimental/optix.py | Python | add_noise | add_noise | 293 | 324 | 293 | 293 | f03529678039dbf682b22455e29d7f3a7fff5916 | bigcode/the-stack | train |
920e722f230266833aa047c7 | train | function | def scale_by_adam(b1=0.9, b2=0.999, eps=1e-8):
"""Rescale updates according to the Adam algorithm.
References:
[Kingma et al, 2014](https://arxiv.org/abs/1412.6980)
Args:
b1: decay rate for the exponentially weighted average of grads.
b2: decay rate for the exponentially weighted average of squared ... | def scale_by_adam(b1=0.9, b2=0.999, eps=1e-8):
| """Rescale updates according to the Adam algorithm.
References:
[Kingma et al, 2014](https://arxiv.org/abs/1412.6980)
Args:
b1: decay rate for the exponentially weighted average of grads.
b2: decay rate for the exponentially weighted average of squared grads.
eps: term added to the denominator t... | updates = tree_multimap(
lambda g, m, n: g / jnp.sqrt(n - m**2 + eps), updates, mu, nu)
return updates, ScaleByRStdDevState(mu=mu, nu=nu)
return InitUpdate(init_fn, update_fn)
ScaleByAdamState = collections.namedtuple("ScaleByAdamState", "count mu nu")
def scale_by_adam(b1=0.9, b2=0.999, eps=1e-8):... | 107 | 107 | 357 | 26 | 81 | jvmncs/jax | jax/experimental/optix.py | Python | scale_by_adam | scale_by_adam | 211 | 240 | 211 | 211 | 2a661a7cfd30df1fe4ecea84f13a1ecc690fc2ec | bigcode/the-stack | train |
6c2f1d9edcd6ee5d5d12f17c | train | function | def global_norm(items):
return jnp.sqrt(jnp.sum([jnp.sum(x**2) for x in tree_leaves(items)]))
| def global_norm(items):
| return jnp.sqrt(jnp.sum([jnp.sum(x**2) for x in tree_leaves(items)]))
| = tree_multimap(
lambda g: jnp.clip_by_value(g, -max_delta, max_delta), updates)
return updates, state
return InitUpdate(init_fn, update_fn)
ClipByGlobalNormState = collections.namedtuple("ClipByGlobalNormState", "")
def global_norm(items):
| 63 | 64 | 30 | 5 | 58 | jvmncs/jax | jax/experimental/optix.py | Python | global_norm | global_norm | 84 | 85 | 84 | 84 | e8cd3117b962987a0f117297988cc9075cb13231 | bigcode/the-stack | train |
ee4493183c6317b1617f597e | train | function | def scale_by_stddev(decay=0.9, eps=1e-8):
"""Rescale updates by the root of the centered exp. moving average of squares.
References:
[Hinton](www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
Args:
decay: decay rate for the exponentially weighted average of squared grads.
eps: term a... | def scale_by_stddev(decay=0.9, eps=1e-8):
| """Rescale updates by the root of the centered exp. moving average of squares.
References:
[Hinton](www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
Args:
decay: decay rate for the exponentially weighted average of squared grads.
eps: term added to the denominator to improve numeric... | (lambda g, n: g / (jnp.sqrt(n + eps)), updates, nu)
return updates, ScaleByRmsState(nu=nu)
return InitUpdate(init_fn, update_fn)
ScaleByRStdDevState = collections.namedtuple("ScaleByRStdDevState", "mu nu")
def scale_by_stddev(decay=0.9, eps=1e-8):
| 84 | 84 | 280 | 19 | 65 | jvmncs/jax | jax/experimental/optix.py | Python | scale_by_stddev | scale_by_stddev | 179 | 205 | 179 | 179 | 7981906dd86004808f0e53b97b85206048d9e2ba | bigcode/the-stack | train |
9791bafb82fd724102033e27 | train | function | def rmsprop(learning_rate, decay=0.9, eps=1e-8, centered=False):
if not centered:
return chain(
scale_by_rms(decay=decay, eps=eps),
scale(-learning_rate))
else:
return chain(
scale_by_stddev(decay=decay, eps=eps),
scale(-learning_rate))
| def rmsprop(learning_rate, decay=0.9, eps=1e-8, centered=False):
| if not centered:
return chain(
scale_by_rms(decay=decay, eps=eps),
scale(-learning_rate))
else:
return chain(
scale_by_stddev(decay=decay, eps=eps),
scale(-learning_rate))
| =0.999, eps=1e-8):
return chain(
scale_by_adam(b1=b1, b2=b2, eps=eps),
scale(-learning_rate))
def rmsprop(learning_rate, decay=0.9, eps=1e-8, centered=False):
| 64 | 64 | 81 | 23 | 41 | jvmncs/jax | jax/experimental/optix.py | Python | rmsprop | rmsprop | 400 | 408 | 400 | 400 | 145c0ed175d6f9606d69e5c5f7e419ef3deb6007 | bigcode/the-stack | train |
af09e51ac81379fd7d0448cd | train | function | def scale_by_schedule(step_size_fn):
"""Scale updates using a custom schedule for the `step_size`.
Args:
step_size_fn: a function that takes an update count as input and proposes
the step_size to multiply the updates by.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
return S... | def scale_by_schedule(step_size_fn):
| """Scale updates using a custom schedule for the `step_size`.
Args:
step_size_fn: a function that takes an update count as input and proposes
the step_size to multiply the updates by.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
return ScaleByScheduleState(count=jnp.zeros([... | update_fn(updates, state):
updates = tree_multimap(lambda g: step_size * g, updates)
return updates, state
return InitUpdate(init_fn, update_fn)
ScaleByScheduleState = collections.namedtuple("ScaleByScheduleState", "count")
def scale_by_schedule(step_size_fn):
| 64 | 64 | 145 | 8 | 56 | jvmncs/jax | jax/experimental/optix.py | Python | scale_by_schedule | scale_by_schedule | 269 | 287 | 269 | 269 | 9e187f0c86282dd3691338eec64ce2463692d53b | bigcode/the-stack | train |
211dbd00c913c12672a8f85f | train | function | def trace(decay, nesterov):
"""Compute a trace of past updates.
Args:
decay: the decay rate for the tracing of past updates.
nesterov: whether to use nesterov momentum.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(params):
return TraceState(trace=tree_multimap(jnp.zeros_like, par... | def trace(decay, nesterov):
| """Compute a trace of past updates.
Args:
decay: the decay rate for the tracing of past updates.
nesterov: whether to use nesterov momentum.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(params):
return TraceState(trace=tree_multimap(jnp.zeros_like, params))
def update_fn(updat... | tree_multimap(
lambda t: jnp.where(trigger, t, t * (max_norm / g_norm)), updates)
return updates, state
return InitUpdate(init_fn, update_fn)
TraceState = collections.namedtuple("TraceState", "trace")
def trace(decay, nesterov):
| 64 | 64 | 166 | 9 | 55 | jvmncs/jax | jax/experimental/optix.py | Python | trace | trace | 118 | 139 | 118 | 118 | fe548a275b2da29f3cc49daa3345469e723bdac6 | bigcode/the-stack | train |
b88aa55864cb013e7da5edf0 | train | function | def noisy_sgd(learning_rate, eta=0.01, gamma=0.55, seed=42):
return chain(
trace(decay=0., nesterov=False),
scale(-learning_rate),
add_noise(eta, gamma, seed))
| def noisy_sgd(learning_rate, eta=0.01, gamma=0.55, seed=42):
| return chain(
trace(decay=0., nesterov=False),
scale(-learning_rate),
add_noise(eta, gamma, seed))
| sgd(learning_rate, momentum=0., nesterov=False):
return chain(
trace(decay=momentum, nesterov=nesterov),
scale(-learning_rate))
def noisy_sgd(learning_rate, eta=0.01, gamma=0.55, seed=42):
| 64 | 64 | 56 | 24 | 40 | jvmncs/jax | jax/experimental/optix.py | Python | noisy_sgd | noisy_sgd | 387 | 391 | 387 | 387 | 6514405b70f777a78fe274626504f160727b416b | bigcode/the-stack | train |
35a55832fba3f2951720115a | train | function | def clip_by_global_norm(max_norm):
"""Clip updates using their global norm.
References:
[Pascanu et al, 2012](https://arxiv.org/abs/1211.5063)
Args:
max_norm: the maximum global norm for an update.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
return ClipByGlobalNormState()... | def clip_by_global_norm(max_norm):
| """Clip updates using their global norm.
References:
[Pascanu et al, 2012](https://arxiv.org/abs/1211.5063)
Args:
max_norm: the maximum global norm for an update.
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
return ClipByGlobalNormState()
def update_fn(updates, state):
... | ClipByGlobalNormState", "")
def global_norm(items):
return jnp.sqrt(jnp.sum([jnp.sum(x**2) for x in tree_leaves(items)]))
_global_norm = global_norm # TODO(mtthss): remove when google code updated
def clip_by_global_norm(max_norm):
| 64 | 64 | 163 | 8 | 55 | jvmncs/jax | jax/experimental/optix.py | Python | clip_by_global_norm | clip_by_global_norm | 89 | 112 | 89 | 89 | 74adf5108e1ff109d14cefe1c9800019884c1b00 | bigcode/the-stack | train |
61d5fb99d1248288ec390a13 | train | function | def apply_updates(params, updates):
"""Applies an update to the corresponding parameters.
This is an (optional) utility functions that applies an update, and returns
the updated parameters to the caller. The update itself is typically the
result of applying any number of `chainable` transformations.
Args:
... | def apply_updates(params, updates):
| """Applies an update to the corresponding parameters.
This is an (optional) utility functions that applies an update, and returns
the updated parameters to the caller. The update itself is typically the
result of applying any number of `chainable` transformations.
Args:
params: a tree of parameters.
... | , state):
new_state = []
for s, fn in zip(state, update_fns):
updates, new_s = fn(updates, s)
new_state.append(new_s)
return updates, new_state
return InitUpdate(init_fn, update_fn)
def apply_updates(params, updates):
| 64 | 64 | 137 | 7 | 57 | jvmncs/jax | jax/experimental/optix.py | Python | apply_updates | apply_updates | 360 | 375 | 360 | 360 | cc82e14df8d1e8ec8a0b3b1c21a2e58d925854e1 | bigcode/the-stack | train |
df0b634d33b5ffd1aa294e0b | train | function | def clip(max_delta):
"""Clip updates element-wise.
Args:
max_delta: the maximum size of an update, for each variable
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
return ClipState()
def update_fn(updates, state):
updates = tree_multimap(
lambda g: jnp.clip_by_value(... | def clip(max_delta):
| """Clip updates element-wise.
Args:
max_delta: the maximum size of an update, for each variable
Returns:
An (init_fn, update_fn) tuple.
"""
def init_fn(_):
return ClipState()
def update_fn(updates, state):
updates = tree_multimap(
lambda g: jnp.clip_by_value(g, -max_delta, max_de... | tree_multimap
from jax.tree_util import tree_structure
from jax.tree_util import tree_unflatten
### Composable gradient transformations. ###
InitUpdate = collections.namedtuple("InitUpdate", ("init", "update"))
ClipState = collections.namedtuple("ClipState", "")
def clip(max_delta):
| 63 | 64 | 109 | 5 | 58 | jvmncs/jax | jax/experimental/optix.py | Python | clip | clip | 60 | 78 | 60 | 60 | 34fe74fa40c18f21f70cb0d2c2439a38526ea22e | bigcode/the-stack | train |
28c3490ad9a666ff266e8376 | train | function | def _update_moment(updates, moments, decay, order):
return tree_multimap(
lambda g, t: (1 - decay) * (g ** order) + decay * t, updates, moments)
| def _update_moment(updates, moments, decay, order):
| return tree_multimap(
lambda g, t: (1 - decay) * (g ** order) + decay * t, updates, moments)
| _trace) if nesterov else update_trace)
return updates, TraceState(trace=update_trace)
return InitUpdate(init_fn, update_fn)
ScaleByRmsState = collections.namedtuple("ScaleByRmsState", "nu")
def _update_moment(updates, moments, decay, order):
| 64 | 64 | 46 | 14 | 50 | jvmncs/jax | jax/experimental/optix.py | Python | _update_moment | _update_moment | 145 | 147 | 145 | 145 | 2d30713aa6cc848ecf8f9890e0dd62e6cfe6bb77 | bigcode/the-stack | train |
a8e4ce3dc824573a639d8760 | train | function | def adam(learning_rate, b1=0.9, b2=0.999, eps=1e-8):
return chain(
scale_by_adam(b1=b1, b2=b2, eps=eps),
scale(-learning_rate))
| def adam(learning_rate, b1=0.9, b2=0.999, eps=1e-8):
| return chain(
scale_by_adam(b1=b1, b2=b2, eps=eps),
scale(-learning_rate))
| , seed=42):
return chain(
trace(decay=0., nesterov=False),
scale(-learning_rate),
add_noise(eta, gamma, seed))
def adam(learning_rate, b1=0.9, b2=0.999, eps=1e-8):
| 64 | 64 | 56 | 27 | 37 | jvmncs/jax | jax/experimental/optix.py | Python | adam | adam | 394 | 397 | 394 | 394 | 23575d227d8519bcf1059549d1ba1b5bd26f66cf | bigcode/the-stack | train |
ace160c7ac6c235b0a744ad9 | train | function | def run_one_date(date):
# load a spectrum
ds = load_dataset(date)
names = np.array([get_name(val) for val in ds.test_ID])
nobj = len(ds.test_ID)
print("%s obj" %nobj)
inds = np.arange(nobj)
m = load_model()
model_spec = get_model_spectra(ds, m)
resid = get_residuals(ds, m)
print... | def run_one_date(date):
# load a spectrum
| ds = load_dataset(date)
names = np.array([get_name(val) for val in ds.test_ID])
nobj = len(ds.test_ID)
print("%s obj" %nobj)
inds = np.arange(nobj)
m = load_model()
model_spec = get_model_spectra(ds, m)
resid = get_residuals(ds, m)
print("get data to fit")
x,y,yerr = get_data_to... | ='k')
xpts = np.linspace(min(x), max(x), 1000)
plt.plot(xpts, gaussian(xpts, popt[0], popt[1], popt[2]), c='r', lw=2)
plt.xlabel("Wavelength (Angstroms)", fontsize=16)
plt.ylabel("Normalized Flux", fontsize=16)
plt.savefig(figname)
plt.close()
def select(yerrs, amps, amp_errs, widths):
... | 212 | 213 | 711 | 12 | 200 | annayqho/the-cannon | code/lamost/li_giants/residuals.py | Python | run_one_date | run_one_date | 146 | 209 | 146 | 147 | 2827fc1d4eb5633ebc10d65972f1f38ce147ca2a | bigcode/the-stack | train |
1f951deb0b994e035b9371d7 | train | function | def load_model():
""" Load the model
Parameters
----------
direc: directory with all of the model files
Returns
-------
m: model object
"""
direc = "/home/annaho/TheCannon/code/lamost/mass_age/cn"
m = model.CannonModel(2)
m.coeffs = np.load(direc + "/coeffs.npz")['arr_... | def load_model():
| """ Load the model
Parameters
----------
direc: directory with all of the model files
Returns
-------
m: model object
"""
direc = "/home/annaho/TheCannon/code/lamost/mass_age/cn"
m = model.CannonModel(2)
m.coeffs = np.load(direc + "/coeffs.npz")['arr_0'][0:3626,:] # no... | """
model_spectra = get_model_spectra(ds, m)
resid = ds.test_flux - model_spectra
return resid
def get_model_spectra(ds, m):
m.infer_spectra(ds)
return m.model_spectra
def load_model():
| 64 | 64 | 197 | 4 | 59 | annayqho/the-cannon | code/lamost/li_giants/residuals.py | Python | load_model | load_model | 48 | 65 | 48 | 48 | 15175b9f63809439fce63d4efa7c14c2f75c2354 | bigcode/the-stack | train |
5819252d8ac9ad76908725e4 | train | function | def fit_gaussian(x, y, yerr, p0):
""" Fit a Gaussian to the data """
try:
popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True)
except RuntimeError:
return [0],[0]
return popt, pcov
| def fit_gaussian(x, y, yerr, p0):
| """ Fit a Gaussian to the data """
try:
popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True)
except RuntimeError:
return [0],[0]
return popt, pcov
| .test_flux = a['arr_0']
ds.test_ivar = a['arr_1']
ds.test_ID = np.load("%s/%s_ids.npz" %(SPEC_DIR,date))['arr_0']
return ds
def fit_gaussian(x, y, yerr, p0):
| 64 | 64 | 76 | 14 | 49 | annayqho/the-cannon | code/lamost/li_giants/residuals.py | Python | fit_gaussian | fit_gaussian | 93 | 99 | 93 | 93 | cecc064dc00687957da15b4006f7fad8ac25095d | bigcode/the-stack | train |
f6d7fcaec68b25c4b2e8d059 | train | function | def get_name(filename):
temp = filename.split('/')[-1]
return temp.split('.')[0]
| def get_name(filename):
| temp = filename.split('/')[-1]
return temp.split('.')[0]
| amps < 0, widths > 1)
keep_2 = np.logical_and(np.abs(amps) > 3*yerrs, amp_errs < 3*np.abs(amps))
keep = np.logical_and(keep_1, keep_2)
return keep
def get_name(filename):
| 64 | 64 | 21 | 5 | 58 | annayqho/the-cannon | code/lamost/li_giants/residuals.py | Python | get_name | get_name | 140 | 142 | 140 | 140 | e76fd18eddf6d875c13972b2b59ecc4ca6d47990 | bigcode/the-stack | train |
2cd5a1556fb1cb27a5f1472d | train | function | def get_residuals(ds, m):
""" Using the dataset and model object, calculate the residuals and return
Parameters
----------
ds: dataset object
m: model object
Return
------
residuals: array of residuals, spec minus model spec
"""
model_spectra = get_model_spectra(ds, m)
resid... | def get_residuals(ds, m):
| """ Using the dataset and model object, calculate the residuals and return
Parameters
----------
ds: dataset object
m: model object
Return
------
residuals: array of residuals, spec minus model spec
"""
model_spectra = get_model_spectra(ds, m)
resid = ds.test_flux - model_sp... | Cannon')
from TheCannon import model
from TheCannon import dataset
from plot_residual import plot
def gaussian(x, a, b, c):
val = a * np.exp(-(x-b)**2 / c**2)
return val
def get_residuals(ds, m):
| 64 | 64 | 95 | 9 | 54 | annayqho/the-cannon | code/lamost/li_giants/residuals.py | Python | get_residuals | get_residuals | 27 | 40 | 27 | 27 | cf306599e97c32c8df61160d96904e8a8f923394 | bigcode/the-stack | train |
0c8d4ea1e6400f0b6050ee4d | train | function | def gaussian(x, a, b, c):
val = a * np.exp(-(x-b)**2 / c**2)
return val
| def gaussian(x, a, b, c):
| val = a * np.exp(-(x-b)**2 / c**2)
return val
| import MaxNLocator
from astropy.modeling import models, fitting
import sys
sys.path.insert(0, '/home/annaho/TheCannon')
from TheCannon import model
from TheCannon import dataset
from plot_residual import plot
def gaussian(x, a, b, c):
| 64 | 64 | 31 | 10 | 53 | annayqho/the-cannon | code/lamost/li_giants/residuals.py | Python | gaussian | gaussian | 22 | 24 | 22 | 22 | de315c48323525bcf75966f7a4db605c5136e4d4 | bigcode/the-stack | train |
c2c5643cf1a578be808cb131 | train | function | def fit_li(x, y, yerr):
p0 = [-0.1, 6707, 2]
popt, pcov = fit_gaussian(
x, y, yerr, p0)
return popt, pcov
| def fit_li(x, y, yerr):
| p0 = [-0.1, 6707, 2]
popt, pcov = fit_gaussian(
x, y, yerr, p0)
return popt, pcov
| """
try:
popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True)
except RuntimeError:
return [0],[0]
return popt, pcov
def fit_li(x, y, yerr):
| 64 | 64 | 56 | 10 | 53 | annayqho/the-cannon | code/lamost/li_giants/residuals.py | Python | fit_li | fit_li | 102 | 106 | 102 | 102 | 7e79470026d15bfa8a5ffb787724a142520bcb03 | bigcode/the-stack | train |
f6f4bbf88a33b692cb3e993f | train | function | def plot_fit(popt, pcov, x, y, yerr, figname='fit.png'):
plt.errorbar(x, y, yerr=yerr, fmt='.', c='k')
xpts = np.linspace(min(x), max(x), 1000)
plt.plot(xpts, gaussian(xpts, popt[0], popt[1], popt[2]), c='r', lw=2)
plt.xlabel("Wavelength (Angstroms)", fontsize=16)
plt.ylabel("Normalized Flux", fonts... | def plot_fit(popt, pcov, x, y, yerr, figname='fit.png'):
| plt.errorbar(x, y, yerr=yerr, fmt='.', c='k')
xpts = np.linspace(min(x), max(x), 1000)
plt.plot(xpts, gaussian(xpts, popt[0], popt[1], popt[2]), c='r', lw=2)
plt.xlabel("Wavelength (Angstroms)", fontsize=16)
plt.ylabel("Normalized Flux", fontsize=16)
plt.savefig(figname)
plt.close()
| ds.wl <= 6730)
x = ds.wl[inds]
y = resid[:,inds]
yerr=err[:,inds]
return x, y, yerr
def plot_fit(popt, pcov, x, y, yerr, figname='fit.png'):
| 64 | 64 | 129 | 23 | 40 | annayqho/the-cannon | code/lamost/li_giants/residuals.py | Python | plot_fit | plot_fit | 121 | 128 | 121 | 121 | 8ff54086f034aae7f063e28b348430545e862f61 | bigcode/the-stack | train |
12d426ece56cda3fe32f291d | train | function | def load_dataset(date):
""" Load the dataset for a single date
Parameters
----------
date: the date (string) for which to load the data & dataset
Returns
-------
ds: the dataset object
"""
LAB_DIR = "/home/annaho/TheCannon/data/lamost"
WL_DIR = "/home/annaho/TheCannon/code... | def load_dataset(date):
| """ Load the dataset for a single date
Parameters
----------
date: the date (string) for which to load the data & dataset
Returns
-------
ds: the dataset object
"""
LAB_DIR = "/home/annaho/TheCannon/data/lamost"
WL_DIR = "/home/annaho/TheCannon/code/lamost/mass_age/cn"
... | ")['arr_0'][0:3626] # no cols
m.chisqs = np.load(direc + "/chisqs.npz")['arr_0'][0:3626] # no cols
m.pivots = np.load(direc + "/pivots.npz")['arr_0']
return m
def load_dataset(date):
| 80 | 80 | 267 | 5 | 74 | annayqho/the-cannon | code/lamost/li_giants/residuals.py | Python | load_dataset | load_dataset | 68 | 90 | 68 | 68 | 2ff5ef10a0ba187b0c4ef1017bca7fb78e54193f | bigcode/the-stack | train |
78b0a65a5d5460b628da055a | train | function | def get_model_spectra(ds, m):
m.infer_spectra(ds)
return m.model_spectra
| def get_model_spectra(ds, m):
| m.infer_spectra(ds)
return m.model_spectra
|
Return
------
residuals: array of residuals, spec minus model spec
"""
model_spectra = get_model_spectra(ds, m)
resid = ds.test_flux - model_spectra
return resid
def get_model_spectra(ds, m):
| 64 | 64 | 27 | 10 | 53 | annayqho/the-cannon | code/lamost/li_giants/residuals.py | Python | get_model_spectra | get_model_spectra | 43 | 45 | 43 | 43 | abc1c34d54382df67a0eeed1cca4fed05aea84b5 | bigcode/the-stack | train |
9af7dc08c5dde0ad8b0aee24 | train | function | def select(yerrs, amps, amp_errs, widths):
""" criteria for keeping an object """
keep_1 = np.logical_and(amps < 0, widths > 1)
keep_2 = np.logical_and(np.abs(amps) > 3*yerrs, amp_errs < 3*np.abs(amps))
keep = np.logical_and(keep_1, keep_2)
return keep
| def select(yerrs, amps, amp_errs, widths):
| """ criteria for keeping an object """
keep_1 = np.logical_and(amps < 0, widths > 1)
keep_2 = np.logical_and(np.abs(amps) > 3*yerrs, amp_errs < 3*np.abs(amps))
keep = np.logical_and(keep_1, keep_2)
return keep
| popt[2]), c='r', lw=2)
plt.xlabel("Wavelength (Angstroms)", fontsize=16)
plt.ylabel("Normalized Flux", fontsize=16)
plt.savefig(figname)
plt.close()
def select(yerrs, amps, amp_errs, widths):
| 63 | 64 | 89 | 13 | 50 | annayqho/the-cannon | code/lamost/li_giants/residuals.py | Python | select | select | 131 | 136 | 131 | 131 | 6a95624765dee1759c8d242ffbf27d94c7e37480 | bigcode/the-stack | train |
9676f1529aa834aa08dfcb8f | train | function | def get_data_to_fit(ds, m, resid):
scat = m.scatters
iv_tot = (ds.test_ivar/(scat**2 * ds.test_ivar + 1))
err = np.ones(iv_tot.shape)*1000
err[iv_tot > 0] = 1/iv_tot[iv_tot>0]**0.5
inds = np.logical_and(ds.wl >= 6690, ds.wl <= 6730)
x = ds.wl[inds]
y = resid[:,inds]
yerr=err[:,inds]
... | def get_data_to_fit(ds, m, resid):
| scat = m.scatters
iv_tot = (ds.test_ivar/(scat**2 * ds.test_ivar + 1))
err = np.ones(iv_tot.shape)*1000
err[iv_tot > 0] = 1/iv_tot[iv_tot>0]**0.5
inds = np.logical_and(ds.wl >= 6690, ds.wl <= 6730)
x = ds.wl[inds]
y = resid[:,inds]
yerr=err[:,inds]
return x, y, yerr
| (x, y, yerr):
p0 = [-0.1, 6707, 2]
popt, pcov = fit_gaussian(
x, y, yerr, p0)
return popt, pcov
def get_data_to_fit(ds, m, resid):
| 64 | 64 | 135 | 11 | 52 | annayqho/the-cannon | code/lamost/li_giants/residuals.py | Python | get_data_to_fit | get_data_to_fit | 109 | 118 | 109 | 109 | 31729b309b5355445d281924535ed5d1f4ccaf86 | bigcode/the-stack | train |
dbe60f0e88592288b96d6f4f | train | function | def run_all():
""" Load the data that we're using to search for Li-rich giants.
Store it in dataset and model objects. """
DATA_DIR = "/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels"
dates = os.listdir("/home/share/LAMOST/DR2/DR2_release")
dates = np.array(dates)
dates = np.delete(date... | def run_all():
| """ Load the data that we're using to search for Li-rich giants.
Store it in dataset and model objects. """
DATA_DIR = "/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels"
dates = os.listdir("/home/share/LAMOST/DR2/DR2_release")
dates = np.array(dates)
dates = np.delete(dates, np.where(dat... | _flux, ds.test_ivar, model_spec,
m.coeffs, m.scatters, m.chisqs, m.pivots,
figname="%s_%s_spec.png" %(date,name)) for ii,name in zip(inds_cands, cands)]
def run_all():
| 63 | 64 | 193 | 4 | 59 | annayqho/the-cannon | code/lamost/li_giants/residuals.py | Python | run_all | run_all | 212 | 227 | 212 | 212 | 7f167eecde679d45e0560cf9f6a827abd0d1b9c7 | bigcode/the-stack | train |
c74ec993ef8ea3a1156044b8 | train | function | def f_gold(price, n):
profit = [0] * n
max_price = price[n - 1]
for i in range(n - 2, 0, - 1):
if price[i] > max_price:
max_price = price[i]
profit[i] = max(profit[i + 1], max_price - price[i])
min_price = price[0]
for i in range(1, n):
if price[i] < min_price:
... | def f_gold(price, n):
| profit = [0] * n
max_price = price[n - 1]
for i in range(n - 2, 0, - 1):
if price[i] > max_price:
max_price = price[i]
profit[i] = max(profit[i + 1], max_price - price[i])
min_price = price[0]
for i in range(1, n):
if price[i] < min_price:
min_price = ... | # Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold(price, n):
| 53 | 64 | 150 | 7 | 46 | mxl1n/CodeGen | data/transcoder_evaluation_gfg/python/MAXIMUM_PROFIT_BY_BUYING_AND_SELLING_A_SHARE_AT_MOST_TWICE.py | Python | f_gold | f_gold | 7 | 20 | 7 | 7 | 886b530a9d5f9b3632a04f7dfc7f91fe64db09ad | bigcode/the-stack | train |
7b7ff752c64643bf03a6b7dc | train | class | class MyBenchmark(Benchmark):
def __init__(self):
Benchmark.__init__(self, -11, 11)
@classmethod
def function(cls):
def evaluate(D, sol):
val = 0.0
for i in range(D): val = val + sol[i] * sol[i]
return val
return evaluate
| class MyBenchmark(Benchmark):
| def __init__(self):
Benchmark.__init__(self, -11, 11)
@classmethod
def function(cls):
def evaluate(D, sol):
val = 0.0
for i in range(D): val = val + sol[i] * sol[i]
return val
return evaluate
| # encoding=utf8
from unittest import TestCase
import NiaPy
from NiaPy.benchmarks import Benchmark
class MyBenchmark(Benchmark):
| 32 | 64 | 75 | 6 | 25 | lucijabrezocnik/NiaPy | NiaPy/tests/test_runner.py | Python | MyBenchmark | MyBenchmark | 7 | 17 | 7 | 7 | b4dd751771d09d54a404186f27499a672f5285a5 | bigcode/the-stack | train |
885b425d64b3731f493c1a64 | train | class | class RunnerTestCase(TestCase):
def setUp(self):
self.algorithms = ['DifferentialEvolution', 'GreyWolfOptimizer', 'GeneticAlgorithm']
self.benchmarks = ['griewank', MyBenchmark()]
def test_runner_works_fine(self):
self.assertTrue(NiaPy.Runner(7, 100, 2, self.algorithms, self.benchmarks).run())
def test_runne... | class RunnerTestCase(TestCase):
| def setUp(self):
self.algorithms = ['DifferentialEvolution', 'GreyWolfOptimizer', 'GeneticAlgorithm']
self.benchmarks = ['griewank', MyBenchmark()]
def test_runner_works_fine(self):
self.assertTrue(NiaPy.Runner(7, 100, 2, self.algorithms, self.benchmarks).run())
def test_runner_bad_algorithm_thorws_fine(self... | Benchmark.__init__(self, -11, 11)
@classmethod
def function(cls):
def evaluate(D, sol):
val = 0.0
for i in range(D): val = val + sol[i] * sol[i]
return val
return evaluate
class RunnerTestCase(TestCase):
| 68 | 68 | 229 | 7 | 60 | lucijabrezocnik/NiaPy | NiaPy/tests/test_runner.py | Python | RunnerTestCase | RunnerTestCase | 19 | 34 | 19 | 19 | efbbdf629dc24ece3be15dfa9c1861b24b939475 | bigcode/the-stack | train |
10ff491d304d55d50d21386e | train | function | def save_fig(fname):
if figdir: plt.savefig(os.path.join(figdir, fname))
| def save_fig(fname):
| if figdir: plt.savefig(os.path.join(figdir, fname))
| www.ritchievink.com/blog/2019/06/10/bayesian-inference-how-we-are-able-to-chase-the-posterior/
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
figdir = "../figures"
import os
def save_fig(fname):
| 64 | 64 | 20 | 5 | 58 | always-newbie161/pyprobml | scripts/posteriorGrid2d.py | Python | save_fig | save_fig | 10 | 11 | 10 | 10 | 6b75e653644d98f40be9d368e40b7a54aad68b82 | bigcode/the-stack | train |
c48f4fea18f92a586a6c49d2 | train | function | def blueprint_schemaform_config(blueprint_template):
"""Generates config,schema and model objects used in schemaform ui component for blueprints"""
plugin = Plugin.query.filter_by(id=blueprint_template.plugin).first()
schema = plugin.schema
blueprint_schema = {'type': 'object', 'title': 'Comment', 'desc... | def blueprint_schemaform_config(blueprint_template):
| """Generates config,schema and model objects used in schemaform ui component for blueprints"""
plugin = Plugin.query.filter_by(id=blueprint_template.plugin).first()
schema = plugin.schema
blueprint_schema = {'type': 'object', 'title': 'Comment', 'description': 'Description', 'required': ['name', 'descri... | = form.is_enabled.raw_data[0] # WTForms Issue#451
else:
blueprint_template.is_enabled = False
if args.get('disable_blueprints'):
# Disable all associated blueprints
blueprints = blueprint_template.blueprints
for blueprint in blueprints:
blueprint... | 83 | 83 | 279 | 10 | 72 | CSCfi/pebbles | pebbles/views/blueprint_templates.py | Python | blueprint_schemaform_config | blueprint_schemaform_config | 160 | 195 | 160 | 160 | a80c9cea0f12d675addbfa182b564933dcec726e | bigcode/the-stack | train |
04d2025750cae410519c56a2 | train | class | class BlueprintTemplateList(restful.Resource):
@auth.login_required
@requires_group_manager_or_admin
@marshal_with(blueprint_template_fields)
def get(self):
user = g.user
query = apply_rules_blueprint_templates(user)
query = query.order_by(BlueprintTemplate.name)
results ... | class BlueprintTemplateList(restful.Resource):
@auth.login_required
@requires_group_manager_or_admin
@marshal_with(blueprint_template_fields)
| def get(self):
user = g.user
query = apply_rules_blueprint_templates(user)
query = query.order_by(BlueprintTemplate.name)
results = []
for blueprint_template in query.all():
plugin = Plugin.query.filter_by(id=blueprint_template.plugin).first()
blueprin... | ': fields.String(attribute='id'),
'name': fields.String,
'is_enabled': fields.Boolean,
'plugin': fields.String,
'config': fields.Raw,
'schema': fields.Raw,
'form': fields.Raw,
'allowed_attrs': fields.Raw,
'blueprint_schema': fields.Raw,
'blueprint_form': fields.Raw,
'blueprint_mo... | 118 | 118 | 394 | 32 | 86 | CSCfi/pebbles | pebbles/views/blueprint_templates.py | Python | BlueprintTemplateList | BlueprintTemplateList | 34 | 81 | 34 | 37 | e979745d9665eafd9dd0d3a2202a57d89dcd0fc6 | bigcode/the-stack | train |
726aaec288d4f6a6686bfa9f | train | function | def toggle_enable_template(form, args, blueprint_template):
"""Logic for activating and deactivating a blueprint template"""
if form.is_enabled.raw_data:
blueprint_template.is_enabled = form.is_enabled.raw_data[0] # WTForms Issue#451
else:
blueprint_template.is_enabled = False
if ar... | def toggle_enable_template(form, args, blueprint_template):
| """Logic for activating and deactivating a blueprint template"""
if form.is_enabled.raw_data:
blueprint_template.is_enabled = form.is_enabled.raw_data[0] # WTForms Issue#451
else:
blueprint_template.is_enabled = False
if args.get('disable_blueprints'):
# Disable all asso... | db.session.expunge(template)
make_transient(template)
template.id = uuid.uuid4().hex
template.name = format("%s - %s" % (template.name, 'Copy'))
db.session.add(template)
db.session.commit()
def toggle_enable_template(form, args, blueprint_template):
| 64 | 64 | 110 | 11 | 53 | CSCfi/pebbles | pebbles/views/blueprint_templates.py | Python | toggle_enable_template | toggle_enable_template | 146 | 157 | 146 | 146 | d119bb37cc3612efab26c81d58b3a146ab8b7c63 | bigcode/the-stack | train |
8c268c8c493cd089fa750078 | train | class | class BlueprintTemplateCopy(restful.Resource):
@auth.login_required
@requires_admin
def put(self, template_id):
template = BlueprintTemplate.query.get_or_404(template_id)
db.session.expunge(template)
make_transient(template)
template.id = uuid.uuid4().hex
template.na... | class BlueprintTemplateCopy(restful.Resource):
@auth.login_required
@requires_admin
| def put(self, template_id):
template = BlueprintTemplate.query.get_or_404(template_id)
db.session.expunge(template)
make_transient(template)
template.id = uuid.uuid4().hex
template.name = format("%s - %s" % (template.name, 'Copy'))
db.session.add(template)
db... | blueprint_schemaform_config(blueprint_template)
args = self.parser.parse_args()
blueprint_template = toggle_enable_template(form, args, blueprint_template)
db.session.add(blueprint_template)
db.session.commit()
class BlueprintTemplateCopy(restful.Resource):
@auth.login_required
... | 64 | 64 | 94 | 19 | 45 | CSCfi/pebbles | pebbles/views/blueprint_templates.py | Python | BlueprintTemplateCopy | BlueprintTemplateCopy | 132 | 143 | 132 | 134 | 48a942ec8822357e6b100db640dbf0e61288be76 | bigcode/the-stack | train |
ab9e8879d5350dc24d2ff318 | train | class | class BlueprintTemplateView(restful.Resource):
parser = reqparse.RequestParser()
parser.add_argument('disable_blueprints', type=bool)
@auth.login_required
@requires_group_manager_or_admin
@marshal_with(blueprint_template_fields)
def get(self, template_id):
args = {'template_id': templat... | class BlueprintTemplateView(restful.Resource):
| parser = reqparse.RequestParser()
parser.add_argument('disable_blueprints', type=bool)
@auth.login_required
@requires_group_manager_or_admin
@marshal_with(blueprint_template_fields)
def get(self, template_id):
args = {'template_id': template_id}
query = apply_rules_blueprint_tem... | lifetime from config
except ValueError:
timeformat_error = {"timeformat error": "pattern should be [days]d [hours]h [minutes]m"}
return timeformat_error, 422
if isinstance(form.allowed_attrs.data, dict): # WTForms can only fetch a dict
blueprint_template.allowed_at... | 114 | 114 | 380 | 8 | 106 | CSCfi/pebbles | pebbles/views/blueprint_templates.py | Python | BlueprintTemplateView | BlueprintTemplateView | 84 | 129 | 84 | 84 | c2f0ad3d6849dcdcd4df1d2a4dda34744f2b9477 | bigcode/the-stack | train |
d48d7afd80f1884e9c32befc | train | function | def validate_max_lifetime_template(config):
"""Checks if the maximum lifetime has a valid pattern"""
if 'maximum_lifetime' in config:
max_life_str = str(config['maximum_lifetime'])
if max_life_str:
parse_maximum_lifetime(max_life_str)
| def validate_max_lifetime_template(config):
| """Checks if the maximum lifetime has a valid pattern"""
if 'maximum_lifetime' in config:
max_life_str = str(config['maximum_lifetime'])
if max_life_str:
parse_maximum_lifetime(max_life_str)
| type": "textarea",
"placeholder": "Blueprint details"
}
] + blueprint_form
blueprint_template.blueprint_schema = blueprint_schema
blueprint_template.blueprint_form = blueprint_form
blueprint_template.blueprint_model = blueprint_model
return blueprint_template
def validate_max_l... | 64 | 64 | 61 | 8 | 55 | CSCfi/pebbles | pebbles/views/blueprint_templates.py | Python | validate_max_lifetime_template | validate_max_lifetime_template | 198 | 203 | 198 | 198 | 6dd7b9ec3bb3a0d9a3b1cb711428b5b9dcf6465a | bigcode/the-stack | train |
77efb5a999e63fefff4ccf80 | train | class | class FadeInFrom(Transform):
def __init__(
self, mobject: "Mobject", direction: np.ndarray = DOWN, **kwargs
) -> None:
self.direction = direction
super().__init__(mobject, **kwargs)
def create_target(self) -> "Mobject":
return self.mobject.copy()
def begin(self) -> None... | class FadeInFrom(Transform):
| def __init__(
self, mobject: "Mobject", direction: np.ndarray = DOWN, **kwargs
) -> None:
self.direction = direction
super().__init__(mobject, **kwargs)
def create_target(self) -> "Mobject":
return self.mobject.copy()
def begin(self) -> None:
super().begin()
... | _mobject(self) -> "Mobject":
start = super().create_starting_mobject()
start.fade(1)
if isinstance(start, VMobject):
start.set_stroke(opacity=0)
start.set_fill(opacity=0)
return start
class FadeInFrom(Transform):
| 64 | 64 | 105 | 7 | 56 | philschatz/manim | manim/animation/fading.py | Python | FadeInFrom | FadeInFrom | 125 | 138 | 125 | 125 | 781d39ac681ecc7748fbaf14e7cf6ea83b0bd296 | bigcode/the-stack | train |
9a666cc4a3e1e55b7cfa76a6 | train | class | class FadeIn(Transform):
def __init__(
self, vmobject: VMobject, lag_ratio: float = DEFAULT_FADE_LAG_RATIO, **kwargs
) -> None:
super().__init__(vmobject, lag_ratio=lag_ratio, **kwargs)
def create_target(self) -> "Mobject":
return self.mobject
def create_starting_mobject(self) ... | class FadeIn(Transform):
| def __init__(
self, vmobject: VMobject, lag_ratio: float = DEFAULT_FADE_LAG_RATIO, **kwargs
) -> None:
super().__init__(vmobject, lag_ratio=lag_ratio, **kwargs)
def create_target(self) -> "Mobject":
return self.mobject
def create_starting_mobject(self) -> "Mobject":
sta... | kwargs)
def create_target(self) -> "Mobject":
return self.mobject.copy().fade(1)
def clean_up_from_scene(self, scene: "Scene" = None) -> None:
super().clean_up_from_scene(scene)
self.interpolate(0)
class FadeIn(Transform):
| 64 | 64 | 136 | 6 | 58 | philschatz/manim | manim/animation/fading.py | Python | FadeIn | FadeIn | 107 | 122 | 107 | 107 | b3f292353e2446e72657ce9bb0fb958b4c11c4a6 | bigcode/the-stack | train |
d380e99e5628ab83c48c1495 | train | class | class FadeInFromPoint(FadeIn):
def __init__(
self, mobject: "Mobject", point: typing.Union["Mobject", np.ndarray], **kwargs
) -> None:
self.point = point
super().__init__(mobject, **kwargs)
def create_starting_mobject(self) -> "Mobject":
start = super().create_starting_mobje... | class FadeInFromPoint(FadeIn):
| def __init__(
self, mobject: "Mobject", point: typing.Union["Mobject", np.ndarray], **kwargs
) -> None:
self.point = point
super().__init__(mobject, **kwargs)
def create_starting_mobject(self) -> "Mobject":
start = super().create_starting_mobject()
start.scale(0)
... | , **kwargs
) -> None:
self.direction = direction
super().__init__(mobject, **kwargs)
def create_target(self) -> "Mobject":
target = super().create_target()
target.shift(self.direction)
return target
class FadeInFromPoint(FadeIn):
| 64 | 64 | 103 | 9 | 54 | philschatz/manim | manim/animation/fading.py | Python | FadeInFromPoint | FadeInFromPoint | 154 | 165 | 154 | 154 | 74a4cf52bf6437767abbcc3043df175c234c4d37 | bigcode/the-stack | train |
875521f9b1c47fbe978dc531 | train | class | class VFadeIn(Animation):
"""
VFadeIn and VFadeOut only work for VMobjects,
"""
def __init__(
self, mobject: "Mobject", suspend_mobject_updating: bool = False, **kwargs
) -> None:
super().__init__(
mobject, suspend_mobject_updating=suspend_mobject_updating, **kwargs
... | class VFadeIn(Animation):
| """
VFadeIn and VFadeOut only work for VMobjects,
"""
def __init__(
self, mobject: "Mobject", suspend_mobject_updating: bool = False, **kwargs
) -> None:
super().__init__(
mobject, suspend_mobject_updating=suspend_mobject_updating, **kwargs
)
def interpolate... | -> None:
self.scale_factor = scale_factor
super().__init__(mobject, **kwargs)
def create_starting_mobject(self) -> "Mobject":
start = super().create_starting_mobject()
start.scale(self.scale_factor)
return start
class VFadeIn(Animation):
| 64 | 64 | 177 | 6 | 57 | philschatz/manim | manim/animation/fading.py | Python | VFadeIn | VFadeIn | 179 | 199 | 179 | 179 | 6b947627b8a503d045f4c9bcfc43ee55f4d743cf | bigcode/the-stack | train |
a8f56e55a16291f5b549d5b4 | train | class | class FadeOutAndShift(FadeOut):
def __init__(
self, mobject: "Mobject", direction: np.ndarray = DOWN, **kwargs
) -> None:
self.direction = direction
super().__init__(mobject, **kwargs)
def create_target(self) -> "Mobject":
target = super().create_target()
target.shif... | class FadeOutAndShift(FadeOut):
| def __init__(
self, mobject: "Mobject", direction: np.ndarray = DOWN, **kwargs
) -> None:
self.direction = direction
super().__init__(mobject, **kwargs)
def create_target(self) -> "Mobject":
target = super().create_target()
target.shift(self.direction)
return... | , **kwargs)
def create_target(self) -> "Mobject":
return self.mobject.copy()
def begin(self) -> None:
super().begin()
self.starting_mobject.shift(self.direction)
self.starting_mobject.fade(1)
class FadeOutAndShift(FadeOut):
| 64 | 64 | 85 | 9 | 55 | philschatz/manim | manim/animation/fading.py | Python | FadeOutAndShift | FadeOutAndShift | 141 | 151 | 141 | 141 | 7404013218ae0a285e9660cb7e5efab9efc64bfe | bigcode/the-stack | train |
06786f6c763356f87a48a0fc | train | class | class VFadeInThenOut(VFadeIn):
def __init__(
self,
mobject: "Mobject",
remover: bool = True,
rate_func: typing.Callable[[float, float], float] = there_and_back,
**kwargs
):
super().__init__(mobject, remover=remover, rate_func=rate_func, **kwargs)
| class VFadeInThenOut(VFadeIn):
| def __init__(
self,
mobject: "Mobject",
remover: bool = True,
rate_func: typing.Callable[[float, float], float] = there_and_back,
**kwargs
):
super().__init__(mobject, remover=remover, rate_func=rate_func, **kwargs)
| mobject(
self, submobject: "Mobject", starting_submobject: "Mobject", alpha: float
) -> None:
super().interpolate_submobject(submobject, starting_submobject, 1 - alpha)
class VFadeInThenOut(VFadeIn):
| 64 | 64 | 80 | 10 | 54 | philschatz/manim | manim/animation/fading.py | Python | VFadeInThenOut | VFadeInThenOut | 212 | 220 | 212 | 212 | 13219c87ea641797ed0659a492020c9e87eb28b5 | bigcode/the-stack | train |
07a413f99f0102455aa8b06d | train | class | class FadeOut(Transform):
"""A transform fading out the given mobject."""
def __init__(
self,
vmobject: VMobject,
remover: bool = True,
lag_ratio: float = DEFAULT_FADE_LAG_RATIO,
**kwargs
) -> None:
super().__init__(vmobject, remover=remover, lag_ratio=lag_ra... | class FadeOut(Transform):
| """A transform fading out the given mobject."""
def __init__(
self,
vmobject: VMobject,
remover: bool = True,
lag_ratio: float = DEFAULT_FADE_LAG_RATIO,
**kwargs
) -> None:
super().__init__(vmobject, remover=remover, lag_ratio=lag_ratio, **kwargs)
def cr... | object
from ..utils.bezier import interpolate
from ..utils.rate_functions import there_and_back
if typing.TYPE_CHECKING:
from ..mobject.mobject import Mobject
from ..scene.scene import Scene
DEFAULT_FADE_LAG_RATIO: float = 0
class FadeOut(Transform):
| 64 | 64 | 139 | 6 | 57 | philschatz/manim | manim/animation/fading.py | Python | FadeOut | FadeOut | 87 | 104 | 87 | 87 | abb41dae78444a4c3881c32e8bcf0e03d994e91d | bigcode/the-stack | train |
f5971c55890900cac9aa3b2a | train | class | class FadeInFromLarge(FadeIn):
def __init__(self, mobject: "Mobject", scale_factor: float = 2, **kwargs) -> None:
self.scale_factor = scale_factor
super().__init__(mobject, **kwargs)
def create_starting_mobject(self) -> "Mobject":
start = super().create_starting_mobject()
start.... | class FadeInFromLarge(FadeIn):
| def __init__(self, mobject: "Mobject", scale_factor: float = 2, **kwargs) -> None:
self.scale_factor = scale_factor
super().__init__(mobject, **kwargs)
def create_starting_mobject(self) -> "Mobject":
start = super().create_starting_mobject()
start.scale(self.scale_factor)
... | point
super().__init__(mobject, **kwargs)
def create_starting_mobject(self) -> "Mobject":
start = super().create_starting_mobject()
start.scale(0)
start.move_to(self.point)
return start
class FadeInFromLarge(FadeIn):
| 64 | 64 | 92 | 9 | 54 | philschatz/manim | manim/animation/fading.py | Python | FadeInFromLarge | FadeInFromLarge | 168 | 176 | 168 | 168 | 7083c26be87812522f7d8528c6ec56f78b99b740 | bigcode/the-stack | train |
333f718e94d4179d8df2f6e1 | train | class | class VFadeOut(VFadeIn):
def __init__(self, mobject: "Mobject", remover: bool = True, **kwargs) -> None:
super().__init__(mobject, remover=remover, **kwargs)
def interpolate_submobject(
self, submobject: "Mobject", starting_submobject: "Mobject", alpha: float
) -> None:
super().inte... | class VFadeOut(VFadeIn):
| def __init__(self, mobject: "Mobject", remover: bool = True, **kwargs) -> None:
super().__init__(mobject, remover=remover, **kwargs)
def interpolate_submobject(
self, submobject: "Mobject", starting_submobject: "Mobject", alpha: float
) -> None:
super().interpolate_submobject(submob... | mobject.set_stroke(
opacity=interpolate(0, starting_submobject.get_stroke_opacity(), alpha)
)
submobject.set_fill(
opacity=interpolate(0, starting_submobject.get_fill_opacity(), alpha)
)
class VFadeOut(VFadeIn):
| 64 | 64 | 108 | 8 | 56 | philschatz/manim | manim/animation/fading.py | Python | VFadeOut | VFadeOut | 202 | 209 | 202 | 202 | 9455c6202f1d4d1144c917a4b1923edf39637f63 | bigcode/the-stack | train |
91e7c2aaf7c7f7fc341977fd | train | class | class PostgreSQL(DBInspector):
def __init__(self, c, include_internal=False):
def processed(q):
if not include_internal:
q = q.replace("-- SKIP_INTERNAL", "")
if c.dialect.server_version_info[0] == 10:
q = q.replace("-- PG_10", "")
else:
... | class PostgreSQL(DBInspector):
| def __init__(self, c, include_internal=False):
def processed(q):
if not include_internal:
q = q.replace("-- SKIP_INTERNAL", "")
if c.dialect.server_version_info[0] == 10:
q = q.replace("-- PG_10", "")
else:
q = q.replace("--... | = "\nusing {}".format(self.qual)
else:
qual_clause = ""
if self.withcheck:
withcheck_clause = "\nwith check {}".format(self.withcheck)
else:
withcheck_clause = ""
roleslist = ", ".join(self.roles)
return RLS_POLICY_CREATE.format(
... | 256 | 256 | 2,867 | 6 | 250 | skoschik/schemainspect | schemainspect/pg/obj.py | Python | PostgreSQL | PostgreSQL | 693 | 1,064 | 693 | 693 | a37b5ba991cb04f3fa07bda2827e6d3ab77f01d0 | bigcode/the-stack | train |
651f68d98b65eab8653fe8b0 | train | class | class InspectedPrivilege(Inspected):
def __init__(self, object_type, schema, name, privilege, target_user):
self.schema = schema
self.object_type = object_type
self.name = name
self.privilege = privilege.lower()
self.target_user = target_user
@property
def drop_state... | class InspectedPrivilege(Inspected):
| def __init__(self, object_type, schema, name, privilege, target_user):
self.schema = schema
self.object_type = object_type
self.name = name
self.privilege = privilege.lower()
self.target_user = target_user
@property
def drop_statement(self):
return "revoke {}... | quoted_identifier(self.name),
)
def __eq__(self, other):
equalities = (
self.name == other.name,
self.schema == other.schema,
self.table_name == other.table_name,
self.definition == other.definition,
self.index == other.index,
... | 75 | 75 | 250 | 8 | 67 | skoschik/schemainspect | schemainspect/pg/obj.py | Python | InspectedPrivilege | InspectedPrivilege | 579 | 611 | 579 | 579 | dc62f8879b760ef7b711b69a367abd2dbbc49eec | bigcode/the-stack | train |
c42f9f475a20fa42b92ec947 | train | class | class InspectedConstraint(Inspected, TableRelated):
def __init__(self, name, schema, constraint_type, table_name, definition, index):
self.name = name
self.schema = schema
self.constraint_type = constraint_type
self.table_name = table_name
self.definition = definition
... | class InspectedConstraint(Inspected, TableRelated):
| def __init__(self, name, schema, constraint_type, table_name, definition, index):
self.name = name
self.schema = schema
self.constraint_type = constraint_type
self.table_name = table_name
self.definition = definition
self.index = index
@property
def drop_stat... |
)
@property
def update_statement(self):
return "alter extension {} update to version '{}';".format(
self.quoted_full_name, self.version
)
def __eq__(self, other):
equalities = (
self.name == other.name,
self.schema == other.schema,
... | 93 | 93 | 312 | 11 | 82 | skoschik/schemainspect | schemainspect/pg/obj.py | Python | InspectedConstraint | InspectedConstraint | 528 | 576 | 528 | 528 | 02f8b7c095f13bd818d63580073270c4b85e0038 | bigcode/the-stack | train |
ab5e229993a1d7d187cf9499 | train | class | class InspectedExtension(Inspected):
def __init__(self, name, schema, version):
self.name = name
self.schema = schema
self.version = version
@property
def drop_statement(self):
return "drop extension if exists {};".format(self.quoted_name)
@property
def create_state... | class InspectedExtension(Inspected):
| def __init__(self, name, schema, version):
self.name = name
self.schema = schema
self.version = version
@property
def drop_statement(self):
return "drop extension if exists {};".format(self.quoted_name)
@property
def create_statement(self):
return "create ex... | "create schema if not exists {};".format(self.quoted_schema)
@property
def drop_statement(self):
return "drop schema if exists {};".format(self.quoted_schema)
def __eq__(self, other):
return self.schema == other.schema
class InspectedExtension(Inspected):
| 64 | 64 | 187 | 8 | 55 | skoschik/schemainspect | schemainspect/pg/obj.py | Python | InspectedExtension | InspectedExtension | 497 | 525 | 497 | 497 | d6cdc58d195ff317e0a43934cbdf72daf173c9f8 | bigcode/the-stack | train |
d43cbf95ac782df7219ce512 | train | class | class InspectedSequence(Inspected):
def __init__(self, name, schema):
self.name = name
self.schema = schema
@property
def drop_statement(self):
return "drop sequence if exists {};".format(self.quoted_full_name)
@property
def create_statement(self):
return "create se... | class InspectedSequence(Inspected):
| def __init__(self, name, schema):
self.name = name
self.schema = schema
@property
def drop_statement(self):
return "drop sequence if exists {};".format(self.quoted_full_name)
@property
def create_statement(self):
return "create sequence {};".format(self.quoted_full_... | .is_immediate,
self.is_clustered == other.is_clustered,
self.key_collations == other.key_collations,
self.key_expressions == other.key_expressions,
self.partial_predicate == other.partial_predicate,
)
return all(equalities)
class InspectedSequence(Inspecte... | 64 | 64 | 112 | 8 | 56 | skoschik/schemainspect | schemainspect/pg/obj.py | Python | InspectedSequence | InspectedSequence | 370 | 385 | 370 | 370 | 80aa268251f155b55a04654860fc5eff87881474 | bigcode/the-stack | train |
765e15fe58269df95a7fb0aa | train | class | class InspectedCollation(Inspected):
def __init__(self, name, schema, provider, encoding, lc_collate, lc_ctype, version):
self.name = name
self.schema = schema
self.provider = provider
self.lc_collate = lc_collate
self.lc_ctype = lc_ctype
self.encoding = encoding
... | class InspectedCollation(Inspected):
| def __init__(self, name, schema, provider, encoding, lc_collate, lc_ctype, version):
self.name = name
self.schema = schema
self.provider = provider
self.lc_collate = lc_collate
self.lc_ctype = lc_ctype
self.encoding = encoding
self.version = version
@prop... | quoted_full_name)
@property
def create_statement(self):
return "create sequence {};".format(self.quoted_full_name)
def __eq__(self, other):
equalities = self.name == other.name, self.schema == other.schema
return all(equalities)
class InspectedCollation(Inspected):
| 68 | 68 | 227 | 9 | 59 | skoschik/schemainspect | schemainspect/pg/obj.py | Python | InspectedCollation | InspectedCollation | 388 | 420 | 388 | 388 | 40a634820ec3dc4cb5fcfcb01da23419cb8827d5 | bigcode/the-stack | train |
5d0d5f50dd16ff127f24bd15 | train | class | class InspectedTrigger(Inspected):
def __init__(
self, name, schema, table_name, proc_schema, proc_name, enabled, full_definition
):
self.name, self.schema, self.table_name, self.proc_schema, self.proc_name, self.enabled, self.full_definition = (
name,
schema,
... | class InspectedTrigger(Inspected):
| def __init__(
self, name, schema, table_name, proc_schema, proc_name, enabled, full_definition
):
self.name, self.schema, self.table_name, self.proc_schema, self.proc_name, self.enabled, self.full_definition = (
name,
schema,
table_name,
proc_schem... | ".format(self.signature)
def __eq__(self, other):
return (
self.signature == other.signature
and self.result_string == other.result_string
and self.definition == other.definition
and self.language == other.language
and self.volatility == other.vol... | 90 | 90 | 301 | 8 | 82 | skoschik/schemainspect | schemainspect/pg/obj.py | Python | InspectedTrigger | InspectedTrigger | 251 | 300 | 251 | 251 | 65f843e738a77514154debd10185772ce3e81da2 | bigcode/the-stack | train |
7b649f57bf6728ce933b5ba3 | train | class | class InspectedIndex(Inspected, TableRelated):
def __init__(
self,
name,
schema,
table_name,
key_columns,
key_options,
num_att,
is_unique,
is_pk,
is_exclusion,
is_immediate,
is_clustered,
key_collations,
... | class InspectedIndex(Inspected, TableRelated):
| def __init__(
self,
name,
schema,
table_name,
key_columns,
key_options,
num_att,
is_unique,
is_pk,
is_exclusion,
is_immediate,
is_clustered,
key_collations,
key_expressions,
partial_predicate,
... | _name
)
@property
def create_statement(self):
return self.full_definition + ";"
def __eq__(self, other):
"""
:type other: InspectedTrigger
:rtype: bool
"""
return (
self.name == other.name
and self.schema == other.schema
... | 129 | 129 | 431 | 11 | 118 | skoschik/schemainspect | schemainspect/pg/obj.py | Python | InspectedIndex | InspectedIndex | 303 | 367 | 303 | 303 | d4558b3a870b1cecdaa7b5b365554fac10eb52bf | bigcode/the-stack | train |
b394b1feca5188bcf13926d0 | train | class | class InspectedEnum(Inspected):
def __init__(self, name, schema, elements):
self.name = name
self.schema = schema
self.elements = elements
@property
def drop_statement(self):
return "drop type {};".format(self.quoted_full_name)
@property
def create_statement(self):
... | class InspectedEnum(Inspected):
| def __init__(self, name, schema, elements):
self.name = name
self.schema = schema
self.elements = elements
@property
def drop_statement(self):
return "drop type {};".format(self.quoted_full_name)
@property
def create_statement(self):
return "create type {} a... | .quoted_full_name)
@property
def create_statement(self):
return "create collation if not exists {} (provider = '{}', locale = '{}');".format(
self.quoted_full_name, self.provider, self.locale
)
def __eq__(self, other):
equalities = (
self.name == other.name... | 110 | 110 | 367 | 8 | 102 | skoschik/schemainspect | schemainspect/pg/obj.py | Python | InspectedEnum | InspectedEnum | 423 | 477 | 423 | 423 | e8d68bbfb7ef1463dcda6febaab5144306ba01f5 | bigcode/the-stack | train |
30e73b1feeeb56bcec666c91 | train | class | class InspectedRowPolicy(Inspected, TableRelated):
def __init__(
self, name, schema, table_name, commandtype, permissive, roles, qual, withcheck
):
self.name = name
self.schema = schema
self.table_name = table_name
self.commandtype = commandtype
self.permissive = ... | class InspectedRowPolicy(Inspected, TableRelated):
| def __init__(
self, name, schema, table_name, commandtype, permissive, roles, qual, withcheck
):
self.name = name
self.schema = schema
self.table_name = table_name
self.commandtype = commandtype
self.permissive = permissive
self.roles = roles
self.... | _user == other.target_user,
)
return all(equalities)
@property
def key(self):
return self.object_type, self.quoted_full_name, self.target_user, self.privilege
RLS_POLICY_CREATE = """create policy {name}
on {table_name}
as {permissiveness}
for {commandtype_keyword}
to {roleslist}{qual_... | 131 | 132 | 441 | 12 | 119 | skoschik/schemainspect | schemainspect/pg/obj.py | Python | InspectedRowPolicy | InspectedRowPolicy | 624 | 690 | 624 | 624 | 93922410ee643ea0952ce7cac5ae6a4784ca70a7 | bigcode/the-stack | train |
aa43ee9db0115ebfeb6cce9c | train | class | class InspectedSelectable(BaseInspectedSelectable):
def has_compatible_columns(self, other):
def names_and_types(cols):
return [(k, c.dbtype) for k, c in cols.items()]
items = names_and_types(self.columns)
if self.relationtype != "f":
old_arg_count = len(other.colum... | class InspectedSelectable(BaseInspectedSelectable):
| def has_compatible_columns(self, other):
def names_and_types(cols):
return [(k, c.dbtype) for k, c in cols.items()]
items = names_and_types(self.columns)
if self.relationtype != "f":
old_arg_count = len(other.columns)
items = items[:old_arg_count]
... | from ..misc import quoted_identifier, resource_text
CREATE_TABLE = """create table {} ({}
){};
"""
CREATE_TABLE_SUBCLASS = """create table partition of {} {};
"""
CREATE_FUNCTION_FORMAT = """create or replace function {signature}
returns {result_string} as
$${definition}$$
language {language} {volatility} {strictness}... | 256 | 256 | 995 | 9 | 247 | skoschik/schemainspect | schemainspect/pg/obj.py | Python | InspectedSelectable | InspectedSelectable | 38 | 178 | 38 | 38 | 8d7158b0a7a5a89784994b6fc2da2d7781e110c7 | bigcode/the-stack | train |
71cb27fa1a09bbbea4682d0e | train | class | class InspectedSchema(Inspected):
def __init__(self, schema):
self.schema = schema
self.name = None
@property
def create_statement(self):
return "create schema if not exists {};".format(self.quoted_schema)
@property
def drop_statement(self):
return "drop schema if e... | class InspectedSchema(Inspected):
| def __init__(self, schema):
self.schema = schema
self.name = None
@property
def create_statement(self):
return "create schema if not exists {};".format(self.quoted_schema)
@property
def drop_statement(self):
return "drop schema if exists {};".format(self.quoted_sche... | for e in new.elements if e in old] == old
def __eq__(self, other):
equalities = (
self.name == other.name,
self.schema == other.schema,
self.elements == other.elements,
)
return all(equalities)
class InspectedSchema(Inspected):
| 64 | 64 | 97 | 8 | 56 | skoschik/schemainspect | schemainspect/pg/obj.py | Python | InspectedSchema | InspectedSchema | 480 | 494 | 480 | 480 | 57d13e5dc25bc638c58a9991afbea50ce859646b | bigcode/the-stack | train |
33ecd756f3499a61bee32d13 | train | class | class InspectedFunction(InspectedSelectable):
def __init__(
self,
name,
schema,
columns,
inputs,
definition,
volatility,
strictness,
security_type,
identity_arguments,
result_string,
language,
full_definition,
... | class InspectedFunction(InspectedSelectable):
| def __init__(
self,
name,
schema,
columns,
inputs,
definition,
volatility,
strictness,
security_type,
identity_arguments,
result_string,
language,
full_definition,
comment,
):
self.identity_ar... | .parent_table:
if before.parent_table:
slist.append(before.detach_statement)
if self.parent_table:
slist.append(self.attach_statement)
return slist
@property
def alter_rls_clause(self):
keyword = "enable" if self.rowsecurity else "disable"... | 108 | 108 | 363 | 9 | 99 | skoschik/schemainspect | schemainspect/pg/obj.py | Python | InspectedFunction | InspectedFunction | 181 | 248 | 181 | 181 | ffbcd90fe4ee7286ec6b33d112a8eaca9fc07e07 | bigcode/the-stack | train |
82d9bcddeb00a8ffcf07d199 | train | class | class DenoiseDiffusion:
"""
## Denoise Diffusion
"""
def __init__(self, eps_model: nn.Module, n_steps: int, device: torch.device):
"""
* `eps_model` is $\textcolor{lightgreen}{\epsilon_\theta}(x_t, t)$ model
* `n_steps` is $t$
* `device` is the device to place constants ... | class DenoiseDiffusion:
| """
## Denoise Diffusion
"""
def __init__(self, eps_model: nn.Module, n_steps: int, device: torch.device):
"""
* `eps_model` is $\textcolor{lightgreen}{\epsilon_\theta}(x_t, t)$ model
* `n_steps` is $t$
* `device` is the device to place constants on
"""
s... | Here is the [UNet model](unet.html) that gives $\textcolor{lightgreen}{\epsilon_\theta}(x_t, t)$ and
[training code](experiment.html).
[This file](evaluate.html) can generate samples and interpolations from a trained model.
[](https://colab.rese... | 256 | 256 | 1,420 | 7 | 248 | mcx/annotated_deep_learning_paper_implementations | labml_nn/diffusion/ddpm/__init__.py | Python | DenoiseDiffusion | DenoiseDiffusion | 173 | 288 | 173 | 173 | bd089469af6345bd62c69bfc71f0d1d719b57081 | bigcode/the-stack | train |
266ad444ee6563f685b6a7c8 | train | function | def main():
if len(sys.argv) == 1 or len(sys.argv) > 2:
print('FORMAT : python words.py --count|--set')
sys.exit(0)
# This could have been done by using exception handlers for IndexError.
option = sys.argv[1]
if option not in ['--count', '--set']:
print('FORMAT : python words.py --count|--set')
sys.exit(0)... | def main():
| if len(sys.argv) == 1 or len(sys.argv) > 2:
print('FORMAT : python words.py --count|--set')
sys.exit(0)
# This could have been done by using exception handlers for IndexError.
option = sys.argv[1]
if option not in ['--count', '--set']:
print('FORMAT : python words.py --count|--set')
sys.exit(0)
try:
wit... | words]
wordset = set()
wordcount = dict()
for word in words:
prev_size = len(wordset)
wordset.add(word)
new_size = len(wordset)
if new_size > prev_size:
wordcount[word] = words.count(word)
return wordset, wordcount
def main():
| 67 | 67 | 225 | 3 | 63 | AlexMathew/workshop-materials | python-day1/solution/words.py | Python | main | main | 20 | 43 | 20 | 20 | 6917fea78855cabdee04f2805e1abb454b368399 | bigcode/the-stack | train |
f8c55b9aa589c9d4143ed266 | train | function | def setup(words):
new_words = []
for word in words:
new_words.append(word.lower())
words = new_words
# This could have been done easier with list comprehensions.
# words = [word.lower() for word in words]
wordset = set()
wordcount = dict()
for word in words:
prev_size = len(wordset)
wordset.add(word)
ne... | def setup(words):
| new_words = []
for word in words:
new_words.append(word.lower())
words = new_words
# This could have been done easier with list comprehensions.
# words = [word.lower() for word in words]
wordset = set()
wordcount = dict()
for word in words:
prev_size = len(wordset)
wordset.add(word)
new_size = len(words... | import sys
def setup(words):
| 7 | 64 | 114 | 4 | 2 | AlexMathew/workshop-materials | python-day1/solution/words.py | Python | setup | setup | 3 | 18 | 3 | 3 | 0b70b27400ab7b2384bd090fb998b74afc6f3f15 | bigcode/the-stack | train |
bc6a1d61a3b5abee979a6e62 | train | class | class Phoenix(Package):
"""Apache Phoenix is a SQL skin over HBase delivered as a client-embedded
JDBC driver targeting low latency queries over HBase data."""
homepage = "https://github.com"
git = "https://github.com/apache/phoenix.git"
version('master', branch='master')
depends_on('jav... | class Phoenix(Package):
| """Apache Phoenix is a SQL skin over HBase delivered as a client-embedded
JDBC driver targeting low latency queries over HBase data."""
homepage = "https://github.com"
git = "https://github.com/apache/phoenix.git"
version('master', branch='master')
depends_on('java@8:', type=('build', 'r... | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Phoenix(Package):
| 59 | 64 | 129 | 5 | 54 | wortiz/spack | var/spack/repos/builtin/packages/phoenix/package.py | Python | Phoenix | Phoenix | 9 | 24 | 9 | 9 | 08c6624743805e2456fc8b0fbb28228866d91de7 | bigcode/the-stack | train |
e45ea32ff5b0c04e11c3bc83 | train | class | class TestStratumRetentionCondemnerPerfectResolution(unittest.TestCase):
# tests can run independently
_multiprocess_can_split_ = True
def test_equality(self):
assert (
hstrat.StratumRetentionCondemnerPerfectResolution()
== hstrat.StratumRetentionCondemnerPerfectResolution(... | class TestStratumRetentionCondemnerPerfectResolution(unittest.TestCase):
# tests can run independently
| _multiprocess_can_split_ = True
def test_equality(self):
assert (
hstrat.StratumRetentionCondemnerPerfectResolution()
== hstrat.StratumRetentionCondemnerPerfectResolution()
)
original = hstrat.StratumRetentionCondemnerPerfectResolution()
copy = deepcopy(... | from copy import deepcopy
import unittest
from hstrat import hstrat
class TestStratumRetentionCondemnerPerfectResolution(unittest.TestCase):
# tests can run independently
| 38 | 256 | 1,015 | 21 | 16 | mmore500/hstrat | hstrat/test/test_hstrat/test_stratum_retention_condemners/test_StratumRetentionCondemnerPerfectResolution.py | Python | TestStratumRetentionCondemnerPerfectResolution | TestStratumRetentionCondemnerPerfectResolution | 7 | 116 | 7 | 9 | 64407955b1742d331c17457c33d99945536eaf8a | bigcode/the-stack | train |
8ce7165e5e375db37d9a5fda | train | class | class ManterConfiguracaoForm(FlaskForm):
chave = StringField('Chave', validators=[DataRequired(), Length(1, 50,
"A chave deve ter no máximo 50 caracteres.")])
valor = StringField('Valor', validators=[DataRequired(), Length(1, 500,
"O valor deve ter... | class ManterConfiguracaoForm(FlaskForm):
| chave = StringField('Chave', validators=[DataRequired(), Length(1, 50,
"A chave deve ter no máximo 50 caracteres.")])
valor = StringField('Valor', validators=[DataRequired(), Length(1, 500,
"O valor deve ter no máximo 500 caracteres.")])
submit... | from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Length
class ManterConfiguracaoForm(FlaskForm):
| 39 | 64 | 117 | 11 | 27 | vitimdt/TraderExpert | TraderExpert/app/main/forms/manterConfiguracao.py | Python | ManterConfiguracaoForm | ManterConfiguracaoForm | 6 | 14 | 6 | 6 | 636ebdd0293ed2db42a5a329463c0574fc39775d | bigcode/the-stack | train |
abd173a3e83415d99fbac9e0 | train | function | def _install_chronos(
args=['--yes'],
returncode=0,
stdout=b'Installing Marathon app for package [chronos] '
b'version [3.0.1]\n',
stderr=b'',
pre_install_notes=b'We recommend a minimum of one node with at least '
b'2 CPUs and 2.5GiB of RA... | def _install_chronos(
args=['--yes'],
returncode=0,
stdout=b'Installing Marathon app for package [chronos] '
b'version [3.0.1]\n',
stderr=b'',
pre_install_notes=b'We recommend a minimum of one node with at least '
b'2 CPUs and 2.5GiB of RA... | cmd = ['dcos', 'package', 'install', 'chronos'] + args
assert_command(
cmd,
returncode,
pre_install_notes + stdout + post_install_notes,
stderr,
stdin=stdin)
| def _install_chronos(
args=['--yes'],
returncode=0,
stdout=b'Installing Marathon app for package [chronos] '
b'version [3.0.1]\n',
stderr=b'',
pre_install_notes=b'We recommend a minimum of one node with at least '
b'2 CPUs and 2.5GiB of RA... | 166 | 64 | 216 | 166 | 0 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | _install_chronos | _install_chronos | 926 | 949 | 926 | 942 | a48619f08f6d5e0410a015ba86d9d2361eeba5b0 | bigcode/the-stack | train |
f2357b0744bc4b1bc4132373 | train | function | def test_describe_options():
stdout = file_json(
'tests/data/package/json/test_describe_app_options.json')
stdout = json.loads(stdout.decode('utf-8'))
expected_labels = stdout.pop("labels", None)
returncode, stdout_, stderr = exec_command(
['dcos', 'package', 'describe', '--app', '--opt... | def test_describe_options():
| stdout = file_json(
'tests/data/package/json/test_describe_app_options.json')
stdout = json.loads(stdout.decode('utf-8'))
expected_labels = stdout.pop("labels", None)
returncode, stdout_, stderr = exec_command(
['dcos', 'package', 'describe', '--app', '--options',
'tests/data/p... | )
def test_describe_package_versions():
stdout = file_bytes(
'tests/data/package/json/test_describe_kafka_package_versions.json')
assert_command(
['dcos', 'package', 'describe', 'kafka', '--package-versions'],
stdout=stdout)
def test_describe_options():
| 64 | 64 | 209 | 6 | 58 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_describe_options | test_describe_options | 279 | 303 | 279 | 279 | d639809aeb35a60de34b3a23aa422b54545041fb | bigcode/the-stack | train |
4a1b3c28febd527a07a9090a | train | function | def test_images_in_metadata():
package_install('cassandra')
labels = _get_app_labels('/cassandra')
dcos_package_metadata = labels.get("DCOS_PACKAGE_METADATA")
images = json.loads(
base64.b64decode(dcos_package_metadata).decode('utf-8'))["images"]
assert images.get("icon-small") is not None
... | def test_images_in_metadata():
| package_install('cassandra')
labels = _get_app_labels('/cassandra')
dcos_package_metadata = labels.get("DCOS_PACKAGE_METADATA")
images = json.loads(
base64.b64decode(dcos_package_metadata).decode('utf-8'))["images"]
assert images.get("icon-small") is not None
assert images.get("icon-med... | osphere/dcos-helloworld",
}
helloworld_subcommand = subcommand.InstalledSubcommand("helloworld")
# test local package.json
assert helloworld_subcommand.package_json() == package
# uninstall helloworld
_uninstall_helloworld()
def test_images_in_metadata():
| 65 | 65 | 219 | 6 | 59 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_images_in_metadata | test_images_in_metadata | 474 | 495 | 474 | 474 | 3572b394dc38438d9461692ed3059a49c7366b9f | bigcode/the-stack | train |
ac1966c8c5bef437986b9407 | train | function | def test_uninstall_all(zk_znode):
_uninstall_chronos(args=['--all'])
| def test_uninstall_all(zk_znode):
| _uninstall_chronos(args=['--all'])
| dcos', 'package', 'install', 'missing-package'],
returncode=1,
stderr=stderr)
def test_uninstall_with_id(zk_znode):
_uninstall_chronos(args=['--app-id=chronos-1'])
def test_uninstall_all(zk_znode):
| 63 | 64 | 22 | 10 | 53 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_uninstall_all | test_uninstall_all | 526 | 527 | 526 | 526 | 0b58eabf74963228403a340e1fe4a9232529163a | bigcode/the-stack | train |
5e864dae3324c2db98f0ffd0 | train | function | def test_install_missing_options_file():
"""Test that a missing options file results in the expected stderr
message."""
assert_command(
['dcos', 'package', 'install', 'chronos', '--yes',
'--options=asdf.json'],
returncode=1,
stderr=b"Error opening file [asdf.json]: No such f... | def test_install_missing_options_file():
| """Test that a missing options file results in the expected stderr
message."""
assert_command(
['dcos', 'package', 'install', 'chronos', '--yes',
'--options=asdf.json'],
returncode=1,
stderr=b"Error opening file [asdf.json]: No such file or directory\n")
| and Applications may not have the same '
b'identifier.\n')
_install_helloworld(['--yes', '--app-id=/foo/bar'],
stdout=stdout2,
stderr=stderr,
returncode=1)
_uninstall_helloworld()
def test_install_missing_options_file():
| 64 | 64 | 77 | 7 | 57 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_install_missing_options_file | test_install_missing_options_file | 354 | 361 | 354 | 354 | 839168d828dcfb06b84058d2359215e147a32f8e | bigcode/the-stack | train |
e9873ae5840ad082a6875264 | train | function | def test_install_bad_package_version():
stderr = b'Version [a.b.c] of package [cassandra] not found\n'
assert_command(
['dcos', 'package', 'install', 'cassandra',
'--package-version=a.b.c'],
returncode=1,
stderr=stderr)
| def test_install_bad_package_version():
| stderr = b'Version [a.b.c] of package [cassandra] not found\n'
assert_command(
['dcos', 'package', 'install', 'cassandra',
'--package-version=a.b.c'],
returncode=1,
stderr=stderr)
| (
['dcos', 'package', 'list', 'marathon', '--json'])
assert returncode == 0
assert stderr == b''
assert json.loads(stdout.decode('utf-8'))[0]['version'] == "0.11.1"
def test_install_bad_package_version():
| 64 | 64 | 68 | 7 | 57 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_install_bad_package_version | test_install_bad_package_version | 393 | 399 | 393 | 393 | 45863f5cfbf07a43b6a0e764eb6ae062ffab9749 | bigcode/the-stack | train |
cd4cf937bfe5065c25f16d0f | train | function | def _helloworld():
stdout = (b'A sample pre-installation message\n'
b'Installing Marathon app for package [helloworld] version '
b'[0.1.0]\n' + HELLOWORLD_CLI_STDOUT +
b'A sample post-installation message\n')
stderr = b'Uninstalled package [helloworld] version [0.1.0]\... | def _helloworld():
| stdout = (b'A sample pre-installation message\n'
b'Installing Marathon app for package [helloworld] version '
b'[0.1.0]\n' + HELLOWORLD_CLI_STDOUT +
b'A sample post-installation message\n')
stderr = b'Uninstalled package [helloworld] version [0.1.0]\n'
return _pack... | _CLI_STDOUT = (b'Installing CLI subcommand for package [helloworld] '
b'version [0.1.0]\n'
b'New command available: dcos ' +
_executable_name(b'helloworld') + b'\n')
def _helloworld():
| 64 | 64 | 111 | 5 | 59 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | _helloworld | _helloworld | 996 | 1,006 | 996 | 996 | 29f31d764c8a02e0519d3e2c318bd396cc94aaa2 | bigcode/the-stack | train |
73e14730f57420bf7a5188b1 | train | function | def test_bad_install():
args = ['--options=tests/data/package/chronos-bad.json', '--yes']
stdout = b""
stderr = """\
Please create a JSON file with the appropriate options, and pass the \
/path/to/file as an --options argument.
"""
_install_bad_chronos(args=args,
stdout=stdout,
... | def test_bad_install():
| args = ['--options=tests/data/package/chronos-bad.json', '--yes']
stdout = b""
stderr = """\
Please create a JSON file with the appropriate options, and pass the \
/path/to/file as an --options argument.
"""
_install_bad_chronos(args=args,
stdout=stdout,
... | 0
def test_describe_app_cli():
stdout = file_bytes(
'tests/data/package/json/test_describe_app_cli.json')
assert_command(
['dcos', 'package', 'describe', 'kafka', '--app', '--cli'],
stdout=stdout)
def test_bad_install():
| 64 | 64 | 81 | 5 | 59 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_bad_install | test_bad_install | 314 | 323 | 314 | 314 | d22d5733843456a84ae100f6f564c3b08219fbac | bigcode/the-stack | train |
c445b4d7bc2abe107a7984ae | train | function | def test_describe_cli():
stdout = file_json(
'tests/data/package/json/test_describe_cli_kafka.json')
assert_command(['dcos', 'package', 'describe', 'kafka', '--cli'],
stdout=stdout)
| def test_describe_cli():
| stdout = file_json(
'tests/data/package/json/test_describe_cli_kafka.json')
assert_command(['dcos', 'package', 'describe', 'kafka', '--cli'],
stdout=stdout)
| stderr = b'Version [a.b.c] of package [marathon] not found\n'
assert_command(['dcos', 'package', 'describe', 'marathon',
'--package-version=a.b.c'],
stderr=stderr,
returncode=1)
def test_describe_cli():
| 64 | 64 | 51 | 6 | 58 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_describe_cli | test_describe_cli | 202 | 206 | 202 | 202 | 96d6c39f74a1f02709d38792b7bde4a8af6f1030 | bigcode/the-stack | train |
f5d2272b54a9f189ccc5cfd4 | train | function | def _repo_add(args=[], repo_list=[]):
assert_command(['dcos', 'package', 'repo', 'add'] + args)
assert_command(['dcos', 'package', 'repo', 'list'], stdout=repo_list)
| def _repo_add(args=[], repo_list=[]):
| assert_command(['dcos', 'package', 'repo', 'add'] + args)
assert_command(['dcos', 'package', 'repo', 'list'], stdout=repo_list)
| assert installed
assert stdout_ == stdout
yield
finally:
if installed:
assert_command(
['dcos', 'package', 'uninstall', name],
stderr=uninstall_stderr)
watch_all_deployments()
def _repo_add(args=[], repo_list=[]):
| 64 | 64 | 50 | 10 | 54 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | _repo_add | _repo_add | 1,057 | 1,059 | 1,057 | 1,057 | c19ee5667071bfe6da2cd055d1fa86f71da11293 | bigcode/the-stack | train |
d51722312a384f89105ce5b5 | train | function | def test_bad_install_helloworld_msg():
stdout = (b'A sample pre-installation message\n'
b'Installing Marathon app for package [helloworld] version '
b'[0.1.0] with app id [/foo]\n'
b'Installing CLI subcommand for package [helloworld] '
b'version [0.1.0]\n'
... | def test_bad_install_helloworld_msg():
| stdout = (b'A sample pre-installation message\n'
b'Installing Marathon app for package [helloworld] version '
b'[0.1.0] with app id [/foo]\n'
b'Installing CLI subcommand for package [helloworld] '
b'version [0.1.0]\n'
b'New command available: dco... | /package/chronos-bad.json', '--yes']
stdout = b""
stderr = """\
Please create a JSON file with the appropriate options, and pass the \
/path/to/file as an --options argument.
"""
_install_bad_chronos(args=args,
stdout=stdout,
stderr=stderr)
def test_bad_inst... | 76 | 76 | 255 | 9 | 67 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_bad_install_helloworld_msg | test_bad_install_helloworld_msg | 326 | 351 | 326 | 326 | 66cdb857a4731348d67b071be03ddbc2f87bc11c | bigcode/the-stack | train |
cfd81eca82fe171aa71c0f8e | train | function | def test_repo_empty():
for name in UNIVERSE_TEST_REPOS.keys():
assert_command(['dcos', 'package', 'repo', 'remove', name])
returncode, stdout, stderr = exec_command(
['dcos', 'package', 'repo', 'list'])
stderr_msg = (b"There are currently no repos configured. "
b"Please us... | def test_repo_empty():
| for name in UNIVERSE_TEST_REPOS.keys():
assert_command(['dcos', 'package', 'repo', 'remove', name])
returncode, stdout, stderr = exec_command(
['dcos', 'package', 'repo', 'list'])
stderr_msg = (b"There are currently no repos configured. "
b"Please use `dcos package repo ad... | : {test-universe}\n"
"helloworld-universe: {helloworld-universe}\n"
).format(**UNIVERSE_TEST_REPOS),
'utf-8'
)
_repo_remove(['1.7-universe', 'Universe'], repo_list)
def test_repo_empty():
| 64 | 64 | 147 | 5 | 59 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_repo_empty | test_repo_empty | 172 | 185 | 172 | 172 | 95068ce2468aeecc5ceebe4b17396069109708b2 | bigcode/the-stack | train |
cc604011303bb2185068019f | train | function | def test_install_yes():
with open('tests/data/package/assume_yes.txt') as yes_file:
_install_helloworld(
args=[],
stdin=yes_file,
stdout=b'A sample pre-installation message\n'
b'Continue installing? [yes/no] '
b'Installing Marathon ap... | def test_install_yes():
| with open('tests/data/package/assume_yes.txt') as yes_file:
_install_helloworld(
args=[],
stdin=yes_file,
stdout=b'A sample pre-installation message\n'
b'Continue installing? [yes/no] '
b'Installing Marathon app for package [helloworl... | =['--json', le_package], stdout=empty)
_list(args=['--json', '--app-id=/' + le_package], stdout=empty)
def test_list_table():
with _helloworld():
assert_lines(['dcos', 'package', 'list'], 2)
def test_install_yes():
| 64 | 64 | 155 | 5 | 59 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_install_yes | test_install_yes | 638 | 652 | 638 | 638 | a6c1a5862391b918d8b3bc3a6ff0917a494c1c63 | bigcode/the-stack | train |
d30af639abb1ff6b335128f7 | train | function | def _repo_remove(args=[], repo_list=[]):
assert_command(['dcos', 'package', 'repo', 'remove'] + args)
assert_command(['dcos', 'package', 'repo', 'list'], stdout=repo_list)
| def _repo_remove(args=[], repo_list=[]):
| assert_command(['dcos', 'package', 'repo', 'remove'] + args)
assert_command(['dcos', 'package', 'repo', 'list'], stdout=repo_list)
| _deployments()
def _repo_add(args=[], repo_list=[]):
assert_command(['dcos', 'package', 'repo', 'add'] + args)
assert_command(['dcos', 'package', 'repo', 'list'], stdout=repo_list)
def _repo_remove(args=[], repo_list=[]):
| 64 | 64 | 50 | 10 | 54 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | _repo_remove | _repo_remove | 1,062 | 1,064 | 1,062 | 1,062 | 4fa72e928d464e850d33c9b39a91ba601a3ab6d1 | bigcode/the-stack | train |
4059fa03aa8758cae070e5dd | train | function | def test_install_no():
with open('tests/data/package/assume_no.txt') as no_file:
_install_helloworld(
args=[],
stdin=no_file,
stdout=b'A sample pre-installation message\n'
b'Continue installing? [yes/no] Exiting installation.\n')
| def test_install_no():
| with open('tests/data/package/assume_no.txt') as no_file:
_install_helloworld(
args=[],
stdin=no_file,
stdout=b'A sample pre-installation message\n'
b'Continue installing? [yes/no] Exiting installation.\n')
| oworld] '
b'version [0.1.0]\n'
b'New command available: dcos ' +
_executable_name(b'helloworld') +
b'\nA sample post-installation message\n')
_uninstall_helloworld()
def test_install_no():
| 64 | 64 | 65 | 5 | 59 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_install_no | test_install_no | 655 | 661 | 655 | 655 | f8e234e9373a13ea562cb1a307e7fa689766bf9d | bigcode/the-stack | train |
0e446c9a309be28810b9dcf4 | train | function | def test_search_middle_with_wildcard():
returncode, stdout, stderr = exec_command(
['dcos', 'package', 'search', 'c*s', '--json'])
assert returncode == 0
assert b'chronos' in stdout
assert stderr == b''
registries = json.loads(stdout.decode('utf-8'))
assert len(registries['packages']) ... | def test_search_middle_with_wildcard():
| returncode, stdout, stderr = exec_command(
['dcos', 'package', 'search', 'c*s', '--json'])
assert returncode == 0
assert b'chronos' in stdout
assert stderr == b''
registries = json.loads(stdout.decode('utf-8'))
assert len(registries['packages']) == 4
| ', '--json'])
assert returncode == 0
assert b'chronos' in stdout
assert stderr == b''
registries = json.loads(stdout.decode('utf-8'))
assert len(registries['packages']) == 1
def test_search_middle_with_wildcard():
| 64 | 64 | 89 | 9 | 54 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_search_middle_with_wildcard | test_search_middle_with_wildcard | 828 | 837 | 828 | 828 | 679d52546e8408bbeb605364ba110bd550f6f913 | bigcode/the-stack | train |
a50413e1e9c191c08b65c9ff | train | function | def test_search_table():
returncode, stdout, stderr = exec_command(
['dcos', 'package', 'search'])
assert returncode == 0
assert b'chronos' in stdout
assert len(stdout.decode('utf-8').split('\n')) > 5
assert stderr == b''
| def test_search_table():
| returncode, stdout, stderr = exec_command(
['dcos', 'package', 'search'])
assert returncode == 0
assert b'chronos' in stdout
assert len(stdout.decode('utf-8').split('\n')) > 5
assert stderr == b''
| .loads(stdout.decode('utf-8'))
# assert the number of packages is gte the number at the time
# this test was written
assert len(registries['packages']) >= 5
assert returncode == 0
assert stderr == b''
def test_search_table():
| 63 | 64 | 69 | 5 | 58 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_search_table | test_search_table | 791 | 798 | 791 | 791 | 5acb05658d1d9501a6e72a77745408e2e1fb15bd | bigcode/the-stack | train |
0dcdfacb19029c1a793bb709 | train | function | def test_describe_nonexistent_version():
stderr = b'Version [a.b.c] of package [marathon] not found\n'
assert_command(['dcos', 'package', 'describe', 'marathon',
'--package-version=a.b.c'],
stderr=stderr,
returncode=1)
| def test_describe_nonexistent_version():
| stderr = b'Version [a.b.c] of package [marathon] not found\n'
assert_command(['dcos', 'package', 'describe', 'marathon',
'--package-version=a.b.c'],
stderr=stderr,
returncode=1)
| 'package', 'repo', 'add', name, url])
def test_describe_nonexistent():
assert_command(['dcos', 'package', 'describe', 'xyzzy'],
stderr=b'Package [xyzzy] not found\n',
returncode=1)
def test_describe_nonexistent_version():
| 64 | 64 | 67 | 8 | 56 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_describe_nonexistent_version | test_describe_nonexistent_version | 194 | 199 | 194 | 194 | cd1bca251104230f6d669cdda3e2ca61df1da383 | bigcode/the-stack | train |
d77d7fd9bff3fa23367c8240 | train | function | def test_uninstall_missing():
stderr = 'Package [chronos] is not installed\n'
_uninstall_chronos(returncode=1, stderr=stderr)
stderr = 'Package [chronos] with id [/chronos-1] is not installed\n'
_uninstall_chronos(
args=['--app-id=chronos-1'],
returncode=1,
stderr=stderr)
| def test_uninstall_missing():
| stderr = 'Package [chronos] is not installed\n'
_uninstall_chronos(returncode=1, stderr=stderr)
stderr = 'Package [chronos] with id [/chronos-1] is not installed\n'
_uninstall_chronos(
args=['--app-id=chronos-1'],
returncode=1,
stderr=stderr)
| stderr=stderr)
def test_uninstall_with_id(zk_znode):
_uninstall_chronos(args=['--app-id=chronos-1'])
def test_uninstall_all(zk_znode):
_uninstall_chronos(args=['--all'])
def test_uninstall_missing():
| 63 | 64 | 89 | 6 | 57 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_uninstall_missing | test_uninstall_missing | 530 | 538 | 530 | 530 | d979cca9972aaefe54be839b95d5ecfe0b08e224 | bigcode/the-stack | train |
89e483f9a506f3814620d6f8 | train | function | def test_describe_app():
stdout = file_bytes(
'tests/data/package/json/test_describe_app_marathon.json')
assert_command(['dcos', 'package', 'describe', 'marathon', '--app'],
stdout=stdout)
| def test_describe_app():
| stdout = file_bytes(
'tests/data/package/json/test_describe_app_marathon.json')
assert_command(['dcos', 'package', 'describe', 'marathon', '--app'],
stdout=stdout)
| ,
returncode=1)
def test_describe_cli():
stdout = file_json(
'tests/data/package/json/test_describe_cli_kafka.json')
assert_command(['dcos', 'package', 'describe', 'kafka', '--cli'],
stdout=stdout)
def test_describe_app():
| 64 | 64 | 51 | 6 | 58 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | test_describe_app | test_describe_app | 209 | 213 | 209 | 209 | 75b4c25cb1a62f19bcea24adca83dc231aeb4eb4 | bigcode/the-stack | train |
07071f97479e5a03ab53a804 | train | function | def setup_module(module):
setup_universe_server()
| def setup_module(module):
| setup_universe_server()
| IVERSE_TEST_REPOS)
from .helpers.service import get_services, service_shutdown
from ..common import file_bytes
@pytest.fixture
def env():
r = os.environ.copy()
r.update({constants.PATH_ENV: os.environ[constants.PATH_ENV]})
return r
def setup_module(module):
| 64 | 64 | 11 | 5 | 58 | christopherhein/dcos-cli | cli/tests/integrations/test_package.py | Python | setup_module | setup_module | 31 | 32 | 31 | 31 | c12d52fdf401da76b5b289a2377fbc603464b22f | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.