code stringlengths 281 23.7M |
|---|
_baseline_registry.register_il_policy
class ObjectNavILPolicy(ILPolicy):
def __init__(self, observation_space: Space, action_space: Space, backbone_config: Config, model_config: Config, run_type: str):
super().__init__(ObjectNavILNet(observation_space=observation_space, model_config=model_config, backbone_c... |
class TestWriteProtectionCommands(EfuseTestCase):
def test_write_protect_efuse(self):
self.espefuse_py('write_protect_efuse -h')
if (arg_chip == 'esp32'):
efuse_lists = 'WR_DIS RD_DIS CODING_SCHEME\n XPD_SDIO_FORCE XPD_SDIO_REG XPD_SDIO_TIEH SPI_PAD_CONFIG_CLK\n... |
def extractAbodammenWpcomstagingCom(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_ty... |
.django_db
def test_failure_with_invalid_filters(client, monkeypatch, elasticsearch_award_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_award_index)
resp = client.post('/api/v2/search/spending_by_award', content_type='application/json', data=json.dumps({}))
assert (resp.status_code == status.H... |
def map_collection(func: Callable[(..., TReturn)], collection: Any) -> Any:
datatype = type(collection)
if isinstance(collection, Mapping):
return datatype(((key, func(val)) for (key, val) in collection.items()))
if is_string(collection):
return collection
elif isinstance(collection, Ite... |
class BlameHunk(object):
def _from_c(cls, blame, ptr):
hunk = cls.__new__(cls)
hunk._blame = blame
hunk._hunk = ptr
return hunk
def lines_in_hunk(self):
return self._hunk.lines_in_hunk
def boundary(self):
return (int(ffi.cast('int', self._hunk.boundary)) != 0)... |
class FillingParser(RewritingParser):
default_encoding = 'utf8'
text_input_types = set('text hidden search tel url email datetime date month week time datetime-local number range color'.split())
def __init__(self, defaults, errors=None, use_all_keys=False, error_formatters=None, error_class='error', add_att... |
def wenxin_generate_stream(model: ProxyModel, tokenizer, params, device, context_len=2048):
MODEL_VERSION = {'ERNIE-Bot': 'completions', 'ERNIE-Bot-turbo': 'eb-instant'}
model_params = model.get_params()
model_name = model_params.proxyllm_backend
model_version = MODEL_VERSION.get(model_name)
if (not... |
def chromosome_scatter(cnarr, segments, variants, show_range, show_gene, antitarget_marker, do_trend, by_bin, window_width, y_min, y_max, title, segment_color):
(sel_probes, sel_segs, sel_snvs, window_coords, genes, chrom) = select_range_genes(cnarr, segments, variants, show_range, show_gene, window_width)
if (... |
def upgrade():
op.add_column('copr_dir', sa.Column('ownername', sa.Text(), nullable=False))
op.create_index(op.f('ix_copr_dir_ownername'), 'copr_dir', ['ownername'], unique=False)
op.create_unique_constraint('ownername_copr_dir_uniq', 'copr_dir', ['ownername', 'name'])
op.drop_constraint(u'copr_dir_copr... |
class OptionPlotoptionsNetworkgraphSonificationDefaultspeechoptionsMappingTime(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 test_footballmatch_module_no_matchdata(lfs_match, monkeypatch):
def no_match(*args, **kwargs):
return {'fixtureListMeta': {'scorersButtonShouldBeEnabled': False}, 'matchData': []}
monkeypatch.setattr('qtile_extras.resources.footballscores.FootballMatch._get_scores_fixtures', no_match)
che = lfs_... |
def test_transformer_with_default_params():
df = pd.DataFrame({'var_A': (((['A'] * 6) + (['B'] * 10)) + (['C'] * 4)), 'var_B': (((['A'] * 10) + (['B'] * 6)) + (['C'] * 4)), 'var_C': (((['X'] * 7) + (['Y'] * 5)) + (['Z'] * 8)), 'var_D': (((['L'] * 3) + (['M'] * 9)) + (['N'] * 8)), 'var_E': (((['R'] * 7) + (['S'] * 4... |
def test_decode_endpoints():
p = Prometheus()
hashes = {'6b33db53faf33c77d694ecab2e3fefadc7dacc70': {'__name__': 'poseidon_endpoint_metadata', 'acls': '[]', 'controller_type': 'faucet', 'ether_vendor': 'Micro-Star', 'hash_id': '6b33db53faf33c77d694ecab2e3fefadc7dacc70', 'ignore': 'False', 'instance': 'poseidon:... |
def prophet_copy(m, cutoff=None):
if (m.history is None):
raise Exception('This is for copying a fitted Prophet object.')
if m.specified_changepoints:
changepoints = m.changepoints
if (cutoff is not None):
last_history_date = max(m.history['ds'][(m.history['ds'] <= cutoff)])
... |
def test_service_annotations():
config = '\nservice:\n annotations:\n cloud.google.com/load-balancer-type: "Internal"\n '
r = helm_template(config)
s = r['service'][name]['metadata']['annotations']['cloud.google.com/load-balancer-type']
assert (s == 'Internal')
config = '\nservice:\n annotat... |
def failed_role_request(test, role, gen, code, con=None):
if (con == None):
con = test.controller
request = ofp.message.role_request(role=role, generation_id=gen)
(response, _) = con.transact(request)
test.assertIsInstance(response, ofp.message.role_request_failed_error_msg)
test.assertEqual... |
def fxfy_loops(ft: A, fn: A, theta: A):
n0 = theta.size
fx = np.empty_like(ft)
fy = np.empty_like(fn)
for index in range(n0):
sin_theta = np.sin(theta[index])
cos_theta = np.cos(theta[index])
fx[index] = ((cos_theta * ft[index]) - (sin_theta * fn[index]))
fy[index] = ((si... |
.django_db
def test_financial_obligations(client, financial_obligations_models):
resp = client.get('/api/v2/federal_obligations/?funding_agency_id=654&fiscal_year=2016')
assert (resp.status_code == status.HTTP_200_OK)
assert (len(resp.data['results']) == 2)
res_awesome = resp.data['results'][0]
asse... |
class OptionPlotoptionsLineSonificationContexttracksMappingTremolo(Options):
def depth(self) -> 'OptionPlotoptionsLineSonificationContexttracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionPlotoptionsLineSonificationContexttracksMappingTremoloDepth)
def speed(self) -> 'OptionPlotopti... |
class ICSCalendarData():
def __init__(self, device_data):
self.name = device_data[CONF_NAME]
self._days = device_data[CONF_DAYS]
self._offset_hours = device_data[CONF_OFFSET_HOURS]
self.include_all_day = device_data[CONF_INCLUDE_ALL_DAY]
self._summary_prefix: str = device_dat... |
def test_application_close(test_client_factory):
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
(await websocket.accept())
(await websocket.close(status.WS_1001_GOING_AWAY))
client = test_client_factory(app)
... |
def test_oniom_md():
calc_dict = {'high': {'type': 'pypsi4', 'method': 'scf', 'basis': 'sto-3g'}, 'low': {'type': 'pyxtb'}}
high_inds = (4, 5, 6)
from pysisyphus.calculators.ONIOM import ONIOM
oniom = ONIOM(calc_dict, high_inds)
geom = geom_loader('lib:acetaldehyd_oniom.xyz')
geom.set_calculator... |
.parametrize('type_, test, expected', [('str', 'value', 'value'), ('int', '10', 10), ('float', '0.5', 0.5), ('bool', 'yes', True), ('bool', 'y', True), ('bool', 'true', True), ('bool', 'True', True), ('bool', '1', True), ('bool', 'anything_else', False), ('SomeType', 'value', 'value')])
def test_from_str_to(type_, test... |
class LivenessAnalysis():
def __init__(self, cfg: ControlFlowGraph):
self._cfg: ControlFlowGraph = cfg
self._uses_block: DefaultDict[(BasicBlock, InsertionOrderedSet[Variable])] = defaultdict(InsertionOrderedSet)
self._defs_block: DefaultDict[(BasicBlock, InsertionOrderedSet[Variable])] = de... |
def test_medium_dispersion():
m_PR = td.PoleResidue(eps_inf=1.0, poles=[(((- 1) + 2j), (1 + 3j)), (((- 2) + 4j), (1 + 5j))])
m_SM = td.Sellmeier(coeffs=[(2, 3), (2, 4)])
m_LZ = td.Lorentz(eps_inf=1.0, coeffs=[(1, 3, 2), (2, 4, 1)])
m_LZ2 = td.Lorentz(eps_inf=1.0, coeffs=[(1, 2, 3), (2, 1, 4)])
m_DR ... |
class LedgerApiDialogues(Model, BaseLedgerApiDialogues):
def __init__(self, **kwargs: Any) -> None:
Model.__init__(self, **kwargs)
def role_from_first_message(message: Message, receiver_address: Address) -> BaseDialogue.Role:
return BaseLedgerApiDialogue.Role.AGENT
BaseLedgerApiD... |
def get_table_features(dp, waiters, to_user=True):
stats = dp.ofproto_parser.OFPTableFeaturesStatsRequest(dp, 0, [])
msgs = []
ofproto = dp.ofproto
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
p_type_instructions = [ofproto.OFPTFPT_INSTRUCTIONS, ofproto.OFPTFPT_INSTRUCTIONS_MISS]
... |
class IntegrationGrid():
points = None
h = None
_N = None
_dim = None
_runtime = None
def __init__(self, N, integration_domain, grid_func=grid_func, disable_integration_domain_check=False):
start = perf_counter()
self._check_inputs(N, integration_domain, disable_integration_domai... |
(urls.POLICY_POST_WEBHOOK_DETAIL, status_code=HTTP_200_OK, dependencies=[Security(verify_oauth_client, scopes=[scopes.WEBHOOK_DELETE])], response_model=schemas.PolicyWebhookDeleteResponse)
def delete_post_execution_webhook(*, db: Session=Depends(deps.get_db), policy_key: FidesKey, post_webhook_key: FidesKey) -> schemas... |
def runon30seconds():
procarr = []
for y in range(0, len(Settings.Controllers)):
if Settings.Controllers[y]:
if Settings.Controllers[y].enabled:
if Settings.Controllers[y].timer30s:
t = threading.Thread(target=Settings.Controllers[y].timer_thirty_second)
... |
def get_current_ethdo_version():
version = UNKNOWN_VERSION
try:
process_result = subprocess.run([(ETHDO_INSTALLED_PATH + 'ethdo'), 'version'], capture_output=True, text=True)
process_output = ((process_result.stdout + '\n') + process_result.stderr)
version = process_output.strip()
ex... |
class TestMassEditWalk(unittest.TestCase):
def setUp(self):
self.workspace = Workspace()
self.subdirectory = self.workspace.get_directory()
self.file_names = []
for ii in range(3):
file_name = self.workspace.get_file(parent_dir=self.subdirectory, extension='.txt')
... |
.parametrize('data,expected', [({'hello': 'world'}, b'hello=world'), ({'number': [1, 2]}, b'number=1&number=2')])
def test_urlencoded_form_handler_serialize(data, expected):
handler = media.URLEncodedFormHandler()
assert (handler.serialize(data, falcon.MEDIA_URLENCODED) == expected)
value = falcon.async_to_... |
class OptionSeriesBubbleDataEvents(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)
def... |
def extractMintmatchalatteBlogspotCom(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_... |
class TestIndexListFilterAlias(TestCase):
def builder(self, key='2'):
self.client = Mock()
self.client.info.return_value = get_es_ver()
self.client.cat.indices.return_value = get_testvals(key, 'state')
self.client.indices.get_settings.return_value = get_testvals(key, 'settings')
... |
def remove_old_backups(bpath):
max_backups = get_setting_int('backups', 4)
versions = sorted([parse_version(version) for version in listdir(bpath)])
if (len(versions) < 2):
return
try:
installed_version = load_widevine_config()['version']
except TypeError:
log(2, 'could not d... |
class Result():
difficulty: Any
base_fee: Any
state_root: Any = None
tx_root: Any = None
receipt_root: Any = None
withdrawals_root: Any = None
logs_hash: Any = None
bloom: Any = None
receipts: Any = None
rejected: Any = None
gas_used: Any = None
def to_json(self) -> Any:
... |
class Migration(migrations.Migration):
dependencies = [('search', '0031_add_iija_spending_fields')]
operations = [migrations.AddField(model_name='awardsearch', name='pop_congressional_code_current', field=models.TextField(null=True)), migrations.AddField(model_name='awardsearch', name='recipient_location_congre... |
def timeRange(start: Time_t, end: Time_t, step: float) -> Iterator[dt.datetime]:
assert (step > 0)
delta = dt.timedelta(seconds=step)
t = _fillDate(start)
tz = (dt.timezone.utc if t.tzinfo else None)
now = dt.datetime.now(tz)
while (t < now):
t += delta
while (t <= _fillDate(end)):
... |
class ShipitPathMap(object):
def __init__(self) -> None:
self.roots = []
self.mapping = []
self.exclusion = []
def add_mapping(self, fbsource_dir, target_dir) -> None:
self.roots.append(fbsource_dir)
self.mapping.append((fbsource_dir, target_dir))
def add_exclusion(se... |
def main():
screenWidth = 800
screenHeight = 450
set_config_flags(ConfigFlags.FLAG_MSAA_4X_HINT)
init_window(screenWidth, screenHeight, 'raylib [shapes] example - cubic-bezier lines')
start = Vector2(0, 0)
end = Vector2(screenWidth, screenHeight)
set_target_fps(60)
while (not window_shou... |
class BulletPointDescriptor(TypeDescriptor[Iterable[str]]):
def visit_default(self, node: 'AbstractSchemaNode', **kwargs: Any) -> List[str]:
depth = kwargs['depth']
space = ('* ' + (depth * ' '))
return [f'{space}{node.id}: {node.__class__.__name__} # {node.description}']
def visit_objec... |
class invert_test_case(unittest.TestCase):
def test_invert_with_unique_values(self):
i = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
o = _invert(i)
r = {1: ['a'], 2: ['b'], 3: ['c'], 4: ['d'], 5: ['e']}
self.assertEqual(o, r)
def test_invert_with_flat_unique_values(self):
i ... |
(IDataViewWidget)
class DataViewWidget(MDataViewWidget, LayoutWidget):
control_factory = Callable(DataViewTreeView)
selection_type = Enum('row', 'column', 'item')
selection_mode = Enum('extended', 'none', 'single')
control = Instance(QAbstractItemView)
_item_model = Instance(QAbstractItemModel)
... |
(python=PYTHON_VERSIONS)
def test_tools(session: Session) -> None:
_upgrade_basic(session)
install_cmd = ['pip', 'install']
session.install('pytest')
install_hydra(session, install_cmd)
tools = [x for x in sorted(os.listdir(os.path.join(BASE, 'tools'))) if (not os.path.isfile(x))]
for tool in to... |
def fix_event_and_speaker_images():
events = Event.query.filter(Event.original_image_url.isnot(None), or_((Event.thumbnail_image_url == None), (Event.large_image_url == None), (Event.icon_image_url == None))).all()
logger.info('Resizing images of %s events...', len(events))
for event in events:
logg... |
def run(url_suffix='', retry=0):
url = sys.argv[0]
log.debug(('Running action: %s' % url))
if ('/clear_cookies' in url):
client = Client()
cookies = client._locate_cookies()
log.info(('Removing cookies from %s' % cookies))
if os.path.isfile(cookies):
os.remove(coo... |
class Migration(migrations.Migration):
dependencies = [('users', '0002_auto__1548')]
operations = [migrations.AlterField(model_name='userprofile', name='current_level', field=models.IntegerField(choices=[(1, 'Level One'), (2, 'Level Two')], default=1)), migrations.AlterField(model_name='userprofile', name='phon... |
class TestLayout(BaseTestMixin, unittest.TestCase):
def setUp(self):
BaseTestMixin.setUp(self)
def tearDown(self):
BaseTestMixin.tearDown(self)
_toolkit([ToolkitName.qt])
def test_qt_resizable_in_vgroup(self):
with reraise_exceptions(), create_ui(VResizeDialog()) as ui:
... |
def main():
if (('-h' in sys.argv) or ('--help' in sys.argv)):
docopt(__doc__)
project_path = project.check_for_project('.')
if (project_path is None):
raise ProjectNotFound
project.main._add_to_sys_path(project_path)
pytest_args = sys.argv[(sys.argv.index('test') + 1):]
if ((not... |
def check_fix_numbering(log, releases, series_id):
if (not isinstance(series_id, str)):
log.warning('Series id is not a string: %s -> %s', series_id, type(series_id))
assert isinstance(series_id, (str, int))
series_id = str(series_id)
conf = load_lut()
must_renumber = (series_id in c... |
('flytekit.core.data_persistence.FileAccessProvider.put_data')
def test_optional_flytefile_in_dataclassjsonmixin(mock_upload_dir):
remote_path = 's3://tmp/file'
mock_upload_dir.return_value = remote_path
with tempfile.TemporaryFile() as f:
f.write(b'abc')
f1 = FlyteFile('f1', remote_path=rem... |
def select(read_list, write_list, error_list, timeout=None):
if (timeout is not None):
try:
timeout = float(timeout)
except ValueError:
raise TypeError('Expected number for timeout')
hub = get_hub()
timers = []
current = eventlet.getcurrent()
assert (hub.green... |
class Solution(object):
def checkPossibility(self, nums):
def is_non_decreasing(ns):
p = None
for n in ns:
if (p is None):
p = n
continue
if (n < p):
return False
p = n
... |
.django_db
def test_tas_with_no_program_activity(client, monkeypatch, tas_with_no_object_class, helpers):
helpers.mock_current_fiscal_year(monkeypatch)
tas = '001-X-0000-000'
resp = client.get(url.format(tas=tas, query_params=''))
expected_result = {'fiscal_year': helpers.get_mocked_current_fiscal_year(... |
def test_non_utf_8_body_in_ignored_paths_with_capture_body(app, elasticapm_client):
client = TestClient(app)
elasticapm_client.config.update(1, capture_body='all', transaction_ignore_urls='/hello')
response = client.post('/hello', data=b'b$\x19\xc2')
assert (response.status_code == 200)
assert (len(... |
def write_json_files(stubs_dict):
class BytesEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, bytes):
return base64.b64encode(obj).decode('ascii')
return json.JSONEncoder.default(self, obj)
for (filename, stub_data) in stubs_dict.items():
... |
def test_missing_cursor_value(response_with_body):
config = CursorPaginationConfiguration(cursor_param='after', field='hash')
request_params: SaaSRequestParams = SaaSRequestParams(method=HTTPMethod.GET, path='/conversations')
paginator = CursorPaginationStrategy(config)
next_request: SaaSRequestParams =... |
class Solution():
def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
def sumBinary(node, s):
if (node is None):
return s
ns = ((s + s) + node.val)
if ((node.left is None) and (node.right is None)):
return ns
elif (node.le... |
def longest_consecutive_sequence(seq: str, char: str) -> int:
assert (len(char) == 1)
longest = 0
current_streak = 0
for c in seq:
if (c == char):
current_streak += 1
else:
current_streak = 0
if (current_streak > longest):
longest = current_str... |
def test_iou_score():
box1 = [(0, 0), (100, 0), (100, 100), (0, 100)]
box2 = [(50, 50), (100, 50), (100, 100), (50, 100)]
assert (keras_ocr.evaluation.iou_score(box1, box2) == 0.25)
box2 = [(100, 100), (200, 100), (200, 200), (100, 200)]
assert (keras_ocr.evaluation.iou_score(box1, box2) == 0.0) |
def test_get_registration_stats(db, client, jwt):
speaker = SpeakerFactory()
db.session.add(speaker)
db.session.commit()
response = client.get('/v1/user-check-in/stats/event/1?session_ids=1', headers=jwt)
result = {'session_stats': [{'check_in': 0, 'check_out': 0, 'manual_count': {}, 'session_id': '... |
class GaussianTimeOutSimulator(TimeOutSimulator):
def __init__(self, **kwargs):
init_self_cfg(self, component_class=__class__, config_class=GaussianTimeOutSimulatorConfig, **kwargs)
super().__init__(**kwargs)
self.duration_distribution_generator = instantiate(self.cfg.duration_distribution_g... |
def test_default_setup_provider_is_ansible(tmpdir):
wd = tmpdir.strpath
ssh_key_path = os.path.join(wd, 'id_rsa.pem')
with open(ssh_key_path, 'w+') as ssh_key_file:
ssh_key_file.write('')
ssh_key_file.flush()
config_path = os.path.join(wd, 'config.ini')
with open(config_path, 'w+') a... |
def read_data(inFile):
with open(inFile, 'r', encoding='utf-8') as fd:
line = fd.readline().strip()
if line.startswith('Filetype:'):
a = line.split(':', 1)
if (not a[1].strip().startswith(FLIPPER_NFC_FILETYPE)):
print(f'Error: {inFile} is not a Flipper NFC dat... |
def _replace_contraction_with_var_where_possible(instruction: Instruction):
for expr in _find_cast_subexpressions(instruction):
if (_is_cast(expr.operand) and expr.contraction):
if (expr.type.size < expr.operand.type.size):
if (expr.type.size == expr.operand.operand.type.size):
... |
_action_type(ofproto.OFPAT_COPY_FIELD, ofproto.OFP_ACTION_COPY_FIELD_SIZE)
class OFPActionCopyField(OFPAction):
def __init__(self, n_bits=0, src_offset=0, dst_offset=0, oxm_ids=None, type_=None, len_=None):
oxm_ids = (oxm_ids if oxm_ids else [])
super(OFPActionCopyField, self).__init__()
sel... |
class TestSmithWatermanDecoder(unittest.TestCase):
def setUp(self):
if torch.cuda.is_available():
cuda_device = torch.device('cuda')
torch.manual_seed(2)
(B, S, N, M) = (3, 3, 5, 5)
self.theta = torch.rand(B, N, M, requires_grad=True, dtype=torch.float32, devi... |
class OptionPlotoptionsSunburstSonificationTracksMappingLowpassFrequency(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):... |
('new')
('--username', '-u', help='The username of the user.')
('--email', '-e', type=EmailType(), help='The email address of the user.')
('--password', '-p', help='The password of the user.')
('--group', '-g', help='The group of the user.', type=click.Choice(['admin', 'super_mod', 'mod', 'member']))
def new_user(usern... |
class TestLocalizedDecimalField(TestCase):
_settings(LANGUAGE_CODE='pl')
def test_to_internal_value(self):
field = serializers.DecimalField(max_digits=2, decimal_places=1, localize=True)
assert (field.to_internal_value('1,1') == Decimal('1.1'))
_settings(LANGUAGE_CODE='pl')
def test_to_r... |
.parametrize('params', (['t', 'u'], ['u', 't']))
.parametrize('levels', ([500, 850], [850, 500]))
.parametrize('source_name', ['indexed-directory'])
def test_indexing_to_xarray(params, levels, source_name):
request = dict(level=levels, variable=params, date=, time='1200')
(ds, __tmp, total, n) = get_fixtures(so... |
class OptionPlotoptionsNetworkgraphSonificationTracksMappingLowpassFrequency(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: s... |
def _get_valid_extension(fname: str) -> str:
valid_extensions = ['.json', '.yaml', '.hdf5', '.h5', '.hdf5.gz']
extensions = [s.lower() for s in pathlib.Path(fname).suffixes[(- 2):]]
if (len(extensions) == 0):
raise FileError(f"File '{fname}' missing extension.")
single_extension = extensions[(- ... |
def extractNovelfanatistWordpressCom(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_t... |
_in_both()
def test_calllater():
def x1():
print('called later')
def x2(i):
print('called with', i)
def x3(i, j):
print('called with', i, 'and', j)
loop.call_soon(x1)
loop.call_soon(x1)
print('xx')
loop.iter()
loop.call_soon(x2, 3)
loop.call_soon(x2, 4)
pr... |
class ACL():
def __init__(self, faucetconfgetsetter):
self.logger = logging.getLogger('acl')
self.frpc = faucetconfgetsetter
def _config_file_paths(self, file_paths):
return [self.frpc.config_file_path(f) for f in file_paths]
def include_acl_files(self, rules_doc, rules_file, coproce... |
('sys.argv', ['flakehell'])
def test_exceptions(capsys, tmp_path: Path):
text = '\n [tool.flakehell.plugins]\n pyflakes = ["+*"]\n\n [tool.flakehell.exceptions."tests/"]\n pyflakes = ["-F401"]\n '
(tmp_path / 'pyproject.toml').write_text(dedent(text))
(tmp_path / 'example.py').write_text('imp... |
class Schedule(object):
def __init__(self, ctx):
self.ctx = ctx
self.events = []
self.passed = 0.0
self.clock = 0.0
self.last_clock = 0
self.started = False
def pending(self):
return len(self.events)
def add(self, e):
self.events.append(e)
... |
class Solution():
def maxNumberOfBalloons(self, text: str) -> int:
base = Counter('balloon')
tr = {}
for a in text:
if (a not in base):
continue
tr[a] = (tr.get(a, 0) + 1)
multiple = len(text)
for k in base.keys():
if (k not... |
class GenerateActionMetaData():
RECENCY_SLOPE = 30
def __init__(self, index_name, type_name, conflicting_ids=None, conflict_probability=None, on_conflict=None, recency=None, rand=random.random, randint=random.randint, randexp=random.expovariate, use_create=False):
if type_name:
self.meta_dat... |
class ERC20IndexedPattern(DeclarationUtils, AbstractAstPattern):
name = 'ERC20 Indexed Pattern'
description = "Events defined by ERC20 specification should use the 'indexed' keyword."
severity = Severity.LOW
tags = {}
def find_matches(self) -> List[PatternMatch]:
ast_root = self.get_ast_root... |
.requires_window_manager
def test_analyse_success(mock_storage, qtbot, ert_mock):
(target, source) = mock_storage
analyse = Analyse(ert_mock, target, source)
thread = QThread()
with qtbot.waitSignals([analyse.finished, thread.finished], timeout=2000, raising=True):
analyse.moveToThread(thread)
... |
class RefreshSequencer(Module):
def __init__(self, cmd, trp, trfc, postponing=1):
self.start = Signal()
self.done = Signal()
executer = RefreshExecuter(cmd, trp, trfc)
self.submodules += executer
count = Signal(bits_for(postponing), reset=(postponing - 1))
self.sync +... |
(expression='^Finished Phase (?P<phase>\\d+) in (?P<duration>[^ ]+) seconds.')
def phase_finished(match: typing.Match[str], info: SpecificInfo) -> SpecificInfo:
major = int(match.group('phase'))
duration = float(match.group('duration'))
duration_dict = {f'phase{major}_duration_raw': duration}
return att... |
.parametrize('estimator, cv, threshold, scoring, dropped_features, performances', _model_and_expectations)
def test_classification(estimator, cv, threshold, scoring, dropped_features, performances, df_test):
(X, y) = df_test
sel = RecursiveFeatureAddition(estimator=estimator, cv=cv, threshold=threshold, scoring... |
def bulk_run_args__init__(self, device_to_commands=None, timeout=bulk_run_args.thrift_spec[3][4], open_timeout=bulk_run_args.thrift_spec[4][4], client_ip=bulk_run_args.thrift_spec[10][4], client_port=bulk_run_args.thrift_spec[11][4], uuid=bulk_run_args.thrift_spec[12][4]):
self.device_to_commands = device_to_comman... |
def _test_generate_delft_with_multiple_tokens_tei_only(tmp_path: Path, model_name: str, file_suffix: str, tei_root: etree.ElementBase, tokens: Sequence[str], expected_labels: Sequence[str], data_generator: ModelDataGenerator, layout_document: Optional[LayoutDocument]=None):
tei_source_path = (tmp_path / 'tei')
... |
class TestGlobalScriptContainer(unittest.TestCase):
def test_init_with_no_scripts(self):
gsc = containers.GlobalScriptContainer()
self.assertEqual(len(gsc.loaded_data), 0)
_settings(GLOBAL_SCRIPTS={})
def test_start_with_no_scripts(self):
gsc = containers.GlobalScriptContainer()
... |
class Demo(lg.Graph):
GENERATOR: Generator
VIZ: SimpleVizGroup
def setup(self) -> None:
self.GENERATOR.configure(GeneratorConfig(sample_rate=SAMPLE_RATE, num_features=NUM_FEATURES))
def connections(self) -> lg.Connections:
return ((self.GENERATOR.OUTPUT, self.VIZ.INPUT), (self.GENERATOR.... |
class TestOFPQueueStatsReply(unittest.TestCase):
class Datapath(object):
ofproto = ofproto
ofproto_parser = ofproto_v1_0_parser
c = OFPQueueStatsReply(Datapath)
def setUp(self):
pass
def tearDown(self):
pass
def test_init(self):
pass
def test_parser(self):... |
def find_referenced_fides_keys(resource: object) -> Set[FidesKey]:
referenced_fides_keys: Set[FidesKey] = set()
if (isinstance(resource, str) and (not isinstance(resource, Enum))):
return set()
signature = inspect.signature(type(resource), follow_wrapped=True)
attributes = filter((lambda paramet... |
class ScopeableStatsProxy(object):
EXTENDABLE_FUNC = ['incr', 'decr', 'timing', 'timer', 'gauge', 'set']
def __init__(self, client, prefix=None):
self._client = client
self._scope_prefix = prefix
for extendable_func in self.EXTENDABLE_FUNC:
base_func = getattr(self._client, e... |
_defaults()
class PageSchema(Schema):
class Meta():
type_ = 'page'
self_view = 'v1.page_detail'
self_view_kwargs = {'id': '<id>'}
inflect = dasherize
id = fields.Str(dump_only=True)
name = fields.Str(required=True)
title = fields.Str(allow_none=True)
url = fields.Stri... |
.parametrize('amount, min_deposit_size, success', [((2000 * (10 ** 18)), (2000 * (10 ** 18)), True), ((1000 * (10 ** 18)), (100 * (10 ** 18)), True), ((1500 * (10 ** 18)), (1499 * (10 ** 18)), True), (1, 1, True), ((999 * (10 ** 18)), (1000 * (10 ** 18)), False), ((10 * (10 ** 18)), (1500 * (10 ** 18)), False), (0, 1, ... |
def main():
parser = argparse.ArgumentParser(prog='3d_diagrams', description='Plot 3D gamut in a different color spaces.')
parser.add_argument('--space', '-s', help='Desired space.')
parser.add_argument('--gamut', '-g', default='srgb', help='Gamut space to render space in. Gamut space must be bounded and mu... |
class OptionSeriesTimelineDragdropGuideboxDefault(Options):
def className(self):
return self._config_get('highcharts-drag-box-default')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('rgba(0, 0, 0, 0.1)')
def color(self,... |
.usefixtures('use_tmpdir')
.parametrize('queue_system, queue_system_option', [('LSF', 'LSF_SERVER'), ('SLURM', 'SQUEUE'), ('TORQUE', 'QUEUE')])
def test_initializing_empty_config_queue_options_resets_to_default_value(queue_system, queue_system_option):
filename = 'config.ert'
with open(filename, 'w', encoding='... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.