code stringlengths 281 23.7M |
|---|
def lazy_import():
from fastly.model.relationship_waf_rule import RelationshipWafRule
from fastly.model.type_waf_rule_revision import TypeWafRuleRevision
from fastly.model.waf_rule_revision import WafRuleRevision
from fastly.model.waf_rule_revision_attributes import WafRuleRevisionAttributes
from fa... |
class TestRemovePrefix():
def test_remove_matching_prefix(self):
suffix = runner.remove_prefix('index-', 'index')
assert (suffix == '-')
def test_prefix_doesnt_exit(self):
index_name = 'index-'
suffix = runner.remove_prefix(index_name, 'unrelatedprefix')
assert (index_nam... |
class TestTraitDict(unittest.TestCase):
def setUp(self):
self.added = None
self.changed = None
self.removed = None
self.trait_dict = None
def notification_handler(self, trait_dict, removed, added, changed):
self.trait_list = trait_dict
self.removed = removed
... |
class EnumProp(Property):
_default = ''
def _consume_args(self, options, *args):
if (not isinstance(options, (list, tuple))):
raise TypeError('EnumProp needs list of options')
if (not all([isinstance(i, str) for i in options])):
raise TypeError('EnumProp options must be s... |
def run():
tiles = list(gen_sites())
print(('// Tile count: %d' % len(tiles)))
print(("// Seed: '%s'" % os.getenv('SEED')))
ninputs = 0
do_idx = []
for (i, sites) in enumerate(tiles):
if random.randint(0, 1):
do_idx.append(ninputs)
ninputs += 1
else:
... |
class OptionSeriesLollipopSonificationDefaultinstrumentoptions(Options):
def activeWhen(self) -> 'OptionSeriesLollipopSonificationDefaultinstrumentoptionsActivewhen':
return self._config_sub_data('activeWhen', OptionSeriesLollipopSonificationDefaultinstrumentoptionsActivewhen)
def instrument(self):
... |
def server(sock, site, log=None, environ=None, max_size=None, max_ protocol=HttpProtocol, server_event=None, minimum_chunk_size=None, log_x_forwarded_for=True, custom_pool=None, keepalive=True, log_output=True, log_format=DEFAULT_LOG_FORMAT, url_length_limit=MAX_REQUEST_LINE, debug=True, socket_timeout=None, capitalize... |
_click
def mouse_click_combobox_or_choice(control, index, delay):
if isinstance(control, wx.ComboBox):
click_event = _create_event(wx.wxEVT_COMMAND_COMBOBOX_SELECTED, control)
elif isinstance(control, wx.Choice):
click_event = _create_event(wx.wxEVT_COMMAND_CHOICE_SELECTED, control)
else:
... |
def test_load_submission(tmp_path: Path) -> None:
executor = local.LocalExecutor(tmp_path)
job = executor.submit(f66, 67, y=68)
submission = local.LocalJob(tmp_path, job.job_id).submission()
assert (submission.function is f66)
assert (submission.args == (67,))
assert (submission.kwargs == {'y': ... |
class MockSock():
def __init__(self, *, chunk=None, exception=None):
self._recver = io.BytesIO(ZEN)
self._sender = io.BytesIO()
self.__closed = False
self.__chunk = chunk
self.__exception = exception
self.flags = None
def __enter__(self):
return self
d... |
class AmazonLootScraper(AmazonBaseScraper):
def get_type() -> OfferType:
return OfferType.LOOT
def get_offer_handlers(self, page: Page) -> list[OfferHandler]:
return [OfferHandler(page.locator('[data-a-target="offer-list-IN_GAME_LOOT"] .item-card__action > a:first-child'), self.read_raw_offer, ... |
def test_far_to_near(mesh, DGDPC0, W):
velocity = as_vector((0.0, (- 1.0), 0.0))
u0 = project(velocity, W)
xs = SpatialCoordinate(mesh)
inflowexpr = conditional(And((real(xs[2]) > 0.25), (real(xs[2]) < 0.75)), 1.0, 0.5)
inflow = Function(DGDPC0)
inflow.interpolate(inflowexpr)
n = FacetNormal... |
def introduce_data_drops(data, drop_config, set_to_none=False):
assert isinstance(drop_config, DataDropConfig)
assert (type(data) is list)
assert (drop_config.max_percentage_for_single_drop < drop_config.overall_drop_percentage)
num_datapoints = len(data)
max_datapoints_per_drop = ((drop_config.max_... |
class BertLayer(nn.Module):
def __init__(self, hidden_size, batch_size, seq_len, num_attention_heads, intermediate_size, hidden_act, layer_norm_eps, attention_probs_dropout_prob, hidden_dropout_prob):
super().__init__()
self.attention = BertAttention(batch_size=batch_size, seq_len=seq_len, hidden_si... |
def extractMayangel7WordpressCom(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)... |
(frozen=True, **SLOTS)
class Field():
number: int
if (version_info >= (3, 10)):
_: ClassVar[KW_ONLY]
packed: Union[(bool, Sentinel)] = DEFAULT
one_of: Optional[OneOf] = None
def _from_annotated_args(cls, *args: Any) -> Optional[Field]:
for arg in args:
if isinstance(arg, ... |
class IRCBot(Bot):
factory_path = 'evennia.server.portal.irc.IRCBotFactory'
def start(self, ev_channel=None, irc_botname=None, irc_channel=None, irc_network=None, irc_port=None, irc_ssl=None):
if (not _IRC_ENABLED):
self.delete()
return
if irc_botname:
self.db... |
def flash_id(esp, args):
flash_id = esp.flash_id()
print(('Manufacturer: %02x' % (flash_id & 255)))
flid_lowbyte = ((flash_id >> 16) & 255)
print(('Device: %02x%02x' % (((flash_id >> 8) & 255), flid_lowbyte)))
print(('Detected flash size: %s' % DETECTED_FLASH_SIZES.get(flid_lowbyte, 'Unknown')))
... |
def neval(expr, digits=20, **kwargs):
from flint import ctx, acb
assert (digits >= 1)
orig = ctx.prec
target = ((digits * 3.33) + 5)
wp = ((digits * 3.33) + 30)
maxprec = ((wp * 10) + 4000)
evaluator = ArbNumericalEvaluation()
try:
while 1:
ctx.prec = wp
t... |
def name_of_process(hProcess):
hModule = c_ulong()
count = c_ulong()
modname = c_buffer(30)
windll.psapi.EnumProcessModules(hProcess, byref(hModule), sizeof(hModule), byref(count))
windll.psapi.GetModuleBaseNameA(hProcess, hModule.value, modname, sizeof(modname))
return b''.join([i for i in modn... |
def test_byte_strobes():
bf_a = BitField('bf_a', lsb=0, width=16)
bf_b = BitField('bf_b', lsb=0, width=13)
bf_c = BitField('bf_c', lsb=8, width=16)
bf_d = BitField('bf_d', lsb=14, width=14)
assert (bf_a.byte_strobes == {0: {'bf_lsb': 0, 'bf_msb': 7, 'wdata_lsb': 0, 'wdata_msb': 7}, 1: {'bf_lsb': 8, ... |
def _model_stats_str(model: nn.Module, statistics: Dict[(str, Dict[(str, str)])]) -> str:
def _addindent(s_: str, numSpaces: int) -> str:
s = s_.split('\n')
if (len(s) == 1):
return s_
first = s.pop(0)
s = [((numSpaces * ' ') + line) for line in s]
s = '\n'.join(s... |
class OptionSeriesStreamgraphOnpoint(Options):
def connectorOptions(self) -> 'OptionSeriesStreamgraphOnpointConnectoroptions':
return self._config_sub_data('connectorOptions', OptionSeriesStreamgraphOnpointConnectoroptions)
def id(self):
return self._config_get(None)
def id(self, text: str):... |
class OptionSeriesBubbleSonificationTracksMappingLowpassFrequency(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):
... |
class ActionDescriptor(BaseDescriptor):
def __init__(self, func, name, doc):
self._func = func
self._name = name
self.__doc__ = self._format_doc('action', name, doc, func)
def __get__(self, instance, owner):
if (instance is None):
return self
private_name = ((... |
class RoundTripConstructor(SafeConstructor):
def construct_scalar(self, node):
if (not isinstance(node, ScalarNode)):
raise ConstructorError(None, None, ('expected a scalar node, but found %s' % node.id), node.start_mark)
if ((node.style == '|') and isinstance(node.value, text_type)):
... |
class DefaultRenderer(PyGridCellRenderer):
selected_cells = wx.Brush(wx.Colour(255, 255, 200), wx.SOLID)
normal_cells = wx.Brush('white', wx.SOLID)
odd_cells = wx.Brush(wx.Colour(240, 240, 240), wx.SOLID)
error_cells = wx.Brush(wx.Colour(255, 122, 122), wx.SOLID)
warn_cells = wx.Brush(wx.Colour(255,... |
def babai(B, t):
A = IntegerMatrix((B.nrows + 1), (B.ncols + 1))
for i in range(B.nrows):
for j in range(B.ncols):
A[(i, j)] = B[(i, j)]
LLL.reduction(A)
A.swap_rows(0, B.nrows)
for j in range(B.ncols):
A[((- 1), j)] = t[j]
A[((- 1), (- 1))] = ceil(A[(- 2)].norm())
... |
def test_correct_number_of_rows_are_generated():
df = gen.generate(props={'region': gen.choice(data=['EMEA', 'LATAM', 'NAM', 'APAC'], weights=[0.1, 0.1, 0.3, 0.5]), 'country': gen.country_codes(region_field='region'), 'client_type': gen.choice(data=data.client_types()), 'client_name': gen.company_namer(field='clien... |
def get_tx_status(account: AbstractAccount, tx_hash: bytes, height: int, conf: int, timestamp: Union[(bool, int)]) -> TxStatus:
if (not account.have_transaction_data(tx_hash)):
return TxStatus.MISSING
metadata = account.get_transaction_metadata(tx_hash)
if (metadata.position == 0):
if ((heig... |
class TestTachoMotorCountPerRotValue(ptc.ParameterizedTestCase):
def test_count_per_rot_value(self):
self.assertEqual(self._param['motor'].count_per_rot, motor_info[self._param['motor'].driver_name]['count_per_rot'])
def test_count_per_rot_value_is_read_only(self):
with self.assertRaises(Attribu... |
class OptionSeriesFunnelSonificationContexttracksMappingNoteduration(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 show_request_result(request_result):
rr = request_result
parts = []
log = parts.append
def _indent(s):
indent_str = ' '
return ('\n' + indent_str).join(s.split('\n'))
if rr.query:
query_string = ('?' + '&'.join((('%s=%s' % (k, v)) for (k, v) in sorted(rr.query.items())))... |
class IBCApplicationsTransferRestClientTestCase(TestCase):
REST_CLIENT = IBCApplicationsTransferRestClient
def make_clients(self, response_content: Dict) -> Tuple[(MockRestClient, IBCApplicationsTransferRestClient)]:
mock_client = MockRestClient(json_encode(response_content).encode('utf-8'))
res... |
def train(config, train_dataloader, valid_dataloader, device, model, loss_class, optimizer, lr_scheduler, post_process_class, eval_class, pre_best_model_dict, logger, vdl_writer=None):
cal_metric_during_train = config['Global'].get('cal_metric_during_train', False)
log_smooth_window = config['Global']['log_smoo... |
class petsc_ASM(KSP_Preconditioner):
def __init__(self, L, prefix=None):
self.PCType = 'asm'
self.L = L
self._initializePC(prefix)
self.pc.setFromOptions()
def _initializePC(self, prefix=None):
self.pc = p4pyPETSc.PC().create()
self.pc.setOptionsPrefix(prefix)
... |
def get_archdir_freebytes(arch_cfg: configuration.Archiving) -> typing.Tuple[(typing.Dict[(str, int)], typing.List[str])]:
log_messages = []
target = arch_cfg.target_definition()
archdir_freebytes = {}
timeout = 5
try:
completed_process = subprocess.run([target.disk_space_path], env={**os.en... |
class TestHidden(testgui.TestCase):
def wait(self):
self.loop = GLib.MainLoop()
self.loop.run()
def quitloop(self, f, status):
if (status == 0):
self.loop.quit()
def testCreate(self):
f = gtkfractal.Hidden(TestHidden.g_comp, 64, 40)
f.connect('status-chang... |
class TestPrivacyRequestsManualWebhooks():
('fides.api.service.privacy_request.request_runner_service.upload')
def test_privacy_request_needs_manual_input_key_in_cache(self, mock_upload, integration_manual_webhook_config, access_manual_webhook, policy, run_privacy_request_task, db):
customer_email = 'cu... |
def test_that_invalid_time_map_file_raises_config_validation_error(tmpdir):
with tmpdir.as_cwd():
with open('time_map.txt', 'w', encoding='utf-8') as fo:
fo.writelines('invalid')
with pytest.raises(ConfigValidationError, match='Could not read timemap file'):
_ = ModelConfig.f... |
class OptionSeriesScatter3dDragdropDraghandle(Options):
def className(self):
return self._config_get('highcharts-drag-handle')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('#fff')
def color(self, text: str):
se... |
def delete_service_archive(archive_name):
response = get_session().delete((base_url + 'service-archives/{}'.format(archive_name)))
if (response.status_code != 200):
raise get_exception(response)
else:
return response.json().get('message', 'service archive deleted successfully') |
def test_encode_complete_keywords():
df = pd.DataFrame({'var_A': (((((((['A'] * 5) + (['B'] * 11)) + (['C'] * 4)) + (['D'] * 9)) + (['E'] * 2)) + (['F'] * 2)) + (['G'] * 7)), 'var_B': (((((((['A'] * 11) + (['B'] * 7)) + (['C'] * 4)) + (['D'] * 9)) + (['E'] * 2)) + (['F'] * 2)) + (['G'] * 5)), 'var_C': (((((((['A'] ... |
def test_break_contained_in_switch_add_case_default(task):
(arg1_1, vertices) = __graph_loop_break_in_switch(task)
task.options = Options()
task.options.update({'pattern-independent-restructuring.loop_break_switch': 'None'})
PatternIndependentRestructuring().run(task)
assert (isinstance((seq_node :=... |
def botcmd(*args, hidden: bool=None, name: str=None, split_args_with: str='', admin_only: bool=False, historize: bool=True, template: str=None, flow_only: bool=False, syntax: str=None) -> Callable[([BotPlugin, Message, Any], Any)]:
def decorator(func):
return _tag_botcmd(func, _re=False, _arg=False, hidden=... |
class ReverseRegisterLookup():
def __init__(self, d):
self._dict = d
def __getitem__(self, spec_lookup):
for (_entity_cls, entity_id) in self._dict.items():
for (entity_idd, entry) in entity_id.items():
if (entry['spec'] == spec_lookup):
return ent... |
class IndexValidator(OptionValidator):
def __init__(self, model, extra=None, exclude=None):
self.model = model
self.extra = (extra or [])
self.exclude = (exclude or [])
def values(self):
inspector = sa.inspect(db.engine)
column_map = {column.key: label for (label, column)... |
def test_show_with_content(tmp_path, capsys):
args = helpers.setup_temp_env(tmp_path)
reqid = 'req-compile-bench--nobody-mac'
reqdir = (((tmp_path / 'BENCH') / 'REQUESTS') / reqid)
reqdir.mkdir()
shutil.copy((helpers.DATA_ROOT / 'request.json'), (reqdir / 'request.json'))
shutil.copy((helpers.DA... |
def _build_request(self, func, path, method, *args, **kwargs):
return_type = get_type_hints(func).get('return')
if (return_type is None):
raise TypeError('Return type must be annotated in the decorated function.')
actual_dataclass = _extract_dataclass_from_generic(return_type)
logger.debug(f'ret... |
def ths_1():
shape = (2000, 1000)
sample = np.random.randint(0, 255, (1000,), dtype='uint8')
plain = np.random.randint(0, 255, 16, dtype='uint8')
samples = np.array([sample for i in range(shape[0])], dtype='uint8')
plaintext = np.array([plain for i in range(shape[0])], dtype='uint8')
return scar... |
class OptionPlotoptionsAreasplineSonificationTracksMapping(Options):
def frequency(self) -> 'OptionPlotoptionsAreasplineSonificationTracksMappingFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsAreasplineSonificationTracksMappingFrequency)
def gapBetweenNotes(self) -> 'OptionPlotop... |
class OptionPlotoptionsWaterfallSonificationTracksMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsWaterfallSonificationTracksMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsWaterfallSonificationTracksMappingLowpassFrequency)
def resonance(self) -> '... |
def run_pre_publishers():
from anima.dcc.mayaEnv.publish import PublishError
from anima.dcc import mayaEnv
m_env = mayaEnv.Maya()
version = m_env.get_current_version()
if (not version):
return
from anima.representation import Representation
if (Representation.repr_separator in versio... |
class TestGlobalAdaptationManager(unittest.TestCase):
examples = traits.adaptation.tests.abc_examples
def setUp(self):
reset_global_adaptation_manager()
def test_reset_adaptation_manager(self):
ex = self.examples
adaptation_manager = get_global_adaptation_manager()
adaptation... |
def extractHiganbanaloveschrysanthemumHomeBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Powerful Skull in The Last Days', 'Powerful Skull in The Last Days', 'translated'... |
class TestCallableModuleCallableRaise():
def test_callable_module(self, monkeypatch):
with monkeypatch.context() as m:
m.setattr(sys, 'argv', ['', '--config', './tests/conf/yaml/test_fail_callable.yaml'])
with pytest.raises(_SpockFieldHandlerError):
config = ConfigArg... |
class Close():
def __init__(self, ilo, delete_aliases=False, skip_flush=False):
verify_index_list(ilo)
self.index_list = ilo
self.delete_aliases = delete_aliases
self.skip_flush = skip_flush
self.client = ilo.client
self.loggit = logging.getLogger('curator.actions.clo... |
class BarrierRequestReply(base_tests.SimpleProtocol):
def runTest(self):
logging.info('Running Barrier_Request_Reply test')
logging.info('Sending Barrier Request')
logging.info('Expecting a Barrier Reply with same xid')
request = ofp.message.barrier_request()
(response, pkt) ... |
def clear_orphan_webdriver():
process = all_webdriver()
killed = []
for item in process:
if (not item.parent()):
kill_process_tree_by_id(item.pid)
killed.append(item)
elif (item.parent().name().lower() == 'systemd'):
kill_process_tree_by_id(item.pid)
... |
class Neon(Memory):
def global_(cls):
return '#include <arm_neon.h>'
def can_read(cls):
return False
def alloc(cls, new_name, prim_type, shape, srcinfo):
if (not shape):
raise MemGenError(f'{srcinfo}: Neon vectors are not scalar values')
vec_types = {'float': (4, ... |
def esrep_sync_cb(result, task_prefix):
result['task_prefix'] = task_prefix
task_id = generate_internal_task_id()
task = cq.send_task(ESREP_SYNC_CB, args=(result, task_id), queue=Q_MGMT, expires=120, task_id=task_id)
if (not task):
raise CallbackError(('Failed to created task "%s"' % ESREP_SYNC_... |
def test_performative_string_value():
assert (str(FipaMessage.Performative.CFP) == 'cfp'), 'The str value must be cfp'
assert (str(FipaMessage.Performative.PROPOSE) == 'propose'), 'The str value must be propose'
assert (str(FipaMessage.Performative.DECLINE) == 'decline'), 'The str value must be decline'
... |
(st.lists(st.integers(min_value=0, max_value=6), min_size=3))
def test_prune_reinsert_root_tracking_binary_tree(element_flipping):
tracker = RootTracker()
present = set()
for node_id in element_flipping:
node = FULL_BINARY_TREE[node_id]
if (node in present):
(prune_root_id, _) = ... |
.xfail(raises=ImageComparisonFailure, reason='Matplotlib plots for reasons a different image size.')
.skipif((MID_MEMORY > memory), reason='Travis has too less memory to run it.')
def test_hicAggregateContacts_chromosome_not_given():
outfile_aggregate_plots = NamedTemporaryFile(suffix='.png', prefix='hicaggregate_t... |
class GraphicalWifiMixin(_BaseMixin):
defaults = [('wifi_arc', 75, 'Angle of arc in degrees.'), ('wifi_rectangle_width', 5, 'Width of rectangle in pixels.'), ('wifi_shape', 'arc', "'arc' or 'rectangle'")]
def __init__(self):
self.wifi_width = 0
def set_wifi_sizes(self):
self.wifi_padding_x =... |
def test_epoch():
expected = pytest.approx(0)
assert (_rfc3339.parse_to_epoch('1970-01-01T00:00:00Z') == expected)
assert (_rfc3339.parse_to_epoch('1970-01-01T00:00:00z') == expected)
assert (_rfc3339.parse_to_epoch('1970-01-01T00:00:00+00:00') == expected)
assert (_rfc3339.parse_to_epoch('1970-01-0... |
class Trips(list):
def __init__(self, *args):
list.__init__(self, *args)
self.trip_num = 1
def to_geo_json(self):
feature_collection = FeatureCollection(self)
return feature_collection
def get_trips_as_dict(self):
return [trip.get_info() for trip in self]
def get_... |
def gen_function(func_attrs, reduction_op, reduction_identity='ElementCompute()'):
backend_spec = CUDASpec()
elem_input_type = backend_spec.dtype_to_lib_type(func_attrs['inputs'][0]._attrs['dtype'])
output_type = func_attrs['outputs'][0]._attrs['dtype']
elem_output_type = backend_spec.dtype_to_lib_type(... |
def prepare_db(user_engine=None, user_session=None, print_sql=False):
global engine
global Session
if ((user_engine is not None) and (user_session is not None)):
engine = user_engine
Session = user_session
if ((engine is None) or (Session is None)):
engine_args = {'encoding': 'ut... |
def validate_bls_to_execution_change(btec_dict: Dict[(str, Any)], credential: Credential, *, input_validator_index: int, input_execution_address: str, chain_setting: BaseChainSetting) -> bool:
validator_index = int(btec_dict['message']['validator_index'])
from_bls_pubkey = BLSPubkey(decode_hex(btec_dict['messag... |
_tag(takes_context=True)
def feincms_nav(context, feincms_page, level=1, depth=1, group=None):
page_class = _get_page_model()
if (not feincms_page):
return []
if isinstance(feincms_page, HttpRequest):
try:
feincms_page = page_class.objects.for_request(feincms_page, best_match=Tru... |
class Query(object):
def Channel(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None):
return grpc.experimental.unary_unary(request, target, '/ibc.core.channel.v1.Query/Channel', ibc_dot_core_dot_cha... |
class OptionSeriesNetworkgraphDataEvents(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)
... |
class TestDeleteComposableTemplateParamSource():
def test_delete_composable_template_by_name(self):
source = params.DeleteComposableTemplateParamSource(track.Track(name='unit-test'), params={'template': 'default'})
assert (source.params() == {'template': 'default', 'templates': [('default', False, N... |
def extractXiongmaotlsWordpressCom(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_typ... |
def downgrade():
op.add_column('session', sa.Column('level_id', sa.INTEGER(), autoincrement=False, nullable=True))
op.create_foreign_key(u'session_level_id_fkey', 'session', 'level', ['level_id'], ['id'])
op.create_table('level', sa.Column('id', sa.INTEGER(), nullable=False), sa.Column('name', sa.VARCHAR(),... |
class LtileLayer():
def __init__(self, component, token, url, options, leaflet_map=None):
(self.component, self.leaflet_map) = (component, leaflet_map)
self.srv_url = ('%s?access_token=%s' % (url, token))
(self.options, self.__is_attached, self._js) = ((options or {}), False, [])
def att... |
def Run(params):
base_branch = params.args[1]
repos_and_local_branches = GetReposAndLocalBranches(params, patterns=[('*%s*' % base_branch)])
branch_to_repos = ConvertRepoToBranchesToBranchToRepos(repos_and_local_branches)
if (len(params.config.repos) == 1):
params.config.serial = True
if ((b... |
(name='api.mon.node.tasks.mon_node_sync', base=NodeMonInternalTask)
_lock(key_kwargs=('node_uuid',), wait_for_release=True)
_task_log(LOG_MON_NODE_UPDATE)
def mon_node_sync(task_id, sender, node_uuid=None, log=LOG, **kwargs):
assert node_uuid
node = log.obj = Node.objects.get(uuid=node_uuid)
return get_moni... |
class TestUserPermissions(BaseTestCase):
def test_user_permissions(self, db_session):
created_user = add_user(db_session)
permissions = UserService.permissions(created_user, db_session=db_session)
expected = [PermissionTuple(created_user, 'alter_users', 'user', None, None, False, True), Perm... |
class SnmpContext(object):
def __init__(self, snmpEngine, contextEngineId=None):
mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder
(snmpEngineId,) = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')
if (contextEngineId is None):
self.contextEngin... |
class OptionSeriesAreasplinerangeSonification(Options):
def contextTracks(self) -> 'OptionSeriesAreasplinerangeSonificationContexttracks':
return self._config_sub_data('contextTracks', OptionSeriesAreasplinerangeSonificationContexttracks)
def defaultInstrumentOptions(self) -> 'OptionSeriesAreasplinerang... |
class File(FileSource):
def __init__(self, path, expand_user=True, expand_vars=False, unix_glob=True, recursive_glob=True, filter=None, merger=None):
if expand_user:
path = os.path.expanduser(path)
if expand_vars:
path = os.path.expandvars(path)
if (unix_glob and set(... |
(frozen=True)
class ConditionSymbol():
condition: Condition
symbol: LogicCondition
z3_condition: PseudoLogicCondition
def __eq__(self, other):
return (isinstance(other, ConditionSymbol) and (self.condition == other.condition) and (self.symbol == other.symbol) and self.z3_condition.is_equivalent_... |
class ExchangeRateTests(unittest.TestCase):
def test_unicode(self):
exchange_rate = ExchangeRate()
exchange_rate.SourceCurrencyCode = 'EUR'
self.assertEqual(str(exchange_rate), 'EUR')
def test_valid_object_name(self):
obj = ExchangeRate()
client = QuickBooks()
res... |
class Billing(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
lazy_import()
retu... |
class Solution():
def postorderTraversal(self, root: TreeNode) -> List[int]:
stk = [(root, False, False)]
ret = []
while stk:
(curr, left_done, right_done) = stk.pop()
if (curr is None):
continue
if (left_done and right_done):
... |
class Migration(migrations.Migration):
dependencies = [('reporting', '0002_auto__2051')]
operations = [migrations.CreateModel(name='ReportingAgencyMissingTas', fields=[('reporting_agency_missing_tas_id', models.AutoField(primary_key=True, serialize=False)), ('toptier_code', models.TextField()), ('fiscal_year', ... |
class BlockStateDep(Checker):
def __init__(self):
super().__init__()
def check(self, logger):
block_state_op_idx = (- 1)
for (i, log) in enumerate(logger.logs):
if (log.op in (COINBASE, TIMESTAMP, NUMBER, DIFFICULTY, GASLIMIT)):
block_state_op_idx = i
... |
def get_context(context):
if (frappe.session.user == 'Guest'):
frappe.throw(_('You need to be logged in to access this page'), frappe.PermissionError)
context.show_sidebar = True
if frappe.db.exists('Patient', {'email': frappe.session.user}):
patient = frappe.get_doc('Patient', {'email': fra... |
class Migration(migrations.Migration):
dependencies = [('django_etebase', '0017_auto__0958')]
operations = [migrations.AlterField(model_name='collectionitem', name='uid', field=models.CharField(db_index=True, max_length=43, validators=[django.core.validators.RegexValidator(message='Not a valid UID', regex='^[a-... |
(no_gui_test_assistant, 'No GuiTestAssistant')
class TestDoLater(TestCase, GuiTestAssistant):
def setUp(self):
GuiTestAssistant.setUp(self)
def tearDown(self):
GuiTestAssistant.tearDown(self)
def test_basic(self):
handler = ConditionHandler()
timer = do_later(handler.callback... |
class TestCalcParser(unittest.TestCase):
def setUp(self):
self.calc_parser = rd_parser.CalcParser()
def calc(self, calc_stmt):
self.calc_parser.calc(calc_stmt)
def assertResult(self, calc_stmt, result):
self.assertEqual(self.calc_parser.calc(calc_stmt), result)
def assertParseErr... |
class OptionSeriesArearangeStatesSelectMarker(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._c... |
class DummyEmbeddingProvider(BaseEmbeddingProvider):
def get(self, text):
return np.zeros(768)
def __call__(self, text):
return self.get(text)
def config(self):
return {'class': self.__class__.__name__, 'type': 'embedding_provider'}
def from_config(cls, config):
return cl... |
def test_strava_widget_popup(manager_nospawn, strava):
manager_nospawn.start(strava)
data_parsed(manager_nospawn)
manager_nospawn.c.bar['top'].fake_button_press(0, 'top', 0, 0, 1)
assert (len(manager_nospawn.c.internal_windows()) == 2)
(_, text) = manager_nospawn.c.widget['stravawidget'].eval('self.... |
.parametrize('argset', (mixed_test_argsets() + mixed_trial_argsets()))
def test_replace_arg_mixed(mixed_form, argset):
new_arg = argset.new_arg
idxs = argset.idxs
error = argset.error
replace_function = argset.replace_function
arg_idx = argset.arg_idx
mixed_form = mixed_form.label_map((lambda t:... |
def summary_observations(draw, summary_keys, std_cutoff, names):
kws = {'name': draw(names), 'key': draw(summary_keys), 'error': draw(st.floats(min_value=std_cutoff, allow_nan=False, allow_infinity=False)), 'error_min': draw(positive_floats), 'error_mode': draw(st.sampled_from(ErrorMode)), 'value': draw(positive_fl... |
class OptionSeriesAreasplineDatalabels(Options):
def align(self):
return self._config_get('center')
def align(self, text: str):
self._config(text, js_type=False)
def allowOverlap(self):
return self._config_get(False)
def allowOverlap(self, flag: bool):
self._config(flag, ... |
_metrics.timeit
def __country_codes(region_field=None, key=None, context=None, randomstate=None, df=None, sampler=None):
region = None
if (region_field and df):
region = df[region_field]
key = ((key + '-') + region)
if (not context.has_generator(key)):
generator = CountryCodeGenerato... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.