code stringlengths 281 23.7M |
|---|
def _handle_optimizer_in_client(client):
if ('optim_config' not in client):
return
client['optimizer'] = client['optim_config']
del client['optim_config']
optimizer = client['optimizer']
if ('type' not in optimizer):
pass
elif ('sgd' == optimizer['type'].lower()):
optimiz... |
class PanelsBar(Html.Html):
name = 'Panel Bar'
def __init__(self, page: primitives.PageModel, width: tuple, height: tuple, options: Optional[dict], helper: str, profile: Optional[Union[(dict, bool)]]):
super(PanelsBar, self).__init__(page, None, profile=profile, css_attrs={'width': width, 'height': heig... |
class ObjectSpec(EntitySpec):
def __init__(self, params):
super().__init__(params)
def _lookup(self, depth, unlocked=False):
name = self._params['config']['name']
return SpecView(self, depth=[depth], name=name, unlocked=unlocked)
def gui(self, engine_cls: Type['Engine'], interactive:... |
('cuda.bmm_rcr_n1.gen_function')
def gen_function(func_attrs, exec_cond_template, dim_info_dict):
func_name = func_attrs['name']
shape_func = gemm_common.gen_shape_eval_code(indent=1, dtype='int64_t', dim_info_dict=dim_info_dict, is_ptr=True)
def _get_original_dim_val(func_attrs, input_idx, dim):
ac... |
class OptionPlotoptionsSeriesStatesHoverHalo(Options):
def attributes(self):
return self._config_get(None)
def attributes(self, value: Any):
self._config(value, js_type=False)
def opacity(self):
return self._config_get(0.25)
def opacity(self, num: float):
self._config(num... |
(CISAudit, '_shellexec', mock_homedirs_data)
def test_audit_homedirs_ownership_pass(fs):
fake_filesystem.set_uid(0)
fake_filesystem.set_gid(0)
fs.create_dir('/root')
fake_filesystem.set_uid(1000)
fake_filesystem.set_gid(1000)
fs.create_dir('/home/pytest')
state = test.audit_homedirs_ownershi... |
def test_async_partial_object_call():
class Async():
async def __call__(self, a, b):
...
class Sync():
def __call__(self, a, b):
...
partial = functools.partial(Async(), 1)
assert is_async_callable(partial)
partial = functools.partial(Sync(), 1)
assert (no... |
def get_ait_params(hidden_size, vocab_size, max_position_embeddings, type_vocab_size, dtype='float16'):
word_embeddings = Tensor(shape=[vocab_size, hidden_size], dtype=dtype, name='word_embeddings', is_input=True)
token_type_embeddings = Tensor(shape=[type_vocab_size, hidden_size], dtype=dtype, name='token_type... |
class ImportCluster(AbstractCommand):
def setup(self, subparsers):
parser = subparsers.add_parser('import', help='Import a cluster from a zip file', description=self.__doc__)
parser.set_defaults(func=self)
parser.add_argument('--rename', metavar='NAME', help='Rename the cluster during import... |
def extractSlothfulworksWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return False
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag... |
('llama_recipes.finetuning.train')
('llama_recipes.finetuning.LlamaForCausalLM.from_pretrained')
('llama_recipes.finetuning.LlamaTokenizer.from_pretrained')
('llama_recipes.finetuning.get_preprocessed_dataset')
('llama_recipes.finetuning.generate_peft_config')
('llama_recipes.finetuning.get_peft_model')
('llama_recipes... |
def _get_post_processing_handlers(config: Dict[(str, Any)], trace_logging_svc: TraceLoggingService) -> Dict[(str, PostProcessingHandler)]:
if (not config):
return {}
post_processing_handlers = {}
for (name, handler_config) in config['dependency'].items():
constructor_info = handler_config.ge... |
class OptionPlotoptionsArearangeSonificationDefaultinstrumentoptionsMappingNoteduration(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(se... |
class Query(DslBase):
_type_name = 'query'
_type_shortcut = staticmethod(Q)
name = None
def __add__(self, other):
if hasattr(other, '__radd__'):
return other.__radd__(self)
return Bool(must=[self, other])
def __invert__(self):
return Bool(must_not=[self])
def ... |
def _assemble_source_procurement_records(id_list):
for trx_id in id_list:
dummy_row = _assemble_dummy_source_data()
dummy_row['detached_award_procurement_id'] = trx_id
dummy_row['detached_award_proc_unique'] = str(trx_id)
dummy_row['ordering_period_end_date'] = '2010-01-01 00:00:00'
... |
class Review(SimpleEntity, ScheduleMixin, StatusMixin):
__auto_name__ = True
__tablename__ = 'Reviews'
__table_args__ = {'extend_existing': True}
__mapper_args__ = {'polymorphic_identity': 'Review'}
review_id = Column('id', Integer, ForeignKey('SimpleEntities.id'), primary_key=True)
task_id = Co... |
class EMAHook(HookBase):
def __init__(self, cfg, model):
model = _remove_ddp(model)
assert cfg.MODEL_EMA.ENABLED
assert hasattr(model, 'ema_state'), 'Call `may_build_model_ema` first to initilaize the model ema'
self.model = model
self.ema = self.model.ema_state
self.... |
class OptionValidator(object):
def __init__(self, values):
self.values = values
def __call__(self, value):
if (value.lstrip('-') not in self.values):
raise exceptions.ApiError('Cannot sort on value "{0}". Instead choose one of: "{1}"'.format(value, '", "'.join(self.values)), status_c... |
class INETETW(ETW):
def __init__(self, ring_buf_size=1024, max_str_len=1024, min_buffers=0, max_buffers=0, level=et.TRACE_LEVEL_INFORMATION, any_keywords=None, all_keywords=None, filters=None, event_callback=None, logfile=None, no_conout=False):
self.logfile = logfile
self.no_conout = no_conout
... |
class CTCHead(nn.Layer):
def __init__(self, in_channels, out_channels, fc_decay=0.0004, mid_channels=None, **kwargs):
super(CTCHead, self).__init__()
if (mid_channels is None):
(weight_attr, bias_attr) = get_para_bias_attr(l2_decay=fc_decay, k=in_channels)
self.fc = nn.Linear... |
.usefixtures('use_tmpdir')
def test_job_dispatch_run_subset_specified_as_parmeter():
with open('dummy_executable', 'w', encoding='utf-8') as f:
f.write('#!/usr/bin/env python\nimport sys, os\nfilename = "job_{}.out".format(sys.argv[1])\nf = open(filename, "w", encoding="utf-8")\nf.close()\n')
executable... |
def readFunLite():
from optparse import OptionParser
usage = 'usage: %readFunLite [options] meshFile funFile funOutFile'
parser = OptionParser(usage=usage)
parser.add_option('-m', '--matlab', help='print edges to files for plotting in matlab', action='store_true', dest='matlab', default=False)
parse... |
def getPathFromShp(shpfile, region, encoding='utf-8'):
try:
sf = shapefile.Reader(shpfile, encoding=encoding)
vertices = []
codes = []
paths = []
for shape_rec in sf.shapeRecords():
if ((region == [100000]) or (shape_rec.record[4] in region)):
pts ... |
class OptionPlotoptionsWindbarbLabelStyle(Options):
def fontSize(self):
return self._config_get('0.8em')
def fontSize(self, num: float):
self._config(num, js_type=False)
def fontWeight(self):
return self._config_get('bold')
def fontWeight(self, text: str):
self._config(te... |
_os(*metadata.platforms)
def main():
key = 'Software\\Classes\\ms-settings\\shell\\open\\command'
value = 'test'
data = 'test'
with common.temporary_reg(common.HKCU, key, value, data):
pass
fodhelper = 'C:\\Users\\Public\\fodhelper.exe'
powershell = 'C:\\Windows\\System32\\WindowsPowerSh... |
class OptionPlotoptionsNetworkgraphSonificationTracksPointgrouping(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):
... |
class ReferenceTemplate(object):
def __init__(self, id: _identifier_model.Identifier, resource_type: int) -> None:
self._id = id
self._resource_type = resource_type
def id(self) -> _identifier_model.Identifier:
return self._id
def resource_type(self) -> int:
return self._reso... |
class BlockedWell(Well):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._gridname = None
def gridname(self):
return self._gridname
def gridname(self, newname):
if isinstance(newname, str):
self._gridname = newname
else:
... |
class OptionPlotoptionsArcdiagramLabelStyle(Options):
def fontSize(self):
return self._config_get('0.8em')
def fontSize(self, num: float):
self._config(num, js_type=False)
def fontWeight(self):
return self._config_get('bold')
def fontWeight(self, text: str):
self._config(... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'name'
fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path':... |
def decorator_with_optional_params(decorator: Callable) -> Callable:
(decorator)
def new_decorator(*args: Any, **kwargs: Any) -> Callable:
if ((len(args) == 1) and (len(kwargs) == 0) and callable(args[0])):
return decorator(args[0])
def final_decorator(real_function: Callable) -> Cal... |
class Parser(object):
def __init__(self):
self._declarations = {}
self._anonymous_counter = 0
self._structnode2type = weakref.WeakKeyDictionary()
self._override = False
self._packed = False
self._int_constants = {}
def _parse(self, csource):
(csource, macr... |
def sync_from_localcopy(repo_section, local_copy_dir):
logging.info('Syncing from local_copy_dir to this repo.')
common.local_rsync(options, (os.path.join(local_copy_dir, repo_section).rstrip('/') + '/'), (repo_section.rstrip('/') + '/'))
offline_copy = os.path.join(local_copy_dir, BINARY_TRANSPARENCY_DIR)
... |
class RxEngine(object):
def __init__(self, name, message_broker):
self.name = name
self.ns = '/'.join(name.split('/')[:2])
self.mb = message_broker
self.backend = message_broker.backend
self.initialized = False
self.has_shutdown = False
(rate, inputs, outputs,... |
def test_resets():
tfm = get_tfm()
tfm._reset_data_results(True, True, True)
tfm._reset_internal_settings()
for data in ['data', 'model_components']:
for field in OBJ_DESC[data]:
assert (getattr(tfm, field) is None)
for field in OBJ_DESC['results']:
assert np.all(np.isnan... |
class AsyncTestCase(unittest.TestCase):
def setUp(self) -> None:
self._loop = FcrTestEventLoop()
asyncio.set_event_loop(None)
def tearDown(self) -> None:
pending = [t for t in asyncio.all_tasks(self._loop) if (not t.done())]
if pending:
res = self._run_loop(asyncio.wa... |
class BokehWidget(Widget):
DEFAULT_MIN_SIZE = (100, 100)
CSS = '\n .flx-BokehWidget > .plotdiv {\n overflow: hidden;\n }\n '
def from_plot(cls, plot, **kwargs):
return make_bokeh_widget(plot, **kwargs)
plot = event.Attribute(doc='The JS-side of the Bokeh plot object.')
def _r... |
def test_dice_implicit_resolver():
import srsly.ruamel_yaml
pattern = re.compile('^\\d+d\\d+$')
with pytest.raises(ValueError):
srsly.ruamel_yaml.add_implicit_resolver(u'!dice', pattern)
assert (srsly.ruamel_yaml.dump(dict(treasure=Dice(10, 20)), default_flow_style=False) == 'treasure: 10d20... |
class TestCliQuiet(TestCliBase):
def setUp(self):
super().setUp()
self.env = {'PRINT': 'True'}
def test_with_quiet(self):
self.argv.insert(0, '--quiet')
self.run_testslide(expected_return_code=1, expected_stdout_startswith='top context\n passing example: PASS\nstdout:\nfailing_e... |
class ScheduleHandle():
def __init__(self, task_allocation, sched, task_progress_control, runner, params):
self.task_allocation = task_allocation
self.operation_type = task_allocation.task.operation.type
self.sched = sched
self.task_progress_control = task_progress_control
se... |
class TestTask():
def test_tasks_deve_retornar_200_quando_receber_um_get(self):
request = get(url_base)
assert (request.status_code == 200)
def test_tasks_deve_retornar_uma_lista_vazia_no_primeiro_request(self):
request = get(url_base)
assert (request.json() == [])
def test_t... |
def test_unpickling_watcher_registration(tmp_path: Path) -> None:
executor = FakeExecutor(folder=tmp_path)
job = executor.submit(_three_time, 4)
original_job_id = job._job_id
job._job_id = '007'
assert (job.watcher._registered == {original_job_id})
pkl = pickle.dumps(job)
newjob = pickle.loa... |
def opensfm_shot_from_info(info: dict, projection: Projection) -> Shot:
latlong = info['computed_geometry']['coordinates'][::(- 1)]
alt = info['computed_altitude']
xyz = projection.project(np.array([*latlong, alt]), return_z=True)
c_rotvec_w = np.array(info['computed_rotation'])
pose = Pose()
po... |
('drop')
('path')
def drop(path):
from bench.bench import Bench
from bench.exceptions import BenchNotFoundError, ValidationError
bench = Bench(path)
if (not bench.exists):
raise BenchNotFoundError(f'Bench {bench.name} does not exist')
if bench.sites:
raise ValidationError('Cannot rem... |
def financial_spending_data(db):
federal_account_1 = baker.make('accounts.FederalAccount', id=1)
object_class_1 = baker.make('references.ObjectClass', major_object_class='10', major_object_class_name='mocName1', object_class='111', object_class_name='ocName1')
object_class_2 = baker.make('references.ObjectC... |
def run_update_query(backfill_type):
global TOTAL_UPDATES
sql = SQL_LOOKUP[backfill_type]['update_sql']
with connection.cursor() as cursor:
with Timer() as t:
cursor.execute(sql.format(min_id=_min, max_id=_max))
row_count = cursor.rowcount
progress = (((_max - min_id) + 1... |
class Index(Source):
def new_mask_index(self, *args, **kwargs):
return MaskIndex(*args, **kwargs)
def __len__(self):
self._not_implemented()
def _normalize_kwargs_names(**kwargs):
return kwargs
def sel(self, *args, remapping=None, **kwargs):
kwargs = normalize_selection(*... |
class Label():
type: str
tokens: List[Token]
def __init__(self, type: str=None, tokens: List[Token]=None) -> None:
self.type = type
self.tokens = tokens
def text(self) -> str:
if (not self.tokens):
return ''
return ''.join((token.text for token in self.tokens)... |
def load_vgg_weights(weights_path):
kind = weights_path[(- 3):]
if (kind == 'npz'):
weights = load_from_npz(weights_path)
elif (kind == 'mat'):
weights = load_from_mat(weights_path)
else:
weights = None
print(('Unrecognized file type: %s' % kind))
return weights |
class Barcodes():
def __init__(self):
self._counts = {}
def load(self, fastq=None, fp=None):
for read in FASTQFile.FastqIterator(fastq_file=fastq, fp=fp):
seq = read.seqid.index_sequence
if (seq not in self._counts):
self._counts[seq] = 1
else:... |
def commands():
env.MEGASCAN_LIBRARY_PATH = '/mnt/NAS/Users/eoyilmaz/Stalker_Projects/Resources/Quixel/'
if ('blender' in this.root):
pass
if ('maya' in this.root):
env.PYTHONPATH.append('$MEGASCAN_LIBRARY_PATH/support/plugins/maya/6.8/MSLiveLink/')
if ('houdini' in this.root):
e... |
class OptionSeriesPackedbubbleSonificationDefaultinstrumentoptionsMappingTremoloSpeed(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... |
def calculate_math_string(expr):
ops = {ast.Add: operator.add, ast.Mult: operator.mul, ast.Sub: operator.sub, ast.USub: operator.neg, ast.Pow: operator.pow}
def execute_ast(node):
if isinstance(node, ast.Num):
return node.n
elif isinstance(node, ast.BinOp):
return ops[typ... |
class TestEncryptDescriptor(Descriptor):
TEST_DESC_UUID = '-1234-5678-1234-56789abcdef4'
def __init__(self, bus, index, characteristic):
Descriptor.__init__(self, bus, index, self.TEST_DESC_UUID, ['encrypt-read', 'encrypt-write'], characteristic)
def ReadValue(self, options):
return [dbus.By... |
def pytest_collection_modifyitems(config, items):
has_runslow = config.getoption('--runslow')
has_runsuperslow = config.getoption('--runsuperslow')
skip_slow = pytest.mark.skip(reason='need --runslow option to run')
skip_superslow = pytest.mark.skip(reason='need --runsuperslow option to run')
for it... |
def test_consensus_after_non_finalization_streak(casper, concise_casper, funded_account, validation_key, deposit_amount, new_epoch, induct_validator, mk_suggested_vote, send_vote, assert_tx_failed):
validator_index = induct_validator(funded_account, validation_key, deposit_amount)
assert (concise_casper.total_c... |
def test_member_access_properties():
member_access = MemberAccess(operands=[a], member_name='x', offset=4, vartype=Integer.int32_t(), writes_memory=1)
assert (member_access.member_name == 'x')
assert (member_access.member_offset == 4)
assert (member_access.struct_variable == a)
assert member_access.... |
def init(fips_dir, proj_name):
proj_dir = util.get_project_dir(fips_dir, proj_name)
if os.path.isdir(proj_dir):
templ_values = {'project': proj_name}
for f in ['CMakeLists.txt', 'fips', 'fips.cmd', 'fips.yml']:
template.copy_template_file(fips_dir, proj_dir, f, templ_values)
... |
def test_osrm_distance_call_nonsquare_matrix(mocked_osrm_valid_call):
sources = np.array([[0.0, 0.0], [1.0, 1.0]])
destinations = np.array([[2.0, 2.0], [3.0, 3.0]])
osrm_server_address = 'BASE_URL'
osrm_distance_matrix(sources, destinations, osrm_server_address=osrm_server_address, cost_type='distances'... |
def test_logging_redirect_chain(server, caplog):
caplog.set_level(logging.INFO)
with as client:
response = client.get(server.url.copy_with(path='/redirect_301'))
assert (response.status_code == 200)
assert (caplog.record_tuples == [(' logging.INFO, 'HTTP Request: GET "HTTP/1.1 301 Moved Pe... |
class LoggingNewrelicAdditional(ModelNormal):
allowed_values = {('region',): {'US': 'US', 'EU': 'EU'}}
validations = {}
_property
def additional_properties_type():
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
... |
def extractFuel2RocktranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, na... |
class DelegatedFunctionCheckpoint(CheckpointBase):
def __init__(self, other):
self.other = other
self.count = type(other.output)(other.output.function_space()).count()
def restore(self):
saved_output = self.other.saved_output
if isinstance(saved_output, Number):
retur... |
def test_compression(config_env: Dict):
if (CONFIG_ERROR in config_env.keys()):
fail(f'Config Error: {config_env[CONFIG_ERROR]}')
if (EXPECTED_COMPRESSION not in config_env[EXPECTED_RESULTS].keys()):
skip(f'Test not requested: {EXPECTED_COMPRESSION}')
if (not ({COSE, COMPRESSED} <= config_en... |
def test_generate_ass_repr_for_building_look_dev_is_working_properly(create_test_data, store_local_session, create_pymel, create_maya_env):
data = create_test_data
pm = create_pymel
maya_env = create_maya_env
gen = RepresentationGenerator(version=data['building1_yapi_model_main_v003'])
gen.generate_... |
class PrimaryDagBuilder(DagBuilderBase):
indent_operators = False
def preamble(self):
assert (len(self.reference_path) == 1), 'Invalid Primary DAG reference path: {}'.format(self.reference_path)
template = self.get_jinja_template('primary_preamble.j2')
dag_args_dumped = DagArgsSchema(con... |
(_BUILD_NIGHTHAWK_BENCHMARKS)
(_BUILD_NIGHTHAWK_BINARIES)
(_BUILD_ENVOY_BINARY)
('src.lib.cmd_exec.run_command')
def test_source_to_build_binaries(mock_cmd, mock_envoy_build, mock_nh_bin_build, mock_nh_bench_build):
job_control = generate_test_objects.generate_default_job_control()
generate_test_objects.generat... |
class DataFactory(object):
def __init__(self, seed=36):
self.random = random.Random()
self.random.seed(seed)
counter = itertools.count()
self.next_id = (lambda : next(counter))
self.months = []
self.practices = []
self.practice_statistics = []
self.pre... |
def main_github(args):
token = os.getenv('GITHUB_TOKEN')
if (not token):
raise Exception('Missing GITHUB_TOKEN env variable')
(repos, _) = parse_maintainers(args.repo)
for (repo_name, maintainers) in repos:
pr = get_pr(repo_name, token).json()
if (not pr):
print(f'{re... |
class OptionSeriesAreasplineSonificationDefaultinstrumentoptionsMappingLowpass(Options):
def frequency(self) -> 'OptionSeriesAreasplineSonificationDefaultinstrumentoptionsMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionSeriesAreasplineSonificationDefaultinstrumentoptionsMappingLowp... |
class MibTableRow(ManagedMibObject):
def __init__(self, name):
ManagedMibObject.__init__(self, name)
self._idToIdxCache = cache.Cache()
self._idxToIdCache = cache.Cache()
self._indexNames = ()
self._augmentingRows = set()
def oidToValue(self, syntax, identifier, impliedFl... |
class PaymentNoteWidget(FormSectionWidget):
def __init__(self, parent=None) -> None:
super().__init__(parent)
yours_widget = QLineEdit()
theirs_widget = QLineEdit()
theirs_widget.setEnabled(False)
self.add_title(_('Payment notes'))
self.add_row(_('Yours'), yours_widge... |
def get_editor_args(editor):
if (editor in ['vim', 'gvim', 'vim.basic', 'vim.tiny']):
return ['-f', '-o']
elif (editor == 'emacs'):
return ['-nw']
elif (editor == 'gedit'):
return ['-w', '--new-window']
elif (editor == 'nano'):
return ['-R']
elif (editor == 'code'):
... |
class GroupAddMaxID(GroupTest):
def runTest(self):
(port1,) = openflow_ports(1)
msg = ofp.message.group_add(group_type=ofp.OFPGT_ALL, group_id=ofp.OFPG_MAX, buckets=[create_bucket(actions=[ofp.action.output(port1)])])
self.controller.message_send(msg)
do_barrier(self.controller)
... |
class SigningDialogue(Dialogue):
INITIAL_PERFORMATIVES: FrozenSet[Message.Performative] = frozenset({SigningMessage.Performative.SIGN_TRANSACTION, SigningMessage.Performative.SIGN_MESSAGE})
TERMINAL_PERFORMATIVES: FrozenSet[Message.Performative] = frozenset({SigningMessage.Performative.SIGNED_TRANSACTION, Signi... |
def create_default_experience_config(db: Session, experience_config_data: dict) -> Optional[PrivacyExperienceConfig]:
experience_config_data = experience_config_data.copy()
experience_config_schema = transform_fields(transformation=escape, model=ExperienceConfigCreateWithId(**experience_config_data), fields=PRI... |
.usefixtures('_run_around_tests')
def test_transform_freeze_cache(mocker, tmpdir):
online = mocker.spy(Input, '_online')
offline = mocker.spy(Input, '_offline')
(output1=Output('/output/to/dataset'), input1=Input('/input1'))
def transform_me_data_from_online_cache(output1, input1):
pass
onli... |
class MulticlassClassificationTestPreset(TestPreset):
stattest: Optional[PossibleStatTestType]
stattest_threshold: Optional[float]
def __init__(self, stattest: Optional[PossibleStatTestType]=None, stattest_threshold: Optional[float]=None):
super().__init__()
self.stattest = stattest
... |
class DictActionWrapper(ActionWrapper[gym.Env]):
def __init__(self, env):
super().__init__(env)
assert (not isinstance(env.action_space, gym.spaces.Dict)), 'Action spaces is already a dict space!'
self._original_space = env.action_space
if isinstance(self._original_space, gym.spaces.... |
('path', ['examples/tutorials/structured_configs/5.1_structured_config_schema_same_config_group/my_app.py', 'examples/tutorials/structured_configs/5.2_structured_config_schema_different_config_group/my_app.py'])
def test_5_structured_config_schema(tmpdir: Path, path: str) -> None:
cmd = [path, ('hydra.run.dir=' + s... |
.EventDecorator()
def create_field_decomposition(dm, *args, **kwargs):
W = get_function_space(dm)
names = [s.name for s in W]
dms = [V.dm for V in W]
ctx = get_appctx(dm)
coarsen = get_ctx_coarsener(dm)
parent = get_parent(dm)
for d in dms:
add_hook(parent, setup=partial(push_parent,... |
class velx(object):
def __init__(self):
pass
def uOfXT(self, x, t):
pi = np.pi
if (manufactured_solution == 1):
return (np.sin(x[0]) * np.sin((x[1] + t)))
else:
return ((np.sin((pi * x[0])) * np.cos((pi * x[1]))) * np.sin(t))
def duOfXT(self, x, t):
... |
def test_datafile(name, ofp, pyversion):
data = test_data.read(name)
if (pyversion == 3):
key = 'python3'
if (key not in data):
key = 'python'
else:
key = 'python'
if (key not in data):
raise unittest.SkipTest(('no %s section in datafile' % key))
binary = ... |
class OptionPlotoptionsTimelineAccessibilityPoint(Options):
def dateFormat(self):
return self._config_get(None)
def dateFormat(self, text: str):
self._config(text, js_type=False)
def dateFormatter(self):
return self._config_get(None)
def dateFormatter(self, value: Any):
s... |
class OptionSeriesGaugeDial(Options):
def backgroundColor(self):
return self._config_get('#000000')
def backgroundColor(self, text: str):
self._config(text, js_type=False)
def baseLength(self):
return self._config_get('70%')
def baseLength(self, text: str):
self._config(t... |
def test_map_points_to_perimeter():
mesh_obj = load_mesh((parent_dir + '/data/Rectangle.STL'))
angles = [((np.pi / 4) * i) for i in range(8)]
points = [((10 * np.sin(angle)), (10 * np.cos(angle))) for angle in angles]
plotting_obj = {}
intersections = map_points_to_perimeter(mesh_obj, points, output... |
class ModelControllerAdapter(BaseModelController):
def __init__(self, backend: BaseModelController=None) -> None:
self.backend = backend
async def register_instance(self, instance: ModelInstance) -> bool:
return (await self.backend.register_instance(instance))
async def deregister_instance(s... |
def extractDlscanlationsWpcomstagingCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, t... |
class CookieTokenAuthMixin(RefreshTokenMutationMixin):
_jwt_settings(JWT_LONG_RUNNING_REFRESH_TOKEN=True)
def test_token_auth(self):
with catch_signal(token_issued) as token_issued_handler:
response = self.execute({self.user.USERNAME_FIELD: self.user.get_username(), 'password': 'dolphins'})
... |
def test_cluster_balls(nlp):
(ents, wgts) = zip(*[(c.text.lower(), c.vector) for c in (nlp('apple'), nlp('pear'), nlp('orange'), nlp('lemon'))])
model = KeyedVectors(wgts[0].size)
model.add_vectors(ents, list(wgts))
print(cluster_balls(model))
print(cluster_balls(model, root='orange')) |
def check_permissions(doctype, parent):
user = frappe.session.user
if ((not frappe.has_permission(doctype, 'select', user=user, parent_doctype=parent)) and (not frappe.has_permission(doctype, 'read', user=user, parent_doctype=parent))):
frappe.throw(f'Insufficient Permission for {doctype}', frappe.Permi... |
class RestClient():
def __init__(self, rest_address: str):
self._session = requests.session()
self.rest_address = rest_address
def get(self, url_base_path: str, request: Optional[Message]=None, used_params: Optional[List[str]]=None) -> bytes:
url = self._make_url(url_base_path=url_base_p... |
def main():
global_config = config['Global']
valid_dataloader = build_dataloader(config, 'Eval', device, logger)
post_process_class = build_post_process(config['PostProcess'], global_config)
if hasattr(post_process_class, 'character'):
char_num = len(getattr(post_process_class, 'character'))
... |
def extractWwwCentinniCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tag... |
class RelationshipTlsDomainTlsDomain(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():
laz... |
def extractLightnoveldistrictWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name,... |
.parametrize('param', [1, 'hola', [1, 2, 0], (True, False)])
def test_raises_error_when_ignore_format_not_permitted(param):
with pytest.raises(ValueError) as record:
CategoricalInitMixin(ignore_format=param)
msg = f'ignore_format takes only booleans True and False. Got {param} instead.'
assert (str(... |
def lazy_import():
from fastly.model.relationships_for_waf_rule import RelationshipsForWafRule
from fastly.model.type_waf_rule import TypeWafRule
from fastly.model.waf_rule import WafRule
from fastly.model.waf_rule_attributes import WafRuleAttributes
from fastly.model.waf_rule_response_data_all_of i... |
def dumpPrices(dbPath, elementMask, stationID=None, file=None, defaultZero=False, debug=0):
withTimes = (elementMask & Element.timestamp)
getBlanks = (elementMask & Element.blanks)
conn = sqlite3.connect(str(dbPath))
conn.execute('PRAGMA foreign_keys=ON')
cur = conn.cursor()
systems = {ID: name ... |
class AttrList():
def __init__(self, l, obj_wrapper=None):
if (not isinstance(l, list)):
l = list(l)
self._l_ = l
self._obj_wrapper = obj_wrapper
def __repr__(self):
return repr(self._l_)
def __eq__(self, other):
if isinstance(other, AttrList):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.