code stringlengths 281 23.7M |
|---|
class DynamicPatcher(MetaPathFinder, Loader):
def __init__(self, patcher: Patcher) -> None:
self._patcher = patcher
self.sysmodules = {}
self.modules = self._patcher.fake_modules
self._loaded_module_names: Set[str] = set()
for name in self.modules:
if (self.needs_... |
def _problem_to_zz(problem_graph: nx.Graph, qubits: Sequence[cirq.Qid], gamma: float):
for (i1, i2, weight) in problem_graph.edges.data('weight'):
q0 = qubits[i1]
q1 = qubits[i2]
(yield cirq.ZZPowGate(exponent=(((2 * gamma) * weight) / np.pi), global_shift=(- 0.5)).on(q0, q1)) |
def extract_file(path, output_dir='.'):
_FILETYPE_TO_OPENER_MODE_MAPPING = {'.zip': (zipfile.ZipFile, 'r'), '.tar.gz': (tarfile.open, 'r:gz'), '.tgz': (tarfile.open, 'r:gz'), '.tar': (tarfile.open, 'r:'), '.tar.bz2': (tarfile.open, 'r:bz2'), '.tbz': (tarfile.open, 'r:bz2')}
cwd = os.getcwd()
os.chdir(output... |
class Perc(_Numeric):
def to_py(self, value: Union[(float, int, str, _UnsetNone)]) -> Union[(float, int, _UnsetNone)]:
self._basic_py_validation(value, (float, int, str))
if isinstance(value, usertypes.Unset):
return value
elif (not value):
return None
if isin... |
class ProgressBar(object):
def __init__(self, maxval=100, widgets=default_widgets, term_width=None, fd=sys.stdout):
assert (maxval > 0), 'maxval <= 0'
self.maxval = maxval
self.widgets = widgets
self.fd = fd
self.signal_set = False
if (term_width is None):
... |
class TOggVorbis(TestCase, TOggFileTypeMixin):
Kind = OggVorbis
def setUp(self):
self.filename = get_temp_copy(os.path.join(DATA_DIR, 'empty.ogg'))
self.audio = self.Kind(self.filename)
def tearDown(self):
os.unlink(self.filename)
def test_module_delete(self):
delete(self... |
class TrayIcon():
def __init__(self, mainWindow) -> None:
self.tray = QSystemTrayIcon(mainWindow)
self.mainWindow = mainWindow
theme_icon = self.mainWindow.settings.value('notification/theme_tray', 'default', str)
self.tray.setIcon(getIconTray(theme_icon))
self.tray.activated... |
class FlaubertTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self, vocab_file, merg... |
class Upsample(nn.Module):
def __init__(self, channels, use_conv, dims=2):
super().__init__()
self.channels = channels
self.use_conv = use_conv
self.dims = dims
if use_conv:
self.conv = conv_nd(dims, channels, channels, 3, padding=1)
def forward(self, x):
... |
.parametrize('path', ['/', _TEST_PATH])
def test_clean_partial_uploads(storage_engine, path):
storage_engine._root_path = path
storage_engine.put_content(_TEST_UPLOADS_PATH, _TEST_CONTENT)
assert storage_engine.exists(_TEST_UPLOADS_PATH)
assert (storage_engine.get_content(_TEST_UPLOADS_PATH) == _TEST_CO... |
def _segm_resnet(name, backbone_name, num_classes, aux, pretrained_backbone=True):
backbone = resnet.__dict__[backbone_name](pretrained=pretrained_backbone, replace_stride_with_dilation=[False, True, True])
return_layers = {'layer4': 'out'}
if aux:
return_layers['layer3'] = 'aux'
backbone = Inte... |
def add_import(project, pymodule, module_name, name=None):
imports = get_module_imports(project, pymodule)
candidates = []
names = []
selected_import = None
if (name is not None):
from_import = FromImport(module_name, 0, [(name, None)])
names.append(name)
candidates.append(fr... |
class LlamaMhaWrapper(torch.nn.Module):
def __init__(self, multihead_attn, attention_mask: Optional[torch.Tensor]=None, position_ids: Optional[torch.LongTensor]=None, past_key_value: Optional[Tuple[torch.Tensor]]=None, output_attentions: bool=False, use_cache: bool=False):
super(LlamaMhaWrapper, self).__ini... |
def test_geojson(driver):
data_url = '
m = folium.Map((41.9, 12.5), zoom_start=10, tiles='cartodbpositron')
marker_cluster = folium.plugins.MarkerCluster(name='cluster').add_to(m)
folium.GeoJson(data_url, embed=False).add_to(marker_cluster)
folium.GeoJson(data_url, embed=False, show=False, name='geo... |
class IndexedWeightsDataset(data.indexed_dataset.IndexedDataset):
def __init__(self, path):
self.values = []
self.read_data(path)
def read_data(self, path):
with open(path, 'r') as f:
for line in f:
self.values.append(float(line.strip('\n')))
self.... |
class Solution(object):
def maximalRectangle(self, matrix):
if ((matrix is None) or (len(matrix) == 0)):
return 0
(ls_row, ls_col) = (len(matrix), len(matrix[0]))
(left, right, height) = (([0] * ls_col), ([ls_col] * ls_col), ([0] * ls_col))
maxA = 0
for i in range... |
def convert_pytorch_grid2scipy(grid):
(_, H, W, D) = grid.shape
grid_x = (((grid[(0, ...)] + 1) * (D - 1)) / 2)
grid_y = (((grid[(1, ...)] + 1) * (W - 1)) / 2)
grid_z = (((grid[(2, ...)] + 1) * (H - 1)) / 2)
grid = np.stack([grid_z, grid_y, grid_x])
identity_grid = np.meshgrid(np.arange(H), np.a... |
def join_dataset_splits(datasets):
assert (len(datasets) == 3), 'Expecting train, val, test datasets'
(n1, n2, n3) = (len(datasets[0]), len(datasets[1]), len(datasets[2]))
data_list = (([datasets[0].get(i) for i in range(n1)] + [datasets[1].get(i) for i in range(n2)]) + [datasets[2].get(i) for i in range(n3... |
def test_negotiate_locale():
assert (core.negotiate_locale(['de_DE', 'en_US'], ['de_DE', 'de_AT']) == 'de_DE')
assert (core.negotiate_locale(['de_DE', 'en_US'], ['en', 'de']) == 'de')
assert (core.negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at']) == 'de_DE')
assert (core.negotiate_locale(['de_DE'... |
def parse_version_info(version_str: str, length: int=4) -> tuple:
from packaging.version import parse
version = parse(version_str)
assert version.release, f'failed to parse version {version_str}'
release = list(version.release)
release = release[:length]
if (len(release) < length):
relea... |
def calculate_arg_defaults(builder: IRBuilder, fn_info: FuncInfo, func_reg: (Value | None), symtable: dict[(SymbolNode, SymbolTarget)]) -> None:
fitem = fn_info.fitem
for arg in fitem.arguments:
if (arg.initializer and (not is_constant(arg.initializer))):
value = builder.coerce(builder.accep... |
def test_handle_block_closed_channel():
channel_state = factories.create(factories.NettingChannelStateProperties(close_transaction=TransactionExecutionStatus(finished_block_number=50, result=TransactionExecutionStatus.SUCCESS), settle_timeout=50))
pseudo_random_generator = random.Random()
block = Block(bloc... |
class TrainOptions():
def __init__(self):
self.parser = ArgumentParser()
self.initialize()
def initialize(self):
self.parser.add_argument('--exp_dir', type=str, help='Path to experiment output directory')
self.parser.add_argument('--dataset_type', default='ffhq_encode', type=str,... |
def save_colorful_images(prediction, filename, output_dir, palettes):
im = Image.fromarray(palettes[prediction.astype('uint8').squeeze()])
fn = os.path.join(output_dir, filename)
out_dir = os.path.split(fn)[0]
if (not os.path.exists(out_dir)):
os.mkdir(out_dir)
im.save(fn) |
class TestDOTAR3DetGWD(TestDOTA):
def eval(self):
txt_name = '{}.txt'.format(self.cfgs.VERSION)
real_test_img_list = self.get_test_image()
r3det_gwd = build_whole_network.DetectionNetworkR3DetGWD(cfgs=self.cfgs, is_training=False)
self.test_dota(det_net=r3det_gwd, real_test_img_list=... |
class MetricMeter():
def __init__(self, delimiter='\t'):
self.meters = defaultdict(AverageMeter)
self.delimiter = delimiter
def update(self, input_dict):
if (input_dict is None):
return
if (not isinstance(input_dict, dict)):
raise TypeError('Input to Metri... |
def test_pytester_run_with_timeout(pytester: Pytester) -> None:
testfile = pytester.makepyfile('def test_no_timeout(): pass')
timeout = 120
start = time.time()
result = pytester.runpytest_subprocess(testfile, timeout=timeout)
end = time.time()
duration = (end - start)
assert (result.ret == E... |
class MemcacheClient(config.Parser):
def __init__(self, serializer: Optional[Serializer]=None, deserializer: Optional[Deserializer]=None):
self.serializer = serializer
self.deserializer = deserializer
def parse(self, key_path: str, raw_config: config.RawConfig) -> 'MemcacheContextFactory':
... |
class TestUnconnectedCommand(CommandTest):
def test_info_command(self):
gametime.SERVER_START_TIME = 86400
expected = ('## BEGIN INFO 1.1\nName: %s\nUptime: %s\nConnected: %d\nVersion: Evennia %s\n## END INFO' % (settings.SERVERNAME, datetime.datetime.fromtimestamp(gametime.SERVER_START_TIME).ctime(... |
class JAXLinker(JITLinker):
def fgraph_convert(self, fgraph, input_storage, storage_map, **kwargs):
from pytensor.link.jax.dispatch import jax_funcify
from pytensor.tensor.random.type import RandomType
shared_rng_inputs = [inp for inp in fgraph.inputs if (isinstance(inp, SharedVariable) and ... |
class ShortcutFilteringFilter(logging.Filter):
def __init__(self, *, is_blacklist: bool, filters: str):
super().__init__()
self.__is_blacklist = is_blacklist
self.__filters = filters
def filter(self, record):
if (record.levelno >= logging.ERROR):
return True
i... |
class CallbackRegistry():
_by_group: dict[(str, list[RegisteredCallback])] = field(default_factory=(lambda : defaultdict(list)))
_by_callback_name: dict[(str, list[RegisteredCallback])] = field(default_factory=(lambda : defaultdict(list)))
def _register_module(self) -> None:
module = _path_hook._mod... |
def lsymeig(A: LinearOperator, neig: Optional[int]=None, M: Optional[LinearOperator]=None, bck_options: Mapping[(str, Any)]={}, method: Union[(str, Callable, None)]=None, **fwd_options) -> Tuple[(torch.Tensor, torch.Tensor)]:
return symeig(A, neig, 'lowest', M, method=method, bck_options=bck_options, **fwd_options) |
class QuantizeUpSample(nn.Module):
def __init__(self, size=None, scale_factor=None):
super(QuantizeUpSample, self).__init__()
self.size = size
self.scale_factor = scale_factor
def forward(self, x):
return QF.upsample(x, size=self.size, scale_factor=self.scale_factor) |
def test_scalar_conversion():
n = 3
arrays = [m.create_rec_simple(n), m.create_rec_packed(n), m.create_rec_nested(n), m.create_enum_array(n)]
funcs = [m.f_simple, m.f_packed, m.f_nested]
for (i, func) in enumerate(funcs):
for (j, arr) in enumerate(arrays):
if ((i == j) and (i < 2)):
... |
('pypyr.moduleloader.get_module')
(Step, 'run_conditional_decorators')
('unittest.mock.MagicMock', new=DeepCopyMagicMock)
def test_foreach_thrice_with_substitutions(mock_run, mock_moduleloader):
step = Step({'name': 'step1', 'foreach': ['{key1}', '{key2}', 'key3']})
context = get_test_context()
original_len... |
class GradClip(ViewOp):
__props__ = ()
def __init__(self, clip_lower_bound, clip_upper_bound):
self.clip_lower_bound = clip_lower_bound
self.clip_upper_bound = clip_upper_bound
if (not (self.clip_upper_bound >= self.clip_lower_bound)):
raise ValueError('`clip_upper_bound` sho... |
class KombuProducerContextFactory(ContextFactory):
def __init__(self, connection: Connection, exchange: Exchange, max_connections: Optional[int]=None, serializer: Optional[KombuSerializer]=None):
self.connection = connection
self.exchange = exchange
self.producers = Producers(limit=max_conne... |
class MultiFatigueModel(OptionGeneric):
def __init__(self, model: (FatigueModel | list), state_only: bool, split_controls: bool=True, apply_to_joint_dynamics: bool=False, **params):
super(MultiFatigueModel, self).__init__(**params)
if isinstance(model, FatigueModel):
model = [model]
... |
def test_list_build_source_namespaces():
namespaces_expected = [{'personal': True, 'score': 1, 'avatar_url': 'avatarurl', 'id': 'knownuser', 'title': 'knownuser', 'url': ' {'score': 2, 'title': 'someorg', 'personal': False, 'url': ' 'avatar_url': 'avatarurl', 'id': 'someorg'}]
found = get_bitbucket_trigger().li... |
def make_rst(path, main, subpath=[]):
shelp = capture(main, (subpath + ['--help']))
dhelp = parse_help(subpath, shelp)
fn = os.path.join(path, (dhelp['program'].replace(' ', '_') + '.rst'))
with open(fn, 'w') as f:
f.write(format_rst(dhelp))
for (subcommand, _) in dhelp['subcommands'][1:]:
... |
class BaseTemplateStrategy():
def __init__(self, strategy):
self.strategy = strategy
def render(self, tpl=None, html=None, context=None):
if ((not tpl) and (not html)):
raise ValueError('Missing template or html parameters')
context = (context or {})
if tpl:
... |
class PluginErrorWindow(UniqueWindow):
def __init__(self, parent, failures):
if self.is_not_unique():
return
super().__init__()
self.set_title(_('Plugin Errors'))
self.set_border_width(6)
self.set_transient_for(parent)
self.set_default_size(520, 300)
... |
class SawyerDoorUnlockEnvV2(SawyerXYZEnv):
def __init__(self):
hand_low = ((- 0.5), 0.4, (- 0.15))
hand_high = (0.5, 1, 0.5)
obj_low = ((- 0.1), 0.8, 0.15)
obj_high = (0.1, 0.85, 0.15)
goal_low = (0.0, 0.64, 0.21)
goal_high = (0.2, 0.7, 0.2111)
super().__init_... |
def main():
process_list = []
if (len(sys.argv) > 1):
pattern = (('.*' + sys.argv[1]) + '.*')
else:
pattern = '.*'
print((('\nFiltering processes with regex:: ' + pattern) + '\n'))
regex = re.compile(pattern, (re.I | re.UNICODE))
dsz.control.echo.Off()
cmd = ops.cmd.getDszCom... |
def batch_random_blur(images_list, height, width, blur_probability=0.5):
def generate_selector(p, bsz):
shape = [bsz, 1, 1, 1]
selector = tf.cast(tf.less(tf.random_uniform(shape, 0, 1, dtype=tf.float32), p), tf.float32)
return selector
new_images_list = []
for images in images_list:
... |
class Precond():
def __init__(self):
self.precond_dict = {}
def addPrecond(self, cond, obj1, obj2):
if (cond not in self.precond_dict.keys()):
self.precond_dict[cond] = {}
if (obj1 not in self.precond_dict[cond]):
self.precond_dict[cond][obj1] = set(obj2)
... |
def deal_range(pattern):
global ptn_len
ptn_len = 0
p = list(pattern)
if (len(pattern) == 1):
sub_ptn_list[ptn_len].start = p[0]
for i in range((len(pattern) - 1)):
sub_ptn_list[ptn_len].start = p[i]
sub_ptn_list[ptn_len].end = p[(i + 1)]
ptn_len = (ptn_len + 1) |
class SymbolFilter(Filter):
latex_symbols = {'\\alpha': '', '\\beta': '', '\\gamma': '', '\\delta': '', '\\varepsilon': '', '\\zeta': '', '\\eta': '', '\\vartheta': '', '\\iota': '', '\\kappa': '', '\\lambda': '', '\\mu': '', '\\nu': '', '\\xi': '', '\\pi': '', '\\varrho': '', '\\sigma': '', '\\tau': '', '\\upsilon... |
class TrainPipelineSparseDist(TrainPipeline[(In, Out)]):
def __init__(self, model: torch.nn.Module, optimizer: torch.optim.Optimizer, device: torch.device, execute_all_batches: bool=True, apply_jit: bool=False) -> None:
self._model = model
self._optimizer = optimizer
self._device = device
... |
class ResNet152bn_CIFAR(ResNetD):
def __init__(self, n_classes: int, n_input_channels: int=3, input_dimension: int=2, final_layer_dropout: float=0.0, stochastic_depth_p: float=0.0, squeeze_excitation: bool=False, squeeze_excitation_rd_ratio: float=(1.0 / 16)):
super().__init__(n_classes, n_input_channels, c... |
def uniq(container):
try:
sort = sorted((unbool(i) for i in container))
sliced = itertools.islice(sort, 1, None)
for (i, j) in zip(sort, sliced):
if equal(i, j):
return False
except (NotImplementedError, TypeError):
seen = []
for e in container... |
def index(request, person_pk=None):
people = models.Person.objects.all()
titles = models.Person.title.tag_model.objects.all()
skills = models.Skill.objects.all()
hobbies = models.Person.hobbies.tag_model.objects.all()
if person_pk:
person = models.Person.objects.get(pk=person_pk)
sub... |
class _NonLocalBlockND_Group(nn.Module):
def __init__(self, in_channels, num_group, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True, relu_layer=True, use_softmax=True, use_ffconv=True, use_attention=True):
super(_NonLocalBlockND_Group, self).__init__()
assert (dimension in [1, 2, 3]... |
(unittest.mock._patch.decoration_helper)
def _decoration_helper(self, patched, args, keywargs):
extra_args = []
with contextlib.ExitStack() as exit_stack:
for patching in patched.patchings:
arg = exit_stack.enter_context(patching)
if (not getattr(patching, 'dont_pass', False)):
... |
def process(ayat):
result = []
cur_y = ayat[0][1]
same_line = []
for ayah in ayat:
if (abs((ayah[1] - cur_y)) < 20):
same_line.append(ayah)
else:
same_line.sort(key=(lambda tup: tup[0]))
for s in same_line[::(- 1)]:
result.append(s)
... |
def stop_our_server():
if is_our_server_running():
try:
server.stop()
do_request(ADDRESS, 'stopserver', 0.1)
print('Stopped our command server.')
except Exception as err:
print('Failed to stop command server:')
print(err) |
class Bars(object):
widgtet_list = Widgets_List()
def init_top_single_bar(self):
return Bar(widgets=self.widgtet_list.init_top_single(), opacity=1, size=21)
def init_top_double_bar(self):
return Bar(widgets=self.widgtet_list.init_top_double(), opacity=1, size=21)
def init_bottom_double_b... |
def _set_max_batch_size(source: PersistentTensorDict):
tensor_data = list(source._items_metadata())
for (key, val) in tensor_data:
if (not val['array']):
_set_max_batch_size(source.get(key))
batch_size = []
if (not tensor_data):
source.batch_size = batch_size
return
... |
class ExecutionContext(object):
def __init__(self, client: CDPSession, contextPayload: Dict, objectHandleFactory: Any, frame: 'Frame'=None) -> None:
self._client = client
self._frame = frame
self._contextId = contextPayload.get('id')
auxData = contextPayload.get('auxData', {'isDefaul... |
def test_loading_unexpected_error(retort, strict_coercion, debug_trail):
loader_ = retort.replace(strict_coercion=strict_coercion, debug_trail=debug_trail).extend(recipe=[loader(str, bad_string_loader)]).get_loader(List[str])
if (debug_trail == DebugTrail.DISABLE):
raises_exc(TypeError(), (lambda : load... |
class Model(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.layers = torch.nn.Sequential(torch.nn.Linear(128, 64), torch.nn.ReLU(), torch.nn.Linear(64, 32), torch.nn.ReLU(), torch.nn.Linear(32, 2))
def forward(self, X: torch.Tensor) -> torch.Tensor:
return self.laye... |
def test_vectorgrid_dict_options():
m = folium.Map(location=(30, 20), zoom_start=4)
url = '
options = {'subdomain': 'test', 'token': 'test_token', 'vectorTileLayerStyles': {'all': {'fill': True, 'weight': 1, 'fillColor': 'grey', 'color': 'purple', 'fillOpacity': 0.3, 'opacity': 0.6}}}
vc = VectorGridPro... |
class MobileNetV1PreTrainedModel(PreTrainedModel):
config_class = MobileNetV1Config
load_tf_weights = load_tf_weights_in_mobilenet_v1
base_model_prefix = 'mobilenet_v1'
main_input_name = 'pixel_values'
supports_gradient_checkpointing = False
def _init_weights(self, module: Union[(nn.Linear, nn.C... |
class _EvalManager():
def __init__(self, quantsim_factory: Callable, eval_func: Callable[([tf.keras.Model], float)], results_dir: str):
self._quantsim_factory = quantsim_factory
self._eval_func = eval_func
self._results_dir = results_dir
os.makedirs(self._results_dir, exist_ok=True)
... |
class MockAnchorGenerator2x2(anchor_generator.AnchorGenerator):
def name_scope(self):
return 'MockAnchorGenerator'
def num_anchors_per_location(self):
return [1]
def _generate(self, feature_map_shape_list):
return box_list.BoxList(tf.constant([[0, 0, 0.5, 0.5], [0, 0.5, 0.5, 1], [0.5... |
class SliceType(Type[slice]):
def clone(self, **kwargs):
return type(self)()
def filter(self, x, strict=False, allow_downcast=None):
if isinstance(x, slice):
return x
else:
raise TypeError('Expected a slice!')
def __str__(self):
return 'slice'
def ... |
def decode_residuals(inp, blocksize, result):
method = inp.read_uint(2)
if (method >= 2):
raise FLACDecodeException('Reserved residual coding method')
parambits = [4, 5][method]
escapeparam = [15, 31][method]
partitionorder = inp.read_uint(4)
numpartitions = (1 << partitionorder)
if ... |
def affinity_seg(inputs, output_stride=16):
assert ((output_stride == 16) or (output_stride == 8)), 'output_stride should be 16 or 8'
with tf.variable_scope('resnet_v1_101'):
net = resnet_v1_base.resnet_head(inputs)
net = resnet_v1_base.resnet_block(net, 64, 256, 2, 1, 3, scope='block1')
... |
class Testing_branch_renderer_case_mixin(Testing_renderer_case_mixin):
def test_branch_tagged_0_commits_clean(self):
self.assert_rendered(self.define_pieces('v1.2.3', branch=True), 'branch_tagged_0_commits_clean')
def test_branch_tagged_1_commits_clean(self):
self.assert_rendered(self.define_pie... |
def setup_module():
global connection, table
connection = Connection(**connection_kwargs)
assert (connection is not None)
maybe_delete_table()
cfs = {'cf1': {}, 'cf2': None, 'cf3': {'max_versions': 1}}
connection.create_table(TEST_TABLE_NAME, families=cfs)
table = connection.table(TEST_TABLE... |
class SSConv(nn.Module):
def __init__(self, in_ch, out_ch, kernel_size=3):
super(SSConv, self).__init__()
self.depth_conv = nn.Conv2d(in_channels=out_ch, out_channels=out_ch, kernel_size=kernel_size, stride=1, padding=(kernel_size // 2), groups=out_ch)
self.point_conv = nn.Conv2d(in_channels... |
class Conv2d1bit(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding=1, dilation=1, groups=1, bias=False, binarized=False):
super(Conv2d1bit, self).__init__(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilatio... |
class PCenter(LocateSolver, BaseOutputMixin):
def __init__(self, name: str, problem: pulp.LpProblem, aij: np.array):
self.problem = problem
self.name = name
self.aij = aij
def __add_obj(self) -> None:
weight = getattr(self, 'weight_var')
self.problem += (weight, 'objectiv... |
def get_model_params(model_name, override_params, num_classes):
if model_name.startswith('efficientnet'):
(w, d, s, p) = efficientnet_params(model_name)
(blocks_args, global_params) = efficientnet(width_coefficient=w, depth_coefficient=d, dropout_rate=p, image_size=s, num_classes=num_classes)
el... |
class Computer(Prodict):
brand: str
cpu: Cpu
rams: List[Ram]
dict_key: dict
uninitialized: str
rams2: List[Ram]
def total_ram(self):
return sum([ram.capacity for ram in self.rams])
def total_ram2(self):
if (('rams2' in self) and (self['rams2'] is not None)):
r... |
class Dataset(torch.utils.data.Dataset):
def __init__(self, args, data_path, vocabs, rev_vocabs, images, split, set_type=None):
self.images = images
self.max_len = args.max_len
self.vocabs = vocabs
self.rev_vocabs = rev_vocabs
self.split = split
self.dataset = args.da... |
class Terminal256Formatter(Formatter):
name = 'Terminal256'
aliases = ['terminal256', 'console256', '256']
filenames = []
def __init__(self, **options):
Formatter.__init__(self, **options)
self.xterm_colors = []
self.best_match = {}
self.style_string = {}
self.use... |
def _map_context(numcores):
if ((numcores is not None) and (numcores > 1)):
try:
from joblib import Parallel, delayed
from joblib.pool import has_shareable_memory
map = (lambda x, y: Parallel(n_jobs=numcores)(delayed(has_shareable_memory)(x))(y))
parallel = Tr... |
class MDEditorWidget(forms.Textarea):
def __init__(self, config_name='default', *args, **kwargs):
super(MDEditorWidget, self).__init__(*args, **kwargs)
self.config = MDConfig(config_name)
def render(self, name, value, renderer=None, attrs=None):
if (value is None):
value = ''... |
def get_params(shared_model, gpu_id):
theta = {}
for (name, param) in shared_model.named_parameters():
param_copied = param.clone().detach().requires_grad_(True)
if (gpu_id >= 0):
theta[name] = param_copied.to(torch.device('cuda:{}'.format(gpu_id)))
else:
theta[na... |
def test_load_encodings_with_disabled_param():
quantsim_config = {'defaults': {'ops': {'is_output_quantized': 'True', 'is_symmetric': 'True'}, 'params': {'is_quantized': 'False', 'is_symmetric': 'True'}}, 'params': {}, 'op_type': {}, 'supergroups': [], 'model_input': {}, 'model_output': {}}
with open('./quantsi... |
class InferCwSequenceEmbeddingSharding(BaseCwEmbeddingSharding[(InferSequenceShardingContext, KJTList, List[torch.Tensor], List[torch.Tensor])]):
def create_input_dist(self, device: Optional[torch.device]=None) -> BaseSparseFeaturesDist[KJTList]:
return InferTwSparseFeaturesDist(features_per_rank=self.featu... |
class Downloader():
def __init__(self, **kwargs):
self.ua = kwargs.get('useragent', {'User-Agent': 'Mozilla'})
self.chunk = 1048576
cafile = ssl.get_default_verify_paths().openssl_cafile
try:
if (not os.path.exists(cafile)):
import certifi
... |
class MCFunctionLexer(RegexLexer):
name = 'MCFunction'
url = '
aliases = ['mcfunction', 'mcf']
filenames = ['*.mcfunction']
mimetypes = ['text/mcfunction']
version_added = '2.12'
_block_comment_prefix = '[>!]'
tokens = {'root': [include('names'), include('comments'), include('literals'),... |
def test_list_all_commits(project):
data = {'branch': 'new-branch', 'start_branch': 'main', 'commit_message': 'New commit on new branch', 'actions': [{'action': 'create', 'file_path': 'new-file', 'content': 'new content'}]}
commit = project.commits.create(data)
commits = project.commits.list(all=True)
a... |
class Migration(migrations.Migration):
dependencies = [('auth', '0011_update_proxy_permissions'), ('tasks', '0025_task_sites')]
operations = [migrations.AddField(model_name='task', name='groups', field=models.ManyToManyField(blank=True, help_text='The groups for which this task is active.', to='auth.Group', ver... |
class TestNetCDF4Integration(object):
def setup_class(self):
self.tempdir = tempfile.TemporaryDirectory()
return
def teardown_class(self):
self.tempdir.cleanup()
del self.tempdir
return
def setup_method(self):
self.testInst = pysat.Instrument('pysat', 'testing... |
def get_no_comm_postprocess(stage: Dict[(str, Any)], num_rounds: int, batchsize: int, proxify: Proxify) -> Callable[([DataFrame], DataFrame)]:
if (num_rounds == batchsize):
return (lambda x: x)
try:
import cudf
except ImportError:
return (lambda x: x)
if ((not stage) or (not isin... |
class TestMetricModule(RecMetricModule):
def __init__(self, batch_size: int, world_size: int, rec_tasks: Optional[List[RecTaskInfo]]=None, rec_metrics: Optional[RecMetricList]=None, throughput_metric: Optional[ThroughputMetric]=None, state_metrics: Optional[Dict[(str, StateMetric)]]=None, compute_interval_steps: in... |
class UniformTextureSequence(TextureSequence):
def _get_item_width(self):
raise NotImplementedError('abstract')
def _get_item_height(self):
raise NotImplementedError('abstract')
def item_width(self):
return self._get_item_width()
def item_height(self):
return self._get_it... |
def basic_blocks(dim, index, layers, pool_size=3, mlp_ratio=4.0, act_layer=nn.GELU, norm_layer=GroupNorm1, drop_rate=0.0, drop_path_rate=0.0, layer_scale_init_value=1e-05):
blocks = []
for block_idx in range(layers[index]):
block_dpr = ((drop_path_rate * (block_idx + sum(layers[:index]))) / (sum(layers)... |
class NotifyingQueue(Event, Generic[T]):
def __init__(self, maxsize: int=None, items: Iterable[T]=()) -> None:
super().__init__()
self.queue = Queue(maxsize, items)
if items:
self.set()
def put(self, item: T) -> None:
self.queue.put(item)
self.set()
def ge... |
def handle_data(context, data):
context.i += 1
if (context.i < 300):
return
short_mavg = data.history(context.sym, 'price', 100, '1d').mean()
long_mavg = data.history(context.sym, 'price', 300, '1d').mean()
if (short_mavg > long_mavg):
order_target(context.sym, 100)
elif (short_m... |
def train(train_queue, model, criterion, optimizer):
global is_multi_gpu
objs = utils.AvgrageMeter()
top1 = utils.AvgrageMeter()
top5 = utils.AvgrageMeter()
model.train()
for (step, (input, target)) in enumerate(train_queue):
n = input.size(0)
input = input.cuda()
target ... |
def voc_ap(rec, prec, use_07_metric=False):
if use_07_metric:
ap = 0.0
for t in np.arange(0.0, 1.1, 0.1):
if (np.sum((rec >= t)) == 0):
p = 0
else:
p = np.max(prec[(rec >= t)])
ap = (ap + (p / 11.0))
else:
mrec = np.conc... |
_exceptions
_parameters('name', 'description')
_parameters('id', 'name', 'slug', 'periodicity', 'description', 'email')
def handle_update(business_logic, query):
find_identifier(business_logic, query, name_ok=False)
emails = query.get('email', None)
if (emails == []):
emails = None
elif (emails ... |
.online
def test_requirement_source_multiple_files(req_file):
source = _init_requirement([(req_file(), 'flask==2.0.1'), (req_file(), 'requests==2.8.1'), (req_file(), 'pip-api==0.0.22\npackaging==21.0')])
specs = list(source.collect())
assert (ResolvedDependency('Flask', Version('2.0.1')) in specs)
asser... |
def split_by_attr_random(pt2seeds: Dict[(str, List[List[str]])], pt2seed_names: Dict[(str, List[str])], candidate_dir: Path, output_dir: Path, neg_only_pts=None, pos_per_asin=5, times_negative=3, times_asin_negative=5, context_per_sample=2, max_pos_pairs_per_set=None, pct_dev=0.2):
logger.info('Generate by random s... |
def test_to_cirq():
bb = BloqBuilder()
q = bb.add(OneState())
q = bb.add(Hadamard(), q=q)
cbloq = bb.finalize(q=q)
(circuit, _) = cbloq.to_cirq_circuit()
cirq.testing.assert_has_diagram(circuit, '_c(0): XH')
vec1 = cbloq.tensor_contract()
vec2 = cirq.final_state_vector(circuit)
np.te... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.