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
31081d27f184cbbf92ef6f86
train
class
class NTxHash(Enum): mainnet = Hash32.fromhex("0x5aa2453a84ba2fb1e3394b9e3471f5dcebc6225fc311a97ca505728153b9d246") testnet = Hash32.fromhex("0x5a7ce1e10a6fd5fb3925a011528f89a5debfead2405f5545a99d1a1310e48c9e")
class NTxHash(Enum):
mainnet = Hash32.fromhex("0x5aa2453a84ba2fb1e3394b9e3471f5dcebc6225fc311a97ca505728153b9d246") testnet = Hash32.fromhex("0x5a7ce1e10a6fd5fb3925a011528f89a5debfead2405f5545a99d1a1310e48c9e")
setattr__(self, "nid", nid) object.__setattr__(self, "accounts", tuple(accounts)) object.__setattr__(self, "message", message) @property def signer_address(self) -> 'ExternalAddress': raise NotImplementedError class NTxHash(Enum):
64
64
108
6
57
windies21/loopchain
loopchain/blockchain/transactions/genesis/transaction.py
Python
NTxHash
NTxHash
32
34
32
32
8c206ad27246f5ff69ceab8be5dbd4533f2aa202
bigcode/the-stack
train
9fabf7813337f0f7f41f76bb
train
class
@dataclass(frozen=True) class Transaction(BaseTransition): nid: int accounts: tuple message: str version = "genesis" def __init__(self, raw_data: dict, hash: 'Hash32', signature: Union['Signature', None], timestamp: int, nid: int, accounts: list, message: str): super().__i...
@dataclass(frozen=True) class Transaction(BaseTransition):
nid: int accounts: tuple message: str version = "genesis" def __init__(self, raw_data: dict, hash: 'Hash32', signature: Union['Signature', None], timestamp: int, nid: int, accounts: list, message: str): super().__init__(raw_data, hash, signature, timestamp) object...
import dataclass from typing import TYPE_CHECKING, Union from loopchain.blockchain.types import Hash32 from loopchain.blockchain.transactions import Transaction as BaseTransition if TYPE_CHECKING: from loopchain.blockchain.types import Signature, ExternalAddress @dataclass(frozen=True) class Transaction(BaseTrans...
64
64
151
11
52
windies21/loopchain
loopchain/blockchain/transactions/genesis/transaction.py
Python
Transaction
Transaction
11
29
11
12
8d921b670049c1771df5c4af9eeb4b47e5b34ce3
bigcode/the-stack
train
9a1d9629cf0c4bbf913da40f
train
class
class NID(IntEnum): mainnet = 1 testnet = 2 unknown = 3
class NID(IntEnum):
mainnet = 1 testnet = 2 unknown = 3
b9d246") testnet = Hash32.fromhex("0x5a7ce1e10a6fd5fb3925a011528f89a5debfead2405f5545a99d1a1310e48c9e") class NID(IntEnum):
64
64
26
6
58
windies21/loopchain
loopchain/blockchain/transactions/genesis/transaction.py
Python
NID
NID
37
40
37
37
708c925a68aec3bbf9421c07972d9602a3908c4e
bigcode/the-stack
train
70527e24d03313080a53bd27
train
function
def _build_viz_figure(visualization): import dash_cytoscape as cyto if visualization is None: _type = "none" figure = "null" elif isinstance(visualization, go.Figure): _type = "plotly" figure = json.loads(to_json(visualization)) elif isinstance(visualization, str): ...
def _build_viz_figure(visualization):
import dash_cytoscape as cyto if visualization is None: _type = "none" figure = "null" elif isinstance(visualization, go.Figure): _type = "plotly" figure = json.loads(to_json(visualization)) elif isinstance(visualization, str): _type = "html" figure = _bu...
ape_json(cytoscape): json_di = { "elements": cytoscape.elements, "layout": cytoscape.layout, "style": cytoscape.style, "stylesheet": cytoscape.stylesheet, } return json.dumps(json_di) def _build_viz_figure(visualization):
69
69
230
11
58
PiCEulHer/interpret
python/interpret-core/interpret/visual/inline.py
Python
_build_viz_figure
_build_viz_figure
53
76
53
53
b243cf3c31bebfc3f13f3afe0915782ac3bd3c39
bigcode/the-stack
train
029eaff74279d52e405b5391
train
function
def _build_viz_err_obj(err_msg): _type = "html" figure = _build_error_frame(err_msg) viz_figure = {"type": _type, "figure": figure} viz_obj = { "name": "Error", "overall": viz_figure, "specific": [], "selector": {"columns": [], "data": []}, } return viz_obj
def _build_viz_err_obj(err_msg):
_type = "html" figure = _build_error_frame(err_msg) viz_figure = {"type": _type, "figure": figure} viz_obj = { "name": "Error", "overall": viz_figure, "specific": [], "selector": {"columns": [], "data": []}, } return viz_obj
" msg = "This visualization is not yet supported in the cloud environment." log.debug("Visualization type cannot render: {}".format(type(visualization))) figure = _build_error_frame(msg) return {"type": _type, "figure": figure} def _build_viz_err_obj(err_msg):
64
64
88
10
54
PiCEulHer/interpret
python/interpret-core/interpret/visual/inline.py
Python
_build_viz_err_obj
_build_viz_err_obj
79
90
79
79
094604292764a4943e5798bd7c34419843c61ada
bigcode/the-stack
train
67b0171bea34a8dffcd5a65d
train
function
def _build_cytoscape_json(cytoscape): json_di = { "elements": cytoscape.elements, "layout": cytoscape.layout, "style": cytoscape.style, "stylesheet": cytoscape.stylesheet, } return json.dumps(json_di)
def _build_cytoscape_json(cytoscape):
json_di = { "elements": cytoscape.elements, "layout": cytoscape.layout, "style": cytoscape.style, "stylesheet": cytoscape.stylesheet, } return json.dumps(json_di)
_src(html_str) def _build_base64_frame_src(html_str): html_hex64 = base64.b64encode(html_str.encode("utf-8")).decode("ascii") return "data:text/html;base64,{}".format(html_hex64) def _build_cytoscape_json(cytoscape):
64
64
64
13
51
PiCEulHer/interpret
python/interpret-core/interpret/visual/inline.py
Python
_build_cytoscape_json
_build_cytoscape_json
44
51
44
44
51d195fecacef00dd15822413ee383a0acac9c82
bigcode/the-stack
train
66b39ba90eb069c9185ca633
train
function
def _render_databricks(js): # pragma: no cover import inspect if _render_databricks.displayHTML is None: found = False for frame in inspect.getouterframes(inspect.currentframe()): global_names = set(frame.frame.f_globals) target_names = {"displayHTML", "display", "spark...
def _render_databricks(js): # pragma: no cover
import inspect if _render_databricks.displayHTML is None: found = False for frame in inspect.getouterframes(inspect.currentframe()): global_names = set(frame.frame.f_globals) target_names = {"displayHTML", "display", "spark"} if target_names.issubset(global_n...
://github.com/plotly/plotly.py/blob/01a78d3fdac14848affcd33ddc4f9ec72d475232/packages/python/plotly/plotly/io/_base_renderers.py def _render_databricks(js): # pragma: no cover
64
64
149
15
48
PiCEulHer/interpret
python/interpret-core/interpret/visual/inline.py
Python
_render_databricks
_render_databricks
185
203
185
185
4cf5369a8ce65ba0dd6a5573eac65d9c91aee339
bigcode/the-stack
train
d68719c3de8033b74a7a25a1
train
function
def _build_base64_frame_src(html_str): html_hex64 = base64.b64encode(html_str.encode("utf-8")).decode("ascii") return "data:text/html;base64,{}".format(html_hex64)
def _build_base64_frame_src(html_str):
html_hex64 = base64.b64encode(html_str.encode("utf-8")).decode("ascii") return "data:text/html;base64,{}".format(html_hex64)
transform: translate(-50%, -50%); }} </style> <div class='center'><h1>{}</h1></div> """ html_str = error_template.format(msg) return _build_base64_frame_src(html_str) def _build_base64_frame_src(html_str):
64
64
47
10
54
PiCEulHer/interpret
python/interpret-core/interpret/visual/inline.py
Python
_build_base64_frame_src
_build_base64_frame_src
40
42
40
40
abdb387360cec020f31572c12447940eec9e3f89
bigcode/the-stack
train
3a4a8906710f57183529427e
train
function
def _build_error_frame(msg): error_template = r""" <style> .center {{ position: absolute; left: 50%; top: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); }} </style> <div class='center'><h1>{}</h1></div> """ html_st...
def _build_error_frame(msg):
error_template = r""" <style> .center {{ position: absolute; left: 50%; top: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); }} </style> <div class='center'><h1>{}</h1></div> """ html_str = error_template.format(msg...
import uuid from plotly.io import to_json from plotly import graph_objs as go import sys import json import base64 import logging log = logging.getLogger(__name__) this = sys.modules[__name__] this.jupyter_initialized = False def _build_error_frame(msg):
64
64
104
7
56
PiCEulHer/interpret
python/interpret-core/interpret/visual/inline.py
Python
_build_error_frame
_build_error_frame
23
37
23
23
71e540a1120d116c0fe8def09b1fd8279e777937
bigcode/the-stack
train
f82699bd00c2faf19541fa18
train
function
def _build_javascript(viz_obj, id_str=None, default_key=-1, js_url=None): if js_url is None: script_path = os.path.dirname(os.path.abspath(__file__)) js_path = os.path.join(script_path, "..", "lib", "interpret-inline.js") with open(js_path, "r", encoding="utf-8") as f: show_js =...
def _build_javascript(viz_obj, id_str=None, default_key=-1, js_url=None):
if js_url is None: script_path = os.path.dirname(os.path.abspath(__file__)) js_path = os.path.join(script_path, "..", "lib", "interpret-inline.js") with open(js_path, "r", encoding="utf-8") as f: show_js = f.read() init_js = """ <script type="text/javascript"> ...
selector_obj = {"columns": [], "data": []} else: specific = [ _build_viz_figure(explanation.visualize(i)) for i in range(len(explanation.selector)) ] selector_obj = { "columns": list(explanation.selector.columns), "data": explanation.selector....
132
132
443
22
109
PiCEulHer/interpret
python/interpret-core/interpret/visual/inline.py
Python
_build_javascript
_build_javascript
118
180
118
118
7a4c1a63edadd8fd0e2fa20485cdee1b2d62a93b
bigcode/the-stack
train
f749a2739a98e1d2d7f0e9d3
train
function
def _build_viz_obj(explanation): overall = _build_viz_figure(explanation.visualize()) if explanation.selector is None: # NOTE: Unsure if this should be a list or None in the long term. specific = [] selector_obj = {"columns": [], "data": []} else: specific = [ _bu...
def _build_viz_obj(explanation):
overall = _build_viz_figure(explanation.visualize()) if explanation.selector is None: # NOTE: Unsure if this should be a list or None in the long term. specific = [] selector_obj = {"columns": [], "data": []} else: specific = [ _build_viz_figure(explanation.visual...
type": _type, "figure": figure} viz_obj = { "name": "Error", "overall": viz_figure, "specific": [], "selector": {"columns": [], "data": []}, } return viz_obj def _build_viz_obj(explanation):
64
64
164
9
54
PiCEulHer/interpret
python/interpret-core/interpret/visual/inline.py
Python
_build_viz_obj
_build_viz_obj
93
115
93
93
59d02f922c5d0969ee0a46ce8e378939d01505ef
bigcode/the-stack
train
e49fbad6f7ae2bc1876e10a7
train
function
def render(explanation, id_str=None, default_key=-1, detected_envs=None, js_url=None): from IPython.display import display, HTML if isinstance(explanation, list): msg = "Dashboard not yet supported in cloud environments." viz_obj = _build_viz_err_obj(msg) else: viz_obj = _build_viz_...
def render(explanation, id_str=None, default_key=-1, detected_envs=None, js_url=None):
from IPython.display import display, HTML if isinstance(explanation, list): msg = "Dashboard not yet supported in cloud environments." viz_obj = _build_viz_err_obj(msg) else: viz_obj = _build_viz_obj(explanation) init_js, body_js = _build_javascript( viz_obj, id_str, de...
found: msg = "Could not find DataBrick's displayHTML function" log.error(msg) raise RuntimeError(msg) _render_databricks.displayHTML(js) _render_databricks.displayHTML = None def render(explanation, id_str=None, default_key=-1, detected_envs=None, js_url=None):
69
69
233
23
45
PiCEulHer/interpret
python/interpret-core/interpret/visual/inline.py
Python
render
render
209
231
209
209
5c7907621a4419b2f5e1f8263a85fc7f14f740b3
bigcode/the-stack
train
b30b77fcad237c6f32359467
train
function
def mov_avg (mylist): N = 3 cumsum, moving_aves = [0], [] for i, x in enumerate(mylist, 1): cumsum.append(cumsum[i-1] + x) if i>=N: moving_ave = (cumsum[i] - cumsum[i-N])/N if (moving_ave)<140: moving_aves.append(moving_ave) return movin...
def mov_avg (mylist):
N = 3 cumsum, moving_aves = [0], [] for i, x in enumerate(mylist, 1): cumsum.append(cumsum[i-1] + x) if i>=N: moving_ave = (cumsum[i] - cumsum[i-N])/N if (moving_ave)<140: moving_aves.append(moving_ave) return moving_aves
from matplotlib import style import datetime as dt fig=plt.figure() axl=fig.add_subplot(1,1,1) ser=serial.Serial("COM4",115200) beat=[] avg_beat=[] xs=[] ys=[] y_range=[30,150] def mov_avg (mylist):
64
64
101
7
57
Uzama/Smart-Driver-Drowsiness-Detection
pulse.py
Python
mov_avg
mov_avg
18
28
18
18
5564ee5f917863f6164c58ebb98846bd0d305024
bigcode/the-stack
train
7f326e6b24ff1225a6f47cca
train
function
def suite(): loader = unittest.TestLoader() tests = loader.discover(os.path.dirname(__file__), pattern='test*.py', top_level_dir=None) suite = unittest.TestSuite() for test in tests: suite.addTest(test) return suite
def suite():
loader = unittest.TestLoader() tests = loader.discover(os.path.dirname(__file__), pattern='test*.py', top_level_dir=None) suite = unittest.TestSuite() for test in tests: suite.addTest(test) return suite
"""Django feeds test suite""" import unittest import os def suite():
16
64
58
3
12
operasoftware/django-feeds
djangofeeds/tests/__init__.py
Python
suite
suite
6
15
6
6
63f94033cb87918ea33a686e2fb750f5abefb7fe
bigcode/the-stack
train
e1d574425e649c81629ad823
train
class
class Expression(Node.Nodo): def __init__(self, *args): if len(args) == 6: self.exp1 = args[0] self.exp2 = args[1] self.op = args[2] self.line = args[3] self.column = args[4] self.op_type = args[5] self.valor = None ...
class Expression(Node.Nodo):
def __init__(self, *args): if len(args) == 6: self.exp1 = args[0] self.exp2 = args[1] self.op = args[2] self.line = args[3] self.column = args[4] self.op_type = args[5] self.valor = None self.type = None ...
import AST.Nodo as Node from TablaSimbolos.Tipos import * from Errores.Nodo_Error import * class Expression(Node.Nodo):
31
136
454
6
25
susanliss/tytus
parser/team19/BDTytus/AST/Expresiones.py
Python
Expression
Expression
6
59
6
6
1944b459cda02592dcd2fd4986d726e856daec62
bigcode/the-stack
train
1f4af1f169536c756a60aab9
train
class
class variable(Node.Nodo): def __init__(self, nombre, fila, col): self.fila = fila self.columna = col self.nombre = nombre self.temporal = "" def ejecutar(self, TS, Errores): simbolo = TS.obtener(self.nombre) if simbolo is None: Errores.insertar( ...
class variable(Node.Nodo):
def __init__(self, nombre, fila, col): self.fila = fila self.columna = col self.nombre = nombre self.temporal = "" def ejecutar(self, TS, Errores): simbolo = TS.obtener(self.nombre) if simbolo is None: Errores.insertar( Nodo_Error("Sem...
' + str(id(self)) grafica.node(nombrehijo, label=('Exp')) grafica.edge(padre, nombrehijo) grafica.node('NodeV' + str(id(self)), label=(str(self.valor))) grafica.edge(nombrehijo, 'NodeV' + str(id(self))) class variable(Node.Nodo):
71
72
240
6
65
susanliss/tytus
parser/team19/BDTytus/AST/Expresiones.py
Python
variable
variable
225
251
225
225
9f45503a9807036db1468b1b127c292977db6891
bigcode/the-stack
train
6c19916976940af38ef0d4ec
train
class
class Aritmetica(Node.Nodo): def __init__(self, Exp1, Exp2, op, fila, col): #self.Exp1 = primitivo() Descomentar correrlo produce error porque el metodo necesita mas parametros, pienso que querias poner exp1? #self.Exp2 = primitivo() Descomentar correrlo produce error porque el metodo necesita mas p...
class Aritmetica(Node.Nodo):
def __init__(self, Exp1, Exp2, op, fila, col): #self.Exp1 = primitivo() Descomentar correrlo produce error porque el metodo necesita mas parametros, pienso que querias poner exp1? #self.Exp2 = primitivo() Descomentar correrlo produce error porque el metodo necesita mas parametros, pienso que querias...
OS.STRING def ejecutar(self, TS, Errores): if self.op_type is None: return self elif self.op_type == 'Aritmetica': tipo1 = self.exp1.ejecutar(TS, Errores) tipo2 = self.exp2.ejecutar(TS, Errores) if tipo1.type == TIPO_DATOS.INT: if tipo...
256
256
1,089
9
246
susanliss/tytus
parser/team19/BDTytus/AST/Expresiones.py
Python
Aritmetica
Aritmetica
62
144
62
62
31d2a2b052c347347912814847dc98d99b3f6e50
bigcode/the-stack
train
b978b5dfa9274c7a834b4684
train
class
class casteo(Node.Nodo): def __init__(self, Cast, Exp, fila, col): self.fila = fila self.columna = col self.Exp = Exp self.cast = Cast def ejecutar(self, TS, Errores): self.Exp.ejecutar(TS, Errores) if self.cast == "char": self.tipo = TIPO_DATOS.CHAR ...
class casteo(Node.Nodo):
def __init__(self, Cast, Exp, fila, col): self.fila = fila self.columna = col self.Exp = Exp self.cast = Cast def ejecutar(self, TS, Errores): self.Exp.ejecutar(TS, Errores) if self.cast == "char": self.tipo = TIPO_DATOS.CHAR elif self.cast ==...
hijo, grafica) grafica.node('NodeE2' + str(id(self)), label=":") grafica.edge(nombrehijo, 'NodeE2' + str(id(self))) self.Exp2.graficarasc(nombrehijo, grafica) class casteo(Node.Nodo):
64
64
211
7
57
susanliss/tytus
parser/team19/BDTytus/AST/Expresiones.py
Python
casteo
casteo
490
516
490
490
5717b5f7836b2b0b716c40cb8c7815311c5116bc
bigcode/the-stack
train
c910818a26431c3417aba9dc
train
class
class ternario(Node.Nodo): def __init__(self, Cond, Exp1, Exp2, fila, col): self.fila = fila self.columna = col self.Cond = Cond self.Exp1 = Exp1 self.Exp2 = Exp2 def ejecutar(self, TS, Errores): tipo = self.ejecutar(TS, Errores) if not ( ...
class ternario(Node.Nodo):
def __init__(self, Cond, Exp1, Exp2, fila, col): self.fila = fila self.columna = col self.Cond = Cond self.Exp1 = Exp1 self.Exp2 = Exp2 def ejecutar(self, TS, Errores): tipo = self.ejecutar(TS, Errores) if not ( tipo == TIPO_DATOS.INT or t...
getC3D(self, TS): codigo = "" codigo += self.Exp.getC3D(TS) temp = TS.getTemp() self.temporal = temp codigo += self.temporal + ' = ' + str(self.op) + ' ' + self.Exp.temporal + '; \n' return codigo def graficarasc(self, padre, grafica): nombrehijo = 'Node' + ...
187
187
624
7
180
susanliss/tytus
parser/team19/BDTytus/AST/Expresiones.py
Python
ternario
ternario
438
487
438
438
a29663c79b25779ac2aa3feb5d0b34efadcd2b9c
bigcode/the-stack
train
8b93b45a0c4b1e80f3207e99
train
class
class primitivo(Node.Nodo): def __init__(self, Valor, fila, col, tipo): self.fila = fila self.columna = col self.valor = Valor self.temporal = "" if tipo == "decimal": self.tipo = TIPO_DATOS.DOUBLE elif tipo == "entero": self.tipo = TIPO_DATOS....
class primitivo(Node.Nodo):
def __init__(self, Valor, fila, col, tipo): self.fila = fila self.columna = col self.valor = Valor self.temporal = "" if tipo == "decimal": self.tipo = TIPO_DATOS.DOUBLE elif tipo == "entero": self.tipo = TIPO_DATOS.INT elif tipo == "ch...
not None: self.Exp1.graficarasc(nombrehijo, grafica) grafica.node('NodeE1' + str(id(self)), label=(str(self.op))) grafica.edge(nombrehijo, 'NodeE1' + str(id(self))) if self.Exp2 is not None: self.Exp2.graficarasc(nombrehijo, grafica) class primitivo(Node.Nodo):
89
89
299
7
82
susanliss/tytus
parser/team19/BDTytus/AST/Expresiones.py
Python
primitivo
primitivo
190
222
190
190
5dee0e4948879bcf0dccf73f813f324727251a65
bigcode/the-stack
train
8ff67a9353549f9f04500c26
train
class
class unario(Node.Nodo): def __init__(self, Exp, op, fila, col): self.fila = fila self.columna = col self.Exp = Exp self.op = op def ejecutar(self, TS, Errores): tipo = self.Exp.ejecutar(TS, Errores) if self.op == '~': if tipo == TIPO_DATOS.INT or tip...
class unario(Node.Nodo):
def __init__(self, Exp, op, fila, col): self.fila = fila self.columna = col self.Exp = Exp self.op = op def ejecutar(self, TS, Errores): tipo = self.Exp.ejecutar(TS, Errores) if self.op == '~': if tipo == TIPO_DATOS.INT or tipo == TIPO_DATOS.CHAR: ...
grafica.edge(padre, nombrehijo) if self.primero: grafica.node('NodeE1' + str(id(self)), label=(str(self.op))) grafica.edge(nombrehijo, 'NodeE1' + str(id(self))) self.Exp1.graficarasc(nombrehijo, grafica) else: self.Exp1.graficarasc(nombrehijo, grafica) ...
135
136
455
7
128
susanliss/tytus
parser/team19/BDTytus/AST/Expresiones.py
Python
unario
unario
394
435
394
394
bf040b6c199f52a295e452a445fb8da6bfa0d148
bigcode/the-stack
train
2ec6a4f4fb167b1d10999bb2
train
class
class bitabit(Node.Nodo): def __init__(self, Exp1, Exp2, op, fila, col): self.fila = fila self.columna = col self.Exp1 = Exp1 self.Exp2 = Exp2 self.op = op self.temporal = "" def ejecutar(self, TS, Errores): tipo1 = self.Exp1.ejecutar(TS, Errores) ...
class bitabit(Node.Nodo):
def __init__(self, Exp1, Exp2, op, fila, col): self.fila = fila self.columna = col self.Exp1 = Exp1 self.Exp2 = Exp2 self.op = op self.temporal = "" def ejecutar(self, TS, Errores): tipo1 = self.Exp1.ejecutar(TS, Errores) tipo2 = self.Exp2.ejecuta...
return simbolo.tipo def getC3D(self, TS): codigo = "" simbolo = TS.obtener(self.nombre) self.temporal = simbolo.posicion return codigo def graficarasc(self, padre, grafica): nombrehijo = 'Node' + str(id(self)) grafica.node(nombrehijo, label=('Exp')) gra...
134
135
452
7
127
susanliss/tytus
parser/team19/BDTytus/AST/Expresiones.py
Python
bitabit
bitabit
254
295
254
254
67d4b2b687663753ba0b3fa8ed47f14719e324ce
bigcode/the-stack
train
c89d53b865b3063ce3799aec
train
class
class incremento(Node.Nodo): def __init__(self, Exp1, op, primero, fila, col): self.fila = fila self.columna = col self.Exp1 = Exp1 self.primero = primero self.op = op def ejecutar(self, TS, Errores): tipo = self.Exp1.ejecutar(TS, Errores) if tipo == TIPO...
class incremento(Node.Nodo):
def __init__(self, Exp1, op, primero, fila, col): self.fila = fila self.columna = col self.Exp1 = Exp1 self.primero = primero self.op = op def ejecutar(self, TS, Errores): tipo = self.Exp1.ejecutar(TS, Errores) if tipo == TIPO_DATOS.INT or tipo == TIPO_DA...
.Exp2.temporal) return codigo def graficarasc(self, padre, grafica): nombrehijo = 'Node' + str(id(self)) grafica.node(nombrehijo, label=('Exp')) grafica.edge(padre, nombrehijo) if self.Exp1 is not None: self.Exp1.graficarasc(nombrehijo, grafica) grafica.n...
152
152
509
6
146
susanliss/tytus
parser/team19/BDTytus/AST/Expresiones.py
Python
incremento
incremento
341
391
341
341
a74c2adb718551007e16518869c09f3c5283979b
bigcode/the-stack
train
cf39f58eeac4b0d0133686e7
train
class
class Relacional(Node.Nodo): def __init__(self, Exp1, Exp2, op, fila, col): self.Exp1 = Exp1 self.Exp2 = Exp2 self.op = op self.fila = fila self.columna = col def ejecutar(self, TS, Errores): tipo1 = self.Exp1.ejecutar(TS, Errores) tipo2 = self.Exp2.ejecu...
class Relacional(Node.Nodo):
def __init__(self, Exp1, Exp2, op, fila, col): self.Exp1 = Exp1 self.Exp2 = Exp2 self.op = op self.fila = fila self.columna = col def ejecutar(self, TS, Errores): tipo1 = self.Exp1.ejecutar(TS, Errores) tipo2 = self.Exp2.ejecutar(TS, Errores) if ...
poral) return codigo def graficarasc(self, padre, grafica): nombrehijo = 'Node' + str(id(self)) grafica.node(nombrehijo, label=('Exp')) grafica.edge(padre, nombrehijo) if self.Exp1 is not None: self.Exp1.graficarasc(nombrehijo, grafica) grafica.node('Node...
150
150
502
7
143
susanliss/tytus
parser/team19/BDTytus/AST/Expresiones.py
Python
Relacional
Relacional
147
187
147
147
af520e5fa2ace745703fb3d0652821c5a37818d8
bigcode/the-stack
train
3720338b5acd6cc199ef7cea
train
class
class logica(Node.Nodo): def __init__(self, Exp1, Exp2, op, fila, col): self.fila = fila self.columna = col self.Exp1 = Exp1 self.Exp2 = Exp2 self.op = op def ejecutar(self, TS, Errores): tipo1 = self.Exp1.ejecutar(TS, Errores) tipo2 = self.Exp2.ejecutar(...
class logica(Node.Nodo):
def __init__(self, Exp1, Exp2, op, fila, col): self.fila = fila self.columna = col self.Exp1 = Exp1 self.Exp2 = Exp2 self.op = op def ejecutar(self, TS, Errores): tipo1 = self.Exp1.ejecutar(TS, Errores) tipo2 = self.Exp2.ejecutar(TS, Errores) if ...
def graficarasc(self, padre, grafica): nombrehijo = 'Node' + str(id(self)) grafica.node(nombrehijo, label=('Exp')) grafica.edge(padre, nombrehijo) if self.Exp1 is not None: self.Exp1.graficarasc(nombrehijo, grafica) grafica.node('NodeE1' + str(id(self)), label=(...
145
145
486
7
138
susanliss/tytus
parser/team19/BDTytus/AST/Expresiones.py
Python
logica
logica
298
338
298
298
df6572c5b10d3bff09b617c213173d79cdac5dcc
bigcode/the-stack
train
46025b84d781e310d76e43a7
train
class
class Climb(models.Model): FIVE = 5 SIX = 6 SEVEN = 7 EIGHT = 8 NINE = 9 TEN = 10 ELEVEN= 11 TWELVE= 12 THIRTEEN = 13 FOURTEEN = 14 DIFFICULTY = ( (FIVE, '5'), (SIX, '6'), (SEVEN, '7'), (EIGHT, '8'), (NINE, '9'), (TEN, '10'),...
class Climb(models.Model):
FIVE = 5 SIX = 6 SEVEN = 7 EIGHT = 8 NINE = 9 TEN = 10 ELEVEN= 11 TWELVE= 12 THIRTEEN = 13 FOURTEEN = 14 DIFFICULTY = ( (FIVE, '5'), (SIX, '6'), (SEVEN, '7'), (EIGHT, '8'), (NINE, '9'), (TEN, '10'), (ELEVEN, '11'), ...
from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User # Create your models here. class Climb(models.Model):
34
94
315
6
28
djstein/hci_final
hci/rockclimb/models.py
Python
Climb
Climb
7
51
7
8
9816825e004fce5d76170e80b40394de3b58e40d
bigcode/the-stack
train
0e72b4c0a8f8c84cc6274651
train
class
class Attempt(models.Model): climb = models.ForeignKey(Climb) date = models.DateField() attempt_notes = models.TextField(default="")
class Attempt(models.Model):
climb = models.ForeignKey(Climb) date = models.DateField() attempt_notes = models.TextField(default="")
models.ImageField(upload_to='img', blank=True) difficulty = models.IntegerField(choices=DIFFICULTY, default=FIVE) grade = models.CharField(max_length=1, choices=GRADE, default=A) notes = models.TextField(default="", blank=True) class Attempt(models.Model):
64
64
31
5
59
djstein/hci_final
hci/rockclimb/models.py
Python
Attempt
Attempt
53
56
53
53
9da08ca56721467ac8b53f7da613d5b42a9331dd
bigcode/the-stack
train
44d99b161ace2a684323c079
train
class
class DefaultConfig(object): AGORA_PATH = os.getenv('AGORA_PATH', os.path.join('/home', getpass.getuser(), 'agora')) # deprecated/check if unused AGORA_VERSION = '0.9' # standard: no trailing slashes anywhere in variables. # with protocol URL_BASE = "https://anagora.org" API_BASE = "https://...
class DefaultConfig(object):
AGORA_PATH = os.getenv('AGORA_PATH', os.path.join('/home', getpass.getuser(), 'agora')) # deprecated/check if unused AGORA_VERSION = '0.9' # standard: no trailing slashes anywhere in variables. # with protocol URL_BASE = "https://anagora.org" API_BASE = "https://api.anagora.org" #TODO c...
import os import getpass class DefaultConfig(object):
12
69
230
5
6
flancian/agora-server
app/config.py
Python
DefaultConfig
DefaultConfig
4
26
4
4
50cda01340499c3137b88685019c0e1e6d9cff7e
bigcode/the-stack
train
ae64de305ccada5ded03ee40
train
class
class ProductionConfig(DefaultConfig): # EXPERIMENTS ENABLE_CTZN = False ENABLE_STATS = True ENABLE_AUTO_PULL = True ENABLE_AUTO_STOA = False
class ProductionConfig(DefaultConfig): # EXPERIMENTS
ENABLE_CTZN = False ENABLE_STATS = True ENABLE_AUTO_PULL = True ENABLE_AUTO_STOA = False
in the DefaultConfig and then override in the right environment. ENABLE_CTZN = False ENABLE_STATS = False ENABLE_OBSIDIAN_ATTACHMENTS = False ENABLE_AUTO_PULL = False ENABLE_AUTO_STOA = False class ProductionConfig(DefaultConfig): # EXPERIMENTS
64
64
42
14
49
flancian/agora-server
app/config.py
Python
ProductionConfig
ProductionConfig
28
34
28
30
c90bcc1cbddbba3701a3e425b5c147c007d71119
bigcode/the-stack
train
8e1688186674a7768de74524
train
class
class DevelopmentConfig(DefaultConfig): URL_BASE = "http://dev.anagora.org" URI_BASE = "dev.anagora.org" API_BASE = "http://localhost:3000" # EXPERIMENTS ENABLE_CTZN = True ENABLE_STATS = True ENABLE_OBSIDIAN_ATTACHMENTS = True ENABLE_AUTO_PULL = True ENABLE_AUTO_STOA = True
class DevelopmentConfig(DefaultConfig):
URL_BASE = "http://dev.anagora.org" URI_BASE = "dev.anagora.org" API_BASE = "http://localhost:3000" # EXPERIMENTS ENABLE_CTZN = True ENABLE_STATS = True ENABLE_OBSIDIAN_ATTACHMENTS = True ENABLE_AUTO_PULL = True ENABLE_AUTO_STOA = True
ENABLE_AUTO_PULL = False ENABLE_AUTO_STOA = False class ProductionConfig(DefaultConfig): # EXPERIMENTS ENABLE_CTZN = False ENABLE_STATS = True ENABLE_AUTO_PULL = True ENABLE_AUTO_STOA = False class DevelopmentConfig(DefaultConfig):
64
64
87
6
57
flancian/agora-server
app/config.py
Python
DevelopmentConfig
DevelopmentConfig
36
47
36
36
486cd197fa66147ca4f9682c81856223d31ccc51
bigcode/the-stack
train
934165d4fb4301b9e9dff8c5
train
function
@pytest.mark.rigetti_integration def test_bell_circuit_through_service(bell_circuit: cirq.Circuit) -> None: """test that RigettiQCSService can run a basic bell circuit on the QVM and return an accurate ``cirq.study.Result``. """ qc = get_qc('9q-square', as_qvm=True) service = RigettiQCSService( ...
@pytest.mark.rigetti_integration def test_bell_circuit_through_service(bell_circuit: cirq.Circuit) -> None:
"""test that RigettiQCSService can run a basic bell circuit on the QVM and return an accurate ``cirq.study.Result``. """ qc = get_qc('9q-square', as_qvm=True) service = RigettiQCSService( quantum_computer=qc, ) # set the seed so we get a deterministic set of results. qvm = cast(...
-copyright-notice from typing import cast import pytest import cirq from pyquil import get_qc from pyquil.api import QVM from cirq_rigetti import RigettiQCSService @pytest.mark.rigetti_integration def test_bell_circuit_through_service(bell_circuit: cirq.Circuit) -> None:
76
76
256
30
45
dabacon/Cirq
cirq-rigetti/cirq_rigetti/service_bell_circuit_test.py
Python
test_bell_circuit_through_service
test_bell_circuit_through_service
10
36
10
11
d65335293a5feeb5c520fc27e869c2b9440f6b02
bigcode/the-stack
train
57cc5ccb4474d9a10227dd69
train
class
class Test_multi_core(unittest.TestCase): def setUp(self): ql.initialize() # uses defaults of options in mapper branch except for output_dir and for maptiebreak ql.set_option('output_dir', output_dir) # this uses output_dir set above ql.set_option('maptiebreak', 'first') #...
class Test_multi_core(unittest.TestCase):
def setUp(self): ql.initialize() # uses defaults of options in mapper branch except for output_dir and for maptiebreak ql.set_option('output_dir', output_dir) # this uses output_dir set above ql.set_option('maptiebreak', 'first') # this makes behavior deterministic to cmp w...
# tests for multi core # # assumes config files: test_multi_core_4x4_full.json # from openql import openql as ql import os import unittest from utils import file_compare curdir = os.path.dirname(os.path.realpath(__file__)) output_dir = os.path.join(curdir, 'test_output') class Test_multi_core(unittest.TestCase):
79
256
1,840
8
71
TariqTNO/OpenQL
tests/test_multi_core.py
Python
Test_multi_core
Test_multi_core
15
190
15
16
c106bc4f4ecbfc35d97c4510dfa68b97f9f28d35
bigcode/the-stack
train
b208f2fc84cf19d1b5c09b4f
train
class
class CategoricalGibbsMetropolis(ArrayStep): """A Metropolis-within-Gibbs step method optimized for categorical variables. This step method works for Bernoulli variables as well, but it is not optimized for them, like BinaryGibbsMetropolis is. Step method supports two types of proposals: A uniform prop...
class CategoricalGibbsMetropolis(ArrayStep):
"""A Metropolis-within-Gibbs step method optimized for categorical variables. This step method works for Bernoulli variables as well, but it is not optimized for them, like BinaryGibbsMetropolis is. Step method supports two types of proposals: A uniform proposal and a proportional proposal, which w...
logp(q) q.data[idx], accepted = metrop_select(logp_prop - logp_curr, q.data[idx], curr_val) if accepted: logp_curr = logp_prop return q @staticmethod def competence(var): """ BinaryMetropolis is only suitable for Bernoulli an...
256
256
1,369
11
244
percevalve/pymc
pymc/step_methods/metropolis.py
Python
CategoricalGibbsMetropolis
CategoricalGibbsMetropolis
482
634
482
482
5b912337362dff1affaf89c858754a4875b83325
bigcode/the-stack
train
d3ed5e3e0d51b765454a057e
train
class
class DEMetropolisZ(ArrayStepShared): """ Adaptive Differential Evolution Metropolis sampling step that uses the past to inform jumps. Parameters ---------- lamb: float Lambda parameter of the DE proposal mechanism. Defaults to 2.38 / sqrt(2 * ndim) vars: list List of variables ...
class DEMetropolisZ(ArrayStepShared):
""" Adaptive Differential Evolution Metropolis sampling step that uses the past to inform jumps. Parameters ---------- lamb: float Lambda parameter of the DE proposal mechanism. Defaults to 2.38 / sqrt(2 * ndim) vars: list List of variables for sampler S: standard deviation ...
# select two other chains ir1, ir2 = np.random.choice(self.other_chains, 2, replace=False) r1 = DictToArrayBijection.map(self.population[ir1]) r2 = DictToArrayBijection.map(self.population[ir2]) # propose a jump q = floatX(q0 + self.lamb * (r1.data - r2.data) + epsilon) ...
256
256
1,548
9
246
percevalve/pymc
pymc/step_methods/metropolis.py
Python
DEMetropolisZ
DEMetropolisZ
785
974
785
785
989e5e047b14709911f410bdd670f71d4dff4788
bigcode/the-stack
train
b67e3942a4e45d70c1083dd4
train
class
class NormalProposal(Proposal): def __call__(self): return nr.normal(scale=self.s)
class NormalProposal(Proposal):
def __call__(self): return nr.normal(scale=self.s)
"NormalProposal", "CauchyProposal", "LaplaceProposal", "PoissonProposal", "MultivariateNormalProposal", ] # Available proposal distributions for Metropolis class Proposal: def __init__(self, s): self.s = s class NormalProposal(Proposal):
64
64
21
6
57
percevalve/pymc
pymc/step_methods/metropolis.py
Python
NormalProposal
NormalProposal
57
59
57
57
0fc09e88b6ec270921bf8a6679873bcfceacd437
bigcode/the-stack
train
0426912c377e66e1be5da9c9
train
function
def delta_logp(point, logp, vars, shared): [logp0], inarray0 = pm.join_nonshared_inputs(point, [logp], vars, shared) tensor_type = inarray0.type inarray1 = tensor_type("inarray1") logp1 = pm.CallableTensor(logp0)(inarray1) f = compile_rv_inplace([inarray1, inarray0], logp1 - logp0) f.trust_in...
def delta_logp(point, logp, vars, shared):
[logp0], inarray0 = pm.join_nonshared_inputs(point, [logp], vars, shared) tensor_type = inarray0.type inarray1 = tensor_type("inarray1") logp1 = pm.CallableTensor(logp0)(inarray1) f = compile_rv_inplace([inarray1, inarray0], logp1 - logp0) f.trust_input = True return f
- 1) if candidate >= excluded: candidate += 1 return candidate def softmax(x): e_x = np.exp(x - np.max(x)) return e_x / np.sum(e_x, axis=0) def delta_logp(point, logp, vars, shared):
64
64
113
13
51
percevalve/pymc
pymc/step_methods/metropolis.py
Python
delta_logp
delta_logp
989
999
989
989
2ec386639b4d568cb17f86a3fb06d97ae9acc90b
bigcode/the-stack
train
13ddbf1c5e251047da88352e
train
class
class MultivariateNormalProposal(Proposal): def __init__(self, s): n, m = s.shape if n != m: raise ValueError("Covariance matrix is not symmetric.") self.n = n self.chol = scipy.linalg.cholesky(s, lower=True) def __call__(self, num_draws=None): if num_draws i...
class MultivariateNormalProposal(Proposal):
def __init__(self, s): n, m = s.shape if n != m: raise ValueError("Covariance matrix is not symmetric.") self.n = n self.chol = scipy.linalg.cholesky(s, lower=True) def __call__(self, num_draws=None): if num_draws is not None: b = np.random.randn(...
return (nr.standard_exponential(size=size) - nr.standard_exponential(size=size)) * self.s class PoissonProposal(Proposal): def __call__(self): return nr.poisson(lam=self.s, size=np.size(self.s)) - self.s class MultivariateNormalProposal(Proposal):
64
64
132
8
55
percevalve/pymc
pymc/step_methods/metropolis.py
Python
MultivariateNormalProposal
MultivariateNormalProposal
83
97
83
83
f11b3b3ffbf9b4852290ea4dd59c6db3cf9a5766
bigcode/the-stack
train
c855902d06d7a79994665847
train
class
class UniformProposal(Proposal): def __call__(self): return nr.uniform(low=-self.s, high=self.s, size=len(self.s))
class UniformProposal(Proposal):
def __call__(self): return nr.uniform(low=-self.s, high=self.s, size=len(self.s))
issonProposal", "MultivariateNormalProposal", ] # Available proposal distributions for Metropolis class Proposal: def __init__(self, s): self.s = s class NormalProposal(Proposal): def __call__(self): return nr.normal(scale=self.s) class UniformProposal(Proposal):
64
64
31
6
58
percevalve/pymc
pymc/step_methods/metropolis.py
Python
UniformProposal
UniformProposal
62
64
62
62
a481cb1654a0cff68278e6e2cf33499fa04db680
bigcode/the-stack
train
11a654d0ce795aee0bf3294e
train
class
class CauchyProposal(Proposal): def __call__(self): return nr.standard_cauchy(size=np.size(self.s)) * self.s
class CauchyProposal(Proposal):
def __call__(self): return nr.standard_cauchy(size=np.size(self.s)) * self.s
.s = s class NormalProposal(Proposal): def __call__(self): return nr.normal(scale=self.s) class UniformProposal(Proposal): def __call__(self): return nr.uniform(low=-self.s, high=self.s, size=len(self.s)) class CauchyProposal(Proposal):
64
64
32
8
56
percevalve/pymc
pymc/step_methods/metropolis.py
Python
CauchyProposal
CauchyProposal
67
69
67
67
8b3a9c31c89cde3d81ed75e576d832655da46d3e
bigcode/the-stack
train
f51c543621beea7e42435b13
train
class
class BinaryMetropolis(ArrayStep): """Metropolis-Hastings optimized for binary variables Parameters ---------- vars: list List of value variables for sampler scaling: scalar or array Initial scale factor for proposal. Defaults to 1. tune: bool Flag for tuning. Defaults t...
class BinaryMetropolis(ArrayStep):
"""Metropolis-Hastings optimized for binary variables Parameters ---------- vars: list List of value variables for sampler scaling: scalar or array Initial scale factor for proposal. Defaults to 1. tune: bool Flag for tuning. Defaults to True. tune_interval: int ...
<0.05 x 0.5 <0.2 x 0.9 >0.5 x 1.1 >0.75 x 2 >0.95 x 10 """ if acc_rate < 0.001: # reduce by 90 percent return scale * 0.1 elif acc_rate < 0.05: # reduce by 50 percent return scale * 0.5 elif acc_rate < 0.2: ...
226
226
754
7
218
percevalve/pymc
pymc/step_methods/metropolis.py
Python
BinaryMetropolis
BinaryMetropolis
287
386
287
287
a9071bb5ad9a20dbedbfaba5e268e3cbc6002583
bigcode/the-stack
train
0b2d9a7de279b277e7f6fb16
train
class
class Proposal: def __init__(self, s): self.s = s
class Proposal:
def __init__(self, s): self.s = s
ropolis", "BinaryGibbsMetropolis", "CategoricalGibbsMetropolis", "NormalProposal", "CauchyProposal", "LaplaceProposal", "PoissonProposal", "MultivariateNormalProposal", ] # Available proposal distributions for Metropolis class Proposal:
64
64
18
3
60
percevalve/pymc
pymc/step_methods/metropolis.py
Python
Proposal
Proposal
52
54
52
52
f9717f5c9534337fd49207d4bca9852cffc2442f
bigcode/the-stack
train
d2c3cd1bdbabc587bc4da5eb
train
class
class DEMetropolis(PopulationArrayStepShared): """ Differential Evolution Metropolis sampling step. Parameters ---------- lamb: float Lambda parameter of the DE proposal mechanism. Defaults to 2.38 / sqrt(2 * ndim) vars: list List of variables for sampler S: standard deviati...
class DEMetropolis(PopulationArrayStepShared):
""" Differential Evolution Metropolis sampling step. Parameters ---------- lamb: float Lambda parameter of the DE proposal mechanism. Defaults to 2.38 / sqrt(2 * ndim) vars: list List of variables for sampler S: standard deviation or covariance matrix Some measure of...
accept_ratio: q.data[dim] = given_cat return logp_curr q.data[dim] = proposed_cat return log_probs[proposed_cat] @staticmethod def competence(var): """ CategoricalGibbsMetropolis is only suitable for Bernoulli and Categorical variables. "...
256
256
1,155
11
244
percevalve/pymc
pymc/step_methods/metropolis.py
Python
DEMetropolis
DEMetropolis
637
782
637
637
baf9c47b8e4985cd1436b4eb43a05bf3d0c44722
bigcode/the-stack
train
11c3719e21803d0808b639bb
train
function
def softmax(x): e_x = np.exp(x - np.max(x)) return e_x / np.sum(e_x, axis=0)
def softmax(x):
e_x = np.exp(x - np.max(x)) return e_x / np.sum(e_x, axis=0)
if var.dtype in pm.discrete_types: return Competence.INCOMPATIBLE return Competence.COMPATIBLE def sample_except(limit, excluded): candidate = nr.choice(limit - 1) if candidate >= excluded: candidate += 1 return candidate def softmax(x):
64
64
31
5
58
percevalve/pymc
pymc/step_methods/metropolis.py
Python
softmax
softmax
984
986
984
984
eff7f72a0bbf7f2dbbf50e8b95ae4ac60703bb75
bigcode/the-stack
train
53d6b6db2e287a70830422f4
train
function
def tune(scale, acc_rate): """ Tunes the scaling parameter for the proposal distribution according to the acceptance rate over the last tune_interval: Rate Variance adaptation ---- ------------------- <0.001 x 0.1 <0.05 x 0.5 <0.2 x 0.9 >0.5 x ...
def tune(scale, acc_rate):
""" Tunes the scaling parameter for the proposal distribution according to the acceptance rate over the last tune_interval: Rate Variance adaptation ---- ------------------- <0.001 x 0.1 <0.05 x 0.5 <0.2 x 0.9 >0.5 x 1.1 >0.75 x 2 ...
tune": self.tune, "scaling": self.scaling, "accept": np.exp(accept), "accepted": accepted, } q_new = RaveledVars(q_new, point_map_info) return q_new, [stats] @staticmethod def competence(var, has_grad): return Competence.COMPATIBLE def tune(...
82
82
275
7
74
percevalve/pymc
pymc/step_methods/metropolis.py
Python
tune
tune
250
284
250
250
0800f5ca027d49ad6895063b4fc76f2d6cdcd3e4
bigcode/the-stack
train
cacb3e19a5f56de1780f8211
train
class
class PoissonProposal(Proposal): def __call__(self): return nr.poisson(lam=self.s, size=np.size(self.s)) - self.s
class PoissonProposal(Proposal):
def __call__(self): return nr.poisson(lam=self.s, size=np.size(self.s)) - self.s
_cauchy(size=np.size(self.s)) * self.s class LaplaceProposal(Proposal): def __call__(self): size = np.size(self.s) return (nr.standard_exponential(size=size) - nr.standard_exponential(size=size)) * self.s class PoissonProposal(Proposal):
64
64
34
7
56
percevalve/pymc
pymc/step_methods/metropolis.py
Python
PoissonProposal
PoissonProposal
78
80
78
78
e66060bd094a1deb3e7affaff3b9a8ce7d4956b2
bigcode/the-stack
train
cebdfcd97408a7f783fbcdb2
train
class
class LaplaceProposal(Proposal): def __call__(self): size = np.size(self.s) return (nr.standard_exponential(size=size) - nr.standard_exponential(size=size)) * self.s
class LaplaceProposal(Proposal):
def __call__(self): size = np.size(self.s) return (nr.standard_exponential(size=size) - nr.standard_exponential(size=size)) * self.s
def __call__(self): return nr.uniform(low=-self.s, high=self.s, size=len(self.s)) class CauchyProposal(Proposal): def __call__(self): return nr.standard_cauchy(size=np.size(self.s)) * self.s class LaplaceProposal(Proposal):
64
64
44
7
56
percevalve/pymc
pymc/step_methods/metropolis.py
Python
LaplaceProposal
LaplaceProposal
72
75
72
72
166516d9a63020c4a417c82d410214530da65462
bigcode/the-stack
train
be40de582275b06886eb2ce8
train
function
def sample_except(limit, excluded): candidate = nr.choice(limit - 1) if candidate >= excluded: candidate += 1 return candidate
def sample_except(limit, excluded):
candidate = nr.choice(limit - 1) if candidate >= excluded: candidate += 1 return candidate
self._history = self._history[n_drop:] return super().stop_tuning() @staticmethod def competence(var, has_grad): if var.dtype in pm.discrete_types: return Competence.INCOMPATIBLE return Competence.COMPATIBLE def sample_except(limit, excluded):
64
64
33
7
56
percevalve/pymc
pymc/step_methods/metropolis.py
Python
sample_except
sample_except
977
981
977
977
5e1588a753339f7b1d04e766d3f09093c167a313
bigcode/the-stack
train
f3ee2c0d5bf817c0a83b258a
train
class
class Metropolis(ArrayStepShared): """Metropolis-Hastings sampling step""" name = "metropolis" default_blocked = False generates_stats = True stats_dtypes = [ { "accept": np.float64, "accepted": bool, "tune": bool, "scaling": np.float64, ...
class Metropolis(ArrayStepShared):
"""Metropolis-Hastings sampling step""" name = "metropolis" default_blocked = False generates_stats = True stats_dtypes = [ { "accept": np.float64, "accepted": bool, "tune": bool, "scaling": np.float64, } ] def __init__( ...
.s, size=len(self.s)) class CauchyProposal(Proposal): def __call__(self): return nr.standard_cauchy(size=np.size(self.s)) * self.s class LaplaceProposal(Proposal): def __call__(self): size = np.size(self.s) return (nr.standard_exponential(size=size) - nr.standard_exponential(size=siz...
256
256
1,069
7
249
percevalve/pymc
pymc/step_methods/metropolis.py
Python
Metropolis
Metropolis
100
247
100
100
e82a007350b93bd59816e3247ec788d5f4d20a01
bigcode/the-stack
train
1a1d1da93c4107cbfb310a3c
train
class
class BinaryGibbsMetropolis(ArrayStep): """A Metropolis-within-Gibbs step method optimized for binary variables Parameters ---------- vars: list List of value variables for sampler order: list or 'random' List of integers indicating the Gibbs update order e.g., [0, 2, 1, ......
class BinaryGibbsMetropolis(ArrayStep):
"""A Metropolis-within-Gibbs step method optimized for binary variables Parameters ---------- vars: list List of value variables for sampler order: list or 'random' List of integers indicating the Gibbs update order e.g., [0, 2, 1, ...]. Default is random transit_p: floa...
Vars(q_new, point_map_info) return q_new, [stats] @staticmethod def competence(var): """ BinaryMetropolis is only suitable for binary (bool) and Categorical variables with k=1. """ distribution = getattr(var.owner, "op", None) if isinstance(distribution...
225
225
751
10
214
percevalve/pymc
pymc/step_methods/metropolis.py
Python
BinaryGibbsMetropolis
BinaryGibbsMetropolis
389
479
389
389
2443f56d82657acfe4820718ad90ffbd59732d36
bigcode/the-stack
train
e5abd032c7c264fa91bb8d35
train
function
def get_licenses_by_key(): """ Return a mapping of license key -> license object. """ global _LICENSES_BY_KEY if not _LICENSES_BY_KEY : _LICENSES_BY_KEY = load_licenses() return _LICENSES_BY_KEY
def get_licenses_by_key():
""" Return a mapping of license key -> license object. """ global _LICENSES_BY_KEY if not _LICENSES_BY_KEY : _LICENSES_BY_KEY = load_licenses() return _LICENSES_BY_KEY
if not exists(location): text = u'' else: with codecs.open(location, encoding='utf-8') as f: text = f.read() return text # cache license objects in a map by license key _LICENSES_BY_KEY = {} def get_licenses_by_key():
63
64
58
7
56
pombredanne/scancode-toolkit
src/licensedcode/models.py
Python
get_licenses_by_key
get_licenses_by_key
197
204
197
197
3d2c65f8e1eac864c20e9b25a5aa6473f275105b
bigcode/the-stack
train
97d94d34241ad6c56b7baf6d
train
class
class License(object): """ A license consists of these files, where <key> is the license key: - <key>.yml : the license data in YAML - <key>.LICENSE: the license text - <key>.SPDX: the SPDX license text """ def __init__(self, key=None, src_dir=licenses_data_dir): # unique...
class License(object):
""" A license consists of these files, where <key> is the license key: - <key>.yml : the license data in YAML - <key>.LICENSE: the license text - <key>.SPDX: the SPDX license text """ def __init__(self, key=None, src_dir=licenses_data_dir): # unique key: lower case ASCII ...
with ScanCode and provided on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. No content created from # ScanCode should be considered or used as legal advice. Consult an Attorney # for any legal advice. # ScanCode is a free software code scanning tool from nexB Inc. and...
256
256
936
4
252
pombredanne/scancode-toolkit
src/licensedcode/models.py
Python
License
License
58
190
58
58
b9046dee31933899930237390429d8cb3a460033
bigcode/the-stack
train
ee312ea4673101cb06e12a26
train
function
def get_all_rules(_use_cache=False): """ Return an iterable of all unique rules loaded from licenses and rules files. """ rules = chain(get_rules_from_license_texts(), load_rules()) unique = unique_rules(rules) verify_rules_license(unique) return unique
def get_all_rules(_use_cache=False):
""" Return an iterable of all unique rules loaded from licenses and rules files. """ rules = chain(get_rules_from_license_texts(), load_rules()) unique = unique_rules(rules) verify_rules_license(unique) return unique
if unknown_files: print(unknown_files) files = '\n'.join(sorted(unknown_files)) msg = 'Unknown files in rule directory: %(rule_dir)r\n%(files)s' raise Exception(msg % locals()) return rules def get_all_rules(_use_cache=False):
64
64
60
9
54
pombredanne/scancode-toolkit
src/licensedcode/models.py
Python
get_all_rules
get_all_rules
401
408
401
401
692def8e967223ae96cef1d9205aefd9973b1927
bigcode/the-stack
train
fd25a089e402fc32dd08b188
train
class
class Rule(object): """ Base class for detection rules. """ def __init__(self, data_file=None, text_file=None, licenses=None, license_choice=False, template=False, notes=None): self.licenses = licenses or [] self.license_choice = license_choice ...
class Rule(object):
""" Base class for detection rules. """ def __init__(self, data_file=None, text_file=None, licenses=None, license_choice=False, template=False, notes=None): self.licenses = licenses or [] self.license_choice = license_choice self.notes = notes ...
in licenses_list.items(): text = license_obj.text spdx_text = license_obj.spdx_license_text if text: yield Rule( text_file=join(license_obj.src_dir, license_obj.text_file), licenses=[license_key], ) if spdx_text: yield...
192
192
640
4
188
pombredanne/scancode-toolkit
src/licensedcode/models.py
Python
Rule
Rule
276
366
276
276
d73522f187b62f5a2fbccda8b385625f1f290fba
bigcode/the-stack
train
da6f82fad4de3c6542e40a4e
train
function
def load_licenses(license_dir=licenses_data_dir): """ Return a mapping of key -> license objects, loaded from license files. """ licenses = {} # TODO: add check for unknown files for top, _, files in os.walk(license_dir): for yfile in files: if not yfile.endswith('.yml'): ...
def load_licenses(license_dir=licenses_data_dir):
""" Return a mapping of key -> license objects, loaded from license files. """ licenses = {} # TODO: add check for unknown files for top, _, files in os.walk(license_dir): for yfile in files: if not yfile.endswith('.yml'): continue key = yfile.rep...
load_licenses() return _LICENSES_BY_KEY def get_license(key): """ Return a license object for this key. Raise a KeyError if the license does not exists. """ return get_licenses_by_key()[key] def load_licenses(license_dir=licenses_data_dir):
64
64
124
12
52
pombredanne/scancode-toolkit
src/licensedcode/models.py
Python
load_licenses
load_licenses
215
231
215
215
382a76e974741b7653710c4769a3b39e532b685b
bigcode/the-stack
train
52c6e4130fa2b3ace0defd5b
train
function
def load_rules(rule_dir=rules_data_dir): """ Return a list of rules, loaded from rules files. FIXME: return an iterable instead """ rules = [] seen_files = set() processed_files = set() for top, _, files in os.walk(rule_dir): for yfile in files: if yfile.endswith('.y...
def load_rules(rule_dir=rules_data_dir):
""" Return a list of rules, loaded from rules files. FIXME: return an iterable instead """ rules = [] seen_files = set() processed_files = set() for top, _, files in os.walk(rule_dir): for yfile in files: if yfile.endswith('.yml'): data_file = join(to...
', []) self.license_choice = data.get('license_choice', False) self.template = data.get('template', False) # these are purely informational and not used at run time if load_notes: self.notes = data.get('notes') return self def load_rules(rule_dir=rules_data_dir):
68
68
228
10
57
pombredanne/scancode-toolkit
src/licensedcode/models.py
Python
load_rules
load_rules
369
398
369
369
77195bb1ce4fd0c2724b40007d2d36ee4161f22d
bigcode/the-stack
train
1342bc697467beb8aa4cf150
train
function
def get_rules_from_license_texts(licenses_list=None): """ Return an iterable of rules built from license texts and spdx texts from in the `licenses_list` license objects iterable. Load the reference list list from disk if list_list is not provided. """ if not licenses_list: licenses_lis...
def get_rules_from_license_texts(licenses_list=None):
""" Return an iterable of rules built from license texts and spdx texts from in the `licenses_list` license objects iterable. Load the reference list list from disk if list_list is not provided. """ if not licenses_list: licenses_list = get_licenses_by_key() for license_key, licens...
yml'): continue key = yfile.replace('.yml', '') yfile = join(top, yfile) src_dir = os.path.dirname(yfile) licenses[key] = License(key, src_dir) return licenses def get_rules_from_license_texts(licenses_list=None):
64
64
172
12
51
pombredanne/scancode-toolkit
src/licensedcode/models.py
Python
get_rules_from_license_texts
get_rules_from_license_texts
234
257
234
234
646b8c151a8ac08a7b4187eaea7b314b89465e1f
bigcode/the-stack
train
d6bdb7529c3ec12fb45e9e66
train
function
def verify_rules_license(rules): """ Ensure that every rules license is a valid license. Raise a MissingLicense exception with a message containing the list of rule files that do not have a corresponding existing license. """ invalid_rules = defaultdict(list) for rule in rules: for k...
def verify_rules_license(rules):
""" Ensure that every rules license is a valid license. Raise a MissingLicense exception with a message containing the list of rule files that do not have a corresponding existing license. """ invalid_rules = defaultdict(list) for rule in rules: for key in rule.licenses: ...
Return an iterable of all unique rules loaded from licenses and rules files. """ rules = chain(get_rules_from_license_texts(), load_rules()) unique = unique_rules(rules) verify_rules_license(unique) return unique class MissingLicense(Exception): pass def verify_rules_license(rules):
64
64
154
7
56
pombredanne/scancode-toolkit
src/licensedcode/models.py
Python
verify_rules_license
verify_rules_license
415
432
415
415
8ce52f50698e0c7e39e16212ce55f9a32616f472
bigcode/the-stack
train
c44ce008cf142b2cf05cd04c
train
function
def rule_identifier(rule): """ Return a string used to compare similar rules. """ comparable = rule.text.strip().lower().split() comparable.append(repr(rule.license_choice)) comparable.append(repr(rule.template)) comparable.extend(sorted(rule.licenses)) return u''.join([t for t in compar...
def rule_identifier(rule):
""" Return a string used to compare similar rules. """ comparable = rule.text.strip().lower().split() comparable.append(repr(rule.license_choice)) comparable.append(repr(rule.template)) comparable.extend(sorted(rule.licenses)) return u''.join([t for t in comparable if t])
: return an iterable instead """ seen = set() uniques = [] for rule in rules: ridt = rule_identifier(rule) if ridt in seen: continue else: seen.add(ridt) uniques.append(rule) return uniques def rule_identifier(rule):
64
64
70
5
58
pombredanne/scancode-toolkit
src/licensedcode/models.py
Python
rule_identifier
rule_identifier
452
460
452
452
59c43a77949ac69f6cb8d36edddc41dae61de93b
bigcode/the-stack
train
861916bf9eb5066eb16d0613
train
class
class MissingLicense(Exception): pass
class MissingLicense(Exception):
pass
get_all_rules(_use_cache=False): """ Return an iterable of all unique rules loaded from licenses and rules files. """ rules = chain(get_rules_from_license_texts(), load_rules()) unique = unique_rules(rules) verify_rules_license(unique) return unique class MissingLicense(Exception):
64
64
8
5
58
pombredanne/scancode-toolkit
src/licensedcode/models.py
Python
MissingLicense
MissingLicense
411
412
411
411
a4897082eda020cf30e42a183bff518f3f8fd61a
bigcode/the-stack
train
09ee9bcdf74141dee1a0e194
train
function
def get_tokens(location, template): """ Return a list of tokens from a from a file at location using the tokenizer function. """ location = os.path.abspath(location) if not exists(location): return [] tokenizr = template_tknzr if template else text_tknzr lines = analysis.unicode...
def get_tokens(location, template):
""" Return a list of tokens from a from a file at location using the tokenizer function. """ location = os.path.abspath(location) if not exists(location): return [] tokenizr = template_tknzr if template else text_tknzr lines = analysis.unicode_text_lines(location) return lis...
=[license_key], ) if spdx_text: yield Rule( text_file=join(license_obj.src_dir, license_obj.spdx_file), licenses=[license_key], ) text_tknzr, template_tknzr, _ = index.tokenizers() def get_tokens(location, template):
64
64
81
7
57
pombredanne/scancode-toolkit
src/licensedcode/models.py
Python
get_tokens
get_tokens
262
273
262
262
87376b0281bd4284e9d0845c75f899125539233a
bigcode/the-stack
train
62f603c458f5ca57e6f9248a
train
function
def get_license(key): """ Return a license object for this key. Raise a KeyError if the license does not exists. """ return get_licenses_by_key()[key]
def get_license(key):
""" Return a license object for this key. Raise a KeyError if the license does not exists. """ return get_licenses_by_key()[key]
} def get_licenses_by_key(): """ Return a mapping of license key -> license object. """ global _LICENSES_BY_KEY if not _LICENSES_BY_KEY : _LICENSES_BY_KEY = load_licenses() return _LICENSES_BY_KEY def get_license(key):
64
64
40
5
58
pombredanne/scancode-toolkit
src/licensedcode/models.py
Python
get_license
get_license
207
212
207
207
0a866d295782400540c2b8440e4754b66ed32c9d
bigcode/the-stack
train
c21138018ff1eaab3c62ae82
train
function
def unique_rules(rules): """ Return a list of unique rules. FIXME: return an iterable instead """ seen = set() uniques = [] for rule in rules: ridt = rule_identifier(rule) if ridt in seen: continue else: seen.add(ridt) uniques.appen...
def unique_rules(rules):
""" Return a list of unique rules. FIXME: return an iterable instead """ seen = set() uniques = [] for rule in rules: ridt = rule_identifier(rule) if ridt in seen: continue else: seen.add(ridt) uniques.append(rule) return unique...
invalid_rules: invalid_rules = (data_file + ': ' + ' '.join(keys) for data_file, keys in invalid_rules.iteritems()) msg = 'Rules data file with missing licenses:\n' + '\n'.join(invalid_rules) raise MissingLicense(msg) def unique_rules(rules):
64
64
77
6
58
pombredanne/scancode-toolkit
src/licensedcode/models.py
Python
unique_rules
unique_rules
435
449
435
435
86fe7f5d85fdb4e6a30843547d88b70488c51fd3
bigcode/the-stack
train
6fb837cf73ae28d6f98a2713
train
class
@resource("/v1/repository/<apirepopath:repository>/trigger/") @path_param("repository", "The full path of the repository. e.g. namespace/name") class BuildTriggerList(RepositoryParamResource): """ Resource for listing repository build triggers. """ @require_repo_admin @disallow_for_app_repositories @ni...
@resource("/v1/repository/<apirepopath:repository>/trigger/") @path_param("repository", "The full path of the repository. e.g. namespace/name") class BuildTriggerList(RepositoryParamResource):
""" Resource for listing repository build triggers. """ @require_repo_admin @disallow_for_app_repositories @nickname("listBuildTriggers") def get(self, namespace_name, repo_name): """ List the triggers for the specified repository. """ triggers = model.build.list_build_triggers(name...
) except model.InvalidBuildTriggerException: raise NotFound() return trigger @resource("/v1/repository/<apirepopath:repository>/trigger/") @path_param("repository", "The full path of the repository. e.g. namespace/name") class BuildTriggerList(RepositoryParamResource):
64
64
136
46
17
dongboyan77/quay
endpoints/api/trigger.py
Python
BuildTriggerList
BuildTriggerList
63
74
63
65
f1a502651a3cac084626a31bb6ca398a70d5eb3e
bigcode/the-stack
train
e1302d54b9dd52d3157f156e
train
function
def get_trigger(trigger_uuid): try: trigger = model.build.get_build_trigger(trigger_uuid) except model.InvalidBuildTriggerException: raise NotFound() return trigger
def get_trigger(trigger_uuid):
try: trigger = model.build.get_build_trigger(trigger_uuid) except model.InvalidBuildTriggerException: raise NotFound() return trigger
Logger(__name__) def _prepare_webhook_url(scheme, username, password, hostname, path): auth_hostname = "%s:%s@%s" % (username, password, hostname) return urlunparse((scheme, auth_hostname, path, "", "", "")) def get_trigger(trigger_uuid):
64
64
37
6
58
dongboyan77/quay
endpoints/api/trigger.py
Python
get_trigger
get_trigger
55
60
55
55
6a4db24d20d035507396af5deca8a8519a8a9929
bigcode/the-stack
train
06b0b343821471857f5cc5fa
train
class
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/namespaces") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") @internal_only class BuildTriggerSourceNamespaces(RepositoryParamResource): """ Custom...
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/namespaces") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") @internal_only class BuildTriggerSourceNamespaces(RepositoryParamResource):
""" Custom verb to fetch the list of namespaces (orgs, projects, etc) for the trigger config. """ @require_repo_admin @disallow_for_app_repositories @nickname("listTriggerBuildSourceNamespaces") def get(self, namespace_name, repo_name, trigger_uuid): """ List the build sources for the trigg...
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/namespaces") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") @internal_only class BuildTriggerSourceNamespaces(RepositoryParamResource):
72
67
224
72
0
dongboyan77/quay
endpoints/api/trigger.py
Python
BuildTriggerSourceNamespaces
BuildTriggerSourceNamespaces
538
561
538
542
2da3eb012b05b2234c0e8ccd26ae17ee397add32
bigcode/the-stack
train
7e57398c29642e88747a5b92
train
class
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/fields/<field_name>") @internal_only class BuildTriggerFieldValues(RepositoryParamResource): """ Custom verb to fetch a values list for a particular field name. """ @require_repo_admin @disallow_for_app_repositories @disallow_for...
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/fields/<field_name>") @internal_only class BuildTriggerFieldValues(RepositoryParamResource):
""" Custom verb to fetch a values list for a particular field name. """ @require_repo_admin @disallow_for_app_repositories @disallow_for_non_normal_repositories @nickname("listTriggerFieldValues") def post(self, namespace_name, repo_name, trigger_uuid, field_name): """ List the field va...
{"builds": [build_status_view(bld) for bld in builds]} FIELD_VALUE_LIMIT = 30 @resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/fields/<field_name>") @internal_only class BuildTriggerFieldValues(RepositoryParamResource):
64
64
204
39
24
dongboyan77/quay
endpoints/api/trigger.py
Python
BuildTriggerFieldValues
BuildTriggerFieldValues
469
492
469
471
a143f789557a24f4e08b0b756f1f5f4e9a00d1c5
bigcode/the-stack
train
80c0e3fd43a0e1f9c78d648c
train
class
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") class BuildTrigger(RepositoryParamResource): """ Resource for managing specific build triggers. "...
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") class BuildTrigger(RepositoryParamResource):
""" Resource for managing specific build triggers. """ schemas = { "UpdateTrigger": { "type": "object", "description": "Options for updating a build trigger", "required": ["enabled",], "properties": { "enabled": { "type...
repository", "The full path of the repository. e.g. namespace/name") class BuildTriggerList(RepositoryParamResource): """ Resource for listing repository build triggers. """ @require_repo_admin @disallow_for_app_repositories @nickname("listBuildTriggers") def get(self, namespace_name, repo_name): ...
178
179
598
63
115
dongboyan77/quay
endpoints/api/trigger.py
Python
BuildTrigger
BuildTrigger
77
161
77
80
a443b217bcf1367633a1b37c4543b05ebd49eb15
bigcode/the-stack
train
41361c0ad689d8555ce83bcb
train
function
def _prepare_webhook_url(scheme, username, password, hostname, path): auth_hostname = "%s:%s@%s" % (username, password, hostname) return urlunparse((scheme, auth_hostname, path, "", "", ""))
def _prepare_webhook_url(scheme, username, password, hostname, path):
auth_hostname = "%s:%s@%s" % (username, password, hostname) return urlunparse((scheme, auth_hostname, path, "", "", ""))
( start_build, MaximumBuildsQueuedException, BuildTriggerDisabledException, ) from endpoints.exception import NotFound, Unauthorized, InvalidRequest from util.names import parse_robot_username logger = logging.getLogger(__name__) def _prepare_webhook_url(scheme, username, password, hostname, path):
64
64
54
17
47
dongboyan77/quay
endpoints/api/trigger.py
Python
_prepare_webhook_url
_prepare_webhook_url
50
52
50
50
cc616b74fc8423d6da885b0dbd47c75494b008fb
bigcode/the-stack
train
90e236f2d9ecf20837915f4b
train
class
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/subdir") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") @internal_only class BuildTriggerSubdirs(RepositoryParamResource): """ Custom verb for fet...
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/subdir") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") @internal_only class BuildTriggerSubdirs(RepositoryParamResource):
""" Custom verb for fetching the subdirs which are buildable for a trigger. """ schemas = { "BuildTriggerSubdirRequest": {"type": "object", "description": "Arbitrary json.",}, } @require_repo_admin @disallow_for_app_repositories @disallow_for_non_normal_repositories @nickname("list...
=model.repository.get_repository(namespace_name, repo_name), ) trigger.delete_instance(recursive=True) if trigger.write_token is not None: trigger.write_token.delete_instance() return "No Content", 204 @resource("/v1/repository/<apirepopath:repository>/trigger/<trigger...
117
117
390
72
44
dongboyan77/quay
endpoints/api/trigger.py
Python
BuildTriggerSubdirs
BuildTriggerSubdirs
164
212
164
168
ea4a0ffb0a78b786ec25a271423dcc0a0cfe07e3
bigcode/the-stack
train
47127d47a4b30ff334b0f3b2
train
class
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/start") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") class ActivateBuildTrigger(RepositoryParamResource): """ Custom verb to manually activate a...
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/start") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") class ActivateBuildTrigger(RepositoryParamResource):
""" Custom verb to manually activate a build trigger. """ schemas = { "RunParameters": { "type": "object", "description": "Optional run parameters for activating the build trigger", "properties": { "branch_name": { "type": "string"...
Analyzer( handler, namespace_name, server_hostname, new_config_dict, AdministerOrganizationPermission(namespace_name).can(), ) return trigger_analyzer.analyze_trigger() except TriggerException as rre: ...
163
163
546
66
97
dongboyan77/quay
endpoints/api/trigger.py
Python
ActivateBuildTrigger
ActivateBuildTrigger
381
445
381
384
86c000bc7e37bb81466b6512c758176b5d865776
bigcode/the-stack
train
ff7d79c6dd17e70843f36989
train
class
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/analyze") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") @internal_only class BuildTriggerAnalyze(RepositoryParamResource): """ Custom verb for an...
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/analyze") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") @internal_only class BuildTriggerAnalyze(RepositoryParamResource):
""" Custom verb for analyzing the config for a build trigger and suggesting various changes (such as a robot account to use for pulling) """ schemas = { "BuildTriggerAnalyzeRequest": { "type": "object", "required": ["config"], "properties": {"config": {"type"...
"pull_robot": trigger.pull_robot.username if trigger.pull_robot else None, "config": final_config, }, repo=repo, ) return trigger_view(trigger, can_admin=True) else: raise Unauthorized() @resource("/v1/r...
120
120
403
71
49
dongboyan77/quay
endpoints/api/trigger.py
Python
BuildTriggerAnalyze
BuildTriggerAnalyze
326
378
326
330
30a854204c402a7ecf7712e545e684449995aeea
bigcode/the-stack
train
b210aac4eed6472d92d84f9a
train
class
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/activate") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") class BuildTriggerActivate(RepositoryParamResource): """ Custom verb for activating a bu...
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/activate") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") class BuildTriggerActivate(RepositoryParamResource):
""" Custom verb for activating a build trigger once all required information has been collected. """ schemas = { "BuildTriggerActivateRequest": { "type": "object", "required": ["config"], "properties": { "config": {"type": "object", "description": "...
(trigger.connected_user.username) if user_permission.can(): new_config_dict = request.get_json() handler = BuildTriggerHandler.get_handler(trigger, new_config_dict) try: subdirs = handler.list_build_subdirs() context_map = {} f...
245
245
818
66
179
dongboyan77/quay
endpoints/api/trigger.py
Python
BuildTriggerActivate
BuildTriggerActivate
215
323
215
218
f1f50fb10c1462a978c3cd92749eac49d43ac77b
bigcode/the-stack
train
69ac136f7d42125f24b6c8a2
train
class
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/builds") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") class TriggerBuildList(RepositoryParamResource): """ Resource to represent builds that wer...
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/builds") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") class TriggerBuildList(RepositoryParamResource):
""" Resource to represent builds that were activated from the specified trigger. """ @require_repo_admin @disallow_for_app_repositories @parse_args() @query_param("limit", "The maximum number of builds to return", type=int, default=5) @nickname("listTriggerRecentBuilds") def get(self, names...
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/builds") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") class TriggerBuildList(RepositoryParamResource):
67
64
211
67
0
dongboyan77/quay
endpoints/api/trigger.py
Python
TriggerBuildList
TriggerBuildList
448
463
448
451
5d1b8c8ae1e78e7a9a9519113105efbf6ede10b8
bigcode/the-stack
train
8f70345ba47966ecdb26dd3e
train
class
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/sources") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") @internal_only class BuildTriggerSources(RepositoryParamResource): """ Custom verb to fet...
@resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/sources") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("trigger_uuid", "The UUID of the build trigger") @internal_only class BuildTriggerSources(RepositoryParamResource):
""" Custom verb to fetch the list of build sources for the trigger config. """ schemas = { "BuildTriggerSourcesRequest": { "type": "object", "description": "Specifies the namespace under which to fetch sources", "properties": { "namespace": { ...
if values is None: raise NotFound() return {"values": values} else: raise Unauthorized() @resource("/v1/repository/<apirepopath:repository>/trigger/<trigger_uuid>/sources") @path_param("repository", "The full path of the repository. e.g. namespace/name") @path_param("tr...
94
94
316
70
24
dongboyan77/quay
endpoints/api/trigger.py
Python
BuildTriggerSources
BuildTriggerSources
495
535
495
499
12421a4f68fab1d90c63b6d722b007873682a478
bigcode/the-stack
train
de0a05f9a592299f13898be5
train
class
class Migration(migrations.Migration): dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL)] operations = [ migrations.CreateModel( name="Export", fields=[ ("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primar...
class Migration(migrations.Migration):
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL)] operations = [ migrations.CreateModel( name="Export", fields=[ ("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)), ( ...
# coding=utf-8 from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone from django.conf import settings import model_utils.fields class Migration(migrations.Migration):
46
76
254
7
38
uk-gov-mirror/ministryofjustice.cla_backend
cla_backend/apps/reports/migrations/0001_initial.py
Python
Migration
Migration
10
46
10
11
3f140aa2f7aeeb68211efe018e9c8fa7c8ea846a
bigcode/the-stack
train
bb48547386df332775e8d626
train
class
class btcmarkets (Exchange): def describe(self): return self.deep_extend(super(btcmarkets, self).describe(), { 'id': 'btcmarkets', 'name': 'BTC Markets', 'countries': 'AU', # Australia 'rateLimit': 1000, # market data cached for 1 second(trades cached for 2...
class btcmarkets (Exchange):
def describe(self): return self.deep_extend(super(btcmarkets, self).describe(), { 'id': 'btcmarkets', 'name': 'BTC Markets', 'countries': 'AU', # Australia 'rateLimit': 1000, # market data cached for 1 second(trades cached for 2 seconds) 'has': {...
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange import base64 import hashlib import json from ccxt.base.errors import ExchangeError from ccxt.base....
125
256
4,082
6
118
Kubulus1997/Trading
python/ccxt/btcmarkets.py
Python
btcmarkets
btcmarkets
17
412
17
18
683b8e4d629bb15f9ed4c00b736d9f5fca18f9a1
bigcode/the-stack
train
d99736cff76695cc0040abe3
train
function
def extractToomtummootstranslationsWordpressCom(item): ''' Parser for 'toomtummootstranslations.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', ...
def extractToomtummootstranslationsWordpressCom(item):
''' Parser for 'toomtummootstranslations.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', ...
def extractToomtummootstranslationsWordpressCom(item):
14
64
168
14
0
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractToomtummootstranslationsWordpressCom.py
Python
extractToomtummootstranslationsWordpressCom
extractToomtummootstranslationsWordpressCom
2
21
2
2
ffd76498044f923683089131f0efe7f7a6ff6080
bigcode/the-stack
train
5110eab72a587d1bc3a7c89c
train
function
def smarter_repr(obj): if isinstance(obj, datetime.datetime): return obj.isoformat() return repr(obj)
def smarter_repr(obj):
if isinstance(obj, datetime.datetime): return obj.isoformat() return repr(obj)
0.1', port=9401)) # logger.addHandler(GelfTcpHandler(host='localhost', port=12201)) # logger.info('hello gelf wow') import json import datetime obj = { "a": 1, "b": 2, } def smarter_repr(obj):
64
64
24
5
59
sillygod/django-as-pure-api-server
test.py
Python
smarter_repr
smarter_repr
20
23
20
20
7c4f6a2ec34b9e8c66e0dbcbb11b63459522e550
bigcode/the-stack
train
5a8b5a0aced0e677357339a7
train
class
class AsyncSearchClient(NamespacedClient): @query_params() def delete(self, id, params=None, headers=None): """ Deletes an async search by ID. If the search is still running, the search request will be cancelled. Otherwise, the saved search results are deleted. `<https://www.ela...
class AsyncSearchClient(NamespacedClient): @query_params()
def delete(self, id, params=None, headers=None): """ Deletes an async search by ID. If the search is still running, the search request will be cancelled. Otherwise, the saved search results are deleted. `<https://www.elastic.co/guide/en/elasticsearch/reference/master/async-search.ht...
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use ...
216
256
1,956
14
201
danielpine/elasticsearch-py
elasticsearch/client/async_search.py
Python
AsyncSearchClient
AsyncSearchClient
21
228
21
22
eecaf9111ff11fe16a0e18beefd9d7bffd2bab2e
bigcode/the-stack
train
b6565f99b8a22e2f4d1cbe40
train
class
class WorkflowMenuItem(zeit.cms.browser.menu.ContextViewsMenu): """The Workflow menu item which is active when no other item is active.""" def render(self): return ''
class WorkflowMenuItem(zeit.cms.browser.menu.ContextViewsMenu):
"""The Workflow menu item which is active when no other item is active.""" def render(self): return ''
from zeit.cms.i18n import MessageFactory as _ import zeit.cms.browser.menu import zeit.cms.checkout class WorkflowMenuItem(zeit.cms.browser.menu.ContextViewsMenu):
35
64
37
13
21
ZeitOnline/zeit.content.article
src/zeit/content/article/browser/menu.py
Python
WorkflowMenuItem
WorkflowMenuItem
6
9
6
6
9af8e260dcb177c6a66a8eada6f13cf7f5191bdc
bigcode/the-stack
train
83bdbe300f3d30f3d0d2844f
train
class
class EditContentsMenuItem(zeit.cms.browser.menu.ContextViewsMenu): """The Workflow menu item which is active when no other item is active.""" sort = -1 viewURL = "@@edit.html" activeCSS = 'edit_contents selected' inActiveCSS = 'edit_contents' @property def title(self): """Changes ...
class EditContentsMenuItem(zeit.cms.browser.menu.ContextViewsMenu):
"""The Workflow menu item which is active when no other item is active.""" sort = -1 viewURL = "@@edit.html" activeCSS = 'edit_contents selected' inActiveCSS = 'edit_contents' @property def title(self): """Changes wheter item is checked out or checked in""" checkout = zeit....
_ import zeit.cms.browser.menu import zeit.cms.checkout class WorkflowMenuItem(zeit.cms.browser.menu.ContextViewsMenu): """The Workflow menu item which is active when no other item is active.""" def render(self): return '' class EditContentsMenuItem(zeit.cms.browser.menu.ContextViewsMenu):
63
64
173
14
49
ZeitOnline/zeit.content.article
src/zeit/content/article/browser/menu.py
Python
EditContentsMenuItem
EditContentsMenuItem
12
33
12
12
2b1772bb42a2ba9508a09b11a9080e4b63c5d9f7
bigcode/the-stack
train
548af30cca3d05fadcdbb4a0
train
class
class FSBidListBidRegisterView(APIView): permission_classes = (IsAuthenticated, isDjangoGroupMember('cdo'),) def put(self, request, pk, client_id): ''' Registers a bid ''' jwt = request.META['HTTP_JWT'] try: services.register_bid_on_position(client_id, pk, ...
class FSBidListBidRegisterView(APIView):
permission_classes = (IsAuthenticated, isDjangoGroupMember('cdo'),) def put(self, request, pk, client_id): ''' Registers a bid ''' jwt = request.META['HTTP_JWT'] try: services.register_bid_on_position(client_id, pk, jwt) user = UserProfile.object...
emp_id={client_id} did not exist. No notification created for submitting bid on position id={pk}.") return Response(status=status.HTTP_204_NO_CONTENT) message = f"Bid on a position has been submitted by CDO {user}." if owner: Notification.objects.cr...
181
181
606
11
170
MetaPhase-Consulting/State-TalentMAP-API
talentmap_api/fsbid/views/cdo.py
Python
FSBidListBidRegisterView
FSBidListBidRegisterView
97
160
97
98
9a0087e0cf32ef54b368df1f8108303269d2d0dd
bigcode/the-stack
train
eff69f835cd9026c655e301e
train
class
class FSBidCDOListView(BaseView): def get(self, request): ''' Gets all cdos ''' return Response(cdoServices.cdo(request.META['HTTP_JWT']))
class FSBidCDOListView(BaseView):
def get(self, request): ''' Gets all cdos ''' return Response(cdoServices.cdo(request.META['HTTP_JWT']))
registeredHandshakeNotification import talentmap_api.fsbid.services.bid as services import talentmap_api.fsbid.services.cdo as cdoServices import talentmap_api.fsbid.services.classifications as classifications_services logger = logging.getLogger(__name__) class FSBidCDOListView(BaseView):
64
64
44
11
53
MetaPhase-Consulting/State-TalentMAP-API
talentmap_api/fsbid/views/cdo.py
Python
FSBidCDOListView
FSBidCDOListView
23
29
23
24
66fe53e021f06398004a3bee709b054d7f7b32b1
bigcode/the-stack
train
81d4c46819cf72a1251f2bf1
train
class
class FSBidClientEditClassifications(APIView): permission_classes = (IsAuthenticated, isDjangoGroupMember('cdo'),) def put(self, request, client_id): ''' Inserts/Deletes the classifications for the client ''' try: id = [] if request.data['insert']: ...
class FSBidClientEditClassifications(APIView):
permission_classes = (IsAuthenticated, isDjangoGroupMember('cdo'),) def put(self, request, client_id): ''' Inserts/Deletes the classifications for the client ''' try: id = [] if request.data['insert']: id = classifications_services.insert_...
if owner: Notification.objects.create(owner=owner, tags=['bidding'], message=f"Bid on position id={pk} has been removed from your bid list by CDO {user}") return Response(status=status.HTTP_204_NO_CONTENT) class ...
64
64
193
11
53
MetaPhase-Consulting/State-TalentMAP-API
talentmap_api/fsbid/views/cdo.py
Python
FSBidClientEditClassifications
FSBidClientEditClassifications
216
233
216
217
53fe207e68428143ffafef1d766f34ffb2fd5af3
bigcode/the-stack
train
2fae2b8ac96beada777a4a4c
train
class
class FSBidListView(BaseView): permission_classes = (IsAuthenticated, isDjangoGroupMember('cdo'),) def get(self, request, client_id): ''' Gets all bids for the client user ''' return Response({"results": services.user_bids(client_id, request.META['HTTP_JWT'], query=request.quer...
class FSBidListView(BaseView):
permission_classes = (IsAuthenticated, isDjangoGroupMember('cdo'),) def get(self, request, client_id): ''' Gets all bids for the client user ''' return Response({"results": services.user_bids(client_id, request.META['HTTP_JWT'], query=request.query_params)})
class FSBidCDOView(BaseView): def get(self, request, pk): ''' Gets a single cdo by client's perdet_seq_num ''' return Response(cdoServices.single_cdo(request.META['HTTP_JWT'], pk)) class FSBidListView(BaseView):
64
64
76
9
55
MetaPhase-Consulting/State-TalentMAP-API
talentmap_api/fsbid/views/cdo.py
Python
FSBidListView
FSBidListView
41
49
41
42
1c5a43ab10125cb1bd99859929206b1a9d01def5
bigcode/the-stack
train
fe46664c423ed68ca74dd1a3
train
class
class FSBidListPositionActionView(BaseView): ''' list: Lists all bids for the clients's current bidlist ''' permission_classes = (IsAuthenticated, isDjangoGroupMember('cdo'),) def get(self, request, pk, client_id, format=None): ''' Indicates if the position is in the client's bi...
class FSBidListPositionActionView(BaseView):
''' list: Lists all bids for the clients's current bidlist ''' permission_classes = (IsAuthenticated, isDjangoGroupMember('cdo'),) def get(self, request, pk, client_id, format=None): ''' Indicates if the position is in the client's bidlist Returns 204 if the position is...
bid on position id={pk}.") return Response(status=status.HTTP_204_NO_CONTENT) if owner: Notification.objects.create(owner=owner, tags=['bidding'], message=f"Bid on position has been unre...
151
151
504
11
140
MetaPhase-Consulting/State-TalentMAP-API
talentmap_api/fsbid/views/cdo.py
Python
FSBidListPositionActionView
FSBidListPositionActionView
163
213
163
163
21323a1b7300977e9e88c74d1e1ebe274574f6f6
bigcode/the-stack
train
0b238e6722db53d4dabbc2de
train
class
class FSBidListBidActionView(APIView): permission_classes = (IsAuthenticated, isDjangoGroupMember('cdo'),) def put(self, request, pk, client_id): ''' Submits a bid (sets status to A) ''' try: services.submit_bid_on_position(client_id, pk, request.META['HTTP_JWT']) ...
class FSBidListBidActionView(APIView):
permission_classes = (IsAuthenticated, isDjangoGroupMember('cdo'),) def put(self, request, pk, client_id): ''' Submits a bid (sets status to A) ''' try: services.submit_bid_on_position(client_id, pk, request.META['HTTP_JWT']) user = UserProfile.objects.ge...
DjangoGroupMember('cdo'),) @classmethod def get_extra_actions(cls): return [] def get(self, request, client_id, **kwargs): ''' Exports all bids for the client's user to CSV ''' return services.get_user_bids_csv(client_id, request.META['HTTP_JWT'], query=request.quer...
87
87
292
11
76
MetaPhase-Consulting/State-TalentMAP-API
talentmap_api/fsbid/views/cdo.py
Python
FSBidListBidActionView
FSBidListBidActionView
67
94
67
68
00c2795ff3aeb4a1f0fd7ad44cc7f905f9251f0f
bigcode/the-stack
train
384872a6f452c7a827b6f410
train
class
class FSBidBidClientListCSVView(APIView): permission_classes = (IsAuthenticated, isDjangoGroupMember('cdo'),) @classmethod def get_extra_actions(cls): return [] def get(self, request, client_id, **kwargs): ''' Exports all bids for the client's user to CSV ''' r...
class FSBidBidClientListCSVView(APIView):
permission_classes = (IsAuthenticated, isDjangoGroupMember('cdo'),) @classmethod def get_extra_actions(cls): return [] def get(self, request, client_id, **kwargs): ''' Exports all bids for the client's user to CSV ''' return services.get_user_bids_csv(client_id,...
'),) def get(self, request, client_id): ''' Gets all bids for the client user ''' return Response({"results": services.user_bids(client_id, request.META['HTTP_JWT'], query=request.query_params)}) class FSBidBidClientListCSVView(APIView):
63
64
97
12
52
MetaPhase-Consulting/State-TalentMAP-API
talentmap_api/fsbid/views/cdo.py
Python
FSBidBidClientListCSVView
FSBidBidClientListCSVView
52
64
52
53
5042b8e9ed4165f03be3302285c0ccaadc55df22
bigcode/the-stack
train
532c1aea7e66fe241e6e03cf
train
class
class FSBidCDOView(BaseView): def get(self, request, pk): ''' Gets a single cdo by client's perdet_seq_num ''' return Response(cdoServices.single_cdo(request.META['HTTP_JWT'], pk))
class FSBidCDOView(BaseView):
def get(self, request, pk): ''' Gets a single cdo by client's perdet_seq_num ''' return Response(cdoServices.single_cdo(request.META['HTTP_JWT'], pk))
logger = logging.getLogger(__name__) class FSBidCDOListView(BaseView): def get(self, request): ''' Gets all cdos ''' return Response(cdoServices.cdo(request.META['HTTP_JWT'])) class FSBidCDOView(BaseView):
63
64
55
10
53
MetaPhase-Consulting/State-TalentMAP-API
talentmap_api/fsbid/views/cdo.py
Python
FSBidCDOView
FSBidCDOView
32
38
32
33
4a9ec4a937d04d9761b7acd0756b1eb1a3b64df5
bigcode/the-stack
train
578f11f2e3ddff1706611995
train
function
@pytest.mark.level1 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_while_with_param_basic_grad_mul(): class MyWhileNet(nn.Cell): def __init__(self): super().__init__() self.max = P.ReduceMax() self.param ...
@pytest.mark.level1 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_while_with_param_basic_grad_mul():
class MyWhileNet(nn.Cell): def __init__(self): super().__init__() self.max = P.ReduceMax() self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight") self.zero = Tensor(np.ones(([2, 2, 2])), ms.float32) self....
= MyWhileNet() net = GradNet(while_net) graph_output = net(idx, end, x) expect = np.array([[[4, 4], [4, 4]], [[4, 4], [4, 4]]]).astype(np.float32) assert np.allclose(graph_output[0].asnumpy(), expect, 0.0001, 0.0001) @pytest.mark.level1 @pytest.mark.platform_arm_ascend_training @...
127
127
424
38
89
PowerOlive/mindspore
tests/st/control/test_cont_grad.py
Python
test_while_with_param_basic_grad_mul
test_while_with_param_basic_grad_mul
599
638
599
603
9bd9cf477d8dbcbcd864061ecbe9151f7b0de8f2
bigcode/the-stack
train
aeccec04410e2081022c680b
train
function
@pytest.mark.level1 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_if_by_if_return_inside_grad(): class MyIfByIfNet(nn.Cell): def __init__(self): super().__init__() self.max = P.ReduceMax() self.param = P...
@pytest.mark.level1 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_if_by_if_return_inside_grad():
class MyIfByIfNet(nn.Cell): def __init__(self): super().__init__() self.max = P.ReduceMax() self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight") self.zero = Tensor(np.zeros(([2, 2, 2])), ms.float32) def co...
ByIfNet() net = GradNet(if_net) graph_output = net(idx, end, x) expect = np.array([[[0, 0], [0, 0]], [[0, 0], [0, 0]]]).astype(np.float32) assert np.allclose(graph_output[0].asnumpy(), expect, 0.0001, 0.0001) @pytest.mark.level1 @pytest.mark.platform_arm_ascend_training @pytest.m...
124
124
415
37
87
PowerOlive/mindspore
tests/st/control/test_cont_grad.py
Python
test_if_by_if_return_inside_grad
test_if_by_if_return_inside_grad
988
1,028
988
992
260ba20602b06c8320f27420e66323e1e91de292
bigcode/the-stack
train
36dc0333ca8e882f20d5c35f
train
function
@pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_while_with_param_forward_with_const_branch(): class MyWhileNet(nn.Cell): def __init__(self): super().__init__() self.max = P.ReduceMax() ...
@pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_while_with_param_forward_with_const_branch():
class MyWhileNet(nn.Cell): def __init__(self): super().__init__() self.max = P.ReduceMax() self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight") self.zero = Tensor(np.zeros(([2, 2, 2])), ms.float32) self...
, end, x) expect = np.array([[[2, 2], [2, 2]], [[2, 2], [2, 2]]], dtype=np.int32) assert np.allclose(graph_output[0].asnumpy(), expect, 0.0001, 0.0001) @pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_while_with_param_forward_...
107
107
358
39
68
PowerOlive/mindspore
tests/st/control/test_cont_grad.py
Python
test_while_with_param_forward_with_const_branch
test_while_with_param_forward_with_const_branch
249
283
249
253
6dda71de0b47755ef784069aefc9df18c578d10b
bigcode/the-stack
train
2b5fa924163a329a01ea728e
train
function
@pytest.mark.level1 @pytest.mark.platform_x86_cpu @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_if_by_if_const_grad(): class MyNet(nn.Cell): def __init__(self): super().__init__() self.add = P.Add() def construct(self, *inputs): out = s...
@pytest.mark.level1 @pytest.mark.platform_x86_cpu @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_if_by_if_const_grad():
class MyNet(nn.Cell): def __init__(self): super().__init__() self.add = P.Add() def construct(self, *inputs): out = self.add(*inputs) return out class GradNet(nn.Cell): def __init__(self, net): super(GradNet, self).__init__() ...
net = GradNet(my_net) a = Tensor(np.array(0), dtype=ms.int32) b = Tensor(np.array(1), dtype=ms.int32) net(a, b) @pytest.mark.level1 @pytest.mark.platform_x86_cpu @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_if_by_if_const_grad():
78
78
262
34
44
PowerOlive/mindspore
tests/st/control/test_cont_grad.py
Python
test_if_by_if_const_grad
test_if_by_if_const_grad
1,498
1,535
1,498
1,502
4ee761fb9ce77ad72e5e48be466ea19c00cb9098
bigcode/the-stack
train
f7b0e10c0307517227495dfe
train
function
@pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_while_with_variable_grad(): class MyWhileNet(nn.Cell): def __init__(self): super().__init__() self.mul = P.Mul() self.add = P.Add() ...
@pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_while_with_variable_grad():
class MyWhileNet(nn.Cell): def __init__(self): super().__init__() self.mul = P.Mul() self.add = P.Add() def construct(self, x, y): while x < y: z = self.mul(x, x) x = self.add(z, y) return x class GradN...
=np.float32) assert np.allclose(graph_output[0].asnumpy(), expect_one, 0.0001, 0.0001) assert np.allclose(graph_output[1].asnumpy(), expect_two, 0.0001, 0.0001) @pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_while_with_varia...
96
96
322
36
60
PowerOlive/mindspore
tests/st/control/test_cont_grad.py
Python
test_while_with_variable_grad
test_while_with_variable_grad
103
137
103
107
7389a66c75c64652d9df5bc877bb23d87b400181
bigcode/the-stack
train
5d5c9c07a448aea442b6a685
train
function
@pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_if_by_if_forward_control_inside_net(): class Branch3Net(nn.Cell): def __init__(self): super().__init__() self.add = P.Add() self.sub = P....
@pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_if_by_if_forward_control_inside_net():
class Branch3Net(nn.Cell): def __init__(self): super().__init__() self.add = P.Add() self.sub = P.Sub() self.mul = P.Mul() self.div = P.RealDiv() def construct(self, a, b, x): if b == x: b = self.add(a, b) ...
32) end = Tensor(np.array(3), dtype=ms.float32) x = Tensor(np.array(0), dtype=ms.float32) # graph mode context.set_context(mode=context.GRAPH_MODE) if_net = MyIfByIfNet() net = if_net graph_output = net(idx, end, x) expect = 4.444444 assert np.allclose(graph_output.asnumpy(), expect,...
145
145
485
38
107
PowerOlive/mindspore
tests/st/control/test_cont_grad.py
Python
test_if_by_if_forward_control_inside_net
test_if_by_if_forward_control_inside_net
1,142
1,206
1,142
1,146
88cb6a31f3de0360e3ecab7d673ebbfa64c0eb37
bigcode/the-stack
train
a21d21d8d29fa9b635139935
train
function
@pytest.mark.level1 @pytest.mark.platform_x86_cpu @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_if_const_grad(): class MyNet(nn.Cell): def __init__(self): super().__init__() self.add = P.Add() def construct(self, *inputs): out = self.ad...
@pytest.mark.level1 @pytest.mark.platform_x86_cpu @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_if_const_grad():
class MyNet(nn.Cell): def __init__(self): super().__init__() self.add = P.Add() def construct(self, *inputs): out = self.add(*inputs) return out class GradNet(nn.Cell): def __init__(self, net): super(GradNet, self).__init__() ...
(idx, end, x) expect = 240.0 assert np.allclose(graph_output.asnumpy(), expect, 0.0001, 0.0001) @pytest.mark.level1 @pytest.mark.platform_x86_cpu @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_if_const_grad():
70
70
234
32
38
PowerOlive/mindspore
tests/st/control/test_cont_grad.py
Python
test_if_const_grad
test_if_const_grad
1,462
1,495
1,462
1,466
aed60f16b4bd930eb68a5f9065b5a93f64b82c81
bigcode/the-stack
train
d8c3219bac57497a20c5e054
train
function
@pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_for_while_with_param_grad_normal(): class MyWhileNet(nn.Cell): def __init__(self): super().__init__() self.max = P.ReduceMax() self.param...
@pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_for_while_with_param_grad_normal():
class MyWhileNet(nn.Cell): def __init__(self): super().__init__() self.max = P.ReduceMax() self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight") self.zero = Tensor(np.zeros(([2, 2, 2])), ms.float32) self...
APH_MODE) while_net = MyWhileNet() net = GradNet(while_net) graph_output = net(idx, end, x) expect = np.array([[[8, 8], [8, 8]], [[8, 8], [8, 8]]]).astype(np.float32) assert np.allclose(graph_output[0].asnumpy(), expect, 0.0001, 0.0001) @pytest.mark.level0 @pytest.mark.platfor...
133
133
445
38
95
PowerOlive/mindspore
tests/st/control/test_cont_grad.py
Python
test_for_while_with_param_grad_normal
test_for_while_with_param_grad_normal
512
554
512
516
4639853084dd41ee6760f96affc6690d5d7db56a
bigcode/the-stack
train
37dd99c54d354a83c982d71d
train
function
@pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_with_param_if_by_if_forward(): class MyIfByIfNet(nn.Cell): def __init__(self): super().__init__() self.max = P.ReduceMax() self.param = P...
@pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_with_param_if_by_if_forward():
class MyIfByIfNet(nn.Cell): def __init__(self): super().__init__() self.max = P.ReduceMax() self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight") self.zero = Tensor(np.zeros(([2, 2, 2])), ms.float32) def co...
# graph mode context.set_context(mode=context.GRAPH_MODE) while_net = MyWhileNet() net = GradNet(while_net) graph_output = net(idx, end, x) assert np.allclose(graph_output[0].asnumpy(), 1, 0.0001, 0.0001) @pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gp...
108
108
362
37
71
PowerOlive/mindspore
tests/st/control/test_cont_grad.py
Python
test_with_param_if_by_if_forward
test_with_param_if_by_if_forward
822
856
822
826
75e10f6390d7d1e3a8ebc54518f73c6beaeda44d
bigcode/the-stack
train
28e585d2e3b613d8cdb7f810
train
function
@pytest.mark.level1 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_while_with_param_grad(): class MyWhileNet(nn.Cell): def __init__(self): super().__init__() self.max = P.ReduceMax() self.param = Paramete...
@pytest.mark.level1 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_while_with_param_grad():
class MyWhileNet(nn.Cell): def __init__(self): super().__init__() self.max = P.ReduceMax() self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight") self.zero = Tensor(np.zeros(([2, 2, 2])), ms.float32) def con...
graph mode context.set_context(mode=context.GRAPH_MODE) net = MyWhileNet() graph_output = net(idx, end, x) expect = np.array([[[4, 6], [8, 10]], [[4, 6], [8, 10]]]).astype(np.float32) assert np.allclose(graph_output.asnumpy(), expect, 0.0001, 0.0001) @pytest.mark.level1 @pyte...
128
128
428
36
92
PowerOlive/mindspore
tests/st/control/test_cont_grad.py
Python
test_while_with_param_grad
test_while_with_param_grad
207
246
207
211
a4b485e3e038211de6f2cbd998d88597e0b47af2
bigcode/the-stack
train
18a3e5d518be8c5fe008a6f3
train
function
@pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_with_param_if_by_if_grad_param_excute_null(): class MyIfByIfNet(nn.Cell): def __init__(self): super().__init__() self.max = P.ReduceMax() ...
@pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_with_param_if_by_if_grad_param_excute_null():
class MyIfByIfNet(nn.Cell): def __init__(self): super().__init__() self.max = P.ReduceMax() self.param = Parameter(Tensor(np.arange(2 * 2 * 2).reshape((2, 2, 2)), ms.float32), name="weight") self.zero = Tensor(np.zeros(([2, 2, 2])), ms.float32) def co...
Net(if_net) graph_output = net(idx, end, x) expect = np.array([[[2, 2], [2, 2]], [[2, 2], [2, 2]]]).astype(np.float32) assert np.allclose(graph_output[0].asnumpy(), expect, 0.0001, 0.0001) @pytest.mark.level0 @pytest.mark.platform_arm_ascend_training @pytest.mark.platform_x86_gpu_tra...
120
120
401
41
79
PowerOlive/mindspore
tests/st/control/test_cont_grad.py
Python
test_with_param_if_by_if_grad_param_excute_null
test_with_param_if_by_if_grad_param_excute_null
947
985
947
951
2ae505655c2adb08a233e3d696b05b2338c69b0f
bigcode/the-stack
train