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
9479e6b1c51d1854538621dc
train
function
def swap_collection(fn: Callable[..., Any], col_a: str, col_b: str): """Swap two collections.""" def swap(target): a = target[col_a] if col_a in target else {} b = target[col_b] if col_b in target else {} target[col_b], target[col_a] = a, b return target return transform(fn, (col_a, col_b), swap,...
def swap_collection(fn: Callable[..., Any], col_a: str, col_b: str):
"""Swap two collections.""" def swap(target): a = target[col_a] if col_a in target else {} b = target[col_b] if col_b in target else {} target[col_b], target[col_a] = a, b return target return transform(fn, (col_a, col_b), swap, swap, mutable=True)
_in_fn, trans_out_fn=trans_out_fn, init=is_init, mutable=mutable, rngs=rngs, variables=variables) return lift_trans(scope, *args) return wrapper def swap_collection(fn: Callable[..., Any], col_a: str, col_b: str):
64
64
95
19
44
joelgarde/flax
flax/core/lift.py
Python
swap_collection
swap_collection
277
285
277
277
f82875a8c0c2badcbed41238b73851ade8879f7d
bigcode/the-stack
train
d3466dede5748243b4c11976
train
function
def named_call(fn: Callable[..., Any], name: str) -> Callable[..., Any]: """Adds a name scope to `fn` during profiling.""" def inner(scope_fn, repack_fn, variable_groups, rng_groups, args, kwargs): @functools.wraps(fn) def named(variable_groups, rng_groups): scope = scope_fn(variable_groups, rng_group...
def named_call(fn: Callable[..., Any], name: str) -> Callable[..., Any]:
"""Adds a name scope to `fn` during profiling.""" def inner(scope_fn, repack_fn, variable_groups, rng_groups, args, kwargs): @functools.wraps(fn) def named(variable_groups, rng_groups): scope = scope_fn(variable_groups, rng_groups) y = fn(scope, *args, **kwargs) return y, repack_fn(scope) ...
variable_broadcast, variable_carry, variable_axes, split_rngs) return carry, () carry, _ = scan_fn(inner_loop, length=lengths[0])(scope, carry) return carry def named_call(fn: Callable[..., Any], name: str) -> Callable[..., Any]:
64
64
161
18
45
joelgarde/flax
flax/core/lift.py
Python
named_call
named_call
670
683
670
670
387ac1ce12b86bff01e4982117c597db2aa508d2
bigcode/the-stack
train
e81da9cd9b1ec56987d3dee1
train
function
def custom_vjp(fn: Callable[..., Any], backward_fn: Callable[..., Any], grad_kind: CollectionFilter = 'params', nondiff_argnums=()): """"Lifted version of `jax.custom_vjp`. `backward_fn` defines a custom vjp (backward gradient) for `fn`. Example:: def fwd(scope, x, features): ...
def custom_vjp(fn: Callable[..., Any], backward_fn: Callable[..., Any], grad_kind: CollectionFilter = 'params', nondiff_argnums=()):
""""Lifted version of `jax.custom_vjp`. `backward_fn` defines a custom vjp (backward gradient) for `fn`. Example:: def fwd(scope, x, features): y = nn.dense(scope, x, features) return y, x def bwd(features, scope_fn, params, res, g): x = res fn = lambda params, x: nn.dense(scop...
carry_vars, c), (ys, scan_vars) = scanned( broadcast_vars, (carry_vars, init), scan_vars, rng_groups, args) # remove immutable broadcast vars otherwise they will be updated # with their own value which will cause an error for out_group in broadcast_vars: for name, col in tuple(out_group.items(...
194
194
649
34
160
joelgarde/flax
flax/core/lift.py
Python
custom_vjp
custom_vjp
519
586
519
521
692593d922ae23acca5336daf7d19b1fa1957f6d
bigcode/the-stack
train
2c64541076ecf181966d5db9
train
function
def vmap(fn: Callable[..., Any], variable_axes: Mapping[CollectionFilter, InOutAxis], split_rngs: Mapping[PRNGSequenceFilter, bool], in_axes=0, out_axes=0, axis_size=None, axis_name=None) -> Callable[..., Any]: """A lifted version of `jax.vmap`. See `jax.vmap` for the unlifted batch tran...
def vmap(fn: Callable[..., Any], variable_axes: Mapping[CollectionFilter, InOutAxis], split_rngs: Mapping[PRNGSequenceFilter, bool], in_axes=0, out_axes=0, axis_size=None, axis_name=None) -> Callable[..., Any]:
"""A lifted version of `jax.vmap`. See `jax.vmap` for the unlifted batch transform in Jax. Example:: # a dense mapping with separate parameters for axis 0. batch_dense = lift.vmap( nn.dense, in_axes=(0, None), variable_axes={'params': 0}, split_rngs={'params': True}) ...
variable collection should only be lifted as input.""" axis: Any # pytype does not support generic variable annotation @dataclass(frozen=True) class Out(Generic[T]): """Specifies a variable collection should only be lifted as output.""" axis: Any # pytype does not support generic variable annotation def _sp...
238
239
798
60
178
joelgarde/flax
flax/core/lift.py
Python
vmap
vmap
310
387
310
313
0fa310e33cb12f1437d29acda715d387ee0136c8
bigcode/the-stack
train
8dc87f447c8e4887359232b1
train
function
def _transpose(xs): return tuple(zip(*xs))
def _transpose(xs):
return tuple(zip(*xs))
, scopes, paths): mapping = dict(zip(orig_scopes, scopes)) scopes = [] for root, path in paths: scope = mapping[root] for name in path: scope = scope.push(name, reuse=True) scopes.append(scope) return scopes def _transpose(xs):
64
64
12
5
58
joelgarde/flax
flax/core/lift.py
Python
_transpose
_transpose
70
71
70
70
935cc48c9673efa270464bd524d5ad7688d009a0
bigcode/the-stack
train
1cae8fbf47ddd4fbd1250a5b
train
function
def _dedup_scopes(scopes): paths = [] # must preseve insertion order for duplication to work correctly minimal_set = collections.OrderedDict((s, ()) for s in scopes) for leaf in scopes: scope = leaf.parent max_parent = leaf max_parent_path = () path = [leaf.name] while scope is not None: ...
def _dedup_scopes(scopes):
paths = [] # must preseve insertion order for duplication to work correctly minimal_set = collections.OrderedDict((s, ()) for s in scopes) for leaf in scopes: scope = leaf.parent max_parent = leaf max_parent_path = () path = [leaf.name] while scope is not None: if scope in minimal_set:...
rozen_dict import FrozenDict from .frozen_dict import unfreeze from .scope import Scope, CollectionFilter, PRNGSequenceFilter, in_filter, union_filters, intersect_filters, group_collections from . import axes_scan T = TypeVar('T') def _dedup_scopes(scopes):
64
64
157
9
55
joelgarde/flax
flax/core/lift.py
Python
_dedup_scopes
_dedup_scopes
39
57
39
39
fc76a54096abc02fb309afea0e262986b17ef39b
bigcode/the-stack
train
adb4f59384f1276e007a1a76
train
function
def _split_in_out_axes(xs: Mapping[CollectionFilter, Any]): unpack = lambda v: v.axis if isinstance(v, (In, Out)) else v in_axes = {k: unpack(v) for k, v in xs.items() if not isinstance(v, Out)} out_axes = {k: unpack(v) for k, v in xs.items() if not isinstance(v, In)} return in_axes, out_axes
def _split_in_out_axes(xs: Mapping[CollectionFilter, Any]):
unpack = lambda v: v.axis if isinstance(v, (In, Out)) else v in_axes = {k: unpack(v) for k, v in xs.items() if not isinstance(v, Out)} out_axes = {k: unpack(v) for k, v in xs.items() if not isinstance(v, In)} return in_axes, out_axes
pytype does not support generic variable annotation @dataclass(frozen=True) class Out(Generic[T]): """Specifies a variable collection should only be lifted as output.""" axis: Any # pytype does not support generic variable annotation def _split_in_out_axes(xs: Mapping[CollectionFilter, Any]):
64
64
93
15
48
joelgarde/flax
flax/core/lift.py
Python
_split_in_out_axes
_split_in_out_axes
299
303
299
299
ebbc5c5b364fda0883b6141d434c3de3371fb249
bigcode/the-stack
train
8a83a8823e57cbeba8332d46
train
function
def scan(fn: Callable[..., Any], variable_axes: Mapping[CollectionFilter, InOutScanAxis] = {}, variable_broadcast: CollectionFilter = False, variable_carry: CollectionFilter = False, split_rngs: Mapping[PRNGSequenceFilter, bool] = {}, in_axes=0, out_axes=0, length: ...
def scan(fn: Callable[..., Any], variable_axes: Mapping[CollectionFilter, InOutScanAxis] = {}, variable_broadcast: CollectionFilter = False, variable_carry: CollectionFilter = False, split_rngs: Mapping[PRNGSequenceFilter, bool] = {}, in_axes=0, out_axes=0, length: ...
"""A lifted version of `jax.lax.scan`. See `jax.lax.scan` for the unlifted scan in Jax. Example:: scope.variable('counter', 'i', jnp.zeros, ()) def body_fn(scope, c, x): counter = scope.variable('counter', 'i', jnp.zeros, ()) counter.value += 1 x = scope.child(nn.dense)(x, 1) re...
split in zip(rng_groups, rng_splits)) @functools.partial(jax.vmap, in_axes=(variable_in_axes, rng_axes, in_axes), out_axes=(out_axes, variable_out_axes), axis_name=axis_name) @functools.wraps(fn) def mapped(variable_groups, rng_groups, a...
255
256
1,269
92
163
joelgarde/flax
flax/core/lift.py
Python
scan
scan
394
516
394
401
74a45f3bb152bfb437c5c3b8088bdd37dce978d4
bigcode/the-stack
train
7992cceeab208aa355fe69ba
train
function
def remat_scan(body_fn: Callable[..., Any], scope: Scope, carry: Any, lengths: Sequence[int], variable_broadcast: CollectionFilter = False, variable_carry: CollectionFilter = False, variable_axes: Mapping[CollectionFilter, InOutScanAxis] = {}, s...
def remat_scan(body_fn: Callable[..., Any], scope: Scope, carry: Any, lengths: Sequence[int], variable_broadcast: CollectionFilter = False, variable_carry: CollectionFilter = False, variable_axes: Mapping[CollectionFilter, InOutScanAxis] = {}, s...
"""Combines `lift.remat` and `lift.scan` for memory efficient scans. Example:: def body_fn(scope, x): return nn.dense(scope, x, features=x.shape[-1]) # 100x dense with O(sqrt(N)) memory for gradient computation y = lift.remat_scan( body_fn, scope, x, lengths=(10, 10), variable_ax...
) return jitted(variable_groups, rng_groups, *args) return pack(inner, (variables,), (variables,), (rngs,), name='jit') def remat_scan(body_fn: Callable[..., Any], scope: Scope, carry: Any, lengths: Sequence[int], variable_broadcast: CollectionFilter = False, variabl...
111
111
371
78
33
joelgarde/flax
flax/core/lift.py
Python
remat_scan
remat_scan
630
667
630
635
27265303b655eec19eb32d5c51da327398fb5fa3
bigcode/the-stack
train
4f0f5b8af7b81cc716c2908f
train
function
def _dup_scopes(orig_scopes, scopes, paths): mapping = dict(zip(orig_scopes, scopes)) scopes = [] for root, path in paths: scope = mapping[root] for name in path: scope = scope.push(name, reuse=True) scopes.append(scope) return scopes
def _dup_scopes(orig_scopes, scopes, paths):
mapping = dict(zip(orig_scopes, scopes)) scopes = [] for root, path in paths: scope = mapping[root] for name in path: scope = scope.push(name, reuse=True) scopes.append(scope) return scopes
.append(scope.name) scope = scope.parent if max_parent is not leaf and leaf in minimal_set: del minimal_set[leaf] paths.append((max_parent, max_parent_path)) return tuple(minimal_set), tuple(paths) def _dup_scopes(orig_scopes, scopes, paths):
64
64
67
13
51
joelgarde/flax
flax/core/lift.py
Python
_dup_scopes
_dup_scopes
60
68
60
60
3e5129430bf21b26d7689776d80be4aaf0c7ee8a
bigcode/the-stack
train
6f39137fa00a8d93e408526c
train
function
def jit(fn: Callable[..., Any], static_argnums: Union[int, Iterable[int]] = (), device=None, backend: Union[str, None] = None, variables: CollectionFilter = True, rngs: PRNGSequenceFilter = True) -> Callable[..., Any]: """Lifted version of jax.jit.""" if not isinstance(static...
def jit(fn: Callable[..., Any], static_argnums: Union[int, Iterable[int]] = (), device=None, backend: Union[str, None] = None, variables: CollectionFilter = True, rngs: PRNGSequenceFilter = True) -> Callable[..., Any]:
"""Lifted version of jax.jit.""" if not isinstance(static_argnums, Iterable): static_argnums = (static_argnums,) static_argnums = tuple(i + 1 for i in static_argnums if i > 0) def inner(scope_fn, repack_fn, variable_groups, rng_groups, *args): @functools.partial(jax.jit, static_ar...
(variables,), (rngs,), name='remat') def jit(fn: Callable[..., Any], static_argnums: Union[int, Iterable[int]] = (), device=None, backend: Union[str, None] = None, variables: CollectionFilter = True, rngs: PRNGSequenceFilter = True) -> Callable[..., Any]:
72
72
243
60
12
joelgarde/flax
flax/core/lift.py
Python
jit
jit
605
627
605
610
9b5d4fc1b386c380857c7b412d32a39a483cbbc9
bigcode/the-stack
train
fa132e957de5840f6422a3a6
train
function
def transform_module(fn: Callable[..., Any], target: CollectionFilter = 'params', trans_in_fn: Callable[..., Any] = id_fn, trans_out_fn: Callable[..., Any] = id_fn, mutable: bool = False, rngs: PRNGSequenceFilter = ...
def transform_module(fn: Callable[..., Any], target: CollectionFilter = 'params', trans_in_fn: Callable[..., Any] = id_fn, trans_out_fn: Callable[..., Any] = id_fn, mutable: bool = False, rngs: PRNGSequenceFilter = ...
""""Wrapper around `transform` for automatic init detection. This function will detect if the target collection exists. If it doesn't `init=True` is will be passed to `transform`. See `transform` for more details. """ def wrapper(scope, *args, **kwargs): vs = scope.variables() is_init = target not...
def transform_module(fn: Callable[..., Any], target: CollectionFilter = 'params', trans_in_fn: Callable[..., Any] = id_fn, trans_out_fn: Callable[..., Any] = id_fn, mutable: bool = False, rngs: PRNGSequenceFilter = ...
70
67
226
70
0
joelgarde/flax
flax/core/lift.py
Python
transform_module
transform_module
248
274
248
254
518f41818cd7cd18cb39f1ebdaaab60bf4aa5ad1
bigcode/the-stack
train
fcfea5fadbec7d31c96c3fb1
train
function
def parameters_of_type(parameter_type, seed): np.random.seed(seed) while True: if parameter_type is None: yield None else: yield Parameter({k: np.random.random(v) for k, v in parameter_type.items()})
def parameters_of_type(parameter_type, seed):
np.random.seed(seed) while True: if parameter_type is None: yield None else: yield Parameter({k: np.random.random(v) for k, v in parameter_type.items()})
or.org). # Copyright 2013-2016 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) import numpy as np from pymor.parameters.base import Parameter def parameters_of_type(parameter_type, seed):
64
64
54
9
54
JuliaBru/pymor
src/pymortests/fixtures/parameter.py
Python
parameters_of_type
parameters_of_type
10
16
10
10
60439e9a716da0e23b9bcc485cea5cbdbe7779c1
bigcode/the-stack
train
357599e73155f554fd462bdf
train
function
def checkGuide(keyword): global URL, data results_index = [] resultsData = '' keywords = keyword.split(',') for i in range(0,len(keywords)): keywords[i] = keywords[i].lower() data = requests.get(URL,timeout=60) jsonData = data.content.decode("utf-8") data = json.loads(jsonData)...
def checkGuide(keyword):
global URL, data results_index = [] resultsData = '' keywords = keyword.split(',') for i in range(0,len(keywords)): keywords[i] = keywords[i].lower() data = requests.get(URL,timeout=60) jsonData = data.content.decode("utf-8") data = json.loads(jsonData) for count in range ...
config.read('config.ini') KEY = config['guides']['KEY'] SITE_ID = config['guides']['SITE_ID'] URL = 'https://lgapi-au.libapps.com/1.1/guides?site_id='+SITE_ID+'&key='+KEY+'&sort_by=relevance&expand=pages&status=1' data = '' def checkGuide(keyword):
76
76
256
5
71
RonBulaon/DownloadNow
searchGuide.py
Python
checkGuide
checkGuide
16
43
16
16
f45ae91e35816ec66b7955f0028507e6329128c0
bigcode/the-stack
train
b2f0bc17248e75f8fe707f21
train
class
class TestHTTPUtil(unittest.TestCase): def test_read_body_stream(self): for fname, chunked, compression in CONTENT_FILES: file_path = os.path.join(MY_DIR, 'http_content', fname) with self.subTest(fname): with open(file_path, 'rb') as fh: with ope...
class TestHTTPUtil(unittest.TestCase):
def test_read_body_stream(self): for fname, chunked, compression in CONTENT_FILES: file_path = os.path.join(MY_DIR, 'http_content', fname) with self.subTest(fname): with open(file_path, 'rb') as fh: with open(file_path + '.expected', 'rb') as exp_...
deflate', False, httputil.DEFLATE), ('deflate2', False, httputil.DEFLATE), ('deflate3', False, httputil.DEFLATE), ('gzipped', False, httputil.GZIP) ] class TestHTTPUtil(unittest.TestCase):
64
64
211
8
56
vovanec/httputil
httputil/tests/test_httputil.py
Python
TestHTTPUtil
TestHTTPUtil
30
52
30
31
f33ac5641f704ab464d550cd97f0f19f8aa99f52
bigcode/the-stack
train
a9d6b9d5b9107e863e16abd8
train
class
class MujocoXML: """ Class that combines multiple MuJoCo XML files into a single one. """ meshdir = os.path.join(ASSETS_DIR, "stls") texturedir = os.path.join(ASSETS_DIR, "textures") TEXTURE_ATTRIBUTES = [ "file", "fileback" "filedown", "filefront", "fileleft", ...
class MujocoXML:
""" Class that combines multiple MuJoCo XML files into a single one. """ meshdir = os.path.join(ASSETS_DIR, "stls") texturedir = os.path.join(ASSETS_DIR, "textures") TEXTURE_ATTRIBUTES = [ "file", "fileback" "filedown", "filefront", "fileleft", "filerigh...
Sim use __cinit__ # for initialization which happens automatically before subclass __init__ # is called. self._stale: bool = False self._xml = model.get_xml() def get_xml(self): """ Mujoco's internal get_xml() is unreliable as it seems to override the internal ...
256
256
1,994
5
251
0xflotus/robogym
robogym/mujoco/mujoco_xml.py
Python
MujocoXML
MujocoXML
94
375
94
94
7739d217a9ddd2123502acb4238c46e6fc7340ef
bigcode/the-stack
train
5b4e4069627cef5360413fbd
train
function
def _format_array(np_array, precision=6): """ Format numpy array into a nice string suitable for mujoco XML """ if not isinstance(np_array, np.ndarray): np_array = np.array(np_array, dtype=float) # Make sure it's flattened if len(np_array.shape) > 1: np_array = np_array.reshape(-1) ...
def _format_array(np_array, precision=6):
""" Format numpy array into a nice string suitable for mujoco XML """ if not isinstance(np_array, np.ndarray): np_array = np.array(np_array, dtype=float) # Make sure it's flattened if len(np_array.shape) > 1: np_array = np_array.reshape(-1) if np.min(np.abs(np_array)) > 0.001: ...
import xml.etree.ElementTree as et import mujoco_py import numpy as np ASSETS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../assets")) XML_DIR = os.path.join(ASSETS_DIR, "xmls") def _format_array(np_array, precision=6):
64
64
145
11
53
0xflotus/robogym
robogym/mujoco/mujoco_xml.py
Python
_format_array
_format_array
12
27
12
12
66b6e378359f5254d74c3cbee0cdc6dbd027d97a
bigcode/the-stack
train
eac2bd7d12f1c4b75869a86f
train
class
class StaleMjSimError(Exception): """ Exception indicating the MjSim instance is stale and should no longer be used. """ pass
class StaleMjSimError(Exception):
""" Exception indicating the MjSim instance is stale and should no longer be used. """ pass
001: format_str = "{:.%df}" % precision else: format_str = "{:.%de}" % precision # Finally format a string out of numpy array return " ".join(format_str.format(x) for x in np_array) class StaleMjSimError(Exception):
64
64
32
8
56
0xflotus/robogym
robogym/mujoco/mujoco_xml.py
Python
StaleMjSimError
StaleMjSimError
30
35
30
30
ec7008686c67653cd676e7d4e45138f649fc0c52
bigcode/the-stack
train
fed7d97caca8d38aa5371fa3
train
class
class MjSim(mujoco_py.MjSim): """ There are environments e.g. rearrange environment which recreates sim after reach env reset. This can cause potential bugs caused by other components still caching instance of old sim. These bugs are usually quite tricky to find. This class makes it easier to find t...
class MjSim(mujoco_py.MjSim):
""" There are environments e.g. rearrange environment which recreates sim after reach env reset. This can cause potential bugs caused by other components still caching instance of old sim. These bugs are usually quite tricky to find. This class makes it easier to find these bugs by allowing inva...
.reshape(-1) if np.min(np.abs(np_array)) > 0.001: format_str = "{:.%df}" % precision else: format_str = "{:.%de}" % precision # Finally format a string out of numpy array return " ".join(format_str.format(x) for x in np_array) class StaleMjSimError(Exception): """ Exception i...
117
117
391
12
104
0xflotus/robogym
robogym/mujoco/mujoco_xml.py
Python
MjSim
MjSim
38
91
38
38
09296c9fe1c286add5e0829f715f2168991a1d00
bigcode/the-stack
train
76b0a59cde3babc6b5a14694
train
function
def init(name: str, region: Optional[str], debug: bool) -> None: conf_dir = "conf" with MessagesContext("Initializing", debug=debug) as ctx: conf_dir_src = os.path.join(ORBIT_CLI_ROOT, "data", "init") if os.path.exists(conf_dir): shutil.rmtree(conf_dir) env_manifest = "defaul...
def init(name: str, region: Optional[str], debug: bool) -> None:
conf_dir = "conf" with MessagesContext("Initializing", debug=debug) as ctx: conf_dir_src = os.path.join(ORBIT_CLI_ROOT, "data", "init") if os.path.exists(conf_dir): shutil.rmtree(conf_dir) env_manifest = "default-env-manifest.yaml" shutil.copytree(src=conf_dir_src, ds...
str = file.read() content = utils.resolve_parameters(content, dict(region=region_str, name=name, account_id=utils.get_account_id())) with open(filename, "w") as file: file.write(content) def init(name: str, region: Optional[str], debug: bool) -> None:
64
64
193
18
46
srinivasreddych/aws-orbit-workbench
cli/aws_orbit/commands/init.py
Python
init
init
43
62
43
43
723c4487c96e7cc061e7f291a7df2231640dd5c5
bigcode/the-stack
train
aece688be200fd0311c8c5f2
train
function
def write_resolve_parameters( manifest_name: str, name: str, filename: str, region: Optional[str], ) -> None: region_str: str = region if region is not None else utils.get_region() input = os.path.join(ORBIT_CLI_ROOT, "data", "init", manifest_name) with open(input, "r") as file: cont...
def write_resolve_parameters( manifest_name: str, name: str, filename: str, region: Optional[str], ) -> None:
region_str: str = region if region is not None else utils.get_region() input = os.path.join(ORBIT_CLI_ROOT, "data", "init", manifest_name) with open(input, "r") as file: content: str = file.read() content = utils.resolve_parameters(content, dict(region=region_str, name=name, account_id=utils.ge...
aws_orbit import ORBIT_CLI_ROOT, utils from aws_orbit.messages import MessagesContext _logger: logging.Logger = logging.getLogger(__name__) def write_resolve_parameters( manifest_name: str, name: str, filename: str, region: Optional[str], ) -> None:
64
64
131
32
32
srinivasreddych/aws-orbit-workbench
cli/aws_orbit/commands/init.py
Python
write_resolve_parameters
write_resolve_parameters
26
40
26
31
11dd67d3f36c4dd6a77fcc5bf4b7814177577e53
bigcode/the-stack
train
66f8114fd0b6348d58336b27
train
class
class YoutubeAPI: def getEngagement(self, search): try: r = http.request('GET', 'https://www.googleapis.com/youtube/v3/search?maxResults=20&q=' + search + '&type=channel&key=' + key) if r.status != 200: raise Exception(r.data) jsonSearch = json.loads(r.dat...
class YoutubeAPI:
def getEngagement(self, search): try: r = http.request('GET', 'https://www.googleapis.com/youtube/v3/search?maxResults=20&q=' + search + '&type=channel&key=' + key) if r.status != 200: raise Exception(r.data) jsonSearch = json.loads(r.data) cha...
import urllib3 import json from response.EngagementResponse import * import credentials key = credentials.KEY http = urllib3.PoolManager() class YoutubeAPI:
35
191
637
4
31
fegaris/social_networks_term_inspector
social_networks_term_inspector/social_apis/engagement/EngagementYoutubeAPI.py
Python
YoutubeAPI
YoutubeAPI
8
56
8
8
2755d145bcbe2d084d959407c9f844eb7f81d8a1
bigcode/the-stack
train
237852745e3343f5eff7064e
train
class
class Hdf5Transport(BaseTransport): def __init__(self): super(Hdf5Transport, self).__init__() os.environ['savu_mode'] = 'hdf5' self.count = 0 def _transport_initialise(self, options): MPI_setup(options) self.exp_coll = None self.data_flow = [] self.files...
class Hdf5Transport(BaseTransport):
def __init__(self): super(Hdf5Transport, self).__init__() os.environ['savu_mode'] = 'hdf5' self.count = 0 def _transport_initialise(self, options): MPI_setup(options) self.exp_coll = None self.data_flow = [] self.files = [] def _transport_update_plug...
# Copyright 2015 Diamond Light Source Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
234
256
875
8
225
elainehoml/Savu
savu/core/transports/hdf5_transport.py
Python
Hdf5Transport
Hdf5Transport
32
129
32
33
f3dc1043d7429a07e2e3ac1db2fd2f83761088d0
bigcode/the-stack
train
444e71f11ff1a9502b1151fd
train
function
@pytest.mark.parametrize( 'unserialized, expected_fields', ( ( {'pos2': 1, 'pos1': 0}, [0, 1], ), ), ) def test_iteration(unserialized, expected_fields): rlp_obj = TwoIntRLP(**unserialized) for actual, expected in zip(rlp_obj, expected_fields): assert ...
@pytest.mark.parametrize( 'unserialized, expected_fields', ( ( {'pos2': 1, 'pos1': 0}, [0, 1], ), ), ) def test_iteration(unserialized, expected_fields):
rlp_obj = TwoIntRLP(**unserialized) for actual, expected in zip(rlp_obj, expected_fields): assert actual == expected assert list(rlp_obj) == expected_fields
assert getattr(rlp_obj, name) == val @pytest.mark.parametrize( 'unserialized, expected_fields', ( ( {'pos2': 1, 'pos1': 0}, [0, 1], ), ), ) def test_iteration(unserialized, expected_fields):
64
64
98
52
11
vaporyproject/eth-rlp
tests/core/test_hashable.py
Python
test_iteration
test_iteration
60
73
60
69
2e61fe6769cac7ae36cd9e002576733396efc4c7
bigcode/the-stack
train
87f563f7e72fe7c97e554fe7
train
function
@pytest.mark.parametrize( 'unserialized, expected_hash_hex', ( ([0, 1], '0x698b0c299d3182774bd859102bea2f205f0a1b3674c8d1d7aee6b17122a2f73a'), ), ) def test_hash(unserialized, expected_hash_hex): rlp_obj = TwoIntRLP(*unserialized) assert rlp_obj.hash().hex() == expected_hash_hex
@pytest.mark.parametrize( 'unserialized, expected_hash_hex', ( ([0, 1], '0x698b0c299d3182774bd859102bea2f205f0a1b3674c8d1d7aee6b17122a2f73a'), ), ) def test_hash(unserialized, expected_hash_hex):
rlp_obj = TwoIntRLP(*unserialized) assert rlp_obj.hash().hex() == expected_hash_hex
@pytest.mark.parametrize( 'unserialized, expected_hash_hex', ( ([0, 1], '0x698b0c299d3182774bd859102bea2f205f0a1b3674c8d1d7aee6b17122a2f73a'), ), ) def test_hash(unserialized, expected_hash_hex):
79
64
106
79
0
vaporyproject/eth-rlp
tests/core/test_hashable.py
Python
test_hash
test_hash
19
27
19
25
30ad335bfc7c496a51e92fade72dd94ffc7f571f
bigcode/the-stack
train
c40ed8c78363ae001fdd8f39
train
class
class TwoIntRLP(HashableRLP): fields = ( ('pos1', big_endian_int), ('pos2', big_endian_int), )
class TwoIntRLP(HashableRLP):
fields = ( ('pos1', big_endian_int), ('pos2', big_endian_int), )
import pytest from rlp.sedes import ( big_endian_int, ) from eth_rlp import ( HashableRLP, ) class TwoIntRLP(HashableRLP):
40
64
36
10
30
vaporyproject/eth-rlp
tests/core/test_hashable.py
Python
TwoIntRLP
TwoIntRLP
12
16
12
12
668350b75bd8c81d98ebaefd7985b90fe8ca4b08
bigcode/the-stack
train
2ad9c5b36756a768136f0b1e
train
function
@pytest.mark.parametrize( 'unserialized, expected_dict', ( ( {'pos2': 1, 'pos1': 0}, {'pos2': 1, 'pos1': 0}, ), ), ) def test_to_dict(unserialized, expected_dict): rlp_obj = TwoIntRLP(**unserialized) assert rlp_obj.as_dict() == expected_dict
@pytest.mark.parametrize( 'unserialized, expected_dict', ( ( {'pos2': 1, 'pos1': 0}, {'pos2': 1, 'pos1': 0}, ), ), ) def test_to_dict(unserialized, expected_dict):
rlp_obj = TwoIntRLP(**unserialized) assert rlp_obj.as_dict() == expected_dict
expected_fields @pytest.mark.parametrize( 'unserialized, expected_dict', ( ( {'pos2': 1, 'pos1': 0}, {'pos2': 1, 'pos1': 0}, ), ), ) def test_to_dict(unserialized, expected_dict):
64
64
86
61
2
vaporyproject/eth-rlp
tests/core/test_hashable.py
Python
test_to_dict
test_to_dict
76
87
76
85
08e4e1152a185bd1655ec793b2be1a7a010c0014
bigcode/the-stack
train
6fabf5b84c0b32dfd342c9b6
train
function
@pytest.mark.parametrize( 'unserialized, expected_hash_hex', ( ( {'pos1': 0, 'pos2': 1}, '0x698b0c299d3182774bd859102bea2f205f0a1b3674c8d1d7aee6b17122a2f73a', ), ), ) def test_create_with_dict(unserialized, expected_hash_hex): assert TwoIntRLP.from_dict(unserializ...
@pytest.mark.parametrize( 'unserialized, expected_hash_hex', ( ( {'pos1': 0, 'pos2': 1}, '0x698b0c299d3182774bd859102bea2f205f0a1b3674c8d1d7aee6b17122a2f73a', ), ), ) def test_create_with_dict(unserialized, expected_hash_hex):
assert TwoIntRLP.from_dict(unserialized).hash().hex() == expected_hash_hex
@pytest.mark.parametrize( 'unserialized, expected_hash_hex', ( ( {'pos1': 0, 'pos2': 1}, '0x698b0c299d3182774bd859102bea2f205f0a1b3674c8d1d7aee6b17122a2f73a', ), ), ) def test_create_with_dict(unserialized, expected_hash_hex):
94
64
114
94
0
vaporyproject/eth-rlp
tests/core/test_hashable.py
Python
test_create_with_dict
test_create_with_dict
30
40
30
39
ce45fb5578417f2b6b81e1a0d99058033d51cd0d
bigcode/the-stack
train
6d588fd45a341a13092cbd06
train
function
@pytest.mark.parametrize( 'serialized, expected_hash_hex, expected_fields', ( ( b'\xc2\x80\x01', '0x698b0c299d3182774bd859102bea2f205f0a1b3674c8d1d7aee6b17122a2f73a', {'pos1': 0, 'pos2': 1}, ), ), ) def test_from_bytes(serialized, expected_hash_hex, expect...
@pytest.mark.parametrize( 'serialized, expected_hash_hex, expected_fields', ( ( b'\xc2\x80\x01', '0x698b0c299d3182774bd859102bea2f205f0a1b3674c8d1d7aee6b17122a2f73a', {'pos1': 0, 'pos2': 1}, ), ), ) def test_from_bytes(serialized, expected_hash_hex, expect...
rlp_obj = TwoIntRLP.from_bytes(serialized) assert rlp_obj.hash().hex() == expected_hash_hex for name, val in expected_fields.items(): assert getattr(rlp_obj, name) == val
@pytest.mark.parametrize( 'serialized, expected_hash_hex, expected_fields', ( ( b'\xc2\x80\x01', '0x698b0c299d3182774bd859102bea2f205f0a1b3674c8d1d7aee6b17122a2f73a', {'pos1': 0, 'pos2': 1}, ), ), ) def test_from_bytes(serialized, expected_hash_hex, expect...
108
64
159
108
0
vaporyproject/eth-rlp
tests/core/test_hashable.py
Python
test_from_bytes
test_from_bytes
43
57
43
53
32d6462a91302d0b0c01ac38c6604afaef337eac
bigcode/the-stack
train
178d2dde7dfdbdf0e82e2187
train
class
class Visualizations: def __init__(self, env_name=None, update_every=10, server="http://localhost", disabled=True): # Tracking data self.last_update_timestamp = timer() self.update_every = update_every self.step_times = [] self.losses = [] self.eers = [] ...
class Visualizations:
def __init__(self, env_name=None, update_every=10, server="http://localhost", disabled=True): # Tracking data self.last_update_timestamp = timer() self.update_every = update_every self.step_times = [] self.losses = [] self.eers = [] print("Updating the ...
visdom import umap import seaborn as sns import pandas as pd colormap = np.array([ [76, 255, 0], [0, 127, 70], [255, 0, 0], [255, 217, 38], [0, 135, 255], [165, 0, 165], [255, 167, 255], [0, 255, 255], [255, 96, 38], [142, 76, 0], [33, 0, 127], [0, 0, 0],...
178
179
597
4
174
freenowill/autoVC-WavRNN
encoder_test.py
Python
Visualizations
Visualizations
34
95
34
34
2d69da4fe62b83535592c04b7851f3c431ee6012
bigcode/the-stack
train
588286341f755de1523eb4e0
train
function
def unstack_for_pool(fxn, s, py, px): my, mx = (s[2]//py)*py, (s[3]//px)*px for k in range(py*px): Y, X = k//px, k%px ll = fxn(Y*px+X) if X == 0 and Y == 0: ret = np.zeros(s, dtype=ll.dtype) ret[:, :, Y:my:py, X:mx:px] = ll return ret
def unstack_for_pool(fxn, s, py, px):
my, mx = (s[2]//py)*py, (s[3]//px)*px for k in range(py*px): Y, X = k//px, k%px ll = fxn(Y*px+X) if X == 0 and Y == 0: ret = np.zeros(s, dtype=ll.dtype) ret[:, :, Y:my:py, X:mx:px] = ll return ret
= x[:, :, :my, :mx] stack = [xup[:, :, k//px::py, k%px::px][None] for k in range(py*px)] return np.concatenate(stack, axis=0) def unstack_for_pool(fxn, s, py, px):
64
64
118
14
50
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
unstack_for_pool
unstack_for_pool
242
250
242
242
7983a1eb70613fb5bd419a6274162943c0366bc7
bigcode/the-stack
train
6072c8a3dc4c61f83cee315c
train
class
class MaxPool2D(Function): @staticmethod def forward(ctx, x, kernel_size=(2, 2)): stack = stack_for_pool(x, *kernel_size) idxs = np.argmax(stack, axis=0) ctx.save_for_backward(idxs, x.shape) return np.max(stack, axis=0) @staticmethod def backward(ctx, grad_output): idxs,s = ctx.saved_tensor...
class MaxPool2D(Function): @staticmethod
def forward(ctx, x, kernel_size=(2, 2)): stack = stack_for_pool(x, *kernel_size) idxs = np.argmax(stack, axis=0) ctx.save_for_backward(idxs, x.shape) return np.max(stack, axis=0) @staticmethod def backward(ctx, grad_output): idxs,s = ctx.saved_tensors return unstack_for_pool( lambda...
n(Y*px+X) if X == 0 and Y == 0: ret = np.zeros(s, dtype=ll.dtype) ret[:, :, Y:my:py, X:mx:px] = ll return ret class MaxPool2D(Function): @staticmethod
64
64
121
11
52
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
MaxPool2D
MaxPool2D
252
265
252
253
7b2757b1bd7011fd823df084a47befb037a640e5
bigcode/the-stack
train
ac1ebc10b48f537abfad83d4
train
class
class Pad2D(Function): @staticmethod def forward(ctx, x, padding=None): ctx.save_for_backward(padding) return np.pad(x, ((0,0), (0,0), (padding[2], padding[3]), (padding[0], padding[1]))) @staticmethod def backward(ctx, grad_output): padding, = ctx.saved_tensors return grad_output[...
class Pad2D(Function): @staticmethod
def forward(ctx, x, padding=None): ctx.save_for_backward(padding) return np.pad(x, ((0,0), (0,0), (padding[2], padding[3]), (padding[0], padding[1]))) @staticmethod def backward(ctx, grad_output): padding, = ctx.saved_tensors return grad_output[..., padding[2]:-padding[3], padding[0]...
ctx.saved_tensors grad_input = grad_output.dot(weight.T) grad_weight = input.T.dot(grad_output) return grad_input, grad_weight register('dot', Dot) register('matmul', Dot) # ************* simple ops ************* class Pad2D(Function): @staticmethod
64
64
109
10
54
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
Pad2D
Pad2D
94
105
94
95
db1545dba13b1273e7dbea3eb202850d82224ada
bigcode/the-stack
train
27aa81a823eee9580a8c57ba
train
class
class Conv2D(Function): @staticmethod def forward(ctx, x, w, stride=1, groups=1): if type(ctx.stride) == int: ctx.stride = (ctx.stride, ctx.stride) cout,cin,H,W = w.shape ys,xs = ctx.stride bs,cin_ = x.shape[0], x.shape[1] oy,ox = (x.shape[2]-(H-ys))//ys, (x.shape[3]-(W-xs))//xs assert...
class Conv2D(Function): @staticmethod
def forward(ctx, x, w, stride=1, groups=1): if type(ctx.stride) == int: ctx.stride = (ctx.stride, ctx.stride) cout,cin,H,W = w.shape ys,xs = ctx.stride bs,cin_ = x.shape[0], x.shape[1] oy,ox = (x.shape[2]-(H-ys))//ys, (x.shape[3]-(W-xs))//xs assert cin*ctx.groups == cin_ assert cout ...
)) ) ctx.save_for_backward(ret) return ret @staticmethod def backward(ctx, grad_output): ret, = ctx.saved_tensors grad_input = grad_output * (ret * (1 - ret)) return grad_input register('sigmoid', Sigmoid) class LogSoftmax(Function): @staticmethod def forward(ctx, input): def log...
231
231
770
10
221
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
Conv2D
Conv2D
175
230
175
176
b0e055b4d5ddbbcbdeda05dc0750cf015b95c172
bigcode/the-stack
train
9fb8c7e4dacab23434b9675d
train
class
class ReLU(Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(input) return np.maximum(input, 0) @staticmethod def backward(ctx, grad_output): input, = ctx.saved_tensors grad_input = grad_output * (input >= 0) return grad_input
class ReLU(Function): @staticmethod
def forward(ctx, input): ctx.save_for_backward(input) return np.maximum(input, 0) @staticmethod def backward(ctx, grad_output): input, = ctx.saved_tensors grad_input = grad_output * (input >= 0) return grad_input
_for_backward(x.shape) return x.reshape(shape) @staticmethod def backward(ctx, grad_output): in_shape, = ctx.saved_tensors return grad_output.reshape(in_shape) register('reshape', Reshape) # ************* activation ops ************* class ReLU(Function): @staticmethod
64
64
71
9
55
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
ReLU
ReLU
123
133
123
124
bbd170f3cf60e9311b413b8408d30bdb1663bf64
bigcode/the-stack
train
dc05215f6c536eb5c6db704d
train
class
class Sigmoid(Function): @staticmethod def forward(ctx, input): with np.warnings.catch_warnings(): np.warnings.filterwarnings('ignore') ret = np.where(input >= 0, 1/(1 + np.exp(-input)), np.exp(input)/(1 + np.exp(input)) ) ctx.save_for_backward(ret) return ret @stati...
class Sigmoid(Function): @staticmethod
def forward(ctx, input): with np.warnings.catch_warnings(): np.warnings.filterwarnings('ignore') ret = np.where(input >= 0, 1/(1 + np.exp(-input)), np.exp(input)/(1 + np.exp(input)) ) ctx.save_for_backward(ret) return ret @staticmethod def backward(ctx, grad_output):...
return np.maximum(input, 0) @staticmethod def backward(ctx, grad_output): input, = ctx.saved_tensors grad_input = grad_output * (input >= 0) return grad_input register('relu', ReLU) class Sigmoid(Function): @staticmethod
64
64
120
9
55
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
Sigmoid
Sigmoid
136
152
136
137
3d555d4389574385365984885ea60193c96b41bf
bigcode/the-stack
train
ec14b90f079207c197a4ac03
train
function
def unbroadcast(out, in_sh): # adjoint operation to broadcast is sum. Need to sum all axis with 1 = in_sh[i] < out.shape[i] sum_axis = tuple([i for i in range(len(in_sh)) if in_sh[i]==1 and out.shape[i]>1]) if in_sh != (1,) else None return out.sum(axis=sum_axis).reshape(in_sh)
def unbroadcast(out, in_sh): # adjoint operation to broadcast is sum. Need to sum all axis with 1 = in_sh[i] < out.shape[i]
sum_axis = tuple([i for i in range(len(in_sh)) if in_sh[i]==1 and out.shape[i]>1]) if in_sh != (1,) else None return out.sum(axis=sum_axis).reshape(in_sh)
import warnings import numpy as np from .tensor import Function, register # ************* basic ops ************* def unbroadcast(out, in_sh): # adjoint operation to broadcast is sum. Need to sum all axis with 1 = in_sh[i] < out.shape[i]
59
64
86
36
23
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
unbroadcast
unbroadcast
6
9
6
7
c173b1777f43034e6a8e51d00093245ff44104dd
bigcode/the-stack
train
7307d1ccbe6d0a3d22129a7a
train
class
class Reshape(Function): @staticmethod def forward(ctx, x, shape): ctx.save_for_backward(x.shape) return x.reshape(shape) @staticmethod def backward(ctx, grad_output): in_shape, = ctx.saved_tensors return grad_output.reshape(in_shape)
class Reshape(Function): @staticmethod
def forward(ctx, x, shape): ctx.save_for_backward(x.shape) return x.reshape(shape) @staticmethod def backward(ctx, grad_output): in_shape, = ctx.saved_tensors return grad_output.reshape(in_shape)
) @staticmethod def backward(ctx, grad_output): padding, = ctx.saved_tensors return grad_output[..., padding[2]:-padding[3], padding[0]:-padding[1]] register('pad2d', Pad2D) class Reshape(Function): @staticmethod
64
64
62
9
55
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
Reshape
Reshape
108
117
108
109
cfe8ea990bc73df0dc9235e73cca2607e52f723c
bigcode/the-stack
train
99c706cbe5991f789986c820
train
class
class Add(Function): @staticmethod def forward(ctx, x, y): ctx.save_for_backward(x.shape, y.shape) return x+y @staticmethod def backward(ctx, grad_output): shape_x, shape_y = ctx.saved_tensors return unbroadcast(grad_output, shape_x), unbroadcast(grad_output, shape_y)
class Add(Function): @staticmethod
def forward(ctx, x, y): ctx.save_for_backward(x.shape, y.shape) return x+y @staticmethod def backward(ctx, grad_output): shape_x, shape_y = ctx.saved_tensors return unbroadcast(grad_output, shape_x), unbroadcast(grad_output, shape_y)
] < out.shape[i] sum_axis = tuple([i for i in range(len(in_sh)) if in_sh[i]==1 and out.shape[i]>1]) if in_sh != (1,) else None return out.sum(axis=sum_axis).reshape(in_sh) class Add(Function): @staticmethod
64
64
77
8
56
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
Add
Add
11
20
11
12
fb6322af45dda4478048896b8aeea1ed7dabc699
bigcode/the-stack
train
e196147a3694edb03e1a2021
train
class
class Pow(Function): @staticmethod def forward(ctx, x, y): ctx.save_for_backward(x, y) return x ** y @staticmethod def backward(ctx, grad_output): x,y = ctx.saved_tensors return unbroadcast(y * (x**(y-1.0)) * grad_output, x.shape), \ unbroadcast((x**y) * np.log(x) * grad_output, y.sh...
class Pow(Function): @staticmethod
def forward(ctx, x, y): ctx.save_for_backward(x, y) return x ** y @staticmethod def backward(ctx, grad_output): x,y = ctx.saved_tensors return unbroadcast(y * (x**(y-1.0)) * grad_output, x.shape), \ unbroadcast((x**y) * np.log(x) * grad_output, y.shape)
y) return x*y @staticmethod def backward(ctx, grad_output): x,y = ctx.saved_tensors return unbroadcast(y*grad_output, x.shape), unbroadcast(x*grad_output, y.shape) register('mul', Mul) class Pow(Function): @staticmethod
64
64
97
8
56
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
Pow
Pow
47
57
47
48
64aa12f4d044cb8d30a05d98594a824d5f86ae65
bigcode/the-stack
train
6d87a6ac4005d3de2d159d97
train
class
class Sub(Function): @staticmethod def forward(ctx, x, y): ctx.save_for_backward(x.shape, y.shape) return x-y @staticmethod def backward(ctx, grad_output): shape_x, shape_y = ctx.saved_tensors return unbroadcast(grad_output, shape_x), unbroadcast(-grad_output, shape_y)
class Sub(Function): @staticmethod
def forward(ctx, x, y): ctx.save_for_backward(x.shape, y.shape) return x-y @staticmethod def backward(ctx, grad_output): shape_x, shape_y = ctx.saved_tensors return unbroadcast(grad_output, shape_x), unbroadcast(-grad_output, shape_y)
) return x+y @staticmethod def backward(ctx, grad_output): shape_x, shape_y = ctx.saved_tensors return unbroadcast(grad_output, shape_x), unbroadcast(grad_output, shape_y) register('add', Add) class Sub(Function): @staticmethod
64
64
77
8
56
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
Sub
Sub
23
32
23
24
884794da00575a100373ab6ddf605fe6022327f6
bigcode/the-stack
train
a9d2b29024490c9366e71e0d
train
function
def stack_for_pool(x, py, px): my, mx = (x.shape[2]//py)*py, (x.shape[3]//px)*px xup = x[:, :, :my, :mx] stack = [xup[:, :, k//px::py, k%px::px][None] for k in range(py*px)] return np.concatenate(stack, axis=0)
def stack_for_pool(x, py, px):
my, mx = (x.shape[2]//py)*py, (x.shape[3]//px)*px xup = x[:, :, :my, :mx] stack = [xup[:, :, k//px::py, k%px::px][None] for k in range(py*px)] return np.concatenate(stack, axis=0)
W)) return gdx.reshape((bs, ctx.groups*cin, OY, OX)), gdw.reshape((ctx.groups*rcout, cin, H, W)) register('conv2d', Conv2D) # ************* pooling ops ************* def stack_for_pool(x, py, px):
64
64
90
10
54
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
stack_for_pool
stack_for_pool
236
240
236
236
ac45ed4a6326994aecb3a30abb7c85b7aca59846
bigcode/the-stack
train
c37d7abe2cf8a012a1c3b68e
train
class
class Sum(Function): @staticmethod def forward(ctx, input,axis=None): ctx.save_for_backward(input, axis) return np.array([input.sum()]) if axis is None else input.sum(axis=axis) @staticmethod def backward(ctx, grad_output): input, axis = ctx.saved_tensors shape = [1 if axis is None or i in axis...
class Sum(Function): @staticmethod
def forward(ctx, input,axis=None): ctx.save_for_backward(input, axis) return np.array([input.sum()]) if axis is None else input.sum(axis=axis) @staticmethod def backward(ctx, grad_output): input, axis = ctx.saved_tensors shape = [1 if axis is None or i in axis else input.shape[i] for i in range(l...
= ctx.saved_tensors return unbroadcast(y * (x**(y-1.0)) * grad_output, x.shape), \ unbroadcast((x**y) * np.log(x) * grad_output, y.shape) register('pow', Pow) class Sum(Function): @staticmethod
64
64
108
8
56
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
Sum
Sum
60
70
60
61
83a573c7b0fee8cee3afe5faad551e08bdfc6bec
bigcode/the-stack
train
a8a1691174a87fa88c19538a
train
class
class AvgPool2D(Function): @staticmethod def forward(ctx, x, kernel_size=(2, 2)): stack = stack_for_pool(x, *kernel_size) ctx.save_for_backward(x.shape) return np.mean(stack, axis=0) @staticmethod def backward(ctx, grad_output): s, = ctx.saved_tensors py, px = ctx.kernel_size return uns...
class AvgPool2D(Function): @staticmethod
def forward(ctx, x, kernel_size=(2, 2)): stack = stack_for_pool(x, *kernel_size) ctx.save_for_backward(x.shape) return np.mean(stack, axis=0) @staticmethod def backward(ctx, grad_output): s, = ctx.saved_tensors py, px = ctx.kernel_size return unstack_for_pool( lambda idx: grad_outpu...
grad_output): idxs,s = ctx.saved_tensors return unstack_for_pool( lambda idx: grad_output * (idxs == idx), s, *ctx.kernel_size) register('max_pool2d', MaxPool2D) class AvgPool2D(Function): @staticmethod
64
64
111
11
53
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
AvgPool2D
AvgPool2D
268
281
268
269
875c93c039e0e3e1bfccb1efbe954d68b1cf4931
bigcode/the-stack
train
ae83c31e9edb49aa2702995d
train
class
class Dot(Function): @staticmethod def forward(ctx, input, weight): ctx.save_for_backward(input, weight) return input.dot(weight) @staticmethod def backward(ctx, grad_output): input, weight = ctx.saved_tensors grad_input = grad_output.dot(weight.T) grad_weight = input.T.dot(grad_output) ...
class Dot(Function): @staticmethod
def forward(ctx, input, weight): ctx.save_for_backward(input, weight) return input.dot(weight) @staticmethod def backward(ctx, grad_output): input, weight = ctx.saved_tensors grad_input = grad_output.dot(weight.T) grad_weight = input.T.dot(grad_output) return grad_input, grad_weight
.saved_tensors shape = [1 if axis is None or i in axis else input.shape[i] for i in range(len(input.shape))] return grad_output.reshape(shape) + np.zeros_like(input) register('sum', Sum) # ************* GEMM ************* class Dot(Function): @staticmethod
64
64
83
8
56
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
Dot
Dot
76
87
76
77
5c46a14eb40e705226cb6c8725fe5e3ff211ecb3
bigcode/the-stack
train
33d6e68162f25745ef05b761
train
class
class Mul(Function): @staticmethod def forward(ctx, x, y): ctx.save_for_backward(x, y) return x*y @staticmethod def backward(ctx, grad_output): x,y = ctx.saved_tensors return unbroadcast(y*grad_output, x.shape), unbroadcast(x*grad_output, y.shape)
class Mul(Function): @staticmethod
def forward(ctx, x, y): ctx.save_for_backward(x, y) return x*y @staticmethod def backward(ctx, grad_output): x,y = ctx.saved_tensors return unbroadcast(y*grad_output, x.shape), unbroadcast(x*grad_output, y.shape)
) return x-y @staticmethod def backward(ctx, grad_output): shape_x, shape_y = ctx.saved_tensors return unbroadcast(grad_output, shape_x), unbroadcast(-grad_output, shape_y) register('sub', Sub) class Mul(Function): @staticmethod
64
64
74
8
56
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
Mul
Mul
35
44
35
36
3ecf17cb6e8fc58205e39932e0a6effa230894b1
bigcode/the-stack
train
40ebabd3a164e56bb15dd0a5
train
class
class LogSoftmax(Function): @staticmethod def forward(ctx, input): def logsumexp(x): #return np.log(np.exp(x).sum(axis=1)) c = x.max(axis=1) return c + np.log(np.exp(x-c.reshape((-1, 1))).sum(axis=1)) output = input - logsumexp(input).reshape((-1, 1)) ctx.save_for_backward(output) ...
class LogSoftmax(Function): @staticmethod
def forward(ctx, input): def logsumexp(x): #return np.log(np.exp(x).sum(axis=1)) c = x.max(axis=1) return c + np.log(np.exp(x-c.reshape((-1, 1))).sum(axis=1)) output = input - logsumexp(input).reshape((-1, 1)) ctx.save_for_backward(output) return output @staticmethod def backwar...
) return ret @staticmethod def backward(ctx, grad_output): ret, = ctx.saved_tensors grad_input = grad_output * (ret * (1 - ret)) return grad_input register('sigmoid', Sigmoid) class LogSoftmax(Function): @staticmethod
64
64
141
10
54
bweston92/tinygrad
tinygrad/ops_cpu.py
Python
LogSoftmax
LogSoftmax
155
169
155
156
cd4eb759739484e462837cfde1eb733faf035376
bigcode/the-stack
train
612131b23c9c4005ff955c17
train
function
def test_0_7_6_postgres_pre_add_pipeline_snapshot(hostname, conn_string): engine = create_engine(conn_string) engine.execute('drop schema public cascade;') engine.execute('create schema public;') env = os.environ.copy() env['PGPASSWORD'] = 'test' subprocess.check_call( [ 'ps...
def test_0_7_6_postgres_pre_add_pipeline_snapshot(hostname, conn_string):
engine = create_engine(conn_string) engine.execute('drop schema public cascade;') engine.execute('create schema public;') env = os.environ.copy() env['PGPASSWORD'] = 'test' subprocess.check_call( [ 'psql', '-h', hostname, '-p', ...
= instance._event_storage.get_event_log_table_data(run_id, record_id) if row_data.step_key is not None: step_key_records.append(row_data) assert len(step_key_records) == 0 # run the event_log data migration migrate_event_log_data(instance=instance) step_key...
150
150
503
20
129
flowersw/dagster
python_modules/libraries/dagster-postgres/dagster_postgres_tests/compat_tests/test_back_compat.py
Python
test_0_7_6_postgres_pre_add_pipeline_snapshot
test_0_7_6_postgres_pre_add_pipeline_snapshot
132
207
132
132
489f0e6be2fd2771fb4af87d9a3665d47cc01845
bigcode/the-stack
train
14f53391b6fb20e2a9fdc2ef
train
function
def test_0_7_6_postgres_pre_event_log_migration(hostname, conn_string): engine = create_engine(conn_string) engine.execute('drop schema public cascade;') engine.execute('create schema public;') env = os.environ.copy() env['PGPASSWORD'] = 'test' subprocess.check_call( [ 'psql...
def test_0_7_6_postgres_pre_event_log_migration(hostname, conn_string):
engine = create_engine(conn_string) engine.execute('drop schema public cascade;') engine.execute('create schema public;') env = os.environ.copy() env['PGPASSWORD'] = 'test' subprocess.check_call( [ 'psql', '-h', hostname, '-p', ...
().format(hostname=hostname) target_fd.write(template) instance = DagsterInstance.from_config(tempdir) # Runs will appear in DB, but event logs need migration runs = instance.get_runs() assert len(runs) == 1 assert instance.get_run_by_id(run_id) assert ...
152
152
509
21
130
flowersw/dagster
python_modules/libraries/dagster-postgres/dagster_postgres_tests/compat_tests/test_back_compat.py
Python
test_0_7_6_postgres_pre_event_log_migration
test_0_7_6_postgres_pre_event_log_migration
68
129
68
68
4b8709a9a0ebd31e731b56bfce2c491dadb3a7fa
bigcode/the-stack
train
305e970b93443a779bdc3c06
train
function
def test_0_6_6_postgres(hostname, conn_string): # Init a fresh postgres with a 0.6.6 snapshot engine = create_engine(conn_string) engine.execute('drop schema public cascade;') engine.execute('create schema public;') env = os.environ.copy() env['PGPASSWORD'] = 'test' subprocess.check_call( ...
def test_0_6_6_postgres(hostname, conn_string): # Init a fresh postgres with a 0.6.6 snapshot
engine = create_engine(conn_string) engine.execute('drop schema public cascade;') engine.execute('create schema public;') env = os.environ.copy() env['PGPASSWORD'] = 'test' subprocess.check_call( [ 'psql', '-h', hostname, '-p', ...
import create_engine from dagster import execute_pipeline, pipeline, seven, solid from dagster.core.errors import DagsterInstanceMigrationRequired from dagster.core.instance import DagsterInstance from dagster.core.storage.event_log.migration import migrate_event_log_data from dagster.core.storage.event_log.sql_event...
111
111
371
32
78
flowersw/dagster
python_modules/libraries/dagster-postgres/dagster_postgres_tests/compat_tests/test_back_compat.py
Python
test_0_6_6_postgres
test_0_6_6_postgres
17
65
17
18
02085dcbae2d548eeb13ff8d4e45f9982c2a3fc6
bigcode/the-stack
train
aa57f2ee27d6080a809b089e
train
class
class BasePortalFilter(FilterSet): from_date = DateFilter( field_name='slot__date', lookup_expr=('gt'), label='From', widget=forms.DateInput( attrs={ 'class': 'datepicker' } ), ) to_date = DateFilter( field_name='slot__d...
class BasePortalFilter(FilterSet):
from_date = DateFilter( field_name='slot__date', lookup_expr=('gt'), label='From', widget=forms.DateInput( attrs={ 'class': 'datepicker' } ), ) to_date = DateFilter( field_name='slot__date', lookup_expr=('lt'), ...
from django_filters import FilterSet, DateFilter, OrderingFilter, DateRangeFilter, DateFromToRangeFilter from ... import models from ... import forms class BasePortalFilter(FilterSet):
40
64
156
7
32
daksh-yashlaha/onlineCAL
server/booking_portal/views/user/portal.py
Python
BasePortalFilter
BasePortalFilter
7
40
7
7
9fa164cf1e730a6ca384bebbc159368fcc9c3b6a
bigcode/the-stack
train
3e574c8bc80a81f0d0bf783d
train
function
def edit_usuarios(request, pk): usuarios = get_object_or_404(User, id=pk) if request.method == 'POST': usuarios_form = UserForm(data=request.POST, instance=usuarios) if usuarios_form.is_valid(): usuarios = usuarios_form.save(commit=False) usuarios.save() retu...
def edit_usuarios(request, pk):
usuarios = get_object_or_404(User, id=pk) if request.method == 'POST': usuarios_form = UserForm(data=request.POST, instance=usuarios) if usuarios_form.is_valid(): usuarios = usuarios_form.save(commit=False) usuarios.save() return redirect('lista_usuarios') ...
.POST) if usuarios_form.is_valid(): usuarios = usuarios_form.save(commit=False) usuarios.save() return redirect('lista_usuarios') else: usuarios_form = UserForm() #return render(request=request, template_name='', {'form':usuarios_form}) def edit_usuarios(reque...
64
64
86
8
56
eduardoagreda/requisiciones
apps/usuarios/views.py
Python
edit_usuarios
edit_usuarios
62
71
62
62
2d139ef05603a27f9c9ef57307d6371bfddfcbd8
bigcode/the-stack
train
d3c01260b009b1cda13278f8
train
function
def dashboard(request): return render(request=request, template_name='user/dashboard.html')
def dashboard(request):
return render(request=request, template_name='user/dashboard.html')
.http import JsonResponse from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from apps.usuarios.models import User from apps.usuarios.forms import UserForm from apps.usuarios.serializers import UsersSerializers # Create your views here. def dashboa...
64
64
17
4
60
eduardoagreda/requisiciones
apps/usuarios/views.py
Python
dashboard
dashboard
15
16
15
15
36dc8d336a9988db6ba159b90e429572022eafef
bigcode/the-stack
train
b081cd2e9075e0975c6f31a8
train
function
def log(request): return render(request=request, template_name='user/login.html')
def log(request):
return render(request=request, template_name='user/login.html')
= UserForm(data=request.POST) if usuarios_form.is_valid(): usuarios = usuarios_form.save(commit=False) usuarios.save() return redirect('log') else: usuarios_form = UserForm() return render(request, 'user/registration.html', {'form': usuarios_form}) def log(re...
64
64
17
4
60
eduardoagreda/requisiciones
apps/usuarios/views.py
Python
log
log
32
33
32
32
02d895fbe6e45ef55f04ec2e35eb3cfd140d3ca6
bigcode/the-stack
train
abe2760fbf5cd6cae7034817
train
function
def lista_usuarios(request): usuarios = User.objects.filter(is_staff=False)
def lista_usuarios(request):
usuarios = User.objects.filter(is_staff=False)
'POST' and 'delete' in request.POST: usuarios.delete() return redirect ('lista_usuarios') elif request.method == 'POST' and 'cancel' in request.POST: return redirect('lista_usuarios') #return render(request=request, template_name='') def lista_usuarios(request):
63
64
16
6
58
eduardoagreda/requisiciones
apps/usuarios/views.py
Python
lista_usuarios
lista_usuarios
83
84
83
83
98492798107224884bf7c360ea352600699c53b1
bigcode/the-stack
train
a0d0452caac2b85eb70de957
train
function
def delete_usuarios(request, pk): usuarios = get_object_or_404(User, id=pk) if request.method == 'POST' and 'delete' in request.POST: usuarios.delete() return redirect ('lista_usuarios') elif request.method == 'POST' and 'cancel' in request.POST: return redirect('lista_usuarios')
def delete_usuarios(request, pk):
usuarios = get_object_or_404(User, id=pk) if request.method == 'POST' and 'delete' in request.POST: usuarios.delete() return redirect ('lista_usuarios') elif request.method == 'POST' and 'cancel' in request.POST: return redirect('lista_usuarios')
usuarios_form.is_valid(): usuarios = usuarios_form.save(commit=False) usuarios.save() return redirect('lista_usuarios') else: usuarios_form = UserForm(instance=usuarios) #return render (request=request, template_name='', {'form': usuarios_form}) def delete_usuarios(r...
64
64
75
8
56
eduardoagreda/requisiciones
apps/usuarios/views.py
Python
delete_usuarios
delete_usuarios
74
80
74
74
2e2e8dadded2fef1d7df20c8324b45b7789a756d
bigcode/the-stack
train
1bda927baab8b10794a9381d
train
function
def register(request): if request.method == 'POST': usuarios_form = UserForm(data=request.POST) if usuarios_form.is_valid(): usuarios = usuarios_form.save(commit=False) usuarios.save() return redirect('log') else: usuarios_form = UserForm() return ...
def register(request):
if request.method == 'POST': usuarios_form = UserForm(data=request.POST) if usuarios_form.is_valid(): usuarios = usuarios_form.save(commit=False) usuarios.save() return redirect('log') else: usuarios_form = UserForm() return render(request, 'user/r...
from apps.usuarios.forms import UserForm from apps.usuarios.serializers import UsersSerializers # Create your views here. def dashboard(request): return render(request=request, template_name='user/dashboard.html') def index(request): return render(request=request, template_name='index/index.html') def regist...
64
64
75
4
60
eduardoagreda/requisiciones
apps/usuarios/views.py
Python
register
register
21
30
21
21
2769e18ece6a145462d56aa33f08d4cf1240c1a5
bigcode/the-stack
train
f3a5fdbc6e7617e209dd93fb
train
function
def index(request): return render(request=request, template_name='index/index.html')
def index(request):
return render(request=request, template_name='index/index.html')
View from rest_framework.response import Response from apps.usuarios.models import User from apps.usuarios.forms import UserForm from apps.usuarios.serializers import UsersSerializers # Create your views here. def dashboard(request): return render(request=request, template_name='user/dashboard.html') def index(r...
64
64
17
4
60
eduardoagreda/requisiciones
apps/usuarios/views.py
Python
index
index
18
19
18
18
733d3a22e0405aa6762d7a16c0d4799371f9ea94
bigcode/the-stack
train
f77694de12b14897103bcf8d
train
class
class ListUsuarios(APIView): def get(self, request, format=None): usuarios = User.objects.all() if usuarios: serializer = UsersSerializers(usuarios, many=True) return Response(data={'usuarios':serializer.data}, status=status.HTTP_200_OK) result = {'data': 'Error, no s...
class ListUsuarios(APIView):
def get(self, request, format=None): usuarios = User.objects.all() if usuarios: serializer = UsersSerializers(usuarios, many=True) return Response(data={'usuarios':serializer.data}, status=status.HTTP_200_OK) result = {'data': 'Error, no se encuentran datos en la base...
.save(commit=False) usuarios.save() return redirect('log') else: usuarios_form = UserForm() return render(request, 'user/registration.html', {'form': usuarios_form}) def log(request): return render(request=request, template_name='user/login.html') class ListUsuarios(APIView)...
64
64
160
6
58
eduardoagreda/requisiciones
apps/usuarios/views.py
Python
ListUsuarios
ListUsuarios
35
49
35
35
2464d0d4764fdf2a78335dd68e6605c81aad3883
bigcode/the-stack
train
ed58dd917639cd9d8a041fbb
train
function
def add_usuarios(request): if request.method == 'POST': usuarios_form = UserForm(data=request.POST) if usuarios_form.is_valid(): usuarios = usuarios_form.save(commit=False) usuarios.save() return redirect('lista_usuarios') else: usuarios_form = UserFor...
def add_usuarios(request):
if request.method == 'POST': usuarios_form = UserForm(data=request.POST) if usuarios_form.is_valid(): usuarios = usuarios_form.save(commit=False) usuarios.save() return redirect('lista_usuarios') else: usuarios_form = UserForm()
serializer = UsersSerializers(data = request.data) if serializer.is_valid(): serializer.save() return Response({'usuarios':serializer.data}, status= status.HTTP_201_CREATED) return Response({'usuarios':serializer.errors}, status= status.HTTP_4...
64
64
62
6
58
eduardoagreda/requisiciones
apps/usuarios/views.py
Python
add_usuarios
add_usuarios
51
59
51
51
607820d5d5db58428db6c6249f730e59e0913381
bigcode/the-stack
train
e2c296cd3ed5c0b3c62ce7b5
train
function
def pullRecord(address): """ A record from the database presented in the following article: Larson, P. M.; Jacobsen, K. W.; Schiotz, J. Rich Ground-state chemical Ordering in Nanoparticles: Exact Solution of a Model for Ag-Au Clusters. Phys. Rev. Lett. 2018. 120, 256101. DOI: 10.1103/Phy...
def pullRecord(address):
""" A record from the database presented in the following article: Larson, P. M.; Jacobsen, K. W.; Schiotz, J. Rich Ground-state chemical Ordering in Nanoparticles: Exact Solution of a Model for Ag-Au Clusters. Phys. Rev. Lett. 2018. 120, 256101. DOI: 10.1103/PhysRevLett.120.256101 D...
#!/usr/bin/env python import sys import ase.io import requests ##### sys.exit("Delete this line to re-run database scrape") ##### def pullRecord(address):
37
72
241
5
31
loevlie/ce_expansion
data/larson_et_al/_scrape.py
Python
pullRecord
pullRecord
12
41
12
12
8a390605094161bb28dd9ecd8d70b62342d94d97
bigcode/the-stack
train
b5fdf900ea9d8997eb47ba5d
train
class
class Downloader: """ The ``Downloader`` class handles the download of Jupyter notebooks from Kaggle. It needs the notebook slugs and identifiers ``pandas.DataFrame`` in order to request notebooks from Kaggle. To do so it uses one of the following two strategies: ``HTTP`` to download fu...
class Downloader:
""" The ``Downloader`` class handles the download of Jupyter notebooks from Kaggle. It needs the notebook slugs and identifiers ``pandas.DataFrame`` in order to request notebooks from Kaggle. To do so it uses one of the following two strategies: ``HTTP`` to download full notebooks via H...
""" This module defines the class that handles the actual download of Jupyter notebooks from Kaggle. """ import logging import time from pathlib import Path from tqdm import tqdm import requests from kaggle.api.kaggle_api_extended import KaggleApi # Imports for testing import KGTorrent.config as config from KGTorren...
82
256
1,574
3
78
tinayang3024/KGTorrent
KGTorrent/downloader.py
Python
Downloader
Downloader
18
200
18
18
86b7738130645c93dc35e8e2b6c13aaafa15c2cd
bigcode/the-stack
train
4b81cbdb05ccc9d879c471ce
train
function
def use_route_names_as_operation_ids(app: FastAPI) -> None: """ Simplify operation IDs so that generated API clients have simpler function names. Should be called only after all routes have been added. """ for route in app.routes: if isinstance(route, APIRoute): route.operat...
def use_route_names_as_operation_ids(app: FastAPI) -> None:
""" Simplify operation IDs so that generated API clients have simpler function names. Should be called only after all routes have been added. """ for route in app.routes: if isinstance(route, APIRoute): route.operation_id = route.name # in this case, 'read_items'
from fastapi import FastAPI from fastapi.routing import APIRoute def use_route_names_as_operation_ids(app: FastAPI) -> None:
31
64
81
15
15
cotect/covid-help-api
app/covid_local_api/utils/endpoint_utils.py
Python
use_route_names_as_operation_ids
use_route_names_as_operation_ids
5
14
5
5
8e6db03c2c521723fa8786b567cf8e4a86106e0d
bigcode/the-stack
train
99fb8af64f849969f218e47b
train
function
def setup_mock(drv): context = Mock() devprops = {'MAX_THREADS_PER_BLOCK': 1024, 'COMPUTE_CAPABILITY_MAJOR': 5, 'COMPUTE_CAPABILITY_MINOR': 5} context.return_value.get_device.return_value.get_attributes.return_value = devprops context.return_value.get_device.return_value....
def setup_mock(drv):
context = Mock() devprops = {'MAX_THREADS_PER_BLOCK': 1024, 'COMPUTE_CAPABILITY_MAJOR': 5, 'COMPUTE_CAPABILITY_MINOR': 5} context.return_value.get_device.return_value.get_attributes.return_value = devprops context.return_value.get_device.return_value.compute_capability.re...
import numpy as np try: from mock import patch, Mock except ImportError: from unittest.mock import patch, Mock from kernel_tuner import cuda from kernel_tuner.core import KernelSource, KernelInstance def setup_mock(drv):
53
64
109
6
46
jiskattema/kernel_tuner
test/test_cuda_mocked.py
Python
setup_mock
setup_mock
12
21
12
12
cbd2c43ca48e700a72544f554794f7563e5337b3
bigcode/the-stack
train
e68dec00a36b37fcfe3db963
train
function
@patch('kernel_tuner.cuda.nvml') @patch('kernel_tuner.cuda.DynamicSourceModule') @patch('kernel_tuner.cuda.drv') def test_copy_constant_memory_args(drv, *args): drv = setup_mock(drv) fake_array = np.zeros(10).astype(np.float32) cmem_args = {'fake_array': fake_array} with cuda.CudaFunctions(0) as dev: ...
@patch('kernel_tuner.cuda.nvml') @patch('kernel_tuner.cuda.DynamicSourceModule') @patch('kernel_tuner.cuda.drv') def test_copy_constant_memory_args(drv, *args):
drv = setup_mock(drv) fake_array = np.zeros(10).astype(np.float32) cmem_args = {'fake_array': fake_array} with cuda.CudaFunctions(0) as dev: dev.current_module = Mock() dev.current_module.get_global.return_value = ['get_global'] dev.copy_constant_memory_args(cmem_args) ...
*dev.iterations assert drv.Event.return_value.time_since.call_count == dev.iterations @patch('kernel_tuner.cuda.nvml') @patch('kernel_tuner.cuda.DynamicSourceModule') @patch('kernel_tuner.cuda.drv') def test_copy_constant_memory_args(drv, *args):
64
64
151
44
19
jiskattema/kernel_tuner
test/test_cuda_mocked.py
Python
test_copy_constant_memory_args
test_copy_constant_memory_args
97
113
97
100
47afabd81d44d6e8bf6d01a2bdd9707b531ceb3f
bigcode/the-stack
train
3e10d0ef2ae6fc1514021983
train
function
@patch('kernel_tuner.cuda.nvml') @patch('kernel_tuner.cuda.DynamicSourceModule') @patch('kernel_tuner.cuda.drv') def test_compile(drv, *args): # setup mocked stuff drv = setup_mock(drv) with cuda.CudaFunctions(0) as dev: dev.source_mod = Mock() dev.source_mod.return_value.get_function.retur...
@patch('kernel_tuner.cuda.nvml') @patch('kernel_tuner.cuda.DynamicSourceModule') @patch('kernel_tuner.cuda.drv') def test_compile(drv, *args): # setup mocked stuff
drv = setup_mock(drv) with cuda.CudaFunctions(0) as dev: dev.source_mod = Mock() dev.source_mod.return_value.get_function.return_value = 'func' # call compile kernel_string = "__global__ void vector_add()" kernel_sources = KernelSource(kernel_string, "cuda") kern...
_htod.assert_called_once_with('mem_alloc', b) assert isinstance(gpu_args[0], np.int32) @patch('kernel_tuner.cuda.nvml') @patch('kernel_tuner.cuda.DynamicSourceModule') @patch('kernel_tuner.cuda.drv') def test_compile(drv, *args): # setup mocked stuff
72
72
243
47
25
jiskattema/kernel_tuner
test/test_cuda_mocked.py
Python
test_compile
test_compile
47
72
47
52
64b9c8500c8caaa9891a4a4079007c6494ce6515
bigcode/the-stack
train
e62a8020d0c97387e0dc5d25
train
function
@patch('kernel_tuner.cuda.nvml') @patch('kernel_tuner.cuda.DynamicSourceModule') @patch('kernel_tuner.cuda.drv') def test_benchmark(drv, *args): drv = setup_mock(drv) drv.Event.return_value.time_since.return_value = 0.1 with cuda.CudaFunctions(0) as dev: res = dev.benchmark(dummy_func, [1, 2], (1,...
@patch('kernel_tuner.cuda.nvml') @patch('kernel_tuner.cuda.DynamicSourceModule') @patch('kernel_tuner.cuda.drv') def test_benchmark(drv, *args):
drv = setup_mock(drv) drv.Event.return_value.time_since.return_value = 0.1 with cuda.CudaFunctions(0) as dev: res = dev.benchmark(dummy_func, [1, 2], (1, 2), (1, 2)) assert res["time"] > 0 assert dev.context.synchronize.call_count == 1 assert drv.Event.return_value.synchro...
block=0, grid=0, shared=0, stream=None, texrefs=None): pass @patch('kernel_tuner.cuda.nvml') @patch('kernel_tuner.cuda.DynamicSourceModule') @patch('kernel_tuner.cuda.drv') def test_benchmark(drv, *args):
64
64
173
42
21
jiskattema/kernel_tuner
test/test_cuda_mocked.py
Python
test_benchmark
test_benchmark
79
94
79
82
e52edfba606b3aee03ce30f9b399993160d9441a
bigcode/the-stack
train
d565324dbe3970f6d68605da
train
function
@patch('kernel_tuner.cuda.nvml') @patch('kernel_tuner.cuda.DynamicSourceModule') @patch('kernel_tuner.cuda.drv') def test_copy_texture_memory_args(drv, *args): drv = setup_mock(drv) fake_array = np.zeros(10).astype(np.float32) texmem_args = {'fake_tex': fake_array} texref = Mock() with cuda.CudaF...
@patch('kernel_tuner.cuda.nvml') @patch('kernel_tuner.cuda.DynamicSourceModule') @patch('kernel_tuner.cuda.drv') def test_copy_texture_memory_args(drv, *args):
drv = setup_mock(drv) fake_array = np.zeros(10).astype(np.float32) texmem_args = {'fake_tex': fake_array} texref = Mock() with cuda.CudaFunctions(0) as dev: dev.current_module = Mock() dev.current_module.get_texref.return_value = texref dev.copy_texture_memory_args(texmem...
_global'] dev.copy_constant_memory_args(cmem_args) drv.memcpy_htod.assert_called_once_with('get_global', fake_array) dev.current_module.get_global.assert_called_once_with('fake_array') @patch('kernel_tuner.cuda.nvml') @patch('kernel_tuner.cuda.DynamicSourceModule') @patch('kernel_tuner.cuda.dr...
87
87
293
44
43
jiskattema/kernel_tuner
test/test_cuda_mocked.py
Python
test_copy_texture_memory_args
test_copy_texture_memory_args
116
143
116
119
cc97c427d3eda4779133f3f51d4b17260b057f00
bigcode/the-stack
train
ad2b70cd01b7feca38477b81
train
function
@patch('kernel_tuner.cuda.nvml') @patch('kernel_tuner.cuda.DynamicSourceModule') @patch('kernel_tuner.cuda.drv') def test_ready_argument_list(drv, *args): drv = setup_mock(drv) size = 5 a = np.int32(75) b = np.random.randn(size).astype(np.float32) arguments = [a, b] with cuda.CudaFunctions(0) ...
@patch('kernel_tuner.cuda.nvml') @patch('kernel_tuner.cuda.DynamicSourceModule') @patch('kernel_tuner.cuda.drv') def test_ready_argument_list(drv, *args):
drv = setup_mock(drv) size = 5 a = np.int32(75) b = np.random.randn(size).astype(np.float32) arguments = [a, b] with cuda.CudaFunctions(0) as dev: gpu_args = dev.ready_argument_list(arguments) print(drv.mock_calls) print(gpu_args) drv.mem_alloc.assert_called_once_with(20)...
_context.return_value = context() drv.mem_alloc.return_value = 'mem_alloc' return drv @patch('kernel_tuner.cuda.nvml') @patch('kernel_tuner.cuda.DynamicSourceModule') @patch('kernel_tuner.cuda.drv') def test_ready_argument_list(drv, *args):
64
64
162
43
20
jiskattema/kernel_tuner
test/test_cuda_mocked.py
Python
test_ready_argument_list
test_ready_argument_list
24
44
24
27
da14bdd65f2fc07a803802729d8cdabb645e6648
bigcode/the-stack
train
fa3bffc89828aa97fd7dd7c3
train
function
def dummy_func(a, b, block=0, grid=0, shared=0, stream=None, texrefs=None): pass
def dummy_func(a, b, block=0, grid=0, shared=0, stream=None, texrefs=None):
pass
= list(dev.source_mod.mock_calls[0])[2] assert optional_args['code'] == 'sm_55' assert optional_args['arch'] == 'compute_55' def dummy_func(a, b, block=0, grid=0, shared=0, stream=None, texrefs=None):
64
64
29
26
38
jiskattema/kernel_tuner
test/test_cuda_mocked.py
Python
dummy_func
dummy_func
75
76
75
75
e7c3a080af005f42709f03f049ddd593e4ce69d3
bigcode/the-stack
train
9452c96835983abf9f22b223
train
class
class ListCallerExecutionContext(ExecutionContext): stack: inspect.FrameInfo declared: Location def __init__(self, stack: inspect.FrameInfo, declared: Location): self.stack = stack self.declared = declared def wrap(self, err: UntypyTypeError) -> UntypyTypeError: next_type, indi...
class ListCallerExecutionContext(ExecutionContext):
stack: inspect.FrameInfo declared: Location def __init__(self, stack: inspect.FrameInfo, declared: Location): self.stack = stack self.declared = declared def wrap(self, err: UntypyTypeError) -> UntypyTypeError: next_type, indicator = err.next_type_and_indicator() return...
next_type, indicator = err.next_type_and_indicator() err = err.with_frame(Frame( f"list[{next_type}]", (" " * len("list[") + indicator), None, None )) return self.upper.wrap(err) class ListCallerExecutionContext(ExecutionContext):
64
64
126
9
55
CodeSteak/untypy
untypy/impl/list.py
Python
ListCallerExecutionContext
ListCallerExecutionContext
66
81
66
66
6b5a794d6a4ce5c24d9b7d857822f0e9ba8b4a43
bigcode/the-stack
train
fdb1f423a942b35edf11d06e
train
class
class ListFactory(TypeCheckerFactory): def create_from(self, annotation: Any, ctx: CreationContext) -> Optional[TypeChecker]: if (type(annotation) is GenericAlias and annotation.__origin__ == list) or ( type(annotation) is type(List[int]) and annotation.__origin__ == list): asse...
class ListFactory(TypeCheckerFactory):
def create_from(self, annotation: Any, ctx: CreationContext) -> Optional[TypeChecker]: if (type(annotation) is GenericAlias and annotation.__origin__ == list) or ( type(annotation) is type(List[int]) and annotation.__origin__ == list): assert len(annotation.__args__) == 1 ...
import inspect import sys from types import GenericAlias from typing import Any, Optional, List from untypy.error import UntypyTypeError, Frame, Location from untypy.interfaces import TypeChecker, TypeCheckerFactory, CreationContext, ExecutionContext class ListFactory(TypeCheckerFactory):
62
64
115
7
54
CodeSteak/untypy
untypy/impl/list.py
Python
ListFactory
ListFactory
10
21
10
11
9cf638be3eabc82e90eed83f5096750bede2cf81
bigcode/the-stack
train
d0b4bafc5715d161bc4ec6f7
train
class
class TypedList(list): inner: list checker: TypeChecker ctx: ExecutionContext declared: Location def __init__(self, lst, checker, ctx, declared): super().__init__() self.checker = checker self.inner = lst self.ctx = ctx self.declared = declared # Perform...
class TypedList(list):
inner: list checker: TypeChecker ctx: ExecutionContext declared: Location def __init__(self, lst, checker, ctx, declared): super().__init__() self.checker = checker self.inner = lst self.ctx = ctx self.declared = declared # Perform type check def __g...
describe(self) -> str: return f"list[{self.inner.describe()}]" class ListExecutionContext(ExecutionContext): upper: ExecutionContext def __init__(self, upper: ExecutionContext): self.upper = upper def wrap(self, err: UntypyTypeError) -> UntypyTypeError: next_type, indicator = er...
255
256
1,128
5
250
CodeSteak/untypy
untypy/impl/list.py
Python
TypedList
TypedList
84
222
84
84
6717173ebc06b876987098f85775a18dfbb73585
bigcode/the-stack
train
f5cf9098ad18cfea826ca102
train
class
class TypedListIterator: inner: TypedList index: int def __init__(self, inner): super().__init__() self.inner = inner self.index = 0 def __iter__(self): return self def __next__(self): if self.index >= len(self.inner): raise StopIteration ...
class TypedListIterator:
inner: TypedList index: int def __init__(self, inner): super().__init__() self.inner = inner self.index = 0 def __iter__(self): return self def __next__(self): if self.index >= len(self.inner): raise StopIteration ret = self.inner[self....
ul__(*args, **kwargs) def __sizeof__(self, *args, **kwargs): return self.inner.__sizeof__(*args, **kwargs) def __str__(self): return self.inner.__str__() def __copy__(self): return self.inner.copy() class TypedListIterator:
64
64
94
5
59
CodeSteak/untypy
untypy/impl/list.py
Python
TypedListIterator
TypedListIterator
225
243
225
225
e274447977cc31ce3d88aff615224b5890dbf695
bigcode/the-stack
train
db36b4b7c1418525730ea0bd
train
class
class ListChecker(TypeChecker): inner: TypeChecker declared: Location def __init__(self, inner: TypeChecker, declared: Location): self.inner = inner self.declared = declared def may_change_identity(self) -> bool: return True def check_and_wrap(self, arg: Any, ctx: Executio...
class ListChecker(TypeChecker):
inner: TypeChecker declared: Location def __init__(self, inner: TypeChecker, declared: Location): self.inner = inner self.declared = declared def may_change_identity(self) -> bool: return True def check_and_wrap(self, arg: Any, ctx: ExecutionContext) -> Any: if not...
annotation.__origin__ == list): assert len(annotation.__args__) == 1 inner = ctx.find_checker(annotation.__args__[0]) if inner is None: return None return ListChecker(inner, ctx.declared_location()) else: return None class ListChecker(...
64
64
156
6
57
CodeSteak/untypy
untypy/impl/list.py
Python
ListChecker
ListChecker
24
45
24
24
f5c303cd043b10ebb574848258707362c1dbbd55
bigcode/the-stack
train
280d8472f0147d3b4b92332b
train
class
class ListExecutionContext(ExecutionContext): upper: ExecutionContext def __init__(self, upper: ExecutionContext): self.upper = upper def wrap(self, err: UntypyTypeError) -> UntypyTypeError: next_type, indicator = err.next_type_and_indicator() err = err.with_frame(Frame( ...
class ListExecutionContext(ExecutionContext):
upper: ExecutionContext def __init__(self, upper: ExecutionContext): self.upper = upper def wrap(self, err: UntypyTypeError) -> UntypyTypeError: next_type, indicator = err.next_type_and_indicator() err = err.with_frame(Frame( f"list[{next_type}]", (" " * le...
self.describe())) return TypedList(arg, self.inner, ListExecutionContext(ctx), self.declared) def base_type(self) -> list[Any]: return [list] def describe(self) -> str: return f"list[{self.inner.describe()}]" class ListExecutionContext(ExecutionContext):
63
64
106
8
55
CodeSteak/untypy
untypy/impl/list.py
Python
ListExecutionContext
ListExecutionContext
48
63
48
48
d442d0c035e46f62440e44194791247d4f05dd4d
bigcode/the-stack
train
f0f7b856b0cdc46b6e413f00
train
function
def profile(request): if not request.user.is_authenticated or not hasattr(request.user, 'doctorprofile'): return {} specialities = request.user.doctorprofile.specialities # return {"specialities": [x.title for x in request.user.doctorprofile.specialities.all() if not x.hide]} return {"specialiti...
def profile(request):
if not request.user.is_authenticated or not hasattr(request.user, 'doctorprofile'): return {} specialities = request.user.doctorprofile.specialities # return {"specialities": [x.title for x in request.user.doctorprofile.specialities.all() if not x.hide]} return {"specialities": [] if not special...
access"])) == 0) or ( page.get("module") and not SettingManager.get(page["module"], default='false', default_type='b') ): continue page["active"] = current_path == page.get("url") menu.append(page) return menu def profile(request):
64
64
80
4
59
VladimirovAleksandr/l2
context_processors/utils.py
Python
profile
profile
209
214
209
209
9d4b1f0217a3d4a56ad7670602432fb5f47d418a
bigcode/the-stack
train
2e10144d3db5e76170306230
train
function
def card_bases(request): card_bases_vars = [] for b in Clients.CardBase.objects.filter(hide=False).order_by("pk"): card_bases_vars.append(dict(title=b.title, code=b.short_title, pk=b.pk, history_number=b.history_number)) return {"card_bases": json.dumps(card_bases_vars)}
def card_bases(request):
card_bases_vars = [] for b in Clients.CardBase.objects.filter(hide=False).order_by("pk"): card_bases_vars.append(dict(title=b.title, code=b.short_title, pk=b.pk, history_number=b.history_number)) return {"card_bases": json.dumps(card_bases_vars)}
import simplejson import simplejson as json from django.core.cache import cache import clients.models as Clients from appconf.manager import SettingManager from laboratory import settings from rmis_integration.client import get_md5 from utils.common import get_system_name def card_bases(request):
61
64
71
6
54
VladimirovAleksandr/l2
context_processors/utils.py
Python
card_bases
card_bases
12
16
12
12
7e2a6021bb43359744dc87d6260254a7302826c2
bigcode/the-stack
train
1d2182a23cb5ce49da05038a
train
function
def ws(request): return {"ws_url": json.dumps(settings.WS_URL), "ws_enabled": json.dumps(settings.WS_ENABLED)}
def ws(request):
return {"ws_url": json.dumps(settings.WS_URL), "ws_enabled": json.dumps(settings.WS_ENABLED)}
card_bases_vars.append(dict(title=b.title, code=b.short_title, pk=b.pk, history_number=b.history_number)) return {"card_bases": json.dumps(card_bases_vars)} def local_settings(request): return {"SYSTEM_AS_VI": settings.SYSTEM_AS_VI} def ws(request):
64
64
28
4
60
VladimirovAleksandr/l2
context_processors/utils.py
Python
ws
ws
23
24
23
23
5f944d271d6862e54e3b6683b5e050aae045a7f9
bigcode/the-stack
train
0ff21d88265dd2f9f34edafb
train
function
def make_menu(pages, groups, superuser, current_path=None): menu = [] groups_set = set(groups) for page in pages: if (not superuser and "*" not in page["access"] and len(groups_set & set(page["access"])) == 0) or ( page.get("module") and not SettingManager.get(page["module"], default='fa...
def make_menu(pages, groups, superuser, current_path=None):
menu = [] groups_set = set(groups) for page in pages: if (not superuser and "*" not in page["access"] and len(groups_set & set(page["access"])) == 0) or ( page.get("module") and not SettingManager.get(page["module"], default='false', default_type='b') ): continue ...
, groups, request.user.is_superuser, request.path) cache.set(k, simplejson.dumps(data), 300) else: data = simplejson.loads(data) return {"mainmenu": data, "version": VERSION} def make_menu(pages, groups, superuser, current_path=None):
64
64
114
15
49
VladimirovAleksandr/l2
context_processors/utils.py
Python
make_menu
make_menu
196
206
196
196
a10b448220bb593758310ecb7267e499cbd0b378
bigcode/the-stack
train
4f0a93a42b7bfb030ad5fed9
train
function
def local_settings(request): return {"SYSTEM_AS_VI": settings.SYSTEM_AS_VI}
def local_settings(request):
return {"SYSTEM_AS_VI": settings.SYSTEM_AS_VI}
for b in Clients.CardBase.objects.filter(hide=False).order_by("pk"): card_bases_vars.append(dict(title=b.title, code=b.short_title, pk=b.pk, history_number=b.history_number)) return {"card_bases": json.dumps(card_bases_vars)} def local_settings(request):
63
64
19
5
58
VladimirovAleksandr/l2
context_processors/utils.py
Python
local_settings
local_settings
19
20
19
19
34a7dd32339092be9419177ca68911072c4cb92d
bigcode/the-stack
train
119470b844974c61f827c04a
train
function
def menu(request): from laboratory import VERSION data = [] if request.user.is_authenticated and not request.is_ajax(): groups = [str(x) for x in request.user.groups.all()] if hasattr(request.user, 'groups') else [] k = f'menu:{VERSION}:{get_md5(";".join(groups))}' data = cache.get...
def menu(request):
from laboratory import VERSION data = [] if request.user.is_authenticated and not request.is_ajax(): groups = [str(x) for x in request.user.groups.all()] if hasattr(request.user, 'groups') else [] k = f'menu:{VERSION}:{get_md5(";".join(groups))}' data = cache.get(k) if not ...
import simplejson import simplejson as json from django.core.cache import cache import clients.models as Clients from appconf.manager import SettingManager from laboratory import settings from rmis_integration.client import get_md5 from utils.common import get_system_name def card_bases(request): card_bases_vars...
178
256
2,755
4
174
VladimirovAleksandr/l2
context_processors/utils.py
Python
menu
menu
27
193
27
27
abb1120ab9826d01bee0168b84aea8a6c881b77b
bigcode/the-stack
train
ea0d26ee8f1fbf9664a3e066
train
class
class TestPHPApplication(TestApplicationPHP): prerequisites = {'modules': {'php': 'all'}} def before_disable_functions(self): body = self.get()['body'] assert re.search(r'time: \d+', body), 'disable_functions before time' assert re.search(r'exec: \/\w+', body), 'disable_functions befor...
class TestPHPApplication(TestApplicationPHP):
prerequisites = {'modules': {'php': 'all'}} def before_disable_functions(self): body = self.get()['body'] assert re.search(r'time: \d+', body), 'disable_functions before time' assert re.search(r'exec: \/\w+', body), 'disable_functions before exec' def set_opcache(self, app, val): ...
import os import re import shutil import time from subprocess import call import pytest from unit.applications.lang.php import TestApplicationPHP from unit.option import option class TestPHPApplication(TestApplicationPHP):
45
256
5,063
8
36
wujjpp/un
test/test_php_application.py
Python
TestPHPApplication
TestPHPApplication
13
715
13
13
1c60b6f5d77c2534dcbd75e727a3f9f1c7d36633
bigcode/the-stack
train
1ce8c388d53f30cec7f39bbe
train
function
def reflections(depth, e_zH, Gam, lrec, lsrc, use_ne_eval): """Calculate Rp, Rm. .. math:: R^\pm_n, \\bar{R}^\pm_n This function corresponds to equations 64/65 and A-11/A-12 in [Hunziker_et_al_2015]_, and loosely to the corresponding files ``Rmin.F90`` and ``Rplus.F90``. This function is call...
def reflections(depth, e_zH, Gam, lrec, lsrc, use_ne_eval):
"""Calculate Rp, Rm. .. math:: R^\pm_n, \\bar{R}^\pm_n This function corresponds to equations 64/65 and A-11/A-12 in [Hunziker_et_al_2015]_, and loosely to the corresponding files ``Rmin.F90`` and ``Rplus.F90``. This function is called from the function :mod:`kernel.greenfct`. """ #...
lrec, :]/gamTM[:, :, lsrc, :]) PTE = 0 elif ab in [31, 32]: PTM = GTM/etaV[:, None, lrec, None] PTE = 0 elif ab in [34, 35]: PTM = ((etaH[:, lsrc]/etaV[:, lrec])[:, None, None] * GTM/gamTM[:, :, lsrc, :]) PTE = 0 elif ab in [16, 26]: PTM = 0 ...
256
256
868
20
235
sgkang/empymod
empymod/kernel.py
Python
reflections
reflections
334
424
334
334
bc0b5898d22da282e7288b87f0fecaaccdcbb590
bigcode/the-stack
train
db7ca8a1f9a216fc43d51a96
train
function
def fullspace(off, angle, zsrc, zrec, etaH, etaV, zetaH, zetaV, ab, msrc, mrec): """Analytical full-space solutions in the frequency domain. .. math:: \\hat{G}^{ee}_{\\alpha\\beta}, \\hat{G}^{ee}_{3\\alpha}, \\hat{G}^{ee}_{33}, \\hat{G}^{em}_{\\alpha\\beta}, \\hat{G}^{...
def fullspace(off, angle, zsrc, zrec, etaH, etaV, zetaH, zetaV, ab, msrc, mrec):
"""Analytical full-space solutions in the frequency domain. .. math:: \\hat{G}^{ee}_{\\alpha\\beta}, \\hat{G}^{ee}_{3\\alpha}, \\hat{G}^{ee}_{33}, \\hat{G}^{em}_{\\alpha\\beta}, \\hat{G}^{em}_{\\alpha 3} This function corresponds to equations 45--50 in [Hunziker_et_al_2015]_, ...
.pi/2 else: fct = np.sin test_ang_1 = np.pi test_ang_2 = 2*np.pi if ab in [11, 22, 15, 24, 12, 21, 14, 25]: eangle = 2*angle else: eangle = angle # Get factor factAng = fct(eangle) # Ensure cos([pi/2, 3pi/2]) and sin([pi, 2pi]) are zero (floating point ...
256
256
2,115
36
219
sgkang/empymod
empymod/kernel.py
Python
fullspace
fullspace
648
817
648
649
5498405c5456d5c98593977f759b35687e14fa4d
bigcode/the-stack
train
ff6b567a007a2d5959bbdd9d
train
function
def halfspace(off, angle, zsrc, zrec, etaH, etaV, freqtime, ab, signal, solution='dhs'): """Return frequency- or time-space domain VTI half-space solution. Calculates the frequency- or time-space domain electromagnetic response for a half-space below air using the diffusive approximation, as ...
def halfspace(off, angle, zsrc, zrec, etaH, etaV, freqtime, ab, signal, solution='dhs'):
"""Return frequency- or time-space domain VTI half-space solution. Calculates the frequency- or time-space domain electromagnetic response for a half-space below air using the diffusive approximation, as given in [Slob_et_al_2010]_, where the electric source is located at [0, 0, zsrc], and the elec...
, 16]: coo = yco else: coo = -xco # Define R, lGam, uGam, e_zH, and e_zV if ab in [34, 35]: coo *= -1 R = RTM lGam = lGamTM uGam = uGamTM e_zH = etaH e_zV = etaV else: zrec, zsrc ...
256
256
4,129
32
223
sgkang/empymod
empymod/kernel.py
Python
halfspace
halfspace
820
1,133
820
821
6f8f2f0b3d744ce94092e0ede42a85c3fa294e9d
bigcode/the-stack
train
2dbb307b749c093039447b39
train
function
def fields(depth, Rp, Rm, Gam, lrec, lsrc, zsrc, ab, TM, use_ne_eval): """Calculate Pu+, Pu-, Pd+, Pd-. .. math:: P^{u\pm}_s, P^{d\pm}_s, \\bar{P}^{u\pm}_s, \\bar{P}^{d\pm}_s; P^{u\pm}_{s-1}, P^{u\pm}_n, \\bar{P}^{u\pm}_{s-1}, \\bar{P}^{u\pm}_n; P^{d\pm}_{s+1}, P^{d\pm}_n, \\bar{P}^{d\pm}_{...
def fields(depth, Rp, Rm, Gam, lrec, lsrc, zsrc, ab, TM, use_ne_eval):
"""Calculate Pu+, Pu-, Pd+, Pd-. .. math:: P^{u\pm}_s, P^{d\pm}_s, \\bar{P}^{u\pm}_s, \\bar{P}^{d\pm}_s; P^{u\pm}_{s-1}, P^{u\pm}_n, \\bar{P}^{u\pm}_{s-1}, \\bar{P}^{u\pm}_n; P^{d\pm}_{s+1}, P^{d\pm}_n, \\bar{P}^{d\pm}_{s+1}, \\bar{P}^{d\pm}_n This function corresponds to equations 81/...
# Eqs 64, A-11 if use_ne_eval: tRef = use_ne_eval("(rloc + term)/(1 + rloc*term)") else: tRef = (rloc + term)/(1 + rloc*term) # The global reflection coefficient is given back for all layers # between and including src- and rec...
256
256
1,946
28
227
sgkang/empymod
empymod/kernel.py
Python
fields
fields
427
586
427
427
7c0eaa5fdf281bbbbcd10a1560b88274b946931c
bigcode/the-stack
train
5577ebf39f344d31f19a88a0
train
function
def wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH, zetaV, lambd, ab, xdirect, msrc, mrec, use_ne_eval): """Calculate wavenumber domain solution. Return the wavenumber domain solutions ``PJ0``, ``PJ1``, and ``PJ0b``, which have to be transformed with a Hankel transform to the fr...
def wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH, zetaV, lambd, ab, xdirect, msrc, mrec, use_ne_eval):
"""Calculate wavenumber domain solution. Return the wavenumber domain solutions ``PJ0``, ``PJ1``, and ``PJ0b``, which have to be transformed with a Hankel transform to the frequency domain. ``PJ0``/``PJ0b`` and ``PJ1`` have to be transformed with Bessel functions of order 0 (:math:`J_0`) and 1 (:ma...
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" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ...
256
256
1,277
51
204
sgkang/empymod
empymod/kernel.py
Python
wavenumber
wavenumber
51
147
51
52
8375cf10ecd9914a614485dac3f91a6cfc7cde12
bigcode/the-stack
train
19f91e36f5109b43372a0a2a
train
function
def greenfct(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH, zetaV, lambd, ab, xdirect, msrc, mrec, use_ne_eval): """Calculate Green's function for TM and TE. .. math:: \\tilde{g}^{tm}_{hh}, \\tilde{g}^{tm}_{hz}, \\tilde{g}^{tm}_{zh}, \\tilde{g}^{tm}_{zz}, \\tilde{g}^...
def greenfct(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH, zetaV, lambd, ab, xdirect, msrc, mrec, use_ne_eval):
"""Calculate Green's function for TM and TE. .. math:: \\tilde{g}^{tm}_{hh}, \\tilde{g}^{tm}_{hz}, \\tilde{g}^{tm}_{zh}, \\tilde{g}^{tm}_{zz}, \\tilde{g}^{te}_{hh}, \\tilde{g}^{te}_{zz} This function corresponds to equations 108--110, 117/118, 122; 89--94, A18--A23, B13--B1...
26]: # Eqs 107, 113, 114, 115, PJ0 = Ptot2 # 0s # . 121, 125, 126, 127 PJ1 = Ptot1*lambd*lambd PJ0b = Ptot2 # 0s elif ab in [33, ]: # Eq 116 PJ0 = Ptot1*lambd*lambd*lambd PJ1 = Ptot2 # 0s PJ0b = Ptot2 # 0s ...
256
256
2,275
51
204
sgkang/empymod
empymod/kernel.py
Python
greenfct
greenfct
150
331
150
151
de60b1f938a5dd917a45a000793f08f7a55f20cd
bigcode/the-stack
train
8f9e90ef8259c2db3d976a97
train
function
def angle_factor(angle, ab, msrc, mrec): """Return the angle-dependent factor. The whole calculation in the wavenumber domain is only a function of the distance between the source and the receiver, it is independent of the angel. The angle-dependency is this factor, which can be applied to the corr...
def angle_factor(angle, ab, msrc, mrec):
"""Return the angle-dependent factor. The whole calculation in the wavenumber domain is only a function of the distance between the source and the receiver, it is independent of the angel. The angle-dependency is this factor, which can be applied to the corresponding parts in the wavenumber or in t...
depth = depth[isr+iz+1] - depth[isr+iz] iRpm = Rpm[:, :, iz, :] iGam = Gam[:, :, isr+iz, :] if use_ne_eval: P = use_ne_eval("P/(1 + " + "iRpm*exp(-2*iGam * ddepth))") ...
161
161
538
13
147
sgkang/empymod
empymod/kernel.py
Python
angle_factor
angle_factor
591
643
591
591
ea3447235ecb4f3c114820ecff27101d36241f4e
bigcode/the-stack
train
50652cb07b1d5cb2b2ca878d
train
class
class S256(DataDigester): def digest(self, data: bytes) -> bytes: """ SHA-256 """ return hashlib.sha256(data).digest()
class S256(DataDigester):
def digest(self, data: bytes) -> bytes: """ SHA-256 """ return hashlib.sha256(data).digest()
5 digest """ hash_obj = hashlib.md5() hash_obj.update(data) return hash_obj.digest() class S1(DataDigester): def digest(self, data: bytes) -> bytes: """ SHA1 Digest """ return hashlib.sha1(data).digest() class S256(DataDigester):
64
64
34
7
57
dimchat/mkm-py
mkm/crypto/digest.py
Python
S256
S256
90
94
90
91
345a8f7b2ef28b2dd0f2c91f582d248e75bf032d
bigcode/the-stack
train
83d02122f0e4a33576b4fa96
train
function
def keccak256(data: bytes) -> bytes: return KECCAK256.digest(data=data)
def keccak256(data: bytes) -> bytes:
return KECCAK256.digest(data=data)
md5(data: bytes) -> bytes: return MD5.digest(data=data) def sha1(data: bytes) -> bytes: return SHA1.digest(data=data) def sha256(data: bytes) -> bytes: return SHA256.digest(data=data) def keccak256(data: bytes) -> bytes:
64
64
21
11
53
dimchat/mkm-py
mkm/crypto/digest.py
Python
keccak256
keccak256
61
62
61
61
908c5448fda6705708c1b22a7d3a6feadf247e94
bigcode/the-stack
train
0ed8ba6959f0a49610ea1f95
train
function
def sha256(data: bytes) -> bytes: return SHA256.digest(data=data)
def sha256(data: bytes) -> bytes:
return SHA256.digest(data=data)
, data: bytes) -> bytes: raise NotImplemented """ Interfaces """ def md5(data: bytes) -> bytes: return MD5.digest(data=data) def sha1(data: bytes) -> bytes: return SHA1.digest(data=data) def sha256(data: bytes) -> bytes:
64
64
18
10
54
dimchat/mkm-py
mkm/crypto/digest.py
Python
sha256
sha256
57
58
57
57
89023159db94b63d1b3882bd208df9537b9b59ad
bigcode/the-stack
train
545f7d67ad606feaaa429944
train
class
class SHA256: digester: DataDigester = S256() @staticmethod def digest(data: bytes) -> bytes: assert SHA256.digester is not None, 'SHA256 coder not set yet' return SHA256.digester.digest(data=data)
class SHA256:
digester: DataDigester = S256() @staticmethod def digest(data: bytes) -> bytes: assert SHA256.digester is not None, 'SHA256 coder not set yet' return SHA256.digester.digest(data=data)
) class SHA1: digester: DataDigester = S1() @staticmethod def digest(data: bytes) -> bytes: assert SHA1.digester is not None, 'SHA1 coder not set yet' return SHA1.digester.digest(data=data) class SHA256:
64
64
59
4
60
dimchat/mkm-py
mkm/crypto/digest.py
Python
SHA256
SHA256
124
130
124
124
762ce26de3e842e37d24c9ed95d4ee966c683d46
bigcode/the-stack
train
d5d6eba95fae8124cce100c7
train
function
def ripemd160(data: bytes) -> bytes: return RIPEMD160.digest(data=data)
def ripemd160(data: bytes) -> bytes:
return RIPEMD160.digest(data=data)
: bytes) -> bytes: return SHA1.digest(data=data) def sha256(data: bytes) -> bytes: return SHA256.digest(data=data) def keccak256(data: bytes) -> bytes: return KECCAK256.digest(data=data) def ripemd160(data: bytes) -> bytes:
64
64
21
11
53
dimchat/mkm-py
mkm/crypto/digest.py
Python
ripemd160
ripemd160
65
66
65
65
1dc76198dd78b6474c710e4385a5ec8e7507321e
bigcode/the-stack
train
6204cbf012b3378e65bdf464
train
class
class S1(DataDigester): def digest(self, data: bytes) -> bytes: """ SHA1 Digest """ return hashlib.sha1(data).digest()
class S1(DataDigester):
def digest(self, data: bytes) -> bytes: """ SHA1 Digest """ return hashlib.sha1(data).digest()
MD160.digest(data=data) """ Implementations """ class M5(DataDigester): def digest(self, data: bytes) -> bytes: """ MD5 digest """ hash_obj = hashlib.md5() hash_obj.update(data) return hash_obj.digest() class S1(DataDigester):
64
64
34
7
57
dimchat/mkm-py
mkm/crypto/digest.py
Python
S1
S1
83
87
83
84
4767ea75944e8eac7d8d1a0938d87280652f8845
bigcode/the-stack
train
7f7edfd9bf59604cf87ba67a
train
class
class R160(DataDigester): def digest(self, data: bytes) -> bytes: """ RIPEMD-160 """ hash_obj = hashlib.new('ripemd160') hash_obj.update(data) return hash_obj.digest()
class R160(DataDigester):
def digest(self, data: bytes) -> bytes: """ RIPEMD-160 """ hash_obj = hashlib.new('ripemd160') hash_obj.update(data) return hash_obj.digest()
, data: bytes) -> bytes: """ SHA1 Digest """ return hashlib.sha1(data).digest() class S256(DataDigester): def digest(self, data: bytes) -> bytes: """ SHA-256 """ return hashlib.sha256(data).digest() class R160(DataDigester):
64
64
50
7
57
dimchat/mkm-py
mkm/crypto/digest.py
Python
R160
R160
97
103
97
98
b4586cce56d3824b0abd121a40aff09f7c31e615
bigcode/the-stack
train
beee31d56441b8564d640f3d
train
class
class DataDigester: @abstractmethod def digest(self, data: bytes) -> bytes: raise NotImplemented
class DataDigester: @abstractmethod
def digest(self, data: bytes) -> bytes: raise NotImplemented
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ============================================================================== """ Data Digest ~~~~~~~~~~~ MD5, SHA-256, RipeMD-160 """ import hashlib from abc import abstractmethod class DataDigester: @abstractmethod...
64
64
27
10
53
dimchat/mkm-py
mkm/crypto/digest.py
Python
DataDigester
DataDigester
37
41
37
39
4b3cfbe1d86ea04b5a8479ebdbc8d45cd773a6a2
bigcode/the-stack
train
829498abdb2c8c4748234b87
train
function
def sha1(data: bytes) -> bytes: return SHA1.digest(data=data)
def sha1(data: bytes) -> bytes:
return SHA1.digest(data=data)
import abstractmethod class DataDigester: @abstractmethod def digest(self, data: bytes) -> bytes: raise NotImplemented """ Interfaces """ def md5(data: bytes) -> bytes: return MD5.digest(data=data) def sha1(data: bytes) -> bytes:
64
64
18
10
54
dimchat/mkm-py
mkm/crypto/digest.py
Python
sha1
sha1
53
54
53
53
a2601189f97619845830f5c414c5fffdab8bb2f1
bigcode/the-stack
train
ffd8402557845b71116cc32b
train
class
class MD5: digester: DataDigester = M5() @staticmethod def digest(data: bytes) -> bytes: assert MD5.digester is not None, 'MD5 coder not set yet' return MD5.digester.digest(data=data)
class MD5:
digester: DataDigester = M5() @staticmethod def digest(data: bytes) -> bytes: assert MD5.digester is not None, 'MD5 coder not set yet' return MD5.digester.digest(data=data)
""" return hashlib.sha256(data).digest() class R160(DataDigester): def digest(self, data: bytes) -> bytes: """ RIPEMD-160 """ hash_obj = hashlib.new('ripemd160') hash_obj.update(data) return hash_obj.digest() class MD5:
64
64
59
4
60
dimchat/mkm-py
mkm/crypto/digest.py
Python
MD5
MD5
106
112
106
106
716a161913750a3692fc0734954a400e7d66f6bd
bigcode/the-stack
train