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
d08039533a1ca76879c81ff3
train
function
def detect_d_compiler(env: 'Environment', for_machine: MachineChoice) -> Compiler: info = env.machines[for_machine] # Detect the target architecture, required for proper architecture handling on Windows. # MSVC compiler is required for correct platform detection. c_compiler = {'c': detect_c_compiler(en...
def detect_d_compiler(env: 'Environment', for_machine: MachineChoice) -> Compiler:
info = env.machines[for_machine] # Detect the target architecture, required for proper architecture handling on Windows. # MSVC compiler is required for correct platform detection. c_compiler = {'c': detect_c_compiler(env, for_machine)} is_msvc = isinstance(c_compiler['c'], VisualStudioCCompiler) ...
else: # On linux and macos rust will invoke the c compiler for # linking, on windows it will use lld-link or link.exe. # we will simply ask for the C compiler that corresponds to # it, and use that. cc = _detect_c_or_cpp_compile...
255
256
1,084
19
237
johan-boule/meson
mesonbuild/compilers/detect.py
Python
detect_d_compiler
detect_d_compiler
1,031
1,135
1,031
1,031
0c53f473e60872bf00ca75eda87d8645365df405
bigcode/the-stack
train
b6325c3fa4c31f6ec4683baf
train
function
def _detect_c_or_cpp_compiler(env: 'Environment', lang: str, for_machine: MachineChoice, *, override_compiler: T.Optional[T.List[str]] = None) -> Compiler: """Shared implementation for finding the C or C++ compiler to use. the override_compiler option is provided to allow compilers which use the compiler (...
def _detect_c_or_cpp_compiler(env: 'Environment', lang: str, for_machine: MachineChoice, *, override_compiler: T.Optional[T.List[str]] = None) -> Compiler:
"""Shared implementation for finding the C or C++ compiler to use. the override_compiler option is provided to allow compilers which use the compiler (GCC or Clang usually) as their shared linker, to find the linker they need. """ popen_exceptions: T.Dict[str, T.Union[Exception, str]] = {} ...
.startswith('GNU ar') and ('xc16-ar' in linker or 'xc16-ar.exe' in linker): return Xc16Linker(linker) if out.startswith('TMS320C2000') and ('ar2000' in linker or 'ar2000.exe' in linker): return C2000Linker(linker) if out.startswith('The CompCert'): return CompCertLink...
256
256
3,107
40
215
johan-boule/meson
mesonbuild/compilers/detect.py
Python
_detect_c_or_cpp_compiler
_detect_c_or_cpp_compiler
351
626
351
351
26740dc99faaf758fd9b3d1a5de1f5239fda8765
bigcode/the-stack
train
420216f4405445ee443cf774
train
function
def detect_static_linker(env: 'Environment', compiler: Compiler) -> StaticLinker: linker = env.lookup_binary_entry(compiler.for_machine, 'ar') if linker is not None: linkers = [linker] else: default_linkers = [[l] for l in defaults['static_linker']] if isinstance(compiler, CudaCompil...
def detect_static_linker(env: 'Environment', compiler: Compiler) -> StaticLinker:
linker = env.lookup_binary_entry(compiler.for_machine, 'ar') if linker is not None: linkers = [linker] else: default_linkers = [[l] for l in defaults['static_linker']] if isinstance(compiler, CudaCompiler): linkers = [defaults['cuda_static_linker']] + default_linkers ...
' compilers = [comp] else: if not env.machines.matches_build_machine(for_machine): raise EnvironmentException(f'{lang!r} compiler binary not defined in cross or native file') compilers = [[x] for x in defaults[lang]] ccache = BinaryTable.detect_ccache() if env.machin...
255
256
996
19
236
johan-boule/meson
mesonbuild/compilers/detect.py
Python
detect_static_linker
detect_static_linker
268
343
268
268
4ee8145f0ac81c8a10157b903312b9e793fe7eaa
bigcode/the-stack
train
23ecc27c1b74c8e94d4c52f1
train
function
def detect_objcpp_compiler(env: 'Environment', for_machine: MachineChoice) -> 'Compiler': return _detect_objc_or_objcpp_compiler(env, for_machine, False)
def detect_objcpp_compiler(env: 'Environment', for_machine: MachineChoice) -> 'Compiler':
return _detect_objc_or_objcpp_compiler(env, for_machine, False)
py happy)') def detect_objc_compiler(env: 'Environment', for_machine: MachineChoice) -> 'Compiler': return _detect_objc_or_objcpp_compiler(env, for_machine, True) def detect_objcpp_compiler(env: 'Environment', for_machine: MachineChoice) -> 'Compiler':
64
64
39
21
43
johan-boule/meson
mesonbuild/compilers/detect.py
Python
detect_objcpp_compiler
detect_objcpp_compiler
795
796
795
795
be7aac5e2fc208a888c2edbd5c5a9af5fca05369
bigcode/the-stack
train
783cb2763588fbb9ac77e82e
train
function
def detect_objc_compiler(env: 'Environment', for_machine: MachineChoice) -> 'Compiler': return _detect_objc_or_objcpp_compiler(env, for_machine, True)
def detect_objc_compiler(env: 'Environment', for_machine: MachineChoice) -> 'Compiler':
return _detect_objc_or_objcpp_compiler(env, for_machine, True)
_wrap, full_version=full_version, linker=linker) _handle_exceptions(popen_exceptions, compilers) raise EnvironmentException('Unreachable code (exception to make mypy happy)') def detect_objc_compiler(env: 'Environment', for_machine: MachineChoice) -> 'Compiler':
63
64
39
21
43
johan-boule/meson
mesonbuild/compilers/detect.py
Python
detect_objc_compiler
detect_objc_compiler
792
793
792
792
61fbd9b212d467460131435fc2ad88a84808532a
bigcode/the-stack
train
80fa0d141f080c540439d7cf
train
function
def _get_gnu_compiler_defines(compiler: T.List[str]) -> T.Dict[str, str]: """ Detect GNU compiler platform type (Apple, MinGW, Unix) """ # Arguments to output compiler pre-processor defines to stdout # gcc, g++, and gfortran all support these arguments args = compiler + ['-E', '-dM', '-'] p,...
def _get_gnu_compiler_defines(compiler: T.List[str]) -> T.Dict[str, str]:
""" Detect GNU compiler platform type (Apple, MinGW, Unix) """ # Arguments to output compiler pre-processor defines to stdout # gcc, g++, and gfortran all support these arguments args = compiler + ['-E', '-dM', '-'] p, output, error = Popen_safe(args, write='', stdin=subprocess.PIPE) if ...
SwiftCompiler( exelist, version, for_machine, is_cross, info, linker=linker) raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"') # GNU/Clang defines and version # ============================= def _get_gnu_compiler_defines(compiler: T.List[str]) -> T.Dict[str, str]:
75
76
255
23
52
johan-boule/meson
mesonbuild/compilers/detect.py
Python
_get_gnu_compiler_defines
_get_gnu_compiler_defines
1,165
1,189
1,165
1,165
30913b77c26bb14f15a6e08cdd5e5a05e69a920c
bigcode/the-stack
train
897ceeb13cae814177b211cb
train
function
def detect_swift_compiler(env: 'Environment', for_machine: MachineChoice) -> Compiler: exelist = env.lookup_binary_entry(for_machine, 'swift') is_cross = env.is_cross_build(for_machine) info = env.machines[for_machine] if exelist is None: # TODO support fallback exelist = [defaults['swif...
def detect_swift_compiler(env: 'Environment', for_machine: MachineChoice) -> Compiler:
exelist = env.lookup_binary_entry(for_machine, 'swift') is_cross = env.is_cross_build(for_machine) info = env.machines[for_machine] if exelist is None: # TODO support fallback exelist = [defaults['swift'][0]] try: p, _, err = Popen_safe(exelist + ['-v']) except OSError: ...
=linker) raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"') _handle_exceptions(popen_exceptions, compilers) raise EnvironmentException('Unreachable code (exception to make mypy happy)') def detect_swift_compiler(env: 'Environment', for_machine: MachineChoice) -> Compiler:
71
72
243
20
52
johan-boule/meson
mesonbuild/compilers/detect.py
Python
detect_swift_compiler
detect_swift_compiler
1,137
1,159
1,137
1,137
1173989306dcdb8fca6bcc39e18c0ac68a862a4a
bigcode/the-stack
train
e59e4fca583e53c8f248f13d
train
function
def detect_compiler_for(env: 'Environment', lang: str, for_machine: MachineChoice)-> T.Optional[Compiler]: comp = compiler_from_language(env, lang, for_machine) if comp is not None: assert comp.for_machine == for_machine env.coredata.process_new_compiler(lang, comp, env) return comp
def detect_compiler_for(env: 'Environment', lang: str, for_machine: MachineChoice)-> T.Optional[Compiler]:
comp = compiler_from_language(env, lang, for_machine) if comp is not None: assert comp.for_machine == for_machine env.coredata.process_new_compiler(lang, comp, env) return comp
detect_swift_compiler, 'cython': detect_cython_compiler, } return lang_map[lang](env, for_machine) if lang in lang_map else None def detect_compiler_for(env: 'Environment', lang: str, for_machine: MachineChoice)-> T.Optional[Compiler]:
64
64
72
25
38
johan-boule/meson
mesonbuild/compilers/detect.py
Python
detect_compiler_for
detect_compiler_for
218
223
218
218
65831d2f88eeaf7668997c6e7a350bfbe672124c
bigcode/the-stack
train
6025963a7cddf52236126706
train
function
def _get_gnu_version_from_defines(defines: T.Dict[str, str]) -> str: dot = '.' major = defines.get('__GNUC__', '0') minor = defines.get('__GNUC_MINOR__', '0') patch = defines.get('__GNUC_PATCHLEVEL__', '0') return dot.join((major, minor, patch))
def _get_gnu_version_from_defines(defines: T.Dict[str, str]) -> str:
dot = '.' major = defines.get('__GNUC__', '0') minor = defines.get('__GNUC_MINOR__', '0') patch = defines.get('__GNUC_PATCHLEVEL__', '0') return dot.join((major, minor, patch))
if len(rest) == 1: defines[rest[0]] = '' if len(rest) == 2: defines[rest[0]] = rest[1] return defines def _get_gnu_version_from_defines(defines: T.Dict[str, str]) -> str:
64
64
76
21
42
johan-boule/meson
mesonbuild/compilers/detect.py
Python
_get_gnu_version_from_defines
_get_gnu_version_from_defines
1,212
1,217
1,212
1,212
abb0ae02d17a4b2837caf2039dd34127d151b88c
bigcode/the-stack
train
0e19d5b7723ad34ce200d6c9
train
function
def _get_lcc_version_from_defines(defines: T.Dict[str, str]) -> str: dot = '.' generation_and_major = defines.get('__LCC__', '100') generation = generation_and_major[:1] major = generation_and_major[1:] minor = defines.get('__LCC_MINOR__', '0') return dot.join((generation, major, minor))
def _get_lcc_version_from_defines(defines: T.Dict[str, str]) -> str:
dot = '.' generation_and_major = defines.get('__LCC__', '100') generation = generation_and_major[:1] major = generation_and_major[1:] minor = defines.get('__LCC_MINOR__', '0') return dot.join((generation, major, minor))
__', '0') minor = defines.get('__GNUC_MINOR__', '0') patch = defines.get('__GNUC_PATCHLEVEL__', '0') return dot.join((major, minor, patch)) def _get_lcc_version_from_defines(defines: T.Dict[str, str]) -> str:
64
64
84
21
43
johan-boule/meson
mesonbuild/compilers/detect.py
Python
_get_lcc_version_from_defines
_get_lcc_version_from_defines
1,219
1,225
1,219
1,219
5d856f82493322946931a856c505f3873dce18f5
bigcode/the-stack
train
3718105f5ce2b7198eeec2ac
train
function
def get_expbase(lvl): exp_table_pth = join(pathlib.Path(__file__).resolve().parents[0],"exp.txt") with open(exp_table_pth, "r") as f: l = f.readlines() exp_list = [(line.split(" ")[0], line.split(" ")[2].strip()) for line in l] exp_table = dict(exp_list) base_...
def get_expbase(lvl):
exp_table_pth = join(pathlib.Path(__file__).resolve().parents[0],"exp.txt") with open(exp_table_pth, "r") as f: l = f.readlines() exp_list = [(line.split(" ")[0], line.split(" ")[2].strip()) for line in l] exp_table = dict(exp_list) base_exp = exp_table[str(lv...
import os import pathlib from os.path import join def get_expbase(lvl):
19
64
99
7
11
vinmorel/MapleWrapper
maplewrapper/utils/fetch_exp.py
Python
get_expbase
get_expbase
5
14
5
5
c49eb0511f5ed81fdf4673d6d4f40d4fe74e854f
bigcode/the-stack
train
f96111c042bccbe6ed08c4f7
train
class
class TestCallbackTraceback: # When an exception is raised in a ctypes callback function, the C # code prints a traceback. # # This test makes sure the exception types *and* the exception # value is printed correctly. # # Changed in 0.9.3: No longer is '(in callback)' prepended to the # ...
class TestCallbackTraceback: # When an exception is raised in a ctypes callback function, the C # code prints a traceback. # # This test makes sure the exception types *and* the exception # value is printed correctly. # # Changed in 0.9.3: No longer is '(in callback)' prepended to the # ...
def capture_stderr(self, func, *args, **kw): # helper - call function 'func', and return the captured stderr import StringIO old_stderr = sys.stderr logger = sys.stderr = StringIO.StringIO() try: func(*args, **kw) finally: sys.stderr = old_stde...
# derived from test_random_things.py import py from ctypes import * import sys def callback_func(arg): 42 / arg raise ValueError(arg) class TestCallbackTraceback: # When an exception is raised in a ctypes callback function, the C # code prints a traceback. # # This test makes sure the exception...
157
195
651
121
36
m4sterchain/mesapy
pypy/module/test_lib_pypy/ctypes_tests/test_callback_traceback.py
Python
TestCallbackTraceback
TestCallbackTraceback
10
80
10
21
20233bda2eaa06282b35ff55ddaf9015808f541f
bigcode/the-stack
train
1f0fc4f28a342ed6a7d1ae0b
train
function
def callback_func(arg): 42 / arg raise ValueError(arg)
def callback_func(arg):
42 / arg raise ValueError(arg)
# derived from test_random_things.py import py from ctypes import * import sys def callback_func(arg):
24
64
17
5
18
m4sterchain/mesapy
pypy/module/test_lib_pypy/ctypes_tests/test_callback_traceback.py
Python
callback_func
callback_func
6
8
6
6
0aeffdc5f5c52d365a94def5fa9b09e8aa1c6295
bigcode/the-stack
train
1b1e1c9b96c88b6a3fedbb2b
train
class
class MichelsonCodingTestKT1Md4(TestCase): def setUp(self): self.maxDiff = None def test_michelson_parse_code_KT1Md4(self): expected = get_data( path='contracts/KT1Md4zkfCvkdqgxAC9tyRYpRUBKmD1owEi2/code_KT1Md4.json') actual = michelson_to_micheline(get_data( ...
class MichelsonCodingTestKT1Md4(TestCase):
def setUp(self): self.maxDiff = None def test_michelson_parse_code_KT1Md4(self): expected = get_data( path='contracts/KT1Md4zkfCvkdqgxAC9tyRYpRUBKmD1owEi2/code_KT1Md4.json') actual = michelson_to_micheline(get_data( path='contracts/KT1Md4zkfCvkdqgxAC9tyRYpRUBKmD1...
from unittest import TestCase from tests import get_data from pytezos.michelson.micheline import michelson_to_micheline from pytezos.michelson.formatter import micheline_to_michelson class MichelsonCodingTestKT1Md4(TestCase):
61
256
982
13
47
juztin/pytezos-1
tests/contracts/KT1Md4zkfCvkdqgxAC9tyRYpRUBKmD1owEi2/test_michelson_coding_KT1Md4.py
Python
MichelsonCodingTestKT1Md4
MichelsonCodingTestKT1Md4
8
74
8
9
801882036d31a624ed2caca9d0b9023b514e18e5
bigcode/the-stack
train
080b4fd58b3e91105a15f5d8
train
function
def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('post', sa.Column('id', sa.Integer(), nullable=False), sa.Column('body', sa.String(length=140), nullable=True), sa.Column('timestamp', sa.DateTime(), nullable=True), sa.Column('user_id', sa.Integer(), nu...
def upgrade(): # ### commands auto generated by Alembic - please adjust! ###
op.create_table('post', sa.Column('id', sa.Integer(), nullable=False), sa.Column('body', sa.String(length=140), nullable=True), sa.Column('timestamp', sa.DateTime(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.Pri...
sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'cd19cab1b3df' down_revision = '45ad6bf56702' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ###
64
64
122
18
45
satyapramodh/microblog
migrations/versions/cd19cab1b3df_posts_table.py
Python
upgrade
upgrade
19
29
19
20
b6517f66407bf398389b5e23c8388817555e7ce0
bigcode/the-stack
train
166ad1f256dbeac7865e650d
train
function
def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_post_timestamp'), table_name='post') op.drop_table('post')
def downgrade(): # ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_post_timestamp'), table_name='post') op.drop_table('post')
'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_post_timestamp'), 'post', ['timestamp'], unique=False) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ###
63
64
41
18
45
satyapramodh/microblog
migrations/versions/cd19cab1b3df_posts_table.py
Python
downgrade
downgrade
33
36
33
34
7971c15d782bbd251e3a96034eb175b09942d67e
bigcode/the-stack
train
92b1b9eb0a675e6a9fb00e55
train
function
@pytest.mark.parametrize( "params,json_response", [ ([], [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]), ([("prefix", "B")], [{"item_name": "Bar"}, {"item_name": "Baz"}]), ([("prefix", "B"), ("prefix", "Baz")], [{"item_name": "Baz"}]), ([("prefix", "B"), ("pr...
@pytest.mark.parametrize( "params,json_response", [ ([], [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]), ([("prefix", "B")], [{"item_name": "Bar"}, {"item_name": "Baz"}]), ([("prefix", "B"), ("prefix", "Baz")], [{"item_name": "Baz"}]), ([("prefix", "B"), ("pr...
response = client.get("/items/", params=params) assert response.status_code == 200, response.content assert response.json() == json_response
@pytest.mark.parametrize( "params,json_response", [ ([], [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]), ([("prefix", "B")], [{"item_name": "Bar"}, {"item_name": "Baz"}]), ([("prefix", "B"), ("prefix", "Baz")], [{"item_name": "Baz"}]), ([("prefix", "B"), ("pr...
125
64
157
125
0
adriangb/xpresso
tests/test_docs/tutorial/query_params/test_tutorial_004.py
Python
test_read_item
test_read_item
86
98
86
95
c33f87e86a940b317561c48cf7631956005d7870
bigcode/the-stack
train
33f5080544c1194c782b9053
train
function
def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.content assert response.json() == openapi_schema
def test_openapi_schema():
response = client.get("/openapi.json") assert response.status_code == 200, response.content assert response.json() == openapi_schema
"type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } ...
64
64
38
6
58
adriangb/xpresso
tests/test_docs/tutorial/query_params/test_tutorial_004.py
Python
test_openapi_schema
test_openapi_schema
80
83
80
80
442a405f29e99421418b93d8078f11093c1bcfa8
bigcode/the-stack
train
1b1ab4425dcae314626ebfa5
train
function
def check_if_dataframes_are_equal(df1, df2): """ for some reason, this is how you check that two dataframes are equal. """ from pandas.testing import assert_frame_equal try: assert_frame_equal(df1, df2) return True except AssertionError: return False
def check_if_dataframes_are_equal(df1, df2):
""" for some reason, this is how you check that two dataframes are equal. """ from pandas.testing import assert_frame_equal try: assert_frame_equal(df1, df2) return True except AssertionError: return False
's data frame df = pd.DataFrame() for i in range(len(list_to_convert)): inst = list_to_convert[i] data = [] data.append(pd.Series(inst)) df[i] = data return df def check_if_dataframes_are_equal(df1, df2):
64
64
69
13
50
brettkoonce/sktime
sktime/transformers/series_as_features/tests/test_slope_transformer.py
Python
check_if_dataframes_are_equal
check_if_dataframes_are_equal
100
110
100
100
ccc1638b9bc76f8b37c23155e14a67a4ff2e7635
bigcode/the-stack
train
4a9c1f399c16c3decbd12e47
train
function
def convert_list_to_dataframe(list_to_convert): # Convert this into a panda's data frame df = pd.DataFrame() for i in range(len(list_to_convert)): inst = list_to_convert[i] data = [] data.append(pd.Series(inst)) df[i] = data return df
def convert_list_to_dataframe(list_to_convert): # Convert this into a panda's data frame
df = pd.DataFrame() for i in range(len(list_to_convert)): inst = list_to_convert[i] data = [] data.append(pd.Series(inst)) df[i] = data return df
10], [(5+math.sqrt(41))/4, (1+math.sqrt(101))/-10]]) orig.columns = X.columns assert check_if_dataframes_are_equal(res, orig) def convert_list_to_dataframe(list_to_convert): # Convert this into a panda's data frame
64
64
67
20
44
brettkoonce/sktime
sktime/transformers/series_as_features/tests/test_slope_transformer.py
Python
convert_list_to_dataframe
convert_list_to_dataframe
88
97
88
89
1750dae84ee714e8d3b7ad15e5a1c4a1e61f40d3
bigcode/the-stack
train
d37c549bd5d9ec9f95de8659
train
function
@pytest.mark.parametrize("bad_num_intervals", ['str', 1.2, -1.2, -1, {}, 0]) def test_bad_input_args(bad_num_intervals): X = generate_df_from_array(np.ones(10), n_rows=10, n_cols=1) if not isinstance(bad_num_intervals, int): with pytest.raises(TypeError): SlopeTransformer(num_intervals=bad_...
@pytest.mark.parametrize("bad_num_intervals", ['str', 1.2, -1.2, -1, {}, 0]) def test_bad_input_args(bad_num_intervals):
X = generate_df_from_array(np.ones(10), n_rows=10, n_cols=1) if not isinstance(bad_num_intervals, int): with pytest.raises(TypeError): SlopeTransformer(num_intervals=bad_num_intervals) \ .fit(X).transform(X) else: with pytest.raises(ValueError): ...
int, negative float, empty dict. # correct input is meant to be a positive integer of 1 or more. @pytest.mark.parametrize("bad_num_intervals", ['str', 1.2, -1.2, -1, {}, 0]) def test_bad_input_args(bad_num_intervals):
64
64
135
40
24
brettkoonce/sktime
sktime/transformers/series_as_features/tests/test_slope_transformer.py
Python
test_bad_input_args
test_bad_input_args
13
24
13
14
8c0fa94a5abd2305c8e928a5c4f10a7b21390769
bigcode/the-stack
train
72dd980d7794860f5010ed97
train
function
def test_slope_performs_correcly_along_each_dim(): X = generate_df_from_array(np.array([4, 6, 10, 12, 8, 6, 5, 5]), n_rows=1, n_cols=2) s = SlopeTransformer(num_intervals=2).fit(X) res = s.transform(X) orig = convert_list_to_dataframe([[(5+math.sqrt(41))/4, ...
def test_slope_performs_correcly_along_each_dim():
X = generate_df_from_array(np.array([4, 6, 10, 12, 8, 6, 5, 5]), n_rows=1, n_cols=2) s = SlopeTransformer(num_intervals=2).fit(X) res = s.transform(X) orig = convert_list_to_dataframe([[(5+math.sqrt(41))/4, (1+math.sqrt(101))/-10], ...
_cols = res.shape[1] assert act_time_series_length == corr_series_length assert num_rows == 10 assert num_cols == 1 # This is to check that Slope produces the same result along each dimension def test_slope_performs_correcly_along_each_dim():
64
64
152
14
49
brettkoonce/sktime
sktime/transformers/series_as_features/tests/test_slope_transformer.py
Python
test_slope_performs_correcly_along_each_dim
test_slope_performs_correcly_along_each_dim
73
85
73
74
d82cca69ab54e8365da056f26c568620845ddfed
bigcode/the-stack
train
d7a3fcb82870c9405c7e461a
train
function
@pytest.mark.parametrize("num_intervals,corr_series_length", [(2, 2), (5, 5), (8, 8)]) def test_output_dimensions(num_intervals, corr_series_length): X = generate_df_from_array(np.ones(13), n...
@pytest.mark.parametrize("num_intervals,corr_series_length", [(2, 2), (5, 5), (8, 8)]) def test_output_dimensions(num_intervals, corr_series_length):
X = generate_df_from_array(np.ones(13), n_rows=10, n_cols=1) s = SlopeTransformer(num_intervals=num_intervals).fit(X) res = s.transform(X) # get the dimension of the generated dataframe. act_time_series_length = res.iloc[0, 0].shape[0] num_rows = res.shape[0] num_cols = res.shape[1] a...
]) orig.columns = X.columns assert check_if_dataframes_are_equal(res, orig) @pytest.mark.parametrize("num_intervals,corr_series_length", [(2, 2), (5, 5), (8, 8)]) def test_output_dimensio...
64
64
162
44
20
brettkoonce/sktime
sktime/transformers/series_as_features/tests/test_slope_transformer.py
Python
test_output_dimensions
test_output_dimensions
52
69
52
56
85c4e56e6c05c845623c6fe231282afa0aaf81ff
bigcode/the-stack
train
4e3c5ac251bfa0fdcd531ebf
train
function
def test_output_of_transformer(): X = generate_df_from_array(np.array([4, 6, 10, 12, 8, 6, 5, 5]), n_rows=1, n_cols=1) s = SlopeTransformer(num_intervals=2).fit(X) res = s.transform(X) orig = convert_list_to_dataframe([[(5+math.sqrt(41))/4, ...
def test_output_of_transformer():
X = generate_df_from_array(np.array([4, 6, 10, 12, 8, 6, 5, 5]), n_rows=1, n_cols=1) s = SlopeTransformer(num_intervals=2).fit(X) res = s.transform(X) orig = convert_list_to_dataframe([[(5+math.sqrt(41))/4, (1+math.sqrt(101))/-10]]) ...
with pytest.raises(TypeError): SlopeTransformer(num_intervals=bad_num_intervals) \ .fit(X).transform(X) else: with pytest.raises(ValueError): SlopeTransformer(num_intervals=bad_num_intervals) \ .fit(X).transform(X) # Check th...
77
77
257
7
70
brettkoonce/sktime
sktime/transformers/series_as_features/tests/test_slope_transformer.py
Python
test_output_of_transformer
test_output_of_transformer
28
49
28
29
525cc0560967f5abf7ccdf13d9b66d37996a65bc
bigcode/the-stack
train
9ac873da979b5c099857660f
train
class
class LdapAttr(object): def __init__(self, module): # Shortcuts self.module = module self.bind_dn = self.module.params['bind_dn'] self.bind_pw = self.module.params['bind_pw'] self.dn = self.module.params['dn'] self.name = self.module.params['name'] self.server...
class LdapAttr(object):
def __init__(self, module): # Shortcuts self.module = module self.bind_dn = self.module.params['bind_dn'] self.bind_pw = self.module.params['bind_pw'] self.dn = self.module.params['dn'] self.name = self.module.params['name'] self.server_uri = self.module.param...
The same as in the previous example but with the authentication details # stored in the ldap_auth variable: # # ldap_auth: # server_uri: ldap://localhost/ # bind_dn: cn=admin,dc=example,dc=com # bind_pw: password - name: Get rid of an unneeded attribute ldap_entry: dn: uid=jdoe,ou=people,dc=example,dc=com ...
213
213
710
6
206
zone-zero/isam-ansible-collection
plugins/modules/ldap_attr.py
Python
LdapAttr
LdapAttr
203
299
203
203
1125f05d5f7a29b5f570e4620bf3c74e11f9f0ea
bigcode/the-stack
train
fa1091796562f650092b9398
train
function
def main(): module = AnsibleModule( argument_spec={ 'bind_dn': dict(default=None), 'bind_pw': dict(default='', no_log=True), 'dn': dict(required=True), 'name': dict(required=True), 'params': dict(type='dict'), 'server_uri': dict(default...
def main():
module = AnsibleModule( argument_spec={ 'bind_dn': dict(default=None), 'bind_pw': dict(default='', no_log=True), 'dn': dict(required=True), 'name': dict(required=True), 'params': dict(type='dict'), 'server_uri': dict(default='ldapi:///'...
try: connection.start_tls_s() except ldap.LDAPError as e: self.module.fail_json(msg="Cannot start TLS.", details=str(e)) try: if self.bind_dn is not None: connection.simple_bind_s(self.bind_dn, self.bind_pw) else: ...
110
110
367
3
106
zone-zero/isam-ansible-collection
plugins/modules/ldap_attr.py
Python
main
main
302
355
302
302
296b8d995ad9e3311ef2275b8aec794cca2cf3bf
bigcode/the-stack
train
1bc8506e4a17c6cd3f505eb1
train
class
class LossAwareSamplerEma: def __init__(self, num_histogram_buckets=100, uniform_p=0.01, alpha=0.9, warmup=10, jitter=True): assert num_histogram_buckets > 1 self.num_histogram_buckets = num_histogram_buckets self.uniform_p = uniform_p self.alpha = alpha self.warmup = warmup ...
class LossAwareSamplerEma:
def __init__(self, num_histogram_buckets=100, uniform_p=0.01, alpha=0.9, warmup=10, jitter=True): assert num_histogram_buckets > 1 self.num_histogram_buckets = num_histogram_buckets self.uniform_p = uniform_p self.alpha = alpha self.warmup = warmup self.jitter = jitte...
import torch import numpy as np class LossAwareSamplerEma:
15
143
478
7
7
world-modelz/world-modelz
vq-video-diffusion/importance_sampling.py
Python
LossAwareSamplerEma
LossAwareSamplerEma
5
47
5
5
545c49b80ff4939003548ff6c05129293c9cfa95
bigcode/the-stack
train
14ebea8a5b600b13ce5a3a21
train
function
def test(): l = LossAwareSamplerEma(100) l.update_with_losses(torch.rand(10000), torch.rand(10000)) print('counts', l._counts, l._counts.sum()) print('warmed up', l.warmed_up()) print('weights', l.weights()) x = l.sample(10) print('samples', x)
def test():
l = LossAwareSamplerEma(100) l.update_with_losses(torch.rand(10000), torch.rand(10000)) print('counts', l._counts, l._counts.sum()) print('warmed up', l.warmed_up()) print('weights', l.weights()) x = l.sample(10) print('samples', x)
return (self._counts > self.warmup).all() def weights_as_numpy_histogram(self): return ((self.weights() / (self.weights().sum()+1e-6)).numpy(), np.arange(self.num_histogram_buckets+1) / self.num_histogram_buckets) def test():
64
64
80
3
61
world-modelz/world-modelz
vq-video-diffusion/importance_sampling.py
Python
test
test
50
58
50
50
c490d535b3059c42c1aeb1d3fe5a6070013c1ed2
bigcode/the-stack
train
05d33830fcbe78f431696031
train
class
class OrderViewTestCase(APITestCase): def setUp(self): data = { 'username': 'moneyhunter001', 'first_name': 'Josh', 'last_name': 'Mathews', 'email': 'moneyhunter0@example.com', 'iban': '1234567891234567891234567891234567', 'is_trader': ...
class OrderViewTestCase(APITestCase):
def setUp(self): data = { 'username': 'moneyhunter001', 'first_name': 'Josh', 'last_name': 'Mathews', 'email': 'moneyhunter0@example.com', 'iban': '1234567891234567891234567891234567', 'is_trader': True, 'city': "Cairo", ...
from django.urls import reverse from rest_framework.test import APITestCase from rest_framework import status from rest_framework.authtoken.models import Token from ..models import * class OrderViewTestCase(APITestCase):
45
256
1,658
9
36
rdilruba/bounswe2019group2
traiders/backend/api/test/test_order.py
Python
OrderViewTestCase
OrderViewTestCase
9
227
9
9
3f22a764231a4ca0115ee3104e2e819f221036be
bigcode/the-stack
train
c6923f8ab4f519b02fc624bd
train
class
class CoverageContextReport: @staticmethod def create_connection(db_file): conn = None try: conn = sqlite3.connect(db_file) except Error as e: print(e) return conn @staticmethod def dict_factory(cursor, row): d = {} for idx, col in...
class CoverageContextReport: @staticmethod
def create_connection(db_file): conn = None try: conn = sqlite3.connect(db_file) except Error as e: print(e) return conn @staticmethod def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[c...
import configparser import json import os import sqlite3 from sqlite3 import Error class CoverageContextReport: @staticmethod
29
199
666
9
19
sansalinas/coverage-context-report
app/coverage_context_report.py
Python
CoverageContextReport
CoverageContextReport
8
81
8
9
741dcaa9cf0f07aa3d372b9d0e5b52cd9e12777d
bigcode/the-stack
train
70a9dbfc4f3c81b35aa88b7a
train
function
def generate_password(): """Create 32 byte b64 password""" return urlsafe_b64encode(urandom(32)).decode('utf-8')
def generate_password():
"""Create 32 byte b64 password""" return urlsafe_b64encode(urandom(32)).decode('utf-8')
from base64 import urlsafe_b64encode from binascii import hexlify from getpass import getpass from os import urandom import hmac def generate_salt(size): """Create size byte hex salt""" return hexlify(urandom(size)).decode() def generate_password():
64
64
33
4
60
DiniMuhd7/asusucoin
share/rpcauth/rpcauth.py
Python
generate_password
generate_password
18
20
18
18
68aeab3705f07adfd47647d0f3ebad14076dfb95
bigcode/the-stack
train
8c77b2962586dccdc1a30130
train
function
def main(): parser = ArgumentParser(description='Create login credentials for a JSON-RPC user') parser.add_argument('username', help='the username for authentication') parser.add_argument('password', help='leave empty to generate a random password or specify "-" to prompt for password', nargs='?') args ...
def main():
parser = ArgumentParser(description='Create login credentials for a JSON-RPC user') parser.add_argument('username', help='the username for authentication') parser.add_argument('password', help='leave empty to generate a random password or specify "-" to prompt for password', nargs='?') args = parser.par...
safe_b64encode(urandom(32)).decode('utf-8') def password_to_hmac(salt, password): m = hmac.new(bytearray(salt, 'utf-8'), bytearray(password, 'utf-8'), 'SHA256') return m.hexdigest() def main():
64
64
179
3
61
DiniMuhd7/asusucoin
share/rpcauth/rpcauth.py
Python
main
main
26
43
26
26
11bbefab6e646b5b2fe35256a5f898c1416602aa
bigcode/the-stack
train
14a00cffc43c672221ef9016
train
function
def password_to_hmac(salt, password): m = hmac.new(bytearray(salt, 'utf-8'), bytearray(password, 'utf-8'), 'SHA256') return m.hexdigest()
def password_to_hmac(salt, password):
m = hmac.new(bytearray(salt, 'utf-8'), bytearray(password, 'utf-8'), 'SHA256') return m.hexdigest()
(size): """Create size byte hex salt""" return hexlify(urandom(size)).decode() def generate_password(): """Create 32 byte b64 password""" return urlsafe_b64encode(urandom(32)).decode('utf-8') def password_to_hmac(salt, password):
64
64
45
10
54
DiniMuhd7/asusucoin
share/rpcauth/rpcauth.py
Python
password_to_hmac
password_to_hmac
22
24
22
22
0ace624d1bbf1a45b03f514bc6f3661d5881360c
bigcode/the-stack
train
f6e9ff91b3db7f97373d8b7d
train
function
def generate_salt(size): """Create size byte hex salt""" return hexlify(urandom(size)).decode()
def generate_salt(size):
"""Create size byte hex salt""" return hexlify(urandom(size)).decode()
the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from argparse import ArgumentParser from base64 import urlsafe_b64encode from binascii import hexlify from getpass import getpass from os import urandom import hmac def generate_salt(size):
64
64
25
6
57
DiniMuhd7/asusucoin
share/rpcauth/rpcauth.py
Python
generate_salt
generate_salt
14
16
14
14
dfe62f3ca3d128484cd9ea539cb547daec9301a5
bigcode/the-stack
train
e233aa2c584aea0298afd680
train
class
class QueryFpImportResultRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Mts', '2014-06-18', 'QueryFpImportResult','mts') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): ...
class QueryFpImportResultRequest(RpcRequest):
def __init__(self): RpcRequest.__init__(self, 'Mts', '2014-06-18', 'QueryFpImportResult','mts') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_dat...
0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" B...
147
147
492
10
136
yndu13/aliyun-openapi-python-sdk
aliyun-python-sdk-mts/aliyunsdkmts/request/v20140618/QueryFpImportResultRequest.py
Python
QueryFpImportResultRequest
QueryFpImportResultRequest
23
73
23
24
e002d90b451a7ea5fb0eafa6ef5d21ed027a3809
bigcode/the-stack
train
afa023b1636e09159b991c00
train
class
class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, seriali...
class Migration(migrations.Migration):
initial = True dependencies = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
# Generated by Django 2.2.26 on 2022-02-02 06:10 from django.db import migrations, models class Migration(migrations.Migration):
38
93
310
7
30
lastlift/recipe-app-api
app/core/migrations/0001_initial.py
Python
Migration
Migration
6
33
6
7
32e03b1964fbdbd3fe1841d5520b92f99d636b2e
bigcode/the-stack
train
6b687f665b60da7dcd84c1eb
train
class
class TestYacc(unittest.TestCase): def test_yacc_heading(self): data = '# Head1\n## Head2\n### Head3\n' result = parser.parse(data) self.assertEqual(len(result), 3) self.assertEqual(result[0]['type'], 'HEADING') self.assertEqual(result[0]['level'], 1) self.assertEq...
class TestYacc(unittest.TestCase):
def test_yacc_heading(self): data = '# Head1\n## Head2\n### Head3\n' result = parser.parse(data) self.assertEqual(len(result), 3) self.assertEqual(result[0]['type'], 'HEADING') self.assertEqual(result[0]['level'], 1) self.assertEqual(result[1]['type'], 'HEADING') ...
#coding=utf-8 import unittest from lex import lexer from yacc import parser class TestYacc(unittest.TestCase):
27
256
1,132
8
18
Wizmann/mkd
yacc_test.py
Python
TestYacc
TestYacc
7
133
7
7
685d2319d2c9dd96f998df02d548c537260c0f71
bigcode/the-stack
train
4ff85cbd938d078155510117
train
class
class ValidationErrorSchema(BaseSchema): class InnerValidationErrorSchema(BaseSchema): class ValidationFieldErrorSchema(BaseSchema): field = fields.Str(required=True) message = fields.Str(required=True, default='Validation error') fields = fields.Nested(ValidationFieldErrorSch...
class ValidationErrorSchema(BaseSchema):
class InnerValidationErrorSchema(BaseSchema): class ValidationFieldErrorSchema(BaseSchema): field = fields.Str(required=True) message = fields.Str(required=True, default='Validation error') fields = fields.Nested(ValidationFieldErrorSchema, required=True) error = fields.Ne...
from vobla.schemas import BaseSchema from marshmallow import fields class VoblaHTTPErrorSchema(BaseSchema): class InnerValidationErrorSchema(BaseSchema): message = fields.Str(required=True) error = fields.Nested(InnerValidationErrorSchema, required=True) class ValidationErrorSchema(BaseSchema):
64
64
76
7
57
Nuqlear/voila
backend/vobla/schemas/serializers/errors.py
Python
ValidationErrorSchema
ValidationErrorSchema
14
24
14
15
926b4e44bf51cf1280f3ba5f3fbbd05a19c130f4
bigcode/the-stack
train
d18e0770e381feb04cf54c5f
train
class
class VoblaHTTPErrorSchema(BaseSchema): class InnerValidationErrorSchema(BaseSchema): message = fields.Str(required=True) error = fields.Nested(InnerValidationErrorSchema, required=True)
class VoblaHTTPErrorSchema(BaseSchema):
class InnerValidationErrorSchema(BaseSchema): message = fields.Str(required=True) error = fields.Nested(InnerValidationErrorSchema, required=True)
from vobla.schemas import BaseSchema from marshmallow import fields class VoblaHTTPErrorSchema(BaseSchema):
25
64
42
10
14
Nuqlear/voila
backend/vobla/schemas/serializers/errors.py
Python
VoblaHTTPErrorSchema
VoblaHTTPErrorSchema
6
11
6
7
2bbafbad11969209f6bf4cdb5224035f050759af
bigcode/the-stack
train
a032b98e556c04f66b99ed03
train
class
class ORMFixture: db = Database() class ORMGroup(db.Entity): _table_ = 'group_list' id = PrimaryKey(int, column='group_id') name = Optional(str, column='group_name') header = Optional(str, column='group_header') footer = Optional(str, column='group_footer') cont...
class ORMFixture:
db = Database() class ORMGroup(db.Entity): _table_ = 'group_list' id = PrimaryKey(int, column='group_id') name = Optional(str, column='group_name') header = Optional(str, column='group_header') footer = Optional(str, column='group_footer') contacts = Set(lambda: ...
from pony.orm import * from model.group import Group from model.contact import Contact class ORMFixture:
21
164
547
4
16
anreysolovyev/python_training
fixture/orm.py
Python
ORMFixture
ORMFixture
6
64
6
7
50c53c16eaac22e424541958cd75d06db5529d07
bigcode/the-stack
train
62a157245b771f218f70f823
train
class
class Reader(object): def __init__(self, address): self.requester = GATTRequester(address, False) self.connect() self.request_data() def connect(self): print("Connecting...", end=' ') sys.stdout.flush() self.requester.connect(True) print("OK!") def ...
class Reader(object):
def __init__(self, address): self.requester = GATTRequester(address, False) self.connect() self.request_data() def connect(self): print("Connecting...", end=' ') sys.stdout.flush() self.requester.connect(True) print("OK!") def request_data(self): ...
: utf-8 -*- # Copyright (C) 2014, Oscar Acena <oscaracena@gmail.com> # This software is under the terms of Apache License v2 or later. from __future__ import print_function import sys from gattlib import GATTRequester class Reader(object):
64
64
113
4
59
YogeshSingla/pygattlib
examples/read.py
Python
Reader
Reader
13
32
13
13
fcb82c33cac68bb319a33218cd76a293f5fed6fa
bigcode/the-stack
train
cda23347660acc026bcf623a
train
function
def transformation_matrices(base_rpy: np.array) -> List[np.array]: """ Returns the transformation matrices from the hip to the leg base. Arguments: --------- base_rpy: numpy.array, shape(3,) The hip's (and robot base) euler angles. (roll, pitch, yaw) ...
def transformation_matrices(base_rpy: np.array) -> List[np.array]:
""" Returns the transformation matrices from the hip to the leg base. Arguments: --------- base_rpy: numpy.array, shape(3,) The hip's (and robot base) euler angles. (roll, pitch, yaw) Returns: -------- List[numpy.array], shape (4...
), 0, np.cos(pitch)]] ) R_z = np.array( [[np.cos(yaw), -np.sin(yaw), 0], [np.sin(yaw), np.cos(yaw), 0], [0, 0, 1]] ) return np.dot(R_z, np.dot( R_y, R_x )) #@jit def transformation_matrices(base_rpy: np.array) -> List[np.array]:
106
106
355
16
89
eduardo98m/GiaDog
raisimEnvs/giadog_gym_v4/kinematics_optimized/transformation_matrices.py
Python
transformation_matrices
transformation_matrices
52
89
52
52
8c09db55ef002df9c9eeea395ed311ecd2bcd9d5
bigcode/the-stack
train
a0654fdbb3f8530879704411
train
function
def rotation_matrix_from_euler(theta: np.ndarray) -> np.ndarray: """ Calculates a rotation matrix from the euler angles. Arguments: ---------- theta: numpy.array, shape(3,) Euler angles. (roll, pitch, yaw) Return: ------- nump...
def rotation_matrix_from_euler(theta: np.ndarray) -> np.ndarray:
""" Calculates a rotation matrix from the euler angles. Arguments: ---------- theta: numpy.array, shape(3,) Euler angles. (roll, pitch, yaw) Return: ------- numpy.array, shape(3,3) Rotation matrix. """ ...
""" Authors: Amin Arriaga, Eduardo Lopez Project: Graduation Thesis: GIAdog [TODO: DESCRIPTION] """ import numpy as np from typing import List from __env__ import H_OFF, LEG_SPAN from numba import jit #@jit def rotation_matrix_from_euler(theta: np.ndarray) -> np.ndarray:
76
84
281
15
60
eduardo98m/GiaDog
raisimEnvs/giadog_gym_v4/kinematics_optimized/transformation_matrices.py
Python
rotation_matrix_from_euler
rotation_matrix_from_euler
14
49
14
14
3c8cce0b30c28ed70c5f7a22a14dd2f42fcdfeba
bigcode/the-stack
train
aa267b4eeeacc7b5786d3884
train
function
def make_f1score_image(fig_path, mean_train_accs, mean_test_accs,class_num): plt.style.use('ggplot') plt.figure(figsize=(10, 7)) plt.ylim(0.0, 1) plt.plot(mean_train_accs, "b", lw=1) plt.plot(mean_test_accs, "r", lw=1) plt.title("") plt.ylabel("class_"+str(class_num)+"_f1_score") plt.sav...
def make_f1score_image(fig_path, mean_train_accs, mean_test_accs,class_num):
plt.style.use('ggplot') plt.figure(figsize=(10, 7)) plt.ylim(0.0, 1) plt.plot(mean_train_accs, "b", lw=1) plt.plot(mean_test_accs, "r", lw=1) plt.title("") plt.ylabel("class_"+str(class_num)+"_f1_score") plt.savefig(fig_path) plt.xlabel("epoch") plt.close()
1) plt.plot(mean_valid_accs, "r", lw=1) plt.title("") plt.ylabel("accuracy") plt.savefig(fig_path) plt.xlabel("epoch") plt.close() def make_f1score_image(fig_path, mean_train_accs, mean_test_accs,class_num):
64
64
116
21
43
ryama-tokyo/glomerular_classification
util.py
Python
make_f1score_image
make_f1score_image
39
49
39
39
255f56f028b6eeb8c3e0e1e2c8e19b0763c4cc5e
bigcode/the-stack
train
6661563e2e3c354fdaa3db76
train
function
def load_data(path): npz = np.load(path) x_train, y_train = npz['x_train'].astype(np.float32), npz['y_train'].astype(np.int32) x_test, y_test = npz['x_test'].astype(np.float32), npz['y_test'].astype(np.int32) return x_train, x_test, y_train, y_test
def load_data(path):
npz = np.load(path) x_train, y_train = npz['x_train'].astype(np.float32), npz['y_train'].astype(np.int32) x_test, y_test = npz['x_test'].astype(np.float32), npz['y_test'].astype(np.int32) return x_train, x_test, y_train, y_test
# -*- coding: utf-8 -*- import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np def load_data(path):
33
64
85
5
27
ryama-tokyo/glomerular_classification
util.py
Python
load_data
load_data
8
12
8
8
fb5c3a7103ee572035c5da35828e19b6eba9d26c
bigcode/the-stack
train
c3f2c77e78832d54d50bd0a0
train
function
def make_accuracy_image(fig_path, mean_train_accs, mean_valid_accs): plt.style.use('ggplot') plt.figure(figsize=(10, 7)) plt.ylim(0.0, 1) plt.plot(mean_train_accs, "b", lw=1) plt.plot(mean_valid_accs, "r", lw=1) plt.title("") plt.ylabel("accuracy") plt.savefig(fig_path) plt.xlabel("e...
def make_accuracy_image(fig_path, mean_train_accs, mean_valid_accs):
plt.style.use('ggplot') plt.figure(figsize=(10, 7)) plt.ylim(0.0, 1) plt.plot(mean_train_accs, "b", lw=1) plt.plot(mean_valid_accs, "r", lw=1) plt.title("") plt.ylabel("accuracy") plt.savefig(fig_path) plt.xlabel("epoch") plt.close()
1) plt.plot(mean_valid_losses, "r", lw=1) plt.title("") plt.ylabel("softmax cross entopy loss") plt.savefig(fig_path) plt.xlabel("epoch") plt.close() def make_accuracy_image(fig_path, mean_train_accs, mean_valid_accs):
64
64
103
17
47
ryama-tokyo/glomerular_classification
util.py
Python
make_accuracy_image
make_accuracy_image
27
37
27
27
8fc13bbc366abd0893ee91b45e19294e8b0ad14e
bigcode/the-stack
train
b7da65dc9b5a4bd1c8145fc4
train
function
def make_learning_image(fig_path, mean_train_losses, mean_valid_losses): plt.style.use('ggplot') plt.figure(figsize=(10, 7)) k=max(max(mean_train_losses),max(mean_valid_losses)) plt.ylim(0.0, k*1.2) plt.plot(mean_train_losses, "b", lw=1) plt.plot(mean_valid_losses, "r", lw=1) plt.title("") ...
def make_learning_image(fig_path, mean_train_losses, mean_valid_losses):
plt.style.use('ggplot') plt.figure(figsize=(10, 7)) k=max(max(mean_train_losses),max(mean_valid_losses)) plt.ylim(0.0, k*1.2) plt.plot(mean_train_losses, "b", lw=1) plt.plot(mean_valid_losses, "r", lw=1) plt.title("") plt.ylabel("softmax cross entopy loss") plt.savefig(fig_path) ...
'].astype(np.int32) x_test, y_test = npz['x_test'].astype(np.float32), npz['y_test'].astype(np.int32) return x_train, x_test, y_train, y_test def make_learning_image(fig_path, mean_train_losses, mean_valid_losses):
64
64
120
15
48
ryama-tokyo/glomerular_classification
util.py
Python
make_learning_image
make_learning_image
14
25
14
14
170fc2acdf7d94622f3d97e3ab72dc8f7ba27bb0
bigcode/the-stack
train
a75fa798932128df9f3d9871
train
class
@META_ARCH_REGISTRY.register() class SiameseRCNN(GeneralizedRCNN): """ Siamese R-CNN. Any model that contains the following three components: 1. Per-image feature extraction (aka backbone) 2. Region proposal generation 3. Per-region feature extraction and prediction In addition to GeneralizedRCN...
@META_ARCH_REGISTRY.register() class SiameseRCNN(GeneralizedRCNN):
""" Siamese R-CNN. Any model that contains the following three components: 1. Per-image feature extraction (aka backbone) 2. Region proposal generation 3. Per-region feature extraction and prediction In addition to GeneralizedRCNN, this takes in a reference crop as input, extracts features f...
from typing import Dict, Tuple, Any import torch from detectron2.config import CfgNode, configurable from detectron2.modeling.backbone import build_backbone from detectron2.modeling.meta_arch.build import META_ARCH_REGISTRY from detectron2.modeling.meta_arch.rcnn import GeneralizedRCNN from detectron2.modeling.proposa...
147
256
1,336
18
129
emulhall/episodic-memory
VQ2D/detectron2_extensions/modeling/meta_arch/siam_rcnn.py
Python
SiameseRCNN
SiameseRCNN
16
158
16
17
9909e505eac004cca3719266dc94c32f7622c8bc
bigcode/the-stack
train
01c4311ef27276ed007ef91d
train
function
def news_cm_add(request,pk) : if request.method == 'POST': now = datetime.datetime.now() year = now.year month = now.month day = now.day if len(str(day)) == 1 : day = "0" + str(day) if len(str(month)) == 1 : month = "0" + str(month)...
def news_cm_add(request,pk) :
if request.method == 'POST': now = datetime.datetime.now() year = now.year month = now.month day = now.day if len(str(day)) == 1 : day = "0" + str(day) if len(str(month)) == 1 : month = "0" + str(month) today = str(year)...
.models import SubCat from django.contrib.auth import authenticate, login, logout from django.core.files.storage import FileSystemStorage from trending.models import Trending from django.contrib.auth.models import User, Group, Permission from manager.models import Manager import random import string import datetime # ...
75
75
250
10
65
dchacca/DjangoOnline
myweb/myproject/comment/views.py
Python
news_cm_add
news_cm_add
18
57
18
20
9a202e18b742e2478540efa1502141f0428c61aa
bigcode/the-stack
train
5d09e81e77e472ad733268f4
train
function
def comments_list(request): # login check start if not request.user.is_authenticated : return redirect('mylogin') # login check end perm = 0 for i in request.user.groups.all(): if i.name == "masteruser" : perm = 1 if perm == 0 : a = News.objects.get(pk=pk).writer ...
def comments_list(request): # login check start
if not request.user.is_authenticated : return redirect('mylogin') # login check end perm = 0 for i in request.user.groups.all(): if i.name == "masteruser" : perm = 1 if perm == 0 : a = News.objects.get(pk=pk).writer if str(a) != str(request.user) : error...
b = Comment(name=name,email=email,cm=cm,news_id=pk,date=today,time=time) b.save() newsname = News.objects.get(pk=pk).name return redirect('news_detail' , word=newsname) def comments_list(request): # login check start
64
64
140
11
53
dchacca/DjangoOnline
myweb/myproject/comment/views.py
Python
comments_list
comments_list
60
80
60
62
f725d92e40d18ff4b846451f58ada02b81c3ff1a
bigcode/the-stack
train
658550275d2a9da3b605e746
train
function
def comments_confirme(request,pk): # login check start if not request.user.is_authenticated : return redirect('mylogin') # login check end perm = 0 for i in request.user.groups.all(): if i.name == "masteruser" : perm = 1 if perm == 0 : a = News.objects.get(pk=pk).w...
def comments_confirme(request,pk): # login check start
if not request.user.is_authenticated : return redirect('mylogin') # login check end perm = 0 for i in request.user.groups.all(): if i.name == "masteruser" : perm = 1 if perm == 0 : a = News.objects.get(pk=pk).writer if str(a) != str(request.user) : error...
.user) : error = "Access Denied" return render(request, 'back/error.html' , {'error':error}) comment = Comment.objects.filter(pk=pk) comment.delete() return redirect('comments_list') def comments_confirme(request,pk): # login check start
64
64
149
15
49
dchacca/DjangoOnline
myweb/myproject/comment/views.py
Python
comments_confirme
comments_confirme
108
130
108
110
f6136791f3b9ce621fb5c3e6bbc70345ba6798b9
bigcode/the-stack
train
c393c515b8eac958d6305ff9
train
function
def comments_del(request,pk): # login check start if not request.user.is_authenticated : return redirect('mylogin') # login check end perm = 0 for i in request.user.groups.all(): if i.name == "masteruser" : perm = 1 if perm == 0 : a = News.objects.get(pk=pk).writer...
def comments_del(request,pk): # login check start
if not request.user.is_authenticated : return redirect('mylogin') # login check end perm = 0 for i in request.user.groups.all(): if i.name == "masteruser" : perm = 1 if perm == 0 : a = News.objects.get(pk=pk).writer if str(a) != str(request.user) : error...
: error = "Access Denied" return render(request, 'back/error.html' , {'error':error}) comment = Comment.objects.all() return render(request, 'back/comments_list.html', {'comment':comment}) def comments_del(request,pk): # login check start
63
64
141
14
49
dchacca/DjangoOnline
myweb/myproject/comment/views.py
Python
comments_del
comments_del
84
105
84
86
85c69c287c180b7033150f5ec9a1ae992c7c62d9
bigcode/the-stack
train
6d96f1a35a04a0022c54f879
train
class
class GetDocumentUrlRes(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (...
class GetDocumentUrlRes(object):
"""NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name ...
# coding: utf-8 """ Pdf4me No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: v1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class G...
87
182
608
7
79
pdf4me/pdf4me-clientapi-python
pdf4me/Pdf4mePythonClientApi/pdf4me/model/get_document_url_res.py
Python
GetDocumentUrlRes
GetDocumentUrlRes
20
115
20
20
67903f0df46c4d9a1e0ad26961f2c8f4b0262f79
bigcode/the-stack
train
ed7e1a1d3a1ccb6557a50941
train
function
def main(): django.setup() t = Template('''<!DOCTYPE HTML> <html> <head> <title>Issues with more indexed pages than total pages</title> <meta charset='utf-8'> <link rel='stylesheet' href='style.css' type='text/css'> </head> <body> {% spaceless %} <h1>Issues with more indexed pages than total pages</h1> <p...
def main():
django.setup() t = Template('''<!DOCTYPE HTML> <html> <head> <title>Issues with more indexed pages than total pages</title> <meta charset='utf-8'> <link rel='stylesheet' href='style.css' type='text/css'> </head> <body> {% spaceless %} <h1>Issues with more indexed pages than total pages</h1> <p>{{ issue_li...
# -*- coding: utf-8 -*- import django from apps.gcd.models import Issue from apps.gcd.models.story import STORY_TYPES from django.db.models import Sum, F from django.template import Template, Context def main():
49
111
371
3
45
adia/gcd-stat-scripts
page-count-report.py
Python
main
main
9
42
9
9
a191c12bccae52e611042170b5e956bae864e86a
bigcode/the-stack
train
c30b25b1060b66af6d75419f
train
function
def optstring_to_list(options, flag): str_value = options.ensure_value(flag, "") list_values = [] if str_value != "": list_values = str_value.split(",") return list_values
def optstring_to_list(options, flag):
str_value = options.ensure_value(flag, "") list_values = [] if str_value != "": list_values = str_value.split(",") return list_values
is not a valid placetype, skipping") continue yield pt # elif options.roles: else: for pt in mapzen.whosonfirst.placetypes.with_roles(['common', 'common_optional', 'optional']): yield pt def optstring_to_list(options, flag):
64
64
44
9
54
whosonfirst/py-mapzen-whosonfirst-placetypes-utils
mapzen/whosonfirst/placetypes/utils/__init__.py
Python
optstring_to_list
optstring_to_list
44
52
44
45
1f935da5216949ee34c22a90b73538629a4d8c35
bigcode/the-stack
train
137d6630e9da175861bcd703
train
function
def placetypes_from_flags_unfiltered(options, **kwargs): placetypes_flag = kwargs.get('placetypes_flag', 'placetypes') roles_flag = kwargs.get('roles_flag', 'roles') placetypes = optstring_to_list(options, placetypes_flag) if len(placetypes): for pt in placetypes: pt = pt.strip()...
def placetypes_from_flags_unfiltered(options, **kwargs):
placetypes_flag = kwargs.get('placetypes_flag', 'placetypes') roles_flag = kwargs.get('roles_flag', 'roles') placetypes = optstring_to_list(options, placetypes_flag) if len(placetypes): for pt in placetypes: pt = pt.strip() if not mapzen.whosonfirst.placetypes.is_vali...
ignore_flag = kwargs.get('ignore_flag', 'ignore') ignore = optstring_to_list(options, ignore_flag) for pt in placetypes_from_flags_unfiltered(options, **kwargs): if not pt in ignore: yield pt def placetypes_from_flags_unfiltered(options, **kwargs):
64
64
163
13
50
whosonfirst/py-mapzen-whosonfirst-placetypes-utils
mapzen/whosonfirst/placetypes/utils/__init__.py
Python
placetypes_from_flags_unfiltered
placetypes_from_flags_unfiltered
19
42
19
20
8861d3e7389201707b3924a61e373f88a1ef9ddb
bigcode/the-stack
train
54d1b6d383263facbd98c6ff
train
function
def placetypes_from_options(options, **kwargs): ignore_flag = kwargs.get('ignore_flag', 'ignore') ignore = optstring_to_list(options, ignore_flag) for pt in placetypes_from_flags_unfiltered(options, **kwargs): if not pt in ignore: yield pt
def placetypes_from_options(options, **kwargs):
ignore_flag = kwargs.get('ignore_flag', 'ignore') ignore = optstring_to_list(options, ignore_flag) for pt in placetypes_from_flags_unfiltered(options, **kwargs): if not pt in ignore: yield pt
hosted.org/setuptools/setuptools.html#namespace-packages __import__('pkg_resources').declare_namespace(__name__) import mapzen.whosonfirst.placetypes import logging # options is assumed to be a optparse.OptionParser thingy def placetypes_from_options(options, **kwargs):
64
64
63
11
52
whosonfirst/py-mapzen-whosonfirst-placetypes-utils
mapzen/whosonfirst/placetypes/utils/__init__.py
Python
placetypes_from_options
placetypes_from_options
9
17
9
10
f4ab03b232b10c8cd64f71ae01eab05c9e2284ab
bigcode/the-stack
train
21489eebb70bb104040f55c1
train
function
def f_gold ( n ) : res = n for j in range ( len ( n ) - 1 , - 1 , - 1 ) : res += n [ j ] return res
def f_gold ( n ) :
res = n for j in range ( len ( n ) - 1 , - 1 , - 1 ) : res += n [ j ] return res
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( n ) :
53
64
46
7
46
mxl1n/CodeGen
data/transcoder_evaluation_gfg/python/NTH_EVEN_LENGTH_PALINDROME.py
Python
f_gold
f_gold
7
11
7
7
f1d53d3bb8d4fe583fca9d8a906cc935a1b34e16
bigcode/the-stack
train
29a7c8fc2fcf69937dfb7ce4
train
function
@app.errorhandler(404) def page_not_found(e): return redirect("/", code=302)
@app.errorhandler(404) def page_not_found(e):
return redirect("/", code=302)
/ ') response = horoscope_info(sign=sign, day=day, tz=timezone) return response, 200 except Exception as e: logger.error("{}".format(e)) return {'message': str(e)}, 400 @app.errorhandler(404) def page_not_found(e):
64
64
20
12
51
asdfgallardo/horoscopejs
app.py
Python
page_not_found
page_not_found
46
48
46
47
c1acda9ed68e69ca445a460fe6e4cb7701a8a65d
bigcode/the-stack
train
b80ed4d12d9c229c5b5ec161
train
class
class API(Resource): def get(self): # Source: https://github.com/sameerkumar18/aztro-landing-page return make_response( requests.get('https://cdn.jsdelivr.net/gh/sameerkumar18/aztro-landing-page/index.html').text) def post(self): sign = request.args['sign'].lower() d...
class API(Resource):
def get(self): # Source: https://github.com/sameerkumar18/aztro-landing-page return make_response( requests.get('https://cdn.jsdelivr.net/gh/sameerkumar18/aztro-landing-page/index.html').text) def post(self): sign = request.args['sign'].lower() day = request.args.get...
urus', 'gemini', 'cancer', 'leo', 'virgo', 'libra', 'scorpio', 'sagittarius', 'capricorn', 'aquarius', 'pisces' ] days = [ 'today', 'tomorrow', 'yesterday' ] class API(Resource):
64
64
192
4
60
asdfgallardo/horoscopejs
app.py
Python
API
API
25
43
25
25
9479f658ba08691ed3e4d2939483068becf3663d
bigcode/the-stack
train
a8777402866026e379b5b185
train
class
class AliasedGroup(click.Group): """This subclass of a group supports looking up aliases in a config file and with a bit of magic. """ def get_command(self, ctx, cmd_name): # Step one: bulitin commands as normal rv = click.Group.get_command(self, ctx, cmd_name) if rv is not None...
class AliasedGroup(click.Group):
"""This subclass of a group supports looking up aliases in a config file and with a bit of magic. """ def get_command(self, ctx, cmd_name): # Step one: bulitin commands as normal rv = click.Group.get_command(self, ctx, cmd_name) if rv is not None: return rv ...
SectionError: pass def write_config(self, filename): parser = configparser.RawConfigParser() parser.add_section("aliases") for key, value in self.aliases.items(): parser.set("aliases", key, value) with open(filename, "wb") as file: parser.write(fi...
87
87
290
7
80
D4N/asyncclick
examples/aliases/aliases.py
Python
AliasedGroup
AliasedGroup
41
72
41
41
80c5877c58a70334d19844472e4924cff50b3c19
bigcode/the-stack
train
83348321228cd013a5bfcf70
train
function
@cli.command() @pass_config @click.argument("alias_", metavar="ALIAS", type=click.STRING) @click.argument("cmd", type=click.STRING) @click.option( "--config_file", type=click.Path(exists=True, dir_okay=False), default="aliases.ini" ) def alias(config, alias_, cmd, config_file): """Adds an alias to the specified...
@cli.command() @pass_config @click.argument("alias_", metavar="ALIAS", type=click.STRING) @click.argument("cmd", type=click.STRING) @click.option( "--config_file", type=click.Path(exists=True, dir_okay=False), default="aliases.ini" ) def alias(config, alias_, cmd, config_file):
"""Adds an alias to the specified configuration file.""" config.add_alias(alias_, cmd) config.write_config(config_file) click.echo("Added '{}' as alias for '{}'".format(alias_, cmd))
@cli.command() @pass_config @click.argument("alias_", metavar="ALIAS", type=click.STRING) @click.argument("cmd", type=click.STRING) @click.option( "--config_file", type=click.Path(exists=True, dir_okay=False), default="aliases.ini" ) def alias(config, alias_, cmd, config_file):
71
64
113
71
0
D4N/asyncclick
examples/aliases/aliases.py
Python
alias
alias
131
142
131
138
d2007bef95758b814c89c8ab0adfcd17edc5ec0a
bigcode/the-stack
train
5dd5cbedd220c63a7c6380c0
train
function
@cli.command() def push(): """Pushes changes.""" click.echo("Push")
@cli.command() def push():
"""Pushes changes.""" click.echo("Push")
( "--config", type=click.Path(exists=True, dir_okay=False), callback=read_config, expose_value=False, help="The config file to use instead of the default.", ) def cli(): """An example application that supports aliases.""" @cli.command() def push():
63
64
19
7
56
D4N/asyncclick
examples/aliases/aliases.py
Python
push
push
100
103
100
101
8933428e7edef382a049dd7c6f9fa4ae396a1efc
bigcode/the-stack
train
10f5c52c38999ffb840f5aac
train
class
class Config(object): """The config in this example only holds aliases.""" def __init__(self): self.path = os.getcwd() self.aliases = {} def add_alias(self, alias, cmd): self.aliases.update({alias: cmd}) def read_config(self, filename): parser = configparser.RawConfigP...
class Config(object):
"""The config in this example only holds aliases.""" def __init__(self): self.path = os.getcwd() self.aliases = {} def add_alias(self, alias, cmd): self.aliases.update({alias: cmd}) def read_config(self, filename): parser = configparser.RawConfigParser() parser...
import os import asyncclick as click try: import configparser except ImportError: import ConfigParser as configparser class Config(object):
34
64
163
4
29
D4N/asyncclick
examples/aliases/aliases.py
Python
Config
Config
11
35
11
11
980f4b8ecb99a463e606c6e73f40e10cb9215352
bigcode/the-stack
train
f4980871625737832b98f449
train
function
@cli.command() @pass_config def status(config): """Shows the status.""" click.echo("Status for {}".format(config.path))
@cli.command() @pass_config def status(config):
"""Shows the status.""" click.echo("Status for {}".format(config.path))
"""Pulls changes.""" click.echo("Pull") @cli.command() def clone(): """Clones a repository.""" click.echo("Clone") @cli.command() def commit(): """Commits pending changes.""" click.echo("Commit") @cli.command() @pass_config def status(config):
64
64
29
12
52
D4N/asyncclick
examples/aliases/aliases.py
Python
status
status
124
128
124
126
f00465ace9070fea5c5157764fc958923049fed5
bigcode/the-stack
train
b19b48d766d9eaa0e66939bd
train
function
@cli.command() def pull(): """Pulls changes.""" click.echo("Pull")
@cli.command() def pull():
"""Pulls changes.""" click.echo("Pull")
callback=read_config, expose_value=False, help="The config file to use instead of the default.", ) def cli(): """An example application that supports aliases.""" @cli.command() def push(): """Pushes changes.""" click.echo("Push") @cli.command() def pull():
64
64
19
7
57
D4N/asyncclick
examples/aliases/aliases.py
Python
pull
pull
106
109
106
107
06c38508ddf07c54b96a3556b3004c9c58542656
bigcode/the-stack
train
6d0d5ade0a44756bd97d61ec
train
function
@click.command(cls=AliasedGroup) @click.option( "--config", type=click.Path(exists=True, dir_okay=False), callback=read_config, expose_value=False, help="The config file to use instead of the default.", ) def cli(): """An example application that supports aliases."""
@click.command(cls=AliasedGroup) @click.option( "--config", type=click.Path(exists=True, dir_okay=False), callback=read_config, expose_value=False, help="The config file to use instead of the default.", ) def cli():
"""An example application that supports aliases."""
_config(value) return value @click.command(cls=AliasedGroup) @click.option( "--config", type=click.Path(exists=True, dir_okay=False), callback=read_config, expose_value=False, help="The config file to use instead of the default.", ) def cli():
64
64
66
57
6
D4N/asyncclick
examples/aliases/aliases.py
Python
cli
cli
88
97
88
96
d57e2ed135ee27ff0cee9573db9f0e181f37ff64
bigcode/the-stack
train
38f346adf35485ec81338958
train
function
@cli.command() def clone(): """Clones a repository.""" click.echo("Clone")
@cli.command() def clone():
"""Clones a repository.""" click.echo("Clone")
instead of the default.", ) def cli(): """An example application that supports aliases.""" @cli.command() def push(): """Pushes changes.""" click.echo("Push") @cli.command() def pull(): """Pulls changes.""" click.echo("Pull") @cli.command() def clone():
64
64
20
7
57
D4N/asyncclick
examples/aliases/aliases.py
Python
clone
clone
112
115
112
113
044d89525ecd55ce1615d3c4ae9b8eb4a1243776
bigcode/the-stack
train
47cb5424192803a05adb03f8
train
function
@cli.command() def commit(): """Commits pending changes.""" click.echo("Commit")
@cli.command() def commit():
"""Commits pending changes.""" click.echo("Commit")
cli.command() def push(): """Pushes changes.""" click.echo("Push") @cli.command() def pull(): """Pulls changes.""" click.echo("Pull") @cli.command() def clone(): """Clones a repository.""" click.echo("Clone") @cli.command() def commit():
64
64
20
7
57
D4N/asyncclick
examples/aliases/aliases.py
Python
commit
commit
118
121
118
119
d58ce073b500441556b92f2cba8d893360d732c7
bigcode/the-stack
train
f5d0f224a89ba03b12ae5a09
train
function
def read_config(ctx, param, value): """Callback that is used whenever --config is passed. We use this to always load the correct config. This means that the config is loaded even if the group itself never executes so our aliases stay always available. """ cfg = ctx.ensure_object(Config) if...
def read_config(ctx, param, value):
"""Callback that is used whenever --config is passed. We use this to always load the correct config. This means that the config is loaded even if the group itself never executes so our aliases stay always available. """ cfg = ctx.ensure_object(Config) if value is None: value = os.p...
(cmd_name.lower()) ] if not matches: return None elif len(matches) == 1: return click.Group.get_command(self, ctx, matches[0]) ctx.fail("Too many matches: {}".format(", ".join(sorted(matches)))) def read_config(ctx, param, value):
63
64
102
9
54
D4N/asyncclick
examples/aliases/aliases.py
Python
read_config
read_config
75
85
75
75
ebda13150fb2d1c1c4df95aefdb9445b2d2d12e5
bigcode/the-stack
train
722d9327e4ebed84c2731fe9
train
class
class Lineage(chainer.training.Extension): def __init__(self, comm, trigger=(1, 'epoch')): self.log_report = chainer.training.extensions.LogReport(trigger=trigger) self.comm = comm self.trigger = trigger # extention class property self.comm.load_state_reliable("lineage", self.log_rep...
class Lineage(chainer.training.Extension):
def __init__(self, comm, trigger=(1, 'epoch')): self.log_report = chainer.training.extensions.LogReport(trigger=trigger) self.comm = comm self.trigger = trigger # extention class property self.comm.load_state_reliable("lineage", self.log_report) print("first lineage!!!!") ...
suspention mode? self.comm.tick() def finalize(self): pass def initialize(self): pass def serialize(self): pass def on_error(self, trainer, exc, tb): pass def tick(self): pass class Lineage(chainer.training.Extension):
64
64
158
8
55
pfnet-research/echainer
echainer/extension.py
Python
Lineage
Lineage
32
55
32
32
7366d3d2eb93daccf3d5902dc074a8f3a8105131
bigcode/the-stack
train
fdf938f0bbe56f8aff99cd87
train
class
class FailureDetector(chainer.training.Extension): '''An object to Detect Local computing resource failure Check the tick of each iteration''' def __init__(self, comm): self.comm = comm def __call__(self, _trainer): self.tick() # Check the communicator still alive and not in su...
class FailureDetector(chainer.training.Extension):
'''An object to Detect Local computing resource failure Check the tick of each iteration''' def __init__(self, comm): self.comm = comm def __call__(self, _trainer): self.tick() # Check the communicator still alive and not in suspention mode? self.comm.tick() def fi...
import chainer from chainer.training import trigger as trigger_module class FailureDetector(chainer.training.Extension):
22
64
122
8
13
pfnet-research/echainer
echainer/extension.py
Python
FailureDetector
FailureDetector
4
29
4
4
feb2558a99f1d6230e01064d81dba4ff4b5bcee3
bigcode/the-stack
train
bc5e0d6672347664bf4df9a0
train
function
def eval_energy_default(node): dtype = node['dtype'] if dtype is None: dtype = 'float32' energy_compute = node['flops'] * get_energy_cost(dtype, 'mult') total_mem = (node['mem_r'] + node['mem_w']) sram_rw = total_mem * cache_hit_rate dram_rw = total_mem * (1 - cache_hit_rate) energy_...
def eval_energy_default(node):
dtype = node['dtype'] if dtype is None: dtype = 'float32' energy_compute = node['flops'] * get_energy_cost(dtype, 'mult') total_mem = (node['mem_r'] + node['mem_w']) sram_rw = total_mem * cache_hit_rate dram_rw = total_mem * (1 - cache_hit_rate) energy_memory = dram_rw * get_energy_c...
cache_hit_rate = 0.8 def get_energy_cost(dtype, key): return energy_cost_table.get('{}_{}'.format(dtype, key), None) def set_energy_cost(dtype, key, val): energy_cost_table['{}_{}'.format(dtype, key)] = val def eval_energy_default(node):
64
64
130
6
57
CreeperLin/RASP
rasp/addons/energy.py
Python
eval_energy_default
eval_energy_default
41
52
41
41
8a07c26edd0122929b727bdea81e8b3fb176acc3
bigcode/the-stack
train
3e4a6914456dd9e3010ad34f
train
function
def set_energy_cost(dtype, key, val): energy_cost_table['{}_{}'.format(dtype, key)] = val
def set_energy_cost(dtype, key, val):
energy_cost_table['{}_{}'.format(dtype, key)] = val
_sram': 5.0, 'float32_dram': 640.0, } cache_hit_rate = 0.8 def get_energy_cost(dtype, key): return energy_cost_table.get('{}_{}'.format(dtype, key), None) def set_energy_cost(dtype, key, val):
64
64
25
10
54
CreeperLin/RASP
rasp/addons/energy.py
Python
set_energy_cost
set_energy_cost
37
38
37
37
ecd2ad413367fad9440b6d77fe2558ead2738ec4
bigcode/the-stack
train
4682134dde14f288cc664486
train
function
def get_energy_cost(dtype, key): return energy_cost_table.get('{}_{}'.format(dtype, key), None)
def get_energy_cost(dtype, key):
return energy_cost_table.get('{}_{}'.format(dtype, key), None)
32_l2cache': 30.2, 'float32_chipdram': 160.0, 'float32_sram': 5.0, 'float32_dram': 640.0, } cache_hit_rate = 0.8 def get_energy_cost(dtype, key):
64
64
24
8
55
CreeperLin/RASP
rasp/addons/energy.py
Python
get_energy_cost
get_energy_cost
33
34
33
33
a4ec2c7f599f009968255606249d6665dbb9fd01
bigcode/the-stack
train
b6c8558ca4b2d1f5d311a0c1
train
class
class ConvolveByX(LinearOperator): """A LinearOperator that performs convolution as a function of the first argument. The LinearOperator ConvolveByX(x=x)(y) implements jax.scipy.signal.convolve(x, y). """ def __init__( self, x: JaxArray, input_shape: Shape, input_dtype:...
class ConvolveByX(LinearOperator):
"""A LinearOperator that performs convolution as a function of the first argument. The LinearOperator ConvolveByX(x=x)(y) implements jax.scipy.signal.convolve(x, y). """ def __init__( self, x: JaxArray, input_shape: Shape, input_dtype: DType = np.float32, mode: ...
}") @_wrap_mul_div_scalar def __mul__(self, scalar): return Convolve( h=self.h * scalar, input_shape=self.input_shape, input_dtype=result_type(self.input_dtype, type(scalar)), mode=self.mode, output_shape=self.output_shape, adj_fn=...
256
256
1,071
9
247
lukepfister/scico
scico/linop/_convolve.py
Python
ConvolveByX
ConvolveByX
156
284
156
156
93f2db3de83836ae491ac650ce23a1a0e9cf4199
bigcode/the-stack
train
1fe6e8d6c555a6fb0139fcb0
train
class
class Convolve(LinearOperator): """A convolution linear operator.""" def __init__( self, h: JaxArray, input_shape: Shape, input_dtype: DType = np.float32, mode: str = "full", jit: bool = True, **kwargs, ): r""" Wraps :func:`jax.scipy.s...
class Convolve(LinearOperator):
"""A convolution linear operator.""" def __init__( self, h: JaxArray, input_shape: Shape, input_dtype: DType = np.float32, mode: str = "full", jit: bool = True, **kwargs, ): r""" Wraps :func:`jax.scipy.signal.convolve` as a :class:`.Li...
# -*- coding: utf-8 -*- # Copyright (C) 2020-2021 by SCICO Developers # All rights reserved. BSD 3-clause License. # This file is part of the SCICO package. Details of the copyright and # user license can be found in the 'LICENSE' file distributed with the # package. """Convolution linear operator class.""" # needed...
241
256
997
7
234
lukepfister/scico
scico/linop/_convolve.py
Python
Convolve
Convolve
33
153
33
33
d06aa3e4d2442ad24832908adb2c779683c3041a
bigcode/the-stack
train
5ec5455e94cf0c6cf8d55a53
train
function
def get_monitor_default_key(monitor_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetMonitorDefaultKeyResult: """ API Version: 2021-03-01. :param str monitor_name: Moni...
def get_monitor_default_key(monitor_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetMonitorDefaultKeyResult:
""" API Version: 2021-03-01. :param str monitor_name: Monitor resource name :param str resource_group_name: The name of the resource group. The name is case insensitive. """ __args__ = dict() __args__['monitorName'] = monitor_name __args__['resourceGroupName'] = resource_group_name ...
Result( created=self.created, created_by=self.created_by, key=self.key, name=self.name) def get_monitor_default_key(monitor_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi...
72
72
241
48
24
sebtelko/pulumi-azure-native
sdk/python/pulumi_azure_native/datadog/get_monitor_default_key.py
Python
get_monitor_default_key
get_monitor_default_key
78
101
78
80
a349e1ad1d13eda8ef1a5143c8f98dcf589570dd
bigcode/the-stack
train
eedaa630c961aa11191f4473
train
class
class AwaitableGetMonitorDefaultKeyResult(GetMonitorDefaultKeyResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetMonitorDefaultKeyResult( created=self.created, created_by=self.created_by, key=self.key...
class AwaitableGetMonitorDefaultKeyResult(GetMonitorDefaultKeyResult): # pylint: disable=using-constant-test
def __await__(self): if False: yield self return GetMonitorDefaultKeyResult( created=self.created, created_by=self.created_by, key=self.key, name=self.name)
@pulumi.getter def name(self) -> Optional[str]: """ The name of the API key. """ return pulumi.get(self, "name") class AwaitableGetMonitorDefaultKeyResult(GetMonitorDefaultKeyResult): # pylint: disable=using-constant-test
64
64
70
25
39
sebtelko/pulumi-azure-native
sdk/python/pulumi_azure_native/datadog/get_monitor_default_key.py
Python
AwaitableGetMonitorDefaultKeyResult
AwaitableGetMonitorDefaultKeyResult
66
75
66
67
d2b5bcb34ba40d21b82de792e67c41952777bd35
bigcode/the-stack
train
2fcb727e92bea6971246b33c
train
class
@pulumi.output_type class GetMonitorDefaultKeyResult: def __init__(__self__, created=None, created_by=None, key=None, name=None): if created and not isinstance(created, str): raise TypeError("Expected argument 'created' to be a str") pulumi.set(__self__, "created", created) if cr...
@pulumi.output_type class GetMonitorDefaultKeyResult:
def __init__(__self__, created=None, created_by=None, key=None, name=None): if created and not isinstance(created, str): raise TypeError("Expected argument 'created' to be a str") pulumi.set(__self__, "created", created) if created_by and not isinstance(created_by, str): ...
this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = [ 'GetMonitorDefau...
108
108
363
13
95
sebtelko/pulumi-azure-native
sdk/python/pulumi_azure_native/datadog/get_monitor_default_key.py
Python
GetMonitorDefaultKeyResult
GetMonitorDefaultKeyResult
17
63
17
18
7fcbcda709213a4fa41fa8692b35e615eed91873
bigcode/the-stack
train
69f69a35422275bb6842149d
train
class
class DarthVader: def SayName(self): print("DarthVader: If You Will Not Turn To The Dark Side, Then Perhaps She Will!.")
class DarthVader:
def SayName(self): print("DarthVader: If You Will Not Turn To The Dark Side, Then Perhaps She Will!.")
class DarthVader:
5
64
35
5
0
Axe1701/say_my_name_acm
characters/DarthVader.py
Python
DarthVader
DarthVader
1
3
1
1
68bc8c881a06d692fd11f1f89b285535ad1b029c
bigcode/the-stack
train
2ce62c51d791faed9ef0408b
train
function
def project_context(request): return { 'project_name': settings.PROJECT_NAME, 'site': Site.objects.get_current(), }
def project_context(request):
return { 'project_name': settings.PROJECT_NAME, 'site': Site.objects.get_current(), }
from django.conf import settings from django.contrib.sites.models import Site def project_context(request):
20
64
29
5
14
openpolis/op-accesso
project/accesso/contexts.py
Python
project_context
project_context
5
9
5
5
becd2a264de5a1551c9cd8928230379dff2badbe
bigcode/the-stack
train
55d9c2c44673d4877283859c
train
class
class Cert_8_1_01_Commissioning(thread_cert.TestCase): SUPPORT_NCP = False TOPOLOGY = { COMMISSIONER: { 'masterkey': '00112233445566778899aabbccddeeff', 'mode': 'rdn', 'panid': 0xface }, JOINER: { 'masterkey': 'deadbeefdeadbeefdeadbeefdead...
class Cert_8_1_01_Commissioning(thread_cert.TestCase):
SUPPORT_NCP = False TOPOLOGY = { COMMISSIONER: { 'masterkey': '00112233445566778899aabbccddeeff', 'mode': 'rdn', 'panid': 0xface }, JOINER: { 'masterkey': 'deadbeefdeadbeefdeadbeefdeadbeef', 'mode': 'rdn', 'router_s...
nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # ...
256
256
1,057
16
239
nodish/openthread
tests/scripts/thread-cert/Cert_8_1_01_Commissioning.py
Python
Cert_8_1_01_Commissioning
Cert_8_1_01_Commissioning
43
139
43
43
55612000a66ba60683e8aa6c4c26140c532d942a
bigcode/the-stack
train
352789d6110bdd1e71340ed8
train
function
def full_split(path, result=None): """ Split a pathname into components (the opposite of os.path.join) in a platform-neutral way. """ if result is None: result = [] head, tail = os.path.split(path) if head == '': return [tail] + result if head == path: return resu...
def full_split(path, result=None):
""" Split a pathname into components (the opposite of os.path.join) in a platform-neutral way. """ if result is None: result = [] head, tail = os.path.split(path) if head == '': return [tail] + result if head == path: return result return full_split(head, [tai...
package. from distutils.command.install import INSTALL_SCHEMES for scheme in INSTALL_SCHEMES.values(): scheme['data'] = scheme['purelib'] try: long_description = open("README.rst").read() except IOError: long_description = "" def full_split(path, result=None):
63
64
89
8
55
gem/django-extras
setup.py
Python
full_split
full_split
18
30
18
18
1767015bba09f98eac2446ee79307e3f31ed6464
bigcode/the-stack
train
e7583ea80666713a6ed0c343
train
function
def check_key_columns(workflow: Workflow): """Check that key columns maintain their property. Function used to verify that after changes in the DB the key columns maintain their property. :param workflow: Object to use for the verification. :return: Nothing. Raise exception if key column lost the...
def check_key_columns(workflow: Workflow):
"""Check that key columns maintain their property. Function used to verify that after changes in the DB the key columns maintain their property. :param workflow: Object to use for the verification. :return: Nothing. Raise exception if key column lost the property. """ col_name = next( ...
database add_column_to_db( workflow.get_data_frame_table_name(), new_column.name, new_column.data_type) copy_column_in_db( workflow.get_data_frame_table_name(), column.name, new_column.name) return new_column def check_key_columns(workflow: Workflow):
64
64
144
9
54
LucasFranciscoCorreia/ontask_b
ontask/workflow/ops.py
Python
check_key_columns
check_key_columns
238
256
238
238
e67ce63708edffa7bebdc99e4ba4a22e6c4c69e0
bigcode/the-stack
train
74d815e98104cf112125343d
train
function
def do_workflow_update_lusers(workflow: Workflow, log_item: Log): """Recalculate the field lusers. Recalculate the elements in the field lusers of the workflow based on the fields luser_email_column and luser_email_column_MD5 :param workflow: Workflow to update :param log_item: Log where to leave...
def do_workflow_update_lusers(workflow: Workflow, log_item: Log):
"""Recalculate the field lusers. Recalculate the elements in the field lusers of the workflow based on the fields luser_email_column and luser_email_column_MD5 :param workflow: Workflow to update :param log_item: Log where to leave the status of the operation :return: Changes in the lusers M...
(data_frame[column.name].dropna()) if not cat_values: # Column has no meaningful values. Nothing to do. return _('Column has no meaningful values') # Set categories column.set_categories(list(cat_values)) column.save() # Re-evaluate the operands in the workflow column.workflow....
102
102
340
17
84
LucasFranciscoCorreia/ontask_b
ontask/workflow/ops.py
Python
do_workflow_update_lusers
do_workflow_update_lusers
117
163
117
117
b4b0935aa441463e6fa0c37b1576507dc1fc1f5c
bigcode/the-stack
train
86acd54d33dbfb6eebf076da
train
function
def do_clone_column_only( column: Column, new_workflow: Optional[Workflow] = None, new_name: Optional[str] = None, ) -> Column: """Clone a column. :param column: Object to clone. :param new_workflow: Optional new worklow object to link to. :param new_name: Optional new name to use. :...
def do_clone_column_only( column: Column, new_workflow: Optional[Workflow] = None, new_name: Optional[str] = None, ) -> Column:
"""Clone a column. :param column: Object to clone. :param new_workflow: Optional new worklow object to link to. :param new_name: Optional new name to use. :result: New object. """ if new_name is None: new_name = column.name if new_workflow is None: new_workflow = colu...
log_item.payload['status'] = ugettext( 'Learner emails successfully updated.', ) log_item.save() def do_clone_column_only( column: Column, new_workflow: Optional[Workflow] = None, new_name: Optional[str] = None, ) -> Column:
64
64
212
37
27
LucasFranciscoCorreia/ontask_b
ontask/workflow/ops.py
Python
do_clone_column_only
do_clone_column_only
166
199
166
170
fbe683fcc55031119d3cbefe06adf4d182d99409
bigcode/the-stack
train
1be012b3221b2e3b6a627a5c
train
function
def workflow_delete_column( workflow: Workflow, column: Column, cond_to_delete: Optional[List[Condition]] = None, ): """Remove column from ontask.workflow. Given a workflow and a column, removes it from the workflow (and the corresponding data frame :param workflow: Workflow object :p...
def workflow_delete_column( workflow: Workflow, column: Column, cond_to_delete: Optional[List[Condition]] = None, ):
"""Remove column from ontask.workflow. Given a workflow and a column, removes it from the workflow (and the corresponding data frame :param workflow: Workflow object :param column: Column object to delete :param cond_to_delete: List of conditions to delete after removing the column ...
import get_user_model from django.utils.crypto import get_random_string from django.utils.translation import ugettext, ugettext_lazy as _ from ontask import create_new_name from ontask.dataops.pandas import load_table from ontask.dataops.sql import ( add_column_to_db, copy_column_in_db, df_drop_column, get_rows, ...
130
130
435
29
100
LucasFranciscoCorreia/ontask_b
ontask/workflow/ops.py
Python
workflow_delete_column
workflow_delete_column
23
83
23
27
0d80c70a0b4e02b7eac9970b73062193a2873a9a
bigcode/the-stack
train
44c0e6e6386436533b58a66a
train
function
def clone_wf_column(column: Column) -> Column: """Create a clone of a column. :param column: Object to clone :return: Cloned object (DF has an additional column as well """ workflow = column.workflow new_column = do_clone_column_only( column, new_name=create_new_name(column.na...
def clone_wf_column(column: Column) -> Column:
"""Create a clone of a column. :param column: Object to clone :return: Cloned object (DF has an additional column as well """ workflow = column.workflow new_column = do_clone_column_only( column, new_name=create_new_name(column.name, workflow.columns)) # Update the number...
position=column.position, in_viz=column.in_viz, categories=copy.deepcopy(column.categories), active_from=column.active_from, active_to=column.active_to, ) new_column.save() return new_column def clone_wf_column(column: Column) -> Column:
64
64
194
12
51
LucasFranciscoCorreia/ontask_b
ontask/workflow/ops.py
Python
clone_wf_column
clone_wf_column
202
235
202
202
b69edb3cfc8498dcabd9586f5f2ed75feb324eb0
bigcode/the-stack
train
b4d629354a80ce298781ea9a
train
function
def workflow_restrict_column(column: Column) -> Optional[str]: """Set category of the column to the existing set of values. Given a workflow and a column, modifies the column so that only the values already present are allowed for future updates. :param column: Column object to restrict :return: ...
def workflow_restrict_column(column: Column) -> Optional[str]:
"""Set category of the column to the existing set of values. Given a workflow and a column, modifies the column so that only the values already present are allowed for future updates. :param column: Column object to restrict :return: String with error or None if correct """ # Load the dat...
# If a column disappears, the views that contain only that column need to # disappear as well as they are no longer relevant. for view in workflow.views.all(): if view.columns.count() == 0: view.delete() def workflow_restrict_column(column: Column) -> Optional[str]:
64
64
190
13
51
LucasFranciscoCorreia/ontask_b
ontask/workflow/ops.py
Python
workflow_restrict_column
workflow_restrict_column
86
114
86
86
7fb1dca29c69124e33a1fd26dbd72fb054e2ecd2
bigcode/the-stack
train
1193b15ac541a3c633a05888
train
class
class TestActorRoleListResponse(unittest.TestCase): """ ActorRoleListResponse unit test stubs """ def setUp(self): pass def tearDown(self): pass def testActorRoleListResponse(self): """ Test ActorRoleListResponse """ model = kinow_client.models.actor_ro...
class TestActorRoleListResponse(unittest.TestCase):
""" ActorRoleListResponse unit test stubs """ def setUp(self): pass def tearDown(self): pass def testActorRoleListResponse(self): """ Test ActorRoleListResponse """ model = kinow_client.models.actor_role_list_response.ActorRoleListResponse()
/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kinow_client from kinow_client.rest import ApiException from kinow_client.models.actor_role_list_response import ActorRoleListResponse class TestActorRoleListResponse(unittest.TestCase):
64
64
75
10
53
kinow-io/kaemo-python-sdk
test/test_actor_role_list_response.py
Python
TestActorRoleListResponse
TestActorRoleListResponse
25
38
25
25
979bff8fb9196e79e020d564e98b979fc12a9a1a
bigcode/the-stack
train
8f4c69e4ee61f0a2a5cc2298
train
function
def average_poses(poses): """ Calculate the average pose, which is then used to center all poses using @center_poses. Its computation is as follows: 1. Compute the center: the average of pose centers. 2. Compute the z axis: the normalized average z axis. 3. Compute axis y': the average y axis. ...
def average_poses(poses):
""" Calculate the average pose, which is then used to center all poses using @center_poses. Its computation is as follows: 1. Compute the center: the average of pose centers. 2. Compute the z axis: the normalized average z axis. 3. Compute axis y': the average y axis. 4. Compute x' = y' cros...
import torch from torch.utils.data import Dataset import glob import numpy as np import os from PIL import Image from torchvision import transforms as T from .ray_utils import * def normalize(v): """Normalize a vector.""" return v/np.linalg.norm(v) def average_poses(poses):
65
111
372
7
58
bell-one/nerf_cmu
datasets/llff.py
Python
average_poses
average_poses
17
53
17
17
9695a8b91f93085f3590327ec303eff300616126
bigcode/the-stack
train
9bfed271dd88de2a028436a0
train
function
def center_poses(poses): """ Center the poses so that we can use NDC. See https://github.com/bmild/nerf/issues/34 Inputs: poses: (N_images, 3, 4) Outputs: poses_centered: (N_images, 3, 4) the centered poses pose_avg: (3, 4) the average pose """ pose_avg = average_p...
def center_poses(poses):
""" Center the poses so that we can use NDC. See https://github.com/bmild/nerf/issues/34 Inputs: poses: (N_images, 3, 4) Outputs: poses_centered: (N_images, 3, 4) the centered poses pose_avg: (3, 4) the average pose """ pose_avg = average_poses(poses) # (3, 4) ...
x = normalize(np.cross(y_, z)) # (3) # 5. Compute the y axis (as z and x are normalized, y is already of norm 1) y = np.cross(z, x) # (3) pose_avg = np.stack([x, y, z, center], 1) # (3, 4) return pose_avg def center_poses(poses):
88
88
295
7
80
bell-one/nerf_cmu
datasets/llff.py
Python
center_poses
center_poses
56
80
56
56
f16ea5e2f18c0c22bee077f46d9e7f14a959762f
bigcode/the-stack
train
63b48b742c47dc234df38eb8
train
class
class LLFFDataset(Dataset): def __init__(self, root_dir, split='train', img_wh=(504, 378), spheric_poses=False, val_num=1): """ spheric_poses: whether the images are taken in a spheric inward-facing manner default: False (forward-facing) val_num: number of val images (...
class LLFFDataset(Dataset):
def __init__(self, root_dir, split='train', img_wh=(504, 378), spheric_poses=False, val_num=1): """ spheric_poses: whether the images are taken in a spheric inward-facing manner default: False (forward-facing) val_num: number of val images (used for multigpu training, ...
,0,0,0], [0,np.cos(phi),-np.sin(phi),0], [0,np.sin(phi), np.cos(phi),0], [0,0,0,1], ]) rot_theta = lambda th : np.array([ [np.cos(th),0,-np.sin(th),0], [0,1,0,0], [np.sin(th),0, np.cos(th),0], [0,0,0,1], ]) ...
256
256
1,866
7
249
bell-one/nerf_cmu
datasets/llff.py
Python
LLFFDataset
LLFFDataset
159
318
159
159
71798bf7f4593f68063d1dadb2197f4ed5bf2b84
bigcode/the-stack
train
3f4985362fbeb5216b3258db
train
function
def create_spiral_poses(radii, focus_depth, n_poses=120): """ Computes poses that follow a spiral path for rendering purpose. See https://github.com/Fyusion/LLFF/issues/19 In particular, the path looks like: https://tinyurl.com/ybgtfns3 Inputs: radii: (3) radii of the spiral for each ax...
def create_spiral_poses(radii, focus_depth, n_poses=120):
""" Computes poses that follow a spiral path for rendering purpose. See https://github.com/Fyusion/LLFF/issues/19 In particular, the path looks like: https://tinyurl.com/ybgtfns3 Inputs: radii: (3) radii of the spiral for each axis focus_depth: float, the depth that the spiral p...
4) poses_homo = \ np.concatenate([poses, last_row], 1) # (N_images, 4, 4) homogeneous coordinate poses_centered = np.linalg.inv(pose_avg_homo) @ poses_homo # (N_images, 4, 4) poses_centered = poses_centered[:, :3] # (N_images, 3, 4) return poses_centered, pose_avg def create_spiral_poses(radi...
114
114
380
18
95
bell-one/nerf_cmu
datasets/llff.py
Python
create_spiral_poses
create_spiral_poses
83
115
83
83
87b1773eec6f5e6474142e79464b7c7315863daf
bigcode/the-stack
train
bf5e24288426e53fb3f4d4ad
train
function
def normalize(v): """Normalize a vector.""" return v/np.linalg.norm(v)
def normalize(v):
"""Normalize a vector.""" return v/np.linalg.norm(v)
import torch from torch.utils.data import Dataset import glob import numpy as np import os from PIL import Image from torchvision import transforms as T from .ray_utils import * def normalize(v):
43
64
19
4
39
bell-one/nerf_cmu
datasets/llff.py
Python
normalize
normalize
12
14
12
12
66f79f2a4ee0512956551d8a37f4888eed78c8b2
bigcode/the-stack
train
75d545b681004405b1ac8d49
train
function
def create_spheric_poses(radius, n_poses=120): """ Create circular poses around z axis. Inputs: radius: the (negative) height and the radius of the circle. Outputs: spheric_poses: (n_poses, 3, 4) the poses in the circular path """ def spheric_pose(theta, phi, radius): tr...
def create_spheric_poses(radius, n_poses=120):
""" Create circular poses around z axis. Inputs: radius: the (negative) height and the radius of the circle. Outputs: spheric_poses: (n_poses, 3, 4) the poses in the circular path """ def spheric_pose(theta, phi, radius): trans_t = lambda t : np.array([ [1,0,...
axes as in @average_poses y_ = np.array([0, 1, 0]) # (3) x = normalize(np.cross(y_, z)) # (3) y = np.cross(z, x) # (3) poses_spiral += [np.stack([x, y, z, center], 1)] # (3, 4) return np.stack(poses_spiral, 0) # (n_poses, 3, 4) def create_spheric_poses(radius, n_poses=120):
119
119
398
14
105
bell-one/nerf_cmu
datasets/llff.py
Python
create_spheric_poses
create_spheric_poses
118
156
118
118
7dface657c560eb2721558cb1456d6662a81cc3c
bigcode/the-stack
train
db17e138cc4f72f75f5cb626
train
class
class CategoryNameMapIterator(APIObject,IDisposable,IEnumerator): """ An iterator to a category name map. CategoryNameMapIterator() """ def Dispose(self): """ Dispose(self: CategoryNameMapIterator,A_0: bool) """ pass def MoveNext(self): """ MoveNext(self: CategoryNameMapIterator) -> bool ...
class CategoryNameMapIterator(APIObject,IDisposable,IEnumerator):
""" An iterator to a category name map. CategoryNameMapIterator() """ def Dispose(self): """ Dispose(self: CategoryNameMapIterator,A_0: bool) """ pass def MoveNext(self): """ MoveNext(self: CategoryNameMapIterator) -> bool Move the iterator one item forward. Returns: Retu...
class CategoryNameMapIterator(APIObject,IDisposable,IEnumerator):
14
142
475
14
0
htlcnn/ironpython-stubs
release/stubs.min/Autodesk/Revit/DB/__init___parts/CategoryNameMapIterator.py
Python
CategoryNameMapIterator
CategoryNameMapIterator
1
79
1
1
80b586c3328652ba5865c89296ee3d723b87b5e0
bigcode/the-stack
train
8c708a1c4c7da34878fe9b4a
train
function
def gdb_has_xmethods(): try: import gdb.xmethod return True except ImportError: return False
def gdb_has_xmethods():
try: import gdb.xmethod return True except ImportError: return False
://www.gnu.org/licenses/>. import gdb # Load the pretty-printers. from .printers import register_libstdcxx_printers register_libstdcxx_printers(gdb.current_objfile()) # Load the xmethods if GDB supports them. def gdb_has_xmethods():
64
64
30
7
57
hoastyle/lib_robot_build
toolchain/arm-openwrt-linux/share/gcc-5.2.0/python/libstdcxx/v6/__init__.py
Python
gdb_has_xmethods
gdb_has_xmethods
23
28
23
23
b2c82458fff1083c466a52cad4e6a07034f06451
bigcode/the-stack
train
9229b00c604f3d28457c1095
train
function
def in_casapy (helper, asdm=None, ms=None, tbuff=None): """This function is run inside the weirdo casapy IPython environment! A strange set of modules is available, and the `pwkit.environments.casa.scripting` system sets up a very particular environment to allow encapsulated scripting. """ if a...
def in_casapy (helper, asdm=None, ms=None, tbuff=None):
"""This function is run inside the weirdo casapy IPython environment! A strange set of modules is available, and the `pwkit.environments.casa.scripting` system sets up a very particular environment to allow encapsulated scripting. """ if asdm is None: raise ValueError ('asdm') if ms...
file is a casapy script. Do not use it as a module. It is also not intended to be invoked directly through pkcasascript. See `pwkit.environments.casa.tasks.importevla`. """ def in_casapy (helper, asdm=None, ms=None, tbuff=None):
64
64
172
19
45
pkgw/pwk
pwkit/environments/casa/cscript_importevla.py
Python
in_casapy
in_casapy
12
28
12
12
1c10a08f3d795c912bfbfc3d025b7b8e808f2e3a
bigcode/the-stack
train