code stringlengths 281 23.7M |
|---|
class Session(object):
def __init__(self):
self._headers = HEADERS
self._session = requests.sessions.Session()
def _set_auth_headers(self, access_token=''):
self._headers['Authorization'] = 'Bearer {}'.format(access_token)
def _get(self, url):
return self._session.get(url, he... |
def test_TVRegDiff():
n = 800
x = np.linspace((- 10), 10, n)
print(np.std(x))
np.random.seed(1)
noise = (np.random.normal(0, np.std(x), x.shape) * 0.05)
y_clean = np.sin(x)
y_grad = np.cos(x)
y_noise = (y_clean + noise)
dx = (x[1] - x[0])
width = 60
fig = plt.figure(figsize=(... |
class TestDistributedTimeoutWrapper(unittest.TestCase):
def setUp(self):
logging.disable(logging.CRITICAL)
def tearDown(self):
logging.disable(logging.NOTSET)
def test_no_timeout(self):
module = DistributedTimeoutWrapper(ModuleWithDelay(1), 0, signal.SIGINT)
module(torch.rand... |
class CommaSeparatedUUIDField(Field):
version = LooseVersion('2.4')
def deserialize(self, value):
if (not value):
return DirtyableList([])
if hasattr(value, 'split'):
value = value.split(',')
return DirtyableList([uuid.UUID(v) for v in value])
def serialize(se... |
class TestTransportMode():
.parametrize(['enum_member', 'enum_name', 'java_type'], [(r5py.TransportMode.AIR, 'AIR', com.conveyal.r5.api.util.TransitModes), (r5py.TransportMode.BUS, 'BUS', com.conveyal.r5.api.util.TransitModes), (r5py.TransportMode.CABLE_CAR, 'CABLE_CAR', com.conveyal.r5.api.util.TransitModes), (r5p... |
_criterion('label_smoothed_cross_entropy')
class LabelSmoothedCrossEntropyCriterion(FairseqCriterion):
def __init__(self, args, task):
super().__init__(args, task)
self.eps = args.label_smoothing
def add_args(parser):
parser.add_argument('--label-smoothing', default=0.0, type=float, meta... |
class LKA_Attention3d(nn.Module):
def __init__(self, d_model):
super().__init__()
self.proj_1 = nn.Conv3d(d_model, d_model, 1)
self.activation = nn.GELU()
self.spatial_gating_unit = LKA3d(d_model)
self.proj_2 = nn.Conv3d(d_model, d_model, 1)
def forward(self, x):
... |
class CortexMBitband(QlPeripheral):
def __init__(self, ql, label, base, size):
super().__init__(ql, label)
self.bitband_base = base
self.bitband_size = (size * 32)
def _bitband_addr(self, offset):
return (self.bitband_base | ((offset & ) >> 5))
def region(self):
retur... |
.parametrize('package_name', ['pycowsay', 'pycowsay==0.0.0.2', 'pycowsay>=0.0.0.2'])
('os.execvpe', new=execvpe_mock)
def test_simple_run(pipx_temp_env, monkeypatch, capsys, package_name):
run_pipx_cli_exit(['run', package_name, '--help'])
captured = capsys.readouterr()
assert ('Download the latest version ... |
class TransformerEncoderLayer(nn.Module):
def __init__(self, args):
super().__init__()
self.embed_dim = args.encoder_embed_dim
self.quant_noise = getattr(args, 'quant_noise_pq', 0)
self.quant_noise_block_size = getattr(args, 'quant_noise_pq_block_size', 8)
self.self_attn = se... |
class Assign(_base_nodes.AssignTypeNode, _base_nodes.Statement):
targets: list[NodeNG]
value: NodeNG
type_annotation: (NodeNG | None)
_astroid_fields = ('targets', 'value')
_other_other_fields = ('type_annotation',)
def postinit(self, targets: list[NodeNG], value: NodeNG, type_annotation: (NodeN... |
def test_low_sun_angles():
result = tracking.singleaxis(apparent_zenith=80, apparent_azimuth=338, axis_tilt=30, axis_azimuth=180, max_angle=60, backtrack=True, gcr=0.35)
expected = {'tracker_theta': np.array([60.0]), 'aoi': np.array([80.420987]), 'surface_azimuth': np.array([253.897886]), 'surface_tilt': np.arr... |
.parametrize('klass', (ShmemVecEnv, SubprocVecEnv))
.parametrize('dtype', ('uint8', 'float32'))
def test_vec_env(klass, dtype):
num_envs = 3
num_steps = 100
shape = (3, 8)
def make_fn(seed):
return (lambda : SimpleEnv(seed, shape, dtype))
fns = [make_fn(i) for i in range(num_envs)]
env1 ... |
class Resize(object):
def __init__(self, size, interpolation=Image.BILINEAR):
assert (isinstance(size, int) or (isinstance(size, Iterable) and (len(size) == 2)))
self.size = size
self.interpolation = interpolation
def __call__(self, img_list):
return [F.resize(img, self.size, sel... |
.parametrize('func', [(lambda df: df.query('x > 1 and x < 4', engine='python')), (lambda df: df.x.value_counts().nlargest(2))])
def test_dataframe_simple(func):
df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
expected = func(df)
a = DataFrame(example=df)
L = func(a).stream.sink_to_list()
a.emit(... |
class MessageLogModelTest(RapidTest):
def setUp(self):
self.contact = self.create_contact()
self.connection = self.lookup_connections([''])[0]
self.connection.contact = self.contact
self.data = {'contact': self.contact, 'connection': self.connection, 'direction': Message.INCOMING, 'd... |
def recursively_load_weights_wav2vec2(fairseq_model, hf_model):
unused_weights = []
fairseq_dict = fairseq_model.state_dict()
feature_extractor = hf_model.feature_extractor
adapter = hf_model.adapter
for (name, value) in fairseq_dict.items():
is_used = False
if ('conv_layers' in name... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--device', action='store', type=str, default='cuda')
parser.add_argument('--seed', type=int, default=1234, metavar='N', help='random seed (default: 1234)')
parser.add_argument('--evaluate', action='store', type=bool, default=True)... |
def test_inbound_shipment_item_from_plan_constructor(create_inbound_shipment_plan_dummy_response):
resp_parsed = create_inbound_shipment_plan_dummy_response.parsed
item = resp_parsed.InboundShipmentPlans.member.Items.member
item_model_1 = InboundShipmentItem.from_plan_item(item)
assert (item_model_1.sku... |
class Timezone_TestCase(unittest.TestCase):
def runTest(self):
for cmd_class in [FC6_Timezone, F25_Timezone, RHEL7_Timezone]:
cmd = cmd_class()
op = cmd._getParser()
for action in op._actions:
if ('--isUtc' in action.option_strings):
se... |
class Dict(TokenConverter):
def __init__(self, expr):
super().__init__(expr)
self.saveAsList = True
def postParse(self, instring, loc, tokenlist):
for (i, tok) in enumerate(tokenlist):
if (len(tok) == 0):
continue
ikey = tok[0]
if isins... |
def repo_with_git_flow_and_release_channels_angular_commits_using_tag_format(git_repo_factory, file_in_repo):
git_repo = git_repo_factory()
add_text_to_file(git_repo, file_in_repo)
git_repo.git.commit(m='Initial commit')
add_text_to_file(git_repo, file_in_repo)
git_repo.git.commit(m=COMMIT_MESSAGE.f... |
def test_resnet3d_layer():
with pytest.raises(AssertionError):
ResNet3dLayer(22, None)
with pytest.raises(AssertionError):
ResNet3dLayer(50, None, stage=4)
res_layer = ResNet3dLayer(50, None, stage=3, norm_eval=True)
res_layer.init_weights()
res_layer.train()
input_shape = (1, 10... |
class StochasticConvMLP(nn.Module):
def __init__(self, arch, in_dim):
super().__init__()
self.arch = arch
self.z_sz = arch[2]
layers = [nn.Conv2d(arch[0], arch[1], kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Flatten(start_dim=1), nn.Linear((arch[1]... |
def rotate_random_angle(game):
sample_angle = random.randint(0, 359)
player_angle = game.get_game_variable(vzd.GameVariable.ANGLE)
smallest_diff = util.get_angle_diff(player_angle, sample_angle)
while (abs(smallest_diff) > 5):
game.make_action([(- smallest_diff), 0])
player_angle = game.... |
def test_connections(rpaths):
conn_len = len(Globals.connections)
if (conn_len == 1):
log.Log('No remote connections specified, only local one available', log.ERROR)
return Globals.RET_CODE_FILE_ERR
elif (conn_len != (len(rpaths) + 1)):
print("All {pa} parameters must be remote of th... |
class Effect4216(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Energy Nosferatu')), 'powerTransferAmount', src.getModifiedItemAttr('subsystemBonusAmarrCore2'), skill='Amarr Core Systems', **kwa... |
class BaseDataset(object):
def __init__(self, type: str, name: str, device: str='cpu'):
self.type = type
self.name = name
self.device = device
if (self.type in ['cocitation', 'coauthorship']):
self.dataset_dir = osp.join('dataset', self.type, self.name)
else:
... |
class TestFileSelectionDefaults():
def test_include(self, isolation):
builder = MockBuilder(str(isolation))
assert (builder.config.default_include() == [])
def test_exclude(self, isolation):
builder = MockBuilder(str(isolation))
assert (builder.config.default_exclude() == [])
... |
class BatchNormalization(Layer):
_batchnorm_support
def __init__(self, axis=(- 1), momentum=0.99, epsilon=0.001, center=True, scale=True, beta_initializer='zeros', gamma_initializer='ones', moving_mean_initializer='zeros', moving_variance_initializer='ones', beta_regularizer=None, gamma_regularizer=None, beta_c... |
class StatisticsVisitor(TraverserVisitor):
def __init__(self, inferred: bool, filename: str, modules: dict[(str, MypyFile)], typemap: (dict[(Expression, Type)] | None)=None, all_nodes: bool=False, visit_untyped_defs: bool=True) -> None:
self.inferred = inferred
self.filename = filename
self.... |
('iM_product_vect_batch')
def _iM_product_vect_batch(args, axes):
((q, vect), size_batch) = check_batch_inputs(args, axes)
if (len(q.shape) <= 2):
return (_iM_product_vect_prim.bind(q, vect), 0)
for i in range(size_batch):
mCompute = _iM_product_vect_prim.bind(q[i], vect[i])[None]
ba... |
class ProtocolClient(Protocol):
_req_sent = None
def __init__(self, request_queue, response_queue):
self.request_queue = request_queue
self.response_queue = response_queue
self._req_sent = None
def can_take_request(self):
return (self._req_sent is None)
def waiting_for_re... |
class TestLabelSmoothingCrossEntropyLoss(unittest.TestCase):
def test_build_label_smoothing_cross_entropy(self):
config = {'name': 'label_smoothing_cross_entropy', 'ignore_index': (- 1), 'smoothing_param': 0.1}
crit = build_loss(config)
self.assertTrue(isinstance(crit, LabelSmoothingCrossEnt... |
class Invite(models.Model):
key_salt = 'rdmo.projects.models.invite.Invite'
project = models.ForeignKey('Project', on_delete=models.CASCADE, related_name='invites', verbose_name=_('Project'), help_text=_('The project for this invite.'))
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET... |
def pytest_addoption(parser: Parser) -> None:
group = parser.getgroup('general')
group.addoption('--fixtures', '--funcargs', action='store_true', dest='showfixtures', default=False, help="Show available fixtures, sorted by plugin appearance (fixtures with leading '_' are only shown with '-v')")
group.addopt... |
def linear_from_cg_shape(self, x):
params_cg = OrderedDict()
if (self.bias is None):
params_cg['weight'] = torch.nn.Parameter(x)
else:
(W, b) = torch.split(x, self.weight.size(1), dim=0)
params_cg['weight'] = torch.nn.Parameter(W.t())
params_cg['bias'] = torch.nn.Parameter(to... |
def test_get_expansion():
assert (get_expansion(ViPNAS_Bottleneck, 2) == 2)
assert (get_expansion(ViPNAS_Bottleneck) == 1)
class MyResBlock(nn.Module):
expansion = 8
assert (get_expansion(MyResBlock) == 8)
with pytest.raises(TypeError):
get_expansion(ViPNAS_Bottleneck, '0')
with ... |
class BaseTermination():
def __init__(self, value):
self.value = value
def get_event(self, variables, step_value):
raise NotImplementedError
def __eq__(self, other):
if isinstance(other, self.__class__):
return (self.value == other.value)
else:
return ... |
class TargetTask(TransferTask):
role: ClassVar[TransferRole] = TransferRole.TARGET
token_network_address: TokenNetworkAddress = field(init=False, repr=False)
canonical_identifier: CanonicalIdentifier
target_state: TargetTransferState = field(repr=False)
def __post_init__(self) -> None:
self.... |
class QlOsPath():
def __init__(self, rootfs: str, cwd: str, emulos: QL_OS) -> None:
nt_path_os = (QL_OS.WINDOWS, QL_OS.DOS)
posix_path_os = QL_OS_POSIX
self._rootfs_path = Path(rootfs).resolve(strict=True)
if (emulos in nt_path_os):
self.PureVirtualPath = PureWindowsPath
... |
class SpiceLexer(RegexLexer):
name = 'Spice'
url = '
filenames = ['*.spice']
aliases = ['spice', 'spicelang']
mimetypes = ['text/x-spice']
version_added = '2.11'
tokens = {'root': [('\\n', Whitespace), ('\\s+', Whitespace), ('\\\\\\n', Text), ('//(.*?)\\n', Comment.Single), ('/(\\\\\\n)?[*]{... |
class ModuleListModel(nn.Module):
def __init__(self, num_classes=3):
super(ModuleListModel, self).__init__()
self.mod_list = nn.ModuleList([nn.MaxPool2d(kernel_size=2, stride=2, padding=1), nn.ReLU(inplace=True), nn.Conv2d(16, 8, kernel_size=2, stride=2, padding=2), nn.ReLU(), nn.Conv2d(3, 16, kerne... |
def get_all_binary_label(num_label, class_range):
all_binary_label = []
coding_len = get_code_len(class_range)
tmp = (10 ** coding_len)
for i in range(num_label):
binay = bin(i)
binay = (int(binay.split('0b')[(- 1)]) + tmp)
binay = np.array(list(str(binay)[1:]), np.int32)
... |
def check(app: TestApp, browser: Browser='firefox', html_report_dir: Optional[str]=None, interpreter_log_file: Optional[str]=None, driver_log_file: Optional[str]=None, headful: bool=False, stdout: TextIO=sys.stdout, stderr: TextIO=sys.stderr):
include_flags = [arg for path in include_paths for arg in ['-I', path]]
... |
.unit()
def test_sort_tasks_topologically(dag):
sorter = TopologicalSorter.from_dag(dag)
topo_ordering = []
while sorter.is_active():
task_name = sorter.get_ready()[0]
topo_ordering.append(task_name)
sorter.done(task_name)
topo_names = [dag.nodes[sig]['task'].name for sig in topo... |
class OrjsonConverter(Converter):
def dumps(self, obj: Any, unstructure_as: Any=None, **kwargs: Any) -> bytes:
return dumps(self.unstructure(obj, unstructure_as=unstructure_as), **kwargs)
def loads(self, data: Union[(bytes, bytearray, memoryview, str)], cl: Type[T]) -> T:
return self.structure(l... |
.skipif(((((pg.Qt.QT_LIB == 'PySide2') and pg.Qt.QtVersion.startswith('5.15')) or (pg.Qt.QT_LIB == 'PySide6')) and (sys.version_info >= (3, 9))), reason='Unknown Issue')
.usefixtures('tmp_module')
def test_reload(tmp_module):
mod = os.path.join(tmp_module, 'reload_test_mod.py')
print('\nRELOAD FILE:', mod)
... |
def test_membership_stacked_nested_last(benchmark):
td = big_nested_stacked_td()[0][0]
subtd = td
key = []
while True:
for (_key, value) in subtd.items():
key += [_key]
if is_tensor_collection(value):
subtd = value
break
else:
... |
def test_init_factory_alias():
cstats = [m.TestFactory6.get_cstats(), m.TestFactory6.get_alias_cstats()]
cstats[0].alive()
n_inst = ConstructorStats.detail_reg_inst()
a = m.TestFactory6(tag.base, 1)
assert (a.get() == 1)
assert (not a.has_alias())
b = m.TestFactory6(tag.alias, 'hi there')
... |
class HAM10000DatasetFast(Dataset):
def __init__(self, mode, data_dir=None, one_hot=True, image_size=224, aug=None, aug_empty=None, transform=None, img_transform=None, msk_transform=None, add_boundary_mask=False, add_boundary_dist=False, logger=None, **kwargs):
self.print = (logger.info if logger else print... |
class PlatformDirsABC(ABC):
def __init__(self, appname: (str | None)=None, appauthor: ((str | None) | Literal[False])=None, version: (str | None)=None, roaming: bool=False, multipath: bool=False, opinion: bool=True):
self.appname = appname
self.appauthor = appauthor
self.version = version
... |
class Migration(migrations.Migration):
dependencies = [('sponsors', '0095_auto__2025')]
operations = [migrations.AlterModelManagers(name='benefitfeatureconfiguration', managers=[('objects', django.db.models.manager.Manager()), ('non_polymorphic', django.db.models.manager.Manager())]), migrations.AlterModelManag... |
def test_files_from_regex_2(*args, **kwargs):
path = join(TEST_FOLDER_PATH, '*co2*.par')
path_test = get_files_from_regex(path)
path_actual = ['geisa_CO2_fragment.par', 'hitran_CO2_fragment.par', 'hitran_co2_626_bandhead_4165_4200nm.par']
path_actual.sort()
path_test.sort()
for i in range(len(pa... |
def state_with_pickup(state: State, pickup: PickupEntry) -> State:
new_state = state.copy()
new_state.previous_state = state
add_pickup_to_state(new_state, pickup)
if (new_state.maximum_energy > state.maximum_energy):
new_state.energy = new_state.maximum_energy
return new_state |
class Identity(nn.Module):
def __init__(self, inp, oup, stride):
super(Identity, self).__init__()
if ((stride != 1) or (inp != oup)):
self.downsample = nn.Sequential(nn.Conv2d(inp, oup, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(oup))
else:
self.downsam... |
class MeanEllipticalSlice(EllipticalSliceSampler):
def __init__(self, f_init, dist, lnpdf, nsamples, pdf_params=()):
mean_vector = dist.mean
demeaned_lnpdf = (lambda g: lnpdf((g + mean_vector), *pdf_params))
demeaned_init = (f_init - mean_vector)
samples = dist.sample(sample_shape=to... |
def test_activate_activates_non_existing_virtualenv_no_envs_file(tmp_path: Path, manager: EnvManager, poetry: Poetry, config: Config, mocker: MockerFixture, venv_name: str, venv_flags_default: dict[(str, bool)]) -> None:
if ('VIRTUAL_ENV' in os.environ):
del os.environ['VIRTUAL_ENV']
config.merge({'virt... |
class UpdateGrantInput(BaseGrantInput):
instance: strawberry.ID
name: str
full_name: str
conference: strawberry.ID
age_group: AgeGroup
gender: str
occupation: Occupation
grant_type: GrantType
python_usage: str
been_to_other_events: str
community_contribution: str
interest... |
def align_and_update_state_dicts(model_state_dict, loaded_state_dict):
current_keys = sorted(list(model_state_dict.keys()))
loaded_keys = sorted(list(loaded_state_dict.keys()))
match_matrix = [(len(j) if i.endswith(j) else 0) for i in current_keys for j in loaded_keys]
match_matrix = torch.as_tensor(mat... |
def extract_transmit_timestamp(ntp_packet):
encoded_transmit_timestamp = ntp_packet[40:48]
(seconds, fraction) = struct.unpack('!II', encoded_transmit_timestamp)
base_time = datetime.datetime(1900, 1, 1)
offset = datetime.timedelta(seconds=(seconds + (fraction / (2 ** 32))))
return (base_time + offs... |
class GroupEmitter():
def __init__(self, exprs):
self.exprs = ParseResults(exprs)
def make_generator(self):
def group_gen():
def recurse_list(elist):
if (len(elist) == 1):
(yield from elist[0].make_generator()())
else:
... |
def test_unset_cert(tester: CommandTester, auth_config_source: DictConfigSource, mocker: MockerFixture) -> None:
mocker.spy(ConfigSource, '__init__')
tester.execute('certificates.foo.cert path/to/ca.pem')
assert ('cert' in auth_config_source.config['certificates']['foo'])
tester.execute('certificates.fo... |
def test_qt_arg(request, quteproc_new, tmp_path):
args = (['--temp-basedir', '--qt-arg', 'stylesheet', str((tmp_path / 'does-not-exist'))] + _base_args(request.config))
quteproc_new.start(args)
msg = 'QCss::Parser - Failed to load file "*does-not-exist"'
line = quteproc_new.wait_for(message=msg)
li... |
def start(config_file, url_root='./translator', host='0.0.0.0', port=5000, debug=False):
def prefix_route(route_function, prefix='', mask='{0}{1}'):
def newroute(route, *args, **kwargs):
return route_function(mask.format(prefix, route), *args, **kwargs)
return newroute
if debug:
... |
def train_one_epoch(net, optimizer, config, master_bar, dataset=None):
net.train()
num_nodes = config.num_nodes
num_neighbors = config.num_neighbors
batch_size = config.batch_size
batches_per_epoch = config.batches_per_epoch
accumulation_steps = config.accumulation_steps
train_filepath = con... |
class MLP_Parrallel(nn.Module):
def __init__(self):
super(MLP_Parrallel, self).__init__()
self.encoder_1 = MLP_encoder()
self.encoder_2 = MLP_encoder()
self.classifier = nn.Linear(128, 14)
def forward(self, x1, x2, flag='unsupervised'):
if (flag == 'supervised'):
... |
def _translation_xgiga(params):
(corpus_type, json_file, args, save_file, en2de, de2en) = params
is_test = (corpus_type == 'test')
if os.path.exists(save_file):
logger.info(('Ignore %s' % save_file))
return
jobs = json.load(open(json_file))
datasets = []
sources = []
tgts = [... |
(params=['v1', 'v2_1', 'v2_2', 'oci'])
def puller(request, data_model, jwk):
if (request.param == 'v1'):
return V1Protocol(jwk)
if (request.param == 'v2_2'):
return V2Protocol(jwk, schema='schema2')
if (request.param == 'oci'):
return V2Protocol(jwk, schema='oci')
return V2Protoc... |
class TrafficStopAction(_ActionType):
def __init__(self, name=None):
self.name = name
def __eq__(self, other):
if isinstance(other, TrafficStopAction):
if (self.get_attributes() == other.get_attributes()):
return True
return False
def parse(element):
... |
class _FreeBSDBattery(_Battery):
def __init__(self, battery='0') -> None:
self.battery = battery
def update_status(self) -> BatteryStatus:
try:
info = check_output(['acpiconf', '-i', self.battery]).decode('utf-8')
except CalledProcessError:
raise RuntimeError('acp... |
def calc_inception(gen, batchsize=100):
.make_extension()
def evaluation(trainer):
model = load_inception_model()
ims = []
xp = gen.xp
n_ims = 50000
for i in range(0, n_ims, batchsize):
z = Variable(xp.asarray(gen.make_hidden(batchsize)))
with chai... |
def prepare_ref(lines: List[str], ltp_tokenizer: LTP, bert_tokenizer: BertTokenizer):
ltp_res = []
for i in range(0, len(lines), 100):
res = ltp_tokenizer.pipeline(lines[i:(i + 100)], tasks=['cws']).cws
res = [get_chinese_word(r) for r in res]
ltp_res.extend(res)
assert (len(ltp_res)... |
class AttentionGate(nn.Module):
def __init__(self):
super(AttentionGate, self).__init__()
kernel_size = 7
self.compress = ZPool()
self.conv = BasicConv(2, 1, kernel_size, stride=1, padding=((kernel_size - 1) // 2), relu=False)
def forward(self, x):
x_compress = self.compr... |
class PhysicMaterial():
def _setattrException(self, name, value):
raise PyUnityException('Cannot modify properties of PhysicMaterial: it is immutable')
def __init__(self, restitution=0.75, friction=1, immutable=False):
self.restitution = restitution
self.friction = friction
self.... |
def fmcw_tx():
angle = np.arange((- 90), 91, 1)
pattern = ((20 * np.log10((np.cos(((angle / 180) * np.pi)) + 0.01))) + 6)
tx_channel = {'location': (0, 0, 0), 'azimuth_angle': angle, 'azimuth_pattern': pattern, 'elevation_angle': angle, 'elevation_pattern': pattern}
return Transmitter(f=[(.0 - .0), (.0 ... |
def wrap_function_for_tracing(session: Session, task: PTask) -> None:
_pdb = PytaskPDB._init_pdb('runcall')
task_function = task.function
(task_function)
def wrapper(*args: Any, **kwargs: Any) -> None:
capman = session.config['pm'].get_plugin('capturemanager')
live_manager = session.conf... |
def downgrade(op, tables, tester):
op.drop_column('repositorybuildtrigger', 'successive_internal_error_count')
op.drop_column('repositorybuildtrigger', 'successive_failure_count')
op.execute(tables.disablereason.delete().where((tables.disablereason.c.name == op.inline_literal('successive_internal_error_coun... |
def load_class_from_name(fqcn):
paths = fqcn.split('.')
modulename = '.'.join(paths[:(- 1)])
classname = paths[(- 1)]
__import__(modulename, globals(), locals(), ['*'])
cls = getattr(sys.modules[modulename], classname)
if (not inspect.isclass(cls)):
raise TypeError(('%s is not a class' %... |
def video_post_process(opt, video_list, video_dict):
for video_name in video_list:
df = pd.read_csv((('./output/PEM_results/' + video_name) + '.csv'))
df['score'] = ((df.iou_score.values[:] * df.xmin_score.values[:]) * df.xmax_score.values[:])
if (len(df) > 1):
df = Soft_NMS(df, ... |
class WordsInContext(Task):
VERSION = 0
DATASET_PATH = 'super_glue'
DATASET_NAME = 'wic'
def has_training_docs(self):
return True
def has_validation_docs(self):
return True
def has_test_docs(self):
return False
def training_docs(self):
if (self._training_docs ... |
class Ui_ImageSettingsUi(object):
def setupUi(self, ImageSettingsUi):
ImageSettingsUi.setObjectName('ImageSettingsUi')
ImageSettingsUi.resize(332, 270)
self.gridLayout = QtWidgets.QGridLayout(ImageSettingsUi)
self.gridLayout.setObjectName('gridLayout')
self.groupBox_2 = QtWid... |
class ScoreboardView(View):
def __init__(self, bot: Bot):
super().__init__()
self.bot = bot
def _int_to_ordinal(number: int) -> str:
suffix = ['th', 'st', 'nd', 'rd', 'th'][min((number % 10), 4)]
if ((number % 100) in {11, 12, 13}):
suffix = 'th'
return (str(n... |
class FeedForwardNetworks(Model):
def __init__(self, sess, tf_flag):
self.sess = sess
self.oparam = Parameters()
self.oparam.learning_rate = tf_flag.learning_rate
self.oparam.max_iter = tf_flag.max_iter
self.oparam.batch_size = tf_flag.batch_size
self.oparam.image_siz... |
class TestConfigurable(unittest.TestCase):
def testInitWithArgs(self):
_ = _TestClassA(arg1=1, arg2=2, arg3=3)
_ = _TestClassB('shape', arg1=1, arg2=2)
_ = _TestClassC('shape', arg1=1, arg2=2)
_ = _TestClassD('shape', arg1=1, arg2=2, arg3=3)
def testPatchedAttr(self):
sel... |
_REGISTRY.register()
class ESRGANModel(SRGANModel):
def optimize_parameters(self, current_iter):
for p in self.net_d.parameters():
p.requires_grad = False
self.optimizer_g.zero_grad()
self.output = self.net_g(self.lq)
l_g_total = 0
loss_dict = OrderedDict()
... |
def _new_policy_set(new_policy):
if isinstance(new_policy, TrioPolicy):
raise RuntimeError("You can't set the Trio loop policy manually")
if _in_trio_context():
raise RuntimeError("You can't change the event loop policy in Trio context")
if ((new_policy is not None) and (not isinstance(new_p... |
class TestWarningsWrapper():
def test_warn(self):
warn_message = 'short and stout'
warn_source = 'teapot'
with warnings.catch_warnings(record=True) as caught_warnings:
utils.warn(message=warn_message, category=UserWarning, source=warn_source)
assert (len(caught_warnings) ... |
class Effect5553(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Heavy Assault Missiles')), 'maxVelocity', ship.getModifiedItemAttr('eliteBonusHeavyGunship1'), skill='Heavy Assault Cruisers',... |
class TransformerEncoderBlock(nn.Sequential):
def __init__(self, emb_size=900, drop_p=0.0, forward_expansion=4, forward_drop_p=0.0, **kwargs):
super().__init__(ResidualAdd(nn.Sequential(nn.LayerNorm(emb_size), MultiHeadAttention(emb_size, **kwargs), nn.Dropout(drop_p))), ResidualAdd(nn.Sequential(nn.LayerNo... |
def initialize_vars():
global Productions, Prodnames, Prodmap, Terminals
global Nonterminals, First, Follow, Precedence, LRitems
global Errorfunc, Signature, Requires
Productions = [None]
Prodnames = {}
Prodmap = {}
Terminals = {}
Nonterminals = {}
First = {}
Follow = {}
Prec... |
_arg_scope
def softmax(logits, scope=None):
with variable_scope.variable_scope(scope, 'softmax', [logits]):
num_logits = utils.last_dimension(logits.get_shape(), min_rank=2)
logits_2d = array_ops.reshape(logits, [(- 1), num_logits])
predictions = nn.softmax(logits_2d)
predictions = a... |
class PolypTrainer(nnUNetTrainer):
base_ch = 16
block = 'FusedMBConv'
use_my_unet = True
network_name = 'my_unet'
project_prefix = 'polyp'
setting = 2
def __init__(self, plans: dict, configuration: str, fold: int, dataset_json: dict, unpack_dataset: bool=True, device: torch.device=torch.devi... |
class HITAN6(FinTS3Segment):
tan_process = DataElementField(type='code', length=1, _d='TAN-Prozess')
task_hash_value = DataElementField(type='bin', max_length=256, required=False, _d='Auftrags-Hashwert')
task_reference = DataElementField(type='an', max_length=35, required=False, _d='Auftragsreferenz')
c... |
class TestCitationsTracked(unittest.TestCase):
def setUp(self):
self.plugin = get_dummy_plugin()
def test_import(self):
data = qiime2.Artifact.import_data(IntSequence1, [1, 2, 3, 4])
archiver = data._archiver
expected = [(('framework|qiime2:%s|0' % qiime2.__version__), 'Reproduci... |
.parametrize('cli_flat_fee, expected_channel_flat_fee', [(FeeAmount(42), FeeAmount(21)), (FeeAmount(43), FeeAmount(21))])
def test_prepare_mediation_fee_config_flat_fee(cli_flat_fee, expected_channel_flat_fee):
token_address = factories.make_token_address()
fee_config = prepare_mediation_fee_config(cli_token_to... |
class Window(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
toggle_1 = Toggle()
toggle_2 = AnimatedToggle(checked_color='#FFB000', pulse_checked_color='#44FFB000')
container = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout()
layout.addWidget(toggle... |
class PerlinNoiseFactory(object):
def __init__(self, dimension, octaves=1, tile=(), unbias=False, random_state=np.random.RandomState()):
self.dimension = dimension
self.octaves = octaves
self.tile = (tile + ((0,) * dimension))
self.unbias = unbias
self.scale_factor = (2 * (di... |
class TestBagType(unittest.TestCase):
def _create(self, *fields, typename='abc'):
bt = BagType(typename, fields)
assert (bt._fields == fields)
assert (len(bt._fields) == len(bt._attrs))
return bt
def test_factory(self):
Point = BagType('Point', ('x', 'y'))
self.as... |
def test_internal_errors_propagate_to_controller(pytester: pytest.Pytester) -> None:
pytester.makeconftest('\n def pytest_collection_modifyitems():\n raise RuntimeError("Some runtime error")\n ')
pytester.makepyfile('def test(): pass')
result = pytester.runpytest('-n1')
result.s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.