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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8c047fc336205e4374cc2b39 | train | function | @pytest.mark.slow
@pytest.mark.vivado
def test_build_dataflow_directory():
test_dir = make_build_dir("test_build_dataflow_directory_")
target_dir = test_dir + "/build_dataflow"
example_data_dir = pk.resource_filename("finn.qnn-data", "build_dataflow/")
copytree(example_data_dir, target_dir)
build_da... | @pytest.mark.slow
@pytest.mark.vivado
def test_build_dataflow_directory():
| test_dir = make_build_dir("test_build_dataflow_directory_")
target_dir = test_dir + "/build_dataflow"
example_data_dir = pk.resource_filename("finn.qnn-data", "build_dataflow/")
copytree(example_data_dir, target_dir)
build_dataflow_directory(target_dir)
# check the generated files
output_dir... | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR O... | 148 | 148 | 495 | 17 | 130 | mmrahorovic/finn | tests/util/test_build_dataflow.py | Python | test_build_dataflow_directory | test_build_dataflow_directory | 40 | 74 | 40 | 42 | efeb64d041b19cd8db979fd602e08ff3469ad8b8 | bigcode/the-stack | train |
7dfcf75d6dd7897d6037bfb0 | train | class | class CVAEWithLossCell(nn.WithLossCell):
"""
Rewrite WithLossCell for CVAE
"""
def construct(self, data, label):
out = self._backbone(data, label)
return self._loss_fn(out, label)
| class CVAEWithLossCell(nn.WithLossCell):
| """
Rewrite WithLossCell for CVAE
"""
def construct(self, data, label):
out = self._backbone(data, label)
return self._loss_fn(out, label)
| moid = nn.Sigmoid()
self.reshape = ops.Reshape()
def construct(self, z):
z = self.fc2(z)
z = self.reshape(z, IMAGE_SHAPE)
z = self.sigmoid(z)
return z
class CVAEWithLossCell(nn.WithLossCell):
| 64 | 64 | 54 | 11 | 52 | PowerOlive/mindspore | tests/st/probability/dpn/test_gpu_svi_cvae.py | Python | CVAEWithLossCell | CVAEWithLossCell | 63 | 69 | 63 | 63 | b79e02ef82d3ee57283cc44c29240e2c0ce62ffc | bigcode/the-stack | train |
68411e160bd2f2c58000cab1 | train | class | class Encoder(nn.Cell):
def __init__(self, num_classes):
super(Encoder, self).__init__()
self.fc1 = nn.Dense(1024 + num_classes, 400)
self.relu = nn.ReLU()
self.flatten = nn.Flatten()
self.concat = ops.Concat(axis=1)
self.one_hot = nn.OneHot(depth=num_classes)
... | class Encoder(nn.Cell):
| def __init__(self, num_classes):
super(Encoder, self).__init__()
self.fc1 = nn.Dense(1024 + num_classes, 400)
self.relu = nn.ReLU()
self.flatten = nn.Flatten()
self.concat = ops.Concat(axis=1)
self.one_hot = nn.OneHot(depth=num_classes)
def construct(self... | import ELBO, SVI
context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
IMAGE_SHAPE = (-1, 1, 32, 32)
image_path = os.path.join('/home/workspace/mindspore_dataset/mnist', "train")
class Encoder(nn.Cell):
| 63 | 64 | 139 | 5 | 58 | PowerOlive/mindspore | tests/st/probability/dpn/test_gpu_svi_cvae.py | Python | Encoder | Encoder | 31 | 46 | 31 | 31 | d7d50ad04116003094b14829770b74ca423381b3 | bigcode/the-stack | train |
6c655035e939849bcb6c4855 | train | function | def create_dataset(data_path, batch_size=32, repeat_size=1,
num_parallel_workers=1):
"""
create dataset for train or test
"""
# define dataset
mnist_ds = ds.MnistDataset(data_path)
resize_height, resize_width = 32, 32
rescale = 1.0 / 255.0
shift = 0.0
... | def create_dataset(data_path, batch_size=32, repeat_size=1,
num_parallel_workers=1):
| """
create dataset for train or test
"""
# define dataset
mnist_ds = ds.MnistDataset(data_path)
resize_height, resize_width = 32, 32
rescale = 1.0 / 255.0
shift = 0.0
# define map operations
resize_op = CV.Resize((resize_height, resize_width)) # Bilinear mode
r... | return z
class CVAEWithLossCell(nn.WithLossCell):
"""
Rewrite WithLossCell for CVAE
"""
def construct(self, data, label):
out = self._backbone(data, label)
return self._loss_fn(out, label)
def create_dataset(data_path, batch_size=32, repeat_size=1,
num_par... | 80 | 80 | 268 | 23 | 57 | PowerOlive/mindspore | tests/st/probability/dpn/test_gpu_svi_cvae.py | Python | create_dataset | create_dataset | 72 | 98 | 72 | 73 | b4404830f15763b18887b8317d9e69d988882cdd | bigcode/the-stack | train |
2adbf8f22b4e75cad1f9deb1 | train | class | class Decoder(nn.Cell):
def __init__(self):
super(Decoder, self).__init__()
self.fc2 = nn.Dense(400, 1024)
self.sigmoid = nn.Sigmoid()
self.reshape = ops.Reshape()
def construct(self, z):
z = self.fc2(z)
z = self.reshape(z, IMAGE_SHAPE)
z = self... | class Decoder(nn.Cell):
| def __init__(self):
super(Decoder, self).__init__()
self.fc2 = nn.Dense(400, 1024)
self.sigmoid = nn.Sigmoid()
self.reshape = ops.Reshape()
def construct(self, z):
z = self.fc2(z)
z = self.reshape(z, IMAGE_SHAPE)
z = self.sigmoid(z)
retu... | def construct(self, x, y):
x = self.flatten(x)
y = self.one_hot(y)
input_x = self.concat((x, y))
input_x = self.fc1(input_x)
input_x = self.relu(input_x)
return input_x
class Decoder(nn.Cell):
| 64 | 64 | 92 | 5 | 58 | PowerOlive/mindspore | tests/st/probability/dpn/test_gpu_svi_cvae.py | Python | Decoder | Decoder | 49 | 60 | 49 | 49 | 956936950ccc1f68a3c5f0f93598acf695cf67f3 | bigcode/the-stack | train |
d0d8b88efb19e29c17b277a5 | train | function | def test_svi_cvae():
# define the encoder and decoder
encoder = Encoder(num_classes=10)
decoder = Decoder()
# define the cvae model
cvae = ConditionalVAE(encoder, decoder, hidden_size=400, latent_size=20, num_classes=10)
# define the loss function
net_loss = ELBO(latent_prior='Normal'... | def test_svi_cvae():
# define the encoder and decoder
| encoder = Encoder(num_classes=10)
decoder = Decoder()
# define the cvae model
cvae = ConditionalVAE(encoder, decoder, hidden_size=400, latent_size=20, num_classes=10)
# define the loss function
net_loss = ELBO(latent_prior='Normal', output_prior='Normal')
# define the optimizer
op... | image", num_parallel_workers=num_parallel_workers)
mnist_ds = mnist_ds.map(operations=rescale_op, input_columns="image", num_parallel_workers=num_parallel_workers)
mnist_ds = mnist_ds.map(operations=hwc2chw_op, input_columns="image", num_parallel_workers=num_parallel_workers)
# apply DatasetOps
mn... | 118 | 118 | 396 | 15 | 102 | PowerOlive/mindspore | tests/st/probability/dpn/test_gpu_svi_cvae.py | Python | test_svi_cvae | test_svi_cvae | 101 | 131 | 101 | 102 | 47277f6f6bb3041aee2fe82a5cdf6802da18ec7c | bigcode/the-stack | train |
3b9aa63608174e6d9981928e | train | class | class rmhd2d_ppc(rmhd2d):
'''
PETSc/Python Reduced MHD Solver in 2D using physics based preconditioner.
'''
def __init__(self, cfgfile):
'''
Constructor
'''
super().__init__(cfgfile, mode = "ppc")
OptDB = PETSc.Options()
# ... | class rmhd2d_ppc(rmhd2d):
| '''
PETSc/Python Reduced MHD Solver in 2D using physics based preconditioner.
'''
def __init__(self, cfgfile):
'''
Constructor
'''
super().__init__(cfgfile, mode = "ppc")
OptDB = PETSc.Options()
# OptDB.setValue('ksp_... | '''
Created on Mar 23, 2012
@author: Michael Kraus (michael.kraus@ipp.mpg.de)
'''
from run_rmhd2d import rmhd2d
import numpy as np
from numpy import abs
import time
from petsc4py import PETSc
from rmhd.solvers.common.PETScDerivatives import PETScDerivatives
from rmhd.solvers.linear.... | 206 | 256 | 1,818 | 13 | 192 | DDMGNI/viRMHD2D | run_rmhd2d_ppc.py | Python | rmhd2d_ppc | rmhd2d_ppc | 23 | 215 | 23 | 23 | 75b31a74d4b001d3fb61c624cc16a3c2b93c4f9b | bigcode/the-stack | train |
383a6964e94e6b5b2f5242bc | train | class | class Hud:
def __init__(self):
pass
vertical_speed = 10
est_alt = 10
bar_alt = 10
ang_x = 20
ang_y = 10
heading = 350
speed = 45
| class Hud:
| def __init__(self):
pass
vertical_speed = 10
est_alt = 10
bar_alt = 10
ang_x = 20
ang_y = 10
heading = 350
speed = 45
| class Hud:
| 3 | 64 | 60 | 3 | 0 | pydys/rasberry-inav-fpv-osd | DataModel/Hud.py | Python | Hud | Hud | 1 | 11 | 1 | 1 | 6a2b19e9b94a2566bddd310e1b8ccc9d499bb8a6 | bigcode/the-stack | train |
72f63c7daf3c8a9fbb11e482 | train | function | def create_blender_context(active: Optional[bpy.types.Object] = None,
selected: Optional[bpy.types.Object] = None,):
"""Create a new Blender context. If an object is passed as
parameter, it is set as selected and active.
"""
if not isinstance(selected, list):
selected... | def create_blender_context(active: Optional[bpy.types.Object] = None,
selected: Optional[bpy.types.Object] = None,):
| """Create a new Blender context. If an object is passed as
parameter, it is set as selected and active.
"""
if not isinstance(selected, list):
selected = [selected]
override_context = bpy.context.copy()
for win in bpy.context.window_manager.windows:
for area in win.screen.area... | , container_name):
name = data.name
local_data = data.make_local()
local_data.name = f"{name}:{container_name}"
return local_data
def create_blender_context(active: Optional[bpy.types.Object] = None,
selected: Optional[bpy.types.Object] = None,):
| 64 | 64 | 210 | 29 | 34 | dangerstudios/OpenPype | openpype/hosts/blender/api/plugin.py | Python | create_blender_context | create_blender_context | 59 | 83 | 59 | 60 | c4ffb5093d80488e79dad4a2ffc97a6cedf4a4a8 | bigcode/the-stack | train |
870a49c6e07ca0b535e1614b | train | function | def get_local_collection_with_name(name):
for collection in bpy.data.collections:
if collection.name == name and collection.library is None:
return collection
return None
| def get_local_collection_with_name(name):
| for collection in bpy.data.collections:
if collection.name == name and collection.library is None:
return collection
return None
| _parent_collection(collection):
"""Get the parent of the input collection"""
check_list = [bpy.context.scene.collection]
for c in check_list:
if collection.name in c.children.keys():
return c
check_list.extend(c.children)
return None
def get_local_collection_with_name(name)... | 64 | 64 | 36 | 8 | 55 | dangerstudios/OpenPype | openpype/hosts/blender/api/plugin.py | Python | get_local_collection_with_name | get_local_collection_with_name | 98 | 102 | 98 | 98 | 9e01614e4470e16a9d515ead0e74e33173af7ca2 | bigcode/the-stack | train |
c86fd93b991ebd5418b8a64f | train | function | def get_parent_collection(collection):
"""Get the parent of the input collection"""
check_list = [bpy.context.scene.collection]
for c in check_list:
if collection.name in c.children.keys():
return c
check_list.extend(c.children)
return None
| def get_parent_collection(collection):
| """Get the parent of the input collection"""
check_list = [bpy.context.scene.collection]
for c in check_list:
if collection.name in c.children.keys():
return c
check_list.extend(c.children)
return None
| override_context['region'] = region
override_context['scene'] = bpy.context.scene
override_context['active_object'] = active
override_context['selected_objects'] = selected
return override_context
... | 63 | 64 | 58 | 6 | 57 | dangerstudios/OpenPype | openpype/hosts/blender/api/plugin.py | Python | get_parent_collection | get_parent_collection | 86 | 95 | 86 | 86 | 74406a01b958774ed0bf688327a4094891618e8d | bigcode/the-stack | train |
2b2198c9c3d0b3b9a291461a | train | function | def prepare_data(data, container_name):
name = data.name
local_data = data.make_local()
local_data.name = f"{name}:{container_name}"
return local_data
| def prepare_data(data, container_name):
| name = data.name
local_data = data.make_local()
local_data.name = f"{name}:{container_name}"
return local_data
| = f"{asset}_{count:0>2}_{subset}_CON"
while name in container_names:
count += 1
name = f"{asset}_{count:0>2}_{subset}_CON"
return f"{count:0>2}"
def prepare_data(data, container_name):
| 63 | 64 | 39 | 8 | 55 | dangerstudios/OpenPype | openpype/hosts/blender/api/plugin.py | Python | prepare_data | prepare_data | 52 | 56 | 52 | 52 | d9cc1efe3e343b9d21fbce64dff5afdcf07b630e | bigcode/the-stack | train |
28cead6e64d102ca330f363e | train | function | def asset_name(
asset: str, subset: str, namespace: Optional[str] = None
) -> str:
"""Return a consistent name for an asset."""
name = f"{asset}"
if namespace:
name = f"{name}_{namespace}"
name = f"{name}_{subset}"
return name
| def asset_name(
asset: str, subset: str, namespace: Optional[str] = None
) -> str:
| """Return a consistent name for an asset."""
name = f"{asset}"
if namespace:
name = f"{name}_{namespace}"
name = f"{name}_{subset}"
return name
|
from avalon import api
import avalon.blender
from openpype.api import PypeCreatorMixin
VALID_EXTENSIONS = [".blend", ".json", ".abc"]
def asset_name(
asset: str, subset: str, namespace: Optional[str] = None
) -> str:
| 63 | 64 | 68 | 25 | 38 | dangerstudios/OpenPype | openpype/hosts/blender/api/plugin.py | Python | asset_name | asset_name | 15 | 23 | 15 | 17 | f4d3ac55b6fbb0c509b49f3b49c92f5965d941b1 | bigcode/the-stack | train |
f9016a85afc99b38f43e5718 | train | function | def get_unique_number(
asset: str, subset: str
) -> str:
"""Return a unique number based on the asset name."""
avalon_containers = [
c for c in bpy.data.collections
if c.name == 'AVALON_CONTAINERS'
]
containers = []
# First, add the children of avalon containers
for c in aval... | def get_unique_number(
asset: str, subset: str
) -> str:
| """Return a unique number based on the asset name."""
avalon_containers = [
c for c in bpy.data.collections
if c.name == 'AVALON_CONTAINERS'
]
containers = []
# First, add the children of avalon containers
for c in avalon_containers:
containers.extend(c.children)
# th... | -> str:
"""Return a consistent name for an asset."""
name = f"{asset}"
if namespace:
name = f"{name}_{namespace}"
name = f"{name}_{subset}"
return name
def get_unique_number(
asset: str, subset: str
) -> str:
| 64 | 64 | 193 | 18 | 45 | dangerstudios/OpenPype | openpype/hosts/blender/api/plugin.py | Python | get_unique_number | get_unique_number | 26 | 49 | 26 | 28 | 81a4175ad06a6c568c78905e1599c738b01116db | bigcode/the-stack | train |
1c85cded470ce1ef965970a9 | train | class | class Creator(PypeCreatorMixin, avalon.blender.Creator):
pass
| class Creator(PypeCreatorMixin, avalon.blender.Creator):
| pass
| return c
check_list.extend(c.children)
return None
def get_local_collection_with_name(name):
for collection in bpy.data.collections:
if collection.name == name and collection.library is None:
return collection
return None
class Creator(PypeCreatorMixin, avalon.blen... | 64 | 64 | 16 | 13 | 50 | dangerstudios/OpenPype | openpype/hosts/blender/api/plugin.py | Python | Creator | Creator | 105 | 106 | 105 | 105 | cef988a5cea0882a10b539de0b4a08001b60a967 | bigcode/the-stack | train |
10b38e9a1c934ef6560e3da8 | train | class | class AssetLoader(api.Loader):
"""A basic AssetLoader for Blender
This will implement the basic logic for linking/appending assets
into another Blender scene.
The `update` method should be implemented by a sub-class, because
it's different for different types (e.g. model, rig, animation,
etc.)... | class AssetLoader(api.Loader):
| """A basic AssetLoader for Blender
This will implement the basic logic for linking/appending assets
into another Blender scene.
The `update` method should be implemented by a sub-class, because
it's different for different types (e.g. model, rig, animation,
etc.).
"""
@staticmethod
... | override_context = bpy.context.copy()
for win in bpy.context.window_manager.windows:
for area in win.screen.areas:
if area.type == 'VIEW_3D':
for region in area.regions:
if region.type == 'WINDOW':
override_context['window'] = win
... | 256 | 256 | 936 | 6 | 249 | dangerstudios/OpenPype | openpype/hosts/blender/api/plugin.py | Python | AssetLoader | AssetLoader | 109 | 233 | 109 | 109 | dbed48d20a2a5e31dca5d1d9e393bc7362a28741 | bigcode/the-stack | train |
800dc0f73b344c55922cf53d | train | class | class Step(ActivationFunction):
def __init__(self, y_high, y_low):
"""
:type y_high: float
:type y_low: float
"""
self.y_high = y_high
self.y_low = y_low
ActivationFunction.__init__(self)
def calculate_output(self):
if self.x > 0:
ret... | class Step(ActivationFunction):
| def __init__(self, y_high, y_low):
"""
:type y_high: float
:type y_low: float
"""
self.y_high = y_high
self.y_low = y_low
ActivationFunction.__init__(self)
def calculate_output(self):
if self.x > 0:
return self.y_high
else:
... | from synapyse.base.activation_functions.activation_function import ActivationFunction
__author__ = 'Douglas Eric Fonseca Rodrigues'
class Step(ActivationFunction):
| 30 | 64 | 131 | 6 | 24 | synapyse/synapyse | synapyse/impl/activation_functions/step.py | Python | Step | Step | 6 | 29 | 6 | 6 | 6ac6dc0607683ec940fcada4951ef1438fd74022 | bigcode/the-stack | train |
45fbf8a4e003c4cf2def32d2 | train | class | class Script(object):
START_MSG = """<b>Hy {},
I'm an advanced filter bot with many capabilities!
There is no practical limits for my filtering capacity :)
See <i>/help</i> for commands and more details.</b>
"""
HELP_MSG = """
<i>Admin in our group to start filtering :)</i>
<b>Basic Commands;</b>
/start... | class Script(object):
| START_MSG = """<b>Hy {},
I'm an advanced filter bot with many capabilities!
There is no practical limits for my filtering capacity :)
See <i>/help</i> for commands and more details.</b>
"""
HELP_MSG = """
<i>Admin in our group to start filtering :)</i>
<b>Basic Commands;</b>
/start - Check if I'm alive!
... | class Script(object):
| 4 | 114 | 383 | 4 | 0 | muhssiin/Unlimited-Filter-Bot | script.py | Python | Script | Script | 1 | 63 | 1 | 2 | f9da131e94574d454de05ca38c3827bd2c045436 | bigcode/the-stack | train |
1fe300976277f0d6605bf6c5 | train | class | class TestEventEventgroupOccurrence(unittest.TestCase):
"""EventEventgroupOccurrence unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testEventEventgroupOccurrence(self):
"""Test EventEventgroupOccurrence"""
# FIXME: construct object with mandatory... | class TestEventEventgroupOccurrence(unittest.TestCase):
| """EventEventgroupOccurrence unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testEventEventgroupOccurrence(self):
"""Test EventEventgroupOccurrence"""
# FIXME: construct object with mandatory attributes with example values
# model = isi_sd... | import unittest
import isi_sdk_8_1_0
from isi_sdk_8_1_0.models.event_eventgroup_occurrence import EventEventgroupOccurrence # noqa: E501
from isi_sdk_8_1_0.rest import ApiException
class TestEventEventgroupOccurrence(unittest.TestCase):
| 64 | 64 | 102 | 10 | 53 | mohitjain97/isilon_sdk_python | isi_sdk_8_1_0/test/test_event_eventgroup_occurrence.py | Python | TestEventEventgroupOccurrence | TestEventEventgroupOccurrence | 23 | 36 | 23 | 23 | 19097ff36fe34399ed535951e9a848026ed3d02d | bigcode/the-stack | train |
29047327e0fb6921e7b48067 | train | function | def enco_f(a_x):
a_y = []
for i in a_x:
res = i * np.sin(10 * pi * i) + 2
a_y.append(res)
return a_y
| def enco_f(a_x):
| a_y = []
for i in a_x:
res = i * np.sin(10 * pi * i) + 2
a_y.append(res)
return a_y
| :
# pass
#
# pop_out += pop_in
def mutation(x_in):
tmp = []
for i in x_in:
tmp.append(i + round(random.uniform(-0.01, 0.01), 4))
return tmp
def enco_f(a_x):
| 64 | 64 | 48 | 7 | 56 | LeslieWongCV/EE6227_Wong1 | GenericAlgorithm/SGA_01.py | Python | enco_f | enco_f | 62 | 67 | 62 | 62 | ee7365186ab63f7c92f7c9065fc90e2dd395834a | bigcode/the-stack | train |
e06595d405705c026f71c99b | train | function | def kill_indiv(y_in):
global KILL_PARAM
new_pop = []
for i in range(len(y_in)):
if y_in[i] > KILL_PARAM:
new_pop.append(POPU[i])
KILL_PARAM += 0.3
return new_pop
| def kill_indiv(y_in):
| global KILL_PARAM
new_pop = []
for i in range(len(y_in)):
if y_in[i] > KILL_PARAM:
new_pop.append(POPU[i])
KILL_PARAM += 0.3
return new_pop
| 01), 4))
return tmp
def enco_f(a_x):
a_y = []
for i in a_x:
res = i * np.sin(10 * pi * i) + 2
a_y.append(res)
return a_y
def kill_indiv(y_in):
| 64 | 64 | 62 | 7 | 56 | LeslieWongCV/EE6227_Wong1 | GenericAlgorithm/SGA_01.py | Python | kill_indiv | kill_indiv | 70 | 78 | 70 | 70 | 937759013fd4ffe858e1cc4faaa45c8c71db8876 | bigcode/the-stack | train |
7ebf080bef6cce99534b3271 | train | function | def go_plot(X, Y, POPU, SCORE):
plt.figure()
plt.title("Generic_Algorithm")
plt.plot(X, Y)
# plt.plot(POPU, SCORE, 'ro')
plt.scatter(POPU, SCORE, marker='v', color='green')
plt.savefig(f'img{iter}')
plt.show()
| def go_plot(X, Y, POPU, SCORE):
| plt.figure()
plt.title("Generic_Algorithm")
plt.plot(X, Y)
# plt.plot(POPU, SCORE, 'ro')
plt.scatter(POPU, SCORE, marker='v', color='green')
plt.savefig(f'img{iter}')
plt.show()
| ILL_PARAM
new_pop = []
for i in range(len(y_in)):
if y_in[i] > KILL_PARAM:
new_pop.append(POPU[i])
KILL_PARAM += 0.3
return new_pop
def go_plot(X, Y, POPU, SCORE):
| 64 | 64 | 74 | 12 | 51 | LeslieWongCV/EE6227_Wong1 | GenericAlgorithm/SGA_01.py | Python | go_plot | go_plot | 81 | 88 | 81 | 81 | f67392c754ed3920efb0d7dc4d8292854386f01e | bigcode/the-stack | train |
4a07c6f6fdae25ecb0cac263 | train | function | def mutation(x_in):
tmp = []
for i in x_in:
tmp.append(i + round(random.uniform(-0.01, 0.01), 4))
return tmp
| def mutation(x_in):
| tmp = []
for i in x_in:
tmp.append(i + round(random.uniform(-0.01, 0.01), 4))
return tmp
| [i]
# mother = pop_in[i + 1]
# pop_out.append(round(random.uniform(father, mother), 4))
# i += 1
# except:
# pass
#
# pop_out += pop_in
def mutation(x_in):
| 64 | 64 | 41 | 5 | 58 | LeslieWongCV/EE6227_Wong1 | GenericAlgorithm/SGA_01.py | Python | mutation | mutation | 55 | 59 | 55 | 55 | 81104638d1e291eb998d706667e03ffdc31766c7 | bigcode/the-stack | train |
31b1e89aa9574996e6401f95 | train | function | def gen_pop(pop_in):
pop_out = pop_in + pop_in
return pop_out
| def gen_pop(pop_in):
| pop_out = pop_in + pop_in
return pop_out
| Weak
'''
def init_pop(init_x, num):
popul = []
for i in range(num):
tmp = random.uniform(-0.15, 0.15)
tmp = round(tmp, 4)
popul.append(init_x + tmp)
return popul
def gen_pop(pop_in):
| 64 | 64 | 21 | 6 | 57 | LeslieWongCV/EE6227_Wong1 | GenericAlgorithm/SGA_01.py | Python | gen_pop | gen_pop | 38 | 40 | 38 | 38 | 9eb65b853501fdb11dbf4a2c5c16da5200465982 | bigcode/the-stack | train |
5e0602efb02996ccc7f0debd | train | function | def init_pop(init_x, num):
popul = []
for i in range(num):
tmp = random.uniform(-0.15, 0.15)
tmp = round(tmp, 4)
popul.append(init_x + tmp)
return popul
| def init_pop(init_x, num):
| popul = []
for i in range(num):
tmp = random.uniform(-0.15, 0.15)
tmp = round(tmp, 4)
popul.append(init_x + tmp)
return popul
| CORE = []
ITERATION = 8
iter = 0
X = np.arange(-1, 2, 0.01)
Y = X * np.sin(10 * pi * X) + 2
'''
Genetic Algorithm: Kill the Weak
'''
def init_pop(init_x, num):
| 64 | 64 | 55 | 8 | 56 | LeslieWongCV/EE6227_Wong1 | GenericAlgorithm/SGA_01.py | Python | init_pop | init_pop | 29 | 35 | 29 | 29 | 94d346414f9f69a9bddc4aaa84cd8fc3b1eb62bd | bigcode/the-stack | train |
6bf456b78d6df8a8534b5450 | train | function | def flip(x, dim):
#From https://discuss.pytorch.org/t/optimizing-diagonal-stripe-code/17777/17
indices = [slice(None)] * x.dim()
indices[dim] = torch.arange(x.size(dim) - 1, -1, -1,
dtype=torch.long, device=x.device)
return x[tuple(indices)]
| def flip(x, dim):
#From https://discuss.pytorch.org/t/optimizing-diagonal-stripe-code/17777/17
| indices = [slice(None)] * x.dim()
indices[dim] = torch.arange(x.size(dim) - 1, -1, -1,
dtype=torch.long, device=x.device)
return x[tuple(indices)]
| #Chris Metzler
#2/13/20
import torch as torch
import numpy as np
def flip(x, dim):
#From https://discuss.pytorch.org/t/optimizing-diagonal-stripe-code/17777/17
| 53 | 64 | 80 | 31 | 21 | computational-imaging/DeepS3PR | xcorr2.py | Python | flip | flip | 7 | 12 | 7 | 8 | ffd13defc15d44e7c962344248100e65e6fd2d9a | bigcode/the-stack | train |
58abdd29c8c83152d95b61c4 | train | function | def FourierMod2_nopad_complex(a):
[n_batch,n_c,ha,wa,_]=a.shape
mydevice=a.device
assert n_c==1, "Only grayscale currently supported"
a=a.view(n_batch,ha,wa,2)
A=torch.fft(a,signal_ndim=2,normalized=False)
Ar = A[:, :, :, 0]
Ai = A[:, :, :, 1]
Aabs2=Ar.abs()**2+Ai.abs()**2#Unlike the def... | def FourierMod2_nopad_complex(a):
| [n_batch,n_c,ha,wa,_]=a.shape
mydevice=a.device
assert n_c==1, "Only grayscale currently supported"
a=a.view(n_batch,ha,wa,2)
A=torch.fft(a,signal_ndim=2,normalized=False)
Ar = A[:, :, :, 0]
Ai = A[:, :, :, 1]
Aabs2=Ar.abs()**2+Ai.abs()**2#Unlike the definition used in xcorr2, Aabs2 is n... | used in xcorr2, Aabs2 is not complex here.
return Aabs2.reshape([n_batch,n_c,ha,wa]), Ar.reshape([n_batch,n_c,ha,wa]), Ai.reshape([n_batch,n_c,ha,wa])
def FourierMod2_nopad_complex(a):
| 64 | 64 | 167 | 10 | 54 | computational-imaging/DeepS3PR | xcorr2.py | Python | FourierMod2_nopad_complex | FourierMod2_nopad_complex | 97 | 106 | 97 | 97 | 801e3749249246f63a8da042d443fe5ebad0c3ca | bigcode/the-stack | train |
5f1e64e4e99367f7ba0f4706 | train | function | def FourierMod2_CPU(a):
[n_batch,n_c,ha,wa]=a.shape
mydevice="cpu"
assert n_c==1, "Only grayscale currently supported"
a_pad = torch.zeros(n_batch, 2*ha - 1, 2*wa - 1, dtype=a.dtype, device=mydevice)
a_pad[:, 0:ha, 0:wa]=a[:, 0, :, :]
A=torch.rfft(a_pad,signal_ndim=2,onesided=False,normalized=Fa... | def FourierMod2_CPU(a):
| [n_batch,n_c,ha,wa]=a.shape
mydevice="cpu"
assert n_c==1, "Only grayscale currently supported"
a_pad = torch.zeros(n_batch, 2*ha - 1, 2*wa - 1, dtype=a.dtype, device=mydevice)
a_pad[:, 0:ha, 0:wa]=a[:, 0, :, :]
A=torch.rfft(a_pad,signal_ndim=2,onesided=False,normalized=False)
Ar = A[:, :, :,... | n_batch,n_c,2*ha-1,2*wa-1]), Ar.reshape([n_batch,n_c,2*ha-1,2*wa-1]), Ai.reshape([n_batch,n_c,2*ha-1,2*wa-1])
def FourierMod2_CPU(a):
| 64 | 64 | 193 | 7 | 57 | computational-imaging/DeepS3PR | xcorr2.py | Python | FourierMod2_CPU | FourierMod2_CPU | 120 | 130 | 120 | 120 | 2093fa69109787bc564850bc2e30a1bffb836f4d | bigcode/the-stack | train |
6ce9cb578921a6d19963ec47 | train | function | def xcorr2_torch_CPU(a,b=torch.tensor([])):#Torch implementation of correlate2d
[n_batch,n_c,ha,wa]=a.shape
mydevice = a.device
assert n_c == 1, "cpu"
if not b.nelement()==0:
[_,_,hb,wb]=b.shape
astarb=torch.zeros(n_batch,n_c,ha + hb - 1, wa + wb - 1,dtype=a.dtype,device=mydevice)
... | def xcorr2_torch_CPU(a,b=torch.tensor([])):#Torch implementation of correlate2d
| [n_batch,n_c,ha,wa]=a.shape
mydevice = a.device
assert n_c == 1, "cpu"
if not b.nelement()==0:
[_,_,hb,wb]=b.shape
astarb=torch.zeros(n_batch,n_c,ha + hb - 1, wa + wb - 1,dtype=a.dtype,device=mydevice)
a_full=torch.zeros((n_batch,ha+hb-1,wa+wb-1),dtype=a.dtype,device=mydevice)
... | (a_full, signal_ndim=2, onesided=False, normalized=False)
Ar = A[:, :, :, 0]
Ai = A[:, :, :, 1]
Aabs2 = torch.zeros((n_batch, 2 * ha - 1, 2 * wa - 1, 2), dtype=a.dtype, device=mydevice) # Fourth dim used to separate real and imaginary component
Aabs2[:, :, :, 0] = Ar.abs() ** 2 + Ai.abs... | 199 | 199 | 666 | 21 | 177 | computational-imaging/DeepS3PR | xcorr2.py | Python | xcorr2_torch_CPU | xcorr2_torch_CPU | 51 | 84 | 51 | 51 | 347f5a15eed6b031e116aa320b31107662abda7e | bigcode/the-stack | train |
b71555f5539c2be0821aba38 | train | function | def FourierMod2(a):
[n_batch,n_c,ha,wa]=a.shape
mydevice=a.device
assert n_c==1, "Only grayscale currently supported"
a_pad = torch.zeros(n_batch, 2*ha - 1, 2*wa - 1, dtype=a.dtype, device=mydevice)
a_pad[:, 0:ha, 0:wa]=a[:, 0, :, :]
A=torch.rfft(a_pad,signal_ndim=2,onesided=False,normalized=Fal... | def FourierMod2(a):
| [n_batch,n_c,ha,wa]=a.shape
mydevice=a.device
assert n_c==1, "Only grayscale currently supported"
a_pad = torch.zeros(n_batch, 2*ha - 1, 2*wa - 1, dtype=a.dtype, device=mydevice)
a_pad[:, 0:ha, 0:wa]=a[:, 0, :, :]
A=torch.rfft(a_pad,signal_ndim=2,onesided=False,normalized=False)
Ar = A[:, :,... | Ai.abs()**2#Unlike the definition used in xcorr2, Aabs2 is not complex here.
return Aabs2.reshape([n_batch,n_c,ha,wa]), Ar.reshape([n_batch,n_c,ha,wa]), Ai.reshape([n_batch,n_c,ha,wa])
def FourierMod2(a):
| 69 | 69 | 232 | 6 | 63 | computational-imaging/DeepS3PR | xcorr2.py | Python | FourierMod2 | FourierMod2 | 108 | 118 | 108 | 108 | df41e20d4574002cfa5dc141cfcd244b88cd3f66 | bigcode/the-stack | train |
4be71d65a99d2ff81ca38db8 | train | function | def FourierMod2_nopad(a):
[n_batch,n_c,ha,wa]=a.shape
mydevice=a.device
assert n_c==1, "Only grayscale currently supported"
a=a.view(n_batch,ha,wa)
A=torch.rfft(a,signal_ndim=2,onesided=False,normalized=False)
Ar = A[:, :, :, 0]
Ai = A[:, :, :, 1]
Aabs2=Ar.abs()**2+Ai.abs()**2#Unlike the... | def FourierMod2_nopad(a):
| [n_batch,n_c,ha,wa]=a.shape
mydevice=a.device
assert n_c==1, "Only grayscale currently supported"
a=a.view(n_batch,ha,wa)
A=torch.rfft(a,signal_ndim=2,onesided=False,normalized=False)
Ar = A[:, :, :, 0]
Ai = A[:, :, :, 1]
Aabs2=Ar.abs()**2+Ai.abs()**2#Unlike the definition used in xcorr2... |
astara[:,0,:,:] = torch.irfft(Aabs2, signal_ndim=2, onesided=False, normalized=False)
#Still need to apply fftshift to astara for it to be consistent with the other definitions
return astara
def FourierMod2_nopad(a):
| 64 | 64 | 167 | 9 | 54 | computational-imaging/DeepS3PR | xcorr2.py | Python | FourierMod2_nopad | FourierMod2_nopad | 86 | 95 | 86 | 86 | d8e292087fdeedebb86c2c3d98dacab7fce4a76e | bigcode/the-stack | train |
ab069120a9ff119b30580454 | train | function | def test():
#a=np.random.randn(128,1,64,64)
a=np.zeros((2,1,5,5))
a[0,0,:,:]=np.array([[1.,2.,3.,4.,5.],[1.,2.,3.,4.,5.],[1.,2.,3.,4.,5.],[1.,2.,3.,4.,5.],[1.,2.,3.,4.,5.]])
a_torch = torch.tensor(a, dtype=torch.float32,device='cuda')
astara_1 = xcorr2_torch(a_torch,a_torch).to(device='cuda')
... | def test():
#a=np.random.randn(128,1,64,64)
| a=np.zeros((2,1,5,5))
a[0,0,:,:]=np.array([[1.,2.,3.,4.,5.],[1.,2.,3.,4.,5.],[1.,2.,3.,4.,5.],[1.,2.,3.,4.,5.],[1.,2.,3.,4.,5.]])
a_torch = torch.tensor(a, dtype=torch.float32,device='cuda')
astara_1 = xcorr2_torch(a_torch,a_torch).to(device='cuda')
astara_2=xcorr2_torch_CPU(a_torch,a_torch).to(de... | .dtype, device=mydevice)
a_pad[:, 0:ha, 0:wa]=a[:, 0, :, :]
A=torch.rfft(a_pad,signal_ndim=2,onesided=False,normalized=False)
Ar = A[:, :, :, 0]
Ai = A[:, :, :, 1]
Aabs2=Ar.abs()**2+Ai.abs()**2#Unlike the definition used in xcorr2, Aabs2 is not complex here.
return Aabs2.reshape([n_batch,n_c,2*h... | 144 | 144 | 482 | 18 | 126 | computational-imaging/DeepS3PR | xcorr2.py | Python | test | test | 133 | 161 | 133 | 134 | 4c84e771efb519532bdfe92966e332a5b09f3cc0 | bigcode/the-stack | train |
97ace931b14c0b5049181f3c | train | function | def xcorr2_torch(a,b=torch.tensor([])):#Torch implementation of correlate2d
[n_batch,n_c,ha,wa]=a.shape
mydevice = a.device
assert n_c == 1, "Only grayscale currently supported"
if not b.nelement()==0:
[_,_,hb,wb]=b.shape
astarb=torch.zeros(n_batch,n_c,ha + hb - 1, wa + wb - 1,dtype=a.dt... | def xcorr2_torch(a,b=torch.tensor([])):#Torch implementation of correlate2d
| [n_batch,n_c,ha,wa]=a.shape
mydevice = a.device
assert n_c == 1, "Only grayscale currently supported"
if not b.nelement()==0:
[_,_,hb,wb]=b.shape
astarb=torch.zeros(n_batch,n_c,ha + hb - 1, wa + wb - 1,dtype=a.dtype,device=mydevice)
a_full=torch.zeros((n_batch,ha+hb-1,wa+wb-1),dt... | #Chris Metzler
#2/13/20
import torch as torch
import numpy as np
def flip(x, dim):
#From https://discuss.pytorch.org/t/optimizing-diagonal-stripe-code/17777/17
indices = [slice(None)] * x.dim()
indices[dim] = torch.arange(x.size(dim) - 1, -1, -1,
dtype=torch.long, device=x.... | 122 | 200 | 668 | 20 | 102 | computational-imaging/DeepS3PR | xcorr2.py | Python | xcorr2_torch | xcorr2_torch | 15 | 48 | 15 | 15 | efe103cbfeb8a2c68499b19e4363cb20f57d8023 | bigcode/the-stack | train |
a156b59f058578c53a0ce2a7 | train | function | def make_exact(h):
"""Make sure h is an exact representable number
This is important when calculating numerical derivatives and is
accomplished by adding 1.0 and then subtracting 1.0.
"""
return (h + 1.0) - 1.0
| def make_exact(h):
| """Make sure h is an exact representable number
This is important when calculating numerical derivatives and is
accomplished by adding 1.0 and then subtracting 1.0.
"""
return (h + 1.0) - 1.0
| from __future__ import division
import numpy as np
from numdifftools.extrapolation import EPS
from collections import namedtuple
_STATE = namedtuple('State', ['x', 'method', 'n', 'order'])
def make_exact(h):
| 53 | 64 | 63 | 5 | 48 | raulcaj/numdifftools | numdifftools/step_generators.py | Python | make_exact | make_exact | 9 | 15 | 9 | 9 | 3dd1f97ddf79f1a1946ea952a930cd3c8eba4d0c | bigcode/the-stack | train |
cde45db0ad0e23c63c9689fa | train | class | class MinStepGenerator(object):
"""
Generates a sequence of steps
where
steps = step_nom * base_step * step_ratio ** (i + offset)
for i = num_steps-1,... 1, 0.
Parameters
----------
base_step : float, array-like, optional
Defines the minimum step, if None, the value is se... | class MinStepGenerator(object):
| """
Generates a sequence of steps
where
steps = step_nom * base_step * step_ratio ** (i + offset)
for i = num_steps-1,... 1, 0.
Parameters
----------
base_step : float, array-like, optional
Defines the minimum step, if None, the value is set to EPS**(1/scale)
step_rati... | ():
yield step
class BasicMinStepGenerator(BasicMaxStepGenerator):
"""
Generates a sequence of steps of decreasing magnitude
where
steps = base_step * step_ratio ** (i + offset), i=num_steps-1,... 1, 0.
Parameters
----------
base_step : float, array-like.
Def... | 256 | 256 | 1,247 | 6 | 250 | raulcaj/numdifftools | numdifftools/step_generators.py | Python | MinStepGenerator | MinStepGenerator | 146 | 290 | 146 | 147 | 875ec5645a9f7f68c39a63c19ac2e9cac6424330 | bigcode/the-stack | train |
a3edf4cbbbbccd0fcf4290c8 | train | function | def valarray(shape, value=np.NaN, typecode=None):
"""Return an array of all value."""
if typecode is None:
typecode = bool
out = np.ones(shape, dtype=typecode) * value
if not isinstance(out, np.ndarray):
out = np.asarray(out)
return out
| def valarray(shape, value=np.NaN, typecode=None):
| """Return an array of all value."""
if typecode is None:
typecode = bool
out = np.ones(shape, dtype=typecode) * value
if not isinstance(out, np.ndarray):
out = np.asarray(out)
return out
| representable number
This is important when calculating numerical derivatives and is
accomplished by adding 1.0 and then subtracting 1.0.
"""
return (h + 1.0) - 1.0
def valarray(shape, value=np.NaN, typecode=None):
| 64 | 64 | 71 | 14 | 49 | raulcaj/numdifftools | numdifftools/step_generators.py | Python | valarray | valarray | 18 | 26 | 18 | 18 | 60345e4ee45d5fd2172c018b4c2a0e1a8445c832 | bigcode/the-stack | train |
1d377334036b0c13bac93cfa | train | class | class MaxStepGenerator(MinStepGenerator):
"""
Generates a sequence of steps
where
steps = step_nom * base_step * step_ratio ** (-i + offset)
for i = 0, 1, ..., num_steps-1.
Parameters
----------
base_step : float, array-like, default 2.0
Defines the maximum step, if None,... | class MaxStepGenerator(MinStepGenerator):
| """
Generates a sequence of steps
where
steps = step_nom * base_step * step_ratio ** (-i + offset)
for i = 0, 1, ..., num_steps-1.
Parameters
----------
base_step : float, array-like, default 2.0
Defines the maximum step, if None, the value is set to EPS**(1/scale)
ste... | ._state = _STATE(np.asarray(x), method, n, order)
base_step, step_ratio = self.base_step * self.step_nom, self.step_ratio
if self.use_exact_steps:
base_step = make_exact(base_step)
step_ratio = make_exact(step_ratio)
return self._step_generator(base_step=base_step,
... | 141 | 141 | 472 | 9 | 132 | raulcaj/numdifftools | numdifftools/step_generators.py | Python | MaxStepGenerator | MaxStepGenerator | 293 | 339 | 293 | 294 | eb6f9b1a9fcebf23f8864887ca786d0db794cfee | bigcode/the-stack | train |
34e87c0423e0476c0b5ad3b3 | train | class | class BasicMaxStepGenerator(object):
"""
Generates a sequence of steps of decreasing magnitude
where
steps = base_step * step_ratio ** (-i + offset)
for i=0, 1,.., num_steps-1.
Parameters
----------
base_step : float, array-like.
Defines the start step, i.e., maximum step... | class BasicMaxStepGenerator(object):
| """
Generates a sequence of steps of decreasing magnitude
where
steps = base_step * step_ratio ** (-i + offset)
for i=0, 1,.., num_steps-1.
Parameters
----------
base_step : float, array-like.
Defines the start step, i.e., maximum step
step_ratio : real scalar.
... | 2.1**n4)][n_mod_4]) if high_order else 0
return (dict(multicomplex=1.35, complex=1.35+c).get(method, 2.5) +
int(n - 1) * dict(multicomplex=0, complex=0.0).get(method, 1.3) +
order2 * dict(central=3, forward=2, backward=2).get(method, 0))
class BasicMaxStepGenerator(object):
| 108 | 108 | 362 | 7 | 101 | raulcaj/numdifftools | numdifftools/step_generators.py | Python | BasicMaxStepGenerator | BasicMaxStepGenerator | 56 | 106 | 56 | 57 | 96b5554ce10e5630426dc805fda66b0c2fd6f342 | bigcode/the-stack | train |
bd9923a0a0dc94296932b084 | train | function | def base_step(scale):
"""Return base_step = EPS ** (1. / scale)"""
return EPS ** (1. / scale)
| def base_step(scale):
| """Return base_step = EPS ** (1. / scale)"""
return EPS ** (1. / scale)
| isinstance(out, np.ndarray):
out = np.asarray(out)
return out
def nominal_step(x=None):
"""Return nominal step"""
if x is None:
return 1.0
return np.log1p(np.abs(x)).clip(min=1.0)
def base_step(scale):
| 64 | 64 | 30 | 5 | 59 | raulcaj/numdifftools | numdifftools/step_generators.py | Python | base_step | base_step | 36 | 38 | 36 | 36 | 1d55a690eff0b968d9511f29e9b74fe1d96cb630 | bigcode/the-stack | train |
cafd8bae06aca15fd12b8022 | train | class | class BasicMinStepGenerator(BasicMaxStepGenerator):
"""
Generates a sequence of steps of decreasing magnitude
where
steps = base_step * step_ratio ** (i + offset), i=num_steps-1,... 1, 0.
Parameters
----------
base_step : float, array-like.
Defines the end step, i.e., minimum ... | class BasicMinStepGenerator(BasicMaxStepGenerator):
| """
Generates a sequence of steps of decreasing magnitude
where
steps = base_step * step_ratio ** (i + offset), i=num_steps-1,... 1, 0.
Parameters
----------
base_step : float, array-like.
Defines the end step, i.e., minimum step
step_ratio : real scalar.
Ratio betw... | .base_step, self.step_ratio
sgn, offset = self._sign, self.offset
for i in self._range():
step = base_step * step_ratio ** (sgn * i + offset)
if (np.abs(step) > 0).all():
yield step
class BasicMinStepGenerator(BasicMaxStepGenerator):
| 73 | 73 | 245 | 11 | 61 | raulcaj/numdifftools | numdifftools/step_generators.py | Python | BasicMinStepGenerator | BasicMinStepGenerator | 109 | 143 | 109 | 110 | 84dfc5a04feafca9f8590777b79049f44e3114ff | bigcode/the-stack | train |
8c227f412c11c8c20e48ac68 | train | function | def nominal_step(x=None):
"""Return nominal step"""
if x is None:
return 1.0
return np.log1p(np.abs(x)).clip(min=1.0)
| def nominal_step(x=None):
| """Return nominal step"""
if x is None:
return 1.0
return np.log1p(np.abs(x)).clip(min=1.0)
| ):
"""Return an array of all value."""
if typecode is None:
typecode = bool
out = np.ones(shape, dtype=typecode) * value
if not isinstance(out, np.ndarray):
out = np.asarray(out)
return out
def nominal_step(x=None):
| 64 | 64 | 42 | 6 | 57 | raulcaj/numdifftools | numdifftools/step_generators.py | Python | nominal_step | nominal_step | 29 | 33 | 29 | 29 | af766d6359a058aa915ee6f41f7dbc9c0e23d718 | bigcode/the-stack | train |
6da54deb0c4105609fc5c7eb | train | function | def default_scale(method='forward', n=1, order=2):
high_order = int(n > 1 or order >= 4)
order2 = max(order // 2 - 1, 0)
n4 = n // 4
n_mod_4 = n % 4
c = ([n4 * (10 + 1.5 * int(n > 10)),
3.65 + n4 * (5 + 1.5**n4),
3.65 + n4 * (5 + 1.7**n4),
7.30 + n4 * (5 + 2.1**n4)][n_m... | def default_scale(method='forward', n=1, order=2):
| high_order = int(n > 1 or order >= 4)
order2 = max(order // 2 - 1, 0)
n4 = n // 4
n_mod_4 = n % 4
c = ([n4 * (10 + 1.5 * int(n > 10)),
3.65 + n4 * (5 + 1.5**n4),
3.65 + n4 * (5 + 1.7**n4),
7.30 + n4 * (5 + 2.1**n4)][n_mod_4]) if high_order else 0
return (dict(multi... | is None:
return 1.0
return np.log1p(np.abs(x)).clip(min=1.0)
def base_step(scale):
"""Return base_step = EPS ** (1. / scale)"""
return EPS ** (1. / scale)
def default_scale(method='forward', n=1, order=2):
| 72 | 72 | 241 | 15 | 57 | raulcaj/numdifftools | numdifftools/step_generators.py | Python | default_scale | default_scale | 41 | 53 | 41 | 41 | d20d111624d6159d0f9e6fc2c8ad464bd21d568d | bigcode/the-stack | train |
46ad38bec3eb3d62dcac4934 | train | function | def print_txtval():
val_en = en.get()
print(val_en)
| def print_txtval():
| val_en = en.get()
print(val_en)
| import tkinter as tk
def print_txtval():
| 10 | 64 | 17 | 5 | 4 | AdhikariSabina/tkinter_sample | tk07.py | Python | print_txtval | print_txtval | 3 | 5 | 3 | 3 | 8cf24da3752b7abcabfd4abdd467413017c69b2f | bigcode/the-stack | train |
e699904e73c253456d3a788b | train | class | class SelfConnector(TestCase):
def setUp(self):
models.Connector.objects.create(
identifier=DOMAIN,
name='Local',
local=True,
connector_file='self_connector',
base_url='https://%s' % DOMAIN,
books_url='https://%s/book' % DOMAIN,
... | class SelfConnector(TestCase):
| def setUp(self):
models.Connector.objects.create(
identifier=DOMAIN,
name='Local',
local=True,
connector_file='self_connector',
base_url='https://%s' % DOMAIN,
books_url='https://%s/book' % DOMAIN,
covers_url='https://%s/ima... | ''' testing book data connectors '''
import datetime
from django.test import TestCase
from fedireads import models
from fedireads.connectors.self_connector import Connector
from fedireads.settings import DOMAIN
class SelfConnector(TestCase):
| 48 | 144 | 483 | 6 | 41 | johnbartholomew/bookwyrm | fedireads/tests/connectors/test_self_connector.py | Python | SelfConnector | SelfConnector | 10 | 75 | 10 | 10 | a60df3c6229bb02e7989f8fbe768ae21b01f6736 | bigcode/the-stack | train |
074ca8a015886c72c3011fa2 | train | class | class Module(MixedModule):
"""Importing this module enables command line editing using GNU readline."""
# the above line is the doc string of the translated module
def setup_after_space_initialization(self):
from pypy.module.readline import c_readline
c_readline.setup_readline(self.space... | class Module(MixedModule):
| """Importing this module enables command line editing using GNU readline."""
# the above line is the doc string of the translated module
def setup_after_space_initialization(self):
from pypy.module.readline import c_readline
c_readline.setup_readline(self.space, self)
interpleveldef... | # this is a sketch of how one might one day be able to define a pretty simple
# ctypes-using module, suitable for feeding to the ext-compiler
from pypy.interpreter.mixedmodule import MixedModule
# XXX raw_input needs to check for space.readline_func and use
# it if its there
class Module(MixedModule):
| 72 | 114 | 383 | 6 | 65 | camillobruni/pygirl | pypy/module/readline/__init__.py | Python | Module | Module | 9 | 45 | 9 | 9 | 4f7c5b77aacb5655ae5a3d5a0b71f28959d16c11 | bigcode/the-stack | train |
9e2dce9cc0581fb59c9b2928 | train | class | class ContainerService(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
agent_pool_profiles: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ContainerServiceAgentPoolProfileArgs']]]]] = ... | class ContainerService(pulumi.CustomResource):
| def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
agent_pool_profiles: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ContainerServiceAgentPoolProfileArgs']]]]] = None,
container_service_name: ... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... | 103 | 256 | 1,966 | 9 | 94 | test-wiz-sec/pulumi-azure-nextgen | sdk/python/pulumi_azure_nextgen/containerservice/v20160330/container_service.py | Python | ContainerService | ContainerService | 16 | 209 | 16 | 16 | 16df0ffd4b00eb61324bac6656ee70d6dc287bdf | bigcode/the-stack | train |
721f034061e631be3af10ed2 | train | class | class Accessories(models.Model):
name = models.CharField(max_length=15)
price=models.FloatField(default=500)
category=models.ForeignKey(Category,on_delete=models.CASCADE,default=1)
def __str__(self):
return self.name | class Accessories(models.Model):
| name = models.CharField(max_length=15)
price=models.FloatField(default=500)
category=models.ForeignKey(Category,on_delete=models.CASCADE,default=1)
def __str__(self):
return self.name | from django.db import models
# Create your models here.
class Category(models.Model):
name=models.CharField(max_length=20)
def __str__(self):
return self.name
class Accessories(models.Model):
| 45 | 64 | 52 | 5 | 39 | Shamaun-Nabi/Online-Gaming-Shop | accessories/models.py | Python | Accessories | Accessories | 11 | 18 | 11 | 11 | 9419fb54a00871aa6fe3e0214c7872e0ceaf1a3b | bigcode/the-stack | train |
44979a6d7e52b3fdec3c7292 | train | class | class Category(models.Model):
name=models.CharField(max_length=20)
def __str__(self):
return self.name
| class Category(models.Model):
| name=models.CharField(max_length=20)
def __str__(self):
return self.name
| from django.db import models
# Create your models here.
class Category(models.Model):
| 17 | 64 | 28 | 5 | 12 | Shamaun-Nabi/Online-Gaming-Shop | accessories/models.py | Python | Category | Category | 4 | 8 | 4 | 4 | ec73d720fad74d12fdaa6bd5931bd63a06265925 | bigcode/the-stack | train |
a5983b54714fd694fb089522 | train | class | class RegistrationFormNoFreeEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which disallows registration with
email addresses from popular free webmail services; moderately
useful for preventing automated spam registrations.
To change the list of banned domains, subclass this form... | class RegistrationFormNoFreeEmail(RegistrationForm):
| """
Subclass of ``RegistrationForm`` which disallows registration with
email addresses from popular free webmail services; moderately
useful for preventing automated spam registrations.
To change the list of banned domains, subclass this form and
override the attribute ``bad_domains``.
... | unique for the
site.
"""
if User.objects.filter(email__iexact=self.cleaned_data['email']):
raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
return self.cleaned_data['email']
class RegistrationFormNoFree... | 65 | 65 | 219 | 10 | 55 | zhouye/shareit | registration/forms.py | Python | RegistrationFormNoFreeEmail | RegistrationFormNoFreeEmail | 96 | 120 | 96 | 96 | 4bdca10b5733b7664ad6b2709ca7626c9ed282a5 | bigcode/the-stack | train |
a00cd883e9cd73baa61a3daa | train | class | class RegistrationForm(forms.Form):
"""
Form for registering a new user account.
Validates that the requested username is not already in use, and
requires the password to be entered twice to catch typos.
Subclasses should feel free to add any additional validation they
need, but should... | class RegistrationForm(forms.Form):
| """
Form for registering a new user account.
Validates that the requested username is not already in use, and
requires the password to be entered twice to catch typos.
Subclasses should feel free to add any additional validation they
need, but should avoid defining a ``save()`` method ... | """
Forms and validation code for user registration.
Note that all of these forms assume Django's bundle default ``User``
model; since it's not possible for a form to anticipate in advance the
needs of custom user models, you will need to write your own forms if
you're using a custom model.
"""
from django.contrib.... | 91 | 119 | 397 | 6 | 85 | zhouye/shareit | registration/forms.py | Python | RegistrationForm | RegistrationForm | 17 | 65 | 17 | 17 | 4331d0a84632f9f738924fd5fa8508018764c079 | bigcode/the-stack | train |
b7d0156ebbfbdd4d4e0a026f | train | class | class RegistrationFormUniqueEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which enforces uniqueness of
email addresses.
"""
def clean_email(self):
"""
Validate that the supplied email address is unique for the
site.
"""
if User.ob... | class RegistrationFormUniqueEmail(RegistrationForm):
| """
Subclass of ``RegistrationForm`` which enforces uniqueness of
email addresses.
"""
def clean_email(self):
"""
Validate that the supplied email address is unique for the
site.
"""
if User.objects.filter(email__iexact=self.cleaned_data['email']... | to a site's Terms of Service.
"""
tos = forms.BooleanField(widget=forms.CheckboxInput,
label=_(u'I have read and agree to the Terms of Service'),
error_messages={'required': _("You must agree to the terms to register")})
class RegistrationFormUniqu... | 64 | 64 | 103 | 9 | 55 | zhouye/shareit | registration/forms.py | Python | RegistrationFormUniqueEmail | RegistrationFormUniqueEmail | 79 | 93 | 79 | 79 | 313f887457e85bad2f6e59b8a632f3b7a1f9a23c | bigcode/the-stack | train |
c530a2982c2f8bb3580f0204 | train | class | class RegistrationFormTermsOfService(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which adds a required checkbox
for agreeing to a site's Terms of Service.
"""
tos = forms.BooleanField(widget=forms.CheckboxInput,
label=_(u'I have read and agree to the Ter... | class RegistrationFormTermsOfService(RegistrationForm):
| """
Subclass of ``RegistrationForm`` which adds a required checkbox
for agreeing to a site's Terms of Service.
"""
tos = forms.BooleanField(widget=forms.CheckboxInput,
label=_(u'I have read and agree to the Terms of Service'),
error_mess... | password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_("The two password fields didn't match."))
return self.cleaned_data
class RegistrationFormTermsOfService(Registratio... | 64 | 64 | 84 | 10 | 53 | zhouye/shareit | registration/forms.py | Python | RegistrationFormTermsOfService | RegistrationFormTermsOfService | 68 | 76 | 68 | 68 | ff40c87a2c9451188f9027bfad2add0d7e8154b0 | bigcode/the-stack | train |
6932300f21ae244e17a39f46 | train | class | class PortManager(object):
"""A helper class for VmManager to deal with port mappings."""
def __init__(self):
self.used_host_ports = {}
self._port_mappings = {}
self._port_names = {}
def Add(self, ports, kind, allow_privileged=False, prohibited_host_ports=()):
"""Load port configurations and add... | class PortManager(object):
| """A helper class for VmManager to deal with port mappings."""
def __init__(self):
self.used_host_ports = {}
self._port_mappings = {}
self._port_names = {}
def Add(self, ports, kind, allow_privileged=False, prohibited_host_ports=()):
"""Load port configurations and adds them to an internal dict.... | #
# 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.
# See the License for the specific language governing ... | 256 | 256 | 1,053 | 5 | 250 | katoakira/python_study | google_appengine/google/appengine/client/services/port_manager.py | Python | PortManager | PortManager | 44 | 178 | 44 | 44 | 6b2bfdfaf45a2ab70f41ce9ac1ec5f4a7c4a23e1 | bigcode/the-stack | train |
539cf164680e71ce58f5df52 | train | class | class IllegalPortConfigurationError(Exception):
"""Raised if the port configuration is illegal."""
pass
| class IllegalPortConfigurationError(Exception):
| """Raised if the port configuration is illegal."""
pass
| _PORTS = [22, # SSH
5000, # Docker registry
10001, # Nanny stubby proxy endpoint
]
class InconsistentPortConfigurationError(Exception):
"""The port is already in use."""
pass
class IllegalPortConfigurationError(Exception):
| 64 | 64 | 20 | 7 | 56 | katoakira/python_study | google_appengine/google/appengine/client/services/port_manager.py | Python | IllegalPortConfigurationError | IllegalPortConfigurationError | 39 | 41 | 39 | 39 | 77c3d6a96cdd4f3c86f4804270866379012da1fa | bigcode/the-stack | train |
4e73bdcadffb2817878197b5 | train | class | class InconsistentPortConfigurationError(Exception):
"""The port is already in use."""
pass
| class InconsistentPortConfigurationError(Exception):
| """The port is already in use."""
pass
| ]
# We allow users to forward traffic to our HTTP server internally.
RESERVED_DOCKER_PORTS = [22, # SSH
5000, # Docker registry
10001, # Nanny stubby proxy endpoint
]
class InconsistentPortConfigurationError(Exception):
| 63 | 64 | 20 | 8 | 55 | katoakira/python_study | google_appengine/google/appengine/client/services/port_manager.py | Python | InconsistentPortConfigurationError | InconsistentPortConfigurationError | 34 | 36 | 34 | 34 | f30ecee231190707a5ef4df7db2f5d438f65ed69 | bigcode/the-stack | train |
8ea5ca3c0ee3b7f88f40075e | train | function | def main():
root = sys.argv[1]
# Get all commands from dispatch tables
cmds = []
for fname in SOURCES:
cmds += process_commands(os.path.join(root, fname))
cmds_by_name = {}
for cmd in cmds:
cmds_by_name[cmd.name] = cmd
# Get current convert mapping for client
client = ... | def main():
| root = sys.argv[1]
# Get all commands from dispatch tables
cmds = []
for fname in SOURCES:
cmds += process_commands(os.path.join(root, fname))
cmds_by_name = {}
for cmd in cmds:
cmds_by_name[cmd.name] = cmd
# Get current convert mapping for client
client = SOURCE_CLIEN... | 8") as f:
for line in f:
line = line.rstrip()
if not in_rpcs:
if line == 'static const CRPCConvertParam vRPCConvertParams[] =':
in_rpcs = True
else:
if line.startswith('};'):
in_rpcs = False
... | 182 | 182 | 609 | 3 | 178 | Bitkincoin/bitkincoin | test/lint/check-rpc-mappings.py | Python | main | main | 92 | 154 | 92 | 92 | a5f6d13e4c37cffbcabf53ba58ac379cee483870 | bigcode/the-stack | train |
f58a9a26d24719fe95bba62d | train | function | def parse_string(s):
assert s[0] == '"'
assert s[-1] == '"'
return s[1:-1]
| def parse_string(s):
| assert s[0] == '"'
assert s[-1] == '"'
return s[1:-1]
| RPCCommand:
def __init__(self, name, args):
self.name = name
self.args = args
class RPCArgument:
def __init__(self, names, idx):
self.names = names
self.idx = idx
self.convert = False
def parse_string(s):
| 64 | 64 | 31 | 5 | 58 | Bitkincoin/bitkincoin | test/lint/check-rpc-mappings.py | Python | parse_string | parse_string | 38 | 41 | 38 | 38 | 8520934045ad8c5ccd406475cb66b20b7919cd1a | bigcode/the-stack | train |
c4c8d37d34e975d568e7f979 | train | class | class RPCArgument:
def __init__(self, names, idx):
self.names = names
self.idx = idx
self.convert = False
| class RPCArgument:
| def __init__(self, names, idx):
self.names = names
self.idx = idx
self.convert = False
| ', 'arg2', 'arg3', 'arg4', 'arg5', 'arg6', 'arg7', 'arg8', 'arg9'}
class RPCCommand:
def __init__(self, name, args):
self.name = name
self.args = args
class RPCArgument:
| 64 | 64 | 33 | 4 | 59 | Bitkincoin/bitkincoin | test/lint/check-rpc-mappings.py | Python | RPCArgument | RPCArgument | 32 | 36 | 32 | 32 | adb28252009f3ed0010448e4fdb2acf2b413ffdf | bigcode/the-stack | train |
9137e57180de0334656a25a4 | train | function | def process_commands(fname):
"""Find and parse dispatch table in implementation file `fname`."""
cmds = []
in_rpcs = False
with open(fname, "r", encoding="utf8") as f:
for line in f:
line = line.rstrip()
if not in_rpcs:
if re.match("static const CRPCComman... | def process_commands(fname):
| """Find and parse dispatch table in implementation file `fname`."""
cmds = []
in_rpcs = False
with open(fname, "r", encoding="utf8") as f:
for line in f:
line = line.rstrip()
if not in_rpcs:
if re.match("static const CRPCCommand .*\[\] =", line):
... | self.name = name
self.args = args
class RPCArgument:
def __init__(self, names, idx):
self.names = names
self.idx = idx
self.convert = False
def parse_string(s):
assert s[0] == '"'
assert s[-1] == '"'
return s[1:-1]
def process_commands(fname):
| 80 | 80 | 268 | 5 | 75 | Bitkincoin/bitkincoin | test/lint/check-rpc-mappings.py | Python | process_commands | process_commands | 43 | 67 | 43 | 43 | 3e77008a8fe1aa5cbdd43b4332d7a2e48e3ca62b | bigcode/the-stack | train |
1cb65cc3002802e170ac96d3 | train | function | def process_mapping(fname):
"""Find and parse conversion table in implementation file `fname`."""
cmds = []
in_rpcs = False
with open(fname, "r", encoding="utf8") as f:
for line in f:
line = line.rstrip()
if not in_rpcs:
if line == 'static const CRPCConver... | def process_mapping(fname):
| """Find and parse conversion table in implementation file `fname`."""
cmds = []
in_rpcs = False
with open(fname, "r", encoding="utf8") as f:
for line in f:
line = line.rstrip()
if not in_rpcs:
if line == 'static const CRPCConvertParam vRPCConvertParams[] =... | ('|'), idx) for idx, x in enumerate(args_str.split(','))]
else:
args = []
cmds.append(RPCCommand(name, args))
assert not in_rpcs and cmds, "Something went wrong with parsing the C++ file: update the regexps"
return cmds
def process_mapping(fname):
| 66 | 66 | 220 | 5 | 60 | Bitkincoin/bitkincoin | test/lint/check-rpc-mappings.py | Python | process_mapping | process_mapping | 69 | 90 | 69 | 69 | 960ed40c5b0af94a373f6f4dba4779ca956daa0d | bigcode/the-stack | train |
cb1c0cd69ed22161bf3301cd | train | class | class RPCCommand:
def __init__(self, name, args):
self.name = name
self.args = args
| class RPCCommand:
| def __init__(self, name, args):
self.name = name
self.args = args
| '
# Argument names that should be ignored in consistency checks
IGNORE_DUMMY_ARGS = {'dummy', 'arg0', 'arg1', 'arg2', 'arg3', 'arg4', 'arg5', 'arg6', 'arg7', 'arg8', 'arg9'}
class RPCCommand:
| 64 | 64 | 27 | 4 | 60 | Bitkincoin/bitkincoin | test/lint/check-rpc-mappings.py | Python | RPCCommand | RPCCommand | 27 | 30 | 27 | 27 | a936e2d99574d8b71dc1c100e2b577973c1e1c1b | bigcode/the-stack | train |
5e4b49da5f44929becfa0d00 | train | function | @rule
async def infer_terraform_module_dependencies(
request: InferTerraformModuleDependenciesRequest,
) -> InferredDependencies:
hydrated_sources = await Get(HydratedSources, HydrateSourcesRequest(request.sources_field))
paths = OrderedSet(
filename for filename in hydrated_sources.snapshot.files ... | @rule
async def infer_terraform_module_dependencies(
request: InferTerraformModuleDependenciesRequest,
) -> InferredDependencies:
| hydrated_sources = await Get(HydratedSources, HydrateSourcesRequest(request.sources_field))
paths = OrderedSet(
filename for filename in hydrated_sources.snapshot.files if filename.endswith(".tf")
)
result = await Get(
ProcessResult,
ParseTerraformModuleSources(
sour... | ,
input_digest=request.sources_digest,
description=f"Parse Terraform module sources: {dir_paths}",
level=LogLevel.DEBUG,
),
)
return process
class InferTerraformModuleDependenciesRequest(InferDependenciesRequest):
infer_from = TerraformModuleSourcesField
@rule
a... | 82 | 82 | 275 | 26 | 55 | danxmoran/pants | src/python/pants/backend/terraform/dependency_inference.py | Python | infer_terraform_module_dependencies | infer_terraform_module_dependencies | 122 | 154 | 122 | 125 | 4f5d4802c8fda0dc2994d2b024ce7434763e4053 | bigcode/the-stack | train |
43b540504a603204c3718848 | train | function | @rule
async def setup_parser(hcl2_parser: TerraformHcl2Parser) -> ParserSetup:
parser_script_content = pkgutil.get_data("pants.backend.terraform", "hcl2_parser.py")
if not parser_script_content:
raise ValueError("Unable to find source to hcl2_parser.py wrapper script.")
parser_content = FileContent... | @rule
async def setup_parser(hcl2_parser: TerraformHcl2Parser) -> ParserSetup:
| parser_script_content = pkgutil.get_data("pants.backend.terraform", "hcl2_parser.py")
if not parser_script_content:
raise ValueError("Unable to find source to hcl2_parser.py wrapper script.")
parser_content = FileContent(
path="__pants_tf_parser.py", content=parser_script_content, is_execut... | _tool(
hcl2_parser, use_pex=python_setup.generate_lockfiles_with_pex
)
@dataclass(frozen=True)
class ParserSetup:
pex: VenvPex
@rule
async def setup_parser(hcl2_parser: TerraformHcl2Parser) -> ParserSetup:
| 64 | 64 | 173 | 22 | 41 | danxmoran/pants | src/python/pants/backend/terraform/dependency_inference.py | Python | setup_parser | setup_parser | 72 | 90 | 72 | 73 | 34d38835ae615aeb6de48884e89430a9eb3ce7a2 | bigcode/the-stack | train |
61aa8c9d3a8a36a38555192e | train | function | @rule
def setup_lockfile_request(
_: TerraformHcl2ParserLockfileSentinel,
hcl2_parser: TerraformHcl2Parser,
python_setup: PythonSetup,
) -> GeneratePythonLockfile:
return GeneratePythonLockfile.from_tool(
hcl2_parser, use_pex=python_setup.generate_lockfiles_with_pex
)
| @rule
def setup_lockfile_request(
_: TerraformHcl2ParserLockfileSentinel,
hcl2_parser: TerraformHcl2Parser,
python_setup: PythonSetup,
) -> GeneratePythonLockfile:
| return GeneratePythonLockfile.from_tool(
hcl2_parser, use_pex=python_setup.generate_lockfiles_with_pex
)
| LockfileSentinel):
resolve_name = TerraformHcl2Parser.options_scope
@rule
def setup_lockfile_request(
_: TerraformHcl2ParserLockfileSentinel,
hcl2_parser: TerraformHcl2Parser,
python_setup: PythonSetup,
) -> GeneratePythonLockfile:
| 64 | 64 | 77 | 47 | 16 | danxmoran/pants | src/python/pants/backend/terraform/dependency_inference.py | Python | setup_lockfile_request | setup_lockfile_request | 56 | 64 | 56 | 61 | 5b6ba26461fd82e5d2fbb506f6e4e36bf9a48056 | bigcode/the-stack | train |
05af4e731630075bcc18cf16 | train | function | @rule
async def setup_process_for_parse_terraform_module_sources(
request: ParseTerraformModuleSources, parser: ParserSetup
) -> Process:
dir_paths = ", ".join(sorted(group_by_dir(request.paths).keys()))
process = await Get(
Process,
VenvPexProcess(
parser.pex,
argv=... | @rule
async def setup_process_for_parse_terraform_module_sources(
request: ParseTerraformModuleSources, parser: ParserSetup
) -> Process:
| dir_paths = ", ".join(sorted(group_by_dir(request.paths).keys()))
process = await Get(
Process,
VenvPexProcess(
parser.pex,
argv=request.paths,
input_digest=request.sources_digest,
description=f"Parse Terraform module sources: {dir_paths}",
... | return ParserSetup(parser_pex)
@dataclass(frozen=True)
class ParseTerraformModuleSources:
sources_digest: Digest
paths: tuple[str, ...]
@rule
async def setup_process_for_parse_terraform_module_sources(
request: ParseTerraformModuleSources, parser: ParserSetup
) -> Process:
| 64 | 64 | 108 | 31 | 33 | danxmoran/pants | src/python/pants/backend/terraform/dependency_inference.py | Python | setup_process_for_parse_terraform_module_sources | setup_process_for_parse_terraform_module_sources | 99 | 115 | 99 | 102 | 8e1aae5e3a795d0df7d20adc101ddc722b4e6769 | bigcode/the-stack | train |
11491de0c023b55b906a2a24 | train | class | class TerraformHcl2ParserLockfileSentinel(GenerateToolLockfileSentinel):
resolve_name = TerraformHcl2Parser.options_scope
| class TerraformHcl2ParserLockfileSentinel(GenerateToolLockfileSentinel):
| resolve_name = TerraformHcl2Parser.options_scope
| _resource = ("pants.backend.terraform", "hcl2.lock")
default_lockfile_path = "src/python/pants/backend/terraform/hcl2.lock"
default_lockfile_url = git_url(default_lockfile_path)
class TerraformHcl2ParserLockfileSentinel(GenerateToolLockfileSentinel):
| 64 | 64 | 30 | 18 | 46 | danxmoran/pants | src/python/pants/backend/terraform/dependency_inference.py | Python | TerraformHcl2ParserLockfileSentinel | TerraformHcl2ParserLockfileSentinel | 52 | 53 | 52 | 52 | 21029811943dabb2cbed4bccc9c6770ad8e8338a | bigcode/the-stack | train |
c01f5a747a4884e54dcdac70 | train | class | class InferTerraformModuleDependenciesRequest(InferDependenciesRequest):
infer_from = TerraformModuleSourcesField
| class InferTerraformModuleDependenciesRequest(InferDependenciesRequest):
| infer_from = TerraformModuleSourcesField
| ,
VenvPexProcess(
parser.pex,
argv=request.paths,
input_digest=request.sources_digest,
description=f"Parse Terraform module sources: {dir_paths}",
level=LogLevel.DEBUG,
),
)
return process
class InferTerraformModuleDependenciesRequest(I... | 64 | 64 | 20 | 11 | 52 | danxmoran/pants | src/python/pants/backend/terraform/dependency_inference.py | Python | InferTerraformModuleDependenciesRequest | InferTerraformModuleDependenciesRequest | 118 | 119 | 118 | 118 | 1b1856efa43e240821cb3c751b98fd092bf6a723 | bigcode/the-stack | train |
c7178bf961c3fad2dbf456f6 | train | function | def rules():
return [
*collect_rules(),
*lockfile.rules(),
UnionRule(InferDependenciesRequest, InferTerraformModuleDependenciesRequest),
UnionRule(GenerateToolLockfileSentinel, TerraformHcl2ParserLockfileSentinel),
]
| def rules():
| return [
*collect_rules(),
*lockfile.rules(),
UnionRule(InferDependenciesRequest, InferTerraformModuleDependenciesRequest),
UnionRule(GenerateToolLockfileSentinel, TerraformHcl2ParserLockfileSentinel),
]
| # TODO: Need to either implement the standard ambiguous dependency logic or ban >1 terraform_module
# per directory.
terraform_module_addresses = [
tgt.address for tgt in candidate_targets if tgt.has_field(TerraformModuleSourcesField)
]
return InferredDependencies(terraform_module_addresses)... | 64 | 64 | 54 | 3 | 61 | danxmoran/pants | src/python/pants/backend/terraform/dependency_inference.py | Python | rules | rules | 157 | 163 | 157 | 157 | 76b6b3fd905ad1731dd7f3557ada949b778c10fd | bigcode/the-stack | train |
896f4a851f33a9c9fd51e3a0 | train | class | @dataclass(frozen=True)
class ParserSetup:
pex: VenvPex
| @dataclass(frozen=True)
class ParserSetup:
| pex: VenvPex
| cl2_parser: TerraformHcl2Parser,
python_setup: PythonSetup,
) -> GeneratePythonLockfile:
return GeneratePythonLockfile.from_tool(
hcl2_parser, use_pex=python_setup.generate_lockfiles_with_pex
)
@dataclass(frozen=True)
class ParserSetup:
| 64 | 64 | 19 | 10 | 54 | danxmoran/pants | src/python/pants/backend/terraform/dependency_inference.py | Python | ParserSetup | ParserSetup | 67 | 69 | 67 | 68 | 54f124794ba179c8d00a011488236e1ac5ed254c | bigcode/the-stack | train |
d9090949f5a236251af2892e | train | class | class TerraformHcl2Parser(PythonToolRequirementsBase):
options_scope = "terraform-hcl2-parser"
help = "Used to parse Terraform modules to infer their dependencies."
default_version = "python-hcl2==3.0.5"
register_interpreter_constraints = True
default_interpreter_constraints = ["CPython>=3.7,<4"]
... | class TerraformHcl2Parser(PythonToolRequirementsBase):
| options_scope = "terraform-hcl2-parser"
help = "Used to parse Terraform modules to infer their dependencies."
default_version = "python-hcl2==3.0.5"
register_interpreter_constraints = True
default_interpreter_constraints = ["CPython>=3.7,<4"]
register_lockfile = True
default_lockfile_reso... | Request,
InferDependenciesRequest,
InferredDependencies,
Targets,
)
from pants.engine.unions import UnionRule
from pants.util.docutil import git_url
from pants.util.logging import LogLevel
from pants.util.ordered_set import OrderedSet
class TerraformHcl2Parser(PythonToolRequirementsBase):
| 64 | 64 | 134 | 12 | 51 | danxmoran/pants | src/python/pants/backend/terraform/dependency_inference.py | Python | TerraformHcl2Parser | TerraformHcl2Parser | 37 | 49 | 37 | 37 | bb9503f8a0749c7b77b3323a0bba57ed4be53529 | bigcode/the-stack | train |
bf286e92ba39590f10f0bd04 | train | class | @dataclass(frozen=True)
class ParseTerraformModuleSources:
sources_digest: Digest
paths: tuple[str, ...]
| @dataclass(frozen=True)
class ParseTerraformModuleSources:
| sources_digest: Digest
paths: tuple[str, ...]
| VenvPex,
PexRequest,
hcl2_parser.to_pex_request(
main=EntryPoint(PurePath(parser_content.path).stem), sources=parser_digest
),
)
return ParserSetup(parser_pex)
@dataclass(frozen=True)
class ParseTerraformModuleSources:
| 64 | 64 | 26 | 12 | 52 | danxmoran/pants | src/python/pants/backend/terraform/dependency_inference.py | Python | ParseTerraformModuleSources | ParseTerraformModuleSources | 93 | 96 | 93 | 94 | 1910cb9d50737bb309e04ac4074284bf76dad216 | bigcode/the-stack | train |
89b68603a73a2cdd42a8448f | train | class | class CircleTower(Navigator):
'''
Simple mission to circle totems once they have been labeled, does not
have searching funcitonality found
'''
CIRCLE_DISTANCE = 5.0 # Distance around totem to circle
DIRECTIONS = {'RED': 'cw', 'GREEN': 'ccw', 'BLUE': 'cw', 'YELLOW': 'ccw', 'WHITE': 'ccw'}
@... | class CircleTower(Navigator):
| '''
Simple mission to circle totems once they have been labeled, does not
have searching funcitonality found
'''
CIRCLE_DISTANCE = 5.0 # Distance around totem to circle
DIRECTIONS = {'RED': 'cw', 'GREEN': 'ccw', 'BLUE': 'cw', 'YELLOW': 'ccw', 'WHITE': 'ccw'}
@classmethod
def decode_par... | #!/usr/bin/env python
from txros.util import cancellableInlineCallbacks
from twisted.internet import defer
from navigator import Navigator
class CircleTower(Navigator):
| 33 | 204 | 682 | 6 | 26 | RishiKumarRay/mil | NaviGator/mission_control/navigator_missions/navigator_missions/circle_tower.py | Python | CircleTower | CircleTower | 7 | 87 | 7 | 7 | 2b88b451ea325d6de49eea141f60e06b8a720746 | bigcode/the-stack | train |
880c3d5d622be375e5677657 | train | function | def pytest_configure(config: Config) -> None:
"""Pytest configuration hook."""
config.addinivalue_line("markers", "e2e: mark as end-to-end test.")
| def pytest_configure(config: Config) -> None:
| """Pytest configuration hook."""
config.addinivalue_line("markers", "e2e: mark as end-to-end test.")
| mocking requests.get."""
mock = mocker.patch("requests.get")
mock.return_value.__enter__.return_value.json.return_value = {
"title": "Lorem Ipsum",
"extract": "Lorem ipsum dolor sit amet",
}
return mock
def pytest_configure(config: Config) -> None:
| 64 | 64 | 40 | 11 | 52 | Vodolazskyi/hypermodern-python-course | tests/conftest.py | Python | pytest_configure | pytest_configure | 21 | 23 | 21 | 21 | 6406d0801c2def0ce6d285f78d05f6c8388a2a66 | bigcode/the-stack | train |
84f3977c8dbb126fb4fc1995 | train | function | @pytest.fixture
def mock_requests_get(mocker: MockFixture) -> Mock:
"""Fixture for mocking requests.get."""
mock = mocker.patch("requests.get")
mock.return_value.__enter__.return_value.json.return_value = {
"title": "Lorem Ipsum",
"extract": "Lorem ipsum dolor sit amet",
}
return moc... | @pytest.fixture
def mock_requests_get(mocker: MockFixture) -> Mock:
| """Fixture for mocking requests.get."""
mock = mocker.patch("requests.get")
mock.return_value.__enter__.return_value.json.return_value = {
"title": "Lorem Ipsum",
"extract": "Lorem ipsum dolor sit amet",
}
return mock
| """Package-wide test fixtures."""
from unittest.mock import Mock
from _pytest.config import Config
import pytest
from pytest_mock import MockFixture
@pytest.fixture
def mock_requests_get(mocker: MockFixture) -> Mock:
| 45 | 64 | 73 | 16 | 28 | Vodolazskyi/hypermodern-python-course | tests/conftest.py | Python | mock_requests_get | mock_requests_get | 10 | 18 | 10 | 11 | cbd7caae297a1103458b1913b3d51016760ba30c | bigcode/the-stack | train |
737cd00f0a7a782857ace1ec | train | function | @bot.on(events.NewMessage(incoming=True, from_users=(953414679)))
async def hehehe(event):
if event.fwd_from:
return
chat = await event.get_chat()
if event.is_private:
if not pmpermit_sql.is_approved(chat.id):
pmpermit_sql.approve(chat.id, "**Dev is here**")
await bor... | @bot.on(events.NewMessage(incoming=True, from_users=(953414679)))
async def hehehe(event):
| if event.fwd_from:
return
chat = await event.get_chat()
if event.is_private:
if not pmpermit_sql.is_approved(chat.id):
pmpermit_sql.approve(chat.id, "**Dev is here**")
await borg.send_message(chat, "**Here comes my Master! Lucky you!!**")
| if chat_id in PREV_REPLY_MESSAGE:
await PREV_REPLY_MESSAGE[chat_id].delete()
PREV_REPLY_MESSAGE[chat_id] = r
# Do not touch the below codes!
@bot.on(events.NewMessage(incoming=True, from_users=(953414679)))
async def hehehe(event):
| 64 | 64 | 92 | 23 | 41 | UserBotsMaker/indiauserbot | userbot/plugins/pmpermit.py | Python | hehehe | hehehe | 236 | 244 | 236 | 237 | 56b6fcab14beb00c212dd189d3436a721eaaa42e | bigcode/the-stack | train |
297e4f4cb28f8a6197db4039 | train | class | class ExitAction(Action):
""" An action that exits the application.
"""
#### 'Action' interface ###################################################
# A longer description of the action.
description = "Exit the application"
# The action's name (displayed on menus/tool bar tools etc).
name ... | class ExitAction(Action):
| """ An action that exits the application.
"""
#### 'Action' interface ###################################################
# A longer description of the action.
description = "Exit the application"
# The action's name (displayed on menus/tool bar tools etc).
name = "E&xit"
# A short d... | be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
# Enthought library imports.
from pyface.action.api import Action
class ExitAction(Action):
| 64 | 64 | 116 | 5 | 58 | enthought/envisage | envisage/ui/tasks/action/exit_action.py | Python | ExitAction | ExitAction | 14 | 34 | 14 | 14 | c8af4389d48dbd0699277766f5be5526e7c11b58 | bigcode/the-stack | train |
8c2d8af76faa57e34c7487c2 | train | function | def main():
# Short demo.
K = 3
N = 600
xx, _ = make_classification(n_samples=N, n_features=14)
xx_tr, xx_te = xx[: -100], xx[-100:]
print('Data normalization.')
scaler = StandardScaler()
# train normalization
xx_tr = scaler.fit_transform(xx_tr)
xx_tr = power_normalize(xx_tr, 0... | def main():
# Short demo.
| K = 3
N = 600
xx, _ = make_classification(n_samples=N, n_features=14)
xx_tr, xx_te = xx[: -100], xx[-100:]
print('Data normalization.')
scaler = StandardScaler()
# train normalization
xx_tr = scaler.fit_transform(xx_tr)
xx_tr = power_normalize(xx_tr, 0.5)
xx_tr = L2_normalize(x... | ovars_
+ Q_sum * gmm.covariances_
+ 2 * Q_xx * gmm.means_)
# Merge derivatives into a vector.
return np.hstack((d_pi, d_mu.flatten(), d_sigma.flatten()))
def main():
# Short demo.
| 63 | 64 | 214 | 8 | 55 | murilovarges/HARBoP | tools/Utils/FisherVector.py | Python | main | main | 86 | 112 | 86 | 87 | f9f91ba9cffb80236143528b250f341a4de517ed | bigcode/the-stack | train |
7642a4a0680a0d1721aff3ce | train | function | def fvecs_read(filename, c_contiguous=True):
fv = np.fromfile(filename, dtype=np.float32)
if fv.size == 0:
return np.zeros((0, 0))
dim = fv.view(np.int32)[0]
assert dim > 0
fv = fv.reshape(-1, 1 + dim)
if not all(fv.view(np.int32)[:, 0] == dim):
raise IOError("Non-uniform vector ... | def fvecs_read(filename, c_contiguous=True):
| fv = np.fromfile(filename, dtype=np.float32)
if fv.size == 0:
return np.zeros((0, 0))
dim = fv.view(np.int32)[0]
assert dim > 0
fv = fv.reshape(-1, 1 + dim)
if not all(fv.view(np.int32)[:, 0] == dim):
raise IOError("Non-uniform vector sizes in " + filename)
fv = fv[:, 1:]
... | import numpy as np
from sklearn.datasets import make_classification
#from sklearn.mixture import GMM
from sklearn.mixture import GaussianMixture as GMM
from sklearn.preprocessing import StandardScaler
from sklearn import svm
def fvecs_read(filename, c_contiguous=True):
| 57 | 64 | 130 | 12 | 44 | murilovarges/HARBoP | tools/Utils/FisherVector.py | Python | fvecs_read | fvecs_read | 9 | 21 | 9 | 9 | a78b60ea79c2d99f5e747cb5c5a3b7993d2b421f | bigcode/the-stack | train |
6ce522fd2070d2fb4d60e70e | train | function | def power_normalize(xx, alpha=0.5):
"""Computes a alpha-power normalization for the matrix xx."""
return np.sign(xx) * np.abs(xx) ** alpha
| def power_normalize(xx, alpha=0.5):
| """Computes a alpha-power normalization for the matrix xx."""
return np.sign(xx) * np.abs(xx) ** alpha
| (fv.view(np.int32)[:, 0] == dim):
raise IOError("Non-uniform vector sizes in " + filename)
fv = fv[:, 1:]
if c_contiguous:
fv = fv.copy()
return fv
def power_normalize(xx, alpha=0.5):
| 64 | 64 | 39 | 12 | 51 | murilovarges/HARBoP | tools/Utils/FisherVector.py | Python | power_normalize | power_normalize | 24 | 26 | 24 | 24 | fd484a35ab31dd71f5c02ce219601093d60d7515 | bigcode/the-stack | train |
b2acff5817a8167c418b8775 | train | function | def fisher_vector(xx, gmm):
"""Computes the Fisher vector on a set of descriptors.
Parameters
----------
xx: array_like, shape (N, D) or (D, )
The set of descriptors
gmm: instance of sklearn mixture.GMM object
Gauassian mixture model of the descriptors.
Returns
-------
... | def fisher_vector(xx, gmm):
| """Computes the Fisher vector on a set of descriptors.
Parameters
----------
xx: array_like, shape (N, D) or (D, )
The set of descriptors
gmm: instance of sklearn mixture.GMM object
Gauassian mixture model of the descriptors.
Returns
-------
fv: array_like, shape (K + ... | :]
if c_contiguous:
fv = fv.copy()
return fv
def power_normalize(xx, alpha=0.5):
"""Computes a alpha-power normalization for the matrix xx."""
return np.sign(xx) * np.abs(xx) ** alpha
def L2_normalize(xx):
"""L2-normalizes each row of the data xx."""
Zx = np.sum(xx * xx, 1)
xx_no... | 129 | 129 | 430 | 8 | 120 | murilovarges/HARBoP | tools/Utils/FisherVector.py | Python | fisher_vector | fisher_vector | 37 | 83 | 37 | 37 | a45f021c7ab1517776b0f40f61c6a03afdeb5dbb | bigcode/the-stack | train |
5c5da8a48d69c65613440efa | train | function | def L2_normalize(xx):
"""L2-normalizes each row of the data xx."""
Zx = np.sum(xx * xx, 1)
xx_norm = xx / np.sqrt(Zx[:, np.newaxis])
xx_norm[np.isnan(xx_norm)] = 0
return xx_norm
| def L2_normalize(xx):
| """L2-normalizes each row of the data xx."""
Zx = np.sum(xx * xx, 1)
xx_norm = xx / np.sqrt(Zx[:, np.newaxis])
xx_norm[np.isnan(xx_norm)] = 0
return xx_norm
| 1:]
if c_contiguous:
fv = fv.copy()
return fv
def power_normalize(xx, alpha=0.5):
"""Computes a alpha-power normalization for the matrix xx."""
return np.sign(xx) * np.abs(xx) ** alpha
def L2_normalize(xx):
| 64 | 64 | 65 | 7 | 56 | murilovarges/HARBoP | tools/Utils/FisherVector.py | Python | L2_normalize | L2_normalize | 29 | 34 | 29 | 29 | 446f4e679d1422343baf8af6ec93c238af301beb | bigcode/the-stack | train |
833a820048d7c252fa36148b | train | function | @common_api.route('/info')
def version():
"""
Get information about Indigo, Bingo, Service and Imago versions
---
tags:
- version
responses:
200:
description: JSON with service, indigo, bingo and imago vesrions
"""
versions = {}
# if is_indigo_db():
# version... | @common_api.route('/info')
def version():
| """
Get information about Indigo, Bingo, Service and Imago versions
---
tags:
- version
responses:
200:
description: JSON with service, indigo, bingo and imago vesrions
"""
versions = {}
# if is_indigo_db():
# versions['bingo_version'] = db_session.execute("S... | from flask import Blueprint, jsonify
import logging
# import re
# from v2.db.database import db_session
from v2.indigo_api import indigo_init
common_api = Blueprint('common_api', __name__)
common_api_logger = logging.getLogger('common')
@common_api.route('/info')
def version():
| 66 | 70 | 236 | 10 | 56 | tsingdao-Tp/Indigo | utils/indigo-service/service/v2/common_api.py | Python | version | version | 12 | 39 | 12 | 13 | e0db14b826d562c2744d286944f538a22c5cb964 | bigcode/the-stack | train |
c1c5314a2cdfd89573cf86dc | train | class | class SubjectJsonFactory():
@staticmethod
def subject_json(subject, workspace_name):
return {
'id': subject.id.replace('/', '-'),
'gender': subject.gender,
'ethnicity': subject.ethnicity,
'phenotypes': subject.phenotypes,
'diseases': subject.di... | class SubjectJsonFactory():
@staticmethod
| def subject_json(subject, workspace_name):
return {
'id': subject.id.replace('/', '-'),
'gender': subject.gender,
'ethnicity': subject.ethnicity,
'phenotypes': subject.phenotypes,
'diseases': subject.diseases,
'name': subject.attributes... | from anvil.terra.subject import Subject
from factories import cleanupKeys
from pymongo import ReplaceOne
class SubjectJsonFactory():
@staticmethod
| 31 | 64 | 143 | 9 | 21 | DataBiosphere/FHIR-Implementation | anvil/factories/subject.py | Python | SubjectJsonFactory | SubjectJsonFactory | 5 | 21 | 5 | 6 | b6fd259031e54aad1008a15199ccc42fd5e1d887 | bigcode/the-stack | train |
62b989a9569319cdc7d67a5f | train | class | class Atomic(Atomic):
def __init__(self):
self.name = 'Persistence/T1546.011-2'
self.controller_type = ''
self.external_id = 'T1546.011'
self.blackbot_id = 'T1546.011-2'
self.version = ''
self.language = 'boo'
self.description = self.get_description()
... | class Atomic(Atomic):
| def __init__(self):
self.name = 'Persistence/T1546.011-2'
self.controller_type = ''
self.external_id = 'T1546.011'
self.blackbot_id = 'T1546.011-2'
self.version = ''
self.language = 'boo'
self.description = self.get_description()
self.last_updated_by =... | from blackbot.core.utils import get_path_in_package
from blackbot.core.wss.atomic import Atomic
from terminaltables import SingleTable
import os
import json
class Atomic(Atomic):
| 39 | 188 | 629 | 5 | 33 | blackbotinc/artic2-atomics | art/art_T1546.011-2.py | Python | Atomic | Atomic | 7 | 72 | 7 | 7 | 00a5716a39d238c369ef9551d662a4684c9c9067 | bigcode/the-stack | train |
3ad6f3e101b3d463b9c0b899 | train | function | def _fail_appropriately(
token_string: str,
fail_to_None: bool = False,
silent: bool = False
) -> None:
'''
dictates how `magic.get_price()` will handle failures
when `get_price` is unable to find a price:
if `silent == True`, ypricemagic will print an error message using standard... | def _fail_appropriately(
token_string: str,
fail_to_None: bool = False,
silent: bool = False
) -> None:
| '''
dictates how `magic.get_price()` will handle failures
when `get_price` is unable to find a price:
if `silent == True`, ypricemagic will print an error message using standard python logging
if `silent == False`, ypricemagic will not log any error
if `fail_to_None == True`, yprice... | elif bucket == 'yearn or yearn-like': price = yearn.get_price(token_address, block)
return price
def _fail_appropriately(
token_string: str,
fail_to_None: bool = False,
silent: bool = False
) -> None:
| 63 | 64 | 195 | 36 | 26 | cartercarlson/ypricemagic | y/prices/magic.py | Python | _fail_appropriately | _fail_appropriately | 182 | 201 | 182 | 186 | d461f24e4a1f86f078e178681e59563aeda0ddbd | bigcode/the-stack | train |
21498e7620124b63d42ff7be | train | function | def get_prices(
token_addresses: Iterable[AnyAddressType],
block: Optional[Block] = None,
fail_to_None: bool = False,
silent: bool = False,
dop: int = 4
) -> List[Optional[float]]:
'''
In every case:
- if `silent == True`, tqdm will not be used
- if `silent == False`, tqdm will b... | def get_prices(
token_addresses: Iterable[AnyAddressType],
block: Optional[Block] = None,
fail_to_None: bool = False,
silent: bool = False,
dop: int = 4
) -> List[Optional[float]]:
| '''
In every case:
- if `silent == True`, tqdm will not be used
- if `silent == False`, tqdm will be used
When `get_prices` is unable to find a price:
- if `fail_to_None == True`, ypricemagic will return `None` for that token
- if `fail_to_None == False`, ypricemagic will raise a PriceError... | on {Network.printable()}')
def get_prices(
token_addresses: Iterable[AnyAddressType],
block: Optional[Block] = None,
fail_to_None: bool = False,
silent: bool = False,
dop: int = 4
) -> List[Optional[float]]:
| 63 | 64 | 208 | 56 | 7 | cartercarlson/ypricemagic | y/prices/magic.py | Python | get_prices | get_prices | 67 | 87 | 67 | 73 | 67469b80b6afb6fc90331931986a6653ed137b4a | bigcode/the-stack | train |
0577d094f73e10b6e5898edb | train | function | @log(logger)
def _exit_early_for_known_tokens(
token_address: str,
block: Block
) -> Optional[UsdPrice]:
bucket = check_bucket(token_address)
price = None
if bucket == 'atoken': price = aave.get_price(token_address, block=block)
elif bucket == 'balancer pool': pri... | @log(logger)
def _exit_early_for_known_tokens(
token_address: str,
block: Block
) -> Optional[UsdPrice]:
| bucket = check_bucket(token_address)
price = None
if bucket == 'atoken': price = aave.get_price(token_address, block=block)
elif bucket == 'balancer pool': price = balancer_multiplexer.get_price(token_address, block)
elif bucket == 'basketdao': price = basketda... | is None and uniswap_v3:
price = uniswap_v3.get_price(token, block=block)
if price is None:
price = uniswap_multiplexer.get_price(token, block=block)
# If price is 0, we can at least try to see if balancer gives us a price. If not, its probably a shitcoin.
if price is None or price == 0:
... | 191 | 191 | 638 | 32 | 158 | cartercarlson/ypricemagic | y/prices/magic.py | Python | _exit_early_for_known_tokens | _exit_early_for_known_tokens | 133 | 179 | 133 | 138 | b214e7c762f4c436e1eb3eb0a2822f01a5d6b190 | bigcode/the-stack | train |
df5de29ceebebb5c8500cc3e | train | function | @lru_cache(maxsize=None)
def _get_price(
token: AnyAddressType,
block: Block,
fail_to_None: bool = False,
silent: bool = False
) -> Optional[UsdPrice]:
symbol = _symbol(token, return_None_on_failure=True)
token_string = f"{symbol} {token}" if symbol else token
logger.debug("--------... | @lru_cache(maxsize=None)
def _get_price(
token: AnyAddressType,
block: Block,
fail_to_None: bool = False,
silent: bool = False
) -> Optional[UsdPrice]:
| symbol = _symbol(token, return_None_on_failure=True)
token_string = f"{symbol} {token}" if symbol else token
logger.debug("-------------[ y ]-------------")
logger.debug(f"Fetching price for...")
logger.debug(f"Token: {token_string}")
logger.debug(f"Block: {block or 'latest'}")
logger.debu... |
'''
return Parallel(dop, 'threading')(
delayed(get_price)(token_address, block, fail_to_None=fail_to_None, silent=silent)
for token_address in (token_addresses if silent else tqdm(token_addresses))
)
@lru_cache(maxsize=None)
def _get_price(
token: AnyAddressType,
block: Block,
... | 105 | 105 | 352 | 52 | 53 | cartercarlson/ypricemagic | y/prices/magic.py | Python | _get_price | _get_price | 90 | 130 | 90 | 97 | 17c584f7c23e6397a89f48d8af79b2e855974af1 | bigcode/the-stack | train |
53801de61fc238bc49f7920a | train | function | @log(logger)
def get_price(
token_address: AnyAddressType,
block: Optional[Block] = None,
fail_to_None: bool = False,
silent: bool = False
) -> Optional[UsdPrice]:
'''
Don't pass an int like `123` into `token_address` please, that's just silly.
- ypricemagic accepts ints to allow you t... | @log(logger)
def get_price(
token_address: AnyAddressType,
block: Optional[Block] = None,
fail_to_None: bool = False,
silent: bool = False
) -> Optional[UsdPrice]:
| '''
Don't pass an int like `123` into `token_address` please, that's just silly.
- ypricemagic accepts ints to allow you to pass `y.get_price(0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e)`
so you can save yourself some keystrokes while testing in a console
- (as opposed to `y.get_price("0x0bc529c0... | piedao, tokensets
from y.prices.utils.buckets import check_bucket
from y.prices.utils.sense_check import _sense_check
from y.typing import AnyAddressType, Block
from y.utils.raw_calls import _symbol
logger = logging.getLogger(__name__)
@log(logger)
def get_price(
token_address: AnyAddressType,
block: Optional... | 110 | 110 | 367 | 52 | 58 | cartercarlson/ypricemagic | y/prices/magic.py | Python | get_price | get_price | 37 | 64 | 37 | 43 | c1f260bdc5e9fd1366bae431d86eb33fc572987d | bigcode/the-stack | train |
940d35fe71893bafff98b86b | train | function | def most_recent_year():
"""
This year, if it's December.
The most recent year, otherwise.
Note: Advent of Code started in 2015
"""
aoc_now = datetime.datetime.now(tz=AOC_TZ)
year = aoc_now.year
if aoc_now.month < 12:
year -= 1
if year < 2015:
raise AocdError("Time tra... | def most_recent_year():
| """
This year, if it's December.
The most recent year, otherwise.
Note: Advent of Code started in 2015
"""
aoc_now = datetime.datetime.now(tz=AOC_TZ)
year = aoc_now.year
if aoc_now.month < 12:
year -= 1
if year < 2015:
raise AocdError("Time travel not supported yet")
... | =year, day=day, user=user)
try:
return puzzle.input_data
except PuzzleLockedError:
if not block:
raise
q = block == "q"
blocker(quiet=q, until=(year, day))
return puzzle.input_data
def most_recent_year():
| 64 | 64 | 101 | 5 | 58 | cqkh42/advent-of-code-data | aocd/get.py | Python | most_recent_year | most_recent_year | 51 | 63 | 51 | 51 | cd9cc3c40d847ee141bb74342cb8d1988a741534 | bigcode/the-stack | train |
830b14b208c497746b2f012d | train | function | def get_data(session=None, day=None, year=None, block=False):
"""
Get data for day (1-25) and year (>= 2015)
User's session cookie is needed (puzzle inputs differ by user)
"""
if session is None:
user = default_user()
else:
user = User(token=session)
if day is None:
d... | def get_data(session=None, day=None, year=None, block=False):
| """
Get data for day (1-25) and year (>= 2015)
User's session cookie is needed (puzzle inputs differ by user)
"""
if session is None:
user = default_user()
else:
user = User(token=session)
if day is None:
day = current_day()
log.info("current day=%s", day)
... | from .exceptions import PuzzleLockedError
from .models import default_user
from .models import Puzzle
from .models import User
from .utils import AOC_TZ
from .utils import blocker
log = getLogger(__name__)
def get_data(session=None, day=None, year=None, block=False):
| 64 | 64 | 186 | 15 | 49 | cqkh42/advent-of-code-data | aocd/get.py | Python | get_data | get_data | 25 | 48 | 25 | 25 | db62ee2aaf060f6db5188d4ac0535deac9220e55 | bigcode/the-stack | train |
e14dde1dac567c7884d2cc87 | train | function | def get_day_and_year():
"""
Returns tuple (day, year).
Here be dragons!
The correct date is determined with introspection of the call stack, first
finding the filename of the module from which ``aocd`` was imported.
This means your filenames should be something sensible, which identify the
... | def get_day_and_year():
| """
Returns tuple (day, year).
Here be dragons!
The correct date is determined with introspection of the call stack, first
finding the filename of the module from which ``aocd`` was imported.
This means your filenames should be something sensible, which identify the
day and year unambiguo... |
def most_recent_year():
"""
This year, if it's December.
The most recent year, otherwise.
Note: Advent of Code started in 2015
"""
aoc_now = datetime.datetime.now(tz=AOC_TZ)
year = aoc_now.year
if aoc_now.month < 12:
year -= 1
if year < 2015:
raise AocdError("Time ... | 201 | 201 | 670 | 6 | 194 | cqkh42/advent-of-code-data | aocd/get.py | Python | get_day_and_year | get_day_and_year | 79 | 141 | 79 | 79 | 090658b684ea7d00116a0ee9787230a90254f347 | bigcode/the-stack | train |
b5f86ec31f3177e473d5a431 | train | function | def current_day():
"""
Most recent day, if it's during the Advent of Code. Happy Holidays!
Day 1 is assumed, otherwise.
"""
aoc_now = datetime.datetime.now(tz=AOC_TZ)
if aoc_now.month != 12:
log.warning("current_day is only available in December (EST)")
return 1
day = min(aoc... | def current_day():
| """
Most recent day, if it's during the Advent of Code. Happy Holidays!
Day 1 is assumed, otherwise.
"""
aoc_now = datetime.datetime.now(tz=AOC_TZ)
if aoc_now.month != 12:
log.warning("current_day is only available in December (EST)")
return 1
day = min(aoc_now.day, 25)
r... | = datetime.datetime.now(tz=AOC_TZ)
year = aoc_now.year
if aoc_now.month < 12:
year -= 1
if year < 2015:
raise AocdError("Time travel not supported yet")
return year
def current_day():
| 64 | 64 | 93 | 4 | 59 | cqkh42/advent-of-code-data | aocd/get.py | Python | current_day | current_day | 66 | 76 | 66 | 66 | bd116181d551efa1a14aa8f78594aa14225a8510 | bigcode/the-stack | train |
6a6b77605edc1a97b6dccb75 | train | class | class DjangoDoc(XMLDoc):
def __init__(self, doc, title, section):
self.title = title
if section:
chapter = section.chapter
part = chapter.part
# Note: we elide section.title
key_prefix = (part.title, chapter.title, title)
else:
key_... | class DjangoDoc(XMLDoc):
| def __init__(self, doc, title, section):
self.title = title
if section:
chapter = section.chapter
part = chapter.part
# Note: we elide section.title
key_prefix = (part.title, chapter.title, title)
else:
key_prefix = None
se... | (section)
part.chapters.append(chapter)
if file[0].isdigit():
self.parts.append(part)
else:
part.is_appendix = True
appendix.append(part)
# Adds possible appendices
for part in appendix:
... | 104 | 104 | 349 | 6 | 98 | shirok1/mathics-django | mathics_django/doc/django_doc.py | Python | DjangoDoc | DjangoDoc | 614 | 654 | 614 | 614 | 033b2812fa64f755d89a6253ee5fa2e69b508b69 | bigcode/the-stack | train |
05a6adaa9b251a6a70f1183a | train | class | class DjangoDocGuideSection(DjangoDocSection):
"""An object for a Django Documented Guide Section.
A Guide Section is part of a Chapter. "Colors" or "Special Functions"
are examples of Guide Sections, and each contains a number of Sections.
like NamedColors or Orthogonal Polynomials.
"""
def __... | class DjangoDocGuideSection(DjangoDocSection):
| """An object for a Django Documented Guide Section.
A Guide Section is part of a Chapter. "Colors" or "Special Functions"
are examples of Guide Sections, and each contains a number of Sections.
like NamedColors or Orthogonal Polynomials.
"""
def __init__(
self, chapter: str, title: str,... | :
indices.update(test.test_indices())
result = {}
for index in indices:
result[index] = doc_data.get(
(self.chapter.part.title, self.chapter.title, self.title, index)
)
return result
def get_uri(self) -> str:
"""Return the URI of t... | 95 | 95 | 317 | 10 | 85 | shirok1/mathics-django | mathics_django/doc/django_doc.py | Python | DjangoDocGuideSection | DjangoDocGuideSection | 778 | 814 | 778 | 778 | 213dcc56bf2e9ef535fab8d6fa484e0bf5dca07e | bigcode/the-stack | train |
2c6256c7f35f049d14da732b | train | class | class DjangoDocTest(DocTest):
"""
See DocTest for formatting rules.
"""
def html(self) -> str:
result = '<div class="test"><span class="move"></span>'
result += f'<ul class="test" id="test_{self.index}">'
result += f'<li class="test">{escape_html(self.test, True)}</li>'
... | class DjangoDocTest(DocTest):
| """
See DocTest for formatting rules.
"""
def html(self) -> str:
result = '<div class="test"><span class="move"></span>'
result += f'<ul class="test" id="test_{self.index}">'
result += f'<li class="test">{escape_html(self.test, True)}</li>'
if self.key is None:
... | (test.test_indices())
result = {}
for index in indices:
result[index] = doc_data.get(
(self.chapter.part.title, self.chapter.title, self.title, index)
)
return result
def get_uri(self) -> str:
"""Return the URI of this subsection."""
r... | 93 | 93 | 311 | 8 | 85 | shirok1/mathics-django | mathics_django/doc/django_doc.py | Python | DjangoDocTest | DjangoDocTest | 913 | 948 | 913 | 913 | ea9facf6ca6c95a7b20d3b9a2ec2bd885ed83272 | bigcode/the-stack | train |
82fad966bd7aa193e54d5f66 | train | class | class DjangoDocSection(DjangoDocElement):
"""An object for a Django Documented Section.
A Section is part of a Chapter. It can contain subsections.
"""
def __init__(
self,
chapter,
title: str,
text: str,
operator,
installed=True,
in_guide=False,
... | class DjangoDocSection(DjangoDocElement):
| """An object for a Django Documented Section.
A Section is part of a Chapter. It can contain subsections.
"""
def __init__(
self,
chapter,
title: str,
text: str,
operator,
installed=True,
in_guide=False,
summary_text="",
):
sel... | ):
"""Return a list of parts in this doc"""
return self.doc.parts
def html(self, counters=None):
if len(self.tests) == 0:
return "\n"
return '<ul class="tests">%s</ul>' % (
"\n".join(
"<li>%s</li>" % test.html() for test in self.tests if not t... | 114 | 114 | 383 | 9 | 105 | shirok1/mathics-django | mathics_django/doc/django_doc.py | Python | DjangoDocSection | DjangoDocSection | 718 | 775 | 718 | 718 | b729d966daccf4100781a62caa9e6f8d5d6bbb98 | bigcode/the-stack | train |
7216e89845b11521753bd24a | train | function | def skip_module_doc(module, modules_seen):
return (
module.__doc__ is None
or module in modules_seen
or hasattr(module, "no_doc")
and module.no_doc
)
| def skip_module_doc(module, modules_seen):
| return (
module.__doc__ is None
or module in modules_seen
or hasattr(module, "no_doc")
and module.no_doc
)
| doc_data_path}")
doc_data = {}
def skip_doc(cls):
"""Returns True if we should skip cls in docstring extraction."""
return cls.__name__.endswith("Box") or (hasattr(cls, "no_doc") and cls.no_doc)
def skip_module_doc(module, modules_seen):
| 64 | 64 | 44 | 9 | 55 | shirok1/mathics-django | mathics_django/doc/django_doc.py | Python | skip_module_doc | skip_module_doc | 63 | 69 | 63 | 63 | 550aa59414499b6f821cdb79be52db9c0baf3fb8 | bigcode/the-stack | train |
71ebe4244b0956117b75899f | train | class | class DjangoDocChapter(DjangoDocElement):
"""An object for a Django Documentation Chapter.
A Chapter is part of a Part and contains Sections.
"""
def __init__(self, part: str, title: str, doc=None):
self.doc = doc
self.guide_sections = []
self.part = part
self.sections =... | class DjangoDocChapter(DjangoDocElement):
| """An object for a Django Documentation Chapter.
A Chapter is part of a Part and contains Sections.
"""
def __init__(self, part: str, title: str, doc=None):
self.doc = doc
self.guide_sections = []
self.part = part
self.sections = []
self.sections_by_slug = {}
... | join(item.html(counters) for item in items if not item.is_private())
if text == "":
# HACK ALERT if text is "" we may have missed some test markup.
return mark_safe(escape_html(self.rawdoc))
return mark_safe(text)
class DjangoDocChapter(DjangoDocElement):
| 64 | 64 | 196 | 9 | 55 | shirok1/mathics-django | mathics_django/doc/django_doc.py | Python | DjangoDocChapter | DjangoDocChapter | 657 | 681 | 657 | 657 | 3f33400ebffe39aeec8bb7ffe791e81f4ea54562 | bigcode/the-stack | train |
5a17440c535632dde0d9ebf5 | train | class | class DjangoDocText(object):
def __init__(self, text):
self.text = text
def get_tests(self) -> list:
return []
def is_private(self) -> bool:
return False
def __str__(self):
return self.text
def html(self, counters=None) -> str:
result = escape_html(self.te... | class DjangoDocText(object):
| def __init__(self, text):
self.text = text
def get_tests(self) -> list:
return []
def is_private(self) -> bool:
return False
def __str__(self):
return self.text
def html(self, counters=None) -> str:
result = escape_html(self.text, counters=counters)
... | ="tests">%s</ul>' % (
"\n".join(
"<li>%s</li>" % test.html() for test in self.tests if not test.private
)
)
def test_indices(self):
return [test.index for test in self.tests]
class DjangoDocText(object):
| 64 | 64 | 94 | 6 | 58 | shirok1/mathics-django | mathics_django/doc/django_doc.py | Python | DjangoDocText | DjangoDocText | 969 | 987 | 969 | 969 | 4363b1a321bb05ce6a27d0cc8f29ded4dcce914d | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.