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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
83e290956b1feef4272c78b5 | train | function | def p_c_arg_list(s, ctx = Ctx(), in_pyfunc = 0, cmethod_flag = 0,
nonempty_declarators = 0, kw_only = 0, annotated = 1):
# Comma-separated list of C argument declarations, possibly empty.
# May have a trailing comma.
args = []
is_self_arg = cmethod_flag
while s.sy not in c_arg_lis... | def p_c_arg_list(s, ctx = Ctx(), in_pyfunc = 0, cmethod_flag = 0,
nonempty_declarators = 0, kw_only = 0, annotated = 1):
# Comma-separated list of C argument declarations, possibly empty.
# May have a trailing comma.
| args = []
is_self_arg = cmethod_flag
while s.sy not in c_arg_list_terminators:
args.append(p_c_arg_decl(s, ctx, in_pyfunc, is_self_arg,
nonempty = nonempty_declarators, kw_only = kw_only,
annotated = annotated))
if s.sy != ',':
break
s.next()
... | def p_c_arg_list(s, ctx = Ctx(), in_pyfunc = 0, cmethod_flag = 0,
nonempty_declarators = 0, kw_only = 0, annotated = 1):
# Comma-separated list of C argument declarations, possibly empty.
# May have a trailing comma.
| 71 | 64 | 163 | 71 | 0 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_c_arg_list | p_c_arg_list | 2,970 | 2,984 | 2,970 | 2,973 | a90baf6d4c923f5cfed1ec6f9cca834d54b14a78 | bigcode/the-stack | train |
2d3e5e099715429ce1a3c291 | train | function | def p_new_expr(s):
# s.systring == 'new'.
pos = s.position()
s.next()
cppclass = p_c_base_type(s)
return p_call(s, ExprNodes.NewExprNode(pos, cppclass = cppclass))
| def p_new_expr(s):
# s.systring == 'new'.
| pos = s.position()
s.next()
cppclass = p_c_base_type(s)
return p_call(s, ExprNodes.NewExprNode(pos, cppclass = cppclass))
| if s.sy == '**':
pos = s.position()
s.next()
n2 = p_factor(s)
n1 = ExprNodes.binop_node(pos, '**', n1, n2)
return n1
def p_new_expr(s):
# s.systring == 'new'.
| 64 | 64 | 54 | 15 | 48 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_new_expr | p_new_expr | 430 | 435 | 430 | 431 | 6aa33fedbda3ad715c2eaff1abb9edff7f5a7d6b | bigcode/the-stack | train |
6997d742a2db613e083fd1f5 | train | function | def p_if_clause(s):
pos = s.position()
test = p_test(s)
body = p_suite(s)
return Nodes.IfClauseNode(pos,
condition = test, body = body)
| def p_if_clause(s):
| pos = s.position()
test = p_test(s)
body = p_suite(s)
return Nodes.IfClauseNode(pos,
condition = test, body = body)
| )]
while s.sy == 'elif':
s.next()
if_clauses.append(p_if_clause(s))
else_clause = p_else_clause(s)
return Nodes.IfStatNode(pos,
if_clauses = if_clauses, else_clause = else_clause)
def p_if_clause(s):
| 64 | 64 | 43 | 6 | 58 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_if_clause | p_if_clause | 1,834 | 1,839 | 1,834 | 1,834 | 9fcf87ee6f263a4aaa82d71bfcbbdaedee8319ae | bigcode/the-stack | train |
8c3588c15e13338c76d725fc | train | function | def p_del_statement(s):
# s.sy == 'del'
pos = s.position()
s.next()
# FIXME: 'exprlist' in Python
args = p_simple_expr_list(s)
return Nodes.DelStatNode(pos, args = args)
| def p_del_statement(s):
# s.sy == 'del'
| pos = s.position()
s.next()
# FIXME: 'exprlist' in Python
args = p_simple_expr_list(s)
return Nodes.DelStatNode(pos, args = args)
| additional 'in' arguments",
fatal=False)
s.next()
args.append(p_test(s))
if s.sy == ',':
s.next()
args.append(p_test(s))
return Nodes.ExecStatNode(pos, args=args)
def p_del_statement(s):
# s.sy == 'del'
| 64 | 64 | 56 | 14 | 50 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_del_statement | p_del_statement | 1,594 | 1,600 | 1,594 | 1,595 | 81884e96c1ec3eeb068229b25017d8a9232e3cde | bigcode/the-stack | train |
294f94f7c70fc4403d1d39aa | train | function | def looking_at_name(s):
return s.sy == 'IDENT' and not s.systring in calling_convention_words
| def looking_at_name(s):
| return s.sy == 'IDENT' and not s.systring in calling_convention_words
| axis specification in memoryview declaration does not have a ':'.")
s.expect(']')
indexes = make_slice_nodes(pos, subscripts)
result = Nodes.MemoryViewSliceTypeNode(pos,
base_type_node = base_type_node,
axes = indexes)
return result
def looking_at_name(s):
| 64 | 64 | 25 | 6 | 57 | 0101011/cython | Cython/Compiler/Parsing.py | Python | looking_at_name | looking_at_name | 2,656 | 2,657 | 2,656 | 2,656 | b93b4eb74763df607becea5b1eefb397d13d814e | bigcode/the-stack | train |
40877d1e6a7c07433be69d0f | train | function | def p_print_statement(s):
# s.sy == 'print'
pos = s.position()
ends_with_comma = 0
s.next()
if s.sy == '>>':
s.next()
stream = p_test(s)
if s.sy == ',':
s.next()
ends_with_comma = s.sy in ('NEWLINE', 'EOF')
else:
stream = None
args = []... | def p_print_statement(s):
# s.sy == 'print'
| pos = s.position()
ends_with_comma = 0
s.next()
if s.sy == '>>':
s.next()
stream = p_test(s)
if s.sy == ',':
s.next()
ends_with_comma = s.sy in ('NEWLINE', 'EOF')
else:
stream = None
args = []
if s.sy not in ('NEWLINE', 'EOF'):
... | == 2:
return Nodes.SingleAssignmentNode(rhs.pos, lhs=expr_list[0], rhs=rhs)
else:
return Nodes.CascadedAssignmentNode(rhs.pos, lhs_list=expr_list[:-1], rhs=rhs)
def p_print_statement(s):
# s.sy == 'print'
| 64 | 64 | 196 | 14 | 50 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_print_statement | p_print_statement | 1,539 | 1,564 | 1,539 | 1,540 | c1961632c024592e000f7fba329f6cb327f52425 | bigcode/the-stack | train |
ecbfe03a1223302e340dc17e | train | function | def p_calling_convention(s):
if s.sy == 'IDENT' and s.systring in calling_convention_words:
result = s.systring
s.next()
return result
else:
return ""
| def p_calling_convention(s):
| if s.sy == 'IDENT' and s.systring in calling_convention_words:
result = s.systring
s.next()
return result
else:
return ""
| self argument of a C method of an extension type.
if s.sy == '(':
return p_c_complex_base_type(s, templates = templates)
else:
return p_c_simple_base_type(s, self_flag, nonempty = nonempty, templates = templates)
def p_calling_convention(s):
| 64 | 64 | 47 | 8 | 56 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_calling_convention | p_calling_convention | 2,435 | 2,441 | 2,435 | 2,435 | 55c7a94c13717b603bd2676801471b1faeae4545 | bigcode/the-stack | train |
9e2681a490a86ec3c29c8ca9 | train | function | def p_or_test(s):
return p_rassoc_binop_expr(s, ('or',), p_and_test)
| def p_or_test(s):
| return p_rassoc_binop_expr(s, ('or',), p_and_test)
| _test | lambdef_nocond
def p_test_nocond(s):
if s.sy == 'lambda':
return p_lambdef_nocond(s)
else:
return p_or_test(s)
#or_test: and_test ('or' and_test)*
def p_or_test(s):
| 64 | 64 | 24 | 6 | 57 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_or_test | p_or_test | 162 | 163 | 162 | 162 | 5e4819b2149ca86679e06878b5c96b30d1e98884 | bigcode/the-stack | train |
6eb8e37688819c22b8322984 | train | class | class Ctx(object):
# Parsing context
level = 'other'
visibility = 'private'
cdef_flag = 0
typedef_flag = 0
api = 0
overridable = 0
nogil = 0
namespace = None
templates = None
allow_struct_enum_decorator = False
def __init__(self, **kwds):
self.__dict__.update(kw... | class Ctx(object):
# Parsing context
| level = 'other'
visibility = 'private'
cdef_flag = 0
typedef_flag = 0
api = 0
overridable = 0
nogil = 0
namespace = None
templates = None
allow_struct_enum_decorator = False
def __init__(self, **kwds):
self.__dict__.update(kwds)
def __call__(self, **kwds):
... | Future
from . import Options
_IS_PY3 = sys.version_info[0] >= 3
_IS_2BYTE_UNICODE = sys.maxunicode == 0xffff
_CDEF_MODIFIERS = ('inline', 'nogil', 'api')
class Ctx(object):
# Parsing context
| 64 | 64 | 140 | 11 | 53 | 0101011/cython | Cython/Compiler/Parsing.py | Python | Ctx | Ctx | 42 | 63 | 42 | 43 | bf37c5a6e0251b544b0813acf51ac16e5efac08a | bigcode/the-stack | train |
f6592825a79f71ea3c87dc37 | train | function | def p_decorators(s):
decorators = []
while s.sy == '@':
pos = s.position()
s.next()
decstring = p_dotted_name(s, as_allowed=0)[2]
names = decstring.split('.')
decorator = ExprNodes.NameNode(pos, name=s.context.intern_ustring(names[0]))
for name in names[1:]:
... | def p_decorators(s):
| decorators = []
while s.sy == '@':
pos = s.position()
s.next()
decstring = p_dotted_name(s, as_allowed=0)[2]
names = decstring.split('.')
decorator = ExprNodes.NameNode(pos, name=s.context.intern_ustring(names[0]))
for name in names[1:]:
decorator = Ex... | error in ctypedef statement", ignore_semicolon=True)
return Nodes.CTypeDefNode(
pos, base_type = base_type,
declarator = declarator,
visibility = visibility, api = api,
in_pxd = ctx.level == 'module_pxd')
def p_decorators(s):
| 64 | 64 | 157 | 7 | 57 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_decorators | p_decorators | 3,362 | 3,377 | 3,362 | 3,362 | 44c21b246ae1b35ffe131458d879d841f995a9c1 | bigcode/the-stack | train |
01e3840cd99529a15b5fe1a7 | train | function | def p_yield_expression(s):
# s.sy == "yield"
pos = s.position()
s.next()
is_yield_from = False
if s.sy == 'from':
is_yield_from = True
s.next()
if s.sy != ')' and s.sy not in statement_terminators:
# "yield from" does not support implicit tuples, but "yield" does ("yield ... | def p_yield_expression(s):
# s.sy == "yield"
| pos = s.position()
s.next()
is_yield_from = False
if s.sy == 'from':
is_yield_from = True
s.next()
if s.sy != ')' and s.sy not in statement_terminators:
# "yield from" does not support implicit tuples, but "yield" does ("yield 1,2")
arg = p_test(s) if is_yield_from el... | declarator = p_c_declarator(s, empty = 1)
node = ExprNodes.SizeofTypeNode(pos,
base_type = base_type, declarator = declarator)
s.expect(')')
return node
def p_yield_expression(s):
# s.sy == "yield"
| 64 | 64 | 185 | 15 | 48 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_yield_expression | p_yield_expression | 360 | 379 | 360 | 361 | dc8330aadd2f896e2b9e851486955c601ed9fb1c | bigcode/the-stack | train |
f3a7c7820c229cbd630e1bde | train | function | def p_ident_list(s):
names = []
while s.sy == 'IDENT':
names.append(s.context.intern_ustring(s.systring))
s.next()
if s.sy != ',':
break
s.next()
return names
| def p_ident_list(s):
| names = []
while s.sy == 'IDENT':
names.append(s.context.intern_ustring(s.systring))
s.next()
if s.sy != ',':
break
s.next()
return names
| .update(kwds)
return ctx
def p_ident(s, message="Expected an identifier"):
if s.sy == 'IDENT':
name = s.context.intern_ustring(s.systring)
s.next()
return name
else:
s.error(message)
def p_ident_list(s):
| 64 | 64 | 54 | 6 | 58 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_ident_list | p_ident_list | 74 | 82 | 74 | 74 | fbde56e43ac1d278e9a95bf2b04d8881dbb2bd68 | bigcode/the-stack | train |
ecb44eeec1ac79465646312a | train | function | def p_cdef_extern_block(s, pos, ctx):
if ctx.overridable:
error(pos, "cdef extern blocks cannot be declared cpdef")
include_file = None
s.expect('from')
if s.sy == '*':
s.next()
else:
include_file = p_string_literal(s, 'u')[2]
ctx = ctx(cdef_flag = 1, visibility = 'extern... | def p_cdef_extern_block(s, pos, ctx):
| if ctx.overridable:
error(pos, "cdef extern blocks cannot be declared cpdef")
include_file = None
s.expect('from')
if s.sy == '*':
s.next()
else:
include_file = p_string_literal(s, 'u')[2]
ctx = ctx(cdef_flag = 1, visibility = 'extern')
if s.systring == "namespace":
... | p_fused_definition(s, pos, ctx)
else:
return p_c_func_or_var_declaration(s, pos, ctx)
def p_cdef_block(s, ctx):
return p_suite(s, ctx(cdef_flag = 1))
def p_cdef_extern_block(s, pos, ctx):
| 64 | 64 | 203 | 13 | 51 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_cdef_extern_block | p_cdef_extern_block | 3,096 | 3,119 | 3,096 | 3,096 | b4e58b52f209a93541dfc516de416827fbd93f5e | bigcode/the-stack | train |
1702aefe8dc224011e76e3b5 | train | function | def p_subscript(s):
# Parse a subscript and return a list of
# 1, 2 or 3 ExprNodes, depending on how
# many slice elements were encountered.
pos = s.position()
start = p_slice_element(s, (':',))
if s.sy != ':':
return [start]
s.next()
stop = p_slice_element(s, (':', ',', ']'))
... | def p_subscript(s):
# Parse a subscript and return a list of
# 1, 2 or 3 ExprNodes, depending on how
# many slice elements were encountered.
| pos = s.position()
start = p_slice_element(s, (':',))
if s.sy != ':':
return [start]
s.next()
stop = p_slice_element(s, (':', ',', ']'))
if s.sy != ':':
return [start, stop]
s.next()
step = p_slice_element(s, (':', ',', ']'))
return [start, stop, step]
| subscript: '.' '.' '.' | test | [test] ':' [test] [':' [test]]
def p_subscript(s):
# Parse a subscript and return a list of
# 1, 2 or 3 ExprNodes, depending on how
# many slice elements were encountered.
| 64 | 64 | 132 | 43 | 21 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_subscript | p_subscript | 604 | 618 | 604 | 607 | a0859e812b3efcb84c83994163e5b290f7f0927c | bigcode/the-stack | train |
4c513b7194f6732e02cf34e1 | train | function | def p_pass_statement(s, with_newline = 0):
pos = s.position()
s.expect('pass')
if with_newline:
s.expect_newline("Expected a newline", ignore_semicolon=True)
return Nodes.PassStatNode(pos)
| def p_pass_statement(s, with_newline = 0):
| pos = s.position()
s.expect('pass')
if with_newline:
s.expect_newline("Expected a newline", ignore_semicolon=True)
return Nodes.PassStatNode(pos)
| ):
# s.sy == 'del'
pos = s.position()
s.next()
# FIXME: 'exprlist' in Python
args = p_simple_expr_list(s)
return Nodes.DelStatNode(pos, args = args)
def p_pass_statement(s, with_newline = 0):
| 64 | 64 | 54 | 13 | 51 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_pass_statement | p_pass_statement | 1,602 | 1,607 | 1,602 | 1,602 | e3b0d6386abf8a0d2b1ece6da45a2f6a4347b810 | bigcode/the-stack | train |
5e7e6160e505e46fd31f3dc2 | train | function | def p_int_literal(s):
pos = s.position()
value = s.systring
s.next()
unsigned = ""
longness = ""
while value[-1] in u"UuLl":
if value[-1] in u"Ll":
longness += "L"
else:
unsigned += "U"
value = value[:-1]
# '3L' is ambiguous in Py2 but not in P... | def p_int_literal(s):
| pos = s.position()
value = s.systring
s.next()
unsigned = ""
longness = ""
while value[-1] in u"UuLl":
if value[-1] in u"Ll":
longness += "L"
else:
unsigned += "U"
value = value[:-1]
# '3L' is ambiguous in Py2 but not in Py3. '3U' and '3LL' ar... | result = ExprNodes.BoolNode(pos, value=False)
elif name == "NULL" and not s.in_python_file:
result = ExprNodes.NullNode(pos)
else:
result = p_name(s, name)
s.next()
return result
else:
s.error("Expected an identifier or literal")
def p_int_... | 74 | 74 | 247 | 6 | 68 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_int_literal | p_int_literal | 721 | 750 | 721 | 721 | 1d7ccf2faf60fc1eb0fa94f05b8e2fe214f72066 | bigcode/the-stack | train |
bfb7f33ec514dd96f47513a6 | train | function | def p_nonlocal_statement(s):
pos = s.position()
s.next()
names = p_ident_list(s)
return Nodes.NonlocalNode(pos, names = names)
| def p_nonlocal_statement(s):
| pos = s.position()
s.next()
names = p_ident_list(s)
return Nodes.NonlocalNode(pos, names = names)
|
#-------------------------------------------------------
#
# Statements
#
#-------------------------------------------------------
def p_global_statement(s):
# assume s.sy == 'global'
pos = s.position()
s.next()
names = p_ident_list(s)
return Nodes.GlobalNode(pos, names = names)
def p_nonlocal... | 64 | 64 | 37 | 7 | 57 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_nonlocal_statement | p_nonlocal_statement | 1,485 | 1,489 | 1,485 | 1,485 | 2d1d1d70d7ec6181835d42928c898cfe9c5abeba | bigcode/the-stack | train |
9a7a30f43141566fd13995c0 | train | function | def p_imported_name(s, is_cimport):
pos = s.position()
kind = None
if is_cimport and s.systring in imported_name_kinds:
kind = s.systring
s.next()
name = p_ident(s)
as_name = p_as_name(s)
return (pos, name, as_name, kind)
| def p_imported_name(s, is_cimport):
| pos = s.position()
kind = None
if is_cimport and s.systring in imported_name_kinds:
kind = s.systring
s.next()
name = p_ident(s)
as_name = p_as_name(s)
return (pos, name, as_name, kind)
| = ExprNodes.IdentifierStringNode(pos, value = dotted_name),
level = level,
name_list = import_list),
items = items)
imported_name_kinds = cython.declare(set, set(['class', 'struct', 'union']))
def p_imported_name(s, is_cimport):
| 63 | 64 | 76 | 11 | 52 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_imported_name | p_imported_name | 1,775 | 1,783 | 1,775 | 1,775 | a96c5a30b1581169ab941cdc8f22b1178fc251f7 | bigcode/the-stack | train |
70eca8826d1957fa870c320a | train | function | def p_from_import_statement(s, first_statement = 0):
# s.sy == 'from'
pos = s.position()
s.next()
if s.sy == '.':
# count relative import level
level = 0
while s.sy == '.':
level += 1
s.next()
else:
level = None
if level is not None and s.s... | def p_from_import_statement(s, first_statement = 0):
# s.sy == 'from'
| pos = s.position()
s.next()
if s.sy == '.':
# count relative import level
level = 0
while s.sy == '.':
level += 1
s.next()
else:
level = None
if level is not None and s.sy in ('import', 'cimport'):
# we are dealing with "from .. import ... | _allowed=1))
stats = []
is_absolute = Future.absolute_import in s.context.future_directives
for pos, target_name, dotted_name, as_name in items:
if kind == 'cimport':
stat = Nodes.CImportStatNode(
pos,
module_name=dotted_name,
as_name=as_na... | 204 | 204 | 680 | 21 | 183 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_from_import_statement | p_from_import_statement | 1,692 | 1,770 | 1,692 | 1,693 | a37bb63924f319ed408e590a3d07547412a7b528 | bigcode/the-stack | train |
fc7f7d7ab0d1e113c5752310 | train | function | def p_c_class_options(s):
objstruct_name = None
typeobj_name = None
check_size = None
s.expect('[')
while 1:
if s.sy != 'IDENT':
break
if s.systring == 'object':
s.next()
objstruct_name = p_ident(s)
elif s.systring == 'type':
s.... | def p_c_class_options(s):
| objstruct_name = None
typeobj_name = None
check_size = None
s.expect('[')
while 1:
if s.sy != 'IDENT':
break
if s.systring == 'object':
s.next()
objstruct_name = p_ident(s)
elif s.systring == 'type':
s.next()
typeobj... | = as_name,
bases = bases,
objstruct_name = objstruct_name,
typeobj_name = typeobj_name,
check_size = check_size,
in_pxd = ctx.level == 'module_pxd',
doc = doc,
body = body)
def p_c_class_options(s):
| 64 | 64 | 196 | 7 | 57 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_c_class_options | p_c_class_options | 3,553 | 3,576 | 3,553 | 3,553 | a165250d2816330ec713847750682a97da417307 | bigcode/the-stack | train |
05ab8a400097898c25d33a6d | train | function | def p_cdef_block(s, ctx):
return p_suite(s, ctx(cdef_flag = 1))
| def p_cdef_block(s, ctx):
| return p_suite(s, ctx(cdef_flag = 1))
| _struct_enum(s, pos, ctx)
elif s.sy == 'IDENT' and s.systring == 'fused':
return p_fused_definition(s, pos, ctx)
else:
return p_c_func_or_var_declaration(s, pos, ctx)
def p_cdef_block(s, ctx):
| 64 | 64 | 23 | 9 | 55 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_cdef_block | p_cdef_block | 3,093 | 3,094 | 3,093 | 3,093 | 92ced11845e20b5e13a8e53f5df085a8daa35b0c | bigcode/the-stack | train |
5b284bf294b030f5a3041510 | train | function | def p_c_class_definition(s, pos, ctx):
# s.sy == 'class'
s.next()
module_path = []
class_name = p_ident(s)
while s.sy == '.':
s.next()
module_path.append(class_name)
class_name = p_ident(s)
if module_path and ctx.visibility != 'extern':
error(pos, "Qualified clas... | def p_c_class_definition(s, pos, ctx):
# s.sy == 'class'
| s.next()
module_path = []
class_name = p_ident(s)
while s.sy == '.':
s.next()
module_path.append(class_name)
class_name = p_ident(s)
if module_path and ctx.visibility != 'extern':
error(pos, "Qualified class name only allowed for 'extern' C class")
if module_path ... | (p_ident(s))
class_name.encoding = s.source_encoding # FIXME: why is this needed?
arg_tuple = None
keyword_dict = None
if s.sy == '(':
positional_args, keyword_args = p_call_parse_args(s, allow_genexp=False)
arg_tuple, keyword_dict = p_call_build_packed_args(pos, positional_args, keywor... | 203 | 203 | 679 | 20 | 183 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_c_class_definition | p_c_class_definition | 3,477 | 3,550 | 3,477 | 3,478 | 6450121110535c45ee4eab483bf79f9d3ce7fac8 | bigcode/the-stack | train |
27ca2d202d033c8fb15a9f90 | train | function | def p_break_statement(s):
# s.sy == 'break'
pos = s.position()
s.next()
return Nodes.BreakStatNode(pos)
| def p_break_statement(s):
# s.sy == 'break'
| pos = s.position()
s.next()
return Nodes.BreakStatNode(pos)
| (s, with_newline = 0):
pos = s.position()
s.expect('pass')
if with_newline:
s.expect_newline("Expected a newline", ignore_semicolon=True)
return Nodes.PassStatNode(pos)
def p_break_statement(s):
# s.sy == 'break'
| 64 | 64 | 33 | 14 | 50 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_break_statement | p_break_statement | 1,609 | 1,613 | 1,609 | 1,610 | 308cb3e6bf2c9a032605d9231a65f5387cabb4f9 | bigcode/the-stack | train |
e783404ee8cfe4edac56cd96 | train | function | def p_simple_statement_list(s, ctx, first_statement = 0):
# Parse a series of simple statements on one line
# separated by semicolons.
stat = p_simple_statement(s, first_statement = first_statement)
pos = stat.pos
stats = []
if not isinstance(stat, Nodes.PassStatNode):
stats.append(stat)... | def p_simple_statement_list(s, ctx, first_statement = 0):
# Parse a series of simple statements on one line
# separated by semicolons.
| stat = p_simple_statement(s, first_statement = first_statement)
pos = stat.pos
stats = []
if not isinstance(stat, Nodes.PassStatNode):
stats.append(stat)
while s.sy == ';':
#print "p_simple_statement_list: maybe more to follow" ###
s.next()
if s.sy in ('NEWLINE', 'EOF... | node = p_yield_statement(s)
elif s.sy == 'assert':
node = p_assert_statement(s)
elif s.sy == 'pass':
node = p_pass_statement(s)
else:
node = p_expression_or_assignment(s)
return node
def p_simple_statement_list(s, ctx, first_statement = 0):
# Parse a series of simple stateme... | 91 | 91 | 304 | 35 | 55 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_simple_statement_list | p_simple_statement_list | 2,141 | 2,174 | 2,141 | 2,143 | 586184588532b3348416ee52451bbe26483d9209 | bigcode/the-stack | train |
d653c1e3b04d0103ee2dfd73 | train | function | def p_testlist(s):
pos = s.position()
expr = p_test(s)
if s.sy == ',':
s.next()
exprs = p_simple_expr_list(s, expr)
return ExprNodes.TupleNode(pos, args = exprs)
else:
return expr
| def p_testlist(s):
| pos = s.position()
expr = p_test(s)
if s.sy == ',':
s.next()
exprs = p_simple_expr_list(s, expr)
return ExprNodes.TupleNode(pos, args = exprs)
else:
return expr
| expr] or []
while s.sy not in expr_terminators:
exprs.append(p_test_or_starred_expr(s))
if s.sy != ',':
break
s.next()
return exprs
#testlist: test (',' test)* [',']
def p_testlist(s):
| 64 | 64 | 62 | 6 | 58 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_testlist | p_testlist | 1,425 | 1,433 | 1,425 | 1,425 | f7c16912e9d21c0622d76234e981dc7530f78c68 | bigcode/the-stack | train |
95a05768ffce22a88fc424c0 | train | function | def p_template_definition(s):
name = p_ident(s)
if s.sy == '=':
s.expect('=')
s.expect('*')
required = False
else:
required = True
return name, required
| def p_template_definition(s):
| name = p_ident(s)
if s.sy == '=':
s.expect('=')
s.expect('*')
required = False
else:
required = True
return name, required
| 'EOF':
s.error("Syntax error in statement [%s,%s]" % (
repr(s.sy), repr(s.systring)))
return ModuleNode(pos, doc = doc, body = body,
full_module_name = full_module_name,
directive_comments = directive_comments)
def p_template_definition(s):
| 64 | 64 | 49 | 6 | 58 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_template_definition | p_template_definition | 3,724 | 3,732 | 3,724 | 3,724 | 635c8f3e685927dc8f570434aab7faf5de11612e | bigcode/the-stack | train |
fa50c5d724f70272964a4da9 | train | function | def p_call_build_packed_args(pos, positional_args, keyword_args):
keyword_dict = None
subtuples = [
ExprNodes.TupleNode(pos, args=arg) if isinstance(arg, list) else ExprNodes.AsTupleNode(pos, arg=arg)
for arg in positional_args
]
# TODO: implement a faster way to join tuples than creati... | def p_call_build_packed_args(pos, positional_args, keyword_args):
| keyword_dict = None
subtuples = [
ExprNodes.TupleNode(pos, args=arg) if isinstance(arg, list) else ExprNodes.AsTupleNode(pos, arg=arg)
for arg in positional_args
]
# TODO: implement a faster way to join tuples than creating each one and adding them
arg_tuple = reduce(partial(ExprNod... | :
break
s.next()
if s.sy in ('for', 'async'):
if not keyword_args and not last_was_tuple_unpack:
if len(positional_args) == 1 and len(positional_args[0]) == 1:
positional_args = [[p_genexp(s, positional_args[0][0])]]
s.expect(')')
return positional_ar... | 102 | 102 | 342 | 15 | 86 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_call_build_packed_args | p_call_build_packed_args | 512 | 551 | 512 | 512 | 0c8b107af31ba7efe154881e4cd2a1234bc232c0 | bigcode/the-stack | train |
38e14d3a2659b5c3520f80d9 | train | function | def p_while_statement(s):
# s.sy == 'while'
pos = s.position()
s.next()
test = p_test(s)
body = p_suite(s)
else_clause = p_else_clause(s)
return Nodes.WhileStatNode(pos,
condition = test, body = body,
else_clause = else_clause)
| def p_while_statement(s):
# s.sy == 'while'
| pos = s.position()
s.next()
test = p_test(s)
body = p_suite(s)
else_clause = p_else_clause(s)
return Nodes.WhileStatNode(pos,
condition = test, body = body,
else_clause = else_clause)
| )
return Nodes.IfClauseNode(pos,
condition = test, body = body)
def p_else_clause(s):
if s.sy == 'else':
s.next()
return p_suite(s)
else:
return None
def p_while_statement(s):
# s.sy == 'while'
| 64 | 64 | 73 | 15 | 48 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_while_statement | p_while_statement | 1,848 | 1,857 | 1,848 | 1,849 | 945f7e45c038087d7883bf26b8fe3e794a76fb76 | bigcode/the-stack | train |
c3d8be97c00c841245723122 | train | function | def p_c_base_type(s, self_flag = 0, nonempty = 0, templates = None):
# If self_flag is true, this is the base type for the
# self argument of a C method of an extension type.
if s.sy == '(':
return p_c_complex_base_type(s, templates = templates)
else:
return p_c_simple_base_type(s, self_... | def p_c_base_type(s, self_flag = 0, nonempty = 0, templates = None):
# If self_flag is true, this is the base type for the
# self argument of a C method of an extension type.
| if s.sy == '(':
return p_c_complex_base_type(s, templates = templates)
else:
return p_c_simple_base_type(s, self_flag, nonempty = nonempty, templates = templates)
| s.next()
return positional_args, keyword_args
def p_c_base_type(s, self_flag = 0, nonempty = 0, templates = None):
# If self_flag is true, this is the base type for the
# self argument of a C method of an extension type.
| 64 | 64 | 97 | 52 | 11 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_c_base_type | p_c_base_type | 2,427 | 2,433 | 2,427 | 2,429 | 3ba8b5304940849af6ab1d9020e80c7b6e18b044 | bigcode/the-stack | train |
0e86e3c0ac05e82cb93514b0 | train | function | def p_ignorable_statement(s):
"""
Parses any kind of ignorable statement that is allowed in .pxd files.
"""
if s.sy == 'BEGIN_STRING':
pos = s.position()
string_node = p_atom(s)
s.expect_newline("Syntax error in string", ignore_semicolon=True)
return Nodes.ExprStatNode(po... | def p_ignorable_statement(s):
| """
Parses any kind of ignorable statement that is allowed in .pxd files.
"""
if s.sy == 'BEGIN_STRING':
pos = s.position()
string_node = p_atom(s)
s.expect_newline("Syntax error in string", ignore_semicolon=True)
return Nodes.ExprStatNode(pos, expr=string_node)
retur... | () # 'property'
name = p_ident(s)
doc, body = p_suite_with_docstring(
s, Ctx(level='property'), with_doc_only=True)
return Nodes.PropertyNode(pos, name=name, doc=doc, body=body)
def p_ignorable_statement(s):
| 64 | 64 | 85 | 8 | 56 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_ignorable_statement | p_ignorable_statement | 3,588 | 3,597 | 3,588 | 3,588 | 9113535e599cc2eb8acf4bc2b6399f33a0ae8fdb | bigcode/the-stack | train |
50c26ed1be5a3cdbe8a11b3f | train | function | def p_backquote_expr(s):
# s.sy == '`'
pos = s.position()
s.next()
args = [p_test(s)]
while s.sy == ',':
s.next()
args.append(p_test(s))
s.expect('`')
if len(args) == 1:
arg = args[0]
else:
arg = ExprNodes.TupleNode(pos, args = args)
return ExprNodes.B... | def p_backquote_expr(s):
# s.sy == '`'
| pos = s.position()
s.next()
args = [p_test(s)]
while s.sy == ',':
s.next()
args.append(p_test(s))
s.expect('`')
if len(args) == 1:
arg = args[0]
else:
arg = ExprNodes.TupleNode(pos, args = args)
return ExprNodes.BackquoteNode(pos, arg = arg)
| if len(items) == 1 and items[0].is_dict_literal:
return items[0]
return ExprNodes.MergedDictNode(pos, keyword_args=items, reject_duplicates=False)
# NOTE: no longer in Py3 :)
def p_backquote_expr(s):
# s.sy == '`'
| 64 | 64 | 101 | 14 | 50 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_backquote_expr | p_backquote_expr | 1,388 | 1,401 | 1,388 | 1,389 | c96201bb0e5a4e43eeb23e19194b978088fa87d0 | bigcode/the-stack | train |
6bc356977af5cc6f5ad84219 | train | function | def p_c_func_or_var_declaration(s, pos, ctx):
cmethod_flag = ctx.level in ('c_class', 'c_class_pxd')
modifiers = p_c_modifiers(s)
base_type = p_c_base_type(s, nonempty = 1, templates = ctx.templates)
declarator = p_c_declarator(s, ctx(modifiers=modifiers), cmethod_flag = cmethod_flag,
... | def p_c_func_or_var_declaration(s, pos, ctx):
| cmethod_flag = ctx.level in ('c_class', 'c_class_pxd')
modifiers = p_c_modifiers(s)
base_type = p_c_base_type(s, nonempty = 1, templates = ctx.templates)
declarator = p_c_declarator(s, ctx(modifiers=modifiers), cmethod_flag = cmethod_flag,
assignable = 1, nonempty = 1)
... | ':
return p_c_enum_definition(s, pos, ctx)
else:
return p_c_struct_or_union_definition(s, pos, ctx)
def p_visibility(s, prev_visibility):
pos = s.position()
visibility = prev_visibility
if s.sy == 'IDENT' and s.systring in ('extern', 'public', 'readonly'):
visibility = s.systrin... | 191 | 191 | 637 | 14 | 177 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_c_func_or_var_declaration | p_c_func_or_var_declaration | 3,273 | 3,335 | 3,273 | 3,273 | 38e0e146f7ff7370bdd06e1dd92876dfbfd4965c | bigcode/the-stack | train |
27f581c6383baca0480a77d7 | train | function | def p_genexp(s, expr):
# s.sy == 'async' | 'for'
loop = p_comp_for(s, Nodes.ExprStatNode(
expr.pos, expr = ExprNodes.YieldExprNode(expr.pos, arg=expr)))
return ExprNodes.GeneratorExpressionNode(expr.pos, loop=loop)
| def p_genexp(s, expr):
# s.sy == 'async' | 'for'
| loop = p_comp_for(s, Nodes.ExprStatNode(
expr.pos, expr = ExprNodes.YieldExprNode(expr.pos, arg=expr)))
return ExprNodes.GeneratorExpressionNode(expr.pos, loop=loop)
| (s, expr)
return ExprNodes.TupleNode(pos, args = exprs)
elif s.sy in ('for', 'async'):
return p_genexp(s, expr)
else:
return expr
def p_genexp(s, expr):
# s.sy == 'async' | 'for'
| 64 | 64 | 67 | 20 | 43 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_genexp | p_genexp | 1,461 | 1,465 | 1,461 | 1,462 | fdba9cbd231fbb0812e5090dd41f7773ca1923c8 | bigcode/the-stack | train |
57532579254ab002a520f7fe | train | function | def p_class_statement(s, decorators):
# s.sy == 'class'
pos = s.position()
s.next()
class_name = EncodedString(p_ident(s))
class_name.encoding = s.source_encoding # FIXME: why is this needed?
arg_tuple = None
keyword_dict = None
if s.sy == '(':
positional_args, keyword_args = p_... | def p_class_statement(s, decorators):
# s.sy == 'class'
| pos = s.position()
s.next()
class_name = EncodedString(p_ident(s))
class_name.encoding = s.source_encoding # FIXME: why is this needed?
arg_tuple = None
keyword_dict = None
if s.sy == '(':
positional_args, keyword_args = p_call_parse_args(s, allow_genexp=False)
arg_tuple, ke... | = p_ident(s)
annotation = None
if annotated and s.sy == ':':
s.next()
annotation = p_test(s)
return Nodes.PyArgDeclNode(pos, name = name, annotation = annotation)
def p_class_statement(s, decorators):
# s.sy == 'class'
| 64 | 64 | 216 | 16 | 48 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_class_statement | p_class_statement | 3,454 | 3,474 | 3,454 | 3,455 | eae17046925358bfa839fd5d88c8de13760b75da | bigcode/the-stack | train |
1acaccd4d1f64b362fe4e19d | train | function | def p_for_target(s):
return p_target(s, 'in')
| def p_for_target(s):
| return p_target(s, 'in')
| exprs = [expr]
while s.sy != terminator:
exprs.append(p_starred_expr(s))
if s.sy != ',':
break
s.next()
return ExprNodes.TupleNode(pos, args = exprs)
else:
return expr
def p_for_target(s):
| 64 | 64 | 15 | 6 | 57 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_for_target | p_for_target | 1,948 | 1,949 | 1,948 | 1,948 | 0665cc9b9ef04b3c2aed3edb8572b58d212f9ea4 | bigcode/the-stack | train |
7d5804676aaf9858df634672 | train | function | def print_parse_tree(f, node, level, key = None):
ind = " " * level
if node:
f.write(ind)
if key:
f.write("%s: " % key)
t = type(node)
if t is tuple:
f.write("(%s @ %s\n" % (node[0], node[1]))
for i in range(2, len(node)):
prin... | def print_parse_tree(f, node, level, key = None):
| ind = " " * level
if node:
f.write(ind)
if key:
f.write("%s: " % key)
t = type(node)
if t is tuple:
f.write("(%s @ %s\n" % (node[0], node[1]))
for i in range(2, len(node)):
print_parse_tree(f, node[i], level+1)
f.wr... | _decorator:
tup += Nodes.CStructOrUnionDefNode, Nodes.CEnumDefNode
if not isinstance(node, tup):
s.error("Decorators can only be followed by functions or classes")
node.decorators = decorators
return node
#----------------------------------------------
#... | 80 | 80 | 269 | 14 | 66 | 0101011/cython | Cython/Compiler/Parsing.py | Python | print_parse_tree | print_parse_tree | 3,824 | 3,853 | 3,824 | 3,824 | 0e58c8fe58112304459bc6f77378d4c5da558b46 | bigcode/the-stack | train |
ca3c86bcb048d6fbdfaae6e4 | train | function | def p_opt_cname(s):
literal = p_opt_string_literal(s, 'u')
if literal is not None:
cname = EncodedString(literal)
cname.encoding = s.source_encoding
else:
cname = None
return cname
| def p_opt_cname(s):
| literal = p_opt_string_literal(s, 'u')
if literal is not None:
cname = EncodedString(literal)
cname.encoding = s.source_encoding
else:
cname = None
return cname
| elif s.systring == 'signed':
signed = 2
elif s.systring == 'short':
longness = -1
elif s.systring == 'long':
longness += 1
s.next()
return signed, longness
def p_opt_cname(s):
| 64 | 64 | 55 | 7 | 56 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_opt_cname | p_opt_cname | 2,766 | 2,773 | 2,766 | 2,766 | 071975958026644a17a66f959f53141a9371e022 | bigcode/the-stack | train |
fdb155e7180ed6aaa1f6b06e | train | function | def p_starred_expr(s):
pos = s.position()
if s.sy == '*':
starred = True
s.next()
else:
starred = False
expr = p_bit_expr(s)
if starred:
expr = ExprNodes.StarredUnpackingNode(pos, expr)
return expr
| def p_starred_expr(s):
| pos = s.position()
if s.sy == '*':
starred = True
s.next()
else:
starred = False
expr = p_bit_expr(s)
if starred:
expr = ExprNodes.StarredUnpackingNode(pos, expr)
return expr
| s.sy in comparison_ops:
n1.cascade = p_cascaded_cmp(s)
return n1
def p_test_or_starred_expr(s):
if s.sy == '*':
return p_starred_expr(s)
else:
return p_test(s)
def p_starred_expr(s):
| 64 | 64 | 68 | 7 | 57 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_starred_expr | p_starred_expr | 212 | 222 | 212 | 212 | f9bd9bb16021caf2e3bbb8b6e2eeed87d468b2bd | bigcode/the-stack | train |
c852ead1123837d640f826e0 | train | function | def p_cascaded_cmp(s):
pos = s.position()
op = p_cmp_op(s)
n2 = p_starred_expr(s)
result = ExprNodes.CascadedCmpNode(pos,
operator = op, operand2 = n2)
if s.sy in comparison_ops:
result.cascade = p_cascaded_cmp(s)
return result
| def p_cascaded_cmp(s):
| pos = s.position()
op = p_cmp_op(s)
n2 = p_starred_expr(s)
result = ExprNodes.CascadedCmpNode(pos,
operator = op, operand2 = n2)
if s.sy in comparison_ops:
result.cascade = p_cascaded_cmp(s)
return result
| ()
if s.sy == '*':
starred = True
s.next()
else:
starred = False
expr = p_bit_expr(s)
if starred:
expr = ExprNodes.StarredUnpackingNode(pos, expr)
return expr
def p_cascaded_cmp(s):
| 64 | 64 | 79 | 8 | 55 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_cascaded_cmp | p_cascaded_cmp | 224 | 232 | 224 | 224 | eb3b4c8f886058b8c074f6580a0b4200ba3225e1 | bigcode/the-stack | train |
fc73d8d265733749acf29d87 | train | function | def p_list_maker(s):
# s.sy == '['
pos = s.position()
s.next()
if s.sy == ']':
s.expect(']')
return ExprNodes.ListNode(pos, args=[])
expr = p_test_or_starred_expr(s)
if s.sy in ('for', 'async'):
if expr.is_starred:
s.error("iterable unpacking cannot be used i... | def p_list_maker(s):
# s.sy == '['
| pos = s.position()
s.next()
if s.sy == ']':
s.expect(']')
return ExprNodes.ListNode(pos, args=[])
expr = p_test_or_starred_expr(s)
if s.sy in ('for', 'async'):
if expr.is_starred:
s.error("iterable unpacking cannot be used in comprehension")
append = Expr... | star_expr))* [','] )
# comp_iter ::= comp_for | comp_if
# comp_for ::= ["async"] "for" expression_list "in" testlist [comp_iter]
# comp_if ::= "if" test [comp_iter]
def p_list_maker(s):
# s.sy == '['
| 70 | 70 | 234 | 14 | 56 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_list_maker | p_list_maker | 1,208 | 1,235 | 1,208 | 1,209 | c41a4eec0059cdf00948ec0acb7a04df6d4c5c0a | bigcode/the-stack | train |
afcf679810302ff5d5f6729b | train | function | def p_call(s, function):
# s.sy == '('
pos = s.position()
positional_args, keyword_args = p_call_parse_args(s)
if not keyword_args and len(positional_args) == 1 and isinstance(positional_args[0], list):
return ExprNodes.SimpleCallNode(pos, function=function, args=positional_args[0])
else:
... | def p_call(s, function):
# s.sy == '('
| pos = s.position()
positional_args, keyword_args = p_call_parse_args(s)
if not keyword_args and len(positional_args) == 1 and isinstance(positional_args[0], list):
return ExprNodes.SimpleCallNode(pos, function=function, args=positional_args[0])
else:
arg_tuple, keyword_dict = p_call_bui... | arguments found -> one dict
keyword_dict = kwargs[0]
else:
# at least one **kwargs
keyword_dict = ExprNodes.MergedDictNode(pos, keyword_args=kwargs)
return arg_tuple, keyword_dict
def p_call(s, function):
# s.sy == '('
| 64 | 64 | 127 | 14 | 49 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_call | p_call | 554 | 564 | 554 | 555 | 77830fc02dd55cb9933fbb34ea919b679ef2b8eb | bigcode/the-stack | train |
125bb7886ebf9502910f69f7 | train | function | def p_with_gil(s):
if s.sy == 'with':
s.next()
s.expect_keyword('gil')
return 1
else:
return 0
| def p_with_gil(s):
| if s.sy == 'with':
s.next()
s.expect_keyword('gil')
return 1
else:
return 0
| )
result.calling_convention = calling_convention
return result
def p_nogil(s):
if s.sy == 'IDENT' and s.systring == 'nogil':
s.next()
return 1
else:
return 0
def p_with_gil(s):
| 64 | 64 | 39 | 7 | 56 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_with_gil | p_with_gil | 2,935 | 2,941 | 2,935 | 2,935 | 48e846f04487cf47befb2406e4d222ecbf0305c7 | bigcode/the-stack | train |
886e6fde1a8e81a0302754aa | train | function | def p_suite(s, ctx=Ctx()):
return p_suite_with_docstring(s, ctx, with_doc_only=False)[1]
| def p_suite(s, ctx=Ctx()):
| return p_suite_with_docstring(s, ctx, with_doc_only=False)[1]
|
stats.append(stat)
first_statement = False
if not stats:
return Nodes.PassStatNode(pos)
elif len(stats) == 1:
return stats[0]
else:
return Nodes.StatListNode(pos, stats = stats)
def p_suite(s, ctx=Ctx()):
| 64 | 64 | 27 | 9 | 55 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_suite | p_suite | 2,344 | 2,345 | 2,344 | 2,344 | f7f9a56f217656b0082e3209b853073660cb57ed | bigcode/the-stack | train |
51b2a1d8ac766d68fa84676c | train | function | def p_async_statement(s, ctx, decorators):
# s.sy >> 'async' ...
if s.sy == 'def':
# 'async def' statements aren't allowed in pxd files
if 'pxd' in ctx.level:
s.error('def statement not allowed here')
s.level = ctx.level
return p_def_statement(s, decorators, is_async_... | def p_async_statement(s, ctx, decorators):
# s.sy >> 'async' ...
| if s.sy == 'def':
# 'async def' statements aren't allowed in pxd files
if 'pxd' in ctx.level:
s.error('def statement not allowed here')
s.level = ctx.level
return p_def_statement(s, decorators, is_async_def=True)
elif decorators:
s.error("Decorators can only b... | arg=arg)
def p_yield_statement(s):
# s.sy == "yield"
yield_expr = p_yield_expression(s)
return Nodes.ExprStatNode(yield_expr.pos, expr=yield_expr)
def p_async_statement(s, ctx, decorators):
# s.sy >> 'async' ...
| 64 | 64 | 166 | 19 | 45 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_async_statement | p_async_statement | 388 | 404 | 388 | 389 | d5bc349698bf42604315058adffc5f38c2a37164 | bigcode/the-stack | train |
2d3aae818eeb4554e47f86a7 | train | function | def p_optional_ellipsis(s):
if s.sy == '.':
expect_ellipsis(s)
return 1
else:
return 0
| def p_optional_ellipsis(s):
| if s.sy == '.':
expect_ellipsis(s)
return 1
else:
return 0
| ctx, in_pyfunc, is_self_arg,
nonempty = nonempty_declarators, kw_only = kw_only,
annotated = annotated))
if s.sy != ',':
break
s.next()
is_self_arg = 0
return args
def p_optional_ellipsis(s):
| 64 | 64 | 33 | 7 | 56 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_optional_ellipsis | p_optional_ellipsis | 2,986 | 2,991 | 2,986 | 2,986 | 356c3d9e2eb84b2799f07c70cd93bfeb5df58c20 | bigcode/the-stack | train |
e2a909ef0f456315730e5a1f | train | function | def p_shift_expr(s):
return p_binop_expr(s, ('<<', '>>'), p_arith_expr)
| def p_shift_expr(s):
| return p_binop_expr(s, ('<<', '>>'), p_arith_expr)
| p_and_expr)
#and_expr: shift_expr ('&' shift_expr)*
def p_and_expr(s):
return p_binop_expr(s, ('&',), p_shift_expr)
#shift_expr: arith_expr (('<<'|'>>') arith_expr)*
def p_shift_expr(s):
| 64 | 64 | 25 | 6 | 57 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_shift_expr | p_shift_expr | 275 | 276 | 275 | 275 | d53f37728461ac0e5b63c48c1e3311baaf862344 | bigcode/the-stack | train |
35c16208022598b4d71e3cab | train | function | def p_py_arg_decl(s, annotated = 1):
pos = s.position()
name = p_ident(s)
annotation = None
if annotated and s.sy == ':':
s.next()
annotation = p_test(s)
return Nodes.PyArgDeclNode(pos, name = name, annotation = annotation)
| def p_py_arg_decl(s, annotated = 1):
| pos = s.position()
name = p_ident(s)
annotation = None
if annotated and s.sy == ':':
s.next()
annotation = p_test(s)
return Nodes.PyArgDeclNode(pos, name = name, annotation = annotation)
| list")
if s.sy == '**':
s.next()
starstar_arg = p_py_arg_decl(s, annotated=annotated)
if s.sy == ',':
s.next()
return (args, star_arg, starstar_arg)
def p_py_arg_decl(s, annotated = 1):
| 64 | 64 | 68 | 12 | 52 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_py_arg_decl | p_py_arg_decl | 3,444 | 3,451 | 3,444 | 3,444 | 019eac0fe3704aaa17a9f22acb16057e78c7b7de | bigcode/the-stack | train |
5c93e0574dff3be909d9b832 | train | function | def p_c_struct_or_union_definition(s, pos, ctx):
packed = False
if s.systring == 'packed':
packed = True
s.next()
if s.sy != 'IDENT' or s.systring != 'struct':
s.expected('struct')
# s.sy == ident 'struct' or 'union'
kind = s.systring
s.next()
name = p_ident(s... | def p_c_struct_or_union_definition(s, pos, ctx):
| packed = False
if s.systring == 'packed':
packed = True
s.next()
if s.sy != 'IDENT' or s.systring != 'struct':
s.expected('struct')
# s.sy == ident 'struct' or 'union'
kind = s.systring
s.next()
name = p_ident(s)
cname = p_opt_cname(s)
if cname is None... | name = p_ident(s)
cname = p_opt_cname(s)
if cname is None and ctx.namespace is not None:
cname = ctx.namespace + "::" + name
value = None
if s.sy == '=':
s.next()
value = p_test(s)
items.append(Nodes.CEnumDefItemNode(pos,
name = name, cname = cname, value = value))
d... | 99 | 99 | 331 | 13 | 86 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_c_struct_or_union_definition | p_c_struct_or_union_definition | 3,175 | 3,213 | 3,175 | 3,175 | af6f7c8606f3c294d10cfc4c4a6e226cf18da599 | bigcode/the-stack | train |
1f25012e7c31f612d8136185 | train | function | def p_with_items(s, is_async=False):
pos = s.position()
if not s.in_python_file and s.sy == 'IDENT' and s.systring in ('nogil', 'gil'):
if is_async:
s.error("with gil/nogil cannot be async")
state = s.systring
s.next()
# support conditional gil/nogil
conditio... | def p_with_items(s, is_async=False):
| pos = s.position()
if not s.in_python_file and s.sy == 'IDENT' and s.systring in ('nogil', 'gil'):
if is_async:
s.error("with gil/nogil cannot be async")
state = s.systring
s.next()
# support conditional gil/nogil
condition = None
if s.sy == '(':
... | return None
else:
return Nodes.PassStatNode(pos)
def p_with_statement(s):
s.next() # 'with'
if s.systring == 'template' and not s.in_python_file:
node = p_with_template(s)
else:
node = p_with_items(s)
return node
def p_with_items(s, is_async=False):
| 78 | 78 | 262 | 10 | 67 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_with_items | p_with_items | 2,048 | 2,080 | 2,048 | 2,048 | 84ecb9046f90f0f8d3e668cc5daf22097fdb45c9 | bigcode/the-stack | train |
aa12b556daaeb9b394308f21 | train | function | def p_with_statement(s):
s.next() # 'with'
if s.systring == 'template' and not s.in_python_file:
node = p_with_template(s)
else:
node = p_with_items(s)
return node
| def p_with_statement(s):
| s.next() # 'with'
if s.systring == 'template' and not s.in_python_file:
node = p_with_template(s)
else:
node = p_with_items(s)
return node
| s2 = PyrexScanner(f, source_desc, s, source_encoding=f.encoding, parse_comments=s.parse_comments)
tree = p_statement_list(s2, ctx)
return tree
else:
return None
else:
return Nodes.PassStatNode(pos)
def p_with_statement(s):
| 64 | 64 | 54 | 6 | 58 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_with_statement | p_with_statement | 2,039 | 2,045 | 2,039 | 2,039 | 0936f2233389b107e0ef1dd3c9f67ac582cee711 | bigcode/the-stack | train |
9e24219373994eae554b5d5b | train | function | def p_raise_statement(s):
# s.sy == 'raise'
pos = s.position()
s.next()
exc_type = None
exc_value = None
exc_tb = None
cause = None
if s.sy not in statement_terminators:
exc_type = p_test(s)
if s.sy == ',':
s.next()
exc_value = p_test(s)
... | def p_raise_statement(s):
# s.sy == 'raise'
| pos = s.position()
s.next()
exc_type = None
exc_value = None
exc_tb = None
cause = None
if s.sy not in statement_terminators:
exc_type = p_test(s)
if s.sy == ',':
s.next()
exc_value = p_test(s)
if s.sy == ',':
s.next()
... | '
pos = s.position()
s.next()
if s.sy not in statement_terminators:
value = p_testlist(s)
else:
value = None
return Nodes.ReturnStatNode(pos, value = value)
def p_raise_statement(s):
# s.sy == 'raise'
| 64 | 64 | 182 | 14 | 50 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_raise_statement | p_raise_statement | 1,631 | 1,657 | 1,631 | 1,632 | 33f5955e2a61127633998c6a4fda5efed83b28b0 | bigcode/the-stack | train |
2a4fad6492ce3f6dbb1803a8 | train | function | def p_yield_statement(s):
# s.sy == "yield"
yield_expr = p_yield_expression(s)
return Nodes.ExprStatNode(yield_expr.pos, expr=yield_expr)
| def p_yield_statement(s):
# s.sy == "yield"
| yield_expr = p_yield_expression(s)
return Nodes.ExprStatNode(yield_expr.pos, expr=yield_expr)
| pos, fatal=False)
arg = None
if is_yield_from:
return ExprNodes.YieldFromExprNode(pos, arg=arg)
else:
return ExprNodes.YieldExprNode(pos, arg=arg)
def p_yield_statement(s):
# s.sy == "yield"
| 64 | 64 | 41 | 15 | 49 | 0101011/cython | Cython/Compiler/Parsing.py | Python | p_yield_statement | p_yield_statement | 382 | 385 | 382 | 383 | cd4d282674d5938d8b8af08a34b57d816e9c375b | bigcode/the-stack | train |
d626b345044f041a164466c2 | train | function | def _cert_dict(items):
return {i.oid: i.value for i in items}
| def _cert_dict(items):
| return {i.oid: i.value for i in items}
| .oid import ExtensionOID, NameOID
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
CERT_KEYS = [
("cn", NameOID.COMMON_NAME),
("on", NameOID.ORGANIZATION_NAME)
]
def _cert_dict(items):
| 64 | 64 | 20 | 6 | 58 | edk0/twisted-opm | opm/cert.py | Python | _cert_dict | _cert_dict | 15 | 16 | 15 | 15 | 308ee3f4983ccbedc1c0a7d4f04e093986bf031f | bigcode/the-stack | train |
9359ae0bdc6e6583f9048642 | train | class | class CertificateProtocol(protocol.Protocol):
def __init__(self, bad):
self.bad = bad
directlyProvides(self, interfaces.IHandshakeListener)
def connectionMade(self):
self.deferred = defer.Deferred(self.cancel)
def cancel(self, defer):
if defer is self.deferred:
s... | class CertificateProtocol(protocol.Protocol):
| def __init__(self, bad):
self.bad = bad
directlyProvides(self, interfaces.IHandshakeListener)
def connectionMade(self):
self.deferred = defer.Deferred(self.cancel)
def cancel(self, defer):
if defer is self.deferred:
self.deferred = None
self.transport... | from zope.interface import directlyProvides
from cryptography import x509
from cryptography.x509.oid import ExtensionOID, NameOID
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
CERT_KEYS = [
("cn", NameOID.COMMON_NAME),
("on", NameOID.OR... | 106 | 106 | 355 | 6 | 100 | edk0/twisted-opm | opm/cert.py | Python | CertificateProtocol | CertificateProtocol | 18 | 66 | 18 | 18 | b27a28ff344d9a05f851d318b4dd5c01e3eb53b0 | bigcode/the-stack | train |
f7a0d4233caa8bc7e63661cd | train | class | class CertificateChecker(object):
def __init__(self, port, bad):
self.port = port
# convert {k:v} to [(regex(k), v)]
self.bad = [(re.compile(k, re.I), v) for k, v in bad.items()]
def check(self, scan, env):
options = ssl.CertificateOptions(verify=False)
creator = protoc... | class CertificateChecker(object):
| def __init__(self, port, bad):
self.port = port
# convert {k:v} to [(regex(k), v)]
self.bad = [(re.compile(k, re.I), v) for k, v in bad.items()]
def check(self, scan, env):
options = ssl.CertificateOptions(verify=False)
creator = protocol.ClientCreator(env.reactor, Cert... | for pattern, description in self.bad:
for k, v in values:
key = f'{k}:{v}'
if pattern.fullmatch(key):
d = self.deferred
self.deferred = None
d.callback(f"{description} ({key})")
break
... | 73 | 73 | 244 | 5 | 68 | edk0/twisted-opm | opm/cert.py | Python | CertificateChecker | CertificateChecker | 68 | 96 | 68 | 68 | 11456e654eb7c5c477599a0c29372d678fc63459 | bigcode/the-stack | train |
166bab7a2982a2f2e608c5c9 | train | function | @notify.command(name="send_emails", short_help="Send out Email notifications.")
def send_emails():
""" Sends an email to users notifying about new activities.
As currently implemented, it will only send notifications from dashboard
activity list if users have `activity_streams_email_notifications` set
... | @notify.command(name="send_emails", short_help="Send out Email notifications.")
def send_emails():
| """ Sends an email to users notifying about new activities.
As currently implemented, it will only send notifications from dashboard
activity list if users have `activity_streams_email_notifications` set
in their profile. It will send emails with updates depending
on the `ckan.email_notifications_s... | .command(name="replay", short_help="Send out modification signals.")
def replay():
dome = DomainObjectModificationExtension()
for package in Session.query(Package):
dome.notify(package, DomainObjectOperation.changed)
@notify.command(name="send_emails", short_help="Send out Email notifications.")
def sen... | 66 | 66 | 220 | 22 | 44 | salsadigitalauorg/ckan | ckan/cli/notify.py | Python | send_emails | send_emails | 25 | 46 | 25 | 26 | 7e0a988414bcf977dcdd9bf4c95f5c3035fa5cb1 | bigcode/the-stack | train |
16e5e83fd948948a80406eca | train | function | @notify.command(name="replay", short_help="Send out modification signals.")
def replay():
dome = DomainObjectModificationExtension()
for package in Session.query(Package):
dome.notify(package, DomainObjectOperation.changed)
| @notify.command(name="replay", short_help="Send out modification signals.")
def replay():
| dome = DomainObjectModificationExtension()
for package in Session.query(Package):
dome.notify(package, DomainObjectOperation.changed)
| kan.logic import NotAuthorized, ValidationError
from ckan.cli import error_shout
log = getLogger(__name__)
@click.group(name="notify", short_help="Send out modification notifications.")
def notify():
pass
@notify.command(name="replay", short_help="Send out modification signals.")
def replay():
| 64 | 64 | 46 | 19 | 44 | salsadigitalauorg/ckan | ckan/cli/notify.py | Python | replay | replay | 18 | 22 | 18 | 19 | f485d9bcaa27927d06b545c0967ebfeed2578c31 | bigcode/the-stack | train |
3545b8cfad0242b95f6eab7c | train | function | @click.group(name="notify", short_help="Send out modification notifications.")
def notify():
pass
| @click.group(name="notify", short_help="Send out modification notifications.")
def notify():
| pass
| Session, Package, DomainObjectOperation
from ckan.model.modification import DomainObjectModificationExtension
from ckan.logic import NotAuthorized, ValidationError
from ckan.cli import error_shout
log = getLogger(__name__)
@click.group(name="notify", short_help="Send out modification notifications.")
def notify():
| 64 | 64 | 20 | 17 | 47 | salsadigitalauorg/ckan | ckan/cli/notify.py | Python | notify | notify | 13 | 15 | 13 | 14 | fc7d584a22feb17e234baefc3b1f6bda1fb42cd1 | bigcode/the-stack | train |
6a819fedc4d56569ef3a7eff | train | function | def get_global_namespace(decls):
"""
Get the global namespace (::) from a declaration tree.
Args:
decls (list[declaration_t]): a list of declarations
Returns:
namespace_t: the global namespace_t object (::)
"""
found = [
decl for decl in scopedef.make_flatten(decls) if... | def get_global_namespace(decls):
| """
Get the global namespace (::) from a declaration tree.
Args:
decls (list[declaration_t]): a list of declarations
Returns:
namespace_t: the global namespace_t object (::)
"""
found = [
decl for decl in scopedef.make_flatten(decls) if decl.name == '::' and
is... | recursive=recursive,
allow_empty=allow_empty)
)
def i_depend_on_them(self, recursive=True):
answer = []
if recursive:
for decl in self.declarations:
answer.extend(decl.i_depend_on_them())
return answer
def get_global_namesp... | 64 | 64 | 115 | 7 | 56 | PlutoniumHeart/ITK | Modules/ThirdParty/pygccxml/src/pygccxml/declarations/namespace.py | Python | get_global_namespace | get_global_namespace | 285 | 301 | 285 | 285 | 136cb5a9e50fad1bc8758703b4f163a4dfbdc9ca | bigcode/the-stack | train |
b9dca70aebd28921fce56546 | train | class | class namespace_t(scopedef.scopedef_t):
"""
Describes C++ namespace.
"""
def __init__(self, name='', declarations=None):
"""
Creates an object that describes a C++ namespace declaration.
"""
scopedef.scopedef_t.__init__(self, name)
if not declarations:
... | class namespace_t(scopedef.scopedef_t):
| """
Describes C++ namespace.
"""
def __init__(self, name='', declarations=None):
"""
Creates an object that describes a C++ namespace declaration.
"""
scopedef.scopedef_t.__init__(self, name)
if not declarations:
declarations = []
# list of... | # Copyright 2014-2016 Insight Software Consortium.
# Copyright 2004-2008 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0.
# See http://www.boost.org/LICENSE_1_0.txt
"""
Describe a C++ namespace declaration.
"""
import warnings
from . import scopedef
from . import declaration_utils
class ... | 89 | 256 | 1,414 | 11 | 77 | PlutoniumHeart/ITK | Modules/ThirdParty/pygccxml/src/pygccxml/declarations/namespace.py | Python | namespace_t | namespace_t | 16 | 282 | 16 | 16 | 1cfb15f17e3057571d83dfe991b1d010a7ba10a6 | bigcode/the-stack | train |
84949b99b3bf472003634ff9 | train | class | class VrfNetworkExplorerSummariesSectionGridRemote(RemoteModel):
"""
| ``id:`` none
| ``attribute type:`` string
| ``VirtualNetworkMemberID:`` none
| ``attribute type:`` string
| ``VirtualNetworkMemberName:`` none
| ``attribute type:`` string
| ``VirtualNetworkMemberDescript... | class VrfNetworkExplorerSummariesSectionGridRemote(RemoteModel):
| """
| ``id:`` none
| ``attribute type:`` string
| ``VirtualNetworkMemberID:`` none
| ``attribute type:`` string
| ``VirtualNetworkMemberName:`` none
| ``attribute type:`` string
| ``VirtualNetworkMemberDescription:`` none
| ``attribute type:`` string
| ``Count:`` ... | from ..remote import RemoteModel
class VrfNetworkExplorerSummariesSectionGridRemote(RemoteModel):
| 21 | 64 | 156 | 14 | 6 | infobloxopen/infoblox_netmri | infoblox_netmri/api/remote/models/vrf_network_explorer_summaries_section_grid_remote.py | Python | VrfNetworkExplorerSummariesSectionGridRemote | VrfNetworkExplorerSummariesSectionGridRemote | 4 | 31 | 4 | 4 | e25b0666f852b90ef882e9797811354c7e56b1db | bigcode/the-stack | train |
08554295687e9efd85350374 | train | function | def init_app(app):
init_api_routes(app)
| def init_app(app):
| init_api_routes(app)
| app.register_blueprint(user_api, url_prefix='/api/users/')
app.register_blueprint(site_api, url_prefix='/api/sites/')
app.register_blueprint(link_api, url_prefix='/api/links/')
app.register_blueprint(tag_api, url_prefix='/api/tags/')
def init_app(app):
| 63 | 64 | 11 | 5 | 58 | xiaojieluo/sourcehub | sourcehub/routes.py | Python | init_app | init_app | 17 | 18 | 17 | 17 | d456084b7dae0fbd1550ab42154fef56f5edb7ed | bigcode/the-stack | train |
6f78d4c53fd04dcb28466ffa | train | function | def init_api_routes(app):
"""api routes
Args:
app ([type]): [description]
"""
from sourcehub.api import index_api, site_api, app_api, user_api, link_api, tag_api
app.register_blueprint(index_api, url_prefix='/api/')
app.register_blueprint(app_api, url_prefix='/api/app/')
app.regist... | def init_api_routes(app):
| """api routes
Args:
app ([type]): [description]
"""
from sourcehub.api import index_api, site_api, app_api, user_api, link_api, tag_api
app.register_blueprint(index_api, url_prefix='/api/')
app.register_blueprint(app_api, url_prefix='/api/app/')
app.register_blueprint(user_api, url... | def init_api_routes(app):
| 6 | 64 | 133 | 6 | 0 | xiaojieluo/sourcehub | sourcehub/routes.py | Python | init_api_routes | init_api_routes | 1 | 14 | 1 | 1 | c566355fdc90af741bd69d13ada49fbfb4704cfd | bigcode/the-stack | train |
8792788ca1385dd35cdf7b1a | train | class | class PytypeSourceUtilsTest(unittest.TestCase):
"""Test pytype source utilities."""
def setUp(self):
super(PytypeSourceUtilsTest, self).setUp()
self.root = os.path.dirname(__file__)
def testPytypeSourceDir(self):
self.assertEqual(self.root, pytype_source_utils.pytype_source_dir())
def testGetFull... | class PytypeSourceUtilsTest(unittest.TestCase):
| """Test pytype source utilities."""
def setUp(self):
super(PytypeSourceUtilsTest, self).setUp()
self.root = os.path.dirname(__file__)
def testPytypeSourceDir(self):
self.assertEqual(self.root, pytype_source_utils.pytype_source_dir())
def testGetFullPath(self):
self.assertEqual(
os.pat... | """Tests for pytype_source_utils.py."""
import os
import sys
from pytype import pytype_source_utils
import unittest
class PytypeSourceUtilsTest(unittest.TestCase):
| 37 | 83 | 279 | 10 | 26 | Arvind2222/pytype | pytype/pytype_source_utils_test.py | Python | PytypeSourceUtilsTest | PytypeSourceUtilsTest | 11 | 41 | 11 | 11 | 63c9edae2ffebc4e0e5db1364a3a390b6168969d | bigcode/the-stack | train |
880dc6d51e5f390e2547b590 | train | function | def add_archs(archs):
global MODEL_ARCH
for x in archs:
assert x not in MODEL_ARCH, "Duplicated model name {} existed".format(x)
MODEL_ARCH[x] = archs[x]
| def add_archs(archs):
| global MODEL_ARCH
for x in archs:
assert x not in MODEL_ARCH, "Duplicated model name {} existed".format(x)
MODEL_ARCH[x] = archs[x]
| from __future__ import absolute_import, division, print_function, unicode_literals
def add_archs(archs):
| 24 | 64 | 49 | 8 | 15 | vivym/maskrcnn-benchmark | maskrcnn_benchmark/modeling/backbone/fbnet_modeldef.py | Python | add_archs | add_archs | 4 | 8 | 4 | 4 | 11612b0f33517acdccbfa2fe6ce099f77f6c6867 | bigcode/the-stack | train |
e65861b6cf69ca05a46b55ea | train | class | class TimezoneTests(unittest.TestCase):
def test_localtime(self):
now = datetime.datetime.utcnow().replace(tzinfo=timezone.utc)
local_tz = timezone.LocalTimezone()
local_now = timezone.localtime(now, local_tz)
self.assertEqual(local_now.tzinfo, local_tz)
def test_localtime_out_... | class TimezoneTests(unittest.TestCase):
| def test_localtime(self):
now = datetime.datetime.utcnow().replace(tzinfo=timezone.utc)
local_tz = timezone.LocalTimezone()
local_now = timezone.localtime(now, local_tz)
self.assertEqual(local_now.tzinfo, local_tz)
def test_localtime_out_of_range(self):
local_tz = timezo... | import copy
import datetime
import pickle
import unittest
from django.test.utils import override_settings
from django.utils import six
from django.utils import timezone
EAT = timezone.get_fixed_timezone(180) # Africa/Nairobi
ICT = timezone.get_fixed_timezone(420) # Asia/Bangkok
class TimezoneTests(unittest... | 72 | 149 | 498 | 8 | 63 | pomarec/django | tests/utils_tests/test_timezone.py | Python | TimezoneTests | TimezoneTests | 15 | 74 | 15 | 16 | 2a175b6ca145e8e19ec102ce8bbd06ade82f92c2 | bigcode/the-stack | train |
a906cebc4ace46ab8b7898f5 | train | class | class SpecialOption(argparse.Action):
"""
Special argparse option. If option is not called, False is stored.
If the option is called without argument, the value in const is provided as default.
If the option is called with an argumeny, this argument is used as the value.
"""
def __init__(
... | class SpecialOption(argparse.Action):
| """
Special argparse option. If option is not called, False is stored.
If the option is called without argument, the value in const is provided as default.
If the option is called with an argumeny, this argument is used as the value.
"""
def __init__(
self,
option_strings,
... | #!/usr/bin/env python
import argparse
import logging
import os
import torch
import schnetpack as spk
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
class SpecialOption(argparse.Action):
| 47 | 64 | 180 | 7 | 40 | lmj1029123/schnetpack | src/scripts/schnetpack_molecular_dynamics.py | Python | SpecialOption | SpecialOption | 12 | 41 | 12 | 12 | ffedd5b5706acb936059454addd8bede7ceccd37 | bigcode/the-stack | train |
a25a43cc3be2b1ac649e293b | train | function | def get_parser():
""" Setup parser for command line arguments """
main_parser = argparse.ArgumentParser()
# General commands
main_parser.add_argument("molecule_path", help="Initial geometry")
main_parser.add_argument("model_path", help="Path of trained model")
main_parser.add_argument("simulati... | def get_parser():
| """ Setup parser for command line arguments """
main_parser = argparse.ArgumentParser()
# General commands
main_parser.add_argument("molecule_path", help="Initial geometry")
main_parser.add_argument("model_path", help="Path of trained model")
main_parser.add_argument("simulation_dir", help="Pat... | """
Special argparse option. If option is not called, False is stored.
If the option is called without argument, the value in const is provided as default.
If the option is called with an argumeny, this argument is used as the value.
"""
def __init__(
self,
option_strings,
... | 177 | 177 | 590 | 4 | 173 | lmj1029123/schnetpack | src/scripts/schnetpack_molecular_dynamics.py | Python | get_parser | get_parser | 44 | 135 | 44 | 44 | 158a93fe2513c033829f3a22005e8a3a33d70168 | bigcode/the-stack | train |
4aa12e787b6e2743ce9ca438 | train | class | class WriterTest(unittest.TestCase):
def test_writer(self):
with SummaryWriter() as writer:
sample_rate = 44100
n_iter = 0
writer.add_scalar('data/scalar_systemtime', 0.1, n_iter)
writer.add_scalar('data/scalar_customtime', 0.2, n_iter, walltime=n_iter)
... | class WriterTest(unittest.TestCase):
| def test_writer(self):
with SummaryWriter() as writer:
sample_rate = 44100
n_iter = 0
writer.add_scalar('data/scalar_systemtime', 0.1, n_iter)
writer.add_scalar('data/scalar_customtime', 0.2, n_iter, walltime=n_iter)
writer.add_scalars('data/scala... | 21, 5, 0]
false_positive_counts = [150, 105, 18, 0, 0]
true_negative_counts = [0, 45, 132, 150, 150]
false_negative_counts = [0, 11, 54, 70, 75]
precision = [0.3333333, 0.3786982, 0.5384616, 1.0, 0.0]
recall = [1.0, 0.8533334, 0.28, 0.0666667, 0.0]
class WriterTest(unittest.TestCase):
| 137 | 137 | 457 | 7 | 130 | snard6/tensorboardX | tests/test_writer.py | Python | WriterTest | WriterTest | 17 | 50 | 17 | 17 | 5b103417d76ce0881f188b10deb82ea234f15e45 | bigcode/the-stack | train |
b97cdd4eaa7822389bc08c84 | train | function | def plot_result(x_test, data_name, test_y_hat, test_y_fit,
test_c, test_coef, metric, criteria):
"""Plots various fidelity performances.
This module plots fidelity or AWD results with respect to
distance from the boundary where the local dynamics change (in percentile).
Args:
x_test: featu... | def plot_result(x_test, data_name, test_y_hat, test_y_fit,
test_c, test_coef, metric, criteria):
| """Plots various fidelity performances.
This module plots fidelity or AWD results with respect to
distance from the boundary where the local dynamics change (in percentile).
Args:
x_test: features in testing set
data_name: Syn1, Syn2 or Syn3
test_y_hat: black-box model predictions
test_y_fit: ... | (test_c) and estimated local dynamics (test_coef).
Args:
test_c: ground truth local dynamics
test_coef: estimated local dynamics by locally interpretable model
Returns:
awd: absolute weight difference (AWD) performance result
"""
# Only for non-zero coefficients
test_c_nonzero = 1*(test_c > 0)... | 177 | 177 | 592 | 28 | 148 | deepneuralmachine/google-research | rllim/rllim_metrics.py | Python | plot_result | plot_result | 123 | 186 | 123 | 124 | 6f48a90e0a5e7d323263d9515ca09162aa0e1e4f | bigcode/the-stack | train |
ba0e68fced66d8e798fa0fa0 | train | function | def fidelity_metrics(test_y_hat, test_y_fit, metric):
"""Computes fidelity metrics.
Fidelity is defined as the differences between black-box model.
predictions (test_y_hat) and locally interpretable model predictions
(test_y_fit).
Different metrics can be used such as mae, mse, rmse, r2 score.
Args:
t... | def fidelity_metrics(test_y_hat, test_y_fit, metric):
| """Computes fidelity metrics.
Fidelity is defined as the differences between black-box model.
predictions (test_y_hat) and locally interpretable model predictions
(test_y_fit).
Different metrics can be used such as mae, mse, rmse, r2 score.
Args:
test_y_hat: black-box model predictions
test_y_fit:... | specific language governing permissions and
# limitations under the License.
"""Various metric functions to evaluate locally interpretable models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
from s... | 75 | 75 | 252 | 13 | 61 | deepneuralmachine/google-research | rllim/rllim_metrics.py | Python | fidelity_metrics | fidelity_metrics | 27 | 57 | 27 | 27 | c8fdff2ee77b40a2b235ea3bd3a40e3ff83e53db | bigcode/the-stack | train |
4db591cab6926a0d88cca6d2 | train | function | def awd_metric(test_c, test_coef):
"""Computes absolute weight difference (AWD) metric.
Absolute weight difference (AWD) is defined as the differences between
ground truth local dynamics (test_c) and estimated local dynamics (test_coef).
Args:
test_c: ground truth local dynamics
test_coef: estimated l... | def awd_metric(test_c, test_coef):
| """Computes absolute weight difference (AWD) metric.
Absolute weight difference (AWD) is defined as the differences between
ground truth local dynamics (test_c) and estimated local dynamics (test_coef).
Args:
test_c: ground truth local dynamics
test_coef: estimated local dynamics by locally interpreta... | _auc_score(test_y, test_y_fit)
# Accuracy
elif metric == 'accuracy':
overall_perf = metrics.accuracy_score(np.argmax(test_y, axis=1),
np.argmax(test_y_fit, axis=1))
return overall_perf
def awd_metric(test_c, test_coef):
| 64 | 64 | 192 | 10 | 53 | deepneuralmachine/google-research | rllim/rllim_metrics.py | Python | awd_metric | awd_metric | 96 | 120 | 96 | 96 | ca77b6a59d9ef8120bb9e47da33b0b2c55dc3a35 | bigcode/the-stack | train |
3aec3a2adf4b86e1ba3d9182 | train | function | def overall_performance_metrics(test_y, test_y_fit, metric):
"""Computes overall performance metrics.
Overall performance is defined as the differences between ground truth labels
(test_y) and locally interpretable model predictions (test_y_fit).
Different metrics can be used such as mae, mse, rmse, auc, accur... | def overall_performance_metrics(test_y, test_y_fit, metric):
| """Computes overall performance metrics.
Overall performance is defined as the differences between ground truth labels
(test_y) and locally interpretable model predictions (test_y_fit).
Different metrics can be used such as mae, mse, rmse, auc, accuracy.
Args:
test_y: ground truth labels
test_y_fit:... | (test_y_hat, test_y_fit)
# Root Mean Squared Error
elif metric == 'rmse':
fidelity = np.sqrt(metrics.mean_squared_error(test_y_hat, test_y_fit))
# R2 Score
elif metric == 'r2':
fidelity = metrics.r2_score(test_y_hat, test_y_fit)
return fidelity
def overall_performance_metrics(test_y, test_y_fit, metr... | 88 | 88 | 294 | 14 | 73 | deepneuralmachine/google-research | rllim/rllim_metrics.py | Python | overall_performance_metrics | overall_performance_metrics | 60 | 93 | 60 | 60 | d6c23efd6c391611fd8257e3180fa098fced656d | bigcode/the-stack | train |
e37ad49a136608c10c8fa64e | train | function | @app.route('/detection_upload', methods=['POST'])
def detection_upload():
try:
# We will save the file to disk for possible data collection.
imagefile = flask.request.files['imagefile']
filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
werkzeug.utils.secure_f... | @app.route('/detection_upload', methods=['POST'])
def detection_upload():
| try:
# We will save the file to disk for possible data collection.
imagefile = flask.request.files['imagefile']
filename_ = str(datetime.datetime.now()).replace(' ', '_') + \
werkzeug.utils.secure_filename(imagefile.filename)
filename = os.path.join(UPLOAD_FOLDER,... | draw_rectangles(image_pil, results[1:-1])
new_img_base64 = embed_image_html(image_pil)
return flask.render_template(
'index.html', has_result=True, result=results, imagesrc=new_img_base64)
@app.route('/detection_upload', methods=['POST'])
def detection_upload():
| 68 | 68 | 228 | 15 | 53 | kristine-li/SSD-Server | test_web.py | Python | detection_upload | detection_upload | 155 | 184 | 155 | 156 | 40c2bb4b28f601dc674cf2094eff976f3445e9f1 | bigcode/the-stack | train |
0d82804813361057fe9473ae | train | function | def disp_wait_msg(imagesrc):
flask.render_template(
'index.html', has_result=True,
result=(False, '处理图片中...'),
imagesrc=imagesrc
)
| def disp_wait_msg(imagesrc):
| flask.render_template(
'index.html', has_result=True,
result=(False, '处理图片中...'),
imagesrc=imagesrc
)
| LOWED_IMAGE_EXTENSIONS
)
@app.route('/', methods=['POST', 'GET'])
def index():
return flask.render_template('index.html', has_result=False)
# fyk
def load_img(img_buffer):
# image = caffe.io.load_image(string_buffer)
pass
def disp_wait_msg(imagesrc):
| 64 | 64 | 41 | 7 | 56 | kristine-li/SSD-Server | test_web.py | Python | disp_wait_msg | disp_wait_msg | 105 | 110 | 105 | 105 | 32c4aa3d1ba56ee9209462e19d7be60e1a7ce81c | bigcode/the-stack | train |
148d3ae4e6502a527e179072 | train | function | @app.route("/predict", methods=["POST"])
def predict():
# Initialize the data dictionary that will be returned from the view.
data = {"success": False}
# Ensure an image was properly uploaded to our endpoint.
if flask.request.method == 'POST':
if flask.request.files.get("image"):
# ... | @app.route("/predict", methods=["POST"])
def predict():
# Initialize the data dictionary that will be returned from the view.
| data = {"success": False}
# Ensure an image was properly uploaded to our endpoint.
if flask.request.method == 'POST':
if flask.request.files.get("image"):
# Read the image in PIL format
start = time.time()
image = flask.request.files["image"].read()
... | embed_image_html(image_pil):
"""Creates an image embedded in HTML base64 format."""
size = (512, 512) # (256, 256)
resized = image_pil.resize(size)
string_buf = BytesIO()
resized.save(string_buf, format='png')
data = string_buf.getvalue()
data = base64.b64encode(data).decode().replace('\n',... | 130 | 130 | 434 | 26 | 104 | kristine-li/SSD-Server | test_web.py | Python | predict | predict | 257 | 313 | 257 | 259 | 64b795e5e86776b3f0a5e0749ff691f65ce4b5a6 | bigcode/the-stack | train |
77f428885493bc404fe9a6fd | train | function | @app.route('/', methods=['POST', 'GET'])
def index():
return flask.render_template('index.html', has_result=False)
| @app.route('/', methods=['POST', 'GET'])
def index():
| return flask.render_template('index.html', has_result=False)
| 'jpe', 'jpeg', 'gif', 'tif', 'tiff'])
def allowed_file(filename):
return (
'.' in filename and
filename.rsplit('.', 1)[1] in ALLOWED_IMAGE_EXTENSIONS
)
@app.route('/', methods=['POST', 'GET'])
def index():
| 64 | 64 | 26 | 13 | 51 | kristine-li/SSD-Server | test_web.py | Python | index | index | 96 | 99 | 96 | 98 | 3f62e2c42ea925b1e013b5bfa2d69b9633c5caff | bigcode/the-stack | train |
bcee45b2c6ebd9cc82a2b8fa | train | function | def load_img(img_buffer):
# image = caffe.io.load_image(string_buffer)
pass
| def load_img(img_buffer):
# image = caffe.io.load_image(string_buffer)
| pass
| .rsplit('.', 1)[1] in ALLOWED_IMAGE_EXTENSIONS
)
@app.route('/', methods=['POST', 'GET'])
def index():
return flask.render_template('index.html', has_result=False)
# fyk
def load_img(img_buffer):
# image = caffe.io.load_image(string_buffer)
| 64 | 64 | 20 | 17 | 46 | kristine-li/SSD-Server | test_web.py | Python | load_img | load_img | 102 | 104 | 102 | 103 | 92786e38ab0484a4123118f216bf82e342f7891f | bigcode/the-stack | train |
90ee76017fb8e8a675a4b316 | train | function | def prediction(filename):
data = [0]
start = time.time()
print("filename:",filename)
threshold = 0.6 #flask.request.files["threshold"].read()
image = np.array(Image.open(filename).convert("RGB"))
height, width = image.shape[:2]
images = transforms(image)[0].unsqueeze(0)
load_time = t... | def prediction(filename):
| data = [0]
start = time.time()
print("filename:",filename)
threshold = 0.6 #flask.request.files["threshold"].read()
image = np.array(Image.open(filename).convert("RGB"))
height, width = image.shape[:2]
images = transforms(image)[0].unsqueeze(0)
load_time = time.time() - start
st... | flask.render_template(
'index.html', has_result=True,
result=(False, 'Cannot open uploaded image.')
)
results = prediction(filename)
draw_rectangles(image_pil, results[1:-1])
new_img_base64 = embed_image_html(image_pil)
return flask.render_template(
'index.ht... | 92 | 93 | 311 | 4 | 88 | kristine-li/SSD-Server | test_web.py | Python | prediction | prediction | 188 | 237 | 188 | 188 | 7d8ed721c5b41cc715360c319e8e92ebcc4cefa5 | bigcode/the-stack | train |
9e4a87a7cfc69eba4d3752f3 | train | function | def transforms(image):
x = cv2.resize(image, (300, 300)).astype(np.float32)
x -= (104.0, 117.0, 123.0)
x = x.astype(np.float32)
x = x[:, :, ::-1].copy()
# plt.imshow(x)
x = torch.from_numpy(x).permute(2, 0, 1)
xx = Variable(x.unsqueeze(0)) # wrap tensor in Variable
return xx
| def transforms(image):
| x = cv2.resize(image, (300, 300)).astype(np.float32)
x -= (104.0, 117.0, 123.0)
x = x.astype(np.float32)
x = x[:, :, ::-1].copy()
# plt.imshow(x)
x = torch.from_numpy(x).permute(2, 0, 1)
xx = Variable(x.unsqueeze(0)) # wrap tensor in Variable
return xx
| .OUTPUT_DIR)
checkpointer.load(ckpt, use_latest=ckpt is None)
weight_file = ckpt if ckpt else checkpointer.get_checkpoint_file()
print('Loaded weights from {}'.format(weight_file))
model.eval()
if use_gpu:
model.cuda()
def transforms(image):
| 64 | 64 | 107 | 4 | 60 | kristine-li/SSD-Server | test_web.py | Python | transforms | transforms | 56 | 65 | 56 | 56 | a9fff02c6a4953eea5d502ec20083dc3fe0485d5 | bigcode/the-stack | train |
ffd7449ecdd42a6d3b1ef654 | train | function | @app.route('/detection_url', methods=['GET'])
def detection_url():
imageurl = flask.request.args.get('imageurl', '')
try:
# download
raw_data = urllib.request.urlopen(imageurl).read()
string_buffer = BytesIO(raw_data)
# image = load_img(string_buffer)
image_pil = Image.op... | @app.route('/detection_url', methods=['GET'])
def detection_url():
| imageurl = flask.request.args.get('imageurl', '')
try:
# download
raw_data = urllib.request.urlopen(imageurl).read()
string_buffer = BytesIO(raw_data)
# image = load_img(string_buffer)
image_pil = Image.open(string_buffer)
filename = os.path.join(UPLOAD_FOLDER, 't... | xmin, ymin,xmax ,ymax = result['location']
draw.rectangle((xmin,ymin,xmax,ymax), width=2, outline='yellow')
draw.text((xmax + 5, ymax + 5), result['predicted_class']+ str(idx), 'yellow')
del draw
@app.route('/detection_url', methods=['GET'])
def detection_url():
| 81 | 81 | 270 | 15 | 65 | kristine-li/SSD-Server | test_web.py | Python | detection_url | detection_url | 121 | 151 | 121 | 122 | b2bd31c625b1f5b61fae127951b71405b83ff469 | bigcode/the-stack | train |
fd368f733183626bc15f2def | train | function | def draw_rectangles(image_pil,det_result):
# draw rectangles
draw = ImageDraw.Draw(image_pil)
for idx, result in enumerate(det_result):
xmin, ymin,xmax ,ymax = result['location']
draw.rectangle((xmin,ymin,xmax,ymax), width=2, outline='yellow')
draw.text((xmax + 5, ymax + 5), result[... | def draw_rectangles(image_pil,det_result):
# draw rectangles
| draw = ImageDraw.Draw(image_pil)
for idx, result in enumerate(det_result):
xmin, ymin,xmax ,ymax = result['location']
draw.rectangle((xmin,ymin,xmax,ymax), width=2, outline='yellow')
draw.text((xmax + 5, ymax + 5), result['predicted_class']+ str(idx), 'yellow')
del draw
| _image(string_buffer)
pass
def disp_wait_msg(imagesrc):
flask.render_template(
'index.html', has_result=True,
result=(False, '处理图片中...'),
imagesrc=imagesrc
)
def draw_rectangles(image_pil,det_result):
# draw rectangles
| 64 | 64 | 103 | 16 | 48 | kristine-li/SSD-Server | test_web.py | Python | draw_rectangles | draw_rectangles | 112 | 119 | 112 | 113 | 963a41350fffd02d21dea113dc6e3b3a9571e3ed | bigcode/the-stack | train |
008a789f213307763d2f00c9 | train | function | def embed_image_html(image_pil):
"""Creates an image embedded in HTML base64 format."""
size = (512, 512) # (256, 256)
resized = image_pil.resize(size)
string_buf = BytesIO()
resized.save(string_buf, format='png')
data = string_buf.getvalue()
data = base64.b64encode(data).decode().replace('\... | def embed_image_html(image_pil):
| """Creates an image embedded in HTML base64 format."""
size = (512, 512) # (256, 256)
resized = image_pil.resize(size)
string_buf = BytesIO()
resized.save(string_buf, format='png')
data = string_buf.getvalue()
data = base64.b64encode(data).decode().replace('\n', '')
return 'data:image/p... | round(load_time * 1000,3),
'inference': round(inference_time * 1000,3),
'FPS': round(1.0 / inference_time,3)
}
data.append(T)
print(data)
return data
def embed_image_html(image_pil):
| 64 | 64 | 100 | 8 | 55 | kristine-li/SSD-Server | test_web.py | Python | embed_image_html | embed_image_html | 239 | 248 | 239 | 239 | 97287ef132574769acaedf79b352d139e7ea80b6 | bigcode/the-stack | train |
b27b53c03fa801f692cebf66 | train | function | def default(obj):
if isinstance(obj, (numpy.int_, numpy.intc, numpy.intp, numpy.int8,
numpy.int16, numpy.int32, numpy.int64, numpy.uint8,
numpy.uint16,numpy.uint32, numpy.uint64)):
return int(obj)
elif isinstance(obj, (numpy.float_, numpy.float16, numpy.float32,
numpy.float64)):
... | def default(obj):
| if isinstance(obj, (numpy.int_, numpy.intc, numpy.intp, numpy.int8,
numpy.int16, numpy.int32, numpy.int64, numpy.uint8,
numpy.uint16,numpy.uint32, numpy.uint64)):
return int(obj)
elif isinstance(obj, (numpy.float_, numpy.float16, numpy.float32,
numpy.float64)):
return flo... | .float32)
x = x[:, :, ::-1].copy()
# plt.imshow(x)
x = torch.from_numpy(x).permute(2, 0, 1)
xx = Variable(x.unsqueeze(0)) # wrap tensor in Variable
return xx
def default(obj):
| 64 | 64 | 120 | 4 | 59 | kristine-li/SSD-Server | test_web.py | Python | default | default | 69 | 79 | 69 | 69 | a3842b19600ae5ffa510fefee5987d1266217213 | bigcode/the-stack | train |
3b644c521a69304f114c719c | train | function | def load_model():
"""Load the pre-trained model, you can use your model just as easily.
"""
global model
ckpt = 'model/vgg_ssd300_voc0712.pth'
model = build_detection_model(cfg)
checkpointer = CheckPointer(model, save_dir=cfg.OUTPUT_DIR)
checkpointer.load(ckpt, use_latest=ckpt is None)
... | def load_model():
| """Load the pre-trained model, you can use your model just as easily.
"""
global model
ckpt = 'model/vgg_ssd300_voc0712.pth'
model = build_detection_model(cfg)
checkpointer = CheckPointer(model, save_dir=cfg.OUTPUT_DIR)
checkpointer.load(ckpt, use_latest=ckpt is None)
weight_file = ckpt... | from vizer.draw import draw_boxes
# Initialize our Flask application and the PyTorch model.
app = flask.Flask(__name__)
model = None
use_gpu = False
from ssd.data.datasets import COCODataset, VOCDataset
class_names = VOCDataset.class_names
def load_model():
| 64 | 64 | 125 | 4 | 59 | kristine-li/SSD-Server | test_web.py | Python | load_model | load_model | 39 | 53 | 39 | 39 | 814620f0127e2b386e78928b166981bd91512120 | bigcode/the-stack | train |
08ad39d1ba4b3dbddc4f9c2c | train | function | def allowed_file(filename):
return (
'.' in filename and
filename.rsplit('.', 1)[1] in ALLOWED_IMAGE_EXTENSIONS
)
| def allowed_file(filename):
| return (
'.' in filename and
filename.rsplit('.', 1)[1] in ALLOWED_IMAGE_EXTENSIONS
)
| _DIRNAME = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + '/../..')
UPLOAD_FOLDER = 'demo/'
ALLOWED_IMAGE_EXTENSIONS = set(['png', 'bmp', 'jpg', 'jpe', 'jpeg', 'gif', 'tif', 'tiff'])
def allowed_file(filename):
| 64 | 64 | 33 | 5 | 59 | kristine-li/SSD-Server | test_web.py | Python | allowed_file | allowed_file | 89 | 93 | 89 | 89 | cfafef419667674da480fdba28126779d37e3d02 | bigcode/the-stack | train |
a2db520d87fcc466053bb9d7 | train | function | def get_outside_encoded_index(length, offset_cache=None, cuda=False):
if offset_cache is None:
offset_cache = get_offset_cache(length)
index = OutsideIndex()
outside_leaf = {}
node2leaf = index.get_leaf(length)
device = torch.cuda.current_device() if cuda else None
for (lvl, pos), lea... | def get_outside_encoded_index(length, offset_cache=None, cuda=False):
| if offset_cache is None:
offset_cache = get_offset_cache(length)
index = OutsideIndex()
outside_leaf = {}
node2leaf = index.get_leaf(length)
device = torch.cuda.current_device() if cuda else None
for (lvl, pos), leaf in node2leaf.items():
offset = offset_cache[lvl]
idx... | in p_info], dtype=torch.long, device=device)
s_index = torch.tensor([get_val(x) for x in s_info], dtype=torch.long, device=device)
return p_index, p_info, s_index, s_info
def get_outside_encoded_index(length, offset_cache=None, cuda=False):
| 64 | 64 | 122 | 15 | 48 | iesl/s-diora | outside_index.py | Python | get_outside_encoded_index | get_outside_encoded_index | 210 | 226 | 210 | 210 | 2ab788de8afbdd94d91e0b973aec32f52136cb9c | bigcode/the-stack | train |
b5a21b5aa9a8ed6568d09989 | train | function | def get_outside_index(length, level, offset_cache=None, cuda=False):
if offset_cache is None:
offset_cache = get_offset_cache(length)
index = OutsideIndex()
pairs = index.get_all_pairs(level, length)
par_lvl, par_pos = [], []
sis_lvl, sis_pos = [], []
for pair in pairs:
par, si... | def get_outside_index(length, level, offset_cache=None, cuda=False):
| if offset_cache is None:
offset_cache = get_offset_cache(length)
index = OutsideIndex()
pairs = index.get_all_pairs(level, length)
par_lvl, par_pos = [], []
sis_lvl, sis_pos = [], []
for pair in pairs:
par, sis = pair
par_lvl.append(par[0])
par_pos.append(par[1]... | par[0]
par_span = (par_lvl, par_pos)
sis_lvl = sis[0]
sis_pos = sis[1] - sis[0]
sis_span = (sis_lvl, sis_pos)
output.append((par_span, sis_span))
return output
def get_outside_index(length, level, offset_cache=None, cuda=False):
| 77 | 77 | 259 | 16 | 60 | iesl/s-diora | outside_index.py | Python | get_outside_index | get_outside_index | 133 | 167 | 133 | 133 | 35bb580964e6f2bdd06d6c5b61361303ad29f478 | bigcode/the-stack | train |
1b955e354b9e076e5f3dddbf | train | class | class OutsideIndex(object):
def get_pairs(self, level, i, n):
"""
Returns all (parent, sibling) coordinate pairs that
are used to construct a node at coordinates
(level, i) where there n leaf nodes.
"""
pairs = []
for level_ in range(level + 1, i + 1):
... | class OutsideIndex(object):
| def get_pairs(self, level, i, n):
"""
Returns all (parent, sibling) coordinate pairs that
are used to construct a node at coordinates
(level, i) where there n leaf nodes.
"""
pairs = []
for level_ in range(level + 1, i + 1):
p_level = level_
... | import torch
from offset_cache import get_offset_cache
class OutsideIndex(object):
| 16 | 153 | 511 | 5 | 10 | iesl/s-diora | outside_index.py | Python | OutsideIndex | OutsideIndex | 6 | 77 | 6 | 6 | bfd02df44764d96e0bc1c37286d067cefa0ff704 | bigcode/the-stack | train |
7d39ca75c58d6c16a25f22dd | train | function | def get_topk_outside_index(length, level, K, offset_cache=None, cuda=False):
if offset_cache is None:
offset_cache = get_offset_cache(length)
L = length - level
N = length - level - 1
components = get_outside_components(length, level, offset_cache)
p_info, s_info = [], []
for i, (p_sp... | def get_topk_outside_index(length, level, K, offset_cache=None, cuda=False):
| if offset_cache is None:
offset_cache = get_offset_cache(length)
L = length - level
N = length - level - 1
components = get_outside_components(length, level, offset_cache)
p_info, s_info = [], []
for i, (p_span, s_span) in enumerate(components):
p_level, p_pos = p_span
... |
index.append(idx)
par_index = torch.tensor(index, dtype=torch.long, device=device)
# Sibling
index = []
for lvl, pos in zip(sis_lvl, sis_pos):
offset = offset_cache[lvl]
idx = offset + pos
index.append(idx)
sis_index = torch.tensor(index, dtype=torch.long, device=de... | 107 | 107 | 357 | 20 | 86 | iesl/s-diora | outside_index.py | Python | get_topk_outside_index | get_topk_outside_index | 170 | 207 | 170 | 170 | 6ed355b5eb10316a38353a03748b2f5a4ecfd5ec | bigcode/the-stack | train |
8555ac51793a0c08fe311679 | train | function | def get_outside_target(length, level, offset_cache=None, cuda=False):
if offset_cache is None:
offset_cache = get_offset_cache(length)
L = length - level
offset = offset_cache[level]
target = []
for i in range(L-1):
target.extend(range(offset, offset + L))
device = torch.cuda.... | def get_outside_target(length, level, offset_cache=None, cuda=False):
| if offset_cache is None:
offset_cache = get_offset_cache(length)
L = length - level
offset = offset_cache[level]
target = []
for i in range(L-1):
target.extend(range(offset, offset + L))
device = torch.cuda.current_device() if cuda else None
target = torch.tensor(target, d... | node2leaf.items():
offset = offset_cache[lvl]
idx = offset + pos
leaf = torch.tensor(leaf, dtype=torch.long, device=device)
outside_leaf[idx] = leaf
return outside_leaf
def get_outside_target(length, level, offset_cache=None, cuda=False):
| 64 | 64 | 100 | 16 | 47 | iesl/s-diora | outside_index.py | Python | get_outside_target | get_outside_target | 229 | 242 | 229 | 229 | 186842def3b86d01e4700c7bd18a86e78e0c6e27 | bigcode/the-stack | train |
7db76ae1e29f8ab022dace66 | train | class | class OutsideIndexCheck(object):
def __init__(self, index, length, spans, siblings):
sib_map = {}
for x, y, n in siblings:
sib_map[x] = (y, n)
sib_map[y] = (x, n)
check = {}
for sibling, (target, name) in sib_map.items():
xpos = target[0]
... | class OutsideIndexCheck(object):
| def __init__(self, index, length, spans, siblings):
sib_map = {}
for x, y, n in siblings:
sib_map[x] = (y, n)
sib_map[y] = (x, n)
check = {}
for sibling, (target, name) in sib_map.items():
xpos = target[0]
xsize = target[1] - target[0]... | = n - level
for pos in range(L):
node2leaf[(level, pos)] = []
for i in range(L-1):
offset = level + 1
leaf = (pos + offset + i) % n
node2leaf[(level, pos)].append(leaf)
return node2leaf
class OutsideIndexC... | 79 | 79 | 264 | 6 | 72 | iesl/s-diora | outside_index.py | Python | OutsideIndexCheck | OutsideIndexCheck | 80 | 109 | 80 | 80 | cd5187449f48df6d9dc8aa281aaee60c8757251c | bigcode/the-stack | train |
44e4ff4a9cc02f7e261b3185 | train | function | def get_outside_components(length, level, offset_cache=None):
if offset_cache is None:
offset_cache = get_offset_cache(length)
index = OutsideIndex()
pairs = index.get_all_pairs(level, length)
output = []
for pair in pairs:
par, sis = pair
par_lvl = par[0]
par_pos = ... | def get_outside_components(length, level, offset_cache=None):
| if offset_cache is None:
offset_cache = get_offset_cache(length)
index = OutsideIndex()
pairs = index.get_all_pairs(level, length)
output = []
for pair in pairs:
par, sis = pair
par_lvl = par[0]
par_pos = par[1] - par[0]
par_span = (par_lvl, par_pos)
... | idx = poffset + ppos
check[(pidx, xidx)] = True
self.check = check
def is_valid(self, pidx, xidx):
return (pidx, xidx) in self.check
def get_outside_components(length, level, offset_cache=None):
| 64 | 64 | 141 | 13 | 50 | iesl/s-diora | outside_index.py | Python | get_outside_components | get_outside_components | 112 | 130 | 112 | 112 | 4fcbe75bcac4a649c99a9b37175d13cb75efb327 | bigcode/the-stack | train |
d7100905c43c4b014b97ff85 | train | class | class CompetitionTeamsTests(TestCase):
def setUp(self):
self.creator = User.objects.create(email='test@user.com', username='testuser')
self.creator.set_password('test')
self.creator.save()
self.competition = Competition.objects.create(creator=self.creator, modified_by=self.creator)
... | class CompetitionTeamsTests(TestCase):
| def setUp(self):
self.creator = User.objects.create(email='test@user.com', username='testuser')
self.creator.set_password('test')
self.creator.save()
self.competition = Competition.objects.create(creator=self.creator, modified_by=self.creator)
# Not sure why this status doe... |
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from apps.web.models import Competition, CompetitionParticipant, ParticipantStatus
from apps.teams.models import Team, TeamStatus, ... | 82 | 99 | 331 | 7 | 75 | abdulari/codalab-competitions | k8s/images/codalab/apps/teams/tests/test_team_creation.py | Python | CompetitionTeamsTests | CompetitionTeamsTests | 13 | 54 | 13 | 13 | 5693f945c62712093dcab870b85834bd50ab6783 | bigcode/the-stack | train |
61a6209fc38fb68d6f7b15dc | train | function | def run(): #run this to make model
data = pd.read_csv("data.csv") #Read CSV data
dataset = np.array(data) #Taking in array
np.random.shuffle(dataset) #Shuffling the data as to get enough data for training and testing an the first coloumn represents class
X = dataset
Y = dataset
X = X... | def run(): #run this to make model
| data = pd.read_csv("data.csv") #Read CSV data
dataset = np.array(data) #Taking in array
np.random.shuffle(dataset) #Shuffling the data as to get enough data for training and testing an the first coloumn represents class
X = dataset
Y = dataset
X = X[:, 1:2501] # As we have a 50*50 imag... | 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same'))
model.add(Conv2D(64, (5, 5), activation='sigmoid'))
model.add(MaxPooling2D(pool_size=(5, 5), strides=(5, 5), padding='same'))
model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add... | 202 | 202 | 676 | 11 | 190 | AkhilDixit1998/Hand | modelCreate.py | Python | run | run | 30 | 86 | 30 | 30 | 24cac5c1fa08cfd8cdbacb05cfed089787795986 | bigcode/the-stack | train |
5be3abb8dfc40aa045927802 | train | function | def keras_model(im_x, im_y):
number_of_classes_available = 15 #Here input the number of classes that you want it is from 0 to class-1
model = Sequential()
model.add(Conv2D(32, (5, 5), input_shape=(im_x, im_y, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='sa... | def keras_model(im_x, im_y):
| number_of_classes_available = 15 #Here input the number of classes that you want it is from 0 to class-1
model = Sequential()
model.add(Conv2D(32, (5, 5), input_shape=(im_x, im_y, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same'))
model.add(Conv2D(64... | import numpy as np
import matplotlib.pyplot as plt
from keras.layers import Dense, Flatten, Conv2D
from keras.layers import MaxPooling2D, Dropout
from keras.utils import np_utils
from keras.models import Sequential
from keras.callbacks import ModelCheckpoint
import pandas as pd
def keras_model(im_x, im_y):
| 71 | 78 | 260 | 9 | 61 | AkhilDixit1998/Hand | modelCreate.py | Python | keras_model | keras_model | 11 | 28 | 11 | 11 | 70376c7c6fcd3cea533ddcead2b3759736624576 | bigcode/the-stack | train |
ae211e914493ac71c4fd6ed9 | train | class | class GipGame:
""" This Class is in charge of the logic of the GitGame"""
def __init__(self):
self.currentlyPlaying = False
self.turnScore = 0
def isWinner(self, player):
""" This Method returns a boolean value based on whether or not a player has reached 100 points"""
if p... | class GipGame:
| """ This Class is in charge of the logic of the GitGame"""
def __init__(self):
self.currentlyPlaying = False
self.turnScore = 0
def isWinner(self, player):
""" This Method returns a boolean value based on whether or not a player has reached 100 points"""
if player.score >= ... | # Represents Player Name
self.turn = turn # Represents whether or not it is a player's turn
self.score = 0 # Represents a player's overall score
def updateScore(self, score):
""" This method updates a player's score"""
self.score += score
class GipGame:
| 64 | 64 | 90 | 4 | 59 | james20023355/GipGame | game/gip.py | Python | GipGame | GipGame | 722 | 734 | 722 | 722 | c45d79a7127852eec6dffa35830ecef3c7a875c6 | bigcode/the-stack | train |
f015838ab856223c59af7354 | train | class | class Ui_GameWindow(object):
""" This is the official Game Window"""
def __init__(self):
super().__init__()
self.currentlyPlaying = False
self.turnScore = 0
self.introCount = 0 # I know this is a bad way to do it but i dont want to learn PyQT Threading sorry
def setupUi(sel... | class Ui_GameWindow(object):
| """ This is the official Game Window"""
def __init__(self):
super().__init__()
self.currentlyPlaying = False
self.turnScore = 0
self.introCount = 0 # I know this is a bad way to do it but i dont want to learn PyQT Threading sorry
def setupUi(self, GameWindow):
GameW... | self.p1Entry.text() and self.p2Entry.text() != None:
self.window = QtWidgets.QMainWindow()
self.ui = Ui_GameWindow()
self.ui.setupUi(self.window)
self.setGameWindowText()
self.p1Entry.clear()
self.p2Entry.clear()
self.window.show()
... | 256 | 256 | 5,613 | 6 | 250 | james20023355/GipGame | game/gip.py | Python | Ui_GameWindow | Ui_GameWindow | 210 | 696 | 210 | 210 | 1ba533391929a7d9a0023598e7e2c7db490a91bd | bigcode/the-stack | train |
889c53187c372e32af6f0598 | train | class | class Ui_StartWindow(object):
""" This is the Start Window of the Application"""
def setupUi(self, StartWindow):
StartWindow.setObjectName("StartWindow")
StartWindow.resize(597, 396)
self.centralwidget = QtWidgets.QWidget(StartWindow)
self.centralwidget.setObjectName("centralwidg... | class Ui_StartWindow(object):
| """ This is the Start Window of the Application"""
def setupUi(self, StartWindow):
StartWindow.setObjectName("StartWindow")
StartWindow.resize(597, 396)
self.centralwidget = QtWidgets.QWidget(StartWindow)
self.centralwidget.setObjectName("centralwidget")
self.titleLbl = Q... | """
This File Contains the code for the Git Game
Author: James Penales
"""
import time
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, QtTest
from PyQt5.QtWidgets import QMessageBox
class Ui_StartWindow(object):
| 57 | 256 | 1,451 | 6 | 50 | james20023355/GipGame | game/gip.py | Python | Ui_StartWindow | Ui_StartWindow | 12 | 120 | 12 | 12 | 3da424d4a384f3e03c96e40cdc0e185ad340babe | bigcode/the-stack | train |
dd0c90b6646f0fab7d00d134 | train | class | class Player:
""" This class is to represent a real world player"""
def __init__(self, name, turn):
self.name = name # Represents Player Name
self.turn = turn # Represents whether or not it is a player's turn
self.score = 0 # Represents a player's overall score
def updateScore(se... | class Player:
| """ This class is to represent a real world player"""
def __init__(self, name, turn):
self.name = name # Represents Player Name
self.turn = turn # Represents whether or not it is a player's turn
self.score = 0 # Represents a player's overall score
def updateScore(self, score):
... | ("GipGame")
mbox.setIcon(QMessageBox.Question)
mbox.setText(f"{p2.name} wins! with {p2.score}pts.")
mbox.setStandardButtons(QMessageBox.Ok)
mbox.exec_()
self.centralwidget.close()
class Player:
| 62 | 64 | 91 | 3 | 59 | james20023355/GipGame | game/gip.py | Python | Player | Player | 709 | 718 | 709 | 709 | f381b3157924e241aa236b54fd0a01e3a79fdc2d | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.