code stringlengths 281 23.7M |
|---|
class Solution(object):
def longest_substr(self, string, k):
if (string is None):
raise TypeError('string cannot be None')
if (k is None):
raise TypeError('k cannot be None')
low_index = 0
max_length = 0
chars_to_index_map = {}
for (index, char... |
class JobReturn():
overrides: Optional[Sequence[str]] = None
cfg: Optional[DictConfig] = None
hydra_cfg: Optional[DictConfig] = None
working_dir: Optional[str] = None
task_name: Optional[str] = None
status: JobStatus = JobStatus.UNKNOWN
_return_value: Any = None
def return_value(self) ->... |
def test_tutorial_working_directory_original_cwd(tmpdir: Path) -> None:
cmd = ['examples/tutorials/basic/running_your_hydra_app/3_working_directory/original_cwd.py', f'hydra.run.dir={tmpdir}', 'hydra.job.chdir=True']
(result, _err) = run_python_script(cmd)
assert (result.strip() == dedent(f'''
C... |
def _get_org_from_code_inexact(q, org_type):
if (org_type == 'practice'):
return _get_practices_like_code(q)
elif (org_type == 'ccg'):
return _get_pcts_like_code(q)
elif (org_type == 'practice_or_ccg'):
return (list(_get_pcts_like_code(q)) + _get_practices_like_code(q))
elif (org... |
.parametrize(('degree', 'hdiv_family'), [(1, 'RT'), (1, 'BDM')])
def test_darcy_flow_hybridization(degree, hdiv_family):
mesh = UnitSquareMesh(6, 6)
U = FunctionSpace(mesh, hdiv_family, degree)
V = FunctionSpace(mesh, 'DG', (degree - 1))
W = (U * V)
(sigma, u) = TrialFunctions(W)
(tau, v) = Test... |
def verifier_test(setup, proof):
print('Beginning verifier test')
eqs = ['e public', 'c <== a * b', 'e <== c * d']
public = [60]
vk = c.make_verification_key(setup, 8, eqs)
assert v.verify_proof(setup, 8, vk, proof, public, optimized=False)
assert v.verify_proof(setup, 8, vk, proof, public, opti... |
def _get_sandwich_starting_with_swap(front_swap: Swap, rest_swaps: List[Swap]) -> Optional[Sandwich]:
sandwicher_address = front_swap.to_address
sandwiched_swaps = []
if (sandwicher_address in [UNISWAP_V2_ROUTER, UNISWAP_V3_ROUTER, UNISWAP_V3_ROUTER_2]):
return None
for other_swap in rest_swaps:... |
def test_try_extract_decompress_fail():
test_file = FileObject(file_path=str((TEST_DATA_DIR / 'synthetic/configs.ko.corrupted')))
test_file.processed_analysis['file_type'] = {'result': {'mime': 'application/octet-stream'}}
test_file.processed_analysis['software_components'] = {'summary': ['Linux Kernel']}
... |
_ExtendedCommunity.register_type(_ExtendedCommunity.FLOWSPEC_TRAFFIC_RATE)
class BGPFlowSpecTrafficRateCommunity(_ExtendedCommunity):
_VALUE_PACK_STR = '!BHf'
_VALUE_FIELDS = ['subtype', 'as_number', 'rate_info']
ACTION_NAME = 'traffic_rate'
def __init__(self, **kwargs):
super(BGPFlowSpecTraffic... |
class OptionSeriesHistogramSonificationDefaultspeechoptionsMappingPlaydelay(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: st... |
def _validate_segment_dict(name_token: FileContextToken, inp: Dict[(FileContextToken, Any)]) -> SegmentDict:
start = None
stop = None
error_mode: ErrorModes = 'RELMIN'
error = 0.1
error_min = 0.1
for (key, value) in inp.items():
if (key == 'START'):
start = validate_int(value... |
def index_vault(vault: dict[(str, dict)], client: OpenSearch, index_name: str) -> None:
docs_indexed = 0
chunks_indexed = 0
docs = []
for (chunk_id, doc) in vault.items():
path = doc['path']
title = doc['title']
doc_type = doc['type']
chunk = doc['chunk']
chunk_he... |
.parametrize('n_players', [2, 3, 4, 5, 6])
.parametrize('small_blind', [50, 200])
.parametrize('big_blind', [100, 1000])
def test_pre_flop_pot(n_players: int, small_blind: int, big_blind: int):
(state, pot) = _new_game(n_players=n_players, small_blind=small_blind, big_blind=big_blind)
n_bet_chips = sum((p.n_bet... |
.parametrize('valid, required, feed, missing', [(('foo', 'bar', 'baz'), ('foo',), ('bar',), ('foo',)), (('foo', 'bar', 'baz'), ('foo',), tuple(), ('foo',)), (('foo', 'bar', 'baz'), ('bar', 'baz'), ('bar', 'baz'), tuple()), (('foo', 'bar', 'baz'), ('bar', 'baz'), ('bar', 'foo', 'baz'), tuple())])
def test_keyconstraintd... |
class OptionSeriesBulletSonificationTracksMappingLowpassResonance(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 run(fitter: DispersionFitter, num_poles: PositiveInt=1, num_tries: PositiveInt=50, tolerance_rms: NonNegativeFloat=0.01, advanced_param: AdvancedFitterParam=AdvancedFitterParam()) -> Tuple[(PoleResidue, float)]:
task = FitterData.create(fitter, num_poles, num_tries, tolerance_rms, advanced_param)
return tas... |
(frozen=True)
class BallOrientation():
pos: Tuple[(float, ...)]
sphere: Tuple[(float, ...)]
def random() -> BallOrientation:
quat = ((tmp := ((2 * np.random.rand(4)) - 1)) / ptmath.norm3d(tmp))
(q0, qx, qy, qz) = quat
return BallOrientation(pos=(1.0, 1.0, 1.0, 1.0), sphere=(q0, qx, q... |
def iter_chunks(patch_reader, to_pos, to_size, message):
size = unpack_size(patch_reader)
if ((to_pos + size) > to_size):
raise Error(message)
offset = 0
while (offset < size):
chunk_size = min((size - offset), 4096)
offset += chunk_size
patch_data = patch_reader.decompre... |
def test_multiple_returns_one_stackcheck():
cfg = ControlFlowGraph()
cfg.add_nodes_from([(n0 := BasicBlock(0, instructions=[])), (n1 := BasicBlock(1, instructions=[Branch(Condition(OperationType.less, [Variable('a'), Constant(0)]))])), (n2 := BasicBlock(2, instructions=[Branch(Condition(OperationType.less, [Var... |
def run(model_name=None, progress_queue=None, service_config=None, scanner_name=None):
global_configs = service_config.get_global_config()
scanner_configs = service_config.get_scanner_config()
with service_config.scoped_session() as session:
service_config.violation_access = scanner_dao.ViolationAcc... |
class KMeansTopics(object):
def __init__(self, corpus, k=10):
self.k = k
self.model = None
self.vocab = list(set(normalize(corpus.words(categories=['news']))))
def vectorize(self, document):
features = set(normalize(document))
return np.array([(token in features) for toke... |
def hash(qq: int):
day = (int(time.strftime('%d', time.localtime(time.time()))) + 4)
month = int(time.strftime('%m', time.localtime(time.time())))
year = int(time.strftime('%y', time.localtime(time.time())))
days = (((((day + 11) * year) // month) + (month * 31)) * ((year - day) + 23))
return ((days... |
class OptionPlotoptionsColumnrangeSonificationContexttracks(Options):
def activeWhen(self) -> 'OptionPlotoptionsColumnrangeSonificationContexttracksActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsColumnrangeSonificationContexttracksActivewhen)
def instrument(self):
retur... |
def sentiment_analysis_arguments(provider_name: str):
return {'language': 'en', 'text': "Overall I am satisfied with my experience at Amazon, but two areas of major improvement needed. First is the product reviews and pricing. There are thousands of positive reviews for so many items, and it's clear that the review... |
class SusAcc(BasicACLWithTopicTestCase):
def setUp(self):
BasicACLWithTopicTestCase.setUp(self)
self.acc = models.PROTO_MQTT_ACC_SUS
def test_login_no_acl_allow(self):
response = self._test_login_no_acl_allow()
self.assertEqual(response.status_code, 403)
def test_login_wrong_... |
class TestApplicationConfigResolution():
(scope='function')
def example_config_dict(self) -> Dict[(str, str)]:
return {'setting1': 'value1', 'setting2': 'value2', 'notifications': {'notification_service_type': 'twilio_email', 'nested_setting_2': 'nested_value_2'}}
(scope='function')
def example_... |
class CliTest(unittest.TestCase):
def test_benchmark(self) -> None:
with sample_contents('import sys\n') as dtmp:
runner = CliRunner()
with chdir(dtmp):
result = runner.invoke(main, ['--benchmark', 'check', '.'])
self.assertRegex(result.output, dedent('\n ... |
class OptionSeriesPyramid3dData(Options):
def accessibility(self) -> 'OptionSeriesPyramid3dDataAccessibility':
return self._config_sub_data('accessibility', OptionSeriesPyramid3dDataAccessibility)
def borderColor(self):
return self._config_get(None)
def borderColor(self, text: str):
... |
class CachedAccessor():
def __init__(self: CachedAccessor, name: str, accessor: object) -> None:
self._name = name
self._accessor = accessor
def __get__(self: CachedAccessor, obj: object, cls: object) -> object:
if (obj is None):
return self._accessor
try:
... |
class EmailProvider(Protocol):
DOMAIN_AUTHENTICATION: bool
def send_email(self, *, sender: tuple[(str, (str | None))], recipient: tuple[(str, (str | None))], subject: str, html: (str | None)=None, text: (str | None)=None):
...
def create_domain(self, domain: str) -> EmailDomain:
...
def ... |
def test_projection_KMV(mesh, max_degree, interpolation_expr):
for p in range(1, max_degree):
error = run_projection(mesh(1), interpolation_expr, p)
if config['options']['complex']:
assert (np.abs(error) < 1.05e-14)
else:
assert (np.abs(error) < 1e-14) |
class sdm_control_message(IntEnum):
CONTROL_START = 0
CONTROL_START_RESPONSE = 1
CONTROL_STOP = 2
CONTROL_STOP_RESPONSE = 3
RESET_REQUEST = 4
RESET_RESPONSE = 5
CHANGE_UPDATE_PERIOD_REQUEST = 6
CHANGE_UPDATE_PERIOD_RESPONSE = 7
SLEEP_REQUEST = 8
WAKEUP_REQUEST = 9
COMMON_ITEM... |
class TestVSCtl(unittest.TestCase):
container_mn = None
container_mn_ip = None
vsctl = None
def _docker_exec(cls, container, command):
return _run(('docker exec -t %s %s' % (container, command)))
def _docker_exec_mn(cls, command):
return cls._docker_exec(cls.container_mn, command)
... |
class NamespaceMeta(Base):
__tablename__ = 'namespace'
name = Column(String(256), primary_key=True, nullable=False, unique=True)
properties = Column(String(1024))
def __init__(self, name: str, properties: dict) -> None:
self.name = name
self.properties = json.dumps(properties)
def ge... |
def test_deepcopy_kwargs_non_string_keys():
a1 = object()
a2 = object()
dependent_provider1 = providers.Factory(list)
dependent_provider2 = providers.Factory(dict)
provider = providers.Dict({a1: dependent_provider1, a2: dependent_provider2})
provider_copy = providers.deepcopy(provider)
depen... |
('/pinout')
def handle_pinout(self):
global TXBuffer, navMenuIndex
TXBuffer = ''
navMenuIndex = 3
if rpieGlobals.wifiSetup:
return self.redirect('/setup')
if (not isLoggedIn(self.get, self.cookie)):
return self.redirect('/login')
sendHeadandTail('TmplStd', _HEAD)
try:
... |
def test_decoding_unknown_performative():
msg = OefSearchMessage(performative=OefSearchMessage.Performative.REGISTER_SERVICE, service_description=Description({'foo1': 1, 'bar1': 2}))
encoded_msg = OefSearchMessage.serializer.encode(msg)
with pytest.raises(ValueError, match='Performative not valid:'):
... |
def read_utf16_multisz(io, size=(- 1)):
i = 0
multisz = []
current = b''
is_word_done = False
while ((size == (- 1)) or (i < size)):
wchar = io.read(2)
i += 2
if ((wchar == b'') or (wchar == b'\x00\x00')):
if is_word_done:
break
is_word... |
class CoreGeneratorEnhancer():
def __init__(self, resource_path='./resources/', gpus=0):
self.gpus = gpus
core_generator_original = load_model((resource_path + 'core_generator.h5'), custom_objects={'Conv2D_r': Conv2D_r, 'InstanceNormalization': InstanceNormalization, 'tf': tf, 'ConvSN2D': ConvSN2D, ... |
def generate_cert(cert_path: str=SSL_CERT_FILE, key_path: str=SSL_KEY_FILE, key_size: int=KEY_SIZE, key_days: int=KEY_DAYS):
if os.path.exists(key_path):
print('Skipping key generation as already exists.')
return
hostname = 'localhost'
key = rsa.generate_private_key(public_exponent=65537, ke... |
class AddressGenerator():
seed: int
addresses = {}
_metrics.timeit
def __init__(self, randomstate):
self.randomstate = randomstate
_metrics.timeit
def make(self, country):
if (country.locale not in FAKERS):
fake = Faker(country.locale)
fake.add_provider(ad... |
def run_runnable(args=[]):
paths_being_used = [importable_compiled_loc]
if (('--no-write' not in args) and ('-n' not in args)):
paths_being_used.append(runnable_compiled_loc)
with using_paths(*paths_being_used):
call(((['coconut-run'] + args) + [runnable_coco, '--arg']), assert_output=True) |
class OptionPlotoptionsBoxplotSonificationTracksMappingPan(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.... |
class GymEnv(VecEnv):
def __init__(self, gym_env=None, seed=None):
super().__init__()
assert (not (seed is None))
assert (type(gym_env) is list)
self.gym_envs = gym_env
for k in range(len(self.gym_envs)):
self.gym_envs[k].seed((seed + k))
self.action_space... |
_FlowSpecComponentBase.register_type(_FlowSpecIPv4Component.TYPE_FRAGMENT, addr_family.IP)
class FlowSpecFragment(_FlowSpecBitmask):
COMPONENT_NAME = 'fragment'
LF = (1 << 3)
FF = (1 << 2)
ISF = (1 << 1)
DF = (1 << 0)
_bitmask_flags = collections.OrderedDict()
_bitmask_flags[LF] = 'LF'
_... |
class Auth(object):
def __init__(self, core: Core):
self.core = core
self.pid = 0
D = core.events.server_command
D[wire.AuthSuccess] += self._auth_success
D[wire.AuthError] += self._auth_error
def _auth_success(self, ev: wire.AuthSuccess) -> EventHub.StopPropagation:
... |
def run_acc(size, seed, p):
logging.info(('HyperLogLog using p = %d ' % p))
h = HyperLogLog(p=p)
s = set()
random.seed(seed)
for i in range(size):
v = int_bytes(random.randint(1, size))
h.update(v)
s.add(v)
perr = (abs((float(len(s)) - h.count())) / float(len(s)))
ret... |
.parametrize('err, args, title, desc', ((falcon.HTTPInvalidHeader, ('foo', 'bar'), 'Invalid header value', 'The value provided for the "bar" header is invalid. foo'), (falcon.HTTPMissingHeader, ('foo',), 'Missing header value', 'The "foo" header is required.'), (falcon.HTTPInvalidParam, ('foo', 'bar'), 'Invalid paramet... |
.parametrize('expr', ["revert('foo')", "require(false, 'foo')"])
.parametrize('func', REVERT_FUNCTIONS_NO_INPUT)
def test_final_stmt_revert_no_input(console_mode, evmtester, accounts, expr, func):
func = func.format(expr)
code = f'''
pragma solidity >=0.4.22;
contract Foo {{
{func}
}}
'''
contract =... |
class AllAndNotOneValidator(All):
messages = {'custom': 'must not be %(number)d'}
number = 1
def _attempt_convert(self, value, state, validate):
value = super(AllAndNotOneValidator, self)._attempt_convert(value, state, validate)
if (value == self.number):
raise Invalid(self.messa... |
class ZMQEvent(IntEnum):
EVENT_CONNECTED = zmq.EVENT_CONNECTED
EVENT_CONNECT_DELAYED = zmq.EVENT_CONNECT_DELAYED
EVENT_CONNECT_RETRIED = zmq.EVENT_CONNECT_RETRIED
EVENT_LISTENING = zmq.EVENT_LISTENING
EVENT_BIND_FAILED = zmq.EVENT_BIND_FAILED
EVENT_ACCEPTED = zmq.EVENT_ACCEPTED
EVENT_ACCEPT_... |
def extractWwwVirlyceCom(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'), ('The Blue Mage Raised by Dragons', 'The Blue Mage Raised by Dragons', 'oel... |
class SpecGrid(GrdeclKeyword):
ndivix: int = 1
ndiviy: int = 1
ndiviz: int = 1
numres: int = 1
coordinate_type: CoordinateType = CoordinateType.CARTESIAN
def to_grdecl(self):
return [self.ndivix, self.ndiviy, self.ndiviz, self.numres, self.coordinate_type.to_grdecl()]
def to_bgrdecl(... |
class SubjectClient(ClientRequest):
def __init__(self, api_key: str, domain: str, port: str):
super().__init__()
self.client_url: str = SUBJECTS_CRUD_API
self.api_key: str = api_key
self.url: str = (((domain + ':') + port) + self.client_url)
self.headers = {'Content-Type': 'a... |
def parse_xyz_str(xyz_str, with_comment):
xyz_lines = xyz_str.strip().split('\n')
comment_line = xyz_lines[1]
atom_num = int(xyz_lines[0])
atoms_present = (len(xyz_lines) - 2)
assert (len(xyz_lines) == (atom_num + 2)), f'Expected {atom_num} atoms, but found only {atoms_present}!'
atoms_coords = ... |
def sgr_fg():
output = ''
for row_num in range(0, len(GROUPS[0])):
line = ''
for group in GROUPS:
try:
name = group[row_num]
except IndexError:
continue
line += (((fg(name) + ' ') + name.rjust(12)) + rs.all)
output += (l... |
def cache_initial_status_and_identities_for_consent_reporting(db: Session, privacy_request: PrivacyRequest, connection_config: ConnectionConfig, relevant_preferences: List[PrivacyPreferenceHistory], relevant_user_identities: Dict[(str, Any)]) -> None:
for pref in privacy_request.privacy_preferences:
if (pre... |
class LoopStructurer():
LoopRestructuringRules = [WhileLoopRule, DoWhileLoopRule, NestedDoWhileLoopRule, SequenceRule, ConditionToSequenceRule]
def __init__(self, asforest: AbstractSyntaxForest):
self.asforest: AbstractSyntaxForest = asforest
self._processor = LoopProcessor(asforest)
def ref... |
def test_RegexChecker():
c1 = RegexChecker('^([1-9][0-9])*[0-9]0s$')
assert ('80s' in c1)
assert ('1980s' in c1)
assert ('1880s' in c1)
assert ('00s' in c1)
assert ('2000s' in c1)
assert (not ('2001s' in c1))
assert (not ('81s' in c1))
assert (not ('1881s' in c1))
assert (not ('0... |
class FollowsOthesSerializer(serializers.ModelSerializer):
def to_representation(self, instance):
access = None
res = super(FollowsOthesSerializer, self).to_representation(instance=instance)
fan = self.context['request'].query_params.get('fan')
follow = self.context['request'].query_... |
class OptionSeriesPolygonStatesSelectMarker(Options):
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def enabledThreshold(self):
return self._config_get(2)
def enabledThreshold(self, num: float):
self._con... |
class zip_longest(zip):
__slots__ = ('fillvalue',)
__doc__ = getattr(_coconut.zip_longest, '__doc__', 'Version of zip that fills in missing values with fillvalue.')
def __new__(cls, *iterables, **kwargs):
self = _coconut.super(_coconut_zip_longest, cls).__new__(cls, *iterables, strict=False)
... |
def lexc_escape(s):
s = s.replace('%', '__PERCENT__')
s = s.replace(' ', '% ')
s = s.replace('<', '%<')
s = s.replace('>', '%>')
s = s.replace('0', '%0')
s = s.replace('!', '%!')
s = s.replace(':', '%:')
s = s.replace('"', '%"')
s = s.replace(';', '%;')
s = s.replace('__PERCENT__... |
_set_msg_reply(OFPQueueStatsReply)
_set_stats_type(ofproto.OFPST_QUEUE, OFPQueueStats)
_set_msg_type(ofproto.OFPT_STATS_REQUEST)
class OFPQueueStatsRequest(OFPStatsRequest):
def __init__(self, datapath, flags, port_no, queue_id):
super(OFPQueueStatsRequest, self).__init__(datapath, flags)
self.port_... |
def test_buildCPAL_invalid_color():
with pytest.raises(ColorLibError, match='In palette\\[0\\]\\[1\\]: expected \\(R, G, B, A\\) tuple, got \\(1, 1, 1\\)'):
builder.buildCPAL([[(1, 1, 1, 1), (1, 1, 1)]])
with pytest.raises(ColorLibError, match='palette\\[1\\]\\[0\\] has invalid out-of-range \\[0..1\\] c... |
def write_summary_data(file, x_size, keywords, update_steps):
num_keys = len(keywords)
def content_generator():
for x in range(x_size):
(yield ('SEQHDR ', array([0], dtype=numpy.int32)))
for m in range(update_steps):
step = ((x * update_steps) + m)
... |
class OptionQuadrants(Options):
def topLeft(self):
return self._config_get()
def topLeft(self, text: str):
self._config(text)
def topRight(self):
return self._config_get()
def topRight(self, text: str):
self._config(text)
def bottomRight(self):
return self._co... |
class SingleSiteAdaptiveRandomWalkConjugateTest(unittest.TestCase, AbstractConjugateTests):
def setUp(self):
self.mh = bm.SingleSiteRandomWalk(step_size=5.0)
def test_beta_binomial_conjugate_run(self):
self.mh = bm.SingleSiteRandomWalk(step_size=1.0)
self.beta_binomial_conjugate_run(self... |
class OptionPlotoptionsOrganizationSonificationDefaultinstrumentoptionsMappingTremoloSpeed(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... |
def make_experiment_config(config):
environment_factory = make_environment_factory(config)
logger_factory = make_logger_factory(config)
networks_factory = functools.partial(tdmpc.make_networks, latent_size=config.latent_dim, encoder_hidden_size=config.enc_dim, mlp_hidden_size=config.mlp_dim)
optimizer =... |
def active_tracer() -> Tracer:
_ensure_tracer()
if (len(_tracer.get()) == 0):
warnings.warn('An LMQL tracer was requested in a context without active tracer. This indicates that some internal LLM calls may not be traced correctly.')
return NullTracer('null')
return _tracer.get()[(- 1)] |
class AccountBasedExpenseLine(DetailLine):
class_dict = {'AccountBasedExpenseLineDetail': AccountBasedExpenseLineDetail}
def __init__(self):
super(AccountBasedExpenseLine, self).__init__()
self.DetailType = 'AccountBasedExpenseLineDetail'
self.AccountBasedExpenseLineDetail = None |
def get_expanded_system_data_uses(bind: Connection) -> Set:
system_data_uses: ResultProxy = bind.execute(text('SELECT data_use from privacydeclaration;'))
expanded_data_uses = set()
for row in system_data_uses:
data_use: str = row['data_use']
expanded_data_uses.update(DataUse.get_parent_uses... |
class TestSigning(EspSecureTestCase):
VerifyArgs = namedtuple('verify_signature_args', ['version', 'hsm', 'hsm_config', 'keyfile', 'datafile'])
SignArgs = namedtuple('sign_data_args', ['version', 'keyfile', 'output', 'append_signatures', 'hsm', 'hsm_config', 'pub_key', 'signature', 'datafile'])
ExtractKeyAr... |
class Category(object):
def __init__(self, name, searchlist=None):
self.name = name
self.searchlist = self.load_searchlist(searchlist)
def __str__(self):
return self.name
def is_enabled(self):
return self.category_config('enabled', 'boolean', True)
def threshold(self):
... |
class OfCtl_v1_2later(OfCtl_v1_0):
def __init__(self, dp):
super(OfCtl_v1_2later, self).__init__(dp)
def set_port_status(self, port, state):
ofp = self.dp.ofproto
parser = self.dp.ofproto_parser
config = {ofproto_v1_2: PORT_CONFIG_V1_2, ofproto_v1_3: PORT_CONFIG_V1_3}
mas... |
def test_verify_session_cookie_revoked(new_user, api_key):
custom_token = auth.create_custom_token(new_user.uid)
id_token = _sign_in(custom_token, api_key)
session_cookie = auth.create_session_cookie(id_token, expires_in=datetime.timedelta(days=1))
time.sleep(1)
auth.revoke_refresh_tokens(new_user.u... |
def check_legacy_parent_of_multisig_wallet(wallet: Wallet) -> None:
assert (len(wallet.get_accounts()) == 1)
account: MultisigAccount = wallet.get_accounts()[0]
m = account.m
n = account.n
parent_keystores = wallet.get_keystores()
assert (len(parent_keystores) == 1)
keystore = parent_keystor... |
class ExecutableTemplateShimTask(object):
def __init__(self, tt: _task_model.TaskTemplate, executor_type: Type[ShimTaskExecutor], *args, **kwargs):
self._executor_type = executor_type
self._executor = executor_type()
self._task_template = tt
super().__init__(*args, **kwargs)
def ... |
(post_save, sender=Comment)
def my_callback(sender, **kwargs):
message = UserMessage()
message.user = kwargs['instance'].forums.authors
message.ids = kwargs['instance'].forums.id
message.to_user_id = kwargs['instance'].user_id
message.has_read = False
message.url = kwargs['instance'].url
mes... |
class OptionPlotoptionsBarSonificationDefaultinstrumentoptionsActivewhen(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, n... |
class RemoteWorkspaceView(WorkspaceView):
def verify(self):
try:
response = self.project_manager.metadata._request('/api/version', 'GET')
assert (response.json()['application'] == EVIDENTLY_APPLICATION_NAME)
except (HTTPError, JSONDecodeError, KeyError, AssertionError) as e:
... |
def read_config(config_file_path, field, key):
cf = configparser.ConfigParser()
try:
cf.read(config_file_path)
if (field in cf):
result = cf[field][key]
else:
return ''
except configparser.Error as e:
print(e)
return ''
return result |
def _get_path_to_custom_config_schema_from_type(component_type: ComponentType) -> str:
path_prefix: Path = (Path(_SCHEMAS_DIR) / _SCHEMAS_CONFIGURABLE_PARTS_DIRNAME)
if (component_type in {ComponentType.SKILL, ComponentType.CONNECTION}):
filename_prefix = component_type.value
else:
filename_... |
.parametrize('media_type', [falcon.MEDIA_MSGPACK, 'application/msgpack; charset=utf-8', 'application/x-msgpack'])
def test_msgpack(media_type):
class TestResource():
async def on_get(self, req, resp):
resp.content_type = media_type
resp.media = {b'something': True}
assert... |
def uninstall_pywin32():
with tempfile.TemporaryDirectory() as tempdir:
script_filename = 'pywin32_postinstall.py'
script_filepath = os.path.join(tempdir, script_filename)
get_pywin32_postinstall_script(script_filepath)
cmd = [sys.executable, script_filepath, '-remove']
logge... |
def test_orca_unrestricted(this_dir):
base_fn = ((this_dir / 'h2o2_anion') / '00_h2o2_anion')
json_fn = base_fn.with_suffix('.json')
cis_fn = base_fn.with_suffix('.cis')
wf = Wavefunction.from_orca_json(json_fn)
(P_a, P_b) = wf.P
assert (P_a.shape == P_b.shape)
(occ_a, occ_b) = wf.occ
as... |
def jsonxs(data, expr, action=ACTION_GET, value=None, default=None):
tokens = tokenize(expr)
try:
prev_path = None
cur_path = data
for token in tokens:
prev_path = cur_path
if ((not (token in cur_path)) and (action in [ACTION_SET, ACTION_MKDICT, ACTION_MKLIST])):
... |
class NDCGKMetric(Metric[TopKMetricResult]):
k: int
min_rel_score: Optional[int]
no_feedback_users: bool
def __init__(self, k: int, min_rel_score: Optional[int]=None, no_feedback_users: bool=False, options: AnyOptions=None) -> None:
self.k = k
self.min_rel_score = min_rel_score
s... |
class OptionXaxisEvents(Options):
def afterBreaks(self):
return self._config_get(None)
def afterBreaks(self, value: Any):
self._config(value, js_type=False)
def afterSetExtremes(self):
return self._config_get(None)
def afterSetExtremes(self, value: Any):
self._config(valu... |
class UserRepository(BaseRepository[User], UUIDRepositoryMixin[User]):
model = User
async def list_by_ids(self, ids: list[UUID4]) -> list[User]:
statement = select(User).where(User.id.in_(ids))
return (await self.list(statement))
async def get_by_id_and_tenant(self, id: UUID4, tenant: UUID4)... |
def test_attributes(f, dumpfile):
mesh = f.function_space().mesh()
with DumbCheckpoint(dumpfile, mode=FILE_CREATE, comm=mesh.comm) as chk:
with pytest.raises(AttributeError):
chk.write_attribute('/foo', 'nprocs', 1)
with pytest.raises(AttributeError):
chk.read_attribute('... |
.unit
def test_replace_config_value(tmpdir: LocalPath) -> None:
config_dir = (tmpdir / '.fides')
os.mkdir(config_dir)
config_path = (config_dir / 'fides.toml')
expected_result = '# test_value = true'
test_file = '# test_value = false'
with open(config_path, 'w') as config_file:
config_fi... |
class TestWishbone(MemoryTestDataMixin, unittest.TestCase):
def wishbone_readback_test(self, pattern, mem_expected, wishbone, port, base_address=0):
class DUT(Module):
def __init__(self):
self.port = port
self.wb = wishbone
self.submodules += LiteD... |
class House(GenericObject):
_OFFSET = (- 5.0)
def __init__(self):
super().__init__()
self.type = const.OBJ_HOUSE
self.size = 30.0
def __str__(self):
string = super().__str__()[:(- 1)]
return ('%s %s>' % (string, self.size))
def num(self):
return int(self.i... |
class TestMlTradeHandler(BaseSkillTestCase):
path_to_skill = Path(ROOT_DIR, 'packages', 'fetchai', 'skills', 'ml_train')
def setup(cls):
super().setup()
cls.ml_handler = cast(MlTradeHandler, cls._skill.skill_context.handlers.ml_trade)
cls.strategy = cast(Strategy, cls._skill.skill_contex... |
def test_from_file_param_last(simple_roff_parameter_contents):
buff = io.BytesIO()
roffio.write(buff, simple_roff_parameter_contents)
buff.seek(0)
roff_param = RoffParameter.from_file(buff, 'b')
assert np.array_equal(roff_param.name, 'b')
assert np.array_equal(roff_param.values, np.array([2.0])) |
def download_tools(id, tools):
url = tools[id]['tool']
os.system('wget {} -O /tmp/fishinstall/tools/{} --no-check-certificate'.format(url, url[(url.rfind('/') + 1):]))
for dep in tools[id]['dep']:
url = tools[dep]['tool']
os.system('wget {} -O /tmp/fishinstall/tools/{} --no-check-certificate... |
def test_computation(f):
com = f.object('COMPUTATION', 'COMPUT2', 10, 0)
axis2 = f.object('AXIS', 'AXIS2', 10, 0)
axis3 = f.object('AXIS', 'AXIS3', 10, 0)
zone = f.object('ZONE', 'ZONE-A', 10, 0)
process = f.object('PROCESS', 'PROC1', 10, 0)
assert (com.long_name == 'computation object 2')
a... |
.django_db
def test_match_search_multi_tas_award(client, monkeypatch, elasticsearch_award_index, subaward_with_multiple_tas):
_setup_es(client, monkeypatch, elasticsearch_award_index)
resp = query_by_tas_subaward(client, {'require': [_tas_path(BASIC_TAS)]})
assert (resp.json()['results'] == [_subaward1()]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.