code stringlengths 281 23.7M |
|---|
class DictElementLayer(Layer):
def __init__(self, incoming, key, name=None):
assert isinstance(incoming, DictLayer)
assert (key in incoming.keys())
self.input_layer = incoming
self.input_shape = incoming.output_shape
self.key = key
self.name = name
self.params... |
class NASNetALarge(nn.Module):
def __init__(self, num_classes=1000, in_chans=1, stem_size=96, channel_multiplier=2, num_features=4032, output_stride=32, drop_rate=0.0, global_pool='avg', pad_type='same'):
super(NASNetALarge, self).__init__()
self.num_classes = num_classes
self.stem_size = st... |
def instance_norm(input, name='instance_norm'):
with tf.variable_scope(name):
depth = input.get_shape()[3]
scale = tf.get_variable('scale', [depth], initializer=tf.random_normal_initializer(1.0, 0.02, dtype=tf.float32))
offset = tf.get_variable('offset', [depth], initializer=tf.constant_init... |
class ELF_KO_Test(unittest.TestCase):
(IS_FAST_TEST, 'fast test')
def test_demigod_m0hamed_x86(self):
checklist = []
_kernel_api(params={'format': STRING})
def __my_printk(ql: Qiling, address: int, params):
ql.log.info(f'my printk: params={params!r}')
checklist.ap... |
def create_tasks_from_benchmarks(benchmark_dict):
def version_of(dataset, language_pair):
if (language_pair[(- 2):] in ['zh', 'ja']):
return 1
return 0
return {f'{dataset}-{language_pair}': create_translation_task(dataset, language_pair, version_of(dataset, language_pair)) for (datas... |
class BM25Selector():
def __init__(self, source, target, index_name, num_proc=4, enable_rake=False):
self.source = source
self.target = target
self.num_proc = num_proc
global glob_data_source
glob_data_source = source
global glob_text_column_name
glob_text_col... |
class ProxyEnv(Env):
def __init__(self, wrapped_env):
self._wrapped_env = wrapped_env
self.action_space = self._wrapped_env.action_space
self.observation_space = self._wrapped_env.observation_space
def wrapped_env(self):
return self._wrapped_env
def reset(self, **kwargs):
... |
class MPRIS2(DBusProperty, DBusIntrospectable, MPRISObject):
BUS_NAME = 'org.mpris.MediaPlayer2.quodlibet'
PATH = '/org/mpris/MediaPlayer2'
ROOT_IFACE = 'org.mpris.MediaPlayer2'
ROOT_ISPEC = '\n<method name="Raise"/>\n<method name="Quit"/>'
ROOT_PROPS = '\n<property name="CanQuit" type="b" access="r... |
def spy_auto_quant(auto_quant: AutoQuant):
class Spy():
def __init__(self):
self._eval_manager = None
def get_all_ptq_results(self) -> List[PtqResult]:
if (self._eval_manager is None):
return []
return [sess.ptq_result for sess in self._eval_manage... |
class _IterableCursor():
def __init__(self, context):
self._context = context
async def _iterate(self):
if self._context.dialect.support_prepare:
prepared = (await self._context.cursor.prepare(self._context))
return prepared.iterate(*self._context.parameters[0], timeout=s... |
class TFResNetBasicLayer(tf.keras.layers.Layer):
def __init__(self, in_channels: int, out_channels: int, stride: int=1, activation: str='relu', **kwargs) -> None:
super().__init__(**kwargs)
should_apply_shortcut = ((in_channels != out_channels) or (stride != 1))
self.conv1 = TFResNetConvLaye... |
class TestPynagImporter(unittest.TestCase):
def setUp(self):
filename = tempfile.mktemp()
self.filename = filename
def tearDown(self):
if os.path.exists(self.filename):
os.remove(self.filename)
def test_parse_csv_string(self):
objects = importer.parse_csv_string(_... |
def parseEtree(inFileName, silence=False, print_warnings=True, mapping=None, reverse_mapping=None, nsmap=None):
parser = None
doc = parsexml_(inFileName, parser)
gds_collector = GdsCollector_()
rootNode = doc.getroot()
(rootTag, rootClass) = get_root_tag(rootNode)
if (rootClass is None):
... |
def make_layers(cfg, in_channels=3, batch_norm=False, dilation=1):
d_rate = dilation
layers = []
for v in cfg:
if (v == 'M'):
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=d_rate, dilation=d_rate)
... |
class ArgNamesPlugin(Plugin):
def get_function_hook(self, fullname: str) -> (Callable[([FunctionContext], Type)] | None):
if (fullname in {'mod.func', 'mod.func_unfilled', 'mod.func_star_expr', 'mod.ClassInit', 'mod.Outer.NestedClassInit'}):
return extract_classname_and_set_as_return_type_functi... |
class TestVaisalaGLD360TextFileHandler(unittest.TestCase):
def test_vaisala_gld360(self):
expected_power = np.array([12.3, 13.2, (- 31.0)])
expected_lat = np.array([30.5342, (- 0.5727), 12.1529])
expected_lon = np.array([(- 90.1152), 104.0688, (- 10.8756)])
expected_time = np.array([... |
class Interface():
def __init__(self, alignments, frames):
logger.debug('Initializing %s: (alignments: %s, frames: %s)', self.__class__.__name__, alignments, frames)
self.alignments = alignments
self.frames = frames
self.controls = self.set_controls()
self.state = self.set_st... |
class DataSaver(BaseLearner):
def __init__(self, learner: LearnerType, arg_picker: Callable) -> None:
self.learner = learner
self.extra_data: OrderedDict[(Any, Any)] = OrderedDict()
self.function = learner.function
self.arg_picker = arg_picker
def new(self) -> DataSaver:
... |
def test_list_build_sources():
with get_gitlab_trigger() as trigger:
sources = trigger.list_build_sources_for_namespace('someorg')
assert (sources == [{'last_updated': , 'name': 'someproject', 'url': ' 'private': True, 'full_name': 'someorg/someproject', 'has_admin_permissions': False, 'description'... |
class QiitaOAuth2TestIdentifiedByPermanentId(QiitaOAuth2Test):
def test_login(self):
self.strategy.set_settings({'SOCIAL_AUTH_QIITA_IDENTIFIED_BY_PERMANENT_ID': True})
user = self.do_login()
self.assertEqual(len(user.social), 1)
social = user.social[0]
self.assertEqual(social... |
class TestPreInstallCommands():
def test_default(self, isolation, isolated_data_dir, platform):
config = {'project': {'name': 'my_app', 'version': '0.0.1'}}
project = Project(isolation, config=config)
environment = MockEnvironment(isolation, project.metadata, 'default', project.config.envs['... |
def jsonable_encoder(obj: Any, include: Union[(SetIntStr, DictIntStrAny)]=None, exclude=None, by_alias: bool=True, skip_defaults: bool=None, exclude_unset: bool=True, exclude_none: bool=True):
if (hasattr(obj, 'json') or hasattr(obj, 'model_dump_json')):
return to_json(obj, include=include, exclude=exclude,... |
.parametrize('directory', ['demo', 'non-canonical-name'])
def test_search_for_directory_setup_with_base(provider: Provider, directory: str, fixture_dir: FixtureDirGetter) -> None:
dependency = DirectoryDependency('demo', (((fixture_dir('git') / 'github.com') / 'demo') / directory), base=(((fixture_dir('git') / 'git... |
_tf
class TFXLNetModelLanguageGenerationTest(unittest.TestCase):
def test_lm_generate_xlnet_base_cased(self):
model = TFXLNetLMHeadModel.from_pretrained('xlnet-base-cased')
input_ids = tf.convert_to_tensor([[67, 2840, 19, 18, 1484, 20, 965, 29077, 8719, 1273, 21, 45, 273, 17, 10, 15048, 28, 27511, 2... |
class ZipRunIterator(AbstractRunIterator):
def __init__(self, range_iterators):
self.range_iterators = range_iterators
def ranges(self, start, end):
try:
iterators = [i.ranges(start, end) for i in self.range_iterators]
(starts, ends, values) = zip(*[next(i) for i in itera... |
.end_to_end()
def test_task_function_with_partialed_args(tmp_path, runner):
source = '\n import pytask\n import functools\n\n def func(produces, content):\n produces.write_text(content)\n\n task_func = pytask.mark.produces("out.txt")(\n functools.partial(func, content="hello")\n )\n ... |
def _init_profile(profile: QWebEngineProfile) -> None:
profile.setter = ProfileSetter(profile)
profile.setter.init_profile()
_qute_scheme_handler.install(profile)
_req_interceptor.install(profile)
_download_manager.install(profile)
cookies.install_filter(profile)
if (notification.bridge is n... |
class Document():
def __init__(self, name: str):
self.elements = []
self.parent_builder = None
self.name = name
self._generated_html = None
def generate_html(self) -> str:
if (self._generated_html is not None):
return self._generated_html
env = templat... |
def greedyUpto(lit_str_):
patt1 = re.compile('(\\W)')
m1 = patt1.match(lit_str)
lit_str_ = patt1.sub(m1.group(0), lit_str_)
def gen(str_):
patt2 = re.compile((('^(.*)\\s*' + lit_str_) + '\\s*'))
m2 = patt2.match(str_)
if (m2 is not None):
matches = m2.group(0).strip()... |
def sample_system(sysc, Ts, method='zoh', alpha=None, prewarp_frequency=None, name=None, copy_names=True, **kwargs):
if (not isctime(sysc)):
raise ValueError('First argument must be continuous time system')
return sysc.sample(Ts, method=method, alpha=alpha, prewarp_frequency=prewarp_frequency, name=name... |
_filter('duplicate')
class DuplicateFilter(BaseFilter, FileManagerAware):
def __init__(self, _):
self.duplicates = self.get_duplicates()
def __call__(self, fobj):
return (fobj in self.duplicates)
def __str__(self):
return '<Filter: duplicate>'
def get_duplicates(self):
du... |
def save_plot_history(history, save_path, pickle_only=True):
print('saving history in pickle format...')
historyFile = (save_path + 'history.pickle')
try:
file_ = open(historyFile, 'wb')
pickle.dump(history, file_)
print('saved', historyFile)
except Exception as e:
print(... |
def imp_hash_table_ref_cont(ht, old, env, cont, _vals):
if (_vals.num_values() != 2):
raise SchemeException('hash-ref handler produced the wrong number of results')
(key, post) = _vals.get_all_values()
after = imp_hash_table_post_ref_cont(post, ht, old, env, cont)
return ht.hash_ref(key, env, af... |
def _create_independent_chains_initial_circuit(parameters: FermiHubbardParameters) -> cirq.Circuit:
layout = parameters.layout
initial = cast(IndependentChainsInitialState, parameters.initial_state)
up_circuit = _create_chain_initial_circuit(parameters, layout.up_qubits, initial.up)
down_circuit = _crea... |
def get_test_data(num_train=1000, num_test=500, input_shape=(10,), output_shape=(2,), classification=True, num_classes=2):
samples = (num_train + num_test)
if classification:
y = np.random.randint(0, num_classes, size=(samples,))
X = np.zeros(((samples,) + input_shape))
for i in range(sa... |
class UnpackTest(object):
def test_single_value(self):
(data, code, headers) = utils.unpack('test')
assert (data == 'test')
assert (code == 200)
assert (headers == {})
def test_single_value_with_default_code(self):
(data, code, headers) = utils.unpack('test', 500)
... |
def _init_representations():
global representations
if (sys.hexversion < ):
classobj = [(lambda c: ('classobj(%s)' % repr(c)))]
representations[types.ClassType] = classobj
instance = [(lambda f: ('instance(%s)' % repr(f.__class__)))]
representations[types.InstanceType] = instance... |
class RepublishTFStaticForRosbag():
def __init__(self):
self._tf_msg = TFMessage()
self._pub = rospy.Publisher('/tf_static_republished', TFMessage, queue_size=1, latch=True)
self._sub = rospy.Subscriber('/tf_static', TFMessage, self._sub_callback)
self._timer = rospy.Timer(rospy.Dura... |
class F37_TestCase(F14_TestCase):
def runTest(self):
F14_TestCase.runTest(self)
self.assert_parse('zfcp --devnum=1', 'zfcp --devnum=1\n')
self.assert_parse_error('zfcp --wwpn=2 --fcplun=3')
self.assert_parse_error('zfcp --devnum=1 --wwpn=2')
self.assert_parse_error('zfcp --de... |
.parametrize('given_actual_arguments, expected_messages', [({'FOO': None}, ['Expected argument "foo" is not in matched arguments [\'FOO\']']), ({'foo': 42}, ['Expected argument "foo" is of type "int" instead "str"']), ({'foo': 'foo'}, ['Expected argument "foo" with value "fooo" does not match value "foo"'])], ids=['Mis... |
def test_highlighted(qtbot):
doc = QTextDocument()
completiondelegate._Highlighter(doc, 'Hello', Qt.GlobalColor.red)
doc.setPlainText('Hello World')
edit = QTextEdit()
qtbot.add_widget(edit)
edit.setDocument(doc)
colors = [f.foreground().color() for f in doc.allFormats()]
assert (QColor(... |
def run_base_model_nfm(dfTrain, dfTest, folds, pnn_params):
fd = FeatureDictionary(dfTrain=dfTrain, dfTest=dfTest, numeric_cols=config.NUMERIC_COLS, ignore_cols=config.IGNORE_COLS)
data_parser = DataParser(feat_dict=fd)
(Xi_train, Xv_train, y_train) = data_parser.parse(df=dfTrain, has_label=True)
(Xi_te... |
class SequenceEntry(Channel):
def __init__(self, parent, number_of_channels, sequence_number):
super().__init__(parent, sequence_number)
self.number_of_channels = number_of_channels
self.length_values = [self.length_min, self.length_max]
self.loop_count_values = [self.loop_count_min,... |
class QuadraticExpression(QuadraticProgramElement):
def __init__(self, quadratic_program: Any, coefficients: Union[(ndarray, spmatrix, List[List[float]], Dict[(Tuple[(Union[(int, str)], Union[(int, str)])], float)])]) -> None:
super().__init__(quadratic_program)
self.coefficients = coefficients
... |
class TfEnv(ProxyEnv):
_property
def observation_space(self):
return to_tf_space(self.wrapped_env.observation_space)
_property
def action_space(self):
return to_tf_space(self.wrapped_env.action_space)
_property
def spec(self):
return EnvSpec(observation_space=self.observa... |
def fill_and_finalize_subplot(category, data_to_plot, accept_classes, axis, max_depth):
if (category == 'PR'):
create_PR_plot(axis, data_to_plot, accept_classes)
elif (category == 'AP'):
create_AP_plot(axis, data_to_plot, accept_classes, max_depth)
elif (category in ['Center_Dist', 'Size_Sim... |
def get_stack_info(frames, transformer=transform, capture_locals=True, frame_allowance=25):
__traceback_hide__ = True
result = []
for frame_info in frames:
if isinstance(frame_info, (list, tuple)):
(frame, lineno) = frame_info
else:
frame = frame_info
line... |
def _build_warm_up_scheduler(optimizer, epochs=50, last_epoch=(- 1)):
warmup_epoch = cfg.TRAIN.LR_WARMUP.EPOCH
sc1 = _build_lr_scheduler(optimizer, cfg.TRAIN.LR_WARMUP, warmup_epoch, last_epoch)
sc2 = _build_lr_scheduler(optimizer, cfg.TRAIN.LR, (epochs - warmup_epoch), last_epoch)
return WarmUPSchedule... |
class SpecificEquityTrades(object):
def __init__(self, trading_calendar, asset_finder, sids, start, end, delta, count=500):
self.trading_calendar = trading_calendar
self.count = count
self.start = start
self.end = end
self.delta = delta
self.sids = sids
self.g... |
def _is_valid_bn_fold(conv: LayerType, fold_backward: bool) -> bool:
valid = True
if (not fold_backward):
if isinstance(conv, (torch.nn.Conv2d, torch.nn.Conv1d, torch.nn.Conv3d)):
valid &= all(((item == 0) for item in conv.padding))
valid &= (conv.groups == 1)
elif isinst... |
def test_config_parsing_errors() -> None:
curr_dir = os.path.dirname(__file__)
config = os.path.join(curr_dir, 'file_fixtures', 'test_with_errors.pylintrc')
reporter = python_ta.reset_linter(config=config).reporter
message_ids = [msg.msg_id for message_lis in reporter.messages.values() for msg in messag... |
def run_worker(rank, world_size, num_gpus, train_loader, test_loader):
print(f'Worker rank {rank} initializing RPC')
rpc.init_rpc(name=f'trainer_{rank}', rank=rank, world_size=world_size)
print(f'Worker {rank} done initializing RPC')
run_training_loop(rank, num_gpus, train_loader, test_loader)
rpc.s... |
class DescribeColorFormat():
def it_knows_its_color_type(self, type_fixture):
(color_format, expected_value) = type_fixture
assert (color_format.type == expected_value)
def it_knows_its_RGB_value(self, rgb_get_fixture):
(color_format, expected_value) = rgb_get_fixture
assert (col... |
class MultiprocessingDriver():
def __init__(self):
self._memories = {}
def __reduce__(self):
return (rebuild_driver, tuple())
def _command(self, command, arg):
ipc = multiprocessing.current_process().ipc
return ipc.command(command, arg)
def get(self, memory_id):
i... |
def mouseRelease(widget, pos, button, modifier=None):
if isinstance(widget, QtWidgets.QGraphicsView):
widget = widget.viewport()
global_pos = QtCore.QPointF(widget.mapToGlobal(pos.toPoint()))
if (modifier is None):
modifier = QtCore.Qt.KeyboardModifier.NoModifier
event = QtGui.QMouseEven... |
def load_pretrained(model, url, filter_fn=None, strict=True):
if (not url):
logging.warning('Pretrained model URL is empty, using random initialization. Did you intend to use a `tf_` variant of the model?')
return
state_dict = load_state_dict_from_url(url, progress=False, map_location='cpu')
... |
('/convert', methods=['GET', 'POST'])
def convert():
jinja2_env = Environment()
custom_filters = get_custom_filters()
app.logger.debug(('Add the following customer filters to Jinja environment: %s' % ', '.join(custom_filters.keys())))
jinja2_env.filters.update(custom_filters)
try:
jinja2_tpl... |
def test_window_by_position():
ds = simulate_genotype_call_dataset(n_variant=5, n_sample=3, seed=0)
assert (not has_windows(ds))
ds['variant_position'] = (['variants'], np.array([1, 4, 6, 8, 12]))
ds = window_by_position(ds, size=5, window_start_position='variant_position')
assert has_windows(ds)
... |
class DictProperty(object):
def __init__(self, attr, key=None, read_only=False):
(self.attr, self.key, self.read_only) = (attr, key, read_only)
def __call__(self, func):
functools.update_wrapper(self, func, updated=[])
(self.getter, self.key) = (func, (self.key or func.__name__))
... |
def run_cmd(cmd, throw_on_error=True, env=None, stream_output=False, **kwargs):
cmd_env = os.environ.copy()
if env:
cmd_env.update(env)
if stream_output:
child = subprocess.Popen(cmd, env=cmd_env, **kwargs)
exit_code = child.wait()
if (throw_on_error and (exit_code != 0)):
... |
def get_gpu_memory_info(device, unit='G', number_only=False):
device = get_device_index(device, optional=True)
handler = pynvml.nvmlDeviceGetHandleByIndex(device)
meminfo = pynvml.nvmlDeviceGetMemoryInfo(handler)
total = num_to_str(meminfo.total, unit, number_only=number_only)
used = num_to_str(memi... |
class TimedStorage(Generic[(KeyType, ValueType)]):
frozen = False
def __init__(self, maxsize: Optional[int]=None):
self.maxsize = (maxsize or float('inf'))
self.data: Dict[(KeyType, ValueWithExpiration[ValueType])] = dict()
self.expiration_heap: List[HeapEntry[KeyType]] = []
self... |
def prompt_user_for_input_game_log(window: QtWidgets.QWidget) -> (Path | None):
from randovania.layout.layout_description import LayoutDescription
return _prompt_user_for_file(window, caption='Select a Randovania seed log.', filter=f'Randovania Game, *.{LayoutDescription.file_extension()}', new_file=False) |
def test_top_down_OCHuman_dataset_compatibility():
dataset = 'TopDownOCHumanDataset'
dataset_class = DATASETS.get(dataset)
dataset_class.load_annotations = MagicMock()
dataset_class.coco = MagicMock()
channel_cfg = dict(num_output_channels=17, dataset_joints=17, dataset_channel=[[0, 1, 2, 3, 4, 5, 6... |
class SingleDataset(Dataset):
def __init__(self, anom_idx, x, y, data_selector, transform=None):
self.transform = transform
self.selected_data = data_selector.get_data(anom_idx, x, y)
def __getitem__(self, index):
data = self.selected_data[0][index]
target = self.selected_data[1]... |
def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot, ValueError=ValueError, dict=dict, float=float, GeneratorType=GeneratorType, id=id, int=int, isinstance=isinstance, list=list, long=int, str=str, tuple=tuple):
def _iterencode_list... |
.parametrize('env_id', ENV_IDS)
def test_envs(env_id):
OBS_MODES = ['state_dict', 'state', 'rgbd', 'pointcloud']
for obs_mode in OBS_MODES:
env: BaseEnv = gym.make(env_id, obs_mode=obs_mode)
env.reset()
action_space = env.action_space
for _ in range(5):
env.step(actio... |
.parametrize('base,other', [pytest.param(Version.parse('3.0.0'), Version.parse('3.0.0-1'), id='post'), pytest.param(Version.parse('3.0.0'), Version.parse('3.0.0+local.1'), id='local')])
def test_allows_post_releases_with_min(base: Version, other: Version) -> None:
range = VersionRange(min=base, include_min=True)
... |
class Agilent34450A(Instrument):
BOOLS = {True: 1, False: 0}
MODES = {'current': 'CURR', 'ac current': 'CURR:AC', 'voltage': 'VOLT', 'ac voltage': 'VOLT:AC', 'resistance': 'RES', '4w resistance': 'FRES', 'current frequency': 'FREQ:ACI', 'voltage frequency': 'FREQ:ACV', 'continuity': 'CONT', 'diode': 'DIOD', 'te... |
class MultigroupProperty(bpy.types.PropertyGroup, ArrayGetSet, SizeOffsetGetSet):
arch: PointerProperty(type=ArchProperty)
array: PointerProperty(type=ArrayProperty)
size_offset: PointerProperty(type=SizeOffsetProperty)
panel_fill_door: PointerProperty(type=FillPanel)
louver_fill_door: PointerProper... |
class MemMinionIfcFL(Interface):
def construct(s, read=None, write=None, amo=None):
s.read = CalleeIfcFL(method=read)
s.write = CalleeIfcFL(method=write)
s.amo = CalleeIfcFL(method=amo)
def __str__(s):
return f'r{s.read}|w{s.write}|a{s.amo}'
def connect(s, other, parent):
... |
def cos_sim(a, b):
if (not isinstance(a, torch.Tensor)):
a = torch.tensor(a)
if (not isinstance(b, torch.Tensor)):
b = torch.tensor(b)
if (len(a.shape) == 1):
a = a.unsqueeze(0)
if (len(b.shape) == 1):
b = b.unsqueeze(0)
a_norm = torch.nn.functional.normalize(a, p=2, ... |
()
('tab', value=cmdutils.Value.cur_tab)
('position', completion=miscmodels.inspector_position)
def devtools(tab: apitypes.Tab, position: apitypes.InspectorPosition=None) -> None:
try:
tab.private_api.toggle_inspector(position)
except apitypes.InspectorError as e:
raise cmdutils.CommandError(e) |
class BaseDataPreparing(object):
def __init__(self, vocab_file, slot_file, config, pretrained_embedding_file=None, word_embedding_file=None, word_seq_embedding_file=None, load_w2v_embedding=True, load_word_embedding=True, gen_new_data=False, is_inference=False):
self.gen_new_data = gen_new_data
self... |
def knn_point(k, xyz1, xyz2):
b = xyz1.get_shape()[0].value
n = xyz1.get_shape()[1].value
c = xyz1.get_shape()[2].value
m = xyz2.get_shape()[1].value
xyz1 = tf.tile(tf.reshape(xyz1, (b, 1, n, c)), [1, m, 1, 1])
xyz2 = tf.tile(tf.reshape(xyz2, (b, m, 1, c)), [1, 1, n, 1])
dist = tf.reduce_sum... |
def make_grouped_dataset(dir):
images = []
assert os.path.isdir(dir), ('%s is not a valid directory' % dir)
fnames = sorted(os.walk(dir, followlinks=True))
for fname in sorted(fnames):
paths = []
root = fname[0]
for f in sorted(fname[2]):
if is_image_file(f):
... |
def setUpModule():
global mol, mf, mycc
mol = gto.Mole()
mol.verbose = 7
mol.output = '/dev/null'
mol.atom = [[8, (0.0, 0.0, 0.0)], [1, (0.0, (- 0.757), 0.587)], [1, (0.0, 0.757, 0.587)]]
mol.basis = '631g'
mol.build()
mf = scf.RHF(mol)
mf.kernel()
mycc = qcisd.QCISD(mf)
mycc... |
def get_labeled_data(pos_pos, pos_neg, neg_pos, neg_neg, total, train_s):
x_train = []
x_test = []
for x in pos_pos[:train_s]:
x_train.append((x, 1, 1))
for x in pos_pos[train_s:total]:
x_test.append((x, 1, 1))
for x in pos_neg[:train_s]:
x_train.append((x, 1, 0))
for x i... |
.parametrize(('max_workers', 'cpu_count', 'side_effect', 'expected_workers'), [(None, 3, None, 7), (3, 4, None, 3), (8, 3, None, 7), (None, 8, NotImplementedError(), 5), (2, 8, NotImplementedError(), 2), (8, 8, NotImplementedError(), 5)])
def test_executor_should_be_initialized_with_correct_workers(tmp_venv: VirtualEnv... |
def convert_examples_to_features(examples, tokenizer, max_seq_length, is_training):
features = []
for (example_index, example) in tqdm(enumerate(examples)):
context_tokens = tokenizer.tokenize(example.context_sentence)
start_ending_tokens = tokenizer.tokenize(example.start_ending)
choice... |
def find_structure_handler(a: Attribute, type: Any, c: BaseConverter, prefer_attrs_converters: bool=False) -> (Callable[([Any, Any], Any)] | None):
if ((a.converter is not None) and prefer_attrs_converters):
handler = None
elif ((a.converter is not None) and (not prefer_attrs_converters) and (type is no... |
class CacheControlMixin():
cache_timeout = 60
def get_cache_timeout(self):
return self.cache_timeout
def dispatch(self, *args, **kwargs):
response = super().dispatch(*args, **kwargs)
patch_response_headers(response, self.get_cache_timeout())
return response |
def timeConversion(time):
if ((time[(- 2):] == 'AM') and (time[:2] == '12')):
return ('00' + time[2:(- 2)])
elif (time[(- 2):] == 'AM'):
return time[:(- 2)]
elif ((time[(- 2):] == 'PM') and (time[:2] == '12')):
return time[:(- 2)]
else:
return (str((int(time[:2]) + 12)) +... |
class TransformerEncoderBlock(nn.Sequential):
def __init__(self, emb_size=225, drop_p=0.5, 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 _make_transport(endpoint: config.EndpointConfiguration) -> TSocket:
if (endpoint.family == socket.AF_INET):
trans = TSocket(*endpoint.address)
elif (endpoint.family == socket.AF_UNIX):
trans = TSocket(unix_socket=endpoint.address)
else:
raise Exception(f'unsupported endpoint fami... |
def spladder(options):
options = settings.parse_args(options)
if (not options.no_reset_conf):
options = settings.set_confidence_level(options)
fn_out_merge = get_filename('fn_out_merge', options)
fn_out_merge_val = get_filename('fn_out_merge_val', options)
_prep_workdir(options)
options ... |
def draw_record(record, save_path):
for (key, value) in record.items():
fig = plt.figure(figsize=(12, 6))
ball_round = np.arange(len(record[key]))
plt.title(f'{key} loss')
plt.xlabel('Ball round')
plt.ylabel('Loss')
plt.grid()
plt.bar(ball_round, record[key])
... |
def openqa_collate(samples):
if (len(samples) == 0):
return {}
input_ids = collate_tokens([s['input_ids'] for s in samples], 0)
start_masks = torch.zeros(input_ids.size())
for (b_idx, s) in enumerate(samples):
for _ in s['start']:
if (_ != (- 1)):
start_masks[... |
def main(epsilon):
dis = load_model()
dis.eval()
loader = make_dataset()
correct_real = 0
correct_label = 0
total = 0
for (i, (x_real, y_real)) in enumerate(loader):
if (i == 100):
break
(x_real, y_real) = (x_real.cuda(), y_real.cuda())
(v_y_real, v_x_real... |
class MixedArguments():
def __init__(self, pyname, arguments, scope):
self.pyname = pyname
self.args = arguments
def get_pynames(self, parameters):
return ([self.pyname] + self.args.get_pynames(parameters[1:]))
def get_arguments(self, parameters):
result = []
for pyna... |
class GaussianDiffusion():
def __init__(self, *, betas, model_mean_type, model_var_type, loss_type):
self.model_mean_type = model_mean_type
self.model_var_type = model_var_type
self.loss_type = loss_type
betas = np.array(betas, dtype=np.float64)
self.betas = betas
ass... |
class DHT(mp.Process):
_node: DHTNode
def __init__(self, initial_peers: Optional[Sequence[Union[(Multiaddr, str)]]]=None, *, start: bool, p2p: Optional[P2P]=None, daemon: bool=True, num_workers: int=DEFAULT_NUM_WORKERS, record_validators: Iterable[RecordValidatorBase]=(), shutdown_timeout: float=3, await_ready:... |
class CalcChangeLocalDroneMutationCommand(wx.Command):
def __init__(self, fitID, position, mutation, oldMutation=None):
wx.Command.__init__(self, True, 'Change Local Drone Mutation')
self.fitID = fitID
self.position = position
self.mutation = mutation
self.savedMutation = old... |
class Laplace(Radial):
def _call_impl(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
(x, y) = (self._rescale(x), self._rescale(y))
return torch.exp((- torch.sqrt(pdist2(x, y))))
def string_id(self):
return f'Laplace[{self._scale_str}]'
def effective_dim(self, x) -> float:
... |
class Canvas(Component):
def Update(self, loop):
for descendant in self.transform.GetDescendants():
comp = descendant.GetComponent(GuiComponent)
if (comp is not None):
rectTransform = descendant.GetComponent(RectTransform)
rect = (rectTransform.GetRect... |
def default_evaluation_params():
return {'AREA_RECALL_CONSTRAINT': 0.8, 'AREA_PRECISION_CONSTRAINT': 0.4, 'EV_PARAM_IND_CENTER_DIFF_THR': 1, 'MTYPE_OO_O': 1.0, 'MTYPE_OM_O': 0.8, 'MTYPE_OM_M': 1.0, 'GT_SAMPLE_NAME_2_ID': 'gt_img_([0-9]+).txt', 'DET_SAMPLE_NAME_2_ID': 'res_img_([0-9]+).txt', 'CRLF': False} |
class SubState():
def __init__(self, act, prob_state, all_state, curr_handcards_char, last_cards_value, last_category):
self.act = act
self.prob_state = prob_state
self.all_state = all_state
self.finished = False
self.mode = (MODE.PASSIVE_DECISION if (self.act == ACT_TYPE.PAS... |
class TimeoutHTTPAdapter(HTTPAdapter):
def __init__(self, *args, **kwargs):
self.timeout = 0
if ('timeout' in kwargs):
self.timeout = kwargs['timeout']
del kwargs['timeout']
super().__init__(*args, **kwargs)
def send(self, request, **kwargs):
timeout = kwa... |
def getConfig():
parser = argparse.ArgumentParser()
parser.add_argument('action', choices=('train', 'test'))
parser.add_argument('--dataset', metavar='DIR', default='bird', help='name of the dataset')
parser.add_argument('--image-size', '-i', default=512, type=int, metavar='N', help='image size (default... |
class Writer(SummaryWriter):
def __init__(self, logdir, sample_rate=16000):
super(Writer, self).__init__(logdir)
self.sample_rate = sample_rate
self.logdir = logdir
def logging_loss(self, losses, step):
for key in losses:
self.add_scalar('{}'.format(key), losses[key],... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.