code stringlengths 281 23.7M |
|---|
def forward_step(model, inputs, labels, criterion):
(tweet_input_ids, gif_inputs, gif_ids) = inputs
if opt.use_gpu:
tweet_input_ids = tweet_input_ids.cuda()
gif_inputs = [i.cuda() for i in gif_inputs]
labels = labels.cuda()
score = model(tweet_input_ids, gif_inputs)
loss = ((crit... |
class rpctouch(scan):
def __init__(self, job, timeout=60):
scan.__init__(self, job)
if (len(job) > 1):
self.port = job[0].split('|')[1]
self.scan_type = _whats_your_name()
self.timeout = timeout
def execute_scan(self, verbose):
redir_cmd = scan.gettunnel(self,... |
class ArchiveTestingMixin():
def assertArchiveMembers(self, archive_filepath, root_dir, expected):
archive_filepath = str(archive_filepath)
root_dir = str(root_dir)
with zipfile.ZipFile(archive_filepath, mode='r') as zf:
observed = set(zf.namelist())
expected = {((root_di... |
class MLPFunction(Parameterized, Serializable):
def __init__(self, name, input_pls, hidden_layer_sizes, output_nonlinearity=None):
Parameterized.__init__(self)
Serializable.quick_init(self, locals())
self._name = name
self._input_pls = input_pls
self._layer_sizes = (list(hidd... |
def run_evaluation(labelmap, groundtruth, detections, exclusions):
(categories, class_whitelist) = read_labelmap(labelmap)
logging.info('CATEGORIES (%d):\n%s', len(categories), pprint.pformat(categories, indent=2))
excluded_keys = read_exclusions(exclusions)
pascal_evaluator = object_detection_evaluatio... |
class TestVersion():
def test_bot_api_version_and_info(self):
assert (__bot_api_version__ is constants.BOT_API_VERSION)
assert (__bot_api_version_info__ is constants.BOT_API_VERSION_INFO)
def test_version_and_info(self):
assert (__version__ == str(__version_info__))
.parametrize(('ve... |
def create_exp_dir(path, scripts_to_save=None):
if (not os.path.exists(path)):
os.makedirs(path)
print('Experiment dir : {}'.format(path))
if (scripts_to_save is not None):
os.mkdir(os.path.join(path, 'scripts'))
for script in scripts_to_save:
dst_file = os.path.join(path... |
def from_numpy(array, dtype, scope=None, device: str=''):
scope = (scope or Scope.default)
device = (device or scope.device)
if (isinstance(array, ma.core.MaskedArray) and (array.ndim == 1)):
return _from_numpy_ma(array.data, array.mask, dtype, scope, device)
elif (isinstance(array, np.ndarray) ... |
class ExplicitNamespacePackageFinder(ImportlibFinder):
def find_module(self, modname: str, module_parts: Sequence[str], processed: list[str], submodule_path: (Sequence[str] | None)) -> (ModuleSpec | None):
if processed:
modname = '.'.join([*processed, modname])
if (util.is_namespace(modn... |
class MemTimer(Process):
def __init__(self, monitor_pid, interval, pipe, backend, max_usage=False, *args, **kw):
self.monitor_pid = monitor_pid
self.interval = interval
self.pipe = pipe
self.cont = True
self.backend = backend
self.max_usage = max_usage
self.n_... |
def perform_qat(config: argparse.Namespace):
data_pipeline = ImageNetDataPipeline(config)
input_shape = (image_net_config.dataset['image_width'], image_net_config.dataset['image_height'], image_net_config.dataset['image_channels'])
tf.keras.backend.clear_session()
tf_config = tf.ConfigProto()
tf_con... |
class VGG(nn.Module):
def __init__(self, num_classes=10, depth=16, dropout=0.0, number_net=4):
super(VGG, self).__init__()
self.inplances = 64
self.number_net = number_net
self.conv1 = nn.Conv2d(3, self.inplances, kernel_size=3, padding=1)
self.bn1 = nn.BatchNorm2d(self.inpla... |
def get_article(article_id: str, links: bool=False, url: str=URL) -> str:
articles = _feed(url).entries
try:
article = articles[int(article_id)]
except (IndexError, ValueError):
max_id = (len(articles) - 1)
msg = f'Unknown article ID, use ID from 0 to {max_id}'
raise SystemEx... |
def add_footer(finished_epoch, merged_filename):
print('Adding footer')
nmap_footer = f'<runstats><finished time="{finished_epoch}" timestr="" elapsed="" summary="" exit="success"/></runstats>'
nmap_footer += '</nmaprun>'
with open(merged_filename, 'a') as fh:
fh.write(nmap_footer) |
class TestLayers():
def setup_class(self):
torch.manual_seed(5)
self.Cin = 3
self.Hin = 224
self.Win = 224
self.batch_size = 4
self.use_gpu = False
self.IMAGE = torch.rand((self.batch_size, self.Cin, self.Hin, self.Win))
self.softmax = torch.nn.Softmax... |
class XcelIfcCL2FLAdapter(Component):
def recv_rdy(s):
return (s.entry is None)
def recv(s, msg):
assert (s.entry is None)
s.entry = msg
def construct(s, ReqType, RespType):
s.left = XcelMinionIfcCL(ReqType, RespType, req=s.recv, req_rdy=s.recv_rdy)
s.right = XcelMast... |
class CarliniL2():
def __init__(self, sess, model, image_size, num_channels, num_labels, batch_size=100, confidence=L2_CONFIDENCE, targeted=L2_TARGETED, learning_rate=L2_LEARNING_RATE, binary_search_steps=L2_BINARY_SEARCH_STEPS, max_iterations=L2_MAX_ITERATIONS, abort_early=L2_ABORT_EARLY, initial_const=L2_INITIAL_... |
class Migration(migrations.Migration):
dependencies = [('companies', '0001_initial')]
operations = [migrations.AlterField(model_name='company', name='about_markup_type', field=models.CharField(max_length=30, choices=[('', '--'), ('html', 'HTML'), ('plain', 'Plain'), ('markdown', 'Markdown'), ('restructuredtext'... |
class AddressBookPage(HTML5Page):
def __init__(self, view):
super().__init__(view)
self.body.use_layout(Container())
layout = ResponsiveLayout('md', colour_theme='dark', bg_scheme='primary')
navbar = Navbar(view, css_id='my_nav').use_layout(layout)
navbar.layout.set_brand_tex... |
def get_enabled_activation_quantizers(sim: QuantizationSimModel) -> List[TensorQuantizer]:
enabled_activation_quantizers = []
for quant_wrapper in sim.quant_wrappers():
for quantizer in quant_wrapper.input_quantizers:
if quantizer.is_enabled():
enabled_activation_quantizers.a... |
class MyStringList(UserList[str]):
data: List[str]
def __init__(self, strings: List[str]):
self.data = strings
def __getitem__(self, index: int) -> str:
return self.data[index]
def __setitem__(self, index: int, item: str) -> str:
oldString = self.data[index]
self.data[ind... |
def test_editable_wheel_src_module(copy_sample):
td = copy_sample('module3')
make_wheel_in((td / 'pyproject.toml'), td, editable=True)
whl_file = (td / 'module3-0.1-py2.py3-none-any.whl')
assert_isfile(whl_file)
with unpack(whl_file) as unpacked:
pth_path = Path(unpacked, 'module3.pth')
... |
.parametrize('max_labels,expected', [(10, [0.0, '', 2.0, '', 4.0, '', 6.0, '', 8.0, '', 10.0, '']), (5, [0.0, '', '', 3.0, '', '', 6.0, '', '', 9.0, '', '']), (3, [0.0, '', '', '', 4.0, '', '', '', 8.0, '', '', ''])])
def test_max_labels_step(max_labels, expected):
colorbar = cm.StepColormap((['red', 'blue'] * 5), ... |
def validator(func: Callable[(..., Any)]):
(func)
def wrapper(*args: Any, **kwargs: Any):
try:
return (True if func(*args, **kwargs) else ValidationError(func, _func_args_as_dict(func, *args, **kwargs)))
except Exception as exp:
return ValidationError(func, _func_args_as_... |
def typed_dict_get_signature_callback(ctx: MethodSigContext) -> CallableType:
signature = ctx.default_signature
if (isinstance(ctx.type, TypedDictType) and (len(ctx.args) == 2) and (len(ctx.args[0]) == 1) and isinstance(ctx.args[0][0], StrExpr) and (len(signature.arg_types) == 2) and (len(signature.variables) =... |
def make_commitment_output_to_local_witness_script(revocation_pubkey: bytes, to_self_delay: int, delayed_pubkey: bytes) -> bytes:
script = bfh(construct_script([opcodes.OP_IF, revocation_pubkey, opcodes.OP_ELSE, to_self_delay, opcodes.OP_CHECKSEQUENCEVERIFY, opcodes.OP_DROP, delayed_pubkey, opcodes.OP_ENDIF, opcode... |
def KPbands(material, host_material, return_edges_only=False, plot_result=False, t=0, p=(np.pi / 2), fraction=0.2, points=50, vin=None):
Delta = material.spin_orbit_splitting
Eg = material.band_gap
Ev0 = material.valence_band_offset
Ec0 = (material.valence_band_offset + Eg)
a0 = material.lattice_con... |
def generate_random_search_bash(model_name, data_name, task_num, bash_save_path='../fb_jobs/'):
if os.path.exists(bash_save_path):
remove_all_files(bash_save_path)
if (bash_save_path and (not os.path.exists(bash_save_path))):
os.makedirs(bash_save_path)
search_space = HypeParameterSpace(mode... |
def test_lane():
lane = xodr.Lane()
lane._set_lane_id(1)
lane.add_userdata(xodr.UserData('key', 'value'))
prettyprint(lane.get_element())
lane = xodr.Lane(xodr.LaneType.driving, 1, 1, 1, 1, 2)
lane._set_lane_id(1)
prettyprint(lane.get_element())
lane2 = xodr.Lane(xodr.LaneType.driving, 1... |
def test_ConnectionState_keepalive_protocol_switch_interaction() -> None:
cs = ConnectionState()
cs.process_client_switch_proposal(_SWITCH_UPGRADE)
cs.process_event(CLIENT, Request)
cs.process_keep_alive_disabled()
cs.process_event(CLIENT, Data)
assert (cs.states == {CLIENT: SEND_BODY, SERVER: S... |
def test_first_last_marks(item_names_for):
tests_content = '\n import pytest\n\n .order("last")\n def test_1(): pass\n\n .order("first")\n def test_2(): pass\n\n def test_3(): pass\n '
assert (item_names_for(tests_content) == ['test_2', 'test_3', 'test_1']) |
class Input(Widget):
def __init__(self, input_type='', default_value='', *args, **kwargs):
if ('_class' not in kwargs):
kwargs['_class'] = input_type
super(Input, self).__init__(*args, **kwargs)
self.type = 'input'
self.attributes['value'] = str(default_value)
sel... |
class SubGraphView(object):
def __init__(self, inside_ops=(), passthrough_ts=()):
inside_ops = util.make_list_of_op(inside_ops)
passthrough_ts = util.make_list_of_t(passthrough_ts)
ops_and_ts = (inside_ops + passthrough_ts)
if ops_and_ts:
self._graph = util.get_unique_gra... |
.usefixtures('needs_assert_rewrite')
def test_assert_called_kwargs_with_introspection(mocker: MockerFixture) -> None:
stub = mocker.stub()
complex_kwargs = dict(foo={'bar': 1, 'baz': 'spam'})
wrong_kwargs = dict(foo={'goo': 1, 'baz': 'bran'})
stub(**complex_kwargs)
stub.assert_called_with(**complex_... |
class DisplayNotebook(ttk.Notebook):
def __init__(self, parent):
logger.debug('Initializing %s', self.__class__.__name__)
super().__init__(parent)
parent.add(self)
tk_vars = get_config().tk_vars
self.wrapper_var = tk_vars['display']
self.runningtask = tk_vars['running... |
def test_dependency_constraints_file(tmp_path, build_frontend_env):
if (utils.platform == 'linux'):
pytest.skip("linux doesn't pin individual tool versions, it pins manylinux images instead")
project_dir = (tmp_path / 'project')
project_with_expected_version_checks.generate(project_dir)
tool_ver... |
class DistributionFinder(MetaPathFinder):
class Context():
name = None
def __init__(self, **kwargs):
vars(self).update(kwargs)
def path(self) -> List[str]:
return vars(self).get('path', sys.path)
def find_distributions(self, context=Context()) -> Iterable[Distribu... |
class SEResNetBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, groups, reduction, stride=1, downsample=None):
super(SEResNetBlock, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, padding=1, stride=stride, bias=False)
self.bn1 = nn.BatchNorm2d(... |
class TimedLoop(BlockingLoop):
def __init__(self, hyperparams):
self._hp = self._default_hparams()
self._override_defaults(hyperparams)
super(TimedLoop, self).__init__(hyperparams)
def _default_hparams(self):
default_dict = AttrDict(ask_confirmation=True, absolute_grasp_action=Tr... |
def test_flicker_hhd13():
flicker = parse(',00')
assert (flicker.version == HHD_VERSION_13)
assert (flicker.lc == 29)
assert (flicker.startcode.data == '')
assert (flicker.de1.data == '')
assert (flicker.de2.data == '15,00')
assert (flicker.de3.data is None)
assert (flicker.render() == '... |
class StickSlipOscillator(DynSys):
def _t(self, v):
return (((self.t0 * np.sign(v)) - (self.alpha * v)) + (self.beta * (v ** 3)))
def _rhs(x, v, th, t, a, alpha, b, beta, eps, gamma, t0, vs, w):
tq = (((t0 * np.sign((v - vs))) - (alpha * v)) + (beta * ((v - vs) ** 3)))
xdot = v
v... |
class Logger(object):
def __init__(self, path):
self.logger = logging.getLogger()
self.path = path
self.setup_file_logger()
print('Logging to file: ', self.path)
def setup_file_logger(self):
hdlr = logging.FileHandler(self.path, 'w+')
self.logger.addHandler(hdlr)
... |
def parse_paths(x: (Any | None)) -> (list[Path] | None):
if (x is None):
return None
if isinstance(x, str):
msg = f"""Specifying paths as a string in 'pyproject.toml' is deprecated and will result in an error in v0.5. Please use a list of strings instead: ["{x}"]."""
warnings.warn(msg, c... |
def info_nce(query, positive_key, negative_keys=None, temperature=0.1, reduction='mean', negative_mode='unpaired'):
if (query.dim() != 2):
raise ValueError('<query> must have 2 dimensions.')
if (positive_key.dim() != 2):
raise ValueError('<positive_key> must have 2 dimensions.')
if (negative... |
class ChannetDwsConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride, groups=1, dropout_rate=0.0):
super(ChannetDwsConvBlock, self).__init__()
self.dw_conv = dwconv3x3(in_channels=in_channels, out_channels=in_channels, stride=stride)
self.pw_conv = channet_conv1x1(in_ch... |
class TestSEVIRICalibrationAlgorithm(unittest.TestCase):
def setUp(self):
self.algo = SEVIRICalibrationAlgorithm(platform_id=PLATFORM_ID, scan_time=datetime(2020, 8, 15, 13, 0, 40))
def test_convert_to_radiance(self):
result = self.algo.convert_to_radiance(COUNTS_INPUT, GAIN, OFFSET)
xr.... |
class G4FHandler(LLMHandler):
def __init__(self, settings, path, llm):
self.history = []
self.prompts = []
self.key = 'g4f'
self.settings = settings
self.llm = llm
self.path = path
def send_message(self, window, message):
self.history.append({'User': 'User... |
('/update/view_domain', methods=['POST'])
_params([dict(name='rooms', type=dict, required=False, nullable=False), dict(name='domain_name', type=str, required=True, nullable=False), dict(name='cnames', type=dict, required=False, nullable=False)], need_username=True)
_wrapper_json
_web_opration_log('update_view_domain', ... |
class Test_threaded(unittest.TestCase):
def test_line_reader(self):
class TestLines(serial.threaded.LineReader):
def __init__(self):
super(TestLines, self).__init__()
self.received_lines = []
def handle_line(self, data):
self.received_l... |
.script
def _batch_detection(batch_size: int, class_out, box_out, anchor_boxes, indices, classes, img_scale: Optional[torch.Tensor]=None, img_size: Optional[torch.Tensor]=None):
batch_detections = []
for i in range(batch_size):
img_scale_i = (None if (img_scale is None) else img_scale[i])
img_si... |
def _get_config_directory():
try:
repo_dpath = dirname(dirname(__file__))
except NameError:
import mmseg
repo_dpath = dirname(dirname(mmseg.__file__))
config_dpath = join(repo_dpath, 'configs')
if (not exists(config_dpath)):
raise Exception('Cannot find config path')
... |
def train(epoch, criterion_list, optimizer):
train_loss = 0.0
train_loss_cls = 0.0
train_loss_div = 0.0
train_loss_kd = 0.0
correct = ([0] * args.num_branches)
total = ([0] * args.num_branches)
lr = adjust_lr(optimizer, epoch)
start_time = time.time()
criterion_cls = criterion_list[0... |
class VersionField(SemVerField):
default_error_messages = {'invalid': _('Enter a valid version number in X.Y.Z format.')}
description = _('Version')
def __init__(self, *args, **kwargs):
self.partial = kwargs.pop('partial', False)
if self.partial:
warnings.warn('Use of `partial=Tr... |
class PrimaryBroadcastToEdges(PrimaryBroadcast):
def __init__(self, child, broadcast_domain, name=None):
name = (name or 'broadcast to edges')
super().__init__(child, broadcast_domain, name)
self.broadcast_type = 'primary to edges'
def _evaluates_on_edges(self, dimension):
return... |
class TestHyperCubic(QiskitNatureTestCase):
def test_init(self):
size = (2, 2, 2)
edge_parameter = ((1.0 + 1j), 0.0, ((- 2.0) - 2j))
onsite_parameter = 5.0
boundary_condition = (BoundaryCondition.OPEN, BoundaryCondition.PERIODIC, BoundaryCondition.OPEN)
hyper_cubic = HyperCub... |
class Conv4(nn.Module):
def __init__(self):
super(Conv4, self).__init__()
builder = get_builder()
self.convs = nn.Sequential(builder.conv3x3(3, 64, first_layer=True), nn.ReLU(), builder.conv3x3(64, 64), nn.ReLU(), nn.MaxPool2d((2, 2)), builder.conv3x3(64, 128), nn.ReLU(), builder.conv3x3(128... |
def advance_iter_and_group_samples(train_iterator, num_samples, max_seq_length):
num_total_tokens = (max_seq_length * num_samples)
samples = defaultdict(list)
i = 0
while (i < num_total_tokens):
tokenized_samples = next(train_iterator)
i += len(tokenized_samples['input_ids'])
sam... |
def test_handler_bad_request(mocker):
mock_dynamic_configuration(mocker, MOCKED_SCHEMA)
response = call_create_order(generate_api_gw_event({'order_item_count': 5}))
assert (response['statusCode'] == HTTPStatus.BAD_REQUEST)
body_dict = json.loads(response['body'])
assert (body_dict == {'error': 'inva... |
_test
def test_locallyconnected_2d():
num_samples = 5
filters = 3
stack_size = 4
num_row = 6
num_col = 8
padding = 'valid'
for strides in [(1, 1), (2, 2)]:
layer_test(local.LocallyConnected2D, kwargs={'filters': filters, 'kernel_size': 3, 'padding': padding, 'kernel_regularizer': 'l2... |
class BarFactory(factory.Factory):
foo = factory.SubFactory(FooFactory)
def _create(cls, model_class: type[Bar], foo: Foo) -> Bar:
assert (foo.value == foo.expected)
bar: Bar = super()._create(model_class, foo=foo)
foo.bar = bar
return bar
class Meta():
model = Bar |
class TransformLayer(nn.Module):
def __init__(self, transform_type, in_dim, out_dim, hidden_dim=None):
super(TransformLayer, self).__init__()
if (transform_type == 'linear'):
self.module = LinearTransform(in_dim, out_dim)
elif (transform_type == 'conv'):
self.module =... |
class RPCTransformer(RPCTransformerBase, GDALTransformerBase):
def __init__(self, rpcs, **rpc_options):
if (not isinstance(rpcs, (RPC, dict))):
raise ValueError('RPCTransformer requires RPC')
super().__init__(rpcs, **rpc_options)
def __repr__(self):
return '<{} RPCTransformer... |
class Directory(entry.Entry):
def __init__(self, api, adaptor):
self._cpi_nsentry = super(Directory, self)
self._cpi_nsentry.__init__(api, adaptor)
def init_instance(self, url, flags, session):
pass
def init_instance_async(self, url, flags, session):
pass
def change_dir(s... |
def test_sha256_secrethash():
assert (sha256_secrethash(Secret(b'')) == b"\xe3\xb0\xc4B\x98\xfc\x1c\x14\x9a\xfb\xf4\xc8\x99o\xb9$'\xaeA\xe4d\x9b\x93L\xa4\x95\x99\x1bxR\xb8U")
assert (sha256_secrethash(Secret(b'a')) == b'\xca\x97\x81\x12\xca\x1b\xbd\xca\xfa\xc21\xb3\x9a#\xdcM\xa7\x86\xef\xf8\x14|Nr\xb9\x80w\x85\... |
def test_func_cyclic_invalid():
class Top(ComponentLevel2):
def construct(s):
s.a = Wire(Bits32)
s.b = Wire(Bits32)
s.c = Wire(Bits32)
def assignc(a, b):
s.c = a
assign(a, b)
def assignb(a, b):
s.b = ... |
def main():
global args, best_prec
use_gpu = torch.cuda.is_available()
args.device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
print(args.device)
print('=> Building model...')
model = None
model = models.__dict__[args.arch](bit=args.bit)
net = models.__dict__[args.ar... |
def test_derived_projected_crs():
wkt = 'DERIVEDPROJCRS["derived projectedCRS",\n BASEPROJCRS["WGS 84 / UTM zone 31N",\n BASEGEOGCRS["WGS 84",\n DATUM["World Geodetic System 1984",\n ELLIPSOID["WGS 84",6378137,298.,\n LENGTHUNIT["metre",1]]],\n PRIME... |
class ModelWithSharedParameter(nn.Module):
def __init__(self):
super(ModelWithSharedParameter, self).__init__()
self.embedding = nn.Embedding(1000, 200)
self.FC1 = nn.Linear(200, 200)
self.FC2 = nn.Linear(200, 200)
self.FC2.weight = nn.Parameter(self.FC1.weight)
self.... |
class AIPSW():
def __init__(self, df, exposure, outcome, selection, generalize=True, weights=None):
self.df = df.copy()
self.sample = (df[selection] == 1)
self.target = (df[selection] == 0)
self.generalize = generalize
self.exposure = exposure
self.outcome = outcome
... |
def setup(parser):
parser.add_squirrel_selection_arguments()
parser.add_squirrel_query_arguments()
parser.add_argument('--channel-priorities', dest='channel_priorities', metavar='CHA', help='\nList of 2-character band/instrument code combinations to try. For example,\ngiving ```HH,BH``` would first try to g... |
class IterationTimeLoggerTest(unittest.TestCase):
def test_iteration_time_logger_test_on_train_step_end(self) -> None:
logger = MagicMock(spec=TensorBoardLogger)
logger.writer = MagicMock(spec=SummaryWriter)
state = MagicMock(spec=State)
recorded_durations = {'train_iteration_time': ... |
class TimeBudgetRetryPolicy(RetryPolicy):
def __init__(self, policy: RetryPolicy, budget: float):
assert (budget >= 0), 'The time budget must not be negative.'
self.subpolicy = policy
self.budget = budget
def yield_attempts(self) -> Iterator[Optional[float]]:
start_time = time.ti... |
def migrate_tests_in_file(file_path: str) -> None:
try:
with open(file_path, 'r+') as fd:
content = fd.read()
new_content = MIGRATE_REGEX.sub('\\(\\2)\\ndef \\1():\\n pass\\n', content)
if (new_content != content):
new_content = (new_content.rstrip('\n'... |
def get_argparser():
parser = argparse.ArgumentParser(prog='DermoSegDiff', description='DermoSegDiff: A Boundary-aware Segmentation Diffusion Model for Skin Lesion Delineation', epilog='')
parser.add_argument('-c', '--config_file', type=str, required=True, help='')
parser.add_argument('-n', '--model_name', ... |
def main():
if (len(sys.argv) != 2):
print(('Usage: %s <expected-python-version>' % sys.argv[0]))
exit(1)
expected_impl = None
expected_major = None
expected_minor = None
expected_version_string = sys.argv[1]
match = re.match('^(\\d+)\\.(\\d+)$', expected_version_string)
if (... |
(id='run_python', name='Run a Python script', description='Run a specified Python script', outputs={'success': RunPythonFileOutput, 'error': RunPythonFileError})
def run_python_file(params: RunPythonFileInput) -> typing.Tuple[(str, typing.Union[(RunPythonFileOutput, RunPythonFileError)])]:
run_results = subprocess.... |
(scope='session')
def vcr_config():
def remove_headers(response: dict):
response['headers'] = {}
return response
return {'filter_headers': [('authorization', 'secret_...'), ('user-agent', None), ('cookie', None)], 'before_record_response': remove_headers, 'match_on': ['method', 'remove_page_id_f... |
class DE():
def __init__(self, lde_len):
self.length = 0
self.lde = 0
self.lde_length = lde_len
self.encoding = None
self.data = None
def parse(self, data, version):
self.version = version
if (not data):
return data
self.lde = int(data[... |
def delete_migrated_content(apps, schema_editor):
Release = apps.get_model('downloads', 'Release')
Page = apps.get_model('pages', 'Page')
db_alias = schema_editor.connection.alias
releases = Release.objects.using(db_alias).filter(release_page__isnull=True, content__startswith=MARKER)
for release in ... |
class SaltBackend(base.BaseBackend):
HAS_RUN_SALT = True
NAME = 'salt'
def __init__(self, host: str, *args: Any, **kwargs: Any):
self.host = host
self._client: Optional[salt.client.LocalClient] = None
super().__init__(self.host, *args, **kwargs)
def client(self) -> salt.client.Lo... |
class TestCreateCursor(EndianTest):
def setUp(self):
self.req_args_0 = {'back_blue': 49245, 'back_green': 35528, 'back_red': 27716, 'cid': , 'fore_blue': 55026, 'fore_green': 62740, 'fore_red': 58690, 'mask': , 'source': , 'x': 48400, 'y': 36047}
self.req_bin_0 = b']\x00\x08\x00~\xdfr`\x1c\x15\xec1J... |
class SimpleSchedulePass(BasePass):
def __call__(self, top):
if (not hasattr(top._dag, 'all_constraints')):
raise PassOrderError('all_constraints')
top._sched = PassMetadata()
self.schedule_intra_cycle(top)
self.schedule_ff(top)
self.schedule_posedge_flip(top)
... |
class BaseSubModel(pybamm.BaseModel):
def __init__(self, param, domain=None, name='Unnamed submodel', external=False, options=None, phase=None):
super().__init__(name)
self.domain = domain
self.name = name
self.external = external
if ((options is None) or (type(options) == di... |
def sidexside_plot(df1, df2, col, cmap, supt, subt1, subt2, figsize=(12, 12)):
sub_args = {'gridspec_kw': {'width_ratios': [1, 0.86]}, 'figsize': figsize}
(fig, arr) = matplotlib.pyplot.subplots(1, 2, **sub_args)
arc_args = {'column': col, 'cmap': cmap, 'lw': 6, 'alpha': 0.9, 'legend': True}
for (ar, df... |
class Effect4135(BaseEffect):
runTime = 'early'
type = ('projected', 'passive')
def handler(fit, beacon, context, projectionRange, **kwargs):
fit.ship.boostItemAttr('shieldEmDamageResonance', beacon.getModifiedItemAttr('shieldEmDamageResistanceBonus'), stackingPenalties=True, **kwargs) |
class Tol_matrix():
def __init__(self, *tuples, prototype='atomic', factor=1.0):
f = factor
self.prototype = prototype
if (prototype == 'atomic'):
f *= 0.5
attrindex = 5
self.radius_type = 'covalent'
elif (prototype == 'molecular'):
att... |
def transform_dictionary_comprehension(builder: IRBuilder, o: DictionaryComprehension) -> Value:
d = builder.maybe_spill(builder.call_c(dict_new_op, [], o.line))
loop_params = list(zip(o.indices, o.sequences, o.condlists, o.is_async))
def gen_inner_stmts() -> None:
k = builder.accept(o.key)
... |
def _update_grant(graphql_client, grant, **kwargs):
query = '\n mutation updateGrant($input: UpdateGrantInput!){\n updateGrant(input: $input) {\n __typename\n\n ... on Grant {\n id\n }\n\n ... on GrantErrors {\n errors {\n ... |
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward... |
class GumballMachine():
soldOutState: State
noQuarterState: State
hasQuarterState: State
soldState: State
state: State
count: int = 0
def __init__(self, numberGumballs: int):
self.soldOutState = SoldOutState(self)
self.noQuarterState = NoQuarterState(self)
self.hasQua... |
class Effect3417(BaseEffect):
type = 'passive'
def handler(fit, ship, context, projectionRange, **kwargs):
fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Large Projectile Turret')), 'damageMultiplier', ship.getModifiedItemAttr('eliteBonusViolatorsRole1'), **kwargs) |
def regional_task(population_grid_points, transport_network, departure_datetime):
import r5py
regional_task = r5py.RegionalTask(transport_network, population_grid_points.at[(1, 'geometry')], population_grid_points, departure=departure_datetime)
(yield regional_task)
del regional_task
time.sleep(0.5)... |
class SampleBuffer(object):
def __init__(self, size):
self.idx_to_slot = np.empty(shape=[size], dtype=int)
self.slot_to_idx = np.empty(shape=[size], dtype=int)
self.count = 0
self.clear()
return
def clear(self):
self.idx_to_slot.fill(MathUtil.INVALID_IDX)
... |
def node_home(caller):
text = '\n The |cHome|n location of an object is often only used as a backup - this is where the object\n will be moved to if its location is deleted. The home location can also be used as an actual\n home for characters to quickly move back to.\n\n If unset, the g... |
def gumbel_softmax_conditional_sample(logits, temperature, one_hot_z, eps=1e-20, detach=False):
U = torch.rand(logits.shape).to(device)
log_U = torch.log((U + eps))
log_U_k = (one_hot_z * log_U).sum(dim=(- 1), keepdim=True)
if detach:
logits = logits.detach()
gumbel_conditional_sample = (- t... |
class WSGISOAPHandler(object):
def __init__(self, dispatcher):
self.dispatcher = dispatcher
def __call__(self, environ, start_response):
return self.handler(environ, start_response)
def handler(self, environ, start_response):
if (environ['REQUEST_METHOD'] == 'GET'):
retur... |
def pytask_execute_log_end(session: Session, reports: list[ExecutionReport]) -> bool:
session.execution_end = time.time()
counts = count_outcomes(reports, TaskOutcome)
if session.config['show_traceback']:
console.print()
if counts[TaskOutcome.FAIL]:
console.rule(Text('Failures', ... |
class SourceHandlerMixin():
tables: List[Union[(Path, SubQuery, Table)]]
columns: List[Column]
union_barriers: List[Tuple[(int, int)]]
def end_of_query_cleanup(self, holder: SubQueryLineageHolder) -> None:
for (i, tbl) in enumerate(self.tables):
holder.add_read(tbl)
self.unio... |
.skipif((not torch.cuda.is_available()), reason='The test requires GPUs to run.')
.gpu_only
.usefixtures('toggle_batching')
.parametrize('src_sharding_type', _sharding_types())
.parametrize('dst_sharding_type', _sharding_types())
.parametrize('use_async', [True, False])
_with_pet(nproc=2)
def test_torchrec(src_sharding... |
class Collection():
def __init__(self, name='molecules'):
self.name = name
self._data = {}
self.filename = op.join(op.dirname(__file__), (name + '.json'))
with open(self.filename, 'r') as f:
self.content = json.load(f)
def __getitem__(self, name):
self._read(n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.