code stringlengths 281 23.7M |
|---|
def remove_trivial(types: Iterable[Type]) -> list[Type]:
removed_none = False
new_types = []
all_types = set()
for t in types:
p_t = get_proper_type(t)
if isinstance(p_t, UninhabitedType):
continue
if (isinstance(p_t, NoneType) and (not state.strict_optional)):
... |
def plot_overlap(logger, names=None):
names = (logger.names if (names == None) else names)
numbers = logger.numbers
for (_, name) in enumerate(names):
x = np.arange(len(numbers[name]))
plt.plot(x, np.asarray(numbers[name]))
return [(((logger.title + '(') + name) + ')') for name in names] |
class VecVideoRecorder(VecEnvWrapper):
def __init__(self, venv, directory, record_video_trigger, video_length=200):
VecEnvWrapper.__init__(self, venv)
self.record_video_trigger = record_video_trigger
self.video_recorder = None
self.directory = os.path.abspath(directory)
if (n... |
class Strength(object):
REQUIRED = None
STRONG_PREFERRED = None
PREFERRED = None
STRONG_DEFAULT = None
NORMAL = None
WEAK_DEFAULT = None
WEAKEST = None
def __init__(self, strength, name):
super(Strength, self).__init__()
self.strength = strength
self.name = name
... |
def assert_balance_proof(token_network_address: TokenNetworkAddress, app0: RaidenService, app1: RaidenService, saved_state0: SavedState, saved_state1: SavedState) -> None:
assert app0.wal
assert app1.wal
assert (app0.address == saved_state0.state.our_address)
assert (app1.address == saved_state1.state.o... |
class NColors():
RED = 1
GREEN = 2
YELLOW = 3
BLUE = 4
MAGENTA = 5
CYAN = 6
iRED = 7
iGREEN = 8
iYELLOW = 9
iBLUE = 10
iMAGENTA = 11
iCYAN = 12
def __init__(self, color_filter):
curses.init_pair(NColors.RED, (curses.COLOR_RED if (not color_filter) else curses.... |
def sync_grad(params):
if (not is_distributed()):
return
handles = []
for p in params:
if (p.grad is not None):
handle = torch.distributed.all_reduce(p.grad.data, op=torch.distributed.ReduceOp.SUM, async_op=True)
handles.append((p, handle))
for (p, handle) in hand... |
def align_eyes(landmarks, size):
desiredLeftEye = (0.35, 0.35)
desiredFaceWidth = desiredFaceHeight = size
(lStart, lEnd) = FACIAL_LANDMARKS_IDXS['left_eye']
(rStart, rEnd) = FACIAL_LANDMARKS_IDXS['right_eye']
leftEyePts = landmarks[lStart:lEnd]
rightEyePts = landmarks[rStart:rEnd]
leftEyeCe... |
_grad()
def update_bn_stats(model, data_loader, num_iters=200, logger=None):
model.train()
assert (len(data_loader) >= num_iters), f'length of dataloader {len(data_loader)} must be greater than iteration number {num_iters}'
if is_parallel_module(model):
parallel_module = model
model = model.... |
class DNSAddress(DNSRecord):
__slots__ = ('_hash', 'address', 'scope_id')
def __init__(self, name: str, type_: int, class_: int, ttl: int, address: bytes, scope_id: Optional[int]=None, created: Optional[float]=None) -> None:
super().__init__(name, type_, class_, ttl, created)
self.address = addr... |
def get_train_overlap(docs_by_task_set, ngrams_path, limit):
info_dict_path = os.path.join(ngrams_path, 'info.json')
info_dict = json.load(open(info_dict_path, 'r'))
ngrams_n_size = info_dict['ngram_size']
janitor = Janitor()
print('Building Lookups...')
start = time.perf_counter()
def get_o... |
def _get_nargs_pattern_wrapper(self: argparse.ArgumentParser, action: argparse.Action) -> str:
nargs_range = action.get_nargs_range()
if (nargs_range is not None):
if (nargs_range[1] == constants.INFINITY):
range_max = ''
else:
range_max = nargs_range[1]
nargs_pat... |
class LightSource(TutorialObject):
def at_init(self):
if self.db.is_giving_light:
self.delete()
def at_object_creation(self):
super().at_object_creation()
self.db.tutorial_info = 'This object can be lit to create light. It has a timeout for how long it burns.'
self.db... |
def test_do_class_cleanups_on_setupclass_failure(pytester: Pytester) -> None:
testpath = pytester.makepyfile('\n import unittest\n class MyTestCase(unittest.TestCase):\n values = []\n \n def setUpClass(cls):\n def cleanup():\n cls.valu... |
def create_stairs_split(bm, face, prop):
xyz = local_xyz(face)
size = Vector((prop.size_offset.size.x, prop.step_height))
h_height = (calc_face_dimensions(face)[1] / 2)
f = create_face(bm, size, (prop.size_offset.offset - Vector((0, (h_height - (prop.step_height * (prop.step_count + 0.5)))))), xyz)
... |
class RankingScorer():
def __init__(self, scorer: Scorer, ranking: Ranking):
self.scorer = scorer
self.ranking = ranking.tolist()
self.__provenance = Provenance()
print_message(f'#> Loaded ranking with {len(self.ranking)} qid--pid pairs!')
def provenance(self):
return sel... |
_processor('multi_hot_answer_from_vocab')
class MultiHotAnswerFromVocabProcessor(VQAAnswerProcessor):
def __init__(self, config, *args, **kwargs):
super().__init__(config, *args, **kwargs)
def compute_answers_scores(self, answers_indices):
scores = torch.zeros(self.get_vocab_size(), dtype=torch.... |
class TestNumericalQEOMESCCalculation(QiskitChemistryTestCase):
def setUp(self):
super().setUp()
aqua_globals.random_seed = 8
try:
self.driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.75', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g')
except QiskitChemistryEr... |
def test_step_not_match(sentence, expected_not_matching_step, steps):
step_to_print = (colorful.cyan(expected_not_matching_step) if expected_not_matching_step else 'ANY')
sys.stdout.write('{0} STEP "{1}" SHOULD NOT MATCH {2} '.format(colorful.yellow('>>'), colorful.cyan(sentence), step_to_print))
result ... |
def entry_point_move_plans_between_datasets():
parser = argparse.ArgumentParser()
parser.add_argument('-s', type=str, required=True, help='Source dataset name or id')
parser.add_argument('-t', type=str, required=True, help='Target dataset name or id')
parser.add_argument('-sp', type=str, required=True, ... |
class Conv2d(nn.Conv2d, RelProp):
def gradprop2(self, DY, weight):
Z = self.forward(self.X)
output_padding = (self.X.size()[2] - ((((Z.size()[2] - 1) * self.stride[0]) - (2 * self.padding[0])) + self.kernel_size[0]))
return F.conv_transpose2d(DY, weight, stride=self.stride, padding=self.padd... |
class GetCrtcInfo(rq.ReplyRequest):
_request = rq.Struct(rq.Card8('opcode'), rq.Opcode(20), rq.RequestLength(), rq.Card32('crtc'), rq.Card32('config_timestamp'))
_reply = rq.Struct(rq.ReplyCode(), rq.Card8('status'), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card32('timestamp'), rq.Int16('x'), rq.Int16... |
class YieldInfo():
yield_node: ast.Yield
statement_node: ast.stmt
lines: List[str]
line_range: List[int] = field(init=False)
def __post_init__(self) -> None:
self.line_range = get_line_range_for_node(self.statement_node, self.lines)
def is_assign_or_expr(self) -> bool:
if (not is... |
def test_make_vdom_constructor():
elmt = make_vdom_constructor('some-tag')
assert (elmt({'data': 1}, [elmt()]) == {'tagName': 'some-tag', 'children': [{'tagName': 'some-tag'}], 'attributes': {'data': 1}})
no_children = make_vdom_constructor('no-children', allow_children=False)
with pytest.raises(TypeErr... |
class SerialAdapter(Adapter):
def __init__(self, port, preprocess_reply=None, write_termination='', read_termination='', **kwargs):
super().__init__(preprocess_reply=preprocess_reply)
if isinstance(port, serial.SerialBase):
self.connection = port
else:
self.connection... |
def get_criteo_dataset(params):
name = params['dataset']
print('loading datasest {}'.format(name))
cache_path = os.path.join(params['data_cache_path'], '{}.pkl'.format(name))
if ((params['data_cache_path'] != 'None') and os.path.isfile(cache_path)):
print('cache_path {}'.format(cache_path))
... |
class ServiceBrowser(_ServiceBrowserBase, threading.Thread):
def __init__(self, zc: 'Zeroconf', type_: Union[(str, list)], handlers: Optional[Union[(ServiceListener, List[Callable[(..., None)]])]]=None, listener: Optional[ServiceListener]=None, addr: Optional[str]=None, port: int=_MDNS_PORT, delay: int=_BROWSER_TIM... |
_torch
_vision
class VideoMAEImageProcessingTest(ImageProcessingSavingTestMixin, unittest.TestCase):
image_processing_class = (VideoMAEImageProcessor if is_vision_available() else None)
def setUp(self):
self.image_processor_tester = VideoMAEImageProcessingTester(self)
def image_processor_dict(self):... |
def backward(x0, sc, c, phi, theta, psi, orientation, sigma_c, sigma_l, sigma_d, t1, bm):
angles = (phi[x0], theta[x0], psi[x0])
sc_curr = GR.rotate(sc, angle=angles, default_val=0.0)
x0_loc = convert(np.where((sc_curr == sc_curr.min())))
sc_mask = (sc_curr > 0)
search_result = np.full(sc_mask.shape... |
class SendVideoNote():
async def send_video_note(self: 'pyrogram.Client', chat_id: Union[(int, str)], video_note: Union[(str, BinaryIO)], duration: int=0, length: int=1, thumb: Union[(str, BinaryIO)]=None, disable_notification: bool=None, reply_to_message_id: int=None, schedule_date: datetime=None, protect_content:... |
def createHTMLDeviceSummary(testruns, htmlfile, title):
html = summaryCSS('Device Summary - SleepGraph', False)
devall = dict()
for data in testruns:
(host, url, devlist) = (data['host'], data['url'], data['devlist'])
for type in devlist:
if (type not in devall):
... |
_model
def convformer_b36_in21k(pretrained=False, **kwargs):
model = MetaFormer(depths=[3, 12, 18, 3], dims=[128, 256, 512, 768], token_mixers=SepConv, head_fn=MlpHead, **kwargs)
model.default_cfg = default_cfgs['convformer_b36_in21k']
if pretrained:
state_dict = torch.hub.load_state_dict_from_url(u... |
def are_typed_dicts_overlapping(left: TypedDictType, right: TypedDictType, *, ignore_promotions: bool=False, prohibit_none_typevar_overlap: bool=False) -> bool:
for key in left.required_keys:
if (key not in right.items):
return False
if (not is_overlapping_types(left.items[key], right.it... |
def unevaluatedItems_draft2019(validator, unevaluatedItems, instance, schema):
if (not validator.is_type(instance, 'array')):
return
evaluated_item_indexes = find_evaluated_item_indexes_by_schema(validator, instance, schema)
unevaluated_items = [item for (index, item) in enumerate(instance) if (inde... |
def get_precision_at_k(args, preds_path, gold_data_path):
k = args.k
hypos = [line.strip() for line in open(preds_path, 'r').readlines()]
references = [line.strip() for line in open(gold_data_path, 'r').readlines()]
em = total = 0
for (hypo, reference) in zip(hypos, references):
hypo_provena... |
_bp.route('/images/<image_id>/checksum', methods=['PUT'])
_auth
_namespace_repo_from_session
_v1_push_enabled()
_namespace_enabled
_repository_state
_protect
_readonly
def put_image_checksum(namespace, repository, image_id):
logger.debug('Checking repo permissions')
permission = ModifyRepositoryPermission(names... |
def remove_old_tests(client: APIClient):
try:
client.remove_container(container='freshenv_system_test', force=True)
client.remove_image(image=freshenv_test_image, force=True)
print(':heavy_check_mark: Test images removed.')
except errors.APIError as e:
if (e.status_code == 404):
... |
def getDefaultHeatTransferSolverSettings():
return {'parallel': False, 'compressible': False, 'nonNewtonian': False, 'transonic': False, 'porous': False, 'dynamicMeshing': False, 'buoyant': True, 'gravity': (0, (- 9.81), 0), 'transient': False, 'turbulenceModel': 'kEpsilon', 'potentialInit': False, 'heatTransfering... |
class TestNfsCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('NfsCollector', {'interval': 1})
self.collector = NfsCollector(config, None)
def test_import(self):
self.assertTrue(NfsCollector)
('__builtin__.open')
('os.access', Mock(return_value=True))
... |
class STM32F4xxRccV2(STM32F4xxRcc):
class Type(ctypes.Structure):
_fields_ = [('CR', ctypes.c_uint32), ('PLLCFGR', ctypes.c_uint32), ('CFGR', ctypes.c_uint32), ('CIR', ctypes.c_uint32), ('AHB1RSTR', ctypes.c_uint32), ('AHB2RSTR', ctypes.c_uint32), ('AHB3RSTR', ctypes.c_uint32), ('RESERVED0', ctypes.c_uint32... |
class net():
def __init__(self, X_train, y_train, n_hidden, n_epochs=40, normalize=False, tau=1.0, dropout=0.05):
if normalize:
self.std_X_train = np.std(X_train, 0)
self.std_X_train[(self.std_X_train == 0)] = 1
self.mean_X_train = np.mean(X_train, 0)
else:
... |
def test_direct_junction_minimum_connection_suc_pred(direct_junction_both_lane_fixture):
(main_road, small_road, junction_creator) = direct_junction_both_lane_fixture
main_road.add_successor(xodr.ElementType.junction, junction_creator.id)
small_road.add_predecessor(xodr.ElementType.junction, junction_creato... |
.parametrize('repo_name, extended_repo_names, expected_status', [pytest.param(('x' * 255), False, 201, id='Maximum allowed length'), pytest.param(('x' * 255), True, 201, id='Maximum allowed length'), pytest.param(('x' * 256), False, 400, id='Over allowed length'), pytest.param(('x' * 256), True, 400, id='Over allowed l... |
def recv_param(learner_ip, actor_id, param_queue):
ctx = zmq.Context()
param_socket = ctx.socket(zmq.SUB)
param_socket.setsockopt(zmq.SUBSCRIBE, b'')
param_socket.setsockopt(zmq.CONFLATE, 1)
connect_param_socket(ctx, param_socket, learner_ip, actor_id)
while True:
data = param_socket.rec... |
def test_030_parseTime_legal():
report = Metar.Metar('KEWR 101651Z')
assert report.decode_completed
assert (report.time.day == 10)
assert (report.time.hour == 16)
assert (report.time.minute == 51)
if ((today.day > 10) or ((today.hour > 16) and (today.day == 10))):
assert (report.time.mon... |
class ResNet50bn(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, config='... |
def test_quant_scheme_percentile():
if (version.parse(tf.version.VERSION) >= version.parse('2.00')):
model = dense_functional()
qsim = QuantizationSimModel(model, quant_scheme=QuantScheme.post_training_tf, default_param_bw=16, default_output_bw=16)
(_, _, output_quantizers) = qsim._get_quant... |
def execute_benchmark(config: Config):
args = config.args
if (args.multiprocessing_method == 'forkserver'):
import multiprocessing.forkserver as f
f.ensure_running()
with dask.config.set({'distributed.worker.multiprocessing-method': args.multiprocessing_method}):
if ((args.scheduler_... |
def gamma_dicom(dicom_dataset_ref, dicom_dataset_eval, dose_percent_threshold, distance_mm_threshold, **kwargs):
(axes_reference, dose_reference) = zyx_and_dose_from_dataset(dicom_dataset_ref)
(axes_evaluation, dose_evaluation) = zyx_and_dose_from_dataset(dicom_dataset_eval)
gamma = gamma_shell(axes_referen... |
def _get_code_for_demoing_a_gate(gate_func: Callable, vertical: bool) -> str:
(lines, obj_expression) = _get_lines_for_constructing_an_object(gate_func)
vert_str = ''
if vertical:
vert_str = ', vertical=True'
return _GATE_DISPLAY.format(lines='\n'.join(lines), obj_expression=obj_expression, vert... |
class AttrVI_ATTR_USB_CLASS(RangeAttribute):
resources = [(constants.InterfaceType.usb, 'RAW')]
py_name = ''
visa_name = 'VI_ATTR_USB_CLASS'
visa_type = 'ViInt16'
default = NotAvailable
(read, write, local) = (True, False, False)
(min_value, max_value, values) = (0, 255, None) |
def delimited_list(expr: Union[(str, ParserElement)], delim: Union[(str, ParserElement)]=',', combine: bool=False, min: typing.Optional[int]=None, max: typing.Optional[int]=None, *, allow_trailing_delim: bool=False) -> ParserElement:
return DelimitedList(expr, delim, combine, min, max, allow_trailing_delim=allow_tr... |
def nonempty_intersection_answer_by_order(sets):
answer = [frozenset((sets.index(x) for x in combination)) for combination in utils.powerset(sets, nonempty=True, max_size=None) if ((len(combination) >= 2) and frozenset.intersection(*combination))]
return {i: set((x for x in answer if (len(x) == i))) for i in se... |
class ScheduleItem():
id: strawberry.ID
conference: Annotated[('Conference', strawberry.lazy('api.conferences.types'))]
title: str
start: datetime
end: datetime
status: str
submission: Optional[Submission]
slug: str
description: str
type: str
duration: Optional[int]
highl... |
class HelloGLWidget(QOpenGLWidget):
xRotationChanged = pyqtSignal(int)
yRotationChanged = pyqtSignal(int)
zRotationChanged = pyqtSignal(int)
def __init__(self, parent=None):
super(HelloGLWidget, self).__init__(parent)
self.object = 0
self.xRot = 0
self.yRot = 0
se... |
class SawyerReachWallV2Policy(Policy):
def _parse_obs(obs):
return {'hand_pos': obs[:3], 'unused_1': obs[3], 'puck_pos': obs[4:7], 'unused_2': obs[7:(- 3)], 'goal_pos': obs[(- 3):]}
def get_action(self, obs):
o_d = self._parse_obs(obs)
action = Action({'delta_pos': np.arange(3), 'grab_ef... |
def test_biorbd_model_import():
from bioptim.examples.getting_started import pendulum as ocp_module
bioptim_folder = os.path.dirname(ocp_module.__file__)
model_path = '/models/pendulum.bioMod'
BiorbdModel((bioptim_folder + model_path))
BiorbdModel(biorbd.Model((bioptim_folder + model_path)))
wit... |
class TerminusSendStringCommand(TerminusFindTerminalMixin, sublime_plugin.WindowCommand):
def run(self, string, tag=None, visible_only=False, bracketed=False):
terminal = self.find_terminal(self.window, tag=tag, visible_only=visible_only)
if (not terminal):
raise Exception('no terminal f... |
class Logger(logging.Logger):
NAME = 'SingletonLogger'
def get(cls, file_path=None, level='INFO', colorize=True, track_code=False):
logging.setLoggerClass(cls)
logger = logging.getLogger(cls.NAME)
logging.setLoggerClass(logging.Logger)
logger.setLevel(level)
if logger.has... |
def activate(locale: str, path: (str | None)=None) -> gettext_module.NullTranslations:
if (path is None):
path = _get_default_locale_path()
if (path is None):
msg = "Humanize cannot determinate the default location of the 'locale' folder. You need to pass the path explicitly."
raise Exce... |
class BITMAPV5HEADER(Structure):
_fields_ = [('bV5Size', DWORD), ('bV5Width', LONG), ('bV5Height', LONG), ('bV5Planes', WORD), ('bV5BitCount', WORD), ('bV5Compression', DWORD), ('bV5SizeImage', DWORD), ('bV5XPelsPerMeter', LONG), ('bV5YPelsPerMeter', LONG), ('bV5ClrUsed', DWORD), ('bV5ClrImportant', DWORD), ('bV5Re... |
def get_payee_channel(channelidentifiers_to_channels: Dict[(ChannelID, NettingChannelState)], transfer_pair: MediationPairState) -> Optional[NettingChannelState]:
payee_channel_identifier = transfer_pair.payee_transfer.balance_proof.channel_identifier
return channelidentifiers_to_channels.get(payee_channel_iden... |
class MethodRenamedBase():
def run_method(method: Callable, old: Union[(dict, str)], new: Union[(dict, str)], required: Union[(List[str], str, dict)]=None):
if (required is None):
required = {}
if isinstance(required, str):
required = [required]
if isinstance(required... |
def test_input_toggling_lambda_condition(qtbot):
class TestProcedure(Procedure):
toggle_par = IntegerParameter('toggle', default=100)
x = Parameter('X', default='value', group_by='toggle_par', group_condition=(lambda v: (50 < v < 90)))
wdg = InputsWidget(TestProcedure, inputs=('toggle_par', 'x')... |
class CIFAR10Policy(object):
def __init__(self, fillcolor=(128, 128, 128)):
self.policies = [SubPolicy(0.1, 'invert', 7, 0.2, 'contrast', 6, fillcolor), SubPolicy(0.7, 'rotate', 2, 0.3, 'translateX', 9, fillcolor), SubPolicy(0.8, 'sharpness', 1, 0.9, 'sharpness', 3, fillcolor), SubPolicy(0.5, 'shearY', 8, 0... |
class BartTokenizerFast(PreTrainedTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
model_input_names = ['input_ids', 'attention_mask']
slow_tokenizer_class = BartTokenizer
... |
class Latexify():
def __init__(self, model, filename=None, newline=True):
self.model = model
self.filename = filename
self.newline = newline
def _get_geometry_displays(self, var):
geo = []
if (not var.domain):
return geo
rng_min = None
rng_max ... |
class HIDBS1(FinTS3Segment):
account = DataElementGroupField(type=KTI1, _d='Kontoverbindung international')
sepa_descriptor = DataElementField(type='an', max_length=256, _d='SEPA Descriptor')
sepa_pain_message = DataElementField(type='bin', _d='SEPA pain message')
task_id = DataElementField(type='an', m... |
def update_view_markers(view=None):
if (view is None):
view = sublime.active_window().active_view()
fn = view.file_name()
if (fn is not None):
fn = normalize(fn)
pos_scope = get_setting('position_scope', 'entity.name.class')
pos_icon = get_setting('position_icon', 'bookmark')
cur... |
def test_zip_file_object_read(path_zip_file):
with open(path_zip_file, 'rb') as zip_file_object:
with ZipMemoryFile(zip_file_object) as zipmemfile:
with zipmemfile.open('white-gemini-iv.vrt') as src:
assert (src.driver == 'VRT')
assert (src.count == 3)
... |
class Latency(commands.Cog):
def __init__(self, bot: Bot) -> None:
self.bot = bot
()
_whitelist(channels=(Channels.bot_commands,), roles=STAFF_PARTNERS_COMMUNITY_ROLES)
async def ping(self, ctx: commands.Context) -> None:
bot_ping = ((arrow.utcnow() - ctx.message.created_at).total_second... |
def get_markdown_docstring_lines(cls: Type) -> List[str]:
config = Config()
docstring = (cls.__doc__ if cls.__doc__ else '')
gds = _GoogleDocstringToMarkdown(inspect.cleandoc(docstring), config=config, what='class')
lines = ([f'## `{cls.__name__}`'] + gds.lines())
lines = [re.sub(':py:func:`(\\w+)`'... |
class MetafileLister(ScriptBase):
ARGS_HELP = '<metafile>...'
def add_options(self):
self.add_bool_option('--reveal', help='show full announce URL including keys')
self.add_bool_option('--raw', help="print the metafile's raw content in all detail")
self.add_bool_option('--json', help='pr... |
def _imagenet32(split: str) -> Dataset:
dataset_path = os.path.join(os.getenv('PT_DATA_DIR', 'datasets'), 'Imagenet32')
if (split == 'train'):
return ImageNetDS(dataset_path, 32, train=True, transform=transforms.Compose([transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms... |
class TriviallyDoubleCommutesDualBasisTest(unittest.TestCase):
def test_trivially_double_commutes_no_intersection(self):
self.assertTrue(trivially_double_commutes_dual_basis(FermionOperator('3^ 4'), FermionOperator('3^ 2^ 3 2'), FermionOperator('4^ 1')))
def test_no_trivial_double_commute_with_intersect... |
def stream_run(params):
(train_stream, test_stream) = get_criteo_dataset_stream(params)
if (params['method'] == 'DFM'):
model = get_model('MLP_EXP_DELAY', params)
model.load_weights(params['pretrain_dfm_model_ckpt_path'])
else:
model = get_model('MLP_SIG', params)
model.load_... |
('/reservations/{reservation_number}', status_code=status.HTTP_200_OK, responses={status.HTTP_200_OK: {'model': ReservationResponse}, status.HTTP_404_NOT_FOUND: {'model': BaseResponse}})
def get_reservation(reservation_number: str, reservation_query: ReservationQueryUseCase=Depends(Provide[AppContainer.reception.reserv... |
def infer_numpy_ndarray(node, context: (InferenceContext | None)=None):
ndarray = '\n class ndarray(object):\n def __init__(self, shape, dtype=float, buffer=None, offset=0,\n strides=None, order=None):\n self.T = numpy.ndarray([0, 0])\n self.base = None\n ... |
class TestStatCall(unittest.TestCase):
def test_stat_call(self):
expected = 'Samples read: 627456\nLength (seconds): 14.228027\nScaled by: .0\nMaximum amplitude: 0.010895\nMinimum amplitude: -0.004883\nMidline amplitude: 0.003006\nMean norm: 0.000137\nMean am... |
def test_creating_simple_scenario():
scenario = Scenario(1, 'Scenario', 'I am a Scenario', 'foo.feature', 1, parent=None, tags=None, preconditions=None, background=None)
assert (scenario.id == 1)
assert (scenario.keyword == 'Scenario')
assert (scenario.sentence == 'I am a Scenario')
assert (scenario... |
def user_action_for_spam(user, threshold):
total_spam = ProposalComment.objects.filter(commenter=user, is_spam=True).count()
if (total_spam >= threshold):
if (user.is_active is True):
user.is_active = False
user.save()
elif (user.is_active is False):
user.is_active = ... |
def download_from_google(token_id, filename):
print(('Downloading %s ...' % os.path.basename(filename)))
url = '
destination = (filename + '.tar.gz')
session = requests.Session()
response = session.get(url, params={'id': token_id, 'confirm': 't'}, stream=True)
token = get_confirm_token(response)... |
class RCC_APB2LPENR(IntEnum):
TIM1LPEN = (1 << 0)
USART1LPEN = (1 << 4)
USART6LPEN = (1 << 5)
ADC1LPEN = (1 << 8)
SDIOLPEN = (1 << 11)
SPI1LPEN = (1 << 12)
SPI4LPEN = (1 << 13)
SYSCFGLPEN = (1 << 14)
TIM9LPEN = (1 << 16)
TIM10LPEN = (1 << 17)
TIM11LPEN = (1 << 18)
SPI5LPE... |
def override_services(config, override_services):
if (override_services == []):
return
for service in list(config.keys()):
if ((service + '=true') in override_services):
config[service]['autostart'] = 'true'
elif ((service + '=false') in override_services):
config... |
class GreetExecutor(ActionExecutor):
def execute(self, script: Script, state: EnvironmentState, info: ExecutionInfo, char_index, modify=True, in_place=False):
current_line = script[0]
info.set_current_line(current_line)
node = state.get_state_node(current_line.object())
if (node is N... |
class Logger():
def __init__(self):
self.log_file_open = None
self.log_file_local = None
self.verbosity = self.term_verbosity = int(os.getenv('RDIFF_BACKUP_VERBOSITY', '3'))
self.termverbset = None
def __call__(self, message, verbosity):
if ((verbosity > self.verbosity) a... |
_grad()
def evaluate(parts):
model.eval()
metrics = {}
predictions = {}
for part in parts:
predictions[part] = torch.cat([model((None if (X_num is None) else X_num[part][idx]), (None if (X_cat is None) else X_cat[part][idx])) for idx in lib.IndexLoader(D.size(part), args['training']['eval_batch_... |
def downsample_mask(mask, max_n, seed=0):
train_mask = mask
if ((max_n is not None) and (np.sum(train_mask) > max_n)):
n_train = int(max_n)
curr_train_idxs = np.nonzero(train_mask)[0]
rng = np.random.default_rng(seed=seed)
train_idxs_idx = rng.choice(len(curr_train_idxs), size=n_... |
def createDelexData():
loadData()
dic = delexicalize.prepareSlotValuesIndependent()
fin1 = file('data/multi-woz/data.json')
data = json.load(fin1)
fin2 = file('data/multi-woz/dialogue_acts.json')
data2 = json.load(fin2)
for dialogue_name in tqdm(data):
dialogue = data[dialogue_name]
... |
.parametrize('env', ((), ('TOX_ENV_DIR', '/tox_env_dir')))
def test_cache_reportheader(env, pytester: Pytester, monkeypatch: MonkeyPatch) -> None:
pytester.makepyfile('def test_foo(): pass')
if env:
monkeypatch.setenv(*env)
expected = os.path.join(env[1], '.pytest_cache')
else:
monke... |
def apply_regularization(regularizer, weights_list=None):
if (not weights_list):
weights_list = ops.get_collection(ops.GraphKeys.WEIGHTS)
if (not weights_list):
raise ValueError('No weights to regularize.')
with ops.name_scope('get_regularization_penalty', values=weights_list) as scope:
... |
class Block(nn.Module):
def __init__(self, seq_len, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm, downsample=None, **kwargs):
super().__init__()
self.norm1 = norm_layer(dim)
self.downsample = ... |
def run(args=None):
logger = setup_custom_logger('beaver', args)
beaver_config = BeaverConfig(args, logger=logger)
logger = setup_custom_logger('beaver', args, config=beaver_config)
if (beaver_config.get('logstash_version') not in [0, 1]):
raise LookupError('Invalid logstash_version')
queue ... |
def tor_reconnect(self):
if self.using_tor:
try:
self.tor_controller.signal(Signal.NEWNYM)
self.logger.info('New Tor connection processing')
time.sleep(self.tor_delay)
except (InvalidArguments, ProtocolError):
self.logger.error("couldn't establish new ... |
def get_cmdclass(cmdclass=None):
if ('versioneer' in sys.modules):
del sys.modules['versioneer']
cmds = ({} if (cmdclass is None) else cmdclass.copy())
from setuptools import Command
class cmd_version(Command):
description = 'report generated version string'
user_options = []
... |
def _runner(init, shape, target_mean=None, target_std=None, target_max=None, target_min=None):
variable = K.variable(init(shape))
output = K.get_value(variable)
lim = 0.03
if (target_std is not None):
assert (abs((output.std() - target_std)) < lim)
if (target_mean is not None):
asser... |
def _init_weights(module, name, zero_init_last=False):
if isinstance(module, nn.Conv2d):
nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu')
if (module.bias is not None):
nn.init.zeros_(module.bias)
elif isinstance(module, nn.Linear):
nn.init.normal_(m... |
.parametrize('username,password', users)
.parametrize('project_id', projects)
.parametrize('snapshot_id', snapshots)
def test_snapshot_rollback_get(db, client, username, password, project_id, snapshot_id):
client.login(username=username, password=password)
project = Project.objects.get(pk=project_id)
projec... |
def convert_standalone_batchnorms(model: tf.keras.Model, folded_bns: set) -> List[tf.keras.layers.BatchNormalization]:
bn_converted = []
for layer in model.layers:
if (isinstance(layer, tf.keras.layers.BatchNormalization) and (layer not in folded_bns)):
convert_batchnorm_parameters(layer)
... |
class OpenCLSSASimulator(SSABase):
_supports = {'multi_initials': True, 'multi_param_values': True}
def __init__(self, model, verbose=False, tspan=None, precision=np.float64, **kwargs):
if (cl is None):
raise ImportError('pyopencl library required for {}'.format(self.__class__.__name__))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.