code stringlengths 281 23.7M |
|---|
class Value(object):
def __init__(self, name, initial, **kwargs):
self.name = name
self.watch = False
self.set(initial)
self.info = {'type': 'Value'}
if (('profiled' in kwargs) and kwargs['profiled']):
self.info['profiled'] = True
self.info['persistent... |
class ContactBase(models.Model):
name = models.CharField(max_length=100, blank=True)
created_on = models.DateTimeField(auto_now_add=True)
modified_on = models.DateTimeField(auto_now=True)
language = models.CharField(max_length=6, blank=True, help_text='The language which this contact prefers to communic... |
_torch
_tf
class DetermineFrameworkTest(TestCase):
def setUp(self):
self.test_model = SMALL_MODEL_IDENTIFIER
self.framework_pt = 'pt'
self.framework_tf = 'tf'
def _setup_pt_ckpt(self, save_dir):
model_pt = AutoModel.from_pretrained(self.test_model)
model_pt.save_pretraine... |
def get_dataloader(dataset='coco', img_size=128):
if (dataset == 'coco'):
dataset = CocoSceneGraphDataset(image_dir='./datasets/coco/images/val2017/', instances_json='./datasets/coco/annotations/instances_val2017.json', stuff_json='./datasets/coco/annotations/stuff_val2017.json', stuff_only=True, image_size... |
class CTransport(Transport):
rcache = {}
def hash(self, msg):
return md5_new(ppc.b_(msg)).hexdigest()
def csend(self, msg):
msg = ppc.b_(msg)
hash1 = self.hash(msg)
if (hash1 in self.scache):
self.send(ppc.b_(('H' + hash1)))
else:
self.send((pp... |
def parse_args():
parser = argparse.ArgumentParser(description='MMOCR test (and eval) a onnx or tensorrt model.')
parser.add_argument('model_config', type=str, help='Config file.')
parser.add_argument('model_file', type=str, help='Input file name for evaluation.')
parser.add_argument('model_type', type=... |
def create_resnet20_spec(config):
spec = model_spec.ModelSpec(np.array([[0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 0]]), ['input', 'conv3x3-bn-relu', 'conv3x3-bn-relu', 'output'])
config['num_stacks'] = 3
config['num_modules_per_stack'] = 3
config['stem_filter_size'] = 16
return spec |
class MnistParser():
def __init__(self, data_inputs=None, validation_inputs=None, batch_size=10):
if (not data_inputs):
data_inputs = ['data']
if (len(data_inputs) > 1):
raise ValueError('Only one data input supported for mnist')
self._data_inputs = data_inputs
... |
def _reduction_op_flop_jit(inputs, outputs, reduce_flops=1, finalize_flops=0):
input_shapes = [get_shape(v) for v in inputs]
output_shapes = [get_shape(v) for v in outputs]
in_elements = prod(input_shapes[0])
out_elements = prod(output_shapes[0])
num_flops = ((in_elements * reduce_flops) + (out_elem... |
def get_class_weights():
df_all = pd.read_csv((data_path + 'annotations.csv'))
return {'red_light': torch.Tensor(calc_class_weight(df_all['red_light'])), 'hazard_stop': torch.Tensor(calc_class_weight(df_all['hazard_stop'])), 'speed_sign': torch.Tensor(calc_class_weight(df_all['speed_sign'])), 'relative_angle': ... |
def save_checkpoint(args, trainer, epoch_itr, val_loss):
if (args.no_save or (not distributed_utils.is_master(args))):
return
write_timer = StopwatchMeter()
write_timer.start()
epoch = epoch_itr.epoch
end_of_epoch = epoch_itr.end_of_epoch()
updates = trainer.get_num_updates()
checkpo... |
class JointParameterized(Parameterized):
def __init__(self, components):
super(JointParameterized, self).__init__()
self.components = components
def get_params_internal(self, **tags):
params = [param for comp in self.components for param in comp.get_params_internal(**tags)]
retur... |
def get_observation_photo_metadata(observation_id, access_token):
print(f'Fetching observation {observation_id}')
obs = get_observation(observation_id)
photo_ids = [photo['id'] for photo in obs.get('photos', [])]
photo_urls = [f'{PHOTO_INFO_BASE_URL}/{id}' for id in photo_ids]
print(f'{len(photo_url... |
class HardDiskAnnFileBackend():
def __init__(self, file_format='txt'):
assert (file_format in ['txt', 'lmdb'])
self.file_format = file_format
def __call__(self, ann_file):
if (self.file_format == 'lmdb'):
return LmdbAnnFileBackend(ann_file)
return list_from_file(ann_f... |
def scm_find_files(path: _t.PathT, scm_files: set[str], scm_dirs: set[str], force_all_files: bool=False) -> list[str]:
realpath = os.path.normcase(os.path.realpath(path))
seen: set[str] = set()
res: list[str] = []
for (dirpath, dirnames, filenames) in os.walk(realpath, followlinks=True):
realdir... |
.linux
_locale
def test_downloads_with_ascii_locale(request, server, tmp_path, quteproc_new):
args = (['--temp-basedir'] + _base_args(request.config))
quteproc_new.start(args, env={'LC_ALL': 'C'})
quteproc_new.set_setting('downloads.location.directory', str(tmp_path))
quteproc_new.set_setting('downloads... |
class EventDetector(nn.Module):
def __init__(self, pretrain, width_mult, lstm_layers, lstm_hidden, bidirectional=True, dropout=True):
super(EventDetector, self).__init__()
self.width_mult = width_mult
self.lstm_layers = lstm_layers
self.lstm_hidden = lstm_hidden
self.bidirect... |
(autouse=True)
def _foo_module(mock_module):
mock_module('foo.py', 'import jsonschema\n\nclass MyValidator:\n def __init__(self, schema, *args, **kwargs):\n self.schema = schema\n self.real_validator = jsonschema.validators.Draft7Validator(\n schema, *args, **kwargs\n )\n\n def... |
class PreSEAttBlock(nn.Module):
def __init__(self, in_channels, out_channels, reduction=16):
super(PreSEAttBlock, self).__init__()
mid_cannels = (out_channels // reduction)
self.bn = nn.BatchNorm2d(num_features=in_channels)
self.relu = nn.ReLU(inplace=True)
self.pool = nn.Ada... |
def _compute_intersection(w1, w2):
col_off = max(w1.col_off, w2.col_off)
row_off = max(w1.row_off, w2.row_off)
width = (min((w1.col_off + w1.width), (w2.col_off + w2.width)) - col_off)
height = (min((w1.row_off + w1.height), (w2.row_off + w2.height)) - row_off)
return (col_off, row_off, width, heigh... |
def test_device_from_uuid_and_location_returns_unsupported():
unsupported = mock.create_autospec(discovery.UnsupportedDevice)
with mock.patch('pywemo.discovery.UnsupportedDevice', return_value=unsupported):
assert (discovery.device_from_uuid_and_location('uuid:Unsupported-1_0-SERIALNUMBER', ' debug=True... |
def test_discovery_responder_notify(mock_socket, mock_interface_addresses, mock_get_callback_address):
resp = ssdp.DiscoveryResponder(callback_port=MOCK_CALLBACK_PORT)
resp.send_notify('ssdp:alive')
params = {'callback': MOCK_CALLBACK_ADDRESS, 'nls': resp._nls_uuid, 'nts': 'ssdp:alive'}
mock_socket.send... |
def lisp_to_sparql(lisp_program: str):
clauses = []
order_clauses = []
entities = set()
identical_variables_r = {}
expression = lisp_to_nested_expression(lisp_program)
superlative = False
if (expression[0] in ['ARGMAX', 'ARGMIN']):
superlative = True
if isinstance(expression[... |
class KJTListAwaitable(Awaitable[KJTList]):
def __init__(self, awaitables: List[Awaitable[KeyedJaggedTensor]], ctx: C) -> None:
super().__init__()
self.awaitables = awaitables
self.ctx = ctx
def _wait_impl(self) -> KJTList:
kjts = [w.wait() for w in self.awaitables]
_set_... |
def compile_listings():
listing_files = {}
if os.path.isdir(DIR_LISTINGS):
for f in os.listdir(DIR_LISTINGS):
ex_name = os.path.splitext(f)[0]
f_path = os.path.join(DIR_LISTINGS, f)
if os.path.isfile(f_path):
listing_files[ex_name] = f_path
... |
class QuickCheck():
def __init__(self, ip):
self.ip = ip
self.port = 8123
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.settimeout(3)
self.MSG = b''
self.raw_MSG = ''
self.measurements = pd.DataFrame()
self.data = ''
se... |
class _MixinSvgPosition():
_attribute_decorator('WidgetSpecific', 'Coordinate for Svg element.', float, {'possible_values': '', 'min': (- 65635.0), 'max': 65635.0, 'default': 1.0, 'step': 0.1})
def attr_x(self):
return self.attributes.get('x', '0')
_x.setter
def attr_x(self, value):
self... |
class TestCaseRetry(TestCase):
def name():
return 'retry'
def abbreviation():
return 'S'
def desc():
return 'Server sends a Retry, and a subsequent connection using the Retry token completes successfully.'
def get_paths(self):
self._files = [self._generate_random_file((10... |
class TestGenerator(TestNameCheckVisitorBase):
_passes()
def test_generator_return(self):
from typing import Generator
def gen(cond) -> Generator[(int, str, float)]:
x = (yield 1)
assert_is_value(x, TypedValue(str))
(yield 'x')
if cond:
... |
class DeleteLate(ScrimsButton):
def __init__(self, ctx: Context, letter: str):
super().__init__(emoji=ri(letter))
self.ctx = ctx
async def callback(self, interaction: Interaction):
(await interaction.response.defer())
self.view.record.autodelete_extras = (not self.view.record.aut... |
class Migration(migrations.Migration):
dependencies = [('server', '0001_initial')]
operations = [migrations.RunPython(forwards, migrations.RunPython.noop), migrations.AlterField(model_name='serverconfig', name='db_value', field=evennia.utils.picklefield.PickledObjectField(help_text='The data returned when the c... |
def draw_bounding_box_on_image(image, ymin, xmin, ymax, xmax, color='red', thickness=4, display_str_list=(), use_normalized_coordinates=True):
draw = ImageDraw.Draw(image)
(im_width, im_height) = image.size
if use_normalized_coordinates:
(left, right, top, bottom) = ((xmin * im_width), (xmax * im_wi... |
(Flight)
class FlightAdmin(RemoveDeleteMixin, FlightMixin, SimpleHistoryAdmin):
model = Flight
form = FlightAdminForm
save_as = True
actions = ['action_create_draft_invoice']
inlines = (AdvertisementsInline, InvoiceInline)
list_display = ('name', 'slug', 'campaign', 'live', 'start_date', 'end_da... |
def gmetric_write(NAME, VAL, TYPE, UNITS, SLOPE, TMAX, DMAX, GROUP):
packer = Packer()
HOSTNAME = 'test'
SPOOF = 0
packer.pack_int(128)
packer.pack_string(HOSTNAME)
packer.pack_string(NAME)
packer.pack_int(SPOOF)
packer.pack_string(TYPE)
packer.pack_string(NAME)
packer.pack_strin... |
def analyze_egg(egg_dir, stubs):
for (flag, fn) in safety_flags.items():
if os.path.exists(os.path.join(egg_dir, 'EGG-INFO', fn)):
return flag
if (not can_scan()):
return False
safe = True
for (base, dirs, files) in walk_egg(egg_dir):
for name in files:
if... |
class normalizer(object):
def __init__(self):
self.target_means = None
self.target_stds = None
def fit(self, target):
target = ut.standardize_brightness(target)
(means, stds) = get_mean_std(target)
self.target_means = means
self.target_stds = stds
def transfor... |
def create_new_paste(contents: Union[(str, bytes)]) -> str:
import re
from urllib.request import urlopen
from urllib.parse import urlencode
params = {'code': contents, 'lexer': 'text', 'expiry': '1week'}
url = '
try:
response: str = urlopen(url, data=urlencode(params).encode('ascii')).re... |
class Migration(migrations.Migration):
dependencies = [('objects', '0009_remove_objectdb_db_player')]
operations = [migrations.AlterField(model_name='objectdb', name='db_account', field=models.ForeignKey(help_text='an Account connected to this object, if any.', null=True, on_delete=django.db.models.deletion.SET... |
class Migration(migrations.Migration):
dependencies = [('tasks', '0030_available')]
operations = [migrations.AlterField(model_name='task', name='conditions', field=models.ManyToManyField(blank=True, help_text='The list of conditions evaluated for this task.', related_name='tasks', to='conditions.Condition', ver... |
_layer('gineconv')
class GINEConvGraphGymLayer(nn.Module):
def __init__(self, layer_config: LayerConfig, **kwargs):
super().__init__()
gin_nn = nn.Sequential(Linear_pyg(layer_config.dim_in, layer_config.dim_out), nn.ReLU(), Linear_pyg(layer_config.dim_out, layer_config.dim_out))
self.model =... |
def has(cls):
attrs = getattr(cls, '__attrs_attrs__', None)
if (attrs is not None):
return True
generic_base = get_generic_base(cls)
if (generic_base is not None):
generic_attrs = getattr(generic_base, '__attrs_attrs__', None)
if (generic_attrs is not None):
cls.__att... |
class Effect7098(BaseEffect):
type = 'passive'
def handler(fit, src, context, projectionRange, **kwargs):
for attr in ('hp', 'armorHP', 'shieldCapacity', 'capacitorCapacity'):
fit.ship.boostItemAttr(attr, src.getModifiedItemAttr('conversionRigHPCapBonus'), **kwargs)
fit.ship.boostIte... |
class Names(unittest.TestCase):
def test_long_name(self):
generated = r.DNSOutgoing(const._FLAGS_QR_RESPONSE)
question = r.DNSQuestion('this.is.a.very.long.name.with.lots.of.parts.in.it.local.', const._TYPE_SRV, const._CLASS_IN)
generated.add_question(question)
r.DNSIncoming(generate... |
def random_search(scores_info_export_path, num_trials, report_oracle_bleu=False):
with open(scores_info_export_path, 'rb') as f:
scores_info = pickle.load(f)
dummy_task = DummyTask()
if report_oracle_bleu:
oracle_scorer = bleu.Scorer(bleu.BleuConfig(pad=vocab_constants.PAD_ID, eos=vocab_cons... |
class TestPortaraDataProviderDaily(TestCase):
def setUpClass(cls) -> None:
cls.start_date = str_to_date('2021-05-18')
cls.end_date = str_to_date('2021-06-28')
cls.number_of_data_bars = 29
cls.fields = PriceField.ohlcv()
cls.ticker = PortaraTicker('AB', SecurityType.FUTURE, 1)... |
class Effect4058(BaseEffect):
runTime = 'early'
type = ('projected', 'passive')
def handler(fit, beacon, context, projectionRange, **kwargs):
fit.modules.filteredChargeMultiply((lambda mod: mod.charge.requiresSkill('Rockets')), 'explosiveDamage', beacon.getModifiedItemAttr('smallWeaponDamageMultipli... |
class BasicBlock3d(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, spatial_stride=1, temporal_stride=1, dilation=1, downsample=None, style='pytorch', inflate=True, non_local=False, non_local_cfg=dict(), conv_cfg=dict(typename='Conv3d'), norm_cfg=dict(typename='BN3d'), act_cfg=dict(typename='ReLU'... |
def main():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--pause', action='store_true', help='pause')
args = parser.parse_args()
pybullet_planning.connect()
pybullet_planning.add_data_path()
p.setGravity(0, 0, (- 9.8))
with pyb... |
def auxtrace_error(typ, code, cpu, pid, tid, ip, ts, msg, cpumode, *x):
try:
print(('%16s %5u/%-5u [%03u] %9u.%09u error type %u code %u: %s ip 0x%16x' % ('Trace error', pid, tid, cpu, (ts / ), (ts % ), typ, code, msg, ip)))
except broken_pipe_exception:
sys.stdout = open(os.devnull, 'w')
... |
def summaryCSS(title, center=True):
tdcenter = ('text-align:center;' if center else '')
out = (((('<!DOCTYPE html>\n<html>\n<head>\n\t<meta content="text/html; charset=UTF-8">\n\t<title>' + title) + '</title>\n\t<style type=\'text/css\'>\n\t\t.stamp {width: 100%;text-align:center;background:#888;line-height:30... |
class MouseEvent(QtGui.QMouseEvent):
def get_state(obj, picklable=False):
typ = obj.type()
if isinstance(typ, int):
typ = QtCore.QEvent.Type(typ)
lpos = (obj.position() if hasattr(obj, 'position') else obj.localPos())
gpos = (obj.globalPosition() if hasattr(obj, 'globalPo... |
class ExamplesTests(TestCasePlus):
def test_run_glue(self):
tmp_dir = self.get_auto_remove_tmp_dir()
testargs = f'''
run_glue.py
--model_name_or_path distilbert-base-uncased
--output_dir {tmp_dir}
--overwrite_output_dir
--train_file ./tests... |
def _restore_curry(cls, func, args, kwargs, userdict, is_decorated):
if isinstance(func, str):
(modname, qualname) = func.rsplit(':', 1)
obj = import_module(modname)
for attr in qualname.split('.'):
obj = getattr(obj, attr)
if is_decorated:
return obj
... |
class FixedLengthProcessionSpeed(ProcessingSpeedColumn):
def __init__(self, style: Union[(str, Any)]):
super().__init__(style)
self.max_length = len('0.00')
def render(self, task) -> RenderableType:
task_speed = (f'{task.speed:>.2f}' if (task.speed is not None) else '0.00')
self.... |
def load_model():
if (opt.model == 'resnet_32'):
from gen_models.resnet_32 import ResNetGenerator
gen = ResNetGenerator(ch=opt.ngf, dim_z=opt.nz, bottom_width=opt.start_width, n_classes=opt.nclass)
elif (opt.model == 'resnet_64'):
from gen_models.resnet_64 import ResNetGenerator
... |
class Throughput(Metric[float]):
def __init__(self: TThroughput, *, device: Optional[torch.device]=None) -> None:
super().__init__(device=device)
self._add_state('num_total', 0.0)
self._add_state('elapsed_time_sec', 0.0)
_mode()
def update(self: TThroughput, num_processed: int, elaps... |
class Pizza(ABC):
name: str
dough: str
sauce: str
toppings: List[str]
def prepare(self) -> None:
print(f'Prepare {self.name}')
print('Tossing dough...')
print('Adding sauce...')
print('Adding toppings: ')
for topping in self.toppings:
print(f' {t... |
class TestHarnessSimple(Component):
def construct(s, MsgType, SrcType, SinkType, src_msgs, sink_msgs):
s.src = SrcType(MsgType, src_msgs)
s.sink = SinkType(MsgType, sink_msgs)
connect(s.src.send, s.sink.recv)
def done(s):
return (s.src.done() and s.sink.done())
def line_trace... |
class ApproveSponsorshipApplicationUseCaseTests(TestCase):
def setUp(self):
self.notifications = [Mock(), Mock()]
self.use_case = use_cases.ApproveSponsorshipApplicationUseCase(self.notifications)
self.user = baker.make(settings.AUTH_USER_MODEL)
self.sponsorship = baker.make(Sponsors... |
def _validate_coincident(triangulator):
(triangulator)
def tri_with_validation(coordinates, ids=None, coincident='raise', kernel=None, bandwidth=None, seed=None, **kwargs):
(coordinates, ids, geoms) = _validate_geometry_input(coordinates, ids=ids, valid_geometry_types=_VALID_GEOMETRY_TYPES)
(n_c... |
def socket_level_mapping(t: int, archtype: QL_ARCH) -> str:
socket_level_map = {QL_ARCH.X86: linux_x86_socket_level, QL_ARCH.X8664: linux_x86_socket_level, QL_ARCH.ARM: linux_arm_socket_level, QL_ARCH.ARM64: linux_arm_socket_level, QL_ARCH.MIPS: linux_mips_socket_level}[archtype]
return _constant_mapping(t, soc... |
def get_current_dir():
data = config.getbytes('memory', 'chooser_dir', b'')
try:
path = (bytes2fsn(data, 'utf-8') or None)
except ValueError:
path = None
if (path is not None):
path = find_nearest_dir(path)
if (path is None):
path = get_home_dir()
return path |
def main():
parser = argparse.ArgumentParser(description='Release an OpenNMT-py model for inference')
parser.add_argument('--model', '-m', help='The model path', required=True)
parser.add_argument('--output', '-o', help='The output path', required=True)
parser.add_argument('--format', choices=['pytorch'... |
('--user', '-u', default='reanahub', help='DockerHub user name [reanahub]')
('--tag', '-t', default='latest', help='Image tag [latest]')
('--component', '-c', multiple=True, default=['CLUSTER'], help='Which components? [name|CLUSTER|DEMO]')
_commands.command(name='docker-pull')
def docker_pull(user, tag, component):
... |
def filter(example, uniques, args):
if (not check_uniques(example, uniques)):
return False
elif example['autogenerated']:
return False
elif (example['line_max'] > args.line_max):
return False
elif (example['line_mean'] > args.line_mean):
return False
elif (example['al... |
def test_adjust_max():
candidates = CompletedKeys(10)
assert (candidates.num_remaining == 10)
assert (len(candidates._slabs) == 0)
assert candidates.is_available(9)
candidates.mark_completed(5, 12)
assert (len(candidates._slabs) == 0)
assert (candidates.num_remaining == 5)
assert (not ca... |
def bmm_flop_jit(inputs, outputs):
input_shapes = [get_shape(v) for v in inputs]
assert (len(input_shapes[0]) == 3)
assert (len(input_shapes[1]) == 3)
(T, batch_size, input_dim) = input_shapes[0]
output_dim = input_shapes[1][2]
flop = (((T * batch_size) * input_dim) * output_dim)
flop_counte... |
.slow
def test_hamiltonian_taking_arguments():
N = 10
w0 = ((1.0 * 2) * np.pi)
g = ((0.75 * 2) * np.pi)
kappa = 0.05
a = qutip.tensor(qutip.destroy(N), qutip.qeye(2))
sp = qutip.tensor(qutip.qeye(N), qutip.sigmap())
psi0 = qutip.tensor(qutip.basis(N, 1), qutip.basis(2, 0))
psi0 = qutip.k... |
def filter_latest_pkgs(pkgs):
pkgname2latest = {}
for x in pkgs:
pkgname = normalize_pkgname(x.pkgname)
if (pkgname not in pkgname2latest):
pkgname2latest[pkgname] = x
elif (x.parsed_version > pkgname2latest[pkgname].parsed_version):
pkgname2latest[pkgname] = x
... |
class LegalClause(OrderedModel):
internal_name = models.CharField(max_length=1024, verbose_name='Internal Name', help_text='Friendly name used internally by PSF to reference this clause', blank=False)
clause = models.TextField(verbose_name='Clause', help_text='Legal clause text to be added to contract', blank=F... |
.parametrize('username,password', users)
.parametrize('membership_id', memberships)
def test_delete(db, client, username, password, membership_id):
client.login(username=username, password=password)
url = reverse(urlnames['detail'], args=[membership_id])
response = client.delete(url)
if password:
... |
def reorder_train_deterministic(dataset):
assert isinstance(dataset, torchvision.datasets.STL10)
assert (dataset.split == 'train+unlabeled')
assert (dataset.data.shape == (105000, 3, 96, 96))
ids = []
for i in xrange(5000):
ids.append(i)
ids += range((5000 + (i * 20)), (5000 + ((i + ... |
def test_simulate_genotype_call_dataset__phased(tmp_path):
ds = simulate_genotype_call_dataset(n_variant=10, n_sample=10, phased=True)
assert ('call_genotype_phased' in ds)
assert np.all(ds['call_genotype_phased'])
ds = simulate_genotype_call_dataset(n_variant=10, n_sample=10, phased=False)
assert (... |
class MainWindow(QMainWindow):
signal_close = Signal()
signal_gesture = Signal(QtCore.QEvent)
def __init__(self, parent: Optional[QWidget]=None, title: Optional[str]=None, size: Optional[Tuple[(int, int)]]=None) -> None:
QMainWindow.__init__(self, parent=parent)
if (title is not None):
... |
def convert_pascal_berkeley_augmented_mat_annotations_to_png(pascal_berkeley_augmented_root):
import scipy.io
def read_class_annotation_array_from_berkeley_mat(mat_filename, key='GTcls'):
mat = scipy.io.loadmat(mat_filename, mat_dtype=True, squeeze_me=True, struct_as_record=False)
return mat[key... |
class VGG(nn.Module):
def __init__(self, features, num_classes=11):
super(VGG, self).__init__()
self.features = features
self.classifier = nn.Sequential(nn.Linear(((512 * 7) * 7), 4096), nn.ReLU(True), nn.Dropout(p=0.9), nn.Linear(4096, 4096), nn.ReLU(True), nn.Dropout(p=0.9))
self.f... |
class TestResolver():
def test_resolve_setup_path_cwd(self):
assert (develop._resolve_setup_path('.', '.', '.') == '.')
def test_resolve_setup_path_one_dir(self):
assert (develop._resolve_setup_path('pkgs', '.', 'pkgs') == '../')
def test_resolve_setup_path_one_dir_trailing_slash(self):
... |
class TestCauchy(BaseTestDistributionRandom):
pymc_dist = pm.Cauchy
pymc_dist_params = {'alpha': 2.0, 'beta': 5.0}
expected_rv_op_params = {'alpha': 2.0, 'beta': 5.0}
reference_dist_params = {'loc': 2.0, 'scale': 5.0}
reference_dist = seeded_scipy_distribution_builder('cauchy')
checks_to_run = [... |
class FifoTransactionManager(ModbusTransactionManager):
def __init__(self, client, **kwargs):
super().__init__(client, **kwargs)
self.transactions = []
def __iter__(self):
return iter(self.transactions)
def addTransaction(self, request, tid=None):
tid = (tid if (tid is not No... |
class Visualizer():
def __init__(self, opt, name='train'):
self.logger = tf_logger.Logger(os.path.join(opt.log_dir, name))
self.log_name = os.path.join(opt.log_dir, 'tf_visualizer_log.txt')
with open(self.log_name, 'a') as log_file:
now = time.strftime('%c')
log_file.... |
def gen_pickle(split='val', root='ScanNet'):
if (split == 'test'):
root = (root + '/scans_test')
else:
root = (root + '/scans')
file_list = ('scannetv2_%s.txt' % split)
with open(file_list) as fl:
scene_id = fl.read().splitlines()
scene_data = []
scene_data_labels = []
... |
def lines2dictlist(lines, format):
lines = [x.split() for x in lines]
if (format == 'rawframes'):
data = [dict(frame_dir=line[0], total_frames=int(line[1]), label=[int(x) for x in line[2:]]) for line in lines]
elif (format == 'videos'):
data = [dict(filename=line[0], label=[int(x) for x in l... |
def objective(trial):
k_neighbours = trial.suggest_int('k_neighbours', 5, 20)
frac_samples = (2 ** trial.suggest_int('frac_samples', (- 2), 3))
frac_lam_del = trial.suggest_float('frac_lam_del', 0.0, 0.95, step=0.05)
score = 0.0
with tempfile.TemporaryDirectory() as dir_:
dir_ = Path(dir_)
... |
def compute_mul(tree):
(neg, inputs) = tree
if (inputs is None):
raise AssertionError('Function `compute_mul` found a missing leaf, did you forget to call `simplify_mul` on the tree first?')
elif isinstance(inputs, list):
rval = mul(*list(map(compute_mul, inputs)))
else:
rval = i... |
class BaseDpEmbeddingSharding(EmbeddingSharding[(C, F, T, W)]):
def __init__(self, sharding_infos: List[EmbeddingShardingInfo], env: ShardingEnv, device: Optional[torch.device]=None) -> None:
super().__init__()
self._env = env
self._device = device
self._rank: int = self._env.rank
... |
class TestInstMonthlyCadence(TestInstCadence):
def setup_method(self):
reload(pysat.instruments.pysat_testing)
self.ref_time = pysat.instruments.pysat_testing._test_dates['']['']
self.freq = 'MS'
date_range = pds.date_range((self.ref_time - pds.DateOffset(years=1)), (self.ref_time + ... |
def assert_condition_check_fails():
try:
(yield)
except (PutError, UpdateError, DeleteError) as e:
assert isinstance(e.cause, ClientError)
assert (e.cause_response_code == 'ConditionalCheckFailedException')
except TransactWriteError as e:
assert isinstance(e.cause, ClientErro... |
class OCIConfig(object):
METASCHEMA = {'type': 'object', 'description': 'The container configuration found in an OCI manifest', 'required': [CONFIG_ROOTFS_KEY, CONFIG_ARCHITECTURE_KEY, CONFIG_OS_KEY], 'properties': {CONFIG_CREATED_KEY: {'type': ['string', 'null'], 'description': 'An combined date and time at which ... |
(mass=ShowInInspector(float, 100), inertia=ShowInInspector(float, (200 / 3)))
class Rigidbody(Component):
velocity = ShowInInspector(Vector3)
rotVel = ShowInInspector(Vector3, None, 'Rotational Velocity')
force = ShowInInspector(Vector3)
torque = ShowInInspector(Vector3)
gravity = ShowInInspector(bo... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--data-root', help='directory to search for JSON files')
parser.add_argument('-v', '--verbose', type=int, help='increase output verbosity')
args = parser.parse_args()
check_filename_length(args.data_root, verbose=args.verbose) |
class CatalogQuestionSet(CurrentSiteQuerySetMixin, GroupsQuerySetMixin, AvailabilityQuerySetMixin, models.QuerySet):
def filter_catalog(self, catalog):
return self.filter((models.Q(catalogs=None) | models.Q(catalogs=catalog)))
def prefetch_elements(self):
return self.prefetch_related(*self.model... |
def sched__sched_migrate_task(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, common_callchain, comm, pid, prio, orig_cpu, dest_cpu):
headers = EventHeaders(common_cpu, common_secs, common_nsecs, common_pid, common_comm, common_callchain)
parser.migrate(headers, pid, prio, o... |
def get_process_result_dict(result, config_idx, mode='Train'):
result_dict = {'Env': result['Env'][0], 'Agent': result['Agent'][0], 'Config Index': config_idx, 'Return (mean)': (result['Return'][(- 100):].mean(skipna=False) if (mode == 'Train') else result['Return'][(- 5):].mean(skipna=False))}
return result_di... |
class DwsConv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0):
super(DwsConv, self).__init__()
self.dw_conv = nn.Conv2d(in_channels=in_channels, out_channels=in_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=in_channels, bias=Fal... |
class RouteState(MetadataValidation, State):
route: List[Address]
address_to_metadata: Dict[(Address, AddressMetadata)] = field(default_factory=dict)
swaps: Dict[(Address, TokenNetworkAddress)] = field(default_factory=dict)
estimated_fee: FeeAmount = FeeAmount(0)
def __post_init__(self) -> None:
... |
def eval_triangles(x: wp.array(dtype=wp.vec3), v: wp.array(dtype=wp.vec3), indices: wp.array2d(dtype=int), pose: wp.array(dtype=wp.mat22), activation: wp.array(dtype=float), materials: wp.array2d(dtype=float), f: wp.array(dtype=wp.vec3)):
tid = wp.tid()
k_mu = materials[(tid, 0)]
k_lambda = materials[(tid, ... |
def show_performance_comparison(pos_base, neg_base, pos_ours, neg_ours, baseline_name='Baseline', method_name='Ours', recall_level=recall_level_default):
(auroc_base, aupr_base, fpr_base) = get_measures(pos_base[:], neg_base[:], recall_level)
(auroc_ours, aupr_ours, fpr_ours) = get_measures(pos_ours[:], neg_our... |
def main(args):
utils.import_user_module(args)
print(args)
os.makedirs(args.destdir, exist_ok=True)
target = (not args.only_source)
task = tasks.get_task(args.task)
def train_path(lang):
return '{}{}'.format(args.trainpref, (('.' + lang) if lang else ''))
def file_name(prefix, lang):... |
class ConsoleReporter(Reporter):
report_on_success: bool
file: Optional[IO[Text]] = sys.stdout
def report_test(self, test: Test[(Diff[protocol.JsonLike], bytes)]):
click.echo('Trace:', file=self.file)
for (i, transition) in enumerate(test.transitions):
click.echo(element_heading(... |
def generate_fswap_unitaries(swap_pairs: List[List[Tuple]], dimension: int):
swap_unitaries = []
for swap_tuples in swap_pairs:
generator = np.zeros((dimension, dimension), dtype=np.complex128)
for (i, j) in swap_tuples:
generator[(i, i)] = (- 1)
generator[(j, j)] = (- 1)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.