code stringlengths 281 23.7M |
|---|
def parse_args_and_config():
parser = argparse.ArgumentParser(description=globals()['__doc__'])
parser.add_argument('--config', type=str, required=True, help='Path to the config file')
parser.add_argument('--seed', type=int, default=1234, help='Set different seeds for diverse results')
parser.add_argume... |
_params(node='x')
def test_if_reassignment_in_body(condition: str, satisfy_val: (int | None), fail_val: (int | None)) -> None:
node = builder.extract_node(f'''
def f(x, y):
if {condition}:
if y:
x = {fail_val}
return (
x #
)
''')
... |
_criterion('wsc')
class WSCCriterion(FairseqCriterion):
def __init__(self, args, task):
super().__init__(args, task)
if (self.args.save_predictions is not None):
self.prediction_h = open(self.args.save_predictions, 'w')
else:
self.prediction_h = None
self.bpe ... |
def dataset_id_generator(dataset_spec, split, pool, sampler):
chunk_sizes = sampler.compute_chunk_sizes()
(flush_chunk_size, other_chunk_sizes) = (chunk_sizes[0], chunk_sizes[1:])
class_set = dataset_spec.get_classes(split)
num_classes = len(class_set)
dummy_dataset_id = num_classes
total_images... |
def test_should_fail_no_providers(context, app):
test_config = json.loads(_TEST_CONFIG_JSON)
test_config['providers'] = []
with pytest.raises(InvalidStorageConfigurationException) as exc_info:
engine = MultiCDNStorage(context, **test_config)
assert ('providers should be a dict of storage provide... |
class Dataset(torch.utils.data.Dataset):
def __init__(self, data_folder, image_size):
self.data_folder = data_folder
if (not os.path.exists(self.data_folder)):
raise Exception(f'[!] {self.data_folder} not exists.')
self.objects_path = []
self.image_name = check_data(data_... |
.usefixtures('toggle_batching')
def test_nn_linear(tmp_path: Path) -> None:
foo = torch.nn.Linear(128, 64)
bar = torch.nn.Linear(128, 64)
assert (not check_state_dict_eq(foo.state_dict(), bar.state_dict()))
snapshot = Snapshot.take(str(tmp_path), {'foo': foo})
snapshot.restore({'foo': bar})
asse... |
class LinuxMips32Stat(ctypes.Structure):
_fields_ = [('st_dev', ctypes.c_uint32), ('st_pad1', (ctypes.c_int32 * 3)), ('st_ino', ctypes.c_uint32), ('st_mode', ctypes.c_uint32), ('st_nlink', ctypes.c_uint32), ('st_uid', ctypes.c_uint32), ('st_gid', ctypes.c_uint32), ('st_rdev', ctypes.c_uint32), ('st_pad2', (ctypes.c... |
class BatchTransferParameter1(DataElementGroup):
max_transfer_count = DataElementField(type='num', max_length=7, _d='Maximale Anzahl CreditTransferTransactionInformation')
sum_amount_required = DataElementField(type='jn', _d='Summenfeld benotigt')
single_booking_allowed = DataElementField(type='jn', _d='Ein... |
def voteaction(mutator):
(mutator)
def decorator(_root, info, pk):
(entry, sender) = (Entry.objects_published.select_related('author').only('id', 'author_id', 'author__karma').get(pk=pk), info.context.user)
if (entry.author == sender):
raise PermissionDenied(_("we couldn't handle you... |
class Pad(object):
def __init__(self, padding, fill=0):
assert isinstance(padding, (numbers.Number, tuple))
assert isinstance(fill, (numbers.Number, str, tuple))
if (isinstance(padding, collections.Sequence) and (len(padding) not in [2, 4])):
raise ValueError(('Padding must be an... |
_dataframe_method
_alias(groupby_column_name='by', sort_column_name='column')
def groupby_topk(df: pd.DataFrame, by: Union[(list, Hashable)], column: Hashable, k: int, dropna: bool=True, ascending: bool=True, ignore_index: bool=True) -> pd.DataFrame:
if isinstance(by, Hashable):
by = [by]
check('by', by... |
class JWSzRestrictStateTest(unittest.TestCase):
def test_jw_sz_restrict_state(self):
n_sites = numpy.random.randint(1, 10)
n_qubits = (2 * n_sites)
sz_int = (((- 1) ** numpy.random.randint(2)) * numpy.random.randint((n_sites + 1)))
sz_value = (sz_int / 2)
sz_indices = jw_sz_i... |
def test_token_network_proxy_update_transfer(token_network_proxy, private_keys, token_proxy, chain_id, web3, contract_manager):
token_network_address = to_canonical_address(token_network_proxy.proxy.address)
c1_client = JSONRPCClient(web3, private_keys[1])
c1_proxy_manager = ProxyManager(rpc_client=c1_clien... |
class FcNet(nn.Module):
def __init__(self, input_dim, hidden_dims, output_dim, dropout_p=0.0):
super().__init__()
self.input_dim = input_dim
self.hidden_dims = hidden_dims
self.output_dim = output_dim
self.dropout_p = dropout_p
self.dims = [self.input_dim]
sel... |
_task_action
class GrabOrReleaseActionIdBased(SimulatorTaskAction):
def run_checks(self, task, kwargs, gripped_object_id, distance_threshold, episode):
curr_observations = self._sim.get_sensor_observations()
avail_iids = np.unique(curr_observations['semantic']).tolist()
agent_position = self... |
class ShortCunk_CNN_AutoTagging_Classifier(nn.Module):
def __init__(self, n_channels=128, sample_rate=16000, n_fft=512, f_min=0.0, f_max=8000.0, n_mels=64, n_class=50):
super(ShortCunk_CNN_AutoTagging_Classifier, self).__init__()
self.spec = torchaudio.transforms.MelSpectrogram(sample_rate=sample_ra... |
def test_ordered():
check_vector_transform(tr.ordered, SortedVector(6))
with pytest.warns(FutureWarning, match='ndim_supp argument is deprecated'):
tr.Ordered(1)
check_jacobian_det(tr.ordered, Vector(R, 2), pt.vector, floatX(np.array([0, 0])), elemwise=False)
vals = get_values(tr.ordered, Vector... |
def compare_original_date(a1, a2):
(a1, a2) = (a1.album, a2.album)
if (a1 is None):
return (- 1)
if (a2 is None):
return 1
if (not a1.title):
return 1
if (not a2.title):
return (- 1)
a1_date = a1.get('originaldate', a1.date)
a2_date = a2.get('originaldate', a2... |
def run(model_args, data_args, training_args, additional_training_args):
setup_logging(training_args)
set_seed(training_args.seed)
datasets = load_dataset(data_args.dataset_name, data_args.dataset_config_name)
features = datasets['train'].features
text_column_name = 'tokens'
label_column_name = ... |
def name2cp(k):
if (k == 'apos'):
return ord("'")
if hasattr(htmlentitydefs, 'name2codepoint'):
return htmlentitydefs.name2codepoint[k]
else:
k = htmlentitydefs.entitydefs[k]
if (k.startswith('&#') and k.endswith(';')):
return int(k[2:(- 1)])
return ord(co... |
class Hopper():
def __init__(self, dirname='./Hopper'):
self.mean = np.array([1., (- 0.), (- 0.), (- 0.), 0., 2., (- 0.0085352), 0.0068375, (- 0.), (- 0.), (- 0.)])
self.std = np.array([0., 0., 0., 0., 0., 0., 1., 1., 1., 3., 5.7164752])
self.dims = 33
self.lb = ((- 1) * np.ones(self... |
def train(training_data_loader, G_optimizer, model, criterion, epoch):
lr = adjust_learning_rate(G_optimizer, (epoch - 1))
mse = []
for param_group in G_optimizer.param_groups:
param_group['lr'] = lr
print('Epoch={}, lr={}'.format(epoch, G_optimizer.param_groups[0]['lr']))
for (iteration, ba... |
.parametrize('data, expdata', [([1, 0, 0, 0], [1, 0, 0]), ([1, 0, 0, (np.pi / 2)], [0, 1, (np.pi / 2)]), ([1, 1, 1, 0], [2, 1, 0]), ([1, 1, 1, 0], [2, 1, 0]), ([1, 1, 1, (np.pi / 4)], [1., 1., (np.pi / 4)])])
def test_line_calc(data, expdata):
line = pyodrx.Line(data[0])
(x, y, h, l) = line.get_end_data(data[1]... |
class XModel(nn.Module):
def __init__(self, cfg):
super(XModel, self).__init__()
self.t = cfg.t_step
self.self_attention = XEncoder(d_model=cfg.feat_dim, hid_dim=cfg.hid_dim, out_dim=cfg.out_dim, n_heads=cfg.head_num, win_size=cfg.win_size, dropout=cfg.dropout, gamma=cfg.gamma, bias=cfg.bias... |
class GPUTimer():
def __init__(self, stream):
self.start_ = torch.cuda.Event(enable_timing=True)
self.stop_ = torch.cuda.Event(enable_timing=True)
self.stream_ = stream
def start(self):
self.stream_.record_event(self.start_)
def stop(self):
self.stream_.record_event(s... |
def rnms_gpu(det_boxes, iou_threshold, device_id):
if (det_boxes.shape[0] == 0):
return np.array([], np.int64)
else:
assert (det_boxes.shape[1] == 6), 'shape of det_boxes is not 6, {}'.format(det_boxes)
keep = rotate_gpu_nms(det_boxes, iou_threshold, device_id)
keep = np.reshape(... |
class TestCompareBasicModels(TestCase):
def test_compare_full(self):
basic_full = pybamm.lead_acid.BasicFull()
full = pybamm.lead_acid.Full()
parameter_values = pybamm.ParameterValues('Sulzer2019')
parameter_values['Current function [A]'] = 10
basic_sim = pybamm.Simulation(ba... |
def get_where_function(where_expr=None):
if (where_expr is None):
return None
where_expr = where_expr.strip()
try:
where_code = compile(where_expr, '--where', 'eval')
except Exception as err:
raise ValueError(('Cannot parse: %s' % (err,)))
check_eval_names(where_code, ['__bui... |
def get_proj_libdirs(proj_dir: Path) -> list[str]:
proj_libdir = os.environ.get('PROJ_LIBDIR')
libdirs = []
if (proj_libdir is None):
libdir_search_paths = ((proj_dir / 'lib'), (proj_dir / 'lib64'))
for libdir_search_path in libdir_search_paths:
if libdir_search_path.exists():
... |
def test_discover_raw_target(local_client, grpc_client):
random_image_vector = random_vector(image_vector_size)
def f(client: QdrantBase, **kwargs: Dict[(str, Any)]) -> List[models.ScoredPoint]:
return client.discover(collection_name=COLLECTION_NAME, target=random_image_vector, context=[models.ContextE... |
class AND(BinaryBitOp):
identity = (- 1)
commutative = True
associative = True
nfunc_spec = ('bitwise_and', 2, 1)
def impl(self, x, y):
return (x & y)
def c_code(self, node, name, inputs, outputs, sub):
(x, y) = inputs
(z,) = outputs
return f'{z} = ({x} & {y});'
... |
def make_dataset(dir, class_to_idx):
images = []
dir = os.path.expanduser(dir)
for target in tqdm(sorted(os.listdir(dir))):
d = os.path.join(dir, target)
if (not os.path.isdir(d)):
continue
for (root, _, fnames) in sorted(os.walk(d)):
for fname in sorted(fname... |
def test_package_include_with_multiple_dirs() -> None:
pkg_include = PackageInclude(base=fixtures_dir, include='with_includes')
assert (pkg_include.elements == [(with_includes / '__init__.py'), (with_includes / 'bar'), (with_includes / 'bar/baz.py'), (with_includes / 'extra_package'), (with_includes / 'extra_pa... |
def _is_ambiguous(tags, skip_space_ambiguity=True):
if (len(tags) < 2):
return False
if skip_space_ambiguity:
space_pos = [(tag.index(' ') if (' ' in tag) else None) for tag in map(str, tags)]
if (len(space_pos) == len(set(space_pos))):
return False
return True |
class TestGetHandlers(TestCase):
DEFAULT_APP = 'rapidsms.contrib.default'
ECHO_APP = 'rapidsms.contrib.echo'
ECHO_HANDLER = 'rapidsms.contrib.echo.handlers.echo'
PING_HANDLER = 'rapidsms.contrib.echo.handlers.ping'
ECHO_HANDLER_CLASS = 'rapidsms.contrib.echo.handlers.echo.EchoHandler'
PING_HANDL... |
_end_docstrings(INIT_TOKENIZER_DOCSTRING)
class PreTrainedTokenizerFast(PreTrainedTokenizerBase):
vocab_files_names = VOCAB_FILES_NAMES
slow_tokenizer_class: PreTrainedTokenizer = None
can_save_slow_tokenizer: bool = True
def __init__(self, *args, **kwargs):
tokenizer_object = kwargs.pop('tokeni... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('word')
parser.add_argument('--title', action='store_true', help=_('display word and article'))
parser.add_argument('--name', action='store_true', help=_('display the word itself'))
parser.add_argument('--article', action='stor... |
class CommandRefactorUseFunction(Command):
name = commands.COMMAND_REFACTOR_USE_FUNCTION
kind: CodeActionKind = 'refactor'
document_uri: DocumentUri
position: typing.Range
def validate(self, info):
usefunction.UseFunction(project=self.project, resource=info.resource, offset=info.current_docu... |
class FakeDataABC(metaclass=ABCMeta):
def filelist(self):
msg = 'Collection of (str) file paths to mock'
raise NotImplementedError(msg)
def fake_files(self):
return map(type(self), self.filelist)
def fake_dirs(self):
return set(chain(*map(attr('parents'), self.fake_files)))
... |
def test_concatenate_and_rechunk__tiny_file():
z1 = zarr.zeros(4, chunks=3, dtype='i4')
z1[:] = np.arange(4)
z2 = zarr.zeros(1, chunks=3, dtype='i4')
z2[:] = np.arange(4, 5)
z3 = zarr.zeros(5, chunks=3, dtype='i4')
z3[:] = np.arange(5, 10)
zarrs = [z1, z2, z3]
out = concatenate_and_rechu... |
class CosStepScheduler(LRScheduler):
def __init__(self, optimizer, start_lr=0.01, end_lr=0.005, epochs=50, last_epoch=(- 1), **kwargs):
self.start_lr = start_lr
self.end_lr = end_lr
self.lr_spaces = self._build_lr(start_lr, end_lr, epochs)
super(CosStepScheduler, self).__init__(optim... |
_fixtures(FieldFixture)
def test_helpers_for_events_class_side(fixture):
class ModelObject():
events = ExposedNames()
events.event1 = (lambda i: Event())
events.event2 = (lambda i: Event())
assert (ModelObject.events.event1.name == 'event1')
with expected(AttributeError):
Mod... |
('pytube.request.get')
def test_trimmed_pagination_not_found(request_get, playlist_html, playlist_long_html):
url = '
request_get.side_effect = [playlist_long_html, '{"content_html":"<a href=\\"/watch?v=BcWz41-4cDk&feature=plpp_video&ved=CCYQxjQYACITCO33n5-pn-cCFUG3xAodLogN2yj6LA\\">}", "load_more_widge... |
def add_data_args(parser):
parser.add_argument('--dataset', type=str, default='writing_prompts', choices=DATASET_CHOICES, help='dataset format')
parser.add_argument('--data-dir', type=str, help='data directory')
parser.add_argument('--split-sizes', type=float, nargs=3, default=[0.8, 0.1, 0.1], help='train/v... |
class LevitImageProcessor(BaseImageProcessor):
model_input_names = ['pixel_values']
def __init__(self, do_resize: bool=True, size: Dict[(str, int)]=None, resample: PILImageResampling=PILImageResampling.BICUBIC, do_center_crop: bool=True, crop_size: Dict[(str, int)]=None, do_rescale: bool=True, rescale_factor: U... |
def _check_assertions(wrapped: Callable[(..., Any)], function_locals: dict, condition_type: str='precondition', function_return_val: Any=None) -> None:
if hasattr(wrapped, '__self__'):
target = wrapped.__func__
else:
target = wrapped
assertions = []
if (condition_type == 'precondition'):... |
def get_engine():
db_url = get_db_url()
peewee_connection_args = app.config.get('DB_CONNECTION_ARGS', {})
sa_connection_args = {}
if ('ssl' in peewee_connection_args):
sa_connection_args['ssl'] = peewee_connection_args['ssl']
engine = create_engine(db_url, connect_args=sa_connection_args)
... |
def test_marker_union_intersect_single_with_overlapping_constraints() -> None:
m = parse_marker('sys_platform == "darwin" or python_version < "3.4"')
intersection = m.intersect(parse_marker('python_version <= "3.6"'))
assert (str(intersection) == 'sys_platform == "darwin" and python_version <= "3.6" or pyth... |
def _load_dataparser(parser_file, data_value):
try:
compilation_data = parsing.register_fields(data_value)
specification = util.spec_from_file_location('', parser_file)
specification.loader.exec_module(util.module_from_spec(specification))
string_data = None
if options.data:
... |
class Head(nn.Module):
def __init__(self, input_dim, hidden_dim, n_class=8):
super(Head, self).__init__()
self._name = 'Head'
self.bn0 = nn.BatchNorm1d(input_dim)
self.fc_0 = nn.Linear(input_dim, hidden_dim)
self.bn1 = nn.BatchNorm1d(hidden_dim)
self.fc_1 = nn.Linear(... |
.parametrize('url_str, source_url_str, resource_type', BUGGY_URLS)
def test_buggy_url_workaround_needed(ad_blocker, config_stub, easylist_easyprivacy, url_str, source_url_str, resource_type):
config_stub.val.content.blocking.adblock.lists = easylist_easyprivacy
ad_blocker.adblock_update()
resource_type_str ... |
class ElmLexer(RegexLexer):
name = 'Elm'
url = '
aliases = ['elm']
filenames = ['*.elm']
mimetypes = ['text/x-elm']
version_added = '2.1'
validName = "[a-z_][a-zA-Z0-9_\\']*"
specialName = '^main '
builtinOps = ('~', '||', '|>', '|', '`', '^', '\\', "'", '>>', '>=', '>', '==', '=', '... |
def mx_calculate_dist(anchor, positive):
d1 = mx.ndarray.sum((anchor * anchor), axis=1).reshape(1, 1)
d2 = mx.ndarray.sum((positive * positive), axis=1).reshape((- 1), 1)
eps = 1e-12
a = d1.repeat(int(positive.shape[0]))
b = mx.ndarray.transpose(d2.repeat(1))
c = (2.0 * mx.ndarray.dot(anchor, mx... |
def get_args():
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--uuid', required=True, type=uuid_parse, help='UUID of TA')
parser.add_argument('--version', type=int_parse, default=0, help='Version')
parser.add_argument('--key', required=True, help='Name of key fil... |
class ControlBuilder():
def __init__(self, parent, title, dtype, default, selected_value=None, choices=None, is_radio=False, rounding=None, min_max=None, helptext=None, radio_columns=3, label_width=20, control_width=None):
logger.debug('Initializing %s: (parent: %s, title: %s, dtype: %s, default: %s, select... |
def get_irradiance_poa(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth, gcr, height, pitch, ghi, dhi, dni, albedo, model='isotropic', dni_extra=None, iam=1.0, npoints=100, vectorize=False):
if (model == 'haydavies'):
if (dni_extra is None):
raise ValueError(f'must supply dni_extra for... |
class MockProcResult():
def get_details(self):
random_num = random.randint(1, 1000)
return {'device_name': f'workstation{random_num}', 'process_username': [f'username{random_num}'], 'process_name': f'proc{random_num}', 'process_cmdline': [f'cmdline{random_num}'], 'device_timestamp': f'ts{random_num}... |
def onconditional_peerdir(unit, *args):
dict_name = args[0].upper()
use_var = ('USE_' + dict_name)
make_var = (('MAKE_' + dict_name) + '_FROM_SOURCE')
use_var_value = unit.get(use_var)
make_var_value = unit.get(make_var)
if (use_var_value is None):
unit.set([use_var, 'yes'])
use_... |
def test__getting_started__custom_objectives():
from bioptim.examples.getting_started import custom_objectives as ocp_module
bioptim_folder = os.path.dirname(ocp_module.__file__)
ocp_module.prepare_ocp(biorbd_model_path=(bioptim_folder + '/models/cube.bioMod'), phase_dynamics=PhaseDynamics.SHARED_DURING_THE... |
def ndarray_to_file(np_array: np.ndarray, path: str, file_system: AbstractFileSystem, block_path_provider: BlockWritePathProvider, content_type: str=ContentType.PARQUET.value, **kwargs) -> None:
np_arrays = [array for array in np_array]
pa_utils.table_to_file(pa.table({'data': np_arrays}), path, file_system, bl... |
class GIFEncoder(nn.Module):
def __init__(self, image_feature_size=512, n_frames=4):
super().__init__()
self._n_frames = n_frames
self._image_feature_size = image_feature_size
self.image_seq_reduce_layer = nn.Linear((self._image_feature_size * self._n_frames), self._image_feature_siz... |
def _create_gradient_clipper(cfg: CfgNode) -> _GradientClipper:
cfg = copy.deepcopy(cfg)
def clip_grad_norm(p: _GradientClipperInput):
torch.nn.utils.clip_grad_norm_(p, cfg.CLIP_VALUE, cfg.NORM_TYPE)
def clip_grad_value(p: _GradientClipperInput):
torch.nn.utils.clip_grad_value_(p, cfg.CLIP_V... |
class _LazyAutoMapping(OrderedDict):
def __init__(self, config_mapping, model_mapping):
self._config_mapping = config_mapping
self._reverse_config_mapping = {v: k for (k, v) in config_mapping.items()}
self._model_mapping = model_mapping
self._extra_content = {}
self._modules ... |
_db
def test_slug_is_not_regenerated_when_changing_title(submission_factory):
submission = submission_factory(title=LazyI18nString({'en': 'hello', 'it': 'hell'}))
assert (submission.slug == 'hello')
submission.title = LazyI18nString({'en': 'ciao', 'it': 'cia'})
submission.save()
submission.refresh_f... |
def validate_entangler_map(entangler_map, num_qubits, allow_double_entanglement=False):
if isinstance(entangler_map, dict):
raise TypeError('The type of entangler map is changed to list of list.')
if (not isinstance(entangler_map, list)):
raise TypeError("Entangler map type 'list' expected")
... |
def _list_append_impl(ctx: CallContext) -> ImplReturn:
lst = replace_known_sequence_value(ctx.vars['self'])
element = ctx.vars['object']
if isinstance(lst, SequenceValue):
varname = ctx.visitor.varname_for_self_constraint(ctx.node)
if (varname is not None):
no_return_unless = Con... |
class DataAugmentation(object):
def __init__(self, data_search_path, image_suffix, label_suffix, **kwargs):
self.image_suffix = image_suffix
self.label_suffix = label_suffix
self.image_names = strsort(self._find_image_names(data_search_path))
self.kwargs = kwargs
self.affine_... |
class FixedCategorical(torch.distributions.Categorical):
def sample(self):
return super().sample().unsqueeze((- 1))
def log_probs(self, actions):
return super().log_prob(actions.squeeze((- 1))).view(actions.size(0), (- 1)).sum((- 1)).unsqueeze((- 1))
def mode(self):
return self.probs... |
def help():
parent_dir_of_this_file = os.path.dirname(__file__)
print(((os.path.basename(parent_dir_of_this_file) + ' : ') + __description__))
for module in order_of_module_execution:
library = importlib.import_module(((__package__ + '.') + module))
library.help()
del sys.modules[((_... |
def do_evaluation_atac_from_atac(spliced_net, sc_dual_full_dataset, gene_names: str, atac_names: str, outdir: str, ext: str, marker_genes: List[str], prefix: str=''):
logging.info('Inferring ATAC from ATAC')
sc_atac_full_preds = spliced_net.translate_2_to_2(sc_dual_full_dataset)
sc_atac_full_preds_anndata =... |
class TestMissinGenericParameters(TestNameCheckVisitorBase):
_passes()
def test(self):
from typing import List, Set, Dict
def capybara(x: list, y: List, z: List[int], a: Set[list], b: Dict[(str, list)]) -> set:
return {1}
_before((3, 9))
_passes()
def test_with_pep_585(se... |
class Relationships(Dict[(str, '_Relationship')]):
def __init__(self, baseURI: str):
super(Relationships, self).__init__()
self._baseURI = baseURI
self._target_parts_by_rId: Dict[(str, Any)] = {}
def add_relationship(self, reltype: str, target: (str | Any), rId: str, is_external: bool=Fa... |
class ZeroShotGenerator():
def __init__(self, info_prompt: PromptTemplate, model_name='gpt-4', **kwargs) -> None:
if (model_name in ['gpt-3.5-turbo', 'gpt-3.5-turbo-0613', 'gpt-4', 'gpt-4-0314', 'gpt-4-0613']):
self.chain = LLMChain(prompt=info_prompt, llm=ChatOpenAI(model_name=model_name, **kwa... |
class Loss(metrics.Loss):
def update(self, output: Dict) -> None:
tgt_len = output['tgt_len']
average_loss = self._loss_fn(output).detach()
if (len(average_loss.shape) != 0):
raise ValueError('loss_fn did not return the average loss.')
n = torch.sum(tgt_len)
self.... |
def test_dh_parameter_numbers_equality():
assert (dh.DHParameterNumbers(P_1536, 2) == dh.DHParameterNumbers(P_1536, 2))
assert (dh.DHParameterNumbers(P_1536, 7, 12345) == dh.DHParameterNumbers(P_1536, 7, 12345))
assert (dh.DHParameterNumbers((P_1536 + 2), 2) != dh.DHParameterNumbers(P_1536, 2))
assert (... |
class InitWeights_He(object):
def __init__(self, neg_slope=0.01):
self.neg_slope = neg_slope
def __call__(self, module):
if (isinstance(module, nn.Conv3d) or isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d) or isinstance(module, nn.ConvTranspose3d)):
module.wei... |
class DAQmx():
def __init__(self, name, *args, **kwargs):
super().__init__()
self.resourceName = name
self.numChannels = 0
self.numSamples = 0
self.dataBuffer = 0
self.taskHandleAI = TaskHandle(0)
self.taskHandleAO = TaskHandle(0)
self.terminated = Fal... |
def get_scores(task, mols):
model = models.get(task)
if (model is None):
if (task == 'chemprop_ecoli'):
model = chemprop_model(os.path.join(ROOT_DIR, 'chemprop_ckpt/ecoli'))
elif (task == 'chemprop_sars'):
model = chemprop_model(os.path.join(ROOT_DIR, 'chemprop_ckpt/sars_... |
def test_skip():
build_selector = BuildSelector(build_config='*', skip_config='pp36-* cp3?-manylinux_i686 cp36-win* *-win32')
assert (not build_selector('pp36-manylinux_x86_64'))
assert build_selector('pp37-manylinux_x86_64')
assert build_selector('pp38-manylinux_x86_64')
assert build_selector('pp37... |
class SimpleTransparencyPass(BasePass):
render_mask = 2
write_pick = False
def get_color_descriptors(self, blender):
(bf, bo) = (wgpu.BlendFactor, wgpu.BlendOperation)
return [{'format': blender.color_format, 'blend': {'alpha': (bf.one, bf.one_minus_src_alpha, bo.add), 'color': (bf.one, bf.o... |
def launch_experiments(variant_generator, args):
variants = variant_generator.variants()
variants = [unflatten(variant, separator='.') for variant in variants]
print('Launching seed={} experiment.'.format(args.seed))
variant = variants[(args.seed - 1)]
variant['lr'] = args.lr
variant['tau'] = ar... |
def sd_gen(ctx, queues):
global blocking
print(queues)
if (len(queues) > 0):
blocking = True
prompt = queues.pop(0)
mention = list(prompt.keys())[0]
prompt = list(prompt.values())[0]
filename = hashlib.sha256(prompt.encode('utf-8')).hexdigest()[:20]
if ('seed'... |
def main():
data_provider = daily_data_provider
benchmark_tms = data_provider.get_price(DummyTicker('AAA'), PriceField.Close, start_date, end_date)
strategy_tms = data_provider.get_price(DummyTicker('BBB'), PriceField.Close, start_date, end_date)
regression_chart = RegressionChart(benchmark_tms=benchmar... |
class TransformerAttentionModule(nn.Module):
def __init__(self, dim, num_heads, dropout, **kwargs):
super().__init__()
_check_dim_and_num_heads_consistency(dim, num_heads)
self.dim = dim
self.num_heads = num_heads
self.head_dim = (dim // num_heads)
self.attn_query = n... |
('/oauth/authorizeapp', methods=['POST'])
_auth_or_cookie
def authorize_application():
if (not get_authenticated_user()):
abort(401)
return
client_id = request.form.get('client_id', None)
whitelist = app.config.get('DIRECT_OAUTH_CLIENTID_WHITELIST', [])
if ((client_id not in whitelist) o... |
class SmilesRnnMoleculeGenerator():
def __init__(self, model: SmilesRnn, max_len: int, device: str) -> None:
self.device = device
self.model = model
lr = 0.001
self.optimizer = torch.optim.Adam(self.model.parameters(), lr=lr)
self.criterion = nn.CrossEntropyLoss()
sel... |
def test_enrichments_in_features_for():
vuln_report_filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vulnerabilityreport_withenrichments.json')
security_info_filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'securityinformation_withenrichments.json')
with open(vuln_rep... |
def gpu_init(vmin, Nv, dv, dxG, dxL, v0, da, na, S0, El, gamma_arr, iso, Mm_arr, Q_intp_list, verbose=0, backend='gpu-cuda'):
global gpu_mod
if (gpu_mod is not None):
warn('Only a single GPU context allowed; please call gpu_exit() first.')
return
if (backend == 'cpu-cuda'):
from radi... |
def _extract_episode_num(name):
debug(f'Extracting episode number from "{name}"')
if any(((ex.search(name) is not None) for ex in _excludors)):
return None
for regex in _num_extractors:
match = regex.match(name)
if (match is not None):
num = int(match.group(1))
... |
_fixtures(WebFixture, DynamicExampleFixture)
def test_example(web_fixture, dynamic_example_fixture):
fixture = dynamic_example_fixture
wsgi_application = web_fixture.new_wsgi_app(site_root=DynamicUI, enable_js=True)
web_fixture.reahl_server.set_app(wsgi_application)
browser = fixture.browser
browser... |
class GetDependenciesSuite(DataSuite):
files = find_test_files(pattern='deps*.test')
def run_case(self, testcase: DataDrivenTestCase) -> None:
src = '\n'.join(testcase.input)
dump_all = ('# __dump_all__' in src)
options = parse_options(src, testcase, incremental_step=1)
options.u... |
_module()
class GHMC(nn.Module):
def __init__(self, bins=10, momentum=0, use_sigmoid=True, loss_weight=1.0):
super(GHMC, self).__init__()
self.bins = bins
self.momentum = momentum
edges = (torch.arange((bins + 1)).float() / bins)
self.register_buffer('edges', edges)
s... |
class Effect1060(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Medium Projectile Turret')), 'falloff', ship.getModifiedItemAttr('eliteBonusHeavyGunship1'), skill='Heavy Assault Cruisers', **kwa... |
def resnet18(num_classes, loss='softmax', pretrained=True, **kwargs):
model = ResNet(num_classes=num_classes, loss=loss, block=BasicBlock, layers=[2, 2, 2, 2], last_stride=2, fc_dims=None, dropout_p=None, **kwargs)
if pretrained:
init_pretrained_weights(model, model_urls['resnet18'])
return model |
class OwlViTTextConfig(PretrainedConfig):
model_type = 'owlvit_text_model'
def __init__(self, vocab_size=49408, hidden_size=512, intermediate_size=2048, num_hidden_layers=12, num_attention_heads=8, max_position_embeddings=16, hidden_act='quick_gelu', layer_norm_eps=1e-05, attention_dropout=0.0, initializer_rang... |
def load_modules_from_path(path):
if (path[(- 1):] != '/'):
path += '/'
if (not os.path.exists(path)):
raise OSError(('Directory does not exist: %s' % path))
sys.path.append(path)
for f in os.listdir(path):
if ((len(f) > 3) and (f[(- 3):] == '.py')):
modname = f[:(- 3... |
_module()
class PascalContextDataset(CustomDataset):
CLASSES = ('background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'table', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor', 'bag', 'bed', 'bench', 'book', 'building', 'cabin... |
def _get_room_node(state: EnvironmentState, node: Node):
if (node.category == 'Rooms'):
return node
inside_nodes = state.get_nodes_from(node, Relation.INSIDE)
if (len(inside_nodes) > 1):
for n in state.get_nodes_from(node, Relation.INSIDE):
if (n.category == 'Rooms'):
... |
class Migration(migrations.Migration):
initial = True
dependencies = [('conferences', '0007_auto__1953')]
operations = [migrations.CreateModel(name='Page', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', model_utils.fields.AutoCreatedFie... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.