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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11807b8f1bc1b51dbe63402d | train | function | def p_init(t) :
'init : instrucciones'
t[0] = t[1]
| def p_init(t) :
| 'init : instrucciones'
t[0] = t[1]
| CAT'),
('left','MAS','MENOS'),
('left','POR','DIVISION'),
('left','MODULO','EXP'),
#('right','UMENOS'),
)
# Definición de la gramática
from expresiones import *
from instrucciones import *
def p_init(t) :
| 64 | 64 | 23 | 6 | 58 | webdev188/tytus | parser/team22/gramatica.py | Python | p_init | p_init | 214 | 216 | 214 | 214 | f17c4377099b76c4df3bee3736d1a7fe989b6613 | bigcode/the-stack | train |
cfe8b80a026db652642928ca | train | function | def p_instruccion_Use_BD(t) :
'cambio_bd : ID PTCOMA'
t[0] = Cambio_BD(t[1])
print("CAMBIO de BD")
| def p_instruccion_Use_BD(t) :
| 'cambio_bd : ID PTCOMA'
t[0] = Cambio_BD(t[1])
print("CAMBIO de BD")
| ])
else:
#Si t[5] no existe o es Punto y coma, entonces la tabla no tiene herencia
t[0] = Crear_TB(t[1], t[3])
# INSTRUCCION CON "USE"
def p_instruccion_Use_BD(t) :
| 64 | 64 | 45 | 12 | 52 | webdev188/tytus | parser/team22/gramatica.py | Python | p_instruccion_Use_BD | p_instruccion_Use_BD | 261 | 264 | 261 | 261 | 51bf778cbf70aaee4655690e5c0d7eba86e2f27b | bigcode/the-stack | train |
827dcda9f588b3223ec0ed9b | train | function | def p_parametro_con_tabla_columna(t) :
'name_column : ID'
t[0] = t[1]
print("Nombre de la columna")
| def p_parametro_con_tabla_columna(t) :
| 'name_column : ID'
t[0] = t[1]
print("Nombre de la columna")
| t[1]]
print("Un parametro")
def p_parametro_con_tabla(t) :
'parametro : ID PUNTO name_column'
t[0] = t[1]
print("Parametro con indice de tabla")
def p_parametro_con_tabla_columna(t) :
| 64 | 64 | 38 | 12 | 52 | webdev188/tytus | parser/team22/gramatica.py | Python | p_parametro_con_tabla_columna | p_parametro_con_tabla_columna | 296 | 299 | 296 | 296 | c370c195a7c46a232b68e008e6320380ffc87d5d | bigcode/the-stack | train |
3ffa57b3e8fc6e4e5863caf0 | train | function | def p_instruccion_delete_condicional(t) :
'delete_condicional : ID WHERE PTCOMA'
# t[0] = Delete_incondicional(t[1])
print("Eliminar tabla: " + t[1])
| def p_instruccion_delete_condicional(t) :
| 'delete_condicional : ID WHERE PTCOMA'
# t[0] = Delete_incondicional(t[1])
print("Eliminar tabla: " + t[1])
| | delete_incondicional'''
print("ELIMINACION")
def p_instruccion_delete_incondicional(t) :
'delete_incondicional : ID PTCOMA'
t[0] = Delete_incondicional(t[1])
def p_instruccion_delete_condicional(t) :
| 64 | 64 | 51 | 11 | 53 | webdev188/tytus | parser/team22/gramatica.py | Python | p_instruccion_delete_condicional | p_instruccion_delete_condicional | 339 | 342 | 339 | 339 | 6a87af9d93c72bd16a64a24d05fcc9857cb0ec40 | bigcode/the-stack | train |
36bec26df270ec7d71fa5ee8 | train | function | def p_instrucciones_lista(t) :
'instrucciones : instrucciones instruccion'
t[1].append(t[2])
t[0] = t[1]
| def p_instrucciones_lista(t) :
| 'instrucciones : instrucciones instruccion'
t[1].append(t[2])
t[0] = t[1]
| ','EXP'),
#('right','UMENOS'),
)
# Definición de la gramática
from expresiones import *
from instrucciones import *
def p_init(t) :
'init : instrucciones'
t[0] = t[1]
def p_instrucciones_lista(t) :
| 64 | 64 | 40 | 9 | 55 | webdev188/tytus | parser/team22/gramatica.py | Python | p_instrucciones_lista | p_instrucciones_lista | 218 | 221 | 218 | 218 | ffe2ce495fd71480dcd24d091fa135a1d0d77d7b | bigcode/the-stack | train |
f083d3f6f9567de08fbc4bd6 | train | function | def t_ENTERO(t):
r'\d+'
try:
t.value = int(t.value)
except ValueError:
print("Integer value too large %d", t.value)
t.value = 0
return t
| def t_ENTERO(t):
| r'\d+'
try:
t.value = int(t.value)
except ValueError:
print("Integer value too large %d", t.value)
t.value = 0
return t
| '\\'
def t_DECIMAL(t):
r'\d+\.\d+'
try:
t.value = float(t.value)
except ValueError:
print("Float value too large %d", t.value)
t.value = 0
return t
def t_ENTERO(t):
| 64 | 64 | 52 | 6 | 57 | webdev188/tytus | parser/team22/gramatica.py | Python | t_ENTERO | t_ENTERO | 154 | 161 | 154 | 154 | f117654422a61c35ecae6aa3ce820b1b95a31297 | bigcode/the-stack | train |
5a589cb03fa97ec95ff7324b | train | function | def p_instrucciones_lista_parametros(t) :
'lista_parametros : lista_parametros COMA parametro'
t[1].append(t[3])
t[0] = t[1]
print("Varios parametros")
| def p_instrucciones_lista_parametros(t) :
| 'lista_parametros : lista_parametros COMA parametro'
t[1].append(t[3])
t[0] = t[1]
print("Varios parametros")
| _All(t) :
'select_all : ID PTCOMA'
t[0] = Select_All(t[1])
print("Consulta ALL para tabla: " + t[1])
#========================================================
# LISTA DE PARAMETROS
def p_instrucciones_lista_parametros(t) :
| 64 | 64 | 52 | 11 | 52 | webdev188/tytus | parser/team22/gramatica.py | Python | p_instrucciones_lista_parametros | p_instrucciones_lista_parametros | 280 | 284 | 280 | 280 | 261dd2398a5431477c959ac0374684689223e801 | bigcode/the-stack | train |
92956e74febb194667c7ed95 | train | function | def p_parametro_con_tabla(t) :
'parametro : ID PUNTO name_column'
t[0] = t[1]
print("Parametro con indice de tabla")
| def p_parametro_con_tabla(t) :
| 'parametro : ID PUNTO name_column'
t[0] = t[1]
print("Parametro con indice de tabla")
| ])
t[0] = t[1]
print("Varios parametros")
def p_instrucciones_parametro(t) :
'lista_parametros : parametro '
t[0] = [t[1]]
print("Un parametro")
def p_parametro_con_tabla(t) :
| 64 | 64 | 42 | 10 | 54 | webdev188/tytus | parser/team22/gramatica.py | Python | p_parametro_con_tabla | p_parametro_con_tabla | 291 | 294 | 291 | 291 | 00c3918cd568c22d0a512eb4724f507555236397 | bigcode/the-stack | train |
bd8ac656cb2c454b236f073d | train | function | def p_instruccion_crear_BD(t) :
'crear_bd : ID PTCOMA'
t[0] = Crear_BD(t[1])
print("Creacion de BD")
| def p_instruccion_crear_BD(t) :
| 'crear_bd : ID PTCOMA'
t[0] = Crear_BD(t[1])
print("Creacion de BD")
| '''
t[0] = t[2]
# INSTRUCCION CON "CREATE"
def p_instruccion_creacion(t) :
'''creacion : DATABASE crear_bd
| TABLE crear_tb'''
print("Creacion")
def p_instruccion_crear_BD(t) :
| 64 | 64 | 44 | 12 | 52 | webdev188/tytus | parser/team22/gramatica.py | Python | p_instruccion_crear_BD | p_instruccion_crear_BD | 242 | 245 | 242 | 242 | ed932eff27cb555ff438994d5722123aa8b684b8 | bigcode/the-stack | train |
1760d9b23b07a9e4eff254f9 | train | function | def t_newline(t):
r'\n+'
t.lexer.lineno += t.value.count("\n")
| def t_newline(t):
| r'\n+'
t.lexer.lineno += t.value.count("\n")
| t.lexer.lineno += t.value.count('\n')
# Comentario simple // ...
def t_COMENTARIO_SIMPLE(t):
r'--.*\n'
t.lexer.lineno += 1
# Caracteres ignorados
t_ignore = " \t"
def t_newline(t):
| 64 | 64 | 25 | 6 | 58 | webdev188/tytus | parser/team22/gramatica.py | Python | t_newline | t_newline | 186 | 188 | 186 | 186 | 1908ee44fd3d7aef2a4a5e13fa08717ba1c4c8d3 | bigcode/the-stack | train |
b12af6605539b5beffbd8caa | train | function | def p_instruccion_crear_TB_columnas(t) :
'''crear_tb_columnas : crear_tb_columnas COMA ID tipo_valor parametro_columna
| crear_tb_columnas COMA ID tipo_valor
| crear_tb_columnas COMA PRIMARY KEY PARIZQ pkey_id PARDER
| crear_tb_c... | def p_instruccion_crear_TB_columnas(t) :
| '''crear_tb_columnas : crear_tb_columnas COMA ID tipo_valor parametro_columna
| crear_tb_columnas COMA ID tipo_valor
| crear_tb_columnas COMA PRIMARY KEY PARIZQ pkey_id PARDER
| crear_tb_columnas COMA FOREIGN KEY PARIZQ pkey_id P... | [1]
print("Parametro SIN indice de tabla")
#========================================================
#========================================================
# LISTA DE CONDICIONES
#========================================================
#========================================================
# LISTA DE PARA... | 64 | 64 | 169 | 14 | 49 | webdev188/tytus | parser/team22/gramatica.py | Python | p_instruccion_crear_TB_columnas | p_instruccion_crear_TB_columnas | 314 | 324 | 314 | 314 | dcb00a676692687d0b15677fc0520203dab9847a | bigcode/the-stack | train |
3222d86e3e8eda22a9875080 | train | function | def p_instruccion_creacion(t) :
'''creacion : DATABASE crear_bd
| TABLE crear_tb'''
print("Creacion")
| def p_instruccion_creacion(t) :
| '''creacion : DATABASE crear_bd
| TABLE crear_tb'''
print("Creacion")
| def p_instruccion(t) :
'''instruccion : CREATE creacion
| USE cambio_bd
| SELECT selects
| DELETE deletes'''
t[0] = t[2]
# INSTRUCCION CON "CREATE"
def p_instruccion_creacion(t) :
| 64 | 64 | 32 | 10 | 54 | webdev188/tytus | parser/team22/gramatica.py | Python | p_instruccion_creacion | p_instruccion_creacion | 237 | 240 | 237 | 237 | 33d3adff44fc00db4df36ac1f94b7eb223e772af | bigcode/the-stack | train |
30523151c30febbb185d9584 | train | function | def p_instrucciones_instruccion(t) :
'instrucciones : instruccion '
t[0] = [t[1]]
| def p_instrucciones_instruccion(t) :
| 'instrucciones : instruccion '
t[0] = [t[1]]
| : instrucciones'
t[0] = t[1]
def p_instrucciones_lista(t) :
'instrucciones : instrucciones instruccion'
t[1].append(t[2])
t[0] = t[1]
def p_instrucciones_instruccion(t) :
| 64 | 64 | 32 | 11 | 53 | webdev188/tytus | parser/team22/gramatica.py | Python | p_instrucciones_instruccion | p_instrucciones_instruccion | 224 | 226 | 224 | 224 | b818cf535dd2c14ca7782475c08af3f6dbac4169 | bigcode/the-stack | train |
56e2ce32556e6b0167b732e9 | train | function | def p_instruccion_delete(t) :
'''deletes : ID PTCOMA WHERE delete_condicional
| delete_incondicional'''
print("ELIMINACION")
| def p_instruccion_delete(t) :
| '''deletes : ID PTCOMA WHERE delete_condicional
| delete_incondicional'''
print("ELIMINACION")
| key_id PARDER
| FOREIGN KEY PARIZQ pkey_id PARDER REFERNECES ID PARIZQ pkey_id PARDER
'''
print('Cosas')
#========================================================
# INSTRUCCION CON "DELETE"
def p_instruccion_delete(t) :
| 64 | 64 | 39 | 9 | 55 | webdev188/tytus | parser/team22/gramatica.py | Python | p_instruccion_delete | p_instruccion_delete | 330 | 333 | 330 | 330 | 8bef19ad1a355061c97a5f266112da68eba095bf | bigcode/the-stack | train |
85a9fa6a649006e81fe04abe | train | function | def p_instruccion_Select_All(t) :
'select_all : ID PTCOMA'
t[0] = Select_All(t[1])
print("Consulta ALL para tabla: " + t[1])
| def p_instruccion_Select_All(t) :
| 'select_all : ID PTCOMA'
t[0] = Select_All(t[1])
print("Consulta ALL para tabla: " + t[1])
| print("CAMBIO de BD")
# INSTRUCCIONES CON "SELECT"
def p_instruccion_selects(t) :
'''selects : POR FROM select_all
| lista_parametros FROM ID PTCOMA'''
print("selects")
def p_instruccion_Select_All(t) :
| 64 | 64 | 47 | 10 | 54 | webdev188/tytus | parser/team22/gramatica.py | Python | p_instruccion_Select_All | p_instruccion_Select_All | 273 | 276 | 273 | 273 | c5192f511b5b56dd8e8de4f013fb6545b183475b | bigcode/the-stack | train |
a4e120ab2694f30acc74d630 | train | function | def t_COMENTARIO_MULTILINEA(t):
r'/\*(.|\n)*?\*/'
t.lexer.lineno += t.value.count('\n')
| def t_COMENTARIO_MULTILINEA(t):
| r'/\*(.|\n)*?\*/'
t.lexer.lineno += t.value.count('\n')
| reserved words
return t
def t_CADENA(t):
r'\".*?\"'
t.value = t.value[1:-1] # remuevo las comillas
return t
# Comentario de múltiples líneas /* .. */
def t_COMENTARIO_MULTILINEA(t):
| 64 | 64 | 36 | 11 | 53 | webdev188/tytus | parser/team22/gramatica.py | Python | t_COMENTARIO_MULTILINEA | t_COMENTARIO_MULTILINEA | 174 | 176 | 174 | 174 | 28aa0c1f04ec28570ca51e6c054e43d552cea7b3 | bigcode/the-stack | train |
61b50cc1e53de7f11f643376 | train | function | def p_instruccion(t) :
'''instruccion : CREATE creacion
| USE cambio_bd
| SELECT selects
| DELETE deletes'''
t[0] = t[2]
| def p_instruccion(t) :
| '''instruccion : CREATE creacion
| USE cambio_bd
| SELECT selects
| DELETE deletes'''
t[0] = t[2]
| instrucciones instruccion'
t[1].append(t[2])
t[0] = t[1]
def p_instrucciones_instruccion(t) :
'instrucciones : instruccion '
t[0] = [t[1]]
def p_instruccion(t) :
| 64 | 64 | 45 | 8 | 56 | webdev188/tytus | parser/team22/gramatica.py | Python | p_instruccion | p_instruccion | 228 | 233 | 228 | 228 | c2024dfa2e9ae5f9b8eb62f7b438bb7df4d01fa9 | bigcode/the-stack | train |
b83676cc774629db7a043c46 | train | function | def p_instrucciones_parametro(t) :
'lista_parametros : parametro '
t[0] = [t[1]]
print("Un parametro")
| def p_instrucciones_parametro(t) :
| 'lista_parametros : parametro '
t[0] = [t[1]]
print("Un parametro")
| ROS
def p_instrucciones_lista_parametros(t) :
'lista_parametros : lista_parametros COMA parametro'
t[1].append(t[3])
t[0] = t[1]
print("Varios parametros")
def p_instrucciones_parametro(t) :
| 64 | 64 | 36 | 10 | 54 | webdev188/tytus | parser/team22/gramatica.py | Python | p_instrucciones_parametro | p_instrucciones_parametro | 286 | 289 | 286 | 286 | 77305ad3765c11925191bac5231e116332471de5 | bigcode/the-stack | train |
29b2f985257d30f47d725198 | train | function | def parse(input) :
return parser.parse(input)
| def parse(input) :
| return parser.parse(input)
| ] = Delete_incondicional(t[1])
print("Eliminar tabla: " + t[1])
def p_error(t):
print(t)
print("Error sintáctico en '%s'" % t.value)
import ply.yacc as yacc
parser = yacc.yacc()
def parse(input) :
| 64 | 64 | 11 | 5 | 59 | webdev188/tytus | parser/team22/gramatica.py | Python | parse | parse | 352 | 353 | 352 | 352 | ca2887f876b3b7d0c951752320f8aa6f8cb36c14 | bigcode/the-stack | train |
d0a4840d06ce584ee938590c | train | function | def p_instruccion_crear_TB(t) :
'''crear_tb : ID PARIZQ crear_tb_columnas PARDER crear_tb_herencia PTCOMA
| ID PARIZQ crear_tb_columnas PARDER crear_tb_herencia
| ID PARIZQ crear_tb_columnas PARDER PTCOMA
| ID PARIZQ crear_tb_columnas PARDER'''
... | def p_instruccion_crear_TB(t) :
| '''crear_tb : ID PARIZQ crear_tb_columnas PARDER crear_tb_herencia PTCOMA
| ID PARIZQ crear_tb_columnas PARDER crear_tb_herencia
| ID PARIZQ crear_tb_columnas PARDER PTCOMA
| ID PARIZQ crear_tb_columnas PARDER'''
if t[5] != None and t[5] != ';... | _tb'''
print("Creacion")
def p_instruccion_crear_BD(t) :
'crear_bd : ID PTCOMA'
t[0] = Crear_BD(t[1])
print("Creacion de BD")
def p_instruccion_crear_TB(t) :
| 64 | 64 | 194 | 12 | 52 | webdev188/tytus | parser/team22/gramatica.py | Python | p_instruccion_crear_TB | p_instruccion_crear_TB | 247 | 258 | 247 | 247 | c78e79751810073fdc94802ac0779314a132c63d | bigcode/the-stack | train |
0f74b3d3246fb054c608d166 | train | function | def t_DECIMAL(t):
r'\d+\.\d+'
try:
t.value = float(t.value)
except ValueError:
print("Float value too large %d", t.value)
t.value = 0
return t
| def t_DECIMAL(t):
| r'\d+\.\d+'
try:
t.value = float(t.value)
except ValueError:
print("Float value too large %d", t.value)
t.value = 0
return t
| ACION_MULT = r'\*='
t_ASIGNACION_DIVID = r'\/='
t_ASIGNACION_MODULO = r'\%='
t_DOS_PUNTOS = r'\:'
t_DIAG_INVERSA = r'\\'
def t_DECIMAL(t):
| 64 | 64 | 55 | 6 | 58 | webdev188/tytus | parser/team22/gramatica.py | Python | t_DECIMAL | t_DECIMAL | 145 | 152 | 145 | 145 | da56c5b2602ca7ccdf21ebe14759b4708e27fdc1 | bigcode/the-stack | train |
2b9eee7349bc25585299f768 | train | function | def t_CADENA(t):
r'\".*?\"'
t.value = t.value[1:-1] # remuevo las comillas
return t
| def t_CADENA(t):
| r'\".*?\"'
t.value = t.value[1:-1] # remuevo las comillas
return t
| .value = 0
return t
def t_ID(t):
r'[a-zA-Z_][a-zA-Z_0-9]*'
t.type = reservadas.get(t.value.lower(),'ID') # Check for reserved words
return t
def t_CADENA(t):
| 64 | 64 | 37 | 7 | 56 | webdev188/tytus | parser/team22/gramatica.py | Python | t_CADENA | t_CADENA | 168 | 171 | 168 | 168 | 9204500368a26c221fa82f3ed2c90dae74e17474 | bigcode/the-stack | train |
b28239a3e1c522d6f5674d9a | train | function | def p_instruccion_delete_incondicional(t) :
'delete_incondicional : ID PTCOMA'
t[0] = Delete_incondicional(t[1])
| def p_instruccion_delete_incondicional(t) :
| 'delete_incondicional : ID PTCOMA'
t[0] = Delete_incondicional(t[1])
|
#========================================================
# INSTRUCCION CON "DELETE"
def p_instruccion_delete(t) :
'''deletes : ID PTCOMA WHERE delete_condicional
| delete_incondicional'''
print("ELIMINACION")
def p_instruccion_delete_incondicional(t) :
| 64 | 64 | 39 | 12 | 52 | webdev188/tytus | parser/team22/gramatica.py | Python | p_instruccion_delete_incondicional | p_instruccion_delete_incondicional | 335 | 337 | 335 | 335 | 693299cf4fbd1b6feb041e9c1bf5ae091044aa00 | bigcode/the-stack | train |
2bf4c972f69fcd1784b7940a | train | function | @pytest.fixture
def currency_unit():
return Currency.JPY
| @pytest.fixture
def currency_unit():
| return Currency.JPY
| math
import pandas as pd
import pytest
import backlight.datasource
from backlight.trades import trades as tr
from backlight.trades.trades import make_trades
from backlight.asset.currency import Currency
@pytest.fixture
def symbol():
return "USDJPY"
@pytest.fixture
def currency_unit():
| 64 | 64 | 13 | 7 | 57 | AlpacaDB/backlight | tests/metrics/test_trade_metrics.py | Python | currency_unit | currency_unit | 17 | 19 | 17 | 18 | 3230a491aa297c0bd3776af0c55cb89fa8d78803 | bigcode/the-stack | train |
dd8d13fca76346e28ee79aff | train | function | @pytest.fixture
def closed_trades(symbol, currency_unit):
data = [1.0, -1.0, 2.0, -2.0, -4.0, 4.0, 1.0, -1.0, 1.0, -1.0]
index = pd.date_range(start="2018-06-06", freq="1D", periods=len(data))
trades = []
for i in range(0, len(data), 2):
trade = pd.Series(index=index[i : i + 2], data=data[i : i ... | @pytest.fixture
def closed_trades(symbol, currency_unit):
| data = [1.0, -1.0, 2.0, -2.0, -4.0, 4.0, 1.0, -1.0, 1.0, -1.0]
index = pd.date_range(start="2018-06-06", freq="1D", periods=len(data))
trades = []
for i in range(0, len(data), 2):
trade = pd.Series(index=index[i : i + 2], data=data[i : i + 2], name="amount")
trades.append(trade)
trad... | ):
trade = pd.Series(index=index[i : i + 2], data=data[i : i + 2], name="amount")
trades.append(trade)
trades = tr.make_trades(symbol, trades, currency_unit)
return trades
@pytest.fixture
def closed_trades(symbol, currency_unit):
| 64 | 64 | 158 | 12 | 51 | AlpacaDB/backlight | tests/metrics/test_trade_metrics.py | Python | closed_trades | closed_trades | 45 | 54 | 45 | 46 | 61d1450ef0fac48ff8f3d4c43852c30423dcddf4 | bigcode/the-stack | train |
141a611e5d4d2b11395f0348 | train | function | def test_calculate_trade_performance(trades, market):
principal = 100.0
metrics = module.calculate_trade_performance(trades, market, principal=principal)
expected_cnt_trade = 5
expected_cnt_win = 3
expected_cnt_lose = 1
expected_total_pl = 2.0
expected_win_pl = 5.0
expected_lose_pl = -3... | def test_calculate_trade_performance(trades, market):
| principal = 100.0
metrics = module.calculate_trade_performance(trades, market, principal=principal)
expected_cnt_trade = 5
expected_cnt_win = 3
expected_cnt_lose = 1
expected_total_pl = 2.0
expected_win_pl = 5.0
expected_lose_pl = -3.0
expected_trade_amount = 14.0
expected_sharp... | 2]], columns=["mid"]),
symbol,
currency_unit,
)
trade = tr.make_trade([t00, t11])
assert module._calculate_pl(trade, mkt) == 1.0
trade = tr.make_trade([t00, t01])
assert module._calculate_pl(trade, mkt) == 0.0
trade = tr.make_trade([t11, t20])
assert module._calculate_pl(t... | 154 | 154 | 516 | 12 | 141 | AlpacaDB/backlight | tests/metrics/test_trade_metrics.py | Python | test_calculate_trade_performance | test_calculate_trade_performance | 87 | 122 | 87 | 87 | 1dd98dd6fb29d5f71a5f72c08c5bb553c1013565 | bigcode/the-stack | train |
a285bfc4556e209c19a56155 | train | function | def test_calculate_trade_performance_with_closed_trades(closed_trades, market):
principal = 100.0
metrics = module.calculate_trade_performance(
closed_trades, market, principal=principal
)
expected_cnt_trade = 5
expected_cnt_win = 3
expected_cnt_lose = 1
expected_total_pl = 0
ex... | def test_calculate_trade_performance_with_closed_trades(closed_trades, market):
| principal = 100.0
metrics = module.calculate_trade_performance(
closed_trades, market, principal=principal
)
expected_cnt_trade = 5
expected_cnt_win = 3
expected_cnt_lose = 1
expected_total_pl = 0
expected_win_pl = 4.0
expected_lose_pl = -4.0
expected_trade_amount = 18
... | "] == expected_sharpe
assert metrics.loc["metrics", "sharpe"] == expected_sharpe
assert metrics.loc["metrics", "max_drawdown"] == expected_max_drawdown
assert metrics.loc["metrics", "avg_win_pl"] == expected_avg_win_pl
assert metrics.loc["metrics", "avg_lose_pl"] == expected_avg_lose_pl
assert metri... | 152 | 152 | 508 | 18 | 133 | AlpacaDB/backlight | tests/metrics/test_trade_metrics.py | Python | test_calculate_trade_performance_with_closed_trades | test_calculate_trade_performance_with_closed_trades | 125 | 161 | 125 | 125 | f9522556b4a82ea0e940d5daae073eb5fb7e7644 | bigcode/the-stack | train |
d8e4cc44dee641afe0b32ee9 | train | function | @pytest.mark.parametrize(
"a_trades, total_count, win_count, lose_count",
[[trades, 5, 3, 1], [closed_trades, 5, 3, 1]],
)
def test_count_trades(a_trades, total_count, win_count, lose_count, market):
assert (total_count, win_count, lose_count) == module.count_trades(
a_trades(symbol(), currency_unit... | @pytest.mark.parametrize(
"a_trades, total_count, win_count, lose_count",
[[trades, 5, 3, 1], [closed_trades, 5, 3, 1]],
)
def test_count_trades(a_trades, total_count, win_count, lose_count, market):
| assert (total_count, win_count, lose_count) == module.count_trades(
a_trades(symbol(), currency_unit()), market
)
| @pytest.mark.parametrize(
"a_trades, total_count, win_count, lose_count",
[[trades, 5, 3, 1], [closed_trades, 5, 3, 1]],
)
def test_count_trades(a_trades, total_count, win_count, lose_count, market):
| 68 | 64 | 99 | 68 | 0 | AlpacaDB/backlight | tests/metrics/test_trade_metrics.py | Python | test_count_trades | test_count_trades | 164 | 171 | 164 | 168 | 49c578bf6c1a385447b2adb60807e6f3b96288e9 | bigcode/the-stack | train |
c3c1ee179d6cc33dabfd4ae9 | train | function | def test_calculate_trade_performance_for_sametime_trade_case():
symbol = "USDJPY"
data = [[1.0], [2.0], [3.0]]
df = pd.DataFrame(
index=pd.date_range(start="2019-06-06", freq="3S", periods=len(data)),
data=data,
columns=["mid"],
)
mid = backlight.datasource.from_dataframe(df,... | def test_calculate_trade_performance_for_sametime_trade_case():
| symbol = "USDJPY"
data = [[1.0], [2.0], [3.0]]
df = pd.DataFrame(
index=pd.date_range(start="2019-06-06", freq="3S", periods=len(data)),
data=data,
columns=["mid"],
)
mid = backlight.datasource.from_dataframe(df, symbol, Currency.USD)
data = [-1.0, 1.0]
sr = pd.Serie... | _win_pl"] == expected_avg_win_pl
assert metrics.loc["metrics", "avg_lose_pl"] == expected_avg_lose_pl
assert metrics.loc["metrics", "avg_pl_per_trade"] == expected_avg_pl_per_trade
assert metrics.loc["metrics", "win_ratio"] == expected_win_ratio
assert metrics.loc["metrics", "lose_ratio"] == expected_lo... | 195 | 195 | 650 | 14 | 181 | AlpacaDB/backlight | tests/metrics/test_trade_metrics.py | Python | test_calculate_trade_performance_for_sametime_trade_case | test_calculate_trade_performance_for_sametime_trade_case | 174 | 229 | 174 | 174 | ddb554393009827208835abbd8c2ce6b524718cd | bigcode/the-stack | train |
809e82f768a88fa339cea470 | train | function | @pytest.fixture
def symbol():
return "USDJPY"
| @pytest.fixture
def symbol():
| return "USDJPY"
| from backlight.metrics import trade_metrics as module
import math
import pandas as pd
import pytest
import backlight.datasource
from backlight.trades import trades as tr
from backlight.trades.trades import make_trades
from backlight.asset.currency import Currency
@pytest.fixture
def symbol():
| 62 | 64 | 12 | 6 | 55 | AlpacaDB/backlight | tests/metrics/test_trade_metrics.py | Python | symbol | symbol | 12 | 14 | 12 | 13 | 538988a9f047128d5ed78c26ae597f37e1ed8074 | bigcode/the-stack | train |
4239dca4729b6fc81e41f714 | train | function | @pytest.fixture
def trades(symbol, currency_unit):
data = [1.0, -2.0, 1.0, 2.0, -4.0, 2.0, 1.0, 0.0, 1.0, 0.0]
index = pd.date_range(start="2018-06-06", freq="1D", periods=len(data))
trades = []
for i in range(0, len(data), 2):
trade = pd.Series(index=index[i : i + 2], data=data[i : i + 2], name... | @pytest.fixture
def trades(symbol, currency_unit):
| data = [1.0, -2.0, 1.0, 2.0, -4.0, 2.0, 1.0, 0.0, 1.0, 0.0]
index = pd.date_range(start="2018-06-06", freq="1D", periods=len(data))
trades = []
for i in range(0, len(data), 2):
trade = pd.Series(index=index[i : i + 2], data=data[i : i + 2], name="amount")
trades.append(trade)
trades ... | df = pd.DataFrame(
index=pd.date_range(start="2018-06-06", freq="1D", periods=len(data)),
data=data,
columns=["mid"],
)
return backlight.datasource.from_dataframe(df, symbol, currency_unit)
@pytest.fixture
def trades(symbol, currency_unit):
| 64 | 64 | 156 | 10 | 54 | AlpacaDB/backlight | tests/metrics/test_trade_metrics.py | Python | trades | trades | 33 | 42 | 33 | 34 | cdb7f534ff8574e3da920fc7789587f4608056c9 | bigcode/the-stack | train |
e62a1fd62cc76b7fc4da982d | train | function | def test__calculate_pl(symbol, currency_unit):
periods = 3
dates = pd.date_range(start="2018-12-01", periods=periods)
amounts = [1.0, -1.0]
t00 = tr.Transaction(timestamp=dates[0], amount=amounts[0])
t11 = tr.Transaction(timestamp=dates[1], amount=amounts[1])
t10 = tr.Transaction(timestamp=date... | def test__calculate_pl(symbol, currency_unit):
| periods = 3
dates = pd.date_range(start="2018-12-01", periods=periods)
amounts = [1.0, -1.0]
t00 = tr.Transaction(timestamp=dates[0], amount=amounts[0])
t11 = tr.Transaction(timestamp=dates[1], amount=amounts[1])
t10 = tr.Transaction(timestamp=dates[1], amount=amounts[0])
t01 = tr.Transacti... | -06-06", freq="1D", periods=len(data))
trades = []
for i in range(0, len(data), 2):
trade = pd.Series(index=index[i : i + 2], data=data[i : i + 2], name="amount")
trades.append(trade)
trades = module.make_trades(symbol, trades, currency_unit)
return trades
def test__calculate_pl(symbol, ... | 93 | 93 | 312 | 10 | 82 | AlpacaDB/backlight | tests/metrics/test_trade_metrics.py | Python | test__calculate_pl | test__calculate_pl | 57 | 84 | 57 | 57 | 7fbc16d4b63eca4227c2897539823fc5067e5838 | bigcode/the-stack | train |
b6cf12dbb3e6b1dac4a13f75 | train | function | @pytest.fixture
def market(symbol, currency_unit):
data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0], [9.0], [9.0]]
df = pd.DataFrame(
index=pd.date_range(start="2018-06-06", freq="1D", periods=len(data)),
data=data,
columns=["mid"],
)
return backlight.datasource.fro... | @pytest.fixture
def market(symbol, currency_unit):
| data = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0], [9.0], [9.0]]
df = pd.DataFrame(
index=pd.date_range(start="2018-06-06", freq="1D", periods=len(data)),
data=data,
columns=["mid"],
)
return backlight.datasource.from_dataframe(df, symbol, currency_unit)
| backlight.trades import trades as tr
from backlight.trades.trades import make_trades
from backlight.asset.currency import Currency
@pytest.fixture
def symbol():
return "USDJPY"
@pytest.fixture
def currency_unit():
return Currency.JPY
@pytest.fixture
def market(symbol, currency_unit):
| 64 | 64 | 118 | 10 | 53 | AlpacaDB/backlight | tests/metrics/test_trade_metrics.py | Python | market | market | 22 | 30 | 22 | 23 | 4d0b2e8e2126dbee21249e5e91d315600ca53fed | bigcode/the-stack | train |
8a44731d0d66478cfa89dbd9 | train | class | class SinkhornDivergenceTest(jax.test_util.JaxTestCase):
def setUp(self):
super().setUp()
self.rng = jax.random.PRNGKey(0)
self._dim = 4
self._num_points = 30, 37
self.rng, *rngs = jax.random.split(self.rng, 3)
a = jax.random.uniform(rngs[0], (self._num_points[0],))
b = jax.random.uniform... | class SinkhornDivergenceTest(jax.test_util.JaxTestCase):
| def setUp(self):
super().setUp()
self.rng = jax.random.PRNGKey(0)
self._dim = 4
self._num_points = 30, 37
self.rng, *rngs = jax.random.split(self.rng, 3)
a = jax.random.uniform(rngs[0], (self._num_points[0],))
b = jax.random.uniform(rngs[1], (self._num_points[1],))
self._a = a / jnp.su... | # coding=utf-8
# Copyright 2021 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | 216 | 256 | 1,392 | 16 | 199 | bamos/ott | tests/tools/sinkhorn_divergence_test.py | Python | SinkhornDivergenceTest | SinkhornDivergenceTest | 28 | 134 | 28 | 29 | d23df42e257e4d61a1726c418c2b9661364adb60 | bigcode/the-stack | train |
1e0feb9db01fe48c6526f7cf | train | class | @pytest.mark.usefixtures("user_model")
class TestForgotPasswordSchema:
def test_it_is_invalid_with_no_user(self, pyramid_csrf_request, user_model):
schema = ForgotPasswordSchema().bind(request=pyramid_csrf_request)
user_model.get_by_email.return_value = None
with pytest.raises(colander.Inva... | @pytest.mark.usefixtures("user_model")
class TestForgotPasswordSchema:
| def test_it_is_invalid_with_no_user(self, pyramid_csrf_request, user_model):
schema = ForgotPasswordSchema().bind(request=pyramid_csrf_request)
user_model.get_by_email.return_value = None
with pytest.raises(colander.Invalid) as exc:
schema.deserialize({"email": "rapha@example.co... | import colander
import pytest
from h.schemas.forms.accounts import ForgotPasswordSchema
pytestmark = pytest.mark.usefixtures("pyramid_config")
@pytest.mark.usefixtures("user_model")
class TestForgotPasswordSchema:
| 43 | 64 | 179 | 14 | 29 | tgiardina/rpp-h | tests/h/schemas/forms/accounts/forgot_password_test.py | Python | TestForgotPasswordSchema | TestForgotPasswordSchema | 9 | 27 | 9 | 10 | 25a155265e295b2373e9a0b396e9e5e208df6dd6 | bigcode/the-stack | train |
744bfbae3146c00c6c2eb5de | train | function | @pytest.fixture
def user_model(patch):
return patch("h.accounts.schemas.models.User")
| @pytest.fixture
def user_model(patch):
| return patch("h.accounts.schemas.models.User")
| user_model):
schema = ForgotPasswordSchema().bind(request=pyramid_csrf_request)
user = user_model.get_by_email.return_value
appstruct = schema.deserialize({"email": "rapha@example.com"})
assert appstruct["user"] == user
@pytest.fixture
def user_model(patch):
| 64 | 64 | 19 | 9 | 54 | tgiardina/rpp-h | tests/h/schemas/forms/accounts/forgot_password_test.py | Python | user_model | user_model | 30 | 32 | 30 | 31 | f2c2a7d8b3e0c8e2aa22396d78ceeff529344f05 | bigcode/the-stack | train |
67ca416f1b786801ba446a18 | train | class | class Light:
pass
| class Light:
| pass
| class Light:
| 3 | 64 | 6 | 3 | 0 | minefarmer/Coding101-OOP | .history/py/main_20210614163102.py | Python | Light | Light | 1 | 2 | 1 | 1 | 9efa7b300ae99a7be744382b8998eb5ee5803338 | bigcode/the-stack | train |
53a32fe3b65d1e5ac1c5b542 | train | class | class TestIsIdentity(unittest.TestCase):
"""
Defines :func:`colour.algebra.matrix.is_identity` definition unit tests
methods.
"""
def test_is_identity(self):
"""
Tests :func:`colour.algebra.matrix.is_identity` definition.
"""
self.assertTrue(
is_identity... | class TestIsIdentity(unittest.TestCase):
| """
Defines :func:`colour.algebra.matrix.is_identity` definition unit tests
methods.
"""
def test_is_identity(self):
"""
Tests :func:`colour.algebra.matrix.is_identity` definition.
"""
self.assertTrue(
is_identity(np.array([1, 0, 0, 0, 1, 0, 0, 0, 1]).re... | = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'
__maintainer__ = 'Colour Developers'
__email__ = 'colour-science@googlegroups.com'
__status__ = 'Production'
__all__ = ['TestIsIdentity']
class TestIsIdentity(unittest.TestCase):
| 64 | 64 | 210 | 8 | 56 | canavandl/colour | colour/algebra/tests/tests_matrix.py | Python | TestIsIdentity | TestIsIdentity | 30 | 48 | 30 | 30 | e959a83be1983c92787615f68b046cef72aa317c | bigcode/the-stack | train |
fb55bd4ce4b1020f98c4f089 | train | class | class NopExpert(nn.Sequential):
def __init__(self, hid_dim):
super().__init__()
self.w = nn.Parameter(torch.zeros(0), requires_grad=True)
def forward(self, x):
return x.clone()
| class NopExpert(nn.Sequential):
| def __init__(self, hid_dim):
super().__init__()
self.w = nn.Parameter(torch.zeros(0), requires_grad=True)
def forward(self, x):
return x.clone()
| )
src = self.norm1(src)
src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
src = src + self.dropout2(src2)
src = self.norm2(src)
src.transpose_(0, 1)
return src
class NopExpert(nn.Sequential):
| 64 | 64 | 49 | 7 | 56 | xtinkt/hivemind | tests/test_utils/layers.py | Python | NopExpert | NopExpert | 54 | 60 | 54 | 54 | 98c537b8dd60648451b409a566fdc4994e1bf6fd | bigcode/the-stack | train |
56fe01b66133ba4b5dc12b20 | train | class | class TransformerEncoderLayer(nn.Module):
"""
A slight modification of torch.nn.TransformerEncoderLayer which allows for torch.jit scripting
"""
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1):
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhea... | class TransformerEncoderLayer(nn.Module):
| """
A slight modification of torch.nn.TransformerEncoderLayer which allows for torch.jit scripting
"""
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1):
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
# Implementati... | nn.LayerNorm(4 * hid_dim),
nn.ReLU(inplace=True),
nn.Linear(4 * hid_dim, 4 * hid_dim),
nn.LayerNorm(4 * hid_dim),
nn.ReLU(inplace=True),
nn.Linear(4 * hid_dim, hid_dim),
)
def forward(self, x):
return x + self.layers(x)
class TransformerE... | 84 | 84 | 281 | 7 | 77 | xtinkt/hivemind | tests/test_utils/layers.py | Python | TransformerEncoderLayer | TransformerEncoderLayer | 22 | 51 | 22 | 22 | 26547829965348c768037055f2a7961de8537e84 | bigcode/the-stack | train |
6f1033ebaa05a326aab2963a | train | class | class FeedforwardBlock(nn.Module):
def __init__(self, hid_dim):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(hid_dim, 4 * hid_dim),
nn.LayerNorm(4 * hid_dim),
nn.ReLU(inplace=True),
nn.Linear(4 * hid_dim, 4 * hid_dim),
nn.Layer... | class FeedforwardBlock(nn.Module):
| def __init__(self, hid_dim):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(hid_dim, 4 * hid_dim),
nn.LayerNorm(4 * hid_dim),
nn.ReLU(inplace=True),
nn.Linear(4 * hid_dim, 4 * hid_dim),
nn.LayerNorm(4 * hid_dim),
nn.R... | import torch
from torch import nn as nn
class FeedforwardBlock(nn.Module):
| 17 | 64 | 120 | 7 | 9 | xtinkt/hivemind | tests/test_utils/layers.py | Python | FeedforwardBlock | FeedforwardBlock | 5 | 19 | 5 | 5 | 6d9f69297074b776a2f2b159f2f18821c7c06b75 | bigcode/the-stack | train |
5b686b587ed95d14ca976221 | train | function | def start_web_server():
AsyncIOMainLoop().install()
app = tornado.web.Application([
(r'/vdpreview', WebHandler, {'runner': CutServer.vdpreview}),
(r'/vdfilter', CutHandler, {'runner': CutServer}),
(r'/addfeature', AddHandler),
], debug=True
)
http_server = tornado.httpserver... | def start_web_server():
| AsyncIOMainLoop().install()
app = tornado.web.Application([
(r'/vdpreview', WebHandler, {'runner': CutServer.vdpreview}),
(r'/vdfilter', CutHandler, {'runner': CutServer}),
(r'/addfeature', AddHandler),
], debug=True
)
http_server = tornado.httpserver.HTTPServer(app)
http... | filepaths = os.listdir(os.path.join(os.getcwd(), video_path))
for filepath in dirfilepaths:
filepath = os.path.join(video_path, filepath)
video_list[filepath] = str(filepath)
return {'video_path': video_path, 'video_list': video_list}
def start_web_server():
| 64 | 64 | 112 | 5 | 59 | kalenforn/video-context-analyze | Server/videoProcessServer/cutServer.py | Python | start_web_server | start_web_server | 693 | 705 | 693 | 694 | 13a2fbeec095f3dce98a1712eea960ebfec765fb | bigcode/the-stack | train |
0c058bdf5a41a31e85a01174 | train | function | def get_face_data(face_feature_dict: dict, key_words: list):
key_name = []
face_feature = []
for item in key_words:
key_name.append(item)
face_feature.append(face_feature_dict[item])
return key_name, face_feature
| def get_face_data(face_feature_dict: dict, key_words: list):
| key_name = []
face_feature = []
for item in key_words:
key_name.append(item)
face_feature.append(face_feature_dict[item])
return key_name, face_feature
| are {} face feature".format(str(datetime.datetime.now()).split('.')[0], len(feature_dict))
write_log(message=message, file_=os.path.join(LOG_DIR, 'run-' + pr_id + '.log'))
return feature_dict
def get_face_data(face_feature_dict: dict, key_words: list):
| 64 | 64 | 55 | 15 | 48 | kalenforn/video-context-analyze | Server/videoProcessServer/cutServer.py | Python | get_face_data | get_face_data | 59 | 66 | 59 | 59 | e81bd66ad23155c7f5cd7327fe586e32fb840dbf | bigcode/the-stack | train |
b5c45e38c9ce4c9b583aa8b6 | train | function | def wait_to_create(file_name: str, process_name: str, pr_id: str) -> None:
while not os.path.exists(file_name) or os.path.getsize(file_name) == 0:
time.sleep(1)
message = "[INFO]: {} This process: {} is loading ... ...".format(str(datetime.datetime.now()).split('.')[0], process_name)
write_l... | def wait_to_create(file_name: str, process_name: str, pr_id: str) -> None:
| while not os.path.exists(file_name) or os.path.getsize(file_name) == 0:
time.sleep(1)
message = "[INFO]: {} This process: {} is loading ... ...".format(str(datetime.datetime.now()).split('.')[0], process_name)
write_log(message=message, file_=os.path.join(LOG_DIR, 'run-' + pr_id + '.log'))
| ktime_form, mktime_sec
from .mysqlTools import SQLHold
LOG_DIR = os.path.join('log', 'cutServer')
if not os.path.exists(LOG_DIR):
os.mkdir(LOG_DIR)
def wait_to_create(file_name: str, process_name: str, pr_id: str) -> None:
| 64 | 64 | 103 | 22 | 42 | kalenforn/video-context-analyze | Server/videoProcessServer/cutServer.py | Python | wait_to_create | wait_to_create | 37 | 41 | 37 | 37 | 938b4448ab233badb9496b24514fb5baa7e4d53b | bigcode/the-stack | train |
e9a256e1dfad281feaafca5b | train | function | def get_feature(mysql: SQLHold, pr_id: str) -> dict:
message = "[INFO]: {} Get feature.".format(str(datetime.datetime.now()).split('.')[0])
write_log(message=message, file_=os.path.join(LOG_DIR, 'run-' + pr_id + '.log'))
command = 'select * from face_feature'
mysql.execute_command(command)
result = ... | def get_feature(mysql: SQLHold, pr_id: str) -> dict:
| message = "[INFO]: {} Get feature.".format(str(datetime.datetime.now()).split('.')[0])
write_log(message=message, file_=os.path.join(LOG_DIR, 'run-' + pr_id + '.log'))
command = 'select * from face_feature'
mysql.execute_command(command)
result = mysql.fetchall()
feature_dict = {}
for i, nam... | {} This process: {} is loading ... ...".format(str(datetime.datetime.now()).split('.')[0], process_name)
write_log(message=message, file_=os.path.join(LOG_DIR, 'run-' + pr_id + '.log'))
def get_feature(mysql: SQLHold, pr_id: str) -> dict:
| 64 | 64 | 186 | 16 | 48 | kalenforn/video-context-analyze | Server/videoProcessServer/cutServer.py | Python | get_feature | get_feature | 43 | 56 | 43 | 43 | c96f406a40306c993436ecf9a4bb81d58fbb41bb | bigcode/the-stack | train |
99bfce6ec8282e3e9f5baa53 | train | class | class CutServer(mp.Process):
def __init__(self, data: dict):
super(CutServer, self).__init__()
self.data = data
self.__sended = []
self.__send_count = 0
self.key_words = []
self.cap = None
self.mysql = None
self.mode = data['video_mode']
self.... | class CutServer(mp.Process):
| def __init__(self, data: dict):
super(CutServer, self).__init__()
self.data = data
self.__sended = []
self.__send_count = 0
self.key_words = []
self.cap = None
self.mysql = None
self.mode = data['video_mode']
self.video_name = data['video_name'... | .".format(str(datetime.datetime.now()).split('.')[0])
write_log(message=message, file_=os.path.join(LOG_DIR, 'run-' + pr_id + '.log'))
command = 'select * from face_feature'
mysql.execute_command(command)
result = mysql.fetchall()
feature_dict = {}
for i, name, item in result:
item = np.... | 256 | 256 | 7,125 | 6 | 250 | kalenforn/video-context-analyze | Server/videoProcessServer/cutServer.py | Python | CutServer | CutServer | 70 | 690 | 70 | 71 | 8125123b9d028aec09d358a48337152987542ff9 | bigcode/the-stack | train |
afe11ea1b1a9779a1eae5d8b | train | function | def spearman_formula(predictions, labels, mask=None):
"""
This function is spearman formula from:
https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient
"""
if mask is not None:
predictions = predictions * mask
labels = labels * mask
# if all number... | def spearman_formula(predictions, labels, mask=None):
| """
This function is spearman formula from:
https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient
"""
if mask is not None:
predictions = predictions * mask
labels = labels * mask
# if all number of a set is same, return np.nan
if len(torch.uniq... | import math
import torch
from torch.testing import assert_allclose
from allennlp.common.testing import AllenNlpTestCase, multi_device
from allennlp.training.metrics import SpearmanCorrelation
def spearman_formula(predictions, labels, mask=None):
| 53 | 92 | 309 | 12 | 40 | pengshuang/allennlp | tests/training/metrics/spearman_correlation_test.py | Python | spearman_formula | spearman_formula | 10 | 40 | 10 | 10 | 6a0f9e06736fbf7677185afce1173340b43f2fc4 | bigcode/the-stack | train |
dcfb69c5e189b4cd14a77000 | train | class | class SpearmanCorrelationTest(AllenNlpTestCase):
@multi_device
def test_unmasked_computation(self, device: str):
spearman_correlation = SpearmanCorrelation()
batch_size = 10
num_labels = 10
predictions1 = torch.randn(batch_size, num_labels, device=device)
labels1 =... | class SpearmanCorrelationTest(AllenNlpTestCase):
@multi_device
| def test_unmasked_computation(self, device: str):
spearman_correlation = SpearmanCorrelation()
batch_size = 10
num_labels = 10
predictions1 = torch.randn(batch_size, num_labels, device=device)
labels1 = 0.5 * predictions1 + torch.randn(batch_size, num_labels, device=devi... | of a set is same, return np.nan
if len(torch.unique(predictions)) == 1 or len(torch.unique(labels)) == 1:
return float("NaN")
len_pre = len(predictions)
predictions = [(k, v) for k, v in enumerate(predictions)]
predictions.sort(key=lambda x: x[1], reverse=True)
predictions = [(k, ... | 256 | 256 | 925 | 17 | 238 | pengshuang/allennlp | tests/training/metrics/spearman_correlation_test.py | Python | SpearmanCorrelationTest | SpearmanCorrelationTest | 43 | 126 | 43 | 44 | 1e41993d4681ad656536651eb97573e56d4cee6c | bigcode/the-stack | train |
0094bedc18bdce73ac647085 | train | class | class BaseA3CLearner(ActorLearner):
def __init__(self, args):
super(BaseA3CLearner, self).__init__(args)
self.td_lambda = args.td_lambda
self.action_space = args.action_space
self.learning_vars = args.learning_vars
self.beta = args.entropy_regularisation_strength
sel... | class BaseA3CLearner(ActorLearner):
| def __init__(self, args):
super(BaseA3CLearner, self).__init__(args)
self.td_lambda = args.td_lambda
self.action_space = args.action_space
self.learning_vars = args.learning_vars
self.beta = args.entropy_regularisation_strength
self.q_target_update_steps = args.q_tar... | # -*- encoding: utf-8 -*-
import time
import numpy as np
import utils.logger
import tensorflow as tf
from collections import deque
from utils import checkpoint_utils
from utils.decorators import only_on_train
from actor_learner import ActorLearner, ONE_LIFE_GAMES
from networks.policy_v_network import PolicyValueNetwork... | 96 | 256 | 1,007 | 12 | 84 | LihaoR/tensorflow-rl | algorithms/policy_based_actor_learner.py | Python | BaseA3CLearner | BaseA3CLearner | 16 | 143 | 16 | 16 | b07db4cfcbc083feeb06fd0958300ca408bd53b2 | bigcode/the-stack | train |
41f709212c92b198915d61dd | train | class | class A3CLearner(BaseA3CLearner):
def __init__(self, args):
super(A3CLearner, self).__init__(args)
conf_learning = {'name': 'local_learning_{}'.format(self.actor_id),
'input_shape': self.input_shape,
'num_act': self.num_actions,
... | class A3CLearner(BaseA3CLearner):
| def __init__(self, args):
super(A3CLearner, self).__init__(args)
conf_learning = {'name': 'local_learning_{}'.format(self.actor_id),
'input_shape': self.input_shape,
'num_act': self.num_actions,
'args': args}
self.l... | /s".format(
self.actor_id,
self.local_episode,
self.global_step.value()/1000,
np.array(episode_rewards).mean(),
perf))
self.log_summary(total_episode_reward, np.array(values).mean(), entropy)
class A3CLearner(BaseA3CLearner):
| 64 | 64 | 161 | 13 | 51 | LihaoR/tensorflow-rl | algorithms/policy_based_actor_learner.py | Python | A3CLearner | A3CLearner | 146 | 165 | 146 | 146 | bfeebb13a99acd9979d3aeb4bf36fe44f155205f | bigcode/the-stack | train |
1e35d55eb2e55d1d85a05cdb | train | class | class A3CLSTMLearner(BaseA3CLearner):
def __init__(self, args):
super(A3CLSTMLearner, self).__init__(args)
conf_learning = {'name': 'local_learning_{}'.format(self.actor_id),
'input_shape': self.input_shape,
'num_act': self.num_actions,
... | class A3CLSTMLearner(BaseA3CLearner):
| def __init__(self, args):
super(A3CLSTMLearner, self).__init__(args)
conf_learning = {'name': 'local_learning_{}'.format(self.actor_id),
'input_shape': self.input_shape,
'num_act': self.num_actions,
'args': args}
se... | (A3CLearner, self).__init__(args)
conf_learning = {'name': 'local_learning_{}'.format(self.actor_id),
'input_shape': self.input_shape,
'num_act': self.num_actions,
'args': args}
self.local_network = args.network(conf_learning)
... | 152 | 152 | 507 | 15 | 137 | LihaoR/tensorflow-rl | algorithms/policy_based_actor_learner.py | Python | A3CLSTMLearner | A3CLSTMLearner | 168 | 232 | 168 | 168 | 99c9c3bcf682fd9dd1fab33a021250545cf00a89 | bigcode/the-stack | train |
d47e6df34464a31b68e48ad1 | train | function | def create(kernel):
result = Tangible()
result.template = "object/tangible/component/armor/shared_base_armor_segment_enhancement.iff"
result.attribute_template_id = -1
result.stfName("craft_clothing_ingredients_n","armor_segment_enhancement")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
ret... | def create(kernel):
| result = Tangible()
result.template = "object/tangible/component/armor/shared_base_armor_segment_enhancement.iff"
result.attribute_template_id = -1
result.stfName("craft_clothing_ingredients_n","armor_segment_enhancement")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
| 46 | 64 | 77 | 4 | 42 | obi-two/GameServer | data/scripts/templates/object/tangible/component/armor/shared_base_armor_segment_enhancement.py | Python | create | create | 7 | 17 | 7 | 7 | c2a443492819d1193a2d5661616972ccb0ecdd03 | bigcode/the-stack | train |
52f47aa667d19cb63acc658a | train | function | def _jupyter_server_extension_paths():
return [{"module": "pymango"}]
| def _jupyter_server_extension_paths():
| return [{"module": "pymango"}]
|
"""A Jupyter notebook server extension logging to Azure/Microsoft"""
import os
from notebook.utils import url_path_join
from .auth_handler import AuthenticateHandler, CallbackHandler, GetTokens
def _jupyter_server_extension_paths():
| 48 | 64 | 19 | 8 | 39 | cccs-is/pymango | pymango_server/__init__.py | Python | _jupyter_server_extension_paths | _jupyter_server_extension_paths | 9 | 10 | 9 | 9 | b8cd970507fdf2d88228b1aa780b760f3d6c6165 | bigcode/the-stack | train |
96c64341adc1e69a6dd39ad9 | train | function | def load_jupyter_server_extension(nb_server_app):
"""
Called when the extension is loaded.
Args:
nb_server_app (NotebookWebApplication):
handle to the Notebook webserver instance.
"""
web_app = nb_server_app.web_app
web_app.settings['jinja2_env'].loader.searchpath += [
... | def load_jupyter_server_extension(nb_server_app):
| """
Called when the extension is loaded.
Args:
nb_server_app (NotebookWebApplication):
handle to the Notebook webserver instance.
"""
web_app = nb_server_app.web_app
web_app.settings['jinja2_env'].loader.searchpath += [
os.path.join(os.path.dirname(__file__), 'temp... |
"""A Jupyter notebook server extension logging to Azure/Microsoft"""
import os
from notebook.utils import url_path_join
from .auth_handler import AuthenticateHandler, CallbackHandler, GetTokens
def _jupyter_server_extension_paths():
return [{"module": "pymango"}]
def load_jupyter_server_extension(nb_server_app... | 69 | 75 | 253 | 10 | 59 | cccs-is/pymango | pymango_server/__init__.py | Python | load_jupyter_server_extension | load_jupyter_server_extension | 13 | 40 | 13 | 13 | 5f398059e833404b7d834b8102b8e0299eb1946c | bigcode/the-stack | train |
b5d28b852f1bb79e2ee9a37a | train | function | def _check_child_op_types(
op: Operation, child_op_types: List[str], check_order: bool = True
) -> bool:
"""
Returns True child op types match child_op_types, otherwise returns False.
:param op: Current op
:param child_op_type: Expected child op types
:param check_order: Ensure child in given o... | def _check_child_op_types(
op: Operation, child_op_types: List[str], check_order: bool = True
) -> bool:
| """
Returns True child op types match child_op_types, otherwise returns False.
:param op: Current op
:param child_op_type: Expected child op types
:param check_order: Ensure child in given order, defaults to True.
"""
if op is None or len(op.outputs) != 1:
return False
child_ops... | _op.keep_dims.val is False:
return False
if reduce_op.axes is None or reduce_op.axes.val is None:
return False
return True
def _check_child_op_types(
op: Operation, child_op_types: List[str], check_order: bool = True
) -> bool:
| 64 | 64 | 181 | 30 | 33 | tonybove-apple/coremltools | coremltools/converters/mil/mil/passes/layernorm_instancenorm_pattern_fusion.py | Python | _check_child_op_types | _check_child_op_types | 57 | 76 | 57 | 59 | 91cb025cccdd9e1d772da987a68bf196a9546418 | bigcode/the-stack | train |
620f0108149268efba1a065c | train | function | def _try_match_and_transform_pattern_3(reduce_op, block) -> bool:
"""
Detect InstanceNorm pattern in TensorFlow-Addons.
This pattern corresponds to, should be fused as instance_norm.
All of the following must be satisty:
1) Input is rank 4 tensor
2) Reduce operates on spatial dimensions axes=[-... | def _try_match_and_transform_pattern_3(reduce_op, block) -> bool:
| """
Detect InstanceNorm pattern in TensorFlow-Addons.
This pattern corresponds to, should be fused as instance_norm.
All of the following must be satisty:
1) Input is rank 4 tensor
2) Reduce operates on spatial dimensions axes=[-2, -1], or axes=[-3, -2] (a
channel first to channel last t... | ] and real_div_op.y == pow_op.outputs[0]):
return False
ops_to_remove.append(real_div_op)
# check mul with gamma
mul_gamma_op = _try_get_child_op_type(real_div_op, "mul")
if mul_gamma_op is None:
return False
gamma_var = (
mul_gamma_op.y if mul_gamma_op.x == real_div_op.outp... | 256 | 256 | 1,263 | 18 | 238 | tonybove-apple/coremltools | coremltools/converters/mil/mil/passes/layernorm_instancenorm_pattern_fusion.py | Python | _try_match_and_transform_pattern_3 | _try_match_and_transform_pattern_3 | 475 | 613 | 475 | 475 | 3d6496b06c5db38779cec728ee33ab966359ba94 | bigcode/the-stack | train |
6f25195acf3737c8e9f672e9 | train | function | def _try_match_and_transform_pattern_1(reduce_op, block) -> bool:
"""
Identify the pattern:
y = gamma * (x - mean) / sqrt(variance + epsilon) + beta
y = x * [gamma * rsqrt(variance + eps)] + (beta - mean * [gamma * rsqrt(variance + eps)])
x --> reduce_mean --> sub --> square --> reduce_mean --> a... | def _try_match_and_transform_pattern_1(reduce_op, block) -> bool:
| """
Identify the pattern:
y = gamma * (x - mean) / sqrt(variance + epsilon) + beta
y = x * [gamma * rsqrt(variance + eps)] + (beta - mean * [gamma * rsqrt(variance + eps)])
x --> reduce_mean --> sub --> square --> reduce_mean --> add(epsilon) --> rsqrt
| | ^ ... | beta=np.squeeze(beta_var.val),
epsilon=epsilon_var,
name=out_name + "_instancenorm" if is_require_rank4_transpose else out_name,
before_op=end_op,
)
else: # is_layernorm
x = mb.layer_norm(
x=x if is_require_rank4_transpose else reduce_op.x... | 256 | 256 | 1,408 | 18 | 237 | tonybove-apple/coremltools | coremltools/converters/mil/mil/passes/layernorm_instancenorm_pattern_fusion.py | Python | _try_match_and_transform_pattern_1 | _try_match_and_transform_pattern_1 | 197 | 345 | 197 | 197 | 6c536c14742f43a4fe132299c8c060e4573e6850 | bigcode/the-stack | train |
31d626b74b6bba22f055d615 | train | function | def _fuse_layernorm_or_instancenorm_block(block: Block):
fusion_status = False
for i, op in enumerate(list(block.operations)):
for b in op.blocks:
block_changed = True
while block_changed:
block_changed = _fuse_layernorm_or_instancenorm_block(b)
if len(op.... | def _fuse_layernorm_or_instancenorm_block(block: Block):
| fusion_status = False
for i, op in enumerate(list(block.operations)):
for b in op.blocks:
block_changed = True
while block_changed:
block_changed = _fuse_layernorm_or_instancenorm_block(b)
if len(op.blocks) > 0:
continue
# start patter... | _op1.outputs[0] and add_op.x == sub_beta_op.outputs[0])
):
return False
ops_to_remove.append(add_op)
return _try_apply_transform(
reduce_op, block, gamma_var, beta_var, epsilon_var, add_op, ops_to_remove
)
def _fuse_layernorm_or_instancenorm_block(block: Block):
| 78 | 78 | 260 | 15 | 63 | tonybove-apple/coremltools | coremltools/converters/mil/mil/passes/layernorm_instancenorm_pattern_fusion.py | Python | _fuse_layernorm_or_instancenorm_block | _fuse_layernorm_or_instancenorm_block | 792 | 821 | 792 | 792 | 51d1b6541ba07b1bf52d5c3ddeed4ef435cdea6d | bigcode/the-stack | train |
353930da1ca78264ff1a121b | train | function | def _try_match_and_transform_pattern_2(reduce_op, block) -> bool:
"""
Identify the pattern:
y = (x - mean) / pow(variance + epsilon) * gamma + beta
This pattern corresponds to, should be fused as instance_norm.
All of the following must be satisty:
1) Input is rank 4 tensor
2) Reduce operat... | def _try_match_and_transform_pattern_2(reduce_op, block) -> bool:
| """
Identify the pattern:
y = (x - mean) / pow(variance + epsilon) * gamma + beta
This pattern corresponds to, should be fused as instance_norm.
All of the following must be satisty:
1) Input is rank 4 tensor
2) Reduce operates on spatial dimensions axes=[-2, -1], or axes=[-3, -2] (a
... | else:
mul_root_op = mul_op3
mul_mean_op = mul_op2
ops_to_remove.append(mul_mean_op)
ops_to_remove.append(mul_root_op)
# check sub with beta
sub_op2 = _try_get_child_op_type(mul_mean_op, "sub")
if sub_op2 is None:
return False
if sub_op2.y != mul_mean_op.outputs[0]:
... | 256 | 256 | 1,170 | 18 | 238 | tonybove-apple/coremltools | coremltools/converters/mil/mil/passes/layernorm_instancenorm_pattern_fusion.py | Python | _try_match_and_transform_pattern_2 | _try_match_and_transform_pattern_2 | 348 | 472 | 348 | 348 | 2401f8df54efcf59ce3312f2023077f8eb9d0676 | bigcode/the-stack | train |
ed6c3b9fc5e8b4dd12ffa32e | train | function | def _check_reduce_op(reduce_op: Operation, mode: str = "reduce_mean") -> bool:
"""
Check whether or not the reduction op satisfy following conditions:
- Mode is expected.
- Does not change rank (keep_dims is True).
- Axes is known at compile time.
:param reduce_op: reduce op to check on
:pa... | def _check_reduce_op(reduce_op: Operation, mode: str = "reduce_mean") -> bool:
| """
Check whether or not the reduction op satisfy following conditions:
- Mode is expected.
- Does not change rank (keep_dims is True).
- Axes is known at compile time.
:param reduce_op: reduce op to check on
:param mode: reduce mode
"""
if reduce_op is None:
return False
... | param ops: List of operations to check on.
"""
for op in ops[:-1]:
for out in op.outputs:
if out in block.outputs:
return False
return True
def _check_reduce_op(reduce_op: Operation, mode: str = "reduce_mean") -> bool:
| 64 | 64 | 168 | 22 | 41 | tonybove-apple/coremltools | coremltools/converters/mil/mil/passes/layernorm_instancenorm_pattern_fusion.py | Python | _check_reduce_op | _check_reduce_op | 34 | 54 | 34 | 34 | b48b07685aa471140151c4fcb937db6c4d6648be | bigcode/the-stack | train |
8268bcfe0f6bf84a80e94ab4 | train | function | def _check_no_output_connection(block: Block, ops: List[Operation]) -> bool:
"""
Check that none of the op in this pattern is connected to the output
(except the last add op)
:param block: Block
:param ops: List of operations to check on.
"""
for op in ops[:-1]:
for out in op.output... | def _check_no_output_connection(block: Block, ops: List[Operation]) -> bool:
| """
Check that none of the op in this pattern is connected to the output
(except the last add op)
:param block: Block
:param ops: List of operations to check on.
"""
for op in ops[:-1]:
for out in op.outputs:
if out in block.outputs:
return False
retu... | import Operation, Block, Var, Program
from coremltools.converters.mil.mil.passes.pass_registry import register_pass
DEBUG = False # set to true to plot the block before and after the transformation
def _check_no_output_connection(block: Block, ops: List[Operation]) -> bool:
| 64 | 64 | 96 | 19 | 44 | tonybove-apple/coremltools | coremltools/converters/mil/mil/passes/layernorm_instancenorm_pattern_fusion.py | Python | _check_no_output_connection | _check_no_output_connection | 19 | 31 | 19 | 19 | d5aa06b63e67db9f910254395994655f742deade | bigcode/the-stack | train |
e4f50ae86d2de168e4f0c82c | train | function | @register_pass(namespace="common")
def fuse_layernorm_or_instancenorm(prog: Program):
"""
A graph optimization pass on PyMIL to detect and fuse several different
vairants of layer_norm or instance_norm. Pattern 1 is corresponding to
either layer_norm or instance_norm. Pattern 2-4 are instance_norm.
... | @register_pass(namespace="common")
def fuse_layernorm_or_instancenorm(prog: Program):
| """
A graph optimization pass on PyMIL to detect and fuse several different
vairants of layer_norm or instance_norm. Pattern 1 is corresponding to
either layer_norm or instance_norm. Pattern 2-4 are instance_norm.
:param prog: PyMIL Program to work on.
"""
for f in prog.functions.values():
... | _sum":
with block:
if fusion_status is False:
fusion_status = _try_match_and_transform_pattern_4(op, block)
# has to break as the downstream iterator is affected.
if fusion_status:
return fusion_status
return fusion_status
@regi... | 76 | 76 | 255 | 20 | 55 | tonybove-apple/coremltools | coremltools/converters/mil/mil/passes/layernorm_instancenorm_pattern_fusion.py | Python | fuse_layernorm_or_instancenorm | fuse_layernorm_or_instancenorm | 824 | 855 | 824 | 825 | bcdeafe90a14584f7e8968014efb3a6feb44cf00 | bigcode/the-stack | train |
1c72702db18ae935246fe678 | train | function | def _try_match_and_transform_pattern_4(reduce_op: Operation, block: Block) -> bool:
"""
Identify the pattern:
y = x * [gamma * rsqrt(variance + eps)] + (beta - mean * [gamma * rsqrt(variance + eps)])
This pattern corresponds to, should be fused as instance_norm.
All of the following must be satisty... | def _try_match_and_transform_pattern_4(reduce_op: Operation, block: Block) -> bool:
| """
Identify the pattern:
y = x * [gamma * rsqrt(variance + eps)] + (beta - mean * [gamma * rsqrt(variance + eps)])
This pattern corresponds to, should be fused as instance_norm.
All of the following must be satisty:
1) Input is rank 4 tensor
2) Reduce operates on spatial dimensions axes=[-... | return False
ops_to_remove.append(mul_sub_op)
# check last add op
add_op = _try_get_child_op_type(mul_sub_op, "add")
if add_op is None:
return False
if not (
(add_op.x == mul_op1.outputs[0] and add_op.y == mul_sub_op.outputs[0])
or (add_op.x == mul_sub_op.outputs[0] ... | 256 | 256 | 1,632 | 22 | 234 | tonybove-apple/coremltools | coremltools/converters/mil/mil/passes/layernorm_instancenorm_pattern_fusion.py | Python | _try_match_and_transform_pattern_4 | _try_match_and_transform_pattern_4 | 616 | 789 | 616 | 616 | 99f5606036da2e0185972db4735147d46eb82304 | bigcode/the-stack | train |
43ee671067eeced43fb1380d | train | function | def _try_apply_transform(
reduce_op: Operation,
block: Block,
gamma_var: Var,
beta_var: Var,
epsilon_var: Var,
end_op: Operation,
ops_to_remove: List[Operation],
) -> bool:
"""
Insert instance_norm / layer_norm and delete all ops.
:param reduce_op: Start operation of the pattern... | def _try_apply_transform(
reduce_op: Operation,
block: Block,
gamma_var: Var,
beta_var: Var,
epsilon_var: Var,
end_op: Operation,
ops_to_remove: List[Operation],
) -> bool:
| """
Insert instance_norm / layer_norm and delete all ops.
:param reduce_op: Start operation of the pattern.
:param block: Block
:param gamma_var: Gamma variable.
:param beta_var: Beta variable.
:param epsilon_var: Epsilon variable.
:param end_op: End operation of the pattern.
:param... | if check_order is False:
ops_types = sorted(ops_types)
child_op_types = sorted(child_op_types)
return ops_types == child_op_types
def _try_get_child_op_type(
op: Operation, child_op_type: str, index: int = 0
) -> Optional[Operation]:
"""
Returns child op if type matches, otherwise ret... | 237 | 237 | 792 | 54 | 183 | tonybove-apple/coremltools | coremltools/converters/mil/mil/passes/layernorm_instancenorm_pattern_fusion.py | Python | _try_apply_transform | _try_apply_transform | 101 | 194 | 101 | 109 | 94bdd512eb80781b7f77c9834d99957aedc4cd85 | bigcode/the-stack | train |
9c6360a2f5ce6d27d6f6584f | train | function | def _try_get_child_op_type(
op: Operation, child_op_type: str, index: int = 0
) -> Optional[Operation]:
"""
Returns child op if type matches, otherwise returns None.
:param op: Current op
:param child_op_type: Expected child op type
:param index: Child op index
"""
if op is None:
... | def _try_get_child_op_type(
op: Operation, child_op_type: str, index: int = 0
) -> Optional[Operation]:
| """
Returns child op if type matches, otherwise returns None.
:param op: Current op
:param child_op_type: Expected child op type
:param index: Child op index
"""
if op is None:
return None
if len(op.outputs) != 1:
return None
child_ops = list(op.outputs[0].child_ops)... | _order is False:
ops_types = sorted(ops_types)
child_op_types = sorted(child_op_types)
return ops_types == child_op_types
def _try_get_child_op_type(
op: Operation, child_op_type: str, index: int = 0
) -> Optional[Operation]:
| 64 | 64 | 149 | 32 | 31 | tonybove-apple/coremltools | coremltools/converters/mil/mil/passes/layernorm_instancenorm_pattern_fusion.py | Python | _try_get_child_op_type | _try_get_child_op_type | 79 | 98 | 79 | 81 | 6b24a841fdf5171cb4a8285551c0cc5dbf102f03 | bigcode/the-stack | train |
95290e1486093b481c381d0c | train | function | def list_opts():
yield mdns_group, OPTS
| def list_opts():
| yield mdns_group, OPTS
| ns_topic', default='mdns',
help='RPC topic name for mini-DNS')
]
cfg.CONF.register_group(mdns_group)
cfg.CONF.register_opts(OPTS, group=mdns_group)
cfg.CONF.register_opts(dnsutils.util_opts, group=mdns_group)
def list_opts():
| 64 | 64 | 13 | 4 | 60 | scottwedge/OpenStack-Stein | designate-8.0.0/designate/mdns/__init__.py | Python | list_opts | list_opts | 66 | 67 | 66 | 66 | b5e8bf96ff4d17562ceedb53d7829a2b8a5ecd41 | bigcode/the-stack | train |
60aec360ea581128587dd309 | train | class | class MyEnum(StrEnum):
choice_a = auto()
choice_b = auto()
| class MyEnum(StrEnum):
| choice_a = auto()
choice_b = auto()
| from enum import auto
from fastapi_restful.enums import StrEnum
class MyEnum(StrEnum):
| 21 | 64 | 18 | 6 | 14 | DawnOfHell/FastApi-RESTful | docs/src/enums1.py | Python | MyEnum | MyEnum | 6 | 8 | 6 | 6 | 043639b15c80a6f1ba384a0d9298b37d6d8c1519 | bigcode/the-stack | train |
1d15a592f45410dc9dc5250e | train | class | class Embedder(nn.Module):
def __init__(self, vocab_size, d_model):
super().__init__()
self.d_model = d_model
self.embed = Embedder2(vocab_size, d_model)
def forward(self, x):
return self.embed(x)
| class Embedder(nn.Module):
| def __init__(self, vocab_size, d_model):
super().__init__()
self.d_model = d_model
self.embed = Embedder2(vocab_size, d_model)
def forward(self, x):
return self.embed(x)
| import torch
import torch.nn as nn
import math
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
class Embedder(nn.Module):
| 37 | 64 | 59 | 6 | 30 | chenjun-110/WZCQ | Embed.py | Python | Embedder | Embedder | 9 | 16 | 9 | 9 | 48af1de978aa6e7d91923fe0b41fdd14aa21325a | bigcode/the-stack | train |
48c9d09e1cba3b1ffa9c1b18 | train | class | class PositionalEncoder(nn.Module):
def __init__(self, d_model, max_seq_len=1024, dropout=0.1):
super().__init__()
self.d_model = d_model
self.dropout = nn.Dropout(dropout)
# create constant 'pe' matrix with values dependant on
# pos and i
pe = torch.zeros(max_seq_len... | class PositionalEncoder(nn.Module):
| def __init__(self, d_model, max_seq_len=1024, dropout=0.1):
super().__init__()
self.d_model = d_model
self.dropout = nn.Dropout(dropout)
# create constant 'pe' matrix with values dependant on
# pos and i
pe = torch.zeros(max_seq_len, d_model)
for pos in range(... | Variable
import torch.nn.functional as F
import numpy as np
class Embedder(nn.Module):
def __init__(self, vocab_size, d_model):
super().__init__()
self.d_model = d_model
self.embed = Embedder2(vocab_size, d_model)
def forward(self, x):
return self.embed(x)
class PositionalEnc... | 80 | 80 | 267 | 7 | 73 | chenjun-110/WZCQ | Embed.py | Python | PositionalEncoder | PositionalEncoder | 19 | 46 | 19 | 19 | 38a9610ebe28d2ad660ead7d55b55bc57e06767c | bigcode/the-stack | train |
635529be64efabb8fef638fa | train | class | class Embedder2(nn.Module):
def __init__(self, num_embeddings, embedding_dim, padding_idx=None,
max_norm=None, norm_type=2., scale_grad_by_freq=False,
sparse=False, _weight=None):
super(Embedder2, self).__init__()
self.num_embeddings = num_embeddings
self.em... | class Embedder2(nn.Module):
| def __init__(self, num_embeddings, embedding_dim, padding_idx=None,
max_norm=None, norm_type=2., scale_grad_by_freq=False,
sparse=False, _weight=None):
super(Embedder2, self).__init__()
self.num_embeddings = num_embeddings
self.embedding_dim = embedding_dim
... | 1)) / d_model)))
pe = pe.unsqueeze(0)
self.register_buffer('pe', pe)
def forward(self, x):
# make embeddings relatively larger
x = x * math.sqrt(self.d_model)
# add constant to embedding
seq_len = x.size(1)
pe = Variable(self.pe[:, :seq_len], requires_grad=F... | 115 | 115 | 385 | 7 | 107 | chenjun-110/WZCQ | Embed.py | Python | Embedder2 | Embedder2 | 49 | 88 | 49 | 49 | 508558dea3fcb780681f36e6f45f948c72bead59 | bigcode/the-stack | train |
664860f6f43fc39ced6dc633 | train | class | class TestMongoFilter(unittest.TestCase):
def test_parseblock(self):
config_dict = toml.loads(EXAMPLE_TOML)
mfp_config = config_dict.get('filters', {}).get('twitter_filter', {})
self.assertTrue(len(mfp_config) > 0)
mfp = MongoFilterProcessor.parse(mfp_config)
self.assertTrue(... | class TestMongoFilter(unittest.TestCase):
| def test_parseblock(self):
config_dict = toml.loads(EXAMPLE_TOML)
mfp_config = config_dict.get('filters', {}).get('twitter_filter', {})
self.assertTrue(len(mfp_config) > 0)
mfp = MongoFilterProcessor.parse(mfp_config)
self.assertTrue(mfp.name == 'twitter_filter')
self... | datetime.now(), 'msg':3, 'filtered': False},
{'testid':'d', 'content': '4', 'msg':4, 'filtered': False},
{'testid':'b', 'content': '1', 'msg':1+5, 'filtered': False},
{'testid':'c', 'content': '2', 'msg':2+5, 'filtered': False},
{'testid':'d', 'content': '3', 'msg':3+5, 'filtered': True},
{'testid'... | 204 | 204 | 681 | 8 | 196 | deeso/fiery-snap | tests/mongo_tests/mongofilter_test.py | Python | TestMongoFilter | TestMongoFilter | 104 | 174 | 104 | 104 | c6f408e181186fc698795dc4eb9e803ec92d9023 | bigcode/the-stack | train |
5ea67002590e0e0892151bf2 | train | function | def save_data_to_file(data, filename):
with open(filename, 'w') as out:
for userId in data:
for record in data[userId]:
out.write("{}\t{}\t{}\n".format(userId, record[0], record[1]))
| def save_data_to_file(data, filename):
| with open(filename, 'w') as out:
for userId in data:
for record in data[userId]:
out.write("{}\t{}\t{}\n".format(userId, record[0], record[1]))
| total_ratings = 0
print("STATS")
for user in data:
total_ratings += len(data[user])
print("Total Ratings: {}".format(total_ratings))
print("Total User count: {}".format(len(data.keys())))
def save_data_to_file(data, filename):
| 63 | 64 | 58 | 9 | 54 | whn09/DeepRecommender | data_utils/netflix_data_convert.py | Python | save_data_to_file | save_data_to_file | 16 | 20 | 16 | 16 | a09143c85ee69f7e4a0707548b8ea09a4c600168 | bigcode/the-stack | train |
58793e5aa733012a628b9c71 | train | function | def create_NETFLIX_data_timesplit(all_data,
train_min,
train_max,
test_min,
test_max):
"""
Creates time-based split of NETFLIX data into train, and (validation, test)
:param all_... | def create_NETFLIX_data_timesplit(all_data,
train_min,
train_max,
test_min,
test_max):
| """
Creates time-based split of NETFLIX data into train, and (validation, test)
:param all_data:
:param train_min:
:param train_max:
:param test_min:
:param test_max:
:return:
"""
train_min_ts = time.mktime(datetime.datetime.strptime(train_min,"%Y-%m-%d").timetuple())
train_max_ts = time.mktime(da... | edirs
import random
import sys
import time
import datetime
def print_stats(data):
total_ratings = 0
print("STATS")
for user in data:
total_ratings += len(data[user])
print("Total Ratings: {}".format(total_ratings))
print("Total User count: {}".format(len(data.keys())))
def save_data_to_file(data, filena... | 160 | 160 | 535 | 27 | 133 | whn09/DeepRecommender | data_utils/netflix_data_convert.py | Python | create_NETFLIX_data_timesplit | create_NETFLIX_data_timesplit | 22 | 74 | 22 | 26 | bb10ee977b4ec9e08ec2ee05e71bbe6a16b8b474 | bigcode/the-stack | train |
a0a62db1f067af062a4a2345 | train | function | def print_stats(data):
total_ratings = 0
print("STATS")
for user in data:
total_ratings += len(data[user])
print("Total Ratings: {}".format(total_ratings))
print("Total User count: {}".format(len(data.keys())))
| def print_stats(data):
| total_ratings = 0
print("STATS")
for user in data:
total_ratings += len(data[user])
print("Total Ratings: {}".format(total_ratings))
print("Total User count: {}".format(len(data.keys())))
| # Copyright (c) 2017 NVIDIA Corporation
from os import listdir, path, makedirs
import random
import sys
import time
import datetime
def print_stats(data):
| 40 | 64 | 59 | 5 | 34 | whn09/DeepRecommender | data_utils/netflix_data_convert.py | Python | print_stats | print_stats | 8 | 14 | 8 | 8 | 58cadb264ff34e1bf1728c88d914ef57f559bbaa | bigcode/the-stack | train |
aef8997f6727106b252b31fb | train | function | def main(args):
user2id_map = dict()
item2id_map = dict()
userId = 0
itemId = 0
all_data = dict()
folder = args[1]
out_folder = args[2]
# create necessary folders:
for output_dir in [(out_folder + f) for f in [
"/N3M_TRAIN", "/N3M_VALID", "/N3M_TEST", "/N6M_TRAIN",
"/N6M_VALID", "/N6M_TEST", ... | def main(args):
| user2id_map = dict()
item2id_map = dict()
userId = 0
itemId = 0
all_data = dict()
folder = args[1]
out_folder = args[2]
# create necessary folders:
for output_dir in [(out_folder + f) for f in [
"/N3M_TRAIN", "/N3M_VALID", "/N3M_TEST", "/N6M_TRAIN",
"/N6M_VALID", "/N6M_TEST", "/N1Y_TRAIN", "/... | _data:
training_data[userId] = []
training_data[userId].append(rating_item)
train_set_items.add(rating_item[0]) # keep track of items from training set
elif rating_item[2] >= test_min_ts and rating_item[2] <= test_max_ts:
if not userId in training_data: # only include users seen ... | 256 | 256 | 1,169 | 4 | 251 | whn09/DeepRecommender | data_utils/netflix_data_convert.py | Python | main | main | 77 | 185 | 77 | 77 | c7904e6f48b8d0d5072e486ef191aaebc2c5b817 | bigcode/the-stack | train |
8e6b7ab7182673bf9ea43bb3 | train | function | def feed_database(db_cursor):
db_cursor.execute("select sha256,label,av_organisation from label;");
query = db_cursor.fetchall();
for row in query:
#print("Row: ", row);
#print("Row says: ", row[1], ". Type: ", type(row[1]));
if row[2] == "Kaspersky":
if row[1].find("tro... | def feed_database(db_cursor):
| db_cursor.execute("select sha256,label,av_organisation from label;");
query = db_cursor.fetchall();
for row in query:
#print("Row: ", row);
#print("Row says: ", row[1], ". Type: ", type(row[1]));
if row[2] == "Kaspersky":
if row[1].find("trojan") != -1 or row[1].find("Tr... | Feed database with web pages
feed_database(db_cursor);
# Close DB
try:
db_connection.commit();
db_connection.close();
print("Database connection closed.");
except sqlite3.Error as e:
print(" Sqlite error: ", e.args[0]);
def feed_database(db_cursor):
| 64 | 64 | 196 | 6 | 58 | jesperatstockholmuniversity/tor_malware_classification | retomos/wash_labels.py | Python | feed_database | feed_database | 27 | 38 | 27 | 27 | 79e653fa0af5ac0e2d434f6e5ef81b7158c653ba | bigcode/the-stack | train |
573208a68819f303286bea01 | train | function | def main ():
# Open DB
db_connection = sqlite3.connect('cuckoo_reports.db');
db_cursor = db_connection.cursor();
# Feed database with web pages
feed_database(db_cursor);
# Close DB
try:
db_connection.commit();
db_connection.close();
print("Database connection closed... | def main ():
# Open DB
| db_connection = sqlite3.connect('cuckoo_reports.db');
db_cursor = db_connection.cursor();
# Feed database with web pages
feed_database(db_cursor);
# Close DB
try:
db_connection.commit();
db_connection.close();
print("Database connection closed.");
except sqlite3.Err... | #################################################################
# Title: Feed SQLite DB with .json reports from Cuckoo reports
# Author: Jesper Bergman (jesperbe@dsv.su.se)
# Licence: GPLv2
#################################################################
import sqlite3;
import sys;
import os;
def main ():
# Ope... | 64 | 64 | 91 | 9 | 55 | jesperatstockholmuniversity/tor_malware_classification | retomos/wash_labels.py | Python | main | main | 11 | 25 | 11 | 12 | 4800456bdcaac9c11bee87acbfc0e88b1fe23f6e | bigcode/the-stack | train |
ecb015d898d7c2c3f0c6bd3e | train | class | class KNN(NN):
def __init__(self, X=None, Y=None, k=3, p=2):
self.k = k
super().__init__(X, Y, p)
def train(self, X, Y):
super().train(X, Y)
if type(Y) != type(None):
self.unique_labels = self.train_label.unique()
def predict(self, x):
dist = distance_m... | class KNN(NN):
| def __init__(self, X=None, Y=None, k=3, p=2):
self.k = k
super().__init__(X, Y, p)
def train(self, X, Y):
super().train(X, Y)
if type(Y) != type(None):
self.unique_labels = self.train_label.unique()
def predict(self, x):
dist = distance_matrix(x, self.tr... | (f"{name} wasn't trained. Need to execute {name}.train() first")
dist = distance_matrix(x, self.train_pts, self.p) ** (1 / self.p)
labels = torch.argmin(dist, dim=1)
return self.train_label[labels]
class KNN(NN):
| 64 | 64 | 126 | 6 | 58 | DanialGhiaseddin/PatchCore_anomaly_detection | train.py | Python | KNN | KNN | 63 | 79 | 63 | 64 | c614aaae2b04021ef0b6a23c7e8e92b2a370ef64 | bigcode/the-stack | train |
c2a13eeaf6d140e364f4fa75 | train | class | class STPM(pl.LightningModule):
def __init__(self, hparams):
super(STPM, self).__init__()
self.save_hyperparameters(hparams)
self.init_features()
def hook_t(module, input, output):
self.features.append(output)
torch.hub._validate_not_a_forked_repo = lambda a, ... | class STPM(pl.LightningModule):
| def __init__(self, hparams):
super(STPM, self).__init__()
self.save_hyperparameters(hparams)
self.init_features()
def hook_t(module, input, output):
self.features.append(output)
torch.hub._validate_not_a_forked_repo = lambda a, b, c: True
self.model = ... | :
heatmap = cv2.resize(heatmap, (image.shape[0], image.shape[1]))
out = np.float32(heatmap) / 255 + np.float32(image) / 255
out = out / np.max(out)
return np.uint8(255 * out)
def min_max_norm(image):
a_min, a_max = image.min(), image.max()
return (image - a_min) / (a_max - a_min)
def cal... | 256 | 256 | 2,001 | 8 | 248 | DanialGhiaseddin/PatchCore_anomaly_detection | train.py | Python | STPM | STPM | 290 | 476 | 290 | 290 | 3dde2e56d7ae3942ff635c35b417844ffffb8c02 | bigcode/the-stack | train |
2161137585c2dfd6289e045f | train | function | def get_args():
parser = argparse.ArgumentParser(description='ANOMALYDETECTION')
parser.add_argument('--phase', choices=['train', 'test'], default='train')
parser.add_argument('--dataset',
default='Retina')
parser.add_argument('--dataset_path',
default=r'/... | def get_args():
| parser = argparse.ArgumentParser(description='ANOMALYDETECTION')
parser.add_argument('--phase', choices=['train', 'test'], default='train')
parser.add_argument('--dataset',
default='Retina')
parser.add_argument('--dataset_path',
default=r'/content/datasets... | img_path_list = self.img_path_list, thresh = 0.00097)
# # print()
# with open(args.project_root_path + r'/results.txt', 'a') as f:
# f.write(args.category + ' : ' + str(values) + '\n')
def get_args():
| 65 | 65 | 219 | 4 | 61 | DanialGhiaseddin/PatchCore_anomaly_detection | train.py | Python | get_args | get_args | 494 | 513 | 494 | 494 | 229c26e7444ea54412630a5b1ca428c5ce6590e7 | bigcode/the-stack | train |
3345397d6e654ef278192354 | train | class | class MVTecDataset(Dataset):
def __init__(self, root, transform, gt_transform, phase):
if phase == 'train':
self.img_path = os.path.join(root, 'train')
else:
self.img_path = os.path.join(root, 'test')
self.gt_path = os.path.join(root, 'ground_truth')
self.... | class MVTecDataset(Dataset):
| def __init__(self, root, transform, gt_transform, phase):
if phase == 'train':
self.img_path = os.path.join(root, 'train')
else:
self.img_path = os.path.join(root, 'test')
self.gt_path = os.path.join(root, 'ground_truth')
self.transform = transform
... | test and ground truth pair!"
return img_tot_paths, gt_tot_paths, tot_labels, tot_types
def __len__(self):
return len(self.img_paths)
def __getitem__(self, idx):
img_path, gt, label, img_type = self.img_paths[idx], self.gt_paths[idx], self.labels[idx], self.types[idx]
img = Im... | 161 | 161 | 539 | 8 | 152 | DanialGhiaseddin/PatchCore_anomaly_detection | train.py | Python | MVTecDataset | MVTecDataset | 190 | 247 | 190 | 190 | c18ec93a39c1a3627eabdcb594e1bf595eb3b440 | bigcode/the-stack | train |
ff9ca89528ed3dec76c2d111 | train | function | def min_max_norm(image):
a_min, a_max = image.min(), image.max()
return (image - a_min) / (a_max - a_min)
| def min_max_norm(image):
| a_min, a_max = image.min(), image.max()
return (image - a_min) / (a_max - a_min)
| .resize(heatmap, (image.shape[0], image.shape[1]))
out = np.float32(heatmap) / 255 + np.float32(image) / 255
out = out / np.max(out)
return np.uint8(255 * out)
def min_max_norm(image):
| 64 | 64 | 35 | 6 | 58 | DanialGhiaseddin/PatchCore_anomaly_detection | train.py | Python | min_max_norm | min_max_norm | 263 | 265 | 263 | 263 | 1e0c23573f2099215d3e220b7b9fc75f6ac4f7a9 | bigcode/the-stack | train |
2224047383380a1a39c50c45 | train | function | def heatmap_on_image(heatmap, image):
if heatmap.shape != image.shape:
heatmap = cv2.resize(heatmap, (image.shape[0], image.shape[1]))
out = np.float32(heatmap) / 255 + np.float32(image) / 255
out = out / np.max(out)
return np.uint8(255 * out)
| def heatmap_on_image(heatmap, image):
| if heatmap.shape != image.shape:
heatmap = cv2.resize(heatmap, (image.shape[0], image.shape[1]))
out = np.float32(heatmap) / 255 + np.float32(image) / 255
out = out / np.max(out)
return np.uint8(255 * out)
| return img, gt, label, os.path.basename(img_path[:-4]), img_type
def cvt2heatmap(gray):
heatmap = cv2.applyColorMap(np.uint8(gray), cv2.COLORMAP_JET)
return heatmap
def heatmap_on_image(heatmap, image):
| 64 | 64 | 84 | 11 | 52 | DanialGhiaseddin/PatchCore_anomaly_detection | train.py | Python | heatmap_on_image | heatmap_on_image | 255 | 260 | 255 | 255 | 105f7ee24083ff0a83ed41cf3edf8fd52bf14f1d | bigcode/the-stack | train |
092a66e9f0b874e2252a238c | train | function | def embedding_concat(x, y):
# from https://github.com/xiahaifeng1995/PaDiM-Anomaly-Detection-Localization-master
B, C1, H1, W1 = x.size()
_, C2, H2, W2 = y.size()
s = int(H1 / H2)
x = F.unfold(x, kernel_size=s, dilation=1, stride=s)
x = x.view(B, C1, -1, H2, W2)
z = torch.zeros(B, C1 + C2, x... | def embedding_concat(x, y):
# from https://github.com/xiahaifeng1995/PaDiM-Anomaly-Detection-Localization-master
| B, C1, H1, W1 = x.size()
_, C2, H2, W2 = y.size()
s = int(H1 / H2)
x = F.unfold(x, kernel_size=s, dilation=1, stride=s)
x = x.view(B, C1, -1, H2, W2)
z = torch.zeros(B, C1 + C2, x.size(2), H2, W2)
for i in range(x.size(2)):
z[:, :, i, :, :] = torch.cat((x[:, :, i, :, :], y), 1)
z... | 'logs', 'README', 'samples', 'LICENSE']) # copy source code
return embeddings_path, sample_path, source_code_save_path
def embedding_concat(x, y):
# from https://github.com/xiahaifeng1995/PaDiM-Anomaly-Detection-Localization-master
| 64 | 64 | 212 | 33 | 30 | DanialGhiaseddin/PatchCore_anomaly_detection | train.py | Python | embedding_concat | embedding_concat | 112 | 125 | 112 | 113 | 4e22b4a1b59c14272cacce05b8968b2293a2b789 | bigcode/the-stack | train |
671700b5d135b90e9826aa9f | train | function | def cvt2heatmap(gray):
heatmap = cv2.applyColorMap(np.uint8(gray), cv2.COLORMAP_JET)
return heatmap
| def cvt2heatmap(gray):
| heatmap = cv2.applyColorMap(np.uint8(gray), cv2.COLORMAP_JET)
return heatmap
| :
gt = Image.open(gt)
gt = self.gt_transform(gt)
assert img.size()[1:] == gt.size()[1:], "image.size != gt.size !!!"
return img, gt, label, os.path.basename(img_path[:-4]), img_type
def cvt2heatmap(gray):
| 64 | 64 | 35 | 8 | 55 | DanialGhiaseddin/PatchCore_anomaly_detection | train.py | Python | cvt2heatmap | cvt2heatmap | 250 | 252 | 250 | 250 | e37600c447d5d3341298a36a59c2d04405e35f0d | bigcode/the-stack | train |
c530657ea81fb0598d43064f | train | function | def distance_matrix(x, y=None, p=2): # pairwise distance of vectors
y = x if type(y) == type(None) else y
n = x.size(0)
m = y.size(0)
d = x.size(1)
x = x.unsqueeze(1).expand(n, m, d)
y = y.unsqueeze(0).expand(n, m, d)
dist = torch.pow(x - y, p).sum(2)
return dist
| def distance_matrix(x, y=None, p=2): # pairwise distance of vectors
| y = x if type(y) == type(None) else y
n = x.size(0)
m = y.size(0)
d = x.size(1)
x = x.unsqueeze(1).expand(n, m, d)
y = y.unsqueeze(0).expand(n, m, d)
dist = torch.pow(x - y, p).sum(2)
return dist
|
import pickle
from sampling_methods.kcenter_greedy import kCenterGreedy
from sklearn.random_projection import SparseRandomProjection
from sklearn.neighbors import NearestNeighbors
from scipy.ndimage import gaussian_filter
def distance_matrix(x, y=None, p=2): # pairwise distance of vectors
| 64 | 64 | 108 | 20 | 43 | DanialGhiaseddin/PatchCore_anomaly_detection | train.py | Python | distance_matrix | distance_matrix | 24 | 37 | 24 | 25 | 41bc52dc81400d123254a3dbfd0b9d07f75ede19 | bigcode/the-stack | train |
ee5499864246be7c64b08058 | train | function | def cal_confusion_matrix(y_true, y_pred_no_thresh, thresh, img_path_list):
pred_thresh = []
false_n = []
false_p = []
for i in range(len(y_pred_no_thresh)):
if y_pred_no_thresh[i] > thresh:
pred_thresh.append(1)
if y_true[i] == 0:
false_p.append(img_path_l... | def cal_confusion_matrix(y_true, y_pred_no_thresh, thresh, img_path_list):
| pred_thresh = []
false_n = []
false_p = []
for i in range(len(y_pred_no_thresh)):
if y_pred_no_thresh[i] > thresh:
pred_thresh.append(1)
if y_true[i] == 0:
false_p.append(img_path_list[i])
else:
pred_thresh.append(0)
if y_tr... | return np.uint8(255 * out)
def min_max_norm(image):
a_min, a_max = image.min(), image.max()
return (image - a_min) / (a_max - a_min)
def cal_confusion_matrix(y_true, y_pred_no_thresh, thresh, img_path_list):
| 64 | 64 | 148 | 19 | 45 | DanialGhiaseddin/PatchCore_anomaly_detection | train.py | Python | cal_confusion_matrix | cal_confusion_matrix | 268 | 287 | 268 | 268 | 369e4f24dd04e31e24a2c3072751afc65e33495a | bigcode/the-stack | train |
c523c25045e92acb5067f00d | train | class | class NN():
def __init__(self, X=None, Y=None, p=2):
self.p = p
self.train(X, Y)
def train(self, X, Y):
self.train_pts = X
self.train_label = Y
def __call__(self, x):
return self.predict(x)
def predict(self, x):
if type(self.train_pts) == type(None) or... | class NN():
| def __init__(self, X=None, Y=None, p=2):
self.p = p
self.train(X, Y)
def train(self, X, Y):
self.train_pts = X
self.train_label = Y
def __call__(self, x):
return self.predict(x)
def predict(self, x):
if type(self.train_pts) == type(None) or type(self.tr... | .size(0)
d = x.size(1)
x = x.unsqueeze(1).expand(n, m, d)
y = y.unsqueeze(0).expand(n, m, d)
dist = torch.pow(x - y, p).sum(2)
return dist
class NN():
| 64 | 64 | 170 | 3 | 60 | DanialGhiaseddin/PatchCore_anomaly_detection | train.py | Python | NN | NN | 40 | 60 | 40 | 41 | 30c5b8876fb94beed54ca29fa75fa9e016cbc4fe | bigcode/the-stack | train |
14aea729aabf192a53f56841 | train | function | def prep_dirs(root):
# make embeddings dir
# embeddings_path = os.path.join(root, 'embeddings')
embeddings_path = os.path.join('./', 'embeddings', args.category)
os.makedirs(embeddings_path, exist_ok=True)
# make sample dir
sample_path = os.path.join(root, 'sample')
os.makedirs(sample_path, ... | def prep_dirs(root):
# make embeddings dir
# embeddings_path = os.path.join(root, 'embeddings')
| embeddings_path = os.path.join('./', 'embeddings', args.category)
os.makedirs(embeddings_path, exist_ok=True)
# make sample dir
sample_path = os.path.join(root, 'sample')
os.makedirs(sample_path, exist_ok=True)
# make source code record dir & copy
source_code_save_path = os.path.join(root, '... | os.path.isdir(full_file_name):
os.makedirs(os.path.join(dst, file_name), exist_ok=True)
copy_files(full_file_name, os.path.join(dst, file_name), ignores)
def prep_dirs(root):
# make embeddings dir
# embeddings_path = os.path.join(root, 'embeddings')
| 64 | 64 | 172 | 25 | 39 | DanialGhiaseddin/PatchCore_anomaly_detection | train.py | Python | prep_dirs | prep_dirs | 96 | 109 | 96 | 98 | 1ae9a0a379febbfda9ed6222e70e929e35d5e08d | bigcode/the-stack | train |
d98107596f9c07aa0d60fe49 | train | class | class Retina(Dataset):
def __init__(self, root, transform, phase):
if phase == 'train':
self.img_path = os.path.join(root, 'train')
else:
self.img_path = os.path.join(root, 'test')
self.transform = transform
# load dataset
self.img_paths, self.gt_paths... | class Retina(Dataset):
| def __init__(self, root, transform, phase):
if phase == 'train':
self.img_path = os.path.join(root, 'train')
else:
self.img_path = os.path.join(root, 'test')
self.transform = transform
# load dataset
self.img_paths, self.gt_paths, self.labels, self.typ... | _size=(H1, W1), stride=s)
return z
def reshape_embedding(embedding):
embedding_list = []
for k in range(embedding.shape[0]):
for i in range(embedding.shape[2]):
for j in range(embedding.shape[3]):
embedding_list.append(embedding[k, :, i, j])
return embedding_list
... | 122 | 122 | 409 | 5 | 117 | DanialGhiaseddin/PatchCore_anomaly_detection | train.py | Python | Retina | Retina | 142 | 187 | 142 | 142 | 41da638fd5dce27a4c8336a6fb3dfb8c88656b8c | bigcode/the-stack | train |
b73cec4beb6d54620af81538 | train | function | def copy_files(src, dst, ignores=[]):
src_files = os.listdir(src)
for file_name in src_files:
ignore_check = [True for i in ignores if i in file_name]
if ignore_check:
continue
full_file_name = os.path.join(src, file_name)
if os.path.isfile(full_file_name):
... | def copy_files(src, dst, ignores=[]):
| src_files = os.listdir(src)
for file_name in src_files:
ignore_check = [True for i in ignores if i in file_name]
if ignore_check:
continue
full_file_name = os.path.join(src, file_name)
if os.path.isfile(full_file_name):
shutil.copy(full_file_name, os.path.... | .unique_labels = self.train_label.unique()
def predict(self, x):
dist = distance_matrix(x, self.train_pts, self.p) ** (1 / self.p)
knn = dist.topk(self.k, largest=False)
return knn
def copy_files(src, dst, ignores=[]):
| 64 | 64 | 128 | 10 | 53 | DanialGhiaseddin/PatchCore_anomaly_detection | train.py | Python | copy_files | copy_files | 82 | 93 | 82 | 82 | 0a20327217465d1086d06658294f9b7d9288a52e | bigcode/the-stack | train |
350d4dfccd01c5e1d0759fa8 | train | function | def reshape_embedding(embedding):
embedding_list = []
for k in range(embedding.shape[0]):
for i in range(embedding.shape[2]):
for j in range(embedding.shape[3]):
embedding_list.append(embedding[k, :, i, j])
return embedding_list
| def reshape_embedding(embedding):
| embedding_list = []
for k in range(embedding.shape[0]):
for i in range(embedding.shape[2]):
for j in range(embedding.shape[3]):
embedding_list.append(embedding[k, :, i, j])
return embedding_list
| .cat((x[:, :, i, :, :], y), 1)
z = z.view(B, -1, H2 * W2)
z = F.fold(z, kernel_size=s, output_size=(H1, W1), stride=s)
return z
def reshape_embedding(embedding):
| 64 | 64 | 62 | 6 | 57 | DanialGhiaseddin/PatchCore_anomaly_detection | train.py | Python | reshape_embedding | reshape_embedding | 128 | 134 | 128 | 128 | e3bbdfe8fab5f29f60be8c7b08af0f174b3ccb76 | bigcode/the-stack | train |
7b7b11839808caabbc0396d3 | train | function | def construct_blastp_cmd(qfile, dbname, outdir, blastp_exe):
"""Returns a single BLASTP command, using the input qfile against the
database dbname, writing results to outdir, using the executable in
blastp_exe.
Output filename is formatted 'qstem_vs_dbstem.out'
The BLASTP command writes a tabular ... | def construct_blastp_cmd(qfile, dbname, outdir, blastp_exe):
| """Returns a single BLASTP command, using the input qfile against the
database dbname, writing results to outdir, using the executable in
blastp_exe.
Output filename is formatted 'qstem_vs_dbstem.out'
The BLASTP command writes a tabular format output file. The formatting
string returns the fol... | _cmd(infile2, dbname1, outdir, blastp_exe)
job1 = jobs.Job("%s_query_%06d_fwd" % (jobprefix, jobnum), cmd1)
job2 = jobs.Job("%s_query_%06d_rev" % (jobprefix, jobnum), cmd2)
job1.add_dependency(dbjobs[fstem2]) # add dependency on db job
job2.add_dependency(dbjobs[fstem1])
... | 143 | 143 | 477 | 20 | 122 | widdowquinn/pyrbbh | pyrbbh/blast.py | Python | construct_blastp_cmd | construct_blastp_cmd | 147 | 183 | 147 | 147 | 7a132565b55338b38c43a5e44ab169d7d0daa679 | bigcode/the-stack | train |
5bb3325f0a61526bbc03898e | train | function | def make_blast_jobs(infiles, outdir,
blastp_exe=BLASTP_DEFAULT, blastdb_exe=BLASTDB_DEFAULT,
jobprefix="PYRBBH_%s" % str(int(time.time()))):
"""Returns a list of Job objects that represent BLAST commands required
to conduct RBBH on the list of passed sequence files.
... | def make_blast_jobs(infiles, outdir,
blastp_exe=BLASTP_DEFAULT, blastdb_exe=BLASTDB_DEFAULT,
jobprefix="PYRBBH_%s" % str(int(time.time()))):
| """Returns a list of Job objects that represent BLAST commands required
to conduct RBBH on the list of passed sequence files.
The returned list is essentially a job dependency graph. Individual jobs
record their upstream dependencies on other jobs. In all cases, this
should take the form of each q... | produce BLAST command-line jobs for RBH analysis.
"""
import os
import time
from .config import BLASTP_DEFAULT, BLASTDB_DEFAULT
from . import jobs
# Make a dependency graph of BLAST database and query jobs
def make_blast_jobs(infiles, outdir,
blastp_exe=BLASTP_DEFAULT, blastdb_exe=BLASTDB_DEFAU... | 100 | 100 | 334 | 50 | 49 | widdowquinn/pyrbbh | pyrbbh/blast.py | Python | make_blast_jobs | make_blast_jobs | 21 | 46 | 21 | 23 | 7b1a9adbfc9020e967adc915f6faac57d332e5cb | bigcode/the-stack | train |
082934749490f2ce7fd4251a | train | function | def make_blastdb_jobs(infiles, outdir, blastdb_exe, jobprefix):
"""Returns a dictionary of BLAST database construction command-lines,
keyed by the input filestem.
- infiles - a list of paths to input FASTA files
- outdir - path to directory for BLAST databases/output
- blastdb_exe - path to BLAST d... | def make_blastdb_jobs(infiles, outdir, blastdb_exe, jobprefix):
| """Returns a dictionary of BLAST database construction command-lines,
keyed by the input filestem.
- infiles - a list of paths to input FASTA files
- outdir - path to directory for BLAST databases/output
- blastdb_exe - path to BLAST database formatting executable
- jobprefix - a string to pref... | blastdb_exe, jobprefix)
# Create list of BLAST query jobs
queryjobs = make_blastp_jobs(infiles, outdir, blastp_exe, jobprefix, dbjobs)
return list(dbjobs.values()) + queryjobs
# Make a dictionary of makeblastdb jobs
def make_blastdb_jobs(infiles, outdir, blastdb_exe, jobprefix):
| 85 | 85 | 285 | 20 | 64 | widdowquinn/pyrbbh | pyrbbh/blast.py | Python | make_blastdb_jobs | make_blastdb_jobs | 50 | 71 | 50 | 50 | 84c4e147f819d7aad8935e4ee0b7514c165ccc1a | bigcode/the-stack | train |
dba358b0b825a7b9c7a59fd9 | train | function | def make_blastp_jobs(infiles, outdir, blastp_exe, jobprefix, dbjobs):
"""Returns a list of BLASTP query jobs for RBH analysis.
This requires nested loops of
- infiles - a list of paths to input FASTA files
- outdir - path to directory for BLAST output
- blastp_exe - path to BLASTP
- jobprefix... | def make_blastp_jobs(infiles, outdir, blastp_exe, jobprefix, dbjobs):
| """Returns a list of BLASTP query jobs for RBH analysis.
This requires nested loops of
- infiles - a list of paths to input FASTA files
- outdir - path to directory for BLAST output
- blastp_exe - path to BLASTP
- jobprefix - a string to prefix job IDs if run on SGE scheduler
- dbjobs - d... | ')
('makeblastdb -dbtype prot -in ../tests/seqdata/infile1.fasta -title \
infile1 -out ../tests/output/infile1.fasta', 'infile1')
"""
filename = os.path.split(infile)[-1] # strip directory
filestem = os.path.splitext(filename)[0] # strip extension
outfname = os.path.join(outdir, filename) # locat... | 184 | 184 | 615 | 23 | 160 | widdowquinn/pyrbbh | pyrbbh/blast.py | Python | make_blastp_jobs | make_blastp_jobs | 102 | 143 | 102 | 102 | b0b76325dab2873e4982790417f8be75edcc4754 | bigcode/the-stack | train |
fd7daf729cb9bf4250c8a7ba | train | function | def construct_makeblastdb_cmd(infile, outdir, blastdb_exe):
"""Returns a tuple of (cmd_line, filestem) where cmd_line is the BLAST
database formatting command for the passed filename, placing the result
in outdir, with the same filestem as the input filename.
The formatting assumes that the executable ... | def construct_makeblastdb_cmd(infile, outdir, blastdb_exe):
| """Returns a tuple of (cmd_line, filestem) where cmd_line is the BLAST
database formatting command for the passed filename, placing the result
in outdir, with the same filestem as the input filename.
The formatting assumes that the executable is makeblastdb from BLAST+
- infile - input filename
... | files):
dbcmd, dbname = construct_makeblastdb_cmd(fname, outdir, blastdb_exe)
job = jobs.Job("%s_db_%06d" % (jobprefix, idx), dbcmd)
dbjobdict[dbname] = job
return dbjobdict
# Build a makeblastdb command line
def construct_makeblastdb_cmd(infile, outdir, blastdb_exe):
| 88 | 88 | 296 | 17 | 70 | widdowquinn/pyrbbh | pyrbbh/blast.py | Python | construct_makeblastdb_cmd | construct_makeblastdb_cmd | 75 | 98 | 75 | 75 | 1cee7ccf56e4a18e50abc18003edb2613c5c4b0b | bigcode/the-stack | train |
8a300d99013cbf5ff8619eab | train | class | class FindBlanksNode(FindReferencesNode):
def _available_analysis_types_default(self):
return [(b, b) for b in BLANKS]
| class FindBlanksNode(FindReferencesNode):
| def _available_analysis_types_default(self):
return [(b, b) for b in BLANKS]
| def _get_display_loads(self):
if self.limit_to_analysis_loads:
return self.analysis_loads
else:
return self.loads
def _get_threshold_enabled(self):
return not self.load_name or self.load_name == NULL_STR
class FindBlanksNode(FindReferencesNode):
| 64 | 64 | 33 | 10 | 53 | ASUPychron/pychron | pychron/pipeline/nodes/find.py | Python | FindBlanksNode | FindBlanksNode | 667 | 669 | 667 | 667 | b1e18c0b4bd9fae619b5d1b36e92695ee446e2b8 | bigcode/the-stack | train |
8bb493f7a831e13a40b04896 | train | class | class FindIrradiationNode(BaseFindFluxNode):
select_all_button = Button("Select All")
selected_levels = List
def run(self, state):
if not self.irradiation or not self.level:
self.configure()
if not self.irradiation or not self.level:
state.veto = self
else:
... | class FindIrradiationNode(BaseFindFluxNode):
| select_all_button = Button("Select All")
selected_levels = List
def run(self, state):
if not self.irradiation or not self.level:
self.configure()
if not self.irradiation or not self.level:
state.veto = self
else:
state.levels = self.selected_leve... | =j_err or 0,
mean_j=mean_j or 0,
mean_jerr=mean_j_err or 0,
mean_j_mswd=mean_j_mswd or 0,
model_kind=model_kind,
x=x,
y=y,
r=r,
)
return fp
class FindIrradiationNode(BaseFindFluxNode):
| 78 | 78 | 262 | 12 | 65 | ASUPychron/pychron | pychron/pipeline/nodes/find.py | Python | FindIrradiationNode | FindIrradiationNode | 153 | 193 | 153 | 153 | f2e5a67f8aa2b586a1efaadc1da6e7e1708d9be5 | bigcode/the-stack | train |
ae49e0628257d31a4fe116e8 | train | function | def compress_groups(ans):
if ans:
for i, (gid, analyses) in enumerate(groupby_group_id(ans)):
for ai in analyses:
ai.group_id = i
| def compress_groups(ans):
| if ans:
for i, (gid, analyses) in enumerate(groupby_group_id(ans)):
for ai in analyses:
ai.group_id = i
| pychron.pipeline.graphical_filter import GraphicalFilterModel, GraphicalFilterView
from pychron.pipeline.nodes.data import DVCNode
from pychron.pychron_constants import (
DEFAULT_MONITOR_NAME,
NULL_STR,
REFERENCE_ANALYSIS_TYPES,
BLANKS,
)
def compress_groups(ans):
| 64 | 64 | 39 | 5 | 59 | ASUPychron/pychron | pychron/pipeline/nodes/find.py | Python | compress_groups | compress_groups | 37 | 41 | 37 | 37 | 7c93c698afb95aa04b757253943c6ff8cea8de46 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.