code stringlengths 281 23.7M |
|---|
class NBytes_List():
def __init__(self, name, nbytes=2):
self.name = name
self.length = nbytes
self.lonbytes = []
def decode(self, data):
while data:
mynbyte = NBytes('', self.length)
data = mynbyte.decode(data)
self.lonbytes.append(mynbyte)
... |
def test_returning_a_pathlib_path(local_dummy_file):
def t1() -> FlyteFile:
return pathlib.Path(local_dummy_file)
def wf1() -> FlyteFile:
return t1()
wf_out = wf1()
assert isinstance(wf_out, FlyteFile)
with open(wf_out, 'r') as fh:
assert (fh.read() == 'Hello world')
asse... |
def get_network_from_param_list(param_list, new_network):
assert (len(list(new_network.parameters())) == len(param_list))
layer_idx = 0
model_state_dict = new_network.state_dict()
for (key, _) in model_state_dict.items():
model_state_dict[key] = param_list[layer_idx]
layer_idx += 1
n... |
.django_db
def test_federal_accounts_endpoint_keyword_filter_agency_name(client, fixture_data):
resp = client.post('/api/v2/federal_accounts/', content_type='application/json', data=json.dumps({'filters': {'fy': '2017'}, 'keyword': 'burea'}))
response_data = resp.json()
assert (len(response_data['results'])... |
def _is_chinese_char_bert(cp: int) -> bool:
if (((cp >= 19968) and (cp <= 40959)) or ((cp >= 13312) and (cp <= 19903)) or ((cp >= 131072) and (cp <= 173791)) or ((cp >= 173824) and (cp <= 177983)) or ((cp >= 177984) and (cp <= 178207)) or ((cp >= 178208) and (cp <= 183983)) or ((cp >= 63744) and (cp <= 64255)) or (... |
def negative_sharpe_ratio(weights: ARRAY_OR_SERIES[FLOAT], mean_returns: ARRAY_OR_SERIES[FLOAT], cov_matrix: ARRAY_OR_DATAFRAME[FLOAT], risk_free_rate: FLOAT) -> FLOAT:
type_validation(weights=weights, means=mean_returns, cov_matrix=cov_matrix, risk_free_rate=risk_free_rate)
sharpe = annualised_portfolio_quanti... |
class Spool(Boxes):
ui_group = 'Misc'
def __init__(self) -> None:
Boxes.__init__(self)
self.addSettingsArgs(edges.FingerJointSettings)
self.buildArgParser(h=100)
self.argparser.add_argument('--outer_diameter', action='store', type=float, default=200.0, help='diameter of the flang... |
def clean_if_exist(path, files):
path = os.path.abspath(path)
for filename in files:
filename = os.path.join(path, filename)
if os.path.exists(filename):
if os.path.isdir(filename):
log.info('removing folder %s', filename)
shutil.rmtree(filename)
... |
def setup(app):
app.router.add_route('POST', '/fledge/control/script/{script_name}/schedule', add_schedule_and_configuration)
app.router.add_route('POST', '/fledge/control/script', add)
app.router.add_route('GET', '/fledge/control/script', get_all)
app.router.add_route('GET', '/fledge/control/script/{sc... |
class Billboard():
def __init__(self, ui):
self.page = ui.page
self.chartFamily = 'BB'
def plot(self, record=None, y=None, x=None, kind='line', profile=None, width=(100, '%'), height=(330, 'px'), options=None, html_code=None, **kwargs):
if ((y is not None) and (not isinstance(y, list))):... |
def _find_graph_differences(previous_graph: Optional[GraphRepr], current_graph: GraphRepr, previous_results: Dict[(str, Optional[List[Row]])], previous_erasure_results: Dict[(str, int)]) -> Optional[GraphDiff]:
if (not previous_graph):
return None
def all_edges(graph: GraphRepr) -> Set[str]:
edg... |
def refine_hit(args):
(seqname, seq, group_fasta, excluded_taxa, tempdir) = args
F = NamedTemporaryFile(delete=True, dir=tempdir, mode='w+')
F.write(f'''>{seqname}
{seq}''')
F.flush()
best_hit = get_best_hit(F.name, group_fasta, excluded_taxa, tempdir)
F.close()
return ([seqname] + best_hit) |
def upgrade():
op.alter_column('sessions_version', 'end_time', new_column_name='ends_at')
op.alter_column('sessions_version', 'start_time', new_column_name='starts_at')
op.alter_column('events_version', 'end_time', new_column_name='ends_at')
op.alter_column('events_version', 'start_time', new_column_nam... |
def _print_cursor_stmt(cur: Node, target: Cursor, env: PrintEnv, indent: str) -> list[str]:
stmt = cur._node
if isinstance(stmt, LoopIR.If):
cond = _print_expr(stmt.cond, env)
lines = [f'{indent}if {cond}:']
lines.extend(_print_cursor_block(cur.body(), target, env.push(), (indent + ' ')... |
_order_decorator(jwt_required)
def is_registrar(f):
(f)
def decorated_function(*args, **kwargs):
user = current_user
if user.is_staff:
return f(*args, **kwargs)
if (('event_id' in kwargs) and (user.is_registrar(kwargs['event_id']) or user.has_event_access(kwargs['event_id']))... |
class OptionSeriesColumnpyramidSonificationTracksMappingPitch(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('y')
def mapTo(self, text: str):
sel... |
class OptionSeriesColumnStates(Options):
def hover(self) -> 'OptionSeriesColumnStatesHover':
return self._config_sub_data('hover', OptionSeriesColumnStatesHover)
def inactive(self) -> 'OptionSeriesColumnStatesInactive':
return self._config_sub_data('inactive', OptionSeriesColumnStatesInactive)
... |
class OptionSeriesBubbleStatesSelectMarker(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._conf... |
.scheduler
.integration_test
.parametrize('extra_config, extra_poly_eval, cmd_line_arguments,num_successful,num_iters,progress,assert_present_in_snapshot, expected_state', [pytest.param('MAX_RUNTIME 5', ' import time; time.sleep(1000)', [ENSEMBLE_EXPERIMENT_MODE, '--realizations', '0,1', 'poly_example/poly.ert'], 0,... |
def get_label_arrays(fnames, column_num=None):
try:
assert (column_num is not None)
except AssertionError:
print('You need to call this function with a column number for me to read from')
sys.exit()
low_array = []
medium_array = []
high_array = []
fname2label_dict = {}
... |
('aea.cli.upgrade.get_latest_version_available_in_registry')
('click.echo')
class TestUpgradeProjectWithoutNewerVersion(BaseTestUpgradeProject):
def test_run(self, mock_click_echo, mock_get_latest_version):
fake_old_public_id = self.OLD_AGENT_PUBLIC_ID
mock_get_latest_version.return_value = fake_old... |
class TestNull(util.ColorAsserts, unittest.TestCase):
def test_null_input(self):
c = Color('hct', [NaN, 20, 30], 1)
self.assertTrue(c.is_nan('hue'))
def test_none_input(self):
c = Color('color(--hct none 20 30 / 1)')
self.assertTrue(c.is_nan('hue'))
def test_null_normalizatio... |
('/get_vehicleinfo/<string:vin>')
def get_vehicle_info(vin):
from_cache = (int(request.args.get('from_cache', 0)) == 1)
response = app.response_class(response=json.dumps(APP.myp.get_vehicle_info(vin, from_cache).to_dict(), default=str), status=200, mimetype='application/json')
return response |
def print_default_benchmark_total_line(stat: DefaultStat) -> None:
logging.info(SINGLE_UNDERLINE)
logging.info(bold_white(f"|{'Total':^19}|{stat.total_seconds:^16.3f}|{stat.total_tx:^16}|{'-':^16}|{stat.total_blocks:^16}|{'-':^20}|{stat.total_gas:^16,}|{'-':^16}|"))
logging.info(bold_white(f"|{'Avg':^19}|{s... |
class IShellLinkA(IUnknown):
_iid_ = GUID('{000214EE-0000-0000-C000-}')
_methods_ = [COMMETHOD([], HRESULT, 'GetPath', (['in', 'out'], c_char_p, 'pszFile'), (['in'], c_int, 'cchMaxPath'), (['in', 'out'], POINTER(WIN32_FIND_DATAA), 'pfd'), (['in'], DWORD, 'fFlags')), COMMETHOD([], HRESULT, 'GetIDList', (['retval... |
class StringCounter():
def __init__(self):
self._counter = {}
def add(self, string):
if (string is None):
return
if (string in self._counter):
self._counter[string] += 1
else:
self._counter[string] = 1
def count(self, string):
retur... |
def generate_sample_data(output: IO[Any]):
with Writer(output) as writer:
for i in range(1, 11):
simple_message = SimpleMessage(data=f'Hello MCAP protobuf world #{i}!')
writer.write_message(topic='/simple_message', message=simple_message, log_time=(i * 1000), publish_time=(i * 1000))... |
class OptionSeriesScatter3dSonificationTracksMappingPitch(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('y')
def mapTo(self, text: str):
self._c... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = None
fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path': {... |
class BFBase(torch.nn.Module):
def __init__(self, mask_model: torch.nn.Module, ref_mic: Optional[int]=0, eps: Optional[float]=1e-05):
super().__init__()
self.mask_model = mask_model
self._ref_mic = ref_mic
self._eps = eps
self.fake = torch.nn.Parameter(torch.zeros(1))
def... |
def extractClairyclairetranslationWordpressCom(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, ... |
class init_cond(object):
def __init__(self, L, scaling=0.75, r=1):
self.radius = 0.15
self.xc = 0.5
self.yc = 0.75
self.scaling = scaling
if ((r % 2) == 0):
r += 1
self.r = r
def uOfXT(self, x, t):
import numpy as np
theta = math.atan2(... |
def _try_add_key(ctx: Context, type_: str, filepath: str, connection: bool=False) -> None:
try:
if connection:
ctx.agent_config.connection_private_key_paths.create(type_, filepath)
else:
ctx.agent_config.private_key_paths.create(type_, filepath)
except ValueError as e:
... |
class AddableJoinOp(JoinOp):
__slots__ = ('_parent',)
_parent: Optional[Event]
def __init__(self, *sources: Event):
JoinOp.__init__(self)
self._sources = deque()
self._parent = None
self._set_sources(*sources)
def _set_sources(self, *sources):
for source in source... |
def bps(bandwidth):
match = re.match('(\\d+)\\s*(\\w+)', bandwidth)
if (not match):
raise ValueError('bandwidth not in form of 10Mbps')
(bw, units) = match.groups()
bw = int(bw)
units = units.lower()
if (units == 'gbps'):
return (bw * )
if (units == 'mbps'):
return (b... |
(scope='function')
def slack_enterprise_user_id(slack_enterprise_test_client: SlackTestClient, slack_enterprise_identity_email) -> Generator:
response = slack_enterprise_test_client.get_user_from_email(email=slack_enterprise_identity_email)
if (response.ok and response.json()['user']):
return response.j... |
def compare_results(mdir, relaxed=False, artifacts_dir=None):
if (artifacts_dir is None):
artifacts_path = os.environ['rmtoo_test_dir']
else:
artifacts_path = os.path.join(os.environ['rmtoo_test_dir'], artifacts_dir)
files_is = find(artifacts_path)
files_should = find(os.path.join(mdir, ... |
.django_db
def test_object_budget_match(client):
models = copy.deepcopy(GLOBAL_MOCK_DICT)
for entry in models:
baker.make(entry.pop('model'), **entry)
baker.make(FinancialAccountsByProgramActivityObjectClass, **{'financial_accounts_by_program_activity_object_class_id': (- 4), 'submission_id': (- 1),... |
class ConflictIterator(object):
def __init__(self, index):
citer = ffi.new('git_index_conflict_iterator **')
err = C.git_index_conflict_iterator_new(citer, index._index)
check_error(err)
self._index = index
self._iter = citer[0]
def __del__(self):
C.git_index_conf... |
_OptParamCapability.register_type(BGP_CAP_MULTIPROTOCOL)
class BGPOptParamCapabilityMultiprotocol(_OptParamCapability):
_CAP_PACK_STR = '!HBB'
def __init__(self, afi, safi, reserved=0, **kwargs):
super(BGPOptParamCapabilityMultiprotocol, self).__init__(**kwargs)
self.afi = afi
self.reser... |
class TestLegacyTabSlugsSep(util.MdCase):
extension = ['pymdownx.tabbed', 'toc']
extension_configs = {'pymdownx.tabbed': {'slugify': slugify(case='lower'), 'separator': '_', 'alternate_style': True}}
MD = '\n ### Here is some text\n\n === "Here is some text"\n content\n\n === "Here is some t... |
class TestTagPropagation():
.SchedulerTestConfig(items_to_analyze=15, pipeline=True)
def test_run_analysis_with_tag(self, analysis_finished_event, unpacking_scheduler, backend_db, analysis_scheduler):
test_fw = Firmware(file_path=f'{get_test_data_dir()}/container/with_key.7z')
(test_fw.version, ... |
def get_host_port(args, kwargs):
host = (args[0] if args else kwargs.get('server'))
port = None
if (not host):
host = kwargs.get('host', 'localhost')
for sep in (',', ':'):
if (sep in host):
(host, port) = host.rsplit(sep, 1)
port = int(port)
... |
class CacheStorage(object):
def __init__(self):
self.items = {}
def get(self, cachepath, create_template):
template = self.items.get(cachepath)
if (not template):
dct = self._load(cachepath)
if dct:
template = create_template()
for ... |
class HSL(Cylindrical, Space):
BASE = 'srgb'
NAME = 'hsl'
SERIALIZE = ('--hsl',)
CHANNELS = (Channel('h', 0.0, 360.0, bound=True, flags=FLG_ANGLE), Channel('s', 0.0, 1.0, bound=True, flags=FLG_PERCENT), Channel('l', 0.0, 1.0, bound=True, flags=FLG_PERCENT))
CHANNEL_ALIASES = {'hue': 'h', 'saturation... |
def loadAllJsonObjects(dir):
objects = []
badFiles = []
for (root, dirNames, fileNames) in os.walk(dir):
for fileName in fnmatch.filter(fileNames, '*.json'):
try:
path = os.path.join(root, fileName)
with open(path, 'r') as f:
loadedObje... |
def add_blank_grams(pruned_ngrams, num_tokens, blank):
all_grams = [gram for grams in pruned_ngrams for gram in grams]
maxorder = len(pruned_ngrams)
blank_grams = {}
if (blank == 'forced'):
pruned_ngrams = [(pruned_ngrams[0] if (i == 0) else []) for i in range(maxorder)]
pruned_ngrams[0].app... |
class NodeTreeModel(TreeModel):
node_manager = Instance(NodeManager, ())
_monitors = Dict()
def has_children(self, node):
node_type = self.node_manager.get_node_type(node)
if node_type.allows_children(node):
has_children = node_type.has_children(node)
else:
ha... |
class TensorGlyph(Module):
__version__ = 0
glyph = Instance(glyph.Glyph, allow_none=False, record=True)
actor = Instance(Actor, allow_none=False, record=True)
input_info = PipelineInfo(datasets=['any'], attribute_types=['any'], attributes=['tensors'])
view = View(Group(Item(name='actor', style='cust... |
()
def setup_to_fail():
is_active = shellexec('systemctl is-active chronyd').stdout[0]
is_enabled = shellexec('systemctl is-enabled chronyd').stdout[0]
shutil.copy('/etc/chrony.conf', '/etc/chrony.conf.bak')
shellexec('systemctl stop chronyd')
shellexec('systemctl disable chronyd')
shellexec('se... |
class TestComboField(FieldMixin, unittest.TestCase):
def _create_widget_simple(self, **traits):
traits.setdefault('value', 'one')
traits.setdefault('values', ['one', 'two', 'three', 'four'])
traits.setdefault('tooltip', 'Dummy')
return ComboField(**traits)
def test_combo_field(se... |
def add_dataset(dataset, name='', **kwargs):
if isinstance(dataset, (tvtk.DataSet, vtk.vtkDataSet)):
d = VTKDataSource()
d.data = tvtk.to_tvtk(dataset)
elif isinstance(dataset, (tvtk.DataObject, vtk.vtkDataObject)):
d = VTKObjectSource()
tp = tvtk.TrivialProducer()
tp.set... |
class OptionSeriesArcdiagramDatalabels(Options):
def align(self):
return self._config_get('undefined')
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(fla... |
class OptionSonificationGlobaltracksMappingPlaydelay(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._confi... |
def SemiCoarsenedExtrudedHierarchy(base_mesh, height, nref=1, base_layer=(- 1), refinement_ratio=2, layers=None, kernel=None, extrusion_type='uniform', gdim=None, mesh_builder=firedrake.ExtrudedMesh):
if (not isinstance(base_mesh, firedrake.mesh.MeshGeometry)):
raise ValueError(f'Can only extruded a mesh, n... |
class KvmManageController(VmController):
def __init__(self):
import libvirt
self.libvirt = libvirt
def stop_vm(self, vm_name):
with self.libvirt.open(None) as conn:
vm = conn.lookupByName(vm_name)
vm.destroy()
def set_snapshot(self, vm_name, snapshot_name):
... |
class StateStorageBase():
def __init__(self) -> None:
pass
async def set_data(self, chat_id, user_id, key, value):
raise NotImplementedError
async def get_data(self, chat_id, user_id):
raise NotImplementedError
async def set_state(self, chat_id, user_id, state):
raise Not... |
class TestUnreadTopicsTag(BaseTrackingTagsTestCase):
def test_can_determine_unread_forums(self):
def get_rendered(topics, user):
request = self.get_request()
request.user = user
ForumPermissionMiddleware((lambda r: HttpResponse('Response'))).process_request(request)
... |
def process_location(location: str, data_dir: Path, split_path: Path, token: str, cfg: DictConfig, generate_tiles: bool=False):
params = location_to_params[location]
bbox = params['bbox']
projection = Projection(*bbox.center)
splits = json.loads(split_path.read_text())
image_ids = [i for split in sp... |
class TestSplitConverter(AITTestCase):
([[[2, 10], [2, 3, 5]], [[2, 10], 2], [[2, 10], 3]])
def test_with_dim(self, input_shape: List[int], split_size_or_sections: Union[(int, List[int])]) -> None:
class TestModule(torch.nn.Module):
def forward(self, x: torch.Tensor) -> torch.Tensor:
... |
(return_object=_return_object_docstring, return_boundaries=_return_boundaries_docstring, precision=_precision_docstring, binner_dict_=_binner_dict_docstring, fit=_fit_discretiser_docstring, transform=_transform_discretiser_docstring, variables=_variables_numerical_docstring, variables_=_variables_attribute_docstring, f... |
def check_sequential(speed_model):
timing_keywords = {'setup': 'setup', 'remov': 'removal', 'hold': 'hold', 'recov': 'recovery', 'removal': 'removal', 'recovery': 'recovery'}
tmp = speed_model.split('_')
for keyword in sorted(timing_keywords):
if (keyword in tmp):
return [keyword, timing... |
class OptionSeriesFunnel3dData(Options):
def accessibility(self) -> 'OptionSeriesFunnel3dDataAccessibility':
return self._config_sub_data('accessibility', OptionSeriesFunnel3dDataAccessibility)
def borderColor(self):
return self._config_get(None)
def borderColor(self, text: str):
sel... |
def _get_files_as_regularsurfaces_thread(option=1):
surfs = []
with concurrent.futures.ThreadPoolExecutor(max_workers=NTHREAD) as executor:
if (option == 1):
futures = {executor.submit(_get_regsurff, i): i for i in range(NTHREAD)}
else:
futures = {executor.submit(_get_reg... |
def run_task(task, partial_config, logging_handler):
loggers = ['roamer']
for logger_name in loggers:
logger = logging.getLogger(logger_name)
logger.addHandler(logging_handler)
loaded_base_config = importlib.import_module(task['config'])
config = appy_partial_on_base_config(loaded_base_c... |
class RunLogger(ErsiliaBase):
def __init__(self, model_id, config_json):
ErsiliaBase.__init__(self, config_json=config_json, credentials_json=None)
self.model_id = model_id
self.ersilia_runs_folder = os.path.join(EOS, ERSILIA_RUNS_FOLDER)
if (not os.path.exists(self.ersilia_runs_fold... |
.slow
.skipif((not GPU_TESTS_ENABLED), reason='requires GPU')
def test_generate_sample(falcon_generator):
prompts = ['What is spaCy?', 'What is spaCy?']
torch.manual_seed(0)
assert (falcon_generator(prompts, config=SampleGeneratorConfig(top_k=10)) == ["spaCy is a Python package for natural language processi... |
def extractSteadierTranslations(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag,... |
def test_grid_from_file_warns(tmp_path, any_grid):
if (version.parse(xtgeo_version) < version.parse('2.16')):
pytest.skip()
any_grid.to_file((tmp_path / 'grid.roff'), fformat='roff')
with pytest.warns(DeprecationWarning, match='from_file is deprecated'):
any_grid.from_file((tmp_path / 'grid.... |
def get_drug_shortage_map(medication_orders, warehouse):
drug_requirement = dict()
for d in medication_orders:
if (not drug_requirement.get(d.drug_code)):
drug_requirement[d.drug_code] = 0
drug_requirement[d.drug_code] += flt(d.dosage)
drug_shortage = dict()
for (drug, requir... |
class CRUDUser(CRUDBase[(User, RegisterUser, UpdateUser)]):
async def get(self, db: AsyncSession, user_id: int) -> (User | None):
return (await self.get_(db, pk=user_id))
async def get_by_username(self, db: AsyncSession, username: str) -> (User | None):
user = (await db.execute(select(self.model... |
class TestFormatter(unittest.TestCase):
def test_get_format(self) -> None:
f = Formatter.get_format('123/ddd/ddd{{sdd}}/444')
self.assertEqual('123/ddd', f[0])
self.assertEqual('ddd{{sdd}}/444', f[1])
f = Formatter.get_format('123/ddd/ddd{sdd}}/444')
self.assertEqual('123/ddd... |
def test_union_records():
schema = {'name': 'test_name', 'namespace': 'test', 'type': 'record', 'fields': [{'name': 'val', 'type': [{'name': 'a', 'namespace': 'common', 'type': 'record', 'fields': [{'name': 'x', 'type': 'int'}, {'name': 'y', 'type': 'int'}]}, {'name': 'b', 'namespace': 'common', 'type': 'record', '... |
def example():
return ft.Card(content=ft.Container(content=ft.Column([ft.ListTile(leading=ft.Icon(ft.icons.ALBUM), title=ft.Text('The Enchanted Nightingale'), subtitle=ft.Text('Music by Julie Gable. Lyrics by Sidney Stein.')), ft.Row([ft.TextButton('Buy tickets'), ft.TextButton('Listen')], alignment=ft.MainAxisAlig... |
class TestCcrStatsRecorder():
java_signed_maxlong = ((2 ** 63) - 1)
def test_raises_exception_on_transport_error(self):
client = Client(transport_client=TransportClient(response={}, force_error=True))
cfg = create_config()
metrics_store = metrics.EsMetricsStore(cfg)
with pytest.r... |
def test_factorise_4():
c = factorise([{'date': ['1990-01-01/1990-01-02'], 'param': ['Z', 'T']}, {'date': ['1990-01-02/1990-01-05'], 'param': ['Z']}, {'date': ['1990-01-04/1990-01-15'], 'param': ['Z', 'T']}], intervals=['date'])
assert (_(c.to_list()) == _([{'date': ['1990-01-01/1990-01-15'], 'param': ['Z']}, {... |
class TpoolConnectionPool(DBConnectionPool):
__test__ = False
def create_pool(self, min_size=0, max_size=1, max_idle=10, max_age=10, connect_timeout=0.5, module=None):
if (module is None):
module = self._dbmodule
return db_pool.TpooledConnectionPool(module, min_size=min_size, max_siz... |
.django_db
def test_category_naics_awards(naics_test_data, monkeypatch, elasticsearch_transaction_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
test_payload = {'category': 'naics', 'subawards': False, 'page': 1, 'limit': 50}
spending_by_category_logic = NAICSViewSet().perfor... |
class OptionSeriesItemSonificationContexttracksMappingTremolo(Options):
def depth(self) -> 'OptionSeriesItemSonificationContexttracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesItemSonificationContexttracksMappingTremoloDepth)
def speed(self) -> 'OptionSeriesItemSonificationC... |
class BasicDialoguesStorage():
def __init__(self, dialogues: 'Dialogues') -> None:
self._dialogues_by_dialogue_label = {}
self._dialogue_by_address = defaultdict(list)
self._incomplete_to_complete_dialogue_labels = {}
self._dialogues = dialogues
self._terminal_state_dialogues... |
class A7RPCPHY(BasePHY):
def __init__(self, iodelay_clk_freq, **kwargs):
self._rdly_dq_rst = CSR()
self._rdly_dq_inc = CSR()
self._db_enabled = CSRStorage(reset=1)
self._dqs_enabled = CSRStorage(reset=1)
kwargs.update(dict(write_ser_latency=1, read_des_latency=2, phytype=self... |
def report_type_full(report_type, form_type, report_type_full_original):
if ((form_type in ('F5', 'F24')) and (report_type in ('24', '48'))):
return (report_type + '-HOUR REPORT OF INDEPENDENT EXPENDITURES')
elif (form_type == 'F6'):
return '48-HOUR NOTICE OF CONTRIBUTIONS OR LOANS RECEIVED'
... |
def extractBorahae7TumblrCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ((vol, chp, frag) == (None, 100, 0)):
return None
tagmap = [('fbcbtr tl', 'Fiancee Be Chosen By ... |
class TBEArmor(DefaultObject):
def at_object_creation(self):
self.db.damage_reduction = 4
self.db.defense_modifier = (- 4)
def at_pre_drop(self, dropper):
if self.rules.is_in_combat(dropper):
dropper.msg("You can't doff armor in a fight!")
return False
ret... |
class MaintenanceModeMiddleware():
def __init__(self, get_response=None):
self.get_response = get_response
def __call__(self, request):
response = self.process_request(request)
if ((response is None) and callable(self.get_response)):
response = self.get_response(request)
... |
_cache()
def get_solidity_grammar_instance(solidity_version=None):
if isinstance(solidity_version, str):
solidity_version = Version(solidity_version)
version_map = {Version('0.5.0'): (solidity_v_0_5_x, Parser), Version('0.6.0'): (solidity_v_0_5_x, Parser)}
grammar_and_parser = None
for version i... |
def HumanIKTargetDoKill(kwargs: dict) -> OutgoingMessage:
compulsory_params = ['id', 'index']
optional_params = []
utility.CheckKwargs(kwargs, compulsory_params)
msg = OutgoingMessage()
msg.write_int32(kwargs['id'])
msg.write_string('HumanIKTargetDoKill')
msg.write_int32(kwargs['index'])
... |
def get_layout(**kwargs):
athlete_info = app.session.query(athlete).filter((athlete.athlete_id == 1)).first()
use_power = (True if (athlete_info.use_run_power or athlete_info.use_cycle_power) else False)
app.session.remove()
if (not use_power):
return html.H1('Power data currently disabled', cla... |
(scope='session', autouse=True)
def testing_environment(test_certificates: Tuple[(str, str)], find_free_port: Callable) -> None:
location = pathlib.Path(tempfile.gettempdir())
rand_str = ''.join(random.choices((string.ascii_letters + string.digits), k=6))
db_path = (location / f'feedernet.{rand_str}.db')
... |
class Faucet8021XCustomACLLoginTest(Faucet8021XBase):
CONFIG_GLOBAL = '\nvlans:\n 100:\n description: "untagged"\nacls:\n auth_acl:\n - rule:\n dl_type: 0x800 # Allow ICMP / IPv4\n ip_proto: 1\n actions:\n allow: True\n - rule:\n ... |
def debug_response(response):
def success_echo(fmt, *args):
prompt = click.style('< ', fg='green')
click.echo((prompt + expand_args(fmt, args)))
def failure_echo(fmt, *args):
prompt = click.style('< ', fg='red')
click.echo((prompt + expand_args(fmt, args)))
def info_echo(fmt,... |
.xfail(reason='OPM flaky')
.requires_opm
.usefixtures('setup_tmpdir')
(max_examples=5)
(opm_setups)
def test_restart_prop_reading(case):
case.run()
fformat = ('funrst' if case.formatted else 'unrst')
pressure = xtgeo.gridproperty_from_file(case.restart_file, fformat=fformat, name='PRESSURE', date='last', gr... |
def fetch_production_capacity_for_all_zones(target_datetime: datetime, session: Session) -> dict[(str, Any)]:
df_capacity = get_data_from_url(session)
df_capacity = format_ember_data(df_capacity, target_datetime.year)
all_capacity = get_capacity_dict_from_df(df_capacity)
logger.info(f'Fetched capacity d... |
class _BaseScipyGridder(BaseGridder):
def _get_interpolator(self):
def fit(self, coordinates, data, weights=None):
if (weights is not None):
warn('{} does not support weights and they will be ignored.'.format(self.__class__.__name__))
(coordinates, data, weights) = check_fit_input(co... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'name'
fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path':... |
class THBattleFaith(THBattle):
n_persons = 6
game_ehs = [DeathHandler]
bootstrap = THBattleFaithBootstrap
params_def = {'random_seat': (True, False)}
forces: Dict[(THBFaithRole, BatchList[Player])]
pool: Dict[(THBFaithRole, List[CharChoice])]
def can_leave(g: THBattleFaith, p: Any):
... |
class LyricsMethodsComboBox(Gtk.ComboBoxText, providers.ProviderHandler):
def __init__(self):
Gtk.ComboBoxText.__init__(self)
providers.ProviderHandler.__init__(self, 'lyrics')
self.model = self.get_model()
self.append_text(_('Any source'))
for provider in self.get_providers(... |
def notify_ticket_cancel(order, actor):
buyer = order.user
content = NotificationContent(type=NotificationType.TICKET_CANCELLED, target=order, actors=[NotificationActor(actor=actor)])
send_notification(content, buyer)
users = order.event.notify_staff
content = NotificationContent(type=NotificationTy... |
def extractLfnovelsCom(item):
if (not ('English' in item['tags'])):
return None
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Dungeon Hallow', 'Dungeon Hallow', 'transla... |
class ZigguratSignInProvider(object):
def __init__(self, *args, **kwargs):
for (k, v) in kwargs.items():
setattr(self, k, v)
def sign_in(self, request):
came_from = request.params.get(self.signin_came_from_key, '/')
db_session = self.session_getter(request)
user = Use... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.