code stringlengths 281 23.7M |
|---|
def test_get_and_putfield():
hdr = bytearray(_segyio.thsize())
with pytest.raises(BufferError):
_segyio.getfield('.', 0)
with pytest.raises(TypeError):
_segyio.getfield([], 0)
with pytest.raises(TypeError):
_segyio.putfield({}, 0, 1)
with pytest.raises(KeyError):
_seg... |
def board_remove_moderator(board: BoardModel, moderator: ModeratorModel):
with session() as s:
bm = s.query(BoardModeratorOrmModel).filter_by(board_id=board.id, moderator_id=moderator.id).one_or_none()
if (not bm):
raise ArgumentError(MESSAGE_BOARD_NOT_ADDED)
s.delete(bm)
... |
.parametrize('MeshClass', [UnitIcosahedralSphereMesh, UnitCubedSphereMesh])
def test_helmholtz_mixed_sphere_lowestorder(MeshClass):
errors = [run_helmholtz_mixed_sphere(MeshClass, r, 1, 0) for r in range(2, 5)]
errors = np.asarray(errors)
l2conv = np.log2((errors[:(- 1)] / errors[1:]))
assert (l2conv > ... |
class OptionPlotoptionsScatter3dStates(Options):
def hover(self) -> 'OptionPlotoptionsScatter3dStatesHover':
return self._config_sub_data('hover', OptionPlotoptionsScatter3dStatesHover)
def inactive(self) -> 'OptionPlotoptionsScatter3dStatesInactive':
return self._config_sub_data('inactive', Opt... |
class FaqTypeList(ResourceList):
def query(self, view_kwargs):
query_ = self.session.query(FaqType)
query_ = event_query(query_, view_kwargs)
return query_
view_kwargs = True
methods = ['GET']
schema = FaqTypeSchema
data_layer = {'session': db.session, 'model': FaqType, 'meth... |
def draw_nodebox(box, name='', properties=None, node_id=None, searched_by=None, style=None):
properties = {k: v for (k, v) in (properties or {}).items() if (not (k.startswith('_') or (k == 'seq')))}
return ['nodebox', box, name, properties, (node_id or []), (searched_by or []), (style or {})] |
def mean_equality_hypothesis_test(sample_mean: torch.Tensor, true_mean: torch.Tensor, true_std: torch.Tensor, sample_size: torch.Tensor, p_value: int):
'Test for the null hypothesis that the mean of a Gaussian\n distribution is within the central 1 - alpha confidence\n interval (CI) for a sample of size sampl... |
def get_kernel(coordinate_system, field):
kernels = {'cartesian': {'potential': kernel_potential_cartesian, 'g_z': kernel_g_z_cartesian, 'g_northing': kernel_g_northing_cartesian, 'g_easting': kernel_g_easting_cartesian, 'g_ee': kernel_g_ee_cartesian, 'g_nn': kernel_g_nn_cartesian, 'g_zz': kernel_g_zz_cartesian, 'g... |
class Immutable(metaclass=ImmutableMeta):
def __new__(*args, **kwargs):
cls = args[0]
(args, kwargs) = cls._canonicalize(*args, **kwargs)
return cls._new(*args[1:], tuple(sorted(kwargs.items())))
def __reduce__(self):
return (self.__class__._new, self._args)
def __hash__(self... |
class OptionPlotoptionsTimelineSonificationDefaultspeechoptionsMappingPitch(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get('undefined')
def mapTo(self, t... |
class IntVarSymbolTestCase(unittest.TestCase):
def test_add(self):
var1 = IntVar(values=[1, 256], name='var_1')
sym1 = var1.symbolic_value()
var2 = IntVar(values=[1, 256], name='var_2')
sym2 = var2.symbolic_value()
imm1 = IntImm(value=37)
imm2 = IntImm(value=41)
... |
class TlsPrivateKeysResponse(ModelComposed):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
lazy_impo... |
.xfail(strict=True)
.parametrize('dfsr_filename', ['dfsr-depth-dir-down.lis.part', 'dfsr-depth-dir-up.lis.part'])
def test_depth_mode_1_direction_no_match(tmpdir, merge_lis_prs, dfsr_filename):
fpath = os.path.join(str(tmpdir), 'depth-dir-no-data-match.lis')
content = ((headers + [('data/lis/records/curves/' + ... |
class OptionPlotoptionsBellcurveDatalabels(Options):
def align(self):
return self._config_get('center')
def align(self, text: str):
self._config(text, js_type=False)
def allowOverlap(self):
return self._config_get(False)
def allowOverlap(self, flag: bool):
self._config(fl... |
class Validators(Enums):
def required(self):
self._add_value()
return self
def unique(self):
self._add_value()
return self
def integer(self):
self._add_value()
return self
def float(self):
self._add_value()
return self
def numeric(self)... |
class AccessTokenDatabase(Protocol, Generic[AP]):
async def get_by_token(self, token: str, max_age: Optional[datetime]=None) -> Optional[AP]:
...
async def create(self, create_dict: Dict[(str, Any)]) -> AP:
...
async def update(self, access_token: AP, update_dict: Dict[(str, Any)]) -> AP:
... |
def fortios_log_syslogd3(data, fos):
fos.do_member_operation('log.syslogd3', 'setting')
if data['log_syslogd3_setting']:
resp = log_syslogd3_setting(data, fos)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'log_syslogd3_setting'))
return ((not is_successful_status(resp)), (i... |
class OptionPlotoptionsSolidgaugeSonificationDefaultspeechoptionsMapping(Options):
def pitch(self) -> 'OptionPlotoptionsSolidgaugeSonificationDefaultspeechoptionsMappingPitch':
return self._config_sub_data('pitch', OptionPlotoptionsSolidgaugeSonificationDefaultspeechoptionsMappingPitch)
def playDelay(se... |
class ManageCasesTool(Tool):
def __init__(self, config: ErtConfig, notifier, ensemble_size: int):
self.notifier = notifier
self.ert_config = config
self.ensemble_size = ensemble_size
super().__init__('Manage cases', QIcon('img:build_wrench.svg'))
def trigger(self):
case_m... |
def disassemble(reader, data_offset_begin, data_offset_end, data_begin, data_end, code_begin, code_end):
length = file_size(reader)
call0 = {}
data_pointers = {}
code_pointers = {}
while (reader.tell() < length):
address = reader.tell()
if (data_offset_begin <= address < data_offset_... |
class DrQV2Learner(core.Learner):
def __init__(self, random_key: jax_types.PRNGKey, dataset: Iterator[reverb.ReplaySample], networks: drq_v2_networks.DrQV2Networks, sigma_schedule: optax.Schedule, augmentation: augmentations.DataAugmentation, policy_optimizer: optax.GradientTransformation, critic_optimizer: optax.G... |
def connect_fragments_ahlrichs(cdm, fragments, atoms, min_dist_scale=1.1, scale=1.2, avoid_h=False, logger=None):
atoms = [atom.lower() for atom in atoms]
if (len(fragments) > 1):
log(logger, f'Detected {len(fragments)} fragments. Generating interfragment bonds.')
dist_mat = squareform(cdm)
frag... |
def extractAnonanemoneWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('tmpw', "The Man's Perfect Wife", 'translated'), ('DS', 'Doppio Senso', 'translated'), ('loy',... |
class TimeMap():
def __init__(self):
self.track = {}
def set(self, key: str, value: str, timestamp: int) -> None:
if (key not in self.track):
self.track[key] = []
self.track[key].append((timestamp, value))
def get(self, key: str, timestamp: int) -> str:
if (key no... |
class ImportWorkerManager(WorkerManager):
worker_prefix = 'import_worker'
def start_task(self, worker_id, task):
command = ['copr-distgit-process-import', '--daemon', '--build-id', str(task.build_id), '--worker-id', worker_id]
self.log.info('running worker: %s', ' '.join(command))
self.s... |
def test_find_peaks_raises_exception_with_min_peak_height_not_being_int_type():
data = np.random.randint(0, 10, 100)
with pytest.raises(TypeError):
scared.signal_processing.find_peaks(data, 1, 'foo')
with pytest.raises(TypeError):
scared.signal_processing.find_peaks(data, 1, None)
with p... |
class ValveLogger():
def __init__(self, logger, dp_id, dp_name):
self.logger = logger
self.dp_id = dp_id
self.dp_name = dp_name
def _dpid_prefix(self, log_msg):
return ' '.join((valve_util.dpid_log(self.dp_id), self.dp_name, log_msg))
def debug(self, log_msg):
self.lo... |
class AIWrapper():
cache_path_root: str = '.cache'
extra_kwargs = {'cache_seed', 'filter_func', 'allow_format_str_template', 'context', 'llm_model'}
def __init__(self, llm_client: LLMClient, output_parser: Optional[BaseOutputParser]=None):
self.llm_echo = False
self.model_cache_enable = Fals... |
class UvicornWorker(Worker):
CONFIG_KWARGS: Dict[(str, Any)] = {'loop': 'auto', ' 'auto'}
def __init__(self, *args: Any, **kwargs: Any) -> None:
super(UvicornWorker, self).__init__(*args, **kwargs)
logger = logging.getLogger('uvicorn.error')
logger.handlers = self.log.error_log.handlers
... |
class OptionPlotoptionsArearangeSonificationContexttracksMappingLowpassResonance(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, tex... |
def compile_type_def(table_name, table) -> Sql:
assert isinstance(table_name, Id)
assert (table <= T.table)
db = get_db()
posts = []
pks = []
columns = []
pks = {join_names(pk) for pk in table.options.get('pk', [])}
for (name, c) in flatten_type(table):
if ((name in pks) and (c <... |
('ecs_deploy.cli.get_client')
def test_deploy_runtime_platform_with_previous_value(get_client, runner):
get_client.return_value = EcsTestClient('acces_key', 'secret_key')
result = runner.invoke(cli.deploy, (CLUSTER_NAME, SERVICE_NAME, '--runtime-platform', 'ARM64', 'WINDOWS'))
expected_runtime_platform = {u... |
def test_epoch_insta_finalize_logs(tester, concise_casper, casper_epoch_filter, new_epoch):
start_epoch = concise_casper.START_EPOCH()
new_epoch()
new_epoch()
logs = casper_epoch_filter.get_new_entries()
assert (len(logs) == 4)
log_old = logs[(- 2)]['args']
log_new = logs[(- 1)]['args']
... |
class StringRewriteMaskingStrategy(MaskingStrategy):
name = 'string_rewrite'
configuration_model = StringRewriteMaskingConfiguration
def __init__(self, configuration: StringRewriteMaskingConfiguration):
self.rewrite_value = configuration.rewrite_value
self.format_preservation = configuration... |
class OptionSeriesLollipopSonificationTracksMappingTremolo(Options):
def depth(self) -> 'OptionSeriesLollipopSonificationTracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesLollipopSonificationTracksMappingTremoloDepth)
def speed(self) -> 'OptionSeriesLollipopSonificationTracks... |
class Migration(migrations.Migration):
dependencies = [('myauth', '0001_initial'), ('django_etebase', '0001_initial')]
operations = [migrations.CreateModel(name='UserInfo', fields=[('owner', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to=settings.AUTH_USE... |
def edit_catamins(save_stats: dict[(str, Any)]) -> dict[(str, Any)]:
catamins = item.IntItemGroup.from_lists(names=['Catamin A', 'Catamin B', 'Catamin C'], values=save_stats['catamins'], maxes=9999, group_name='Catamins')
catamins.edit()
save_stats['catamins'] = catamins.get_values()
return save_stats |
class CRUDCollection(Generic[T]):
__slots__ = ('_items_by_id',)
def __init__(self) -> None:
self._items_by_id = {}
def create(self, item_id: str, item: T) -> None:
if (item_id in self._items_by_id):
raise ValueError('Item with name {} already present!'.format(item_id))
se... |
def learned_count(start_date):
if ah.user_settings['keep_log']:
ah.log.debug('Begin function')
learned = 0
learned = mw.col.db.scalar('\n select count() from\n (select min(id) as id\n from revlog\n where type = 0\n group by cid) as s\n where id/1000 > ?\n ... |
class TestSQLQueryConfig():
def test_extract_query_components(self):
def found_query_keys(node: TraversalNode, values: Dict[(str, Any)]) -> Set[str]:
return set(node.typed_filtered_values(values).keys())
config = SQLQueryConfig(payment_card_node)
assert (config.field_map().keys()... |
class OptionPlotoptionsDumbbellSonificationDefaultspeechoptionsMappingTime(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str... |
def _convert_inputs(model, X, is_train):
xp2tensorflow_ = (lambda x: xp2tensorflow(x, requires_grad=is_train))
converted = convert_recursive(is_xp_array, xp2tensorflow_, X)
if isinstance(converted, ArgsKwargs):
def reverse_conversion(dXtf):
return convert_recursive(is_tensorflow_array, t... |
class ComponentType(str, Enum):
WORKER_MANAGER = 'dbgpt_worker_manager'
WORKER_MANAGER_FACTORY = 'dbgpt_worker_manager_factory'
MODEL_CONTROLLER = 'dbgpt_model_controller'
MODEL_REGISTRY = 'dbgpt_model_registry'
MODEL_API_SERVER = 'dbgpt_model_api_server'
MODEL_CACHE_MANAGER = 'dbgpt_model_cache... |
class TestReadWrite(util.TestCase):
def test_read_write(self):
markup = '\n <input id="0">\n <textarea id="1"></textarea>\n\n <input id="2">\n <input id="3" disabled>\n\n <input id="4" type="email">\n <input id="5" type="number">\n <input id="6" type="passwor... |
class Jinja2(python.Python):
def init(self):
self.update_actions({'render': {'render': '{{%(code)s}}', 'header': '{{%(header)s}}', 'trailer': '{{%(trailer)s}}', 'test_render': ('(%(n1)s,%(n2)s*%(n3)s)' % {'n1': rand.randints[0], 'n2': rand.randints[1], 'n3': rand.randints[2]}), 'test_render_expected': ('%(r... |
.asyncio
.workspace_host
class TestUpdateEmailTemplate():
async def test_unauthorized(self, unauthorized_api_assertions: HTTPXResponseAssertion, test_client_api: test_data: TestData):
email_template = test_data['email_templates']['base']
response = (await test_client_api.patch(f'/email-templates/{e... |
def PyQtColor(default='white', allow_none=False, **metadata):
if (default is None):
allow_none = True
if allow_none:
return Trait(default, None, standard_colors, convert_to_color, editor=get_color_editor, **metadata)
return Trait(default, standard_colors, convert_to_color, editor=get_color_e... |
def test_always_transact_block_identifier(accounts, tester, argv, web3, monkeypatch, history):
argv['always_transact'] = True
height = web3.eth.block_number
last_tx = history[(- 1)]
monkeypatch.setattr('brownie.network.chain.undo', (lambda : None))
tester.owner(block_identifier='latest')
assert ... |
def process_type(typ):
t = typ.t
if (t == SolType.IntTy):
return ('int', typ.size, [])
elif (t == SolType.UintTy):
return ('uint', typ.size, [])
elif (t == SolType.BoolTy):
return ('bool', '', [])
elif (t == SolType.StringTy):
return ('string', '', [])
elif (t == ... |
def test_play_info():
ali = Aligo()
audio_info = ali.get_audio_play_info(file_id=audio_file_id)
assert isinstance(audio_info, GetAudioPlayInfoResponse)
assert (len(audio_info.template_list) > 0)
video_info = ali.get_video_preview_play_info(file_id=video_file_id)
assert isinstance(video_info, Get... |
class OptionSeriesColumnrangeSonificationDefaultinstrumentoptionsMappingVolume(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text:... |
def upgrade():
op.add_column('image_sizes', sa.Column('icon_size_quality', sa.Integer(), nullable=True))
op.add_column('image_sizes', sa.Column('icon_size_width_height', sa.Integer(), nullable=True))
op.add_column('image_sizes', sa.Column('small_size_quality', sa.Integer(), nullable=True))
op.add_column... |
def test_contract_deployment_with_constructor_with_arguments_non_strict(w3_non_strict_abi, non_strict_contract_with_constructor_args_factory):
deploy_txn = non_strict_contract_with_constructor_args_factory.constructor(1234, 'abcd').transact()
txn_receipt = w3_non_strict_abi.eth.wait_for_transaction_receipt(depl... |
class TlsCertificateDataAttributes(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
return {'cert_blob': (str,)... |
class ChainedGraphicMatcher(GraphicMatcher):
def __init__(self, graphic_matchers: Sequence[GraphicMatcher]):
super().__init__()
self.graphic_matchers = graphic_matchers
def get_graphic_matches(self, semantic_graphic_list: Sequence[SemanticGraphic], candidate_semantic_content_list: Sequence[Seman... |
def local_rsync(options, fromdir, todir):
rsyncargs = ['rsync', '--recursive', '--safe-links', '--times', '--perms', '--one-file-system', '--delete', '--chmod=Da+rx,Fa-x,a+r,u+w']
if (not options.no_checksum):
rsyncargs.append('--checksum')
if options.verbose:
rsyncargs += ['--verbose']
... |
class StorageRepositoryClient(_base_repository.BaseRepositoryClient):
def __init__(self, credentials=None, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True, cache_discovery=False, cache=None):
if (not quota_max_calls):
use_rate_limiter = False
self._buckets = None
se... |
class Script(Revision):
_only_source_rev_file = re.compile('(?!__init__)(.*\\.py)$')
migration_class = None
path = None
def __init__(self, module, migration_class, path):
self.module = module
self.migration_class = migration_class
self.path = path
super(Script, self).__in... |
.parametrize('predictors_only,expected_X,expected_y', [(True, (1309, 8), (1309,)), (False, (1309, 13), (1309,))])
def test_return_X_y(predictors_only, expected_X, expected_y):
(X, y) = load_titanic(return_X_y_frame=True, predictors_only=predictors_only)
assert (X.shape == expected_X)
assert (y.shape == expe... |
('src', [{'_target_': 'tests.instantiate.Adam'}])
def test_instantiate_adam(instantiate_func: Any, config: Any) -> None:
with raises(InstantiationException, match="Error in call to target 'tests\\.instantiate\\.Adam':\\nTypeError\\(.*\\)"):
instantiate_func(config)
adam_params = Parameters([1, 2, 3])
... |
def main():
args = parse_commandline()
pod_deployment: Optional[K8sPodDeployment] = None
if args.from_file:
pod_deployment = K8sPodDeployment([Path(args.from_file)], None)
else:
dargs: List[Any] = [args.key, args.port, args.delegate_port, args.monitoring_port]
dargs.append((args.... |
def extractLewdtranslationBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Everyone can do it! The Instant Love Switch', 'Everyone can do it! The Instant Love Switch... |
def test_transformer_pipeline_tagger_senter_listener():
orig_config = Config().from_str(cfg_string)
nlp = util.load_model_from_config(orig_config, auto_fill=True, validate=True)
assert (nlp.pipe_names == ['transformer', 'tagger', 'senter'])
tagger = nlp.get_pipe('tagger')
transformer = nlp.get_pipe(... |
class FileDialogDemo(HasTraits):
file_name = File()
open = Button('Open...')
traits_view = View(HGroup(Item('open', show_label=False), '_', Item('file_name', style='readonly', springy=True)), width=0.5)
def _open_changed(self):
file_name = open_file(extensions=LineCountInfo(), id=demo_id)
... |
def parse_css(cspace: Space, string: str, start: int=0, fullmatch: bool=True, color: bool=False) -> (tuple[(tuple[(Vector, float)], int)] | None):
target = cspace.SERIALIZE
if (not target):
target = (cspace.NAME,)
tokens = tokenize_css(string, start=start)
if (not tokens):
return None
... |
class ModelSerializerOptions(SerializerOptions):
def __init__(self, meta):
super(ModelSerializerOptions, self).__init__(meta)
self.model = getattr(meta, 'model', None)
self.read_only_fields = getattr(meta, 'read_only_fields', ())
self.write_only_fields = getattr(meta, 'write_only_fie... |
def benchmark_vae(pt_vae, batch_size=1, height=64, width=64, benchmark_pt=False, verify=False):
latent_channels = 4
exe_module = Model('./tmp/AutoencoderKL/test.so')
if (exe_module is None):
print('Error!! Cannot find compiled module for AutoencoderKL.')
exit((- 1))
pt_vae = pt_vae.cuda(... |
def execute_workflow(ert: EnKFMain, storage: StorageAccessor, workflow_name: str) -> None:
logger = logging.getLogger(__name__)
try:
workflow = ert.ert_config.workflows[workflow_name]
except KeyError:
msg = 'Workflow {} is not in the list of available workflows'
logger.error(msg.form... |
.benchmark
('xtb')
.parametrize('fn, geoms, charge, mult, ref_energy', Bh.geom_iter)
def test_xtb_rx(fn, geoms, charge, mult, ref_energy, results_bag):
(start, ts_ref_org, end) = geoms
id_ = fn[:2]
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir)
inp_ts = str((tmp_path... |
def merge_in_fixed_mismatch():
test_data = load_test_data(only_mismatch=True)
count = 0
mismatch = 0
remlines = []
good_lines = []
good_sets = []
for (key, value) in test_data:
p = TPN(key)
(vol, chp, frag, post) = (p.getVolume(), p.getChapter(), p.getFragment(), p.getPostfix... |
class ModelMeta(type):
def __new__(cls, name, bases, attrs):
model_class = super().__new__(cls, name, bases, attrs)
if ('registry' in attrs):
model_class.database = attrs['registry'].database
attrs['registry'].models[name] = model_class
if ('tablename' not in attr... |
class OptionSeriesBellcurveSonificationPointgrouping(Options):
def algorithm(self):
return self._config_get('minmax')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._co... |
class OptionPlotoptionsAreaSonificationContexttracksMappingPan(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
s... |
class RefreshingCredentials():
def __init__(self, client_id: str, client_secret: str=None, redirect_uri: str=None, sender: Sender=None):
self.credentials = Credentials(client_id, client_secret, redirect_uri, sender, asynchronous=False)
def __repr__(self):
options = [f'client_id={self.credentials... |
def calculate_regression_performance(dataset: pd.DataFrame, columns: DatasetColumns, error_bias_prefix: str) -> RegressionPerformanceMetrics:
target_column = columns.utility_columns.target
prediction_column = columns.utility_columns.prediction
num_feature_names = columns.num_feature_names
cat_feature_na... |
def test_slurm_error_mocked(tmp_path: Path) -> None:
with mocked_slurm() as mock:
executor = slurm.SlurmExecutor(folder=tmp_path)
executor.update_parameters(time=24, gpus_per_node=0)
job = executor.submit(test_core.do_nothing, 1, 2, error=12)
with mock.job_context(job.job_id):
... |
def test_univariate_integrate(univariate_data):
x = univariate_data.x
y = univariate_data.y
integral_expected = univariate_data.integral
spline = csaps.CubicSmoothingSpline(x, y, smooth=None).spline
integral = spline.integrate(x[0], x[(- 1)])
assert (integral == pytest.approx(integral_expected)) |
class FlytekitPlugin():
def get_remote(config: Optional[str], project: str, domain: str, data_upload_location: Optional[str]=None) -> FlyteRemote:
cfg_file = get_config_file(config)
if (cfg_file is None):
cfg_obj = Config.for_sandbox()
logger.info('No config files found, crea... |
class LoggingSplunkAdditional(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
lazy_impor... |
class AssistanceDownloadValidator(DownloadValidatorBase):
name = 'assistance'
def __init__(self, request_data: dict):
super().__init__(request_data)
self.tinyshield_models.extend([{'key': 'award_id', 'name': 'award_id', 'type': 'any', 'models': [{'type': 'integer'}, {'type': 'text', 'text_type':... |
class NameCitationModelNestedBluePrint(SegmentedModelNestedBluePrint):
def __init__(self, *args, reference_segmenter_model: Model, citation_model: Model, **kwargs):
super().__init__(*args, **kwargs)
self.reference_segmenter_model = reference_segmenter_model
self.citation_model = citation_mod... |
('calling_file, calling_module', [('tests/test_apps/app_without_config/my_app.py', None), (None, 'tests.test_apps.app_without_config.my_app')])
def test_app_without_config__with_append(hydra_restore_singletons: Any, hydra_task_runner: TTaskRunner, calling_file: str, calling_module: str) -> None:
with hydra_task_run... |
def int3c2e3d_sph_101(ax, da, A, bx, db, B, cx, dc, C):
result = numpy.zeros((3, 1, 3), dtype=float)
x0 = (ax + bx)
x1 = (x0 ** (- 1.0))
x2 = ((- x1) * ((ax * A[0]) + (bx * B[0])))
x3 = (x2 + C[0])
x4 = (cx + x0)
x5 = (x4 ** (- 1.0))
x6 = ((- x1) * ((ax * A[1]) + (bx * B[1])))
x7 = (... |
class FiresiteHTMLTranslator(html.HTMLTranslator):
def __init__(self, builder, *args, **kwds):
html.HTMLTranslator.__init__(self, builder, *args, **kwds)
self.current_section = 'intro'
self.insert_header = False
def visit_desc(self, node):
if (node.parent.tagname == 'section'):
... |
def create_shader(shader_tree, name=None):
shader_type = shader_tree['type']
if ('class' in shader_tree):
class_ = shader_tree['class']
else:
class_ = 'asShader'
shader = pm.shadingNode(shader_type, **{class_: 1})
if name:
shader.rename(name)
attributes = shader_tree['att... |
class OptionSeriesVectorPointEvents(Options):
def click(self):
return self._config_get(None)
def click(self, value: Any):
self._config(value, js_type=False)
def drag(self):
return self._config_get(None)
def drag(self, value: Any):
self._config(value, js_type=False)
de... |
class PCSFeature(Enum):
PCS_DUMMY = 'pcs_dummy_feature'
PRIVATE_LIFT_PCF2_RELEASE = 'private_lift_pcf2_release'
PC_COORDINATED_RETRY = 'private_computation_coordinated_retry'
PRIVATE_LIFT_UNIFIED_DATA_PROCESS = 'private_lift_unified_data_process'
PCS_PRIVATE_LIFT_DECOUPLED_UDP = 'pcs_private_lift_de... |
def create_cosmwasm_execute_msg(sender_address: Address, contract_address: Address, args: Any, funds: Optional[str]=None) -> MsgExecuteContract:
msg = MsgExecuteContract(sender=str(sender_address), contract=str(contract_address), msg=json_encode(args).encode('UTF8'))
if (funds is not None):
msg.funds.ex... |
def monte_carlo_approximate_reparam(observations: RVDict, num_samples: int, discrepancy_fn: DiscrepancyFn, params: Mapping[(RVIdentifier, torch.Tensor)], queries_to_guides: Mapping[(RVIdentifier, RVIdentifier)], subsample_factor: float=1.0, device: torch.device=_CPU_DEVICE) -> torch.Tensor:
loss = torch.zeros(1).to... |
.parametrize('ownership_range,num_components', [((6, 27), 3), ((6, 17), 4)])
def test_interlaced_vel_dof_order(ownership_range, num_components):
interlaced = LS.InterlacedDofOrderType()
num_equations = ((ownership_range[1] - ownership_range[0]) + 1)
(global_IS, vel_IS) = interlaced.create_vel_DOF_IS(ownersh... |
def get_score(A, B):
bbox_A = get_bbox(A)
bbox_B = get_bbox(B)
if (not is_colliding(bbox_A, bbox_B)):
return (- 1.0)
delta_pos = (bbox_B['center'] - bbox_A['center']).length
volume_A = ((bbox_A['size'].x * bbox_A['size'].y) * bbox_A['size'].z)
volume_B = ((bbox_B['size'].x * bbox_B['size... |
def test_create_plan_start_model_downstream():
parsed = Namespace(select=['modelA+'])
graph = _create_test_graph()
execution_plan = ExecutionPlan.create_plan_from_graph(parsed, graph, MagicMock(project_name=PROJECT_NAME))
assert (execution_plan.before_scripts == [])
assert (execution_plan.dbt_models... |
class OptionPlotoptionsAreasplineSonificationContexttracksMappingTremoloDepth(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: ... |
class OptionPlotoptionsDependencywheelSonificationContexttracksMappingNoteduration(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, t... |
def test_structure_json(complex_obj):
c = conversion[SerializeFormat.JSON]
uo = c.unstructure(complex_obj)
o = c.structure(uo, ComplexObj)
assert (o.float64_array.dtype == np.float64)
assert (o.float32_array.dtype == np.float32)
assert (o.int32_array.dtype == np.int32)
assert isinstance(o.an... |
def extractShujinkouCom(item):
if ('Anime' in item['tags']):
return None
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Isekai Kaeri no Ossan', 'Isekai Kaeri no Ossan wa,... |
def test_nonans_tesseroid_mask(dummy_layer):
((longitude, latitude), surface, reference, _) = dummy_layer
shape = (latitude.size, longitude.size)
layer = tesseroid_layer((longitude, latitude), surface, reference)
expected_mask = np.ones(shape, dtype=bool)
mask = layer.tesseroid_layer._get_nonans_mas... |
class TagSearch(object):
def __init__(self, view, bfr, window, center, pattern, match_type, mode, optional_tags, self_closing_tags, void_tags):
self.start = int(window[0])
self.end = int(window[1])
self.optional_tags = optional_tags
self.void_tags = void_tags
self.self_closin... |
class UnsubscribeTest(unittest.TestCase):
('unsubscribe.app.unsubscribe_single_list', side_effect=mocked_unsubscribe_single_list)
('unsubscribe.app.look_up_cognito_id', side_effect=mocked_look_up_cognito_id)
('user_service.query_single_user', side_effect=mocked_query_single_user)
def test_unsubscribe(se... |
(tags=['dates'], description=docs.CALENDAR_DATES)
class CalendarDatesView(ApiResource):
model = models.CalendarDate
schema = schemas.CalendarDateSchema
page_schema = schemas.CalendarDatePageSchema
cap = 500
filter_match_fields = [('event_id', models.CalendarDate.event_id)]
filter_multi_fields = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.