code stringlengths 281 23.7M |
|---|
def main(arguments=None):
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logger = logging.getLogger('scikits.odes setup')
logger.setLevel('INFO')
logfile = join(os.path.dirname(os.path.abspath(__file__)), 'scikits_odes_setup.log')
print(logfile)
file_handler = logging.FileHa... |
class SegmentationHead(nn.Module):
def __init__(self, inplanes, planes, nbr_classes, dilations_conv_list):
super().__init__()
self.conv0 = nn.Conv3d(inplanes, planes, kernel_size=3, padding=1, stride=1)
self.conv_list = dilations_conv_list
self.conv1 = nn.ModuleList([nn.Conv3d(planes... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', type=int, default=0)
parser.add_argument('--times', type=int, default=1000)
parser.add_argument('--dynamic-input', action='store_true')
args = parser.parse_args()
print(('==> Benchmark: gpu=%d, times=%d, dynamic_input=%s... |
def get_preresnet(blocks, bottleneck=None, conv1_stride=True, width_scale=1.0, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs):
if (bottleneck is None):
bottleneck = (blocks >= 50)
if (blocks == 10):
layers = [1, 1, 1, 1]
elif (blocks == 12):
... |
class CmdWho(CmdEvscapeRoom, default_cmds.CmdWho):
key = 'who'
obj1_search = False
obj2_search = False
def func(self):
caller = self.caller
if (self.args == 'all'):
table = self.style_table('|wName', '|wRoom')
sessions = SESSION_HANDLER.get_sessions()
... |
def sr_create_model_and_diffusion(large_size, small_size, class_cond, learn_sigma, num_channels, num_res_blocks, num_heads, num_heads_upsample, attention_resolutions, dropout, diffusion_steps, noise_schedule, timestep_respacing, use_kl, predict_xstart, rescale_timesteps, rescale_learned_sigmas, use_checkpoint, use_scal... |
def test_damaged(s):
cut = models.Cut((0,), (1, 2))
cut_s = Subsystem(s.network, s.state, s.node_indices, cut=cut)
m1 = mice(mechanism=(0, 1), purview=(1, 2), direction=Direction.EFFECT)
assert m1.damaged_by_cut(cut_s)
assert (not m1.damaged_by_cut(s))
m2 = mice(mechanism=(0,), purview=(1, 2), d... |
class PlayMapData(Packet):
id = 37
to = 1
def __init__(self, map_id: int, scale: int, tracking_pos: bool, locked: bool, icons: list, cols: int, rows: int=None, x: int=None, z: int=None, data: bytes=None) -> None:
super().__init__()
self.map_id = map_id
self.scale = scale
self... |
class TestMdconv(object):
def _test_mdconv(self, dtype=torch.float, device='cuda'):
if ((not torch.cuda.is_available()) and (device == 'cuda')):
pytest.skip('test requires GPU')
from mmcv.ops import ModulatedDeformConv2dPack
input = torch.tensor(input_t, dtype=dtype, device=devic... |
_cache(maxsize=None)
def get_search_dirs(python_executable: (str | None)) -> tuple[(list[str], list[str])]:
if (python_executable is None):
return ([], [])
elif (python_executable == sys.executable):
(sys_path, site_packages) = pyinfo.getsearchdirs()
else:
env = {**dict(os.environ), ... |
_module(name='Constant')
class ConstantInit(BaseInit):
def __init__(self, val, **kwargs):
super().__init__(**kwargs)
self.val = val
def __call__(self, module):
def init(m):
if self.wholemodule:
constant_init(m, self.val, self.bias)
else:
... |
def exclude(group):
assert (group is not None)
current = ops.env.get(ops.survey.EXCLUDE, addr='')
if (current is None):
current = []
else:
current = json.loads(current)
if (str is type(group)):
group = codecs.utf_8_decode(group)[0]
if (group not in current):
curre... |
def create_bin(X, Y, Z, color=(0.59, 0.44, 0.2, 1), create=None):
origin = [0, 0, 0]
if (create is None):
create = Ellipsis
def get_parts(origin, X, Y, Z, T=0.01):
extents = np.array([[X, Y, T], [X, T, Z], [X, T, Z], [T, Y, Z], [T, Y, Z]])[create]
positions = np.array([[0, 0, ((- Z) ... |
def score_jnd_dataset(data_loader, func):
ds = []
gts = []
for (i, data) in enumerate(data_loader.load_data()):
ds += func(data['p0'], data['p1']).tolist()
gts += data['same'].cpu().numpy().flatten().tolist()
sames = np.array(gts)
ds = np.array(ds)
sorted_inds = np.argsort(ds)
... |
def test_asyncio_mark_handles_missing_event_loop_triggered_by_fixture(pytester: pytest.Pytester):
pytester.makepyfile(dedent(' import pytest\n import asyncio\n\n class TestClass:\n (scope="class")\n def sets_event_loop_to_none(self):\n ... |
class KnowValues(unittest.TestCase):
def test_energy(self):
coords = [(0.0, 0.1, 0.0)]
charges = [1.0]
mf = itrf.mm_charge(scf.RHF(mol), coords, charges)
self.assertAlmostEqual(mf.kernel(), 2., 9)
self.assertEqual(mf.undo_qmmm().__class__.__name__, 'RHF')
def test_grad(se... |
class BaseElectrumGui():
def __init__(self, *, config: 'SimpleConfig', daemon: 'Daemon', plugins: 'Plugins'):
self.config = config
self.daemon = daemon
self.plugins = plugins
def main(self) -> None:
raise NotImplementedError()
def stop(self) -> None:
pass
def vers... |
def _qr_path(data) -> str:
module = 'qrcode.image.svg.SvgPathImage'
(module, name) = module.rsplit('.', 1)
imp = __import__(module, {}, {}, [name])
svg_path_image = getattr(imp, name)
qr_code = qrcode.QRCode()
qr_code.add_data(data)
img = qr_code.make_image(image_factory=svg_path_image)
... |
class BasicBlockD(nn.Module):
def __init__(self, conv_op: Type[_ConvNd], input_channels: int, output_channels: int, kernel_size: Union[(int, List[int], Tuple[(int, ...)])], stride: Union[(int, List[int], Tuple[(int, ...)])], conv_bias: bool=False, norm_op: Union[(None, Type[nn.Module])]=None, norm_op_kwargs: dict=N... |
class ShardedIterator(object):
def __init__(self, iterable, num_shards, shard_id, fill_value=None):
if ((shard_id < 0) or (shard_id >= num_shards)):
raise ValueError('shard_id must be between 0 and num_shards')
self._sharded_len = (len(iterable) // num_shards)
if ((len(iterable) ... |
def main(params):
imgs = json.load(open(params['input_json'], 'r'))
imgs = imgs['images']
seed(123)
vocab = build_vocab(imgs, params)
itow = {(i + 1): w for (i, w) in enumerate(vocab)}
wtoi = {w: (i + 1) for (i, w) in enumerate(vocab)}
(L, label_start_ix, label_end_ix, label_length) = encode... |
def test_assert_raises_on_assertthis_not_equals_dict_to_dict_substitutions():
context = Context({'k1': 'v1', 'k2': 'v2', 'assert': {'this': {'k1': 1, 'k2': [2, '{k1}'], 'k3': False}, 'equals': {'k1': 1, 'k2': [2, '{k2}'], 'k3': False}}})
with pytest.raises(AssertionError) as err_info:
assert_step.run_st... |
class SingleTagManager(object):
def __init__(self, descriptor, instance):
self.descriptor = descriptor
self.instance = instance
self.tag_model = self.descriptor.tag_model
self.field = self.descriptor.field
self.tag_options = self.descriptor.tag_options
self.changed = ... |
class CommunicationError(Exception):
def __init__(self, msg, source_exc=None):
self.msg = msg
self.source_exc = source_exc
def __str__(self):
s = self.msg
if (self.source_exc is not None):
s = ('SOURCE EXCEPTION:\n%s\n\n%s' % (traceback.format_exc(), s))
retur... |
def test_on_action_save(view, qtbot, imgfilename3x3, tmpdir):
item = BeePixmapItem(QtGui.QImage(imgfilename3x3))
view.scene.addItem(item)
view.scene.cancel_crop_mode = MagicMock()
view.filename = os.path.join(tmpdir, 'test.bee')
root = os.path.dirname(__file__)
shutil.copyfile(os.path.join(root,... |
def create_namespace_autoprune_policy(orgname, policy_config, create_task=False):
with db_transaction():
namespace = get_active_namespace_user_by_username(orgname)
namespace_id = namespace.id
if namespace_has_autoprune_policy(namespace_id):
raise NamespaceAutoPrunePolicyAlreadyEx... |
class _XGBoostEnv():
USE_SPREAD_STRATEGY: bool = True
PLACEMENT_GROUP_TIMEOUT_S: int = 100
STATUS_FREQUENCY_S: int = 30
ELASTIC_RESTART_DISABLED: bool = False
ELASTIC_RESTART_RESOURCE_CHECK_S: int = 30
ELASTIC_RESTART_GRACE_PERIOD_S: int = 10
COMMUNICATION_SOFT_PLACEMENT: bool = True
def... |
class _NetworkServer(pp.Server):
def __init__(self, ncpus='autodetect', interface='0.0.0.0', broadcast='255.255.255.255', port=None, secret=None, timeout=None, restart=False, proto=2, socket_timeout=3600, pid_file=None):
pp.Server.__init__(self, ncpus, (), secret, restart, proto, socket_timeout)
if ... |
def cdsd2df(fname, version='hitemp', cache=True, load_columns=None, verbose=True, drop_non_numeric=True, load_wavenum_min=None, load_wavenum_max=None, engine='pytables', output='pandas'):
metadata = {}
metadata['last_modification'] = time.ctime(getmtime(fname))
if (load_wavenum_min and load_wavenum_max):
... |
def canonicalize_vcf(input: PathType, output: PathType) -> None:
with open_vcf(input) as vcf:
info_field_names = _info_fields(vcf.raw_header)
w = Writer(str(output), vcf)
for v in vcf:
v = _reorder_info_fields(w, v, info_field_names)
w.write_record(v)
w.close(... |
class FilmCast(db.Model):
__tablename__ = 'film_cast'
film_id = Column(Integer, ForeignKey(Film.id, ondelete='CASCADE'), primary_key=True)
actor_id = Column(Integer, ForeignKey(Actor.id, ondelete='CASCADE'), key='id', primary_key=True)
actor = db.relationship(Actor)
film = db.relationship(Film) |
def _test():
import torch
pretrained = False
models = [msdnet22]
for model in models:
net = model(pretrained=pretrained)
net.eval()
weight_count = _calc_width(net)
print('m={}, {}'.format(model.__name__, weight_count))
assert ((model != msdnet22) or (weight_count ... |
class UserNominationsView(LoginRequiredMixin, TemplateView):
model = User
template_name = 'users/nominations_view.html'
def get_queryset(self):
return User.objects.select_related()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
elections = defa... |
('style.paragraph_format is the ParagraphFormat object for the style')
def then_style_paragraph_format_is_the_ParagraphFormat_object(context):
style = context.style
paragraph_format = style.paragraph_format
assert isinstance(paragraph_format, ParagraphFormat)
assert (paragraph_format.element is style.el... |
class IMBALANCECIFAR100(IMBALANCECIFAR10):
base_folder = 'cifar-100-python'
url = '
filename = 'cifar-100-python.tar.gz'
tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85'
train_list = [['train', '16019d7e3df5f24257cddd939b257f8d']]
test_list = [['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc']]
meta =... |
def test_filewritetoml_none_filewritetoml_raises():
context = Context({'k1': 'v1', 'fileWriteToml': None})
with pytest.raises(KeyInContextHasNoValueError) as err_info:
filewrite.run_step(context)
assert (str(err_info.value) == "context['fileWriteToml'] must have a value for pypyr.steps.filewritetoml... |
def clean_all():
migrations_dir = get_migrations_dir()
expected_dir = get_expected_dir()
if (not ((app_name in migrations_dir) and migrations_dir.endswith(migrations_name))):
raise ValueError(('Migrations dir has unexpected name: %s' % migrations_dir))
if os.path.isdir(migrations_dir):
s... |
def test_tags_update(tmpdir):
tiffname = str(tmpdir.join('foo.tif'))
with rasterio.open(tiffname, 'w', driver='GTiff', count=1, dtype=rasterio.uint8, width=10, height=10) as dst:
dst.update_tags(a='1', b='2')
dst.update_tags(1, c=3)
with pytest.raises(IndexError):
dst.update_... |
def mol_ok(mol):
try:
Chem.SanitizeMol(mol)
target_size = ((size_stdev * np.random.randn()) + average_size)
if ((mol.GetNumAtoms() > 5) and (mol.GetNumAtoms() < target_size)):
return True
else:
return False
except ValueError:
return False |
class ThriftPrometheusMetricsTests(GeventPatchedTestCase):
def reset_metrics(self, metrics):
if (not metrics):
return
try:
metrics.get_active_requests_metric().clear()
metrics.get_latency_seconds_metric().clear()
metrics.get_requests_total_metric().cle... |
def file_attr_cache(target_file, cache_dir='~/local/.cache/file_attr_cache'):
cache_dir_path = pathlib.Path(cache_dir).expanduser()
target_file_path = pathlib.Path(target_file).expanduser()
assert target_file_path.exists()
target_key = hashlib.md5(str(target_file_path.absolute()).encode()).hexdigest()
... |
class TestProfileFile():
def setup_method(self):
(self.yaml_fd, self.yaml_fname) = tempfile.mkstemp(suffix='.yaml')
(self.json_fd, self.json_fname) = tempfile.mkstemp(suffix='.json')
self.expected = {'predictors': [{'name': 'CommonNeighbours', 'displayname': 'Common neighbours'}, {'name': 'C... |
class PickleTest(mechanize._testcase.TestCase):
def test_pickle_cookie(self):
from mechanize._clientcookie import cookies_equal
cookiejar = mechanize.CookieJar()
url = '
request = mechanize.Request(url)
response = mechanize._response.test_response(headers=[('Set-Cookie', 'spa... |
def get_id(python=None, prefix=None, *, short=True):
if isinstance(python, str):
python = _pythoninfo.get_info(python)
data = [python.sys.executable, python.sys.version, python.sys.implementation.name.lower(), '.'.join((str(v) for v in python.sys.implementation.version)), str(python.sys.api_version), py... |
def code_block(code, strip_indent=4):
if strip_indent:
lines = ((i[strip_indent:] if (i[:strip_indent] == (' ' * strip_indent)) else i) for i in code.splitlines())
code = '\n'.join(lines)
code = code.strip('\n')
def run_code(code, scope):
with use_scope(scope):
exec(code,... |
def load_data(name, set_name, is_numpy, seqlist_path):
root = ('./datasets/%s' % name)
mvn_path = ('%s/train/mvn.pkl' % root)
seg_len = 20
Dataset = (NumpySegmentDataset if is_numpy else KaldiSegmentDataset)
dt_dset = Dataset(('%s/%s/feats.scp' % (root, set_name)), ('%s/%s/len.scp' % (root, set_name... |
def _system_of_equations_desoto(params, specs):
(Isc, Voc, Imp, Vmp, beta_oc, alpha_sc, EgRef, dEgdT, Tref, k) = specs
(IL, Io, Rs, Rsh, a) = params
y = [0, 0, 0, 0, 0]
y[0] = (((Isc - IL) + (Io * np.expm1(((Isc * Rs) / a)))) + ((Isc * Rs) / Rsh))
y[1] = (((- IL) + (Io * np.expm1((Voc / a)))) + (Voc... |
class Discriminator(nn.Module):
def __init__(self, input_size):
super(Discriminator, self).__init__()
self.linear_input = nn.Linear(input_size, 20)
self.leaky_relu = nn.LeakyReLU(0.2)
self.linear20 = nn.Linear(20, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, input: to... |
def print_exc(exc_info=None, context=None):
if (exc_info is None):
exc_info = sys.exc_info()
(etype, value, tb) = exc_info
if const.DEBUG:
string = ''.join(format_exception(etype, value, tb))
else:
text = ''.join(format_exception_only(etype, value))
try:
(file... |
.skipif((not config.cxx), reason='G++ not available, so we need to skip this test.')
def test_VMLinker_make_vm_cvm():
from pytensor.link.c.cvm import CVM
a = scalar()
linker = VMLinker(allow_gc=False, use_cloop=True)
f = function([a], a, mode=Mode(optimizer=None, linker=linker))
assert isinstance(f.... |
class PQMF(torch.nn.Module):
def __init__(self, device, subbands=4, taps=62, cutoff_ratio=0.15, beta=9.0):
super(PQMF, self).__init__()
h_proto = design_prototype_filter(taps, cutoff_ratio, beta)
h_analysis = np.zeros((subbands, len(h_proto)))
h_synthesis = np.zeros((subbands, len(h_... |
_safe
def build(context, prop):
verify_matgroup_attribute_for_object(context.object)
me = get_edit_mesh()
bm = bmesh.from_edit_mesh(me)
faces = [face for face in bm.faces if face.select]
if validate_balcony_faces(faces):
add_balcony_matgroups()
create_balcony(bm, faces, prop)
... |
def load_checkpoint(args, model, optimizer, scheduler):
logger.info("=> loading checkpoint '{}'".format(args.checkpoint_path))
checkpoint = torch.load(args.checkpoint_path, map_location='cpu')
model.load_state_dict(checkpoint['model'], strict=False)
logger.info("=> loaded successfully '{}' (epoch {})".f... |
def create_temp_files(temp_dir, prefix=1, empty=True):
temp_dir_path = temp_dir.name
with tempfile.NamedTemporaryFile(dir=temp_dir_path, delete=False, prefix=str(prefix), suffix='.txt') as f:
temp_file1_name = f.name
with open(temp_file1_name, 'w') as f1:
f1.write('abcdef')
with tempfile... |
def cloudflare_decode(encoded_string):
decoded = ''
r = int(encoded_string[:2], 16)
decoded = ''.join([chr((int(encoded_string[i:(i + 2)], 16) ^ r)) for i in range(2, len(encoded_string), 2)])
if decoded:
decoded = re.sub('(?:(?:injected)?~(?:0|\\()?(.+?)(?:1|~END)?)', '\\1', decoded)
return... |
class RedisConditionParser(BaseConditionParser):
def __init__(self) -> None:
super().__init__()
self.counter = 0
def build_condition(self, and_subfilters: Optional[List[QueryParamsTuple]], or_subfilters: Optional[List[QueryParamsTuple]]) -> Tuple[(str, Dict[(str, Any)])]:
(and_clauses, a... |
class Curric_Dataset(Dataset):
def __init__(self, root, txt, transform=None):
self.img_path = []
self.labels = []
self.transform = transform
with open(txt) as f:
for line in f:
self.img_path.append(os.path.join(root, line.split()[0]))
self.... |
class IMFSample(IMFAttributes, com.pIUnknown):
_methods_ = [('GetSampleFlags', com.STDMETHOD()), ('SetSampleFlags', com.STDMETHOD()), ('GetSampleTime', com.STDMETHOD()), ('SetSampleTime', com.STDMETHOD()), ('GetSampleDuration', com.STDMETHOD(POINTER(c_ulonglong))), ('SetSampleDuration', com.STDMETHOD(DWORD, IMFMedi... |
def assign_from_checkpoint(model_path, var_list, ignore_missing_vars=False):
grouped_vars = {}
if isinstance(var_list, (tuple, list)):
for var in var_list:
ckpt_name = get_variable_full_name(var)
if (ckpt_name not in grouped_vars):
grouped_vars[ckpt_name] = []
... |
class DTWAligner(object):
def __init__(self, dist=(lambda x, y: norm((x - y))), radius=1, verbose=0):
self.verbose = verbose
self.dist = dist
self.radius = radius
def transform(self, XY):
(X, Y) = XY
assert ((X.ndim == 3) and (Y.ndim == 3))
longer_features = (X if... |
class BattleCmdSet(default_cmds.CharacterCmdSet):
key = 'DefaultCharacter'
def at_cmdset_creation(self):
self.add(CmdFight())
self.add(CmdAttack())
self.add(CmdRest())
self.add(CmdPass())
self.add(CmdDisengage())
self.add(CmdCombatHelp())
self.add(CmdUse()... |
def set_tcs_debug_flag(tcs_addr):
string = read_from_memory((tcs_addr + 8), 4)
if (string == None):
return False
flag = struct.unpack('I', string)[0]
flag |= 1
gdb_cmd = ('set *(unsigned int *)%#x = %#x' % ((tcs_addr + 8), flag))
gdb.execute(gdb_cmd, False, True)
return True |
class Expression():
__slots__ = ('code',)
def __init__(self, code: types.CodeType) -> None:
self.code = code
def compile(self, input: str) -> 'Expression':
astexpr = expression(Scanner(input))
code: types.CodeType = compile(astexpr, filename='<pytest match expression>', mode='eval')
... |
class ModelWithTwoInputs(nn.Module):
def __init__(self):
super(ModelWithTwoInputs, self).__init__()
self.conv1_a = nn.Conv2d(1, 10, kernel_size=5)
self.maxpool1_a = nn.MaxPool2d(2)
self.relu1_a = nn.ReLU()
self.conv1_b = nn.Conv2d(1, 10, kernel_size=5)
self.maxpool1_b... |
def CUBfs(use_hd=True):
datasets = {}
num_elements = {}
folders_path = os.path.join(args.dataset_path, 'CUB_200_2011')
images_path = os.path.join(folders_path, 'CUB_200_2011', 'images')
list_files = os.listdir(images_path)
list_files.sort()
num_elements = {}
buffer = {'train': 0, 'val': ... |
class TestSet(abc.ABC):
known_solver_issues: Set[Tuple[(str, str)]]
known_solver_timeouts: Dict[(Tuple[(str, str, str)], float)]
solver_settings: Dict[(str, SolverSettings)]
tolerances: Dict[(str, Tolerance)]
def __iter__(self) -> Iterator[Problem]:
def description(self) -> str:
def sparse_o... |
class VolleyballDataset(data.Dataset):
def __init__(self, anns, tracks, frames, images_path, image_size, feature_size, num_boxes=12, num_before=4, num_after=4, is_training=True, is_finetune=False):
self.anns = anns
self.tracks = tracks
self.frames = frames
self.images_path = images_p... |
class HDF5ScpLoader(object):
def __init__(self, feats_scp, default_hdf5_path='feats'):
self.default_hdf5_path = default_hdf5_path
with open(feats_scp) as f:
lines = [line.replace('\n', '') for line in f.readlines()]
self.data = {}
for line in lines:
(key, valu... |
def parse_section(prefix: str, template: Options, set_strict_flags: Callable[([], None)], section: Mapping[(str, Any)], config_types: dict[(str, Any)], stderr: TextIO=sys.stderr) -> tuple[(dict[(str, object)], dict[(str, str)])]:
results: dict[(str, object)] = {}
report_dirs: dict[(str, str)] = {}
invalid_o... |
def test_broadcast_messages(gl, get_all_kwargs):
msg = gl.broadcastmessages.create({'message': 'this is the message'})
msg.color = '#444444'
msg.save()
msg_id = msg.id
msg = gl.broadcastmessages.list(**get_all_kwargs)[0]
assert (msg.color == '#444444')
msg = gl.broadcastmessages.get(msg_id)
... |
def setup_ansible_config(tmpdir, name, host, user, port, key):
items = [name, 'ansible_ssh_private_key_file={}'.format(key), 'ansible_ssh_common_args="-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o LogLevel=FATAL"', 'myvar=foo', 'ansible_host={}'.format(host), 'ansible_user={}'.format(user), 'ansibl... |
def _print_atts(func):
if (os.environ.get('CUSIGNAL_DEV_DEBUG') == 'True'):
print('name:', func.kernel.name)
print('max_threads_per_block:', func.kernel.max_threads_per_block)
print('num_regs:', func.kernel.num_regs)
print('max_dynamic_shared_size_bytes:', func.kernel.max_dynamic_sha... |
(reahl_system_fixture=ReahlSystemSessionFixture)
class ReahlSystemFixture(ContextAwareFixture):
def system_control(self):
return self.reahl_system_fixture.system_control
_up
def ensure_connected(self):
if (not self.system_control.connected):
self.system_control.connect()
def ... |
def get_hostname(config, method=None):
method = (method or config.get('hostname_method', 'smart'))
method = method.lower()
if (('hostname' in config) and (method != 'shell')):
return config['hostname']
if (method in get_hostname.cached_results):
return get_hostname.cached_results[method]... |
def D_Reg_BackProp(real_img, discriminator, args, d_optim):
real_img.requires_grad = True
real_pred = discriminator(real_img)
r1_loss = d_r1_loss(real_pred, real_img)
discriminator.zero_grad()
((((args.r1 / 2) * r1_loss) * args.d_reg_every) + (0 * real_pred[0])).backward()
d_optim.step()
ret... |
def gpt_get_estimated_cost(config, prompt, max_tokens):
prompt = prompt.replace('[APE]', '')
n_prompt_tokens = (len(prompt) // 4)
total_tokens = (n_prompt_tokens + max_tokens)
engine = config['gpt_config']['model'].split('-')[1]
costs_per_thousand = gpt_costs_per_thousand
if (engine not in costs... |
def command_init(args):
def setup(parser):
parser.add_option('--force', dest='force', action='store_true', help='overwrite existing files')
parser.add_option('--location', dest='location', metavar='LAT,LON', help='set scenario center location [deg]')
parser.add_option('--radius', dest='radiu... |
class InMemoryZip(object):
def __init__(self, filename):
self.in_memory_zip = io.BytesIO()
self.filename = filename
self.zf = zipfile.ZipFile(self.in_memory_zip, 'w', zipfile.ZIP_DEFLATED, True)
def append_str(self, filename_in_zip, file_contents):
zf = self.zf
zf.writest... |
def test_nested_for_with_continue() -> None:
src = '\n for i in range(10):\n for i in range(5):\n continue\n print(i - 1)\n continue\n print(i)\n '
cfg = build_cfg(src)
expected_blocks = [['range(10)'], ['i'], ['range(5)'], ['i'], ['continue'], ['print(i - 1)', 'cont... |
def plotXY(x, y, savename, log=False):
if (not isinstance(y[0], (list, np.ndarray))):
y = [y]
fig = plt.figure()
ax = fig.add_subplot(111)
for (i, y_) in enumerate(y):
(x, y_) = lists_to_arrays([x, y_])
if log:
y_ = np.log(y_)
ax.scatter(x, y_, s=1)
plt.sa... |
def test_fit(mol, vs, tmpdir):
with tmpdir.as_cwd():
assert (mol.atoms[1].aim.charge == (- 0.183627))
vs.run(molecule=mol)
assert (mol.extra_sites.n_sites == 2)
assert (mol.atoms[1].aim.charge != pytest.approx(float(mol.NonbondedForce[(1,)].charge)))
for atom in mol.atoms:
... |
def collect_textocr_info(root_path, annotation_filename, print_every=1000):
annotation_path = osp.join(root_path, annotation_filename)
if (not osp.exists(annotation_path)):
raise Exception(f'{annotation_path} not exists, please check and try again.')
annotation = mmcv.load(annotation_path)
img_i... |
class DepthDecoder(nn.Module):
def __init__(self, num_ch_enc, scales=range(4), num_output_channels=1, use_skips=True):
super(DepthDecoder, self).__init__()
self.num_output_channels = num_output_channels
self.use_skips = use_skips
self.upsample_mode = 'nearest'
self.scales = s... |
class LoginUI(UserInterface):
def assemble(self):
login_session = LoginSession.for_current_session()
if login_session.account:
logged_in_as = login_session.account.email
else:
logged_in_as = 'Guest'
home = self.define_view('/', title='Home')
home.set_s... |
def test_append_lines():
builder = CodeBuilder()
builder += 'line1'
builder += '\n line2\n line3\n '
assert (builder.string() == 'line1\nline2\nline3')
builder = CodeBuilder()
with builder:
builder += 'line1'
builder += '\n line2\n line3\n ... |
def _remove_dp(recv_dp, send_graph: DataPipeGraph, datapipe: DataPipe) -> None:
dp_id = id(datapipe)
for send_dp_id in send_graph:
if (send_dp_id == dp_id):
(send_dp, sub_send_graph) = send_graph[send_dp_id]
src_dp = list(sub_send_graph.values())[0][0]
_assign_attr(re... |
def patched_widget(monkeypatch):
monkeypatch.setitem(sys.modules, 'dbus_next.constants', Mockconstants('dbus_next.constants'))
from libqtile.widget import keyboardkbdd
reload(keyboardkbdd)
monkeypatch.setattr('libqtile.widget.keyboardkbdd.MessageType', Mockconstants.MessageType)
monkeypatch.setattr(... |
def generate_SBM100noise_parallel(num_samples, num_nodes, num_signals, graph_hyper, weighted, weight_scale):
n_cpu = (multiprocess.cpu_count() - 2)
pool = multiprocess.Pool(n_cpu)
(z_multi, W_multi) = zip(*pool.map(partial(_generate_SBM100noise_to_parallel, num_nodes=num_nodes, num_signals=num_signals, grap... |
def load_state_dict(checkpoint_path):
if (checkpoint_path and os.path.isfile(checkpoint_path)):
checkpoint = torch.load(checkpoint_path, map_location='cpu')
state_dict_key = 'state_dict'
if (state_dict_key in checkpoint):
new_state_dict = OrderedDict()
for (k, v) in c... |
def rnn_model_fn(features, labels, mode):
input_layer = tf.reshape(features['x'], [(- 1), maxlen])
y = tf.keras.layers.Embedding(max_features, 16).apply(input_layer)
y = tf.keras.layers.GlobalAveragePooling1D().apply(y)
y = tf.keras.layers.Dense(16, activation='relu').apply(y)
logits = tf.keras.laye... |
class BotName(TelegramObject):
__slots__ = ('name',)
def __init__(self, name: str, *, api_kwargs: Optional[JSONDict]=None):
super().__init__(api_kwargs=api_kwargs)
self.name: str = name
self._id_attrs = (self.name,)
self._freeze()
MAX_LENGTH: Final[int] = constants.BotNameLim... |
def dla34(pretrained=True, **kwargs):
model = DLA([1, 1, 1, 2, 2, 1], [16, 32, 64, 128, 256, 512], block=BasicBlock, **kwargs)
if pretrained:
model.load_pretrained_model(data='imagenet', name='dla34', hash='ba72cf86')
else:
print('Warning: No ImageNet pretrain!!')
return model |
class ResidualBlock(chainer.Chain):
def __init__(self, in_channels, out_channels):
super(ResidualBlock, self).__init__(res_branch2a=chainer.links.Convolution2D(in_channels, out_channels, (1, 9), pad=(0, 4), initialW=chainer.initializers.HeNormal()), bn_branch2a=chainer.links.BatchNormalization(out_channels)... |
def main():
tmp_dir = None
try:
tmp_dir = tempfile.mkdtemp(prefix='saga-test-', suffix=('-%s' % TEST_NAME), dir=os.path.expanduser('~/tmp'))
print(('tmpdir: %s' % tmp_dir))
ctx = saga.Context('x509')
ctx.user_proxy = '/Users/mark/proj/myproxy/xsede.x509'
session = saga.Se... |
class DataLoader():
def __init__(self, args):
self.args = args
self.base_dir = os.path.join(self.args.task_path, self.args.task)
self.did_to_dname = {0: 'cifar10', 1: 'cifar100', 2: 'mnist', 3: 'svhn', 4: 'fashion_mnist', 5: 'traffic_sign', 6: 'face_scrub', 7: 'not_mnist'}
def init_state... |
def test_alias_create_with_quoted_tokens(base_app):
alias_name = 'fake'
alias_command = 'help ">" "out file.txt" ";"'
create_command = f'alias create {alias_name} {alias_command}'
(out, err) = run_cmd(base_app, create_command)
assert (out == normalize("Alias 'fake' created"))
(out, err) = run_cm... |
def start_api_server(rpc_client: JSONRPCClient, config: RestApiConfig, eth_rpc_endpoint: str) -> APIServer:
api = RestAPI(rpc_client=rpc_client)
api_server = APIServer(rest_api=api, config=config, eth_rpc_endpoint=eth_rpc_endpoint)
api_server.start()
url = f'
print(f'''The Raiden API RPC server is n... |
class Migration(migrations.Migration):
dependencies = [('schedule', '0023_scheduleitem_status')]
operations = [migrations.AlterField(model_name='scheduleitem', name='status', field=models.CharField(choices=[('confirmed', 'Confirmed'), ('maybe', 'Maybe'), ('waiting_confirmation', 'Waiting confirmation'), ('cance... |
class LAV():
def __init__(self, slav):
self.head = None
self._slav = slav
self._len = 0
def from_polygon(cls, polygon, slav):
lav = cls(slav)
for (prev, point, next) in window(polygon):
lav._len += 1
vertex = LAVertex(point, LineSegment2(prev, poin... |
class PreCheckMessage():
def __init__(self, msg):
try:
import wx
app = wx.App(False)
wx.MessageBox(msg, 'Error', (wx.ICON_ERROR | wx.STAY_ON_TOP))
app.MainLoop()
except (KeyboardInterrupt, SystemExit):
raise
except:
pass... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.