code stringlengths 281 23.7M |
|---|
def window_function_test(file_path, args):
out_dir = os.path.dirname(file_path)
if (not os.path.exists(out_dir)):
os.makedirs(out_dir)
if os.path.exists(file_path):
os.remove(file_path)
stdout = run_window_function(args)
assert (file_path in stdout), 'output filename should be mentio... |
class OptionPlotoptionsParetoStatesSelectMarker(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.... |
def test_index_merge(plugdir_and_storage):
(plugdir, storage) = plugdir_and_storage
manager = repo_manager.BotRepoManager(storage, plugdir, (os.path.join(assets, 'repos', 'b.json'), os.path.join(assets, 'repos', 'a.json')))
manager.index_update()
index_entry = manager[repo_manager.REPO_INDEX]
assert... |
def config_wizard():
config = {'chromecast': {}}
if click.confirm('Set up last.fm account?', default=True):
click.echo("\nYou'll need to create a last.fm API application first. Do so here:\n\n you fill in doesn't matter at all, just make sure to save the API\nKey and Shared Secret.\n")
confi... |
class Overworld(wilderness.WildernessScript):
_INSTANCE = None
_NAME = 'overworld'
def get_instance(cls):
if cls._INSTANCE:
return cls._INSTANCE
if (not Overworld.objects.filter(db_key=cls._NAME).exists()):
script = cls.create()
else:
script = Over... |
def check_model(model, args):
assert (model.display_name == args.get('display_name'))
assert (model.tags == args.get('tags'))
assert (model.model_id is not None)
assert (model.create_time is not None)
assert (model.update_time is not None)
assert (model.locked is False)
assert (model.etag is... |
class DoDeletePass(Cursor_Rewrite):
def __init__(self, proc_cursor):
super().__init__(proc_cursor)
def map_s(self, sc):
s = sc._node
if isinstance(s, LoopIR.Pass):
return []
elif isinstance(s, LoopIR.For):
body = self.map_stmts(sc.body())
if (b... |
class Mob(NPC):
loot_chance = AttributeProperty(75, autocreate=False)
def ai_combat_next_action(self, combathandler):
from .combat_turnbased import CombatActionAttack, CombatActionDoNothing
if self.is_idle:
return (CombatActionDoNothing.key, (), {})
target = choice(combathand... |
class Price(Event):
price: (float | None)
currency: str
('currency')
def _validate_currency(cls, v: str) -> str:
if (v not in VALID_CURRENCIES):
raise ValueError(f'Unknown currency: {v}')
return v
('datetime')
def _validate_datetime(cls, v: dt.datetime) -> datetime:
... |
def test_entity_storage_remove_entity_task(create_test_db, create_project, prepare_entity_storage):
from stalker import Asset, Task, Version
project = create_project
char1 = Asset.query.filter((Asset.project == project)).filter((Asset.name == 'Char1')).first()
model = Task.query.filter((Task.parent == c... |
(frozen=True)
class EQLRuleData(QueryRuleData):
type: Literal['eql']
language: Literal['eql']
timestamp_field: Optional[str] = field(metadata=dict(metadata=dict(min_compat='8.0')))
event_category_override: Optional[str] = field(metadata=dict(metadata=dict(min_compat='8.0')))
tiebreaker_field: Option... |
def ensure_permissions(path: str, r: bool=True, w: bool=False, x: bool=False) -> None:
if (not os.path.exists(path)):
log.error(f"Path: '{path}' does not exist.")
raise SystemExit(1)
if (r and (not os.access(path, os.R_OK))):
log.error(f"Path: '{path}' is not readable.")
raise Sy... |
def fofa_search_all(client, query, fields, num):
size = 10000
page = 1
result = {'size': 0, 'results': [], 'consumed_fpoint': 0}
total = 0
while True:
try:
remain_num = (num - total)
if (remain_num < size):
size = remain_num
r = client.sear... |
((not is_qt), 'This test is for qt.')
class TestApiQt(unittest.TestCase):
def test_importable_items_minimal(self):
from pyface.api import AboutDialog, Alignment, Application, ApplicationWindow, Border, BaseDropHandler, CANCEL, Clipboard, ConfirmationDialog, Dialog, DirectoryDialog, ExpandablePanel, FileDial... |
def add_et_column(trace_df: pd.DataFrame, et: ExecutionTrace, column: str) -> None:
if ('et_node' not in trace_df):
logger.error('Please run correlate_execution_trace() first')
return
if (column == 'op_schema'):
def map_func(node_id):
return et.nodes[node_id].op_schema
el... |
def test_manual_flow_with_or_without_hinting(testbot):
assert ('Flow w4 started' in testbot.exec_command('!flows start w4'))
assert ('a' in testbot.exec_command('!a'))
assert ('b' in testbot.exec_command('!b'))
flow_message = testbot.pop_message()
assert ('You are in the flow w4, you can continue wi... |
class OptionPlotoptionsTreegraphMarkerStates(Options):
def hover(self) -> 'OptionPlotoptionsTreegraphMarkerStatesHover':
return self._config_sub_data('hover', OptionPlotoptionsTreegraphMarkerStatesHover)
def normal(self) -> 'OptionPlotoptionsTreegraphMarkerStatesNormal':
return self._config_sub_... |
class VersionStatus(enum.Enum):
incomplete = 1
valid = 2
invalid = 3
min = incomplete
max = invalid
def __str__(self):
return self.name
def is_valid(self):
return (self == self.valid)
def is_deep_scrubbable(self):
return ((self == self.invalid) or (self == self.va... |
class DistributedShampooTest(unittest.TestCase):
def _train_quadratic_with_comms_dtype(self, communication_dtype: CommunicationDType=CommunicationDType.DEFAULT) -> Tuple[(nn.Module, DistributedShampoo)]:
data = torch.arange(10, dtype=torch.float)
model = nn.Sequential(nn.Linear(10, 1, bias=False))
... |
class MessagingConfigBase(BaseModel):
service_type: MessagingServiceType
details: Optional[Union[(MessagingServiceDetailsMailgun, MessagingServiceDetailsTwilioEmail, MessagingServiceDetailsMailchimpTransactional)]]
class Config():
use_enum_values = False
orm_mode = True
extra = Extra... |
def create_transaction_signature(unsigned_txn: UnsignedTransactionAPI, private_key: datatypes.PrivateKey, chain_id: int=None) -> VRS:
transaction_parts = rlp.decode(rlp.encode(unsigned_txn))
if chain_id:
transaction_parts_for_signature = (transaction_parts + [int_to_big_endian(chain_id), b'', b''])
... |
_checkable
class Cache(Protocol):
def initialize(self, vocab: Vocab, task: LLMTask) -> None:
def add(self, doc: Doc) -> None:
def prompt_template(self) -> Optional[str]:
_template.setter
def prompt_template(self, prompt_template: str) -> None:
def __contains__(self, doc: Doc) -> bool:
def __... |
.parametrize('reader_cls', [SeekingReader, NonSeekingReader])
def test_crc_chunk_validation(reader_cls: Union[(Type[SeekingReader], Type[NonSeekingReader])]):
content = produce_corrupted_mcap(DEMO_MCAP, 'chunk')
reader = reader_cls(BytesIO(content), validate_crcs=True)
with pytest.raises(CRCValidationError)... |
def test_get_authenticator_deviceflow():
cfg = PlatformConfig(auth_mode=AuthType.DEVICEFLOW)
with pytest.raises(AuthenticationError):
get_authenticator(cfg, get_client_config())
authn = get_authenticator(cfg, get_client_config(device_authorization_endpoint=DEVICE_AUTH_ENDPOINT))
assert isinstanc... |
class TestGetNormalizedBoundingBoxListForLayoutGraphic():
def test_should_scale_coordinates(self):
result = get_normalized_bounding_box_list_for_layout_graphic(LayoutGraphic(coordinates=LayoutPageCoordinates(x=10, y=10, width=20, height=20, page_number=0), page_meta=LayoutPageMeta.for_coordinates(LayoutPage... |
def make_stub_module(clsid):
spec = GetLatestTypelibSpec(clsid)
(ole_items, _, _, _) = BuildOleItems(spec)
import_froms = [ast.ImportFrom('collections.abc', [ast.alias('Iterator')], 0), ast.ImportFrom('typing', [ast.alias('Any'), ast.alias('Callable'), ast.alias('Union')], 0), ast.ImportFrom('pythoncom', [a... |
class VideoChatParticipantsInvited(JsonDeserializable):
def de_json(cls, json_string):
if (json_string is None):
return None
obj = cls.check_json(json_string)
if ('users' in obj):
obj['users'] = [User.de_json(u) for u in obj['users']]
return cls(**obj)
def... |
class OptionSeriesDumbbellDataEvents(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)
d... |
def reply(fn):
def _call(*args, user, **kwargs):
def render(tpl: str, **kwargs):
template = get_template((('messages/' + tpl) + '.txt'))
return template.render(user=user, **kwargs)
return fn(*args, **kwargs, user=user, render=render)
return with_user(_call) |
def probe_context(transport_domain, transport_address, context_engine_id, context_name):
if context_engine_id:
candidate = [context_engine_id, context_name, '.'.join([str(x) for x in transport_domain])]
else:
candidate = [context_name, '.'.join([str(x) for x in transport_domain])]
if (transp... |
class TraitsDockPane(DockPane):
model = Instance(HasTraits)
ui = Instance('traitsui.ui.UI')
def trait_context(self):
if self.model:
return {'object': self.model, 'pane': self}
return super().trait_context()
def destroy(self):
if (self.ui is not None):
self... |
class TaskState(HasStrictTraits):
task = Instance(Task)
layout = Instance(TaskLayout)
initialized = Bool(False)
central_pane = Instance(ITaskPane)
dock_panes = List(Instance(IDockPane))
menu_bar_manager = Instance(IMenuBarManager)
status_bar_manager = Instance(IStatusBarManager)
tool_bar... |
class SecureAggregator():
def __init__(self, config: Dict[(str, FixedPointConfig)]):
self.converters = {}
for key in config.keys():
self.converters[key] = instantiate(config[key])
self._aggregate_overflows = 0
def _check_converter_dict_items(self, model: nn.Module) -> None:
... |
(auto_attribs=True)
class RequestIO():
request_id: str
date: datetime.datetime
json_input: 'RequestIOJsonInput'
json_output: 'RequestIOJsonOutput'
status_code: int
logs: str
duration_in_seconds: int
additional_properties: Dict[(str, Any)] = attr.ib(init=False, factory=dict)
def to_di... |
class OptionPlotoptionsStreamgraphSonificationContexttracksMappingPan(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_preference_module(graph, bus, config, plugin_engine):
graph.register_instance('tomate.bus', bus)
graph.register_instance('tomate.plugin', plugin_engine)
graph.register_instance('tomate.config', config)
scan_to_graph(['tomate.ui.dialogs.preference'], graph)
instance = graph.get('tomate.ui.pr... |
def ast_reinit_in_condition_true() -> AbstractSyntaxTree:
true_value = LogicCondition.initialize_true((context := LogicCondition.generate_new_context()))
ast = AbstractSyntaxTree((root := SeqNode(true_value)), condition_map={logic_cond('a', context): Condition(OperationType.less, [Variable('i'), Constant(10)]),... |
class tFAWController(Module):
def __init__(self, tfaw):
self.valid = valid = Signal()
self.ready = ready = Signal(reset=1)
ready.attr.add('no_retiming')
if (tfaw is not None):
count = Signal(max=max(tfaw, 2))
window = Signal(tfaw)
self.sync += wind... |
def lambda_handler(event, context):
response = event.get('response')
request = event.get('request')
session = request.get('session')
expectedAnswer = request.get('privateChallengeParameters').get('answer')
challengeAnswer = request.get('challengeAnswer')
if (expectedAnswer == challengeAnswer):
... |
class OpenAIChatMessage(LLMChatMessage):
function_call: Optional[FunctionCall] = None
def __init__(self, role: str, content: Optional[str]=None, function_call: Optional[FunctionCall]=None) -> None:
super().__init__(role=role, content=content)
self.function_call = function_call
def __str__(se... |
def extractFrolicsaboundWordpressCom(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... |
class OptionSeriesColumnSonificationDefaultinstrumentoptionsMappingLowpassResonance(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, ... |
class Calendar(Html.Html):
name = 'Calendar'
requirements = ('jquery',)
_option_cls = OptCalendars.OptionDays
tag = 'table'
def __init__(self, page: primitives.PageModel, content: Optional[str], width: tuple, height: tuple, align: Optional[str], options: Optional[dict], html_code: Optional[str], pro... |
class TestWhiteBoxRWLockReadD(unittest.TestCase):
def test_read_vs_downgrade_read(self) -> None:
c_rwlock_1 = rwlock.RWLockReadD()
c_rwlock_2 = rwlock.RWLockReadD()
def assert_internal_state() -> None:
self.assertEqual(int(c_rwlock_1.v_read_count), int(c_rwlock_2.v_read_count))
... |
def setup_remote_hmmdb(db, dbtype, qtype):
if (':' in db):
(dbname, host, port) = map(str.strip, db.split(':'))
dbpath = host
port = int(port)
else:
dbname = db
dbpath = None
host = None
port = None
if (dbname in get_hmmer_databases()):
(dbfile... |
class TestPerturbText(unittest.TestCase):
def setUp(self) -> None:
ner_pipeline = get_ner_pipeline()
self.perturber = PerturbText(INTENT_DATASET, ner_pipeline=ner_pipeline, batch_size=8, perturbations_per_sample=5)
def test_perturb_names(self):
print(self.perturber.perturb_names())
d... |
(scope='function')
def erasure_policy_hmac(db: Session, oauth_client: ClientDetail, storage_config: StorageConfig) -> Generator:
erasure_policy = Policy.create(db=db, data={'name': 'hmac policy', 'key': 'hmac_policy', 'client_id': oauth_client.id})
erasure_rule = Rule.create(db=db, data={'action_type': ActionTy... |
class TestStringRelatedField(APISimpleTestCase):
def setUp(self):
self.instance = MockObject(pk=1, name='foo')
self.field = serializers.StringRelatedField()
def test_string_related_representation(self):
representation = self.field.to_representation(self.instance)
assert (represen... |
class build_ext_options():
def build_options(self):
if hasattr(self.compiler, 'initialize'):
self.compiler.initialize()
self.compiler.platform = sys.platform[:6]
for e in self.extensions:
e.extra_compile_args = COMPILE_OPTIONS.get(self.compiler.compiler_type, COMPILE_... |
_action_type(ofproto.OFPAT_PUSH_VLAN, ofproto.OFP_ACTION_PUSH_SIZE)
class OFPActionPushVlan(OFPAction):
def __init__(self, ethertype=ether.ETH_TYPE_8021Q, type_=None, len_=None):
super(OFPActionPushVlan, self).__init__()
self.ethertype = ethertype
def parser(cls, buf, offset):
(type_, le... |
class OptionPlotoptionsBellcurveStatesSelect(Options):
def animation(self) -> 'OptionPlotoptionsBellcurveStatesSelectAnimation':
return self._config_sub_data('animation', OptionPlotoptionsBellcurveStatesSelectAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag:... |
def update_mask(db_root, mask_db, src_dbs, offset=0):
bits = set()
mask_db_file = ('%s/mask_%s.db' % (db_root, mask_db))
if os.path.exists(mask_db_file):
with util.OpenSafeFile(mask_db_file, 'r') as f:
for line in f:
line = line.split()
assert (len(line) =... |
def calculate_message_call_gas(state: State, gas: Uint, to: Address, value: U256) -> MessageCallGas:
create_gas_cost = (Uint(0) if account_exists(state, to) else GAS_NEW_ACCOUNT)
transfer_gas_cost = (Uint(0) if (value == 0) else GAS_CALL_VALUE)
cost = (((GAS_CALL + gas) + create_gas_cost) + transfer_gas_cos... |
class RemoteControlledTank(MoveTank):
def __init__(self, left_motor_port, right_motor_port, polarity='inversed', speed=400, channel=1):
MoveTank.__init__(self, left_motor_port, right_motor_port)
self.set_polarity(polarity)
left_motor = self.motors[left_motor_port]
right_motor = self.... |
class Bridge(object):
_DEFAULT_VALUE = {'priority': bpdu.DEFAULT_BRIDGE_PRIORITY, 'sys_ext_id': 0, 'max_age': bpdu.DEFAULT_MAX_AGE, 'hello_time': bpdu.DEFAULT_HELLO_TIME, 'fwd_delay': bpdu.DEFAULT_FORWARD_DELAY}
def __init__(self, dp, logger, config, send_ev_func):
super(Bridge, self).__init__()
... |
class EmovityStation(BikeShareStation):
def __init__(self, latitude, longitude, bikes, free, fuzzle):
dom = html.fromstring(fuzzle)
text = dom.xpath('//div/text()')
name = text[0]
uid = next(iter(re.findall('(\\d+)\\s*-', name)))
super(EmovityStation, self).__init__(name=text... |
class TestSecureAggregationIntegration():
def _load_data(self, num_users: int=26):
shard_size = 1
local_batch_size = 1
dummy_dataset = DummyAlphabetDataset(num_rows=num_users)
(data_provider, data_loader) = DummyAlphabetDataset.create_data_provider_and_loader(dummy_dataset, shard_siz... |
class OrderStatisticsTicketSchema(Schema):
class Meta():
type_ = 'order-statistics-ticket'
self_view = 'v1.order_statistics_ticket_detail'
self_view_kwargs = {'id': '<id>'}
inflect = dasherize
id = fields.Str()
identifier = fields.Str()
tickets = fields.Method('tickets_co... |
class SearchFilterAnnotatedFieldTests(TestCase):
def setUpTestData(cls):
SearchFilterModel.objects.create(title='abc', text='def')
SearchFilterModel.objects.create(title='ghi', text='jkl')
def test_search_in_annotated_field(self):
class SearchListView(generics.ListAPIView):
q... |
def test_centered_product_same_mode_raises_exceptions_if_frame_1_frame_2_different_lengths():
with pytest.raises(scared.PreprocessError):
scared.preprocesses.high_order.CenteredProduct(frame_1=range(60), mode='same')
with pytest.raises(scared.PreprocessError):
scared.preprocesses.high_order.Cent... |
class CaseInsensitiveDict(MutableMapping):
def __init__(self, data: Optional[Iterable[Tuple[(str, Any)]]]=None, **kwargs: Any):
self._store: Dict[(str, Tuple[(str, Any)])] = dict()
if (data is None):
data = {}
self.update(data, **kwargs)
def __setitem__(self, key: str, value:... |
def top_n_correlations(n, column, days=180):
df = generate_oura_correlations(lookback_days=days)
positive = df[column].nlargest(n).reset_index()
positive.columns = ['Positive', 'Pos Corr Coef.']
negative = df[column].nsmallest(n).reset_index()
negative.columns = ['Negative', 'Neg Corr Coef.']
re... |
class ObjectIdentity(object):
(ST_DIRTY, ST_CLEAN) = (1, 2)
def __init__(self, *args, **kwargs):
self._args = args
self._kwargs = kwargs
self._mibSourcesToAdd = None
self._modNamesToLoad = None
self._asn1SourcesToAdd = None
self._asn1SourcesOptions = None
... |
def single(wosclient, wos_query, xml_query=None, count=5, offset=1):
records = _get_records(wosclient, wos_query, count, offset)
xml = _re.sub(' xmlns="[^"]+"', '', records, count=1).encode('utf-8')
if (not xml_query):
return prettify(xml)
xml = _ET.fromstring(xml)
return [el.text for el in ... |
def get_point_of_reference(unit, count, epoch=None):
if (unit == 'seconds'):
multiplier = 1
elif (unit == 'minutes'):
multiplier = 60
elif (unit == 'hours'):
multiplier = 3600
elif (unit == 'days'):
multiplier = (3600 * 24)
elif (unit == 'weeks'):
multiplier =... |
class ExampleValidatedSerializer(serializers.Serializer):
integer = serializers.IntegerField(validators=(MaxValueValidator(limit_value=99), MinValueValidator(limit_value=(- 11))))
string = serializers.CharField(validators=(MaxLengthValidator(limit_value=10), MinLengthValidator(limit_value=2)))
regex = seria... |
def evaluate_type(value):
if isinstance(value, list):
evaluated_type = 'array'
elif isinstance(value, dict):
evaluated_type = 'string'
else:
try:
float(value)
try:
if (str(int(float(value))) == str(value)):
int_str = str(int... |
def test_evaluate_base_rule():
rule_address_match = SingleRule(value_path=['address'], relation='equals', comparison='2')
rule_location_match = SingleRule(value_path=['location'], relation='equals', comparison=[22, 12])
rule_location_no_match = SingleRule(value_path=['location'], relation='equals', comparis... |
def _update_embedding_config():
global EMBEDDING_NAME_TO_PARAMETER_CLASS_CONFIG
for (param_cls, models) in _EMBEDDING_PARAMETER_CLASS_TO_NAME_CONFIG.items():
models = [m.strip() for m in models.split(',')]
for model in models:
if (model not in EMBEDDING_NAME_TO_PARAMETER_CLASS_CONFIG... |
class QueryStub(object):
def __init__(self, channel):
self.Allowance = channel.unary_unary('/cosmos.feegrant.v1beta1.Query/Allowance', request_serializer=cosmos_dot_feegrant_dot_v1beta1_dot_query__pb2.QueryAllowanceRequest.SerializeToString, response_deserializer=cosmos_dot_feegrant_dot_v1beta1_dot_query__p... |
def test_flatten_dict_by_key():
NESTED_DICT = dict(top=2, another_top=2)
DICT = dict(top=1, nested=NESTED_DICT)
flatten_dict = flatten_dict_by_key(DICT, 'nested')
assert (flatten_dict.get('top') == 2)
assert (flatten_dict.get('another_top') == 2)
assert (flatten_dict.get('nested') is None)
f... |
def fetch_transaction_obligated_amount_by_internal_award_id(internal_award_id: int) -> Optional[Decimal]:
_sum = FinancialAccountsByAwards.objects.filter(award_id=internal_award_id).aggregate(Sum('transaction_obligated_amount'))
if _sum:
return _sum['transaction_obligated_amount__sum']
return None |
class Transactions(Model):
def __init__(self, **kwargs: Any) -> None:
self._pending_transaction_timeout = kwargs.pop('pending_transaction_timeout', 30)
super().__init__(**kwargs)
self._pending_proposals = defaultdict((lambda : {}))
self._pending_initial_acceptances = defaultdict((lam... |
class TestsAchromatic(util.ColorAsserts, unittest.TestCase):
def test_achromatic(self):
self.assertEqual(Color('#222222').convert('hct').is_achromatic(), True)
self.assertEqual(Color('srgb', ([1e-09] * 3)).convert('hct').set('c', (lambda x: (x + 1e-08))).is_achromatic(), True)
self.assertEqu... |
def test_call_with_attributes():
provider = providers.Factory(Example)
provider.add_attributes(attribute1='a1', attribute2='a2')
instance1 = provider()
instance2 = provider()
assert (instance1.attribute1 == 'a1')
assert (instance1.attribute2 == 'a2')
assert (instance2.attribute1 == 'a1')
... |
class JavaFile(object):
def __init__(self, read_file, write_file):
self.read_file = read_file
self.write_file = write_file
self.java_file_c = java_file_c.JavaFile(read_file, write_file)
def read(self, data_len, return_on_barrier=False):
if return_on_barrier:
data = se... |
class VernaiApi(ProviderInterface, TextInterface):
provider_name = 'vernai'
def __init__(self, api_keys: Dict={}):
self.api_settings = load_provider(ProviderDataEnum.KEY, provider_name=self.provider_name, api_keys=api_keys)
self.api_key = self.api_settings['api_key']
self.url_emotion_det... |
class TestShell(Nubia):
def __init__(self, commands, name='test_shell'):
super(TestShell, self).__init__(name, plugin=TestPlugin(commands), testing=True)
async def run_cli_line(self, raw_line):
cli_args_list = raw_line.split()
args = (await self._pre_run(cli_args_list))
return (a... |
def register_toy_coco_dataset(dataset_name, num_images=3, image_size=(5, 10), num_classes=(- 1), num_keypoints=0):
(width, height) = image_size
with make_temp_directory('detectron2go_tmp_dataset') as dataset_dir:
image_dir = os.path.join(dataset_dir, 'images')
os.makedirs(image_dir)
imag... |
class Yubikey(IntervalModule):
interval = 1
format = 'Yubikey: '
unlocked_format = 'Yubikey: '
timeout = 5
color = '#00FF00'
unlock_color = '#FF0000'
settings = (('format', 'Format string'), ('unlocked_format', 'Format string when the key is unlocked'), ('timeout', 'How long the Yubikey will... |
def test_fetch_mixed_no_local_registry():
with TemporaryDirectory() as tmp_dir:
with cd(tmp_dir):
name = 'my_first_aea'
runner = CliRunner()
result = runner.invoke(cli, ['fetch', 'fetchai/my_first_aea'], catch_exceptions=False)
assert (result.exit_code == 0), ... |
def test_absent_attribute_in_template(tmpdir, merge_files_oneLR, assert_log):
path = os.path.join(str(tmpdir), 'absent-attribute-in-template.dlis')
content = ['data/chap3/start.dlis.part', 'data/chap3/template/absent.dlis.part', 'data/chap3/template/default.dlis.part', 'data/chap3/object/object.dlis.part']
... |
def scan_targets(access_bed, sample_bams, min_depth, min_gap, min_length, procs):
bait_chunks = []
logging.info('Scanning for enriched regions in:\n %s', '\n '.join(sample_bams))
with parallel.pick_pool(procs) as pool:
args_iter = ((bed_chunk, sample_bams, min_depth, min_gap, min_length) for bed_c... |
class ExoType(Enum):
F32 = auto()
F64 = auto()
I8 = auto()
I32 = auto()
R = auto()
Index = auto()
Bool = auto()
Size = auto()
def is_indexable(self):
return (self in [ExoType.Index, ExoType.Size])
def is_numeric(self):
return (self in [ExoType.F32, ExoType.F64, Ex... |
class PageThreadOwner(AbstractObject):
def __init__(self, api=None):
super(PageThreadOwner, self).__init__()
self._isPageThreadOwner = True
self._api = api
class Field(AbstractObject.Field):
thread_owner = 'thread_owner'
_field_types = {'thread_owner': 'Object'}
def _get_... |
class AirflowContainerTask(PythonAutoContainerTask[AirflowObj]):
def __init__(self, name: str, task_config: AirflowObj, inputs: Optional[Dict[(str, Type)]]=None, **kwargs):
super().__init__(name=name, task_config=task_config, interface=Interface(inputs=(inputs or {})), **kwargs)
self._task_resolver ... |
.asyncio
.workspace_host
class TestTenantEmailDomainVerify():
async def test_unauthorized(self, unauthorized_dashboard_assertions: HTTPXResponseAssertion, test_client_dashboard: test_data: TestData):
response = (await test_client_dashboard.post(f"/tenants/{test_data['tenants']['default'].id}/email/verify")... |
def test_call_address_reflector_single_name(address_reflector_contract, call):
with contract_ens_addresses(address_reflector_contract, [('dennisthepeasant.eth', '0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413')]):
result = call(contract=address_reflector_contract, contract_function='reflect', func_args=['dennis... |
class OptionPlotoptionsDependencywheelEvents(Options):
def afterAnimate(self):
return self._config_get(None)
def afterAnimate(self, value: Any):
self._config(value, js_type=False)
def checkboxClick(self):
return self._config_get(None)
def checkboxClick(self, value: Any):
... |
(scope='module')
def datadir(tmpdir_factory, geth_zipfile_version):
zipfile_path = absolute_datadir(geth_zipfile_version)
base_dir = tmpdir_factory.mktemp('goethereum')
tmp_datadir = os.path.join(str(base_dir), 'datadir')
with zipfile.ZipFile(zipfile_path, 'r') as zip_ref:
zip_ref.extractall(tmp... |
def block_transaction_to_dict(transaction: SignedTransactionAPI, header: BlockHeaderAPI) -> RpcBlockTransactionResponse:
data = cast(RpcBlockTransactionResponse, transaction_to_dict(transaction))
data['blockHash'] = encode_hex(header.hash)
data['blockNumber'] = hex(header.block_number)
return data |
class RecurseNetworks(models.Model):
pg_notify_channel = 'pdns_notify'
pg_notify_payload = 'pdns_recurse_modified'
log_object_name = 'dnsdist recurse networks'
id = models.AutoField(primary_key=True, help_text='Unique handle for network entries')
subnet = models.CharField(_('Subnet'), max_length=50,... |
def check_does_not_have_ids(node, raise_error):
if (nodes.section is type(node)):
if any((name.startswith('fls_') for name in node['names'])):
raise_error('section should not have an id', location=node)
else:
should_not_have_id(node, type(node).__name__, raise_error)
for child in... |
class group_add(group_mod):
version = 4
type = 15
command = 0
def __init__(self, xid=None, group_type=None, group_id=None, buckets=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (group_type != None):
self.group_type = group_ty... |
class Compose(Rule):
first: Rule
second: Rule
def __init__(self, first: Rule, second: Rule, name: str='compose') -> None:
Rule.__init__(self, name)
self.first = first
self.second = second
def apply(self, test: Any) -> RuleResult:
rule_result = self.first.apply(test)
... |
def train(model, train_loader, val_loader, optimizer, init_lr=0.002, checkpoint_dir=None, checkpoint_interval=None, nepochs=None, clip_thresh=1.0):
if use_cuda:
model = model.cuda()
criterion = nn.CrossEntropyLoss()
global global_step, global_epoch
while (global_epoch < nepochs):
model.t... |
class CompWithInit2(event.Component):
foo1 = event.IntProp(1)
foo2 = event.IntProp(2, settable=True)
foo3 = event.IntProp(3)
def init(self, set_foos):
if set_foos:
self._mutate_foo1(11)
self.set_foo2(12)
self.set_foo3(13)
def set_foo3(self, v):
sel... |
class FitFromDictMixin():
def _fit_from_dict(self, X: pd.DataFrame, user_dict_: Dict) -> pd.DataFrame:
X = check_X(X)
variables = list(user_dict_.keys())
self.variables_ = check_numerical_variables(X, variables)
_check_contains_na(X, self.variables_)
_check_contains_inf(X, se... |
class TestMisc(util.ColorAsserts, unittest.TestCase):
def test_max_precision(self):
self.assertEqual(Color('purple').convert('lab').to_string(precision=(- 1)), 'lab(29. 56. -36.)')
def test_percent_bool_list(self):
self.assertEqual(Color('purple').convert('lab').set('alpha', 0.5).to_string(perce... |
class UserPasswordUpdateView(MenuItemMixin, FormView):
form_class = PasswordChangeForm
template_name = 'registration/password.html'
menu_parameters = 'password'
_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(UserPasswordUpdateView, self).dispatch(reques... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.