code stringlengths 281 23.7M |
|---|
def node_error_pass(get_error: Callable[([BMGraphBuilder, bn.BMGNode], Optional[BMGError])]) -> GraphFixer:
def error_pass(bmg: BMGraphBuilder) -> GraphFixerResult:
errors = ErrorReport()
nodes = bmg.all_ancestor_nodes()
for node in nodes:
error = get_error(bmg, node)
... |
def test_overlapping_schemas(hydra_restore_singletons: Any) -> None:
cs = ConfigStore.instance()
cs.store(name='config', node=Config)
cs.store(group='plugin', name='concrete', node=ConcretePlugin)
config_loader = ConfigLoaderImpl(config_search_path=create_config_search_path(None))
cfg = config_loade... |
def export_xml(color_list, export_grid=False):
(export_color_list, export_cname_list) = get_export_color_list(color_list, export_grid=export_grid)
xml_chars = '<!DOCTYPE PencilPalette>\n<palette>\n'
for idx in range(len(export_color_list)):
(r, g, b) = export_color_list[idx].rgb
name = expor... |
class UserConfigItem():
def __init__(self, desc: str=None) -> None:
self.default_value = None
self.is_optional = False
self.item_type = 'str'
self.desc = desc
self.value = None
self.user_set = False
def clone(self):
new_config_item = UserConfigItem()
... |
class OptionPlotoptionsColumnrangeSonificationContexttracksMappingLowpassFrequency(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 extractTranlatioWordpressCom(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)... |
class AddArticleForm(forms.Form):
title = forms.CharField(error_messages={'required': ''})
content = forms.CharField(error_messages={'required': ''})
abstract = forms.CharField(required=False)
cover_id = forms.CharField(required=False)
category = forms.IntegerField(required=False)
status = forms... |
_ocx_not_available
_not_currently_in_session
def test_GetRealDataForCodesAsStream(entrypoint):
from koapy import KiwoomOpenApiPlusRealType
code = '005930'
realtype_name = ''
code_list = [code]
fid_list = KiwoomOpenApiPlusRealType.get_fids_by_realtype_name(realtype_name)
opt_type = '0'
stream... |
def test_python_random_determinism():
generator = random.Random()
generator.seed('theseed', version=2)
assert (generator.randint(0, 100) == 72)
assert (generator.randint(0, 100) == 90)
assert (generator.randint(0, 100) == 41)
assert (generator.randint(0, 100) == 16)
assert (generator.randint... |
class FaucetUntaggedLLDPDefaultFallbackTest(FaucetUntaggedTest):
CONFIG = '\n lldp_beacon:\n send_interval: 5\n max_per_interval: 5\n interfaces:\n %(port_1)d:\n native_vlan: 100\n lldp_beacon:\n enable: True\n ... |
def test_pagination(setup_test_data, client, monkeypatch, helpers):
helpers.mock_current_fiscal_year(monkeypatch)
resp = client.get((url + '?limit=1'))
assert (resp.status_code == status.HTTP_200_OK)
response = resp.json()
assert (len(response['results']) == 1)
expected_results = [{'agency_name'... |
class OptionPlotoptionsTimelineSonificationContexttracksMappingHighpassFrequency(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... |
class THBattleFaithBootstrap(BootstrapAction):
game: 'THBattleFaith'
def __init__(self, params: Dict[(str, Any)], items: Dict[(Player, List[GameItem])], players: BatchList[Player]):
self.source = self.target = None
self.params = params
self.items = items
self.players = players
... |
class L2Distance(Loss):
def __init__(self, *, normalize: bool=True):
self.normalize = normalize
def __call__(self, guesses: Floats2d, truths: Floats2d) -> Tuple[(Floats2d, float)]:
return (self.get_grad(guesses, truths), self.get_loss(guesses, truths))
def get_grad(self, guesses: Floats2d, t... |
class Faucet8021XDynACLLoginTest(Faucet8021XCustomACLLoginTest):
DOT1X_EXPECTED_EVENTS = [{'ENABLED': {}}, {'PORT_UP': {'port': 'port_1', 'port_type': 'supplicant'}}, {'PORT_UP': {'port': 'port_2', 'port_type': 'supplicant'}}, {'PORT_UP': {'port': 'port_4', 'port_type': 'nfv'}}, {'AUTHENTICATION': {'port': 'port_1'... |
def create_award_type_aliases(client, config):
for (award_type, award_type_codes) in INDEX_ALIASES_TO_AWARD_TYPES.items():
alias_name = f"{config['query_alias_prefix']}-{award_type}"
if config['verbose']:
msg = f"Putting alias '{alias_name}' on {config['index_name']} with award codes {aw... |
class TestSyncMimeliteServers():
def _fake_client(self, dataset=None):
if (dataset is None):
dataset = [torch.rand(5, 2) for _ in range(3)]
dataset = DatasetFromList(dataset)
dataset = DummyUserData(dataset, SampleNet(SampleFC()))
clnt = MimeLiteClient(dataset=dat... |
class JSONTranslator():
def process_request(self, req, resp):
if (req.content_length in (None, 0)):
return
body = req.bounded_stream.read()
if (not body):
raise falcon.HTTPBadRequest(title='Empty request body', description='A valid JSON document is required.')
... |
class TestMatrixStoreBuildEndToEnd(TestMatrixStoreBuild):
def create_matrixstore(cls, data_factory, end_date, number_of_months):
cls.tempdir = tempfile.mkdtemp()
cls.data_file = import_test_data_full(cls.tempdir, data_factory, end_date, months=number_of_months)
def tearDownClass(cls):
sh... |
class DuschinskyResult():
J: np.ndarray
K: np.ndarray
ref: DuschinskyRef
def to_K_unitless(self, wavenums):
wavenums_m = (wavenums * 100.0)
conv = ((1 / np.sqrt((HBAR / ((((2 * np.pi) * wavenums_m) * C) * (BOHR2M ** 2))))) * AMU2KG_SQRT)
K_unitless = (self.K * conv)
retur... |
class OptionSeriesVennSonificationDefaultinstrumentoptionsActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(self, num: ... |
class CosmTradeDialogues(Model, BaseCosmTradeDialogues):
def __init__(self, **kwargs: Any) -> None:
Model.__init__(self, **kwargs)
def role_from_first_message(message: Message, receiver_address: Address) -> Dialogue.Role:
return CosmTradeDialogue.Role.AGENT
BaseCosmTradeDialogues... |
.skipif(('pandas' not in sys.modules), reason='Pandas is not installed.')
def test_union():
import pandas as pd
def t1(data: Annotated[(Union[(np.ndarray, pd.DataFrame, Sequence)], 'some annotation')]):
print(data)
task_spec = get_serializable(OrderedDict(), serialization_settings, t1)
variants ... |
def test_parse_color() -> None:
bad = ['', 'aaa', 'midnightblack', '#123', '#12345', '#1234567']
for s in bad:
with pytest.raises(ValueError):
staticmaps.parse_color(s)
good = ['0x1a2b3c', '0x1A2B3C', '#1a2b3c', '0x1A2B3C', '0x1A2B3C4D', 'black', 'RED', 'Green', 'transparent']
for s ... |
class RateTestCase(unittest.TestCase):
def test_timebase_argument_skipped(self):
r = Rate()
self.assertEqual(r.timebase, '25')
def test_timebase_argument_is_None(self):
r = Rate(timebase=None)
self.assertEqual(r.timebase, '25')
def test_timebase_attribute_is_set_to_None(self)... |
def test_adding_serviceaccount_annotations():
config = '\nrbac:\n create: true\n serviceAccountAnnotations:\n eks.amazonaws.com/role-arn: arn:aws:iam:::role/k8s.clustername.namespace.serviceaccount\n'
r = helm_template(config)
assert (r['serviceaccount'][uname]['metadata']['annotations']['eks.amazonaws... |
def extractScryaTranslations(item):
(chp, vol, frag) = extractChapterVolFragment(item['title'])
if ("So What if It's an RPG World!?" in item['tags']):
return buildReleaseMessageWithType(item, "So What if It's an RPG World!?", vol, chp, frag=frag)
if ('My Disciple Died Yet Again' in item['tags']):
... |
def get_featmetainfo(desc_file, feat_name):
f = open(desc_file)
for line in f:
line = line.split('\n')[0]
feat = line.split('|')[0]
if (feat_name == feat):
(feat_length, feat_type) = (line.split('|')[1], line.split('|')[2])
return (feat_length, feat_type) |
class TorchScriptOp(OperatorInterface):
def __init__(self, func_name: str):
super(TorchScriptOp, self).__init__()
self.func_name: str = func_name
self.func: Callable = None
self.fwd_out: torch.tensor = None
self.grad_in: torch.tensor = None
def build(self, op_schema: str)... |
def install_py_deps(deps_list):
if (sys.prefix == sys.base_prefix):
if ((get_distro() != 'guix') and os.path.exists(os.path.join(sysconfig.get_path('stdlib', (sysconfig.get_default_scheme() if hasattr(sysconfig, 'get_default_scheme') else sysconfig._get_default_scheme())), 'EXTERNALLY-MANAGED'))):
... |
class DisplayPackagedMessageAction(argparse.Action):
def __call__(self, parser, namespace, value, option_string=None):
print('E: You cannot perform this action:')
print('You installed Nautilus Terminal using a distribution package. If you encounter an issue, try to reinstall it or contact its mainta... |
def generate_exercise(env: Environment, spec_path: Path, exercise: Path, check: bool=False):
slug = exercise.name
meta_dir = (exercise / '.meta')
plugins_module = None
plugins_name = 'plugins'
plugins_source = (meta_dir / f'{plugins_name}.py')
try:
if plugins_source.is_file():
... |
class TaskResolverMixin(object):
def location(self) -> str:
pass
def name(self) -> str:
pass
def load_task(self, loader_args: List[str]) -> Task:
pass
def loader_args(self, settings: SerializationSettings, t: Task) -> List[str]:
pass
def get_all_tasks(self) -> List[Ta... |
def xx_disabled_test_integrate():
res = []
def calllater(f):
res.append(f)
ori = event.loop._call_soon_func
foo = Foo()
event.loop.integrate(calllater)
foo.emit('foo', {})
foo.emit('foo', {})
assert ((len(res) == 1) and (res[0].__name__ == 'iter'))
with raises(ValueError):
... |
class MockView():
endianness = 0
sections = {}
address_size = 32
def update_analysis_and_wait(self):
pass
def get_tags_at(self, _):
return list()
def get_data_var_at(self, _):
return None
def get_symbol_at(self, _):
return None
def get_function_at(self, _)... |
def show_example_dialog():
ImGui.SetNextWindowPos(ImGui.ImVec2(10.0, 70.0), ImGui.ImGuiCond_FirstUseEver)
ImGui.SetNextWindowSize(ImGui.ImVec2(300.0, 500.0), ImGui.ImGuiCond_FirstUseEver)
ImGui.Begin('\uf080 Statistics')
renderer_name = bgfx.getRendererName(bgfx.getRendererType())
ImGui.TextWrapped(... |
def test():
assert (len(pattern1) == 2), 'pattern1'
assert (len(pattern2) == 4), 'pattern2'
assert (len(pattern1[0]) == 1), 'pattern1'
assert any(((pattern1[0].get(attr) == 'amazon') for attr in ('lower', 'LOWER'))), 'pattern1'
assert (len(pattern1[1]) == 2), 'pattern122'
assert any(((pattern1[1... |
class OptionSeriesWordcloudZones(Options):
def className(self):
return self._config_get(None)
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get(None)
def color(self, text: str):
self._config(text, js_type=False)
... |
class OptionSeriesDumbbellSonificationContexttracksMappingTremoloSpeed(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 test_remove_circular_dependency_no(graph_no_dependency):
(nodes, _, cfg) = graph_no_dependency
instructions = [inst.copy() for inst in cfg.instructions]
remove_circular_dependency(cfg)
assert ((nodes[0].instructions == [instructions[0]]) and (set(nodes[1].instructions[:4]) == set(instructions[1:5]))... |
class GreetingWorkflowImpl(GreetingWorkflow):
async def get_greeting(self):
global a, b, c
a.append(str(Workflow.random_uuid()))
(await Workflow.sleep(1))
b.append(str(Workflow.random_uuid()))
(await Workflow.sleep(1))
c.append(str(Workflow.random_uuid()))
(aw... |
class AgentResource():
type: str
name: str
introduce: str
def from_dict(d: Dict[(str, Any)]) -> Optional[AgentResource]:
if (d is None):
return None
return AgentResource(type=d.get('type'), name=d.get('name'), introduce=d.get('introduce'))
def to_dict(self) -> Dict[(str, ... |
class OptionSeriesItemSonificationContexttracksPointgrouping(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 TestGetAsyncSearch():
('elasticsearch.Elasticsearch')
.asyncio
async def test_get_async_search(self, es):
es.async_search.get = mock.AsyncMock(return_value={'is_running': False, 'response': {'took': 1122, 'timed_out': False, 'hits': {'total': {'value': 1520, 'relation': 'eq'}}}})
r = r... |
def _get_synteny_scale(recipe, synteny_backend):
if ('blocks' in recipe):
if isinstance(recipe['blocks'], six.string_types):
scale = config.vals['blocks'][recipe['blocks']]
else:
scale = recipe['blocks']
else:
scale = config.vals['blocks'][synteny_backend.infer_bl... |
def app_config_from_env(app, prefix='FLASKBB_'):
for (key, value) in os.environ.items():
if key.startswith(prefix):
key = key[len(prefix):]
try:
value = ast.literal_eval(value)
except (ValueError, SyntaxError):
pass
app.config[k... |
class UART(_UARTPrimitive):
def __init__(self, device: SerialHandler=None, *, baudrate: int=9600, bits: int=8, parity: Parity=None, stop: int=1, timeout: float=1):
super().__init__(device)
self._set_uart_baud(baudrate)
if (bits == 8):
pd = 0
elif (bits == 9):
... |
def pull_apps(apps=None, bench_path='.', reset=False):
from bench.bench import Bench
from bench.utils.app import get_current_branch, get_remote
bench = Bench(bench_path)
rebase = ('--rebase' if bench.conf.get('rebase_on_pull') else '')
apps = (apps or bench.apps)
excluded_apps = bench.excluded_a... |
.parametrize('block_identifier,expected_output', ((1, 1), ((- 1), 0), ('latest', 'latest'), ('earliest', 'earliest'), ('pending', 'pending'), ('safe', 'safe'), ('finalized', 'finalized')))
def test_parse_block_identifier_int_and_string(w3, block_identifier, expected_output):
block_id = parse_block_identifier(w3, bl... |
_test
def test_parallel_logging() -> None:
graph = MyDistributedGraph()
graph.configure(MyDistributedConfig(output_filename=DISTRIBUTED_OUTPUT_FILENAME))
runner = ParallelRunner(graph=graph)
runner.run()
output_path = str((Path(runner._options.logger_config.output_directory) / Path(f'{runner._option... |
def test_aggregation_chain_fork():
class _EventInterface(ABC):
_epoch_stats(sum, input_name='attr1_sum')
_epoch_stats(np.mean, input_name='attr2_mean')
_episode_stats(sum, input_name='attr1_sum')
_episode_stats(np.mean, input_name='attr2_mean')
_step_stats(sum, input_name='at... |
def topic_card_body(topics: List[Tuple[(str, float)]]) -> HTML:
html = "\n <div class='flex-row w-100' style='margin-top: 20px; flex-wrap: wrap;'>\n <div style='min-width: 400px; flex: 1 1 auto;'>\n <div class='w-100 ta_center bold'>All PDFs</div>\n ... |
class FourWellAnaPot(AnaPotBase):
def __init__(self):
V_str = 'x**4 + y**4 - 2*x**2 - 4*y**2 + x*y + 0.3*x + 0.1*y'
xlim = ((- 1.75), 1.75)
ylim = ((- 1.75), 1.75)
minima = ((1., (- 1.), 0.0), ((- 0.), (- 1.), 0.0), ((- 1.), 1., 0.0))
super().__init__(V_str=V_str, xlim=xlim, ... |
def test_update_get_model(client: TestClient):
response = client.patch('/models/test_model', json={'stateless': False, 'batch_size': 128, 'run_on_gpu': True})
model_update = response.json()
assert (response.status_code == 200)
response = client.get('/models/test_model')
assert (response.status_code ... |
class Annotation():
thrift_spec = (None, (1, TType.I64, 'timestamp', None, None), (2, TType.STRING, 'value', None, None), (3, TType.STRUCT, 'host', (Endpoint, Endpoint.thrift_spec), None))
def __init__(self, timestamp=None, value=None, host=None):
self.timestamp = timestamp
self.value = value
... |
def update_warning_messages(database: DB, metadata_file: Path) -> None:
warning_messages_from_metadata_file = json.loads(metadata_file.read_text())['codes']
warning_messages = {int(code): message for (code, message) in warning_messages_from_metadata_file.items()}
models.create(database)
warning_messages... |
def write(self, command, method=None):
if ((len(command) > 3) and (command[3] == 176) and (len(command) > 5)):
command = ((((("'" + command[4]) + "'") + '(') + command[5]) + ')')
command = command.encode()
if (method == 'socket'):
log_command = []
for i in command:
if... |
class LogProgress():
def __init__(self, logger: logging.Logger, iterable: Iterable, updates: int=5, min_interval: int=1, time_per_it: bool=False, total: tp.Optional[int]=None, name: str='LogProgress', level: int=logging.INFO):
self.iterable = iterable
if (total is None):
assert isinstanc... |
class HomeBrewTestCase(unittest.TestCase):
def setUp(self):
self.wf = Workflow()
cask.wf = Workflow()
brew.wf = Workflow()
def test_get_all_formulae(self):
result = brew.get_all_formulae()
self.assertTrue((len(result) > 0))
def test_search_key_for_action(self):
... |
def parse_version(v):
undotted = v.split('.')
if (len(undotted) == 0):
raise ValueError('Versio number cannot be empty')
if (len(undotted) > 3):
raise ValueError('Version number cannot have more than 3 dots')
tag_match = re.match('([0-9]+)([a-z]+)([0-9]+)?', undotted[(- 1)])
if (tag_... |
def cli() -> None:
program = ArgumentParser(formatter_class=(lambda prog: HelpFormatter(prog, max_help_position=120)))
program.add_argument('--torch', help=wording.get('install_dependency_help').format(dependency='torch'), choices=TORCH.keys())
program.add_argument('--onnxruntime', help=wording.get('install... |
class HttpWorker(Thread, HttpReq):
def __init__(self, tname, task_queue, flt, suc, fail, headers={}, proxy=None, proxy_policy=None, retry=3, timeout=10, logger=None, keep_alive=None, stream_mode=False, lowspeed_threshold=None):
HttpReq.__init__(self, headers, proxy, proxy_policy, retry, timeout, logger, tna... |
def create_js_component_class(cls, cls_name, base_class='Component.prototype'):
assert (cls_name != 'Component')
mc = MetaCollector(cls)
mc.meta['std_functions'].add('op_instantiate')
total_code = []
funcs_code = []
const_code = []
err = 'Objects on JS Component classes can only be int, floa... |
def test_no_dict_action_wrapper():
base_env = GymMazeEnv(env='CartPole-v0')
env = NoDictSpacesWrapper.wrap(base_env)
assert isinstance(env.action_space, spaces.Discrete)
assert isinstance(env.action_spaces_dict, dict)
action = env.action_space.sample()
out_action = env.action(action)
assert ... |
class Message():
def __init__(self, location, kind, check_id, message, fatal, autofixed):
assert isinstance(location, Location)
assert (kind in ('info', 'style', 'metric', 'check', 'warning', 'lex error', 'error'))
if (check_id is not None):
assert isinstance(check_id, str)
... |
def extractWwwPurplecarnationCom(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)... |
.parametrize('filename', ['inforec_03.lis', 'inforec_04.lis'])
def test_inforec_unstructured(filename):
path = ('data/lis/records/' + filename)
(f,) = lis.load(path)
wellsite = f.wellsite_data()[0]
components = wellsite.components()
assert (wellsite.isstructured() == False)
assert (len(component... |
.django_db
def test_award_amount_success(client, monkeypatch, generic_account_data, unlinked_faba_account_data, helpers, elasticsearch_account_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_account_index)
helpers.patch_datetime_now(monkeypatch, 2022, 12, 31)
helpers.reset_dabs_cache()
resp ... |
class GreenPile():
def __init__(self, size_or_pool=1000):
if isinstance(size_or_pool, GreenPool):
self.pool = size_or_pool
else:
self.pool = GreenPool(size_or_pool)
self.waiters = queue.LightQueue()
self.counter = 0
def spawn(self, func, *args, **kw):
... |
def test_return_named_type_with_named_type_and_null_in_union():
'
schema = {'type': 'record', 'name': 'my_record', 'fields': [{'name': 'my_union', 'type': ['null', {'name': 'foo', 'type': 'fixed', 'size': 10}, {'name': 'bar', 'type': 'enum', 'symbols': ['A', 'B']}]}]}
records = [{'my_union': None}, {'my_uni... |
class ColabPainting(flx.PyWidget):
color = flx.ColorProp(settable=True, doc='Paint color')
status = flx.StringProp('', settable=True, doc='Status text')
def init(self):
self.set_color(random.choice(COLORS))
self.widget = ColabPaintingView(self)
self._update_participants()
def add... |
(bot, 'playerCollect')
def playerCollect(this, collector, collected):
if ((collector.type == 'player') and (collected.type == 'object')):
raw_item = collected.metadata[10]
item = Item.fromNotch(raw_item)
header = (("I'm so jealous. " + collector.username) if (collector.username != bot.userna... |
def init_adapter(model: 'PreTrainedModel', model_args: 'ModelArguments', finetuning_args: 'FinetuningArguments', is_trainable: bool, is_mergeable: bool) -> 'PreTrainedModel':
if ((finetuning_args.finetuning_type == 'none') and is_trainable):
raise ValueError('You cannot use finetuning_type=none while traini... |
def _run_scripts(args: argparse.Namespace, scripts: List[FalScript], faldbt: FalDbt):
scheduler = Scheduler([TaskGroup(FalLocalHookTask.from_fal_script(script)) for script in scripts])
parallel_executor(args, faldbt, scheduler)
failed_tasks: List[FalLocalHookTask] = [group.task for group in scheduler.filter... |
def extractMeteorStrikeCom(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'), ('WGM', "World's Greatest Militia", 'translated'), ('re;s', 'RE: Survival... |
def check_distribution():
codename = distro.codename().lower()
if (codename in BIONIC_CODE_NAMES):
logging.debug('Ubuntu 18.04 detected')
return 'bionic'
if (codename in FOCAL_CODE_NAMES):
logging.debug('Ubuntu 20.04 detected')
return 'focal'
if (codename in JAMMY_CODE_NA... |
def normalize_grib_keys(f):
f = alias_argument('levelist', ['level', 'levellist'])(f)
f = alias_argument('levtype', ['leveltype'])(f)
f = alias_argument('param', ['variable', 'parameter'])(f)
f = alias_argument('number', ['realization', 'realisation'])(f)
f = alias_argument('class', ['klass', 'class... |
class TestNonVendorProject(BaseAEATestCase, BaseTestCase):
capture_log = True
def setup(cls):
super(TestNonVendorProject, cls).setup()
cls.change_directory(Path('..'))
cls.agent_name = 'generic_buyer'
cls.run_cli_command('fetch', 'fetchai/generic_buyer:0.30.5', '--alias', cls.age... |
class OptionSeriesPolygonSonificationTracksMappingVolume(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):
self._c... |
def unbuffered(proc, stream='stdout'):
stream = getattr(proc, stream)
with contextlib.closing(stream):
while (prockilled == False):
out = []
last = stream.read(1)
if ((last == '') and (proc.poll() is not None)):
break
while (last not in new... |
def collect_view_data(request, second_nav, dc_dns_only=False, **context):
view_data = {'navi': get_navigation(request, second_nav, dc_dns_only=dc_dns_only), 'load_base': get_base_template(request), 'tasklog_cached': get_tasklog_cached(request), 'pending_tasks': get_user_tasks(request), 'dcs_form': DcSwitch(request,... |
def sitemap_to_df(sitemap_url, max_workers=8, recursive=True):
if sitemap_url.endswith('robots.txt'):
return pd.concat([sitemap_to_df(sitemap, recursive=recursive) for sitemap in _sitemaps_from_robotstxt(sitemap_url)], ignore_index=True)
if sitemap_url.endswith('xml.gz'):
xml_text = urlopen(Requ... |
def get_vm(filename):
trk = []
VM_Str = {'Virtual Box': 'VBox', 'VMware': 'WMvare'}
VM_Sign = {'Red Pill': '\x0f\x01\r\x00\x00\x00\x00A', 'VirtualPc trick': '\x0f?\x07\x0b', 'VMware trick': 'VMXh', 'VMCheck.dll': 'EC\x00\x01', 'VMCheck.dll for VirtualPC': '\x0f?\x07\x0bCEuyyyy', 'Xen': 'XenVMM', 'Bochs & QE... |
.parametrize('value,expected', (('', False), ('a', False), (1, False), (True, False), ({'a': 1, 'b': 2}, False), (None, False), (b'', False), (b'arst', False), (('a', 'b'), False), (['a', 'b'], False), ([b'a', b'b'], False), ([b'a', None, b'b'], False), (list(), False), ([None], False), (([],), False), (([tuple()],), F... |
class OptionPlotoptionsHeatmapSonificationContexttracksMappingLowpassFrequency(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 SrcInfo():
def __init__(self, filename, lineno, col_offset=None, end_lineno=None, end_col_offset=None, function=None):
self.filename = filename
self.lineno = lineno
self.col_offset = col_offset
self.end_lineno = end_lineno
self.end_col_offset = end_col_offset
se... |
class OptionPlotoptionsTimelineSonificationContexttracksPointgrouping(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):... |
.usefixtures('use_tmpdir')
def test_ensemble_config_fails_on_non_sensical_refcase_file():
refcase_file = 'CEST_PAS_UNE_REFCASE'
refcase_file_content = '\n_________________________________________ _____ ____________________\n\\______ \\_ _____/\\_ _____/\\_ ___ \\ / _ \\ / _____/\\_ _____... |
def test_overview_not_authorized(application, default_settings):
view = views.ManagementOverview.as_view('overview')
with application.test_request_context():
result = view()
messages = get_flashed_messages(with_categories=True)
expected = ('danger', 'You are not allowed to access the managem... |
class OptionSeriesSplineSonificationContexttracksActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(self, num: float):
... |
class FineTuningWrapper(nn.Module):
def __init__(self, trunk: nn.Module, feature_layer: str, head: nn.Module, freeze_trunk: bool=True) -> None:
super().__init__()
self.trunk: GraphModule = create_feature_extractor(trunk, [feature_layer])
self.head = head
self.feature_layer = feature_... |
class DcStorageView(APIView):
serializer = DcNodeStorageSerializer
order_by_default = ('node__hostname', 'zpool')
order_by_field_map = {'hostname': 'node__hostname', 'zpool': 'zpool'}
def __init__(self, request, name, data):
super(DcStorageView, self).__init__(request)
self.data = data
... |
class OptionsTableCell(OptionsWithTemplates):
def cssClasses(self):
return self._config_get([])
def cssClasses(self, values):
self._config(values)
def center(self):
return self._config_get()
def center(self, flag):
if flag:
self.component.attr['class'].add('te... |
class TestAddAndEjectComponent(AEATestCaseEmpty):
def test_add_and_eject(self):
result = self.add_item('skill', str(ECHO_SKILL_PUBLIC_ID), local=True)
assert (result.exit_code == 0)
result = self.eject_item('skill', str(ECHO_SKILL_PUBLIC_ID))
assert (result.exit_code == 0) |
class TestQuery(BodhiClientTestCase):
def test_with_bugs_empty_string(self, mocker):
client = bindings.BodhiClient()
client.send_request = mocker.MagicMock(return_value='return_value')
result = client.query(builds='bodhi-2.4.0-1.fc26', bugs='')
assert (result == 'return_value')
... |
.parametrize('existing_content', [None, 'blublu'])
def test_temporary_save_path(tmp_path: Path, existing_content: Optional[str]) -> None:
filepath = (tmp_path / 'save_and_move_test.txt')
if existing_content:
filepath.write_text(existing_content)
with utils.temporary_save_path(filepath) as tmp:
... |
class SequenceTester(UnitTestDBBase):
def setUp(self):
super(SequenceTester, self).setUp()
from stalker import Type
self.project_type = Type(name='Test Project Type', code='test', target_entity_type='Project')
from stalker.db.session import DBSession
DBSession.add(self.projec... |
def task_revoked_handler(sender, request, terminated, signum, expired, **kwargs):
if getattr(request, 'erigonesd_knows', False):
logger.info('Task %s[%s] in revoked_handler :: Already running - skipping', sender.name, request.id)
return
setattr(request, 'erigonesd_knows', True)
task_id = req... |
def generate_checksum(param_dict, merchant_key, salt=None):
params_string = __get_param_string__(param_dict)
salt = (salt if salt else __id_generator__(4))
final_string = f'{params_string}|{salt}'
hasher = hashlib.sha256(final_string.encode())
hash_string = hasher.hexdigest()
hash_string += salt... |
def extractThenovelstCom(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 tagm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.