code stringlengths 281 23.7M |
|---|
class ImageFormat(Entity):
__auto_name__ = False
__tablename__ = 'ImageFormats'
__mapper_args__ = {'polymorphic_identity': 'ImageFormat'}
imageFormat_id = Column('id', Integer, ForeignKey('Entities.id'), primary_key=True)
width = Column(Integer, doc='The width of this format.\n\n * the width ... |
.parametrize('empty', ([], (), None), ids=['empty-list', 'empty-tuple', 'None'])
def test_empty_mungers_for_property_with_input_parameters_raises_ValidationError(empty):
method = Method(is_property=True, mungers=empty, json_rpc_method='eth_method')
with pytest.raises(ValidationError, match='Parameters cannot be... |
def getRPIVer():
detarr = []
try:
with open('/proc/cpuinfo') as f:
for line in f:
line = line.strip()
if line.startswith('Revision'):
detarr = line.split(':')
break
except:
pass
hwarr = {'name': 'Unknown ... |
def test_populate_response():
view = instantiate_view_for_tests()
expected_dictionary = {'limit': 5, 'results': ['item 1', 'item 2'], 'page_metadata': {'page': 1, 'hasNext': True}, 'messages': [get_time_period_message()]}
assert (view.populate_response(results=['item 1', 'item 2'], has_next=True) == expecte... |
class DatabaseContext():
MEMORY_PATH = ':memory:'
JOURNAL_MODE = JournalModes.WAL
SQLITE_CONN_POOL_SIZE = 0
def __init__(self, wallet_path: str) -> None:
if ((not self.is_special_path(wallet_path)) and (not wallet_path.endswith(DATABASE_EXT))):
wallet_path += DATABASE_EXT
sel... |
def find_and_replace(path, pattern, replace):
with open(path, 'r') as f:
old_data = f.read()
if (re.search(pattern, old_data, flags=re.MULTILINE) is None):
print(f"Didn't find the pattern {pattern!r} in {path!s}")
exit(1)
new_data = re.sub(pattern, replace, old_data, flags=re.MULTILI... |
class ExtendedNodeStorageSerializer(NodeStorageSerializer):
size_vms = s.IntegerField(read_only=True)
size_snapshots = s.IntegerField(read_only=True)
size_rep_snapshots = s.IntegerField(read_only=True)
size_backups = s.IntegerField(read_only=True)
snapshots = s.IntegerField(read_only=True, source='s... |
def plot_error_bias_colored_scatter(curr_scatter_data: RegressionScatter, ref_scatter_data: Optional[RegressionScatter], color_options: ColorOptions):
cols = 1
subplot_titles: Union[(list, str)] = ''
if (ref_scatter_data is not None):
cols = 2
subplot_titles = ['current', 'reference']
fi... |
def test_async_task(test_client_factory):
TASK_COMPLETE = False
async def async_task():
nonlocal TASK_COMPLETE
TASK_COMPLETE = True
task = BackgroundTask(async_task)
async def app(scope, receive, send):
response = Response('task initiated', media_type='text/plain', background=tas... |
def test_alpha_int8():
assert (Color('rgba(0, 0, 0, 1)').alpha_int8 == 255)
assert (Color('rgba(0, 0, 0, 0)').alpha_int8 == 0)
if (not (Color('rgb(127,0,0)').red_quantum <= Color('rgba(0,0,0,0.5').alpha_quantum <= Color('rgb(128,0,0)').red_quantum)):
return
assert (127 <= Color('rgba(0, 0, 0, 0.... |
def test_dao_update(dao, default_entity_dict):
req = ServeRequest(**default_entity_dict)
res: ServerResponse = dao.create(req)
res: ServerResponse = dao.update({'prompt_name': 'my_prompt_1', 'sys_code': 'dbgpt'}, ServeRequest(prompt_name='my_prompt_2'))
assert (res is not None)
assert (res.id == 1)
... |
class PopupRelativeLayout(_PopupLayout):
def _place_control(self, control):
def is_relative(val):
return (0 <= val <= 1)
if (not control.placed):
if (not all([is_relative(x) for x in [control.pos_x, control.pos_y, control.width, control.height]])):
logger.warn... |
def test_option_env_variable_interpolation(config, yaml_config_file_3):
config.option.from_yaml(yaml_config_file_3)
assert (config.option() == {'section1': {'value1': 'test-value', 'value2': 'test-path/path'}})
assert (config.option.section1() == {'value1': 'test-value', 'value2': 'test-path/path'})
ass... |
_type(ofproto.OFPTFPT_WRITE_ACTIONS)
_type(ofproto.OFPTFPT_WRITE_ACTIONS_MISS)
_type(ofproto.OFPTFPT_APPLY_ACTIONS)
_type(ofproto.OFPTFPT_APPLY_ACTIONS_MISS)
class OFPTableFeaturePropActions(OFPTableFeatureProp):
def __init__(self, type_=None, length=None, action_ids=None):
action_ids = (action_ids if actio... |
class EVENT_TRACE_HEADER(ct.Structure):
_fields_ = [('Size', ct.c_ushort), ('HeaderType', ct.c_ubyte), ('MarkerFlags', ct.c_ubyte), ('Class', EVENT_TRACE_HEADER_CLASS), ('ThreadId', ct.c_ulong), ('ProcessId', ct.c_ulong), ('TimeStamp', wt.LARGE_INTEGER), ('Guid', GUID), ('ClientContext', ct.c_ulong), ('Flags', ct.c... |
def decrypt_combined_nonce_and_message(encrypted_value: str, key: bytes) -> str:
verify_encryption_key(key)
gcm = AESGCM(key)
encrypted_combined: bytes = base64.b64decode(encrypted_value)
nonce: bytes = encrypted_combined[0:CONFIG.security.aes_gcm_nonce_length]
encrypted_message: bytes = encrypted_c... |
def test_slash_after_logout_before_logout_delay(casper, concise_casper, funded_account, validation_key, deposit_amount, induct_validator, send_vote, mk_suggested_vote, mk_slash_votes, new_epoch, fake_hash, logout_validator_via_signed_msg):
validator_index = induct_validator(funded_account, validation_key, deposit_a... |
class Environment():
def __init__(self, white: VectorLike, adapting_luminance: float, surround: float, discounting: float) -> None:
self.xyz_w = util.xy_to_xyz(white)
self.surround = surround
self.yn = adapting_luminance
self.d = discounting
self.ram = self.calc_ram()
... |
class BackupProcess(FledgeProcess):
_MODULE_NAME = 'fledge_backup_postgres_process'
_BACKUP_FILE_NAME_PREFIX = 'fledge_backup_'
_MESSAGES_LIST = {'i000001': 'Execution started.', 'i000002': 'Execution completed.', 'e000000': 'general error', 'e000001': 'cannot initialize the logger - error details |{0}|', '... |
def find_muscle(name, muscles):
results = []
for (key, muscle) in muscles.items():
if (key in name):
return muscle
for (key, muscle) in muscles.items():
matcher = SequenceMatcher(None, key, name)
ratio = matcher.ratio()
if (ratio >= 0.75):
results.appe... |
('/monitor-target')
def monitor_target_drift(window_size: int=3000) -> FileResponse:
logging.info('Read current data')
current_data: pd.DataFrame = load_current_data(window_size)
logging.info('Read reference data')
reference_data = load_reference_data(columns=DATA_COLUMNS['columns'])
logging.info('B... |
class CalendarScaleSystemTestCase(TicksTestCase):
def test_hourly_scales(self):
scales = (([TimeScale(seconds=dt) for dt in (1, 5, 15, 30)] + [TimeScale(minutes=dt) for dt in (1, 5, 15, 30)]) + [TimeScale(hours=dt) for dt in (1, 2, 3, 4, 6, 12)])
def test_yearly_scales(self):
ticker = ScaleSyste... |
def find_matching_fn_abi(abi: ABI, abi_codec: ABICodec, fn_identifier: Optional[Union[(str, Type[FallbackFn], Type[ReceiveFn])]]=None, args: Optional[Sequence[Any]]=None, kwargs: Optional[Any]=None) -> ABIFunction:
args = (args or tuple())
kwargs = (kwargs or dict())
num_arguments = (len(args) + len(kwargs)... |
class AgentManager():
_instance = None
def get_instance(cls) -> 'AgentManager':
if (cls._instance is None):
cls._instance = AgentManager()
return cls._instance
def __init__(self) -> None:
self.agent_templete_env: PackageEnv = None
self.agent_env: PackageEnv = None... |
def test_class_variables(additionals):
assert (additionals.mod.name == 'empty')
assert (additionals.mod.disk.base_dir == Path(additionals.BASE_DIR))
assert (additionals.mod._MTModule__LOGS == [])
assert (additionals.mod.disk._LocalStorage__LOGS_DIR == f'{additionals.BASE_DIR}/logs')
assert (addition... |
class OptionSeriesSunburstSonificationContexttracksMappingLowpassResonance(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... |
.django_db
def test_psc_autocomplete_success(client, psc_data):
resp = client.post('/api/v2/autocomplete/psc/', content_type='application/json', data=json.dumps({'search_text': '8435'}))
assert (resp.status_code == status.HTTP_200_OK)
assert (len(resp.data['results']) == 1)
assert (resp.data['results'][... |
class OptionPlotoptionsScatterSonificationContexttracksMappingFrequency(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_geo_group_sim():
geo_grp = td.TriangleMesh.from_stl('tests/data/two_boxes_separate.stl')
geos_orig = list(geo_grp.geometries)
geo_grp_full = geo_grp.updated_copy(geometries=(geos_orig + [td.Box(size=(1, 1, 1))]))
sim = td.Simulation(size=(10, 10, 10), grid_spec=td.GridSpec.uniform(dl=0.1), sour... |
def show_plotcuts(cuts, buttons=False, extraText=None):
if (plt is None):
print('Install matplotlib for python to allow graphical display of cuts', file=sys.stderr)
return 2
if (cuts == []):
print('Empty cut path', file=sys.stderr)
return 3
xy = sum(cuts, [])
least = min(... |
class OptionSeriesColumnpyramidSonificationContexttracksMappingPlaydelay(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 Cell_Reference(Name):
def __init__(self, n_ident):
super().__init__()
assert isinstance(n_ident, Name)
self.n_ident = n_ident
self.n_ident.set_parent(self)
self.l_args = []
def loc(self):
return self.n_ident.loc()
def add_argument(self, n_arg):
a... |
class ChefArray(Processor):
description = 'Produces an array that can be used with other Chef blocks. See
input_variables = {'item_list': {'description': 'Array of items to be put into the array block. This can also be a single string.', 'required': True}, 'no_wrap_quotes': {'description': 'Do not add wrappin... |
def set_webprofileusername(username):
try:
url = (config.host + '/profile/username')
r = requests.put(url, headers=headers, data=json.dumps({'username': username}))
return r.json()
except requests.exceptions.RequestException as e:
print('Something went wrong. Could not set webpro... |
def periodise(m):
element = BrokenElement(FiniteElement('CG', cell=m.ufl_cell(), degree=1))
coord_fs = VectorFunctionSpace(m, element, dim=2)
old_coordinates = m.coordinates
new_coordinates = Function(coord_fs)
domain = '{[i, j]: 0 <= i < old_coords.dofs and 0 <= j < new_coords.dofs}'
instructio... |
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':... |
('int (*git_transport_certificate_check_cb)(git_cert *cert, int valid, const char *host, void *payload)')
def _certificate_cb(cert_i, valid, host, data):
d = ffi.from_handle(data)
try:
val = d['certificate_cb'](None, bool(valid), ffi.string(host))
if (not val):
return C.GIT_ECERTIFIC... |
def stream(audio_stream: Iterator[bytes]) -> bytes:
if (not is_installed('mpv')):
message = "mpv not found, necessary to stream audio. On mac you can install it with 'brew install mpv'. On linux and windows you can install it from
raise ValueError(message)
mpv_command = ['mpv', '--no-cache', '-... |
class SDXLSAGAdapter(SAGAdapter[SDXLUNet]):
def __init__(self, target: SDXLUNet, scale: float=1.0, kernel_size: int=9, sigma: float=1.0) -> None:
super().__init__(target=target, scale=scale, kernel_size=kernel_size, sigma=sigma)
def inject(self: 'SDXLSAGAdapter', parent: (fl.Chain | None)=None) -> 'SDXL... |
class DEOK(DE76):
NAME = 'ok'
SPACE = 'oklab'
def __init__(self, scalar: float=1) -> None:
self.scalar = scalar
def distance(self, color: 'Color', sample: 'Color', scalar: Optional[float]=None, **kwargs: Any) -> float:
if (scalar is None):
scalar = self.scalar
return ... |
class OptionPlotoptionsWordcloudSonificationTracksPointgrouping(Options):
def algorithm(self):
return self._config_get('minmax')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
... |
def compute_max_saturation(a: float, b: float) -> float:
if ((((- 1.) * a) - (0. * b)) > 1):
k0 = 1.
k1 = 1.
k2 = 0.
k3 = 0.
k4 = 0.
wl = 4.
wm = (- 3.)
ws = 0.
elif (((1. * a) - (1. * b)) > 1):
k0 = 0.
k1 = (- 0.)
k2 = 0.
... |
def get_facet_closure_nodes(mesh, key, V):
(_, sub_domain) = key
if (sub_domain not in {'on_boundary', 'top', 'bottom'}):
valid = set(mesh.interior_facets.unique_markers)
valid |= set(mesh.exterior_facets.unique_markers)
invalid = (set(sub_domain) - valid)
if invalid:
... |
class OptionPlotoptionsCylinderSonificationDefaultinstrumentoptionsMappingHighpassResonance(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 mapT... |
def test_nistems():
mp4exc = stempeg.cmds.find_cmd('MP4Box')
(stems, rate) = stempeg.read_stems(stempeg.example_stem_path())
with tmp.NamedTemporaryFile(delete=False, suffix='.m4a') as tempfile:
stempeg.write_stems(tempfile.name, stems, sample_rate=rate, writer=stempeg.NIStemsWriter())
callA... |
def test_finds_correct_dominator():
cfg = ControlFlowGraph()
cfg.add_nodes_from([(head := BasicBlock(0, instructions=[Branch(Condition(OperationType.greater, [Variable('a', ssa_label=0), Constant(0, Integer.int32_t())]))])), (branch_body := BasicBlock(1, instructions=[Assignment(Variable('a', ssa_label=1), Unar... |
class TestArchChecker(unittest.TestCase):
maxDiff = None
def __init__(self, *args, **kwargs):
logSetup.initLogging()
super().__init__(*args, **kwargs)
self.maxDiff = None
def setUp(self):
self.addCleanup(self.dropDatabase)
self.db = Tests.basePhashTestSetup.TestDb()
... |
def make_app():
ctx = click.get_current_context(silent=True)
script_info = None
if (ctx is not None):
script_info = ctx.obj
config_file = getattr(script_info, 'config_file', None)
instance_path = getattr(script_info, 'instance_path', None)
return create_app(config_file, instance_path) |
class BlackJackTest(unittest.TestCase):
.task(taskno=1)
def test_value_of_card(self):
test_data = [('2', 2), ('5', 5), ('8', 8), ('A', 1), ('10', 10), ('J', 10), ('Q', 10), ('K', 10)]
for (variant, (card, expected)) in enumerate(test_data, 1):
with self.subTest(f'variation #{variant}... |
class UnionParamType(click.ParamType):
def __init__(self, types: typing.List[click.ParamType]):
super().__init__()
self._types = self._sort_precedence(types)
def _sort_precedence(tp: typing.List[click.ParamType]) -> typing.List[click.ParamType]:
unprocessed = []
str_types = []
... |
def decorate_name(name, dual_porosity, fracture, date=None):
decorated_name = name
if dual_porosity:
if fracture:
decorated_name += 'F'
else:
decorated_name += 'M'
if (date is not None):
decorated_name += ('_' + str(date))
return decorated_name |
def test_unicode_inside_ascii_range():
resp = falcon.Response()
resp.set_cookie('non_unicode_ascii_name_1', 'ascii_value')
resp.set_cookie('unicode_ascii_name_1', 'ascii_value')
resp.set_cookie('non_unicode_ascii_name_2', 'unicode_ascii_value')
resp.set_cookie('unicode_ascii_name_2', 'unicode_ascii_... |
def make_gridprop_values(values, grid, fracture):
num_cells = np.prod(grid.dimensions)
if np.isscalar(values):
values = expand_scalar_values(values, num_cells, grid.dualporo)
if grid.dualporo:
actind = grid.get_dualactnum_indices(fracture=fracture, order='F')
values = pick_dualporo_v... |
class String(Atom, Seq):
def __init__(self, str):
Atom.__init__(self, str)
def __repr__(self):
return repr(self.data)
def eval(self, env, args=None):
return self
def cons(self, e):
if ((e.__class__ != self.__class__) and (e.__class__ != Symbol.__class__)):
rai... |
class RebuildAllPackagesFormFactory(object):
def __new__(cls, active_chroots, package_names):
form_cls = _get_build_form(active_chroots, BaseForm)
form_cls.packages = MultiCheckboxField('Packages', choices=[(name, name) for name in package_names], default=package_names, validators=[wtforms.validator... |
def export_single_model(model, arch_config, save_path, logger):
if (arch_config['algorithm'] == 'SRN'):
max_text_length = arch_config['Head']['max_text_length']
other_shape = [paddle.static.InputSpec(shape=[None, 1, 64, 256], dtype='float32'), [paddle.static.InputSpec(shape=[None, 256, 1], dtype='in... |
class Listable():
def __init__(self, list_result, get_results=None, archive_result=None):
self.list_result = list_result
self.get_results = get_results
self.archive_result = archive_result
def list(self, as_list=False, archived=None, top_level_only=False):
if (archived is None):
... |
def setup(logger_name: str=None, destination: int=None, level: int=None, propagate: bool=False) -> logging.Logger:
logger = logging.getLogger(logger_name)
if (destination is None):
destination = default_destination
if (destination == SYSLOG):
handler = SysLogHandler(address='/dev/log')
e... |
class OptionPlotoptionsSplineSonificationContexttracksMapping(Options):
def frequency(self) -> 'OptionPlotoptionsSplineSonificationContexttracksMappingFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsSplineSonificationContexttracksMappingFrequency)
def gapBetweenNotes(self) -> 'Opt... |
class KrxHistoricalDailyPriceDataDownloader():
def __init__(self):
self._headers = {'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9,ko;q=0.8,fr;q=0.7,ja;q=0.6,zh-CN;q=0.5,zh;q=0.4', 'Host': 'data.krx.co.kr', 'Origin': ' 'Refe... |
class Bot(object):
def __init__(self, cache_path=None, console_qr=False, qr_path=None, qr_callback=None, login_callback=None, logout_callback=None, user_agent=None, start_immediately=True):
self.core = itchat.Core(user_agent)
self.user_agent = self.core.user_agent
itchat.instanceList.append(... |
class TestSdmCommonParser(unittest.TestCase):
parser = SdmCommonParser(parent=None)
def test_sdm_common_basic_info(self):
self.parser.icd_ver = (4, 54)
payload = binascii.unhexlify('cac6d')
packet = sdmcmd.generate_sdm_packet(160, sdmcmd.sdm_command_group.CMD_COMMON_DATA, sdmcmd.sdm_comm... |
class BCycle(Gbfs):
meta = {'system': 'BCycle', 'company': ['BCycle, LLC']}
def __init__(self, tag, meta, uid, bbox=None):
if ('company' in meta):
meta['company'] += BCycle.meta['company']
feed_url = FEED_URL.format(uid=uid)
super(BCycle, self).__init__(tag, meta, feed_url, b... |
def import_symbol(symbol_path):
if (':' in symbol_path):
(module_name, symbol_name) = symbol_path.split(':')
module = import_module(module_name)
symbol = xgetattr(module, symbol_name)
else:
components = symbol_path.split('.')
module_name = '.'.join(components[:(- 1)])
... |
.integration
class TestUser():
def test_user_login_provide_credentials(self, test_config_path: str, test_cli_runner: CliRunner, credentials_path: str) -> None:
print(credentials_path)
result = test_cli_runner.invoke(cli, ['-f', test_config_path, 'user', 'login', '-u', 'root_user', '-p', 'Testpasswor... |
def randu(bound=(0, 10), shape=(5, 5), missingness='mcar', thr=0.2, dtype='int'):
if (dtype == 'int'):
data = np.random.randint(bound[0], bound[1], size=shape).astype(float)
elif (dtype == 'float'):
data = np.random.uniform(bound[0], bound[1], size=shape)
corruptor = Corruptor(data, thr=thr)... |
def interpret_token(val: str) -> list[str]:
if ((val[0] == "'") and (val[(- 1)] == "'")):
return [val[1:(- 1)]]
if val[0].isalpha():
return [val]
if ('*' in val):
(multiplicand, value) = val.split('*')
return (interpret_token(value) * int(multiplicand))
return [val] |
class _CSP():
def from_prog_name(cls, prog_name):
csp = Path(prog_name).name.replace('run', '')
if (csp not in ['aws', 'azure']):
raise Exception(f'unknown variant: {csp}')
return cls(csp)
def __init__(self, name):
self.name = name
def config_filename(self):
... |
class ReadEnv():
def __init__(self):
pass
def read_env(self):
try:
GlobalAttrs.env_prometheus_server = os.environ['KPTOP_PROMETHEUS_SERVER']
except KeyError as e:
raise SystemExit(f'''
ERROR -- ENV not found => {e}''')
try:
if os.environ['KPTOP... |
class Integer(object):
def __init__(self, maximum, increment=256):
self._maximum = maximum
if (increment >= maximum):
increment = maximum
self._increment = increment
self._threshold = (increment // 2)
e = random.randrange((self._maximum - self._increment))
... |
def test_inputs_outputs_length():
def many_inputs(a: int, b: str, c: float) -> str:
return f'{a} - {b} - {c}'
m = array_node_map_task(many_inputs)
assert (m.python_interface.inputs == {'a': List[int], 'b': List[str], 'c': List[float]})
assert (m.name == 'tests.flytekit.unit.core.test_array_node_... |
(name='testwells')
def fixture_testwells(testpath):
w_names = ['WELL29', 'WELL14', 'WELL30', 'WELL27', 'WELL23', 'WELL32', 'WELL22', 'WELL35', 'WELLX']
well_files = [join(testpath, 'wells', 'battle', '1', (wn + '.rmswell')) for wn in w_names]
return xtgeo.wells_from_files(well_files, fformat='rms_ascii') |
class ReadBed(object):
def __init__(self, file_handle):
self.file_type = None
self.file_handle = file_handle
self.line_number = 0
fields = self.get_no_comment_line()
fields = toString(fields)
fields = fields.split('\t')
self.guess_file_type(fields)
sel... |
def CreateGemmRRRPermOperator(manifest, c_element_op):
operation_kind = library.GemmKind.GemmPermute
a_element_desc = library.TensorDesc(library.DataType.f16, library.LayoutType.RowMajor)
b_element_desc = library.TensorDesc(library.DataType.f16, library.LayoutType.RowMajor)
c_element_desc = library.Tens... |
_required
def account():
emails = {'verified': (e.address for e in current_user.emails.order_by(Email.registered_on.desc())), 'pending': filter(bool, request.cookies.get('pending-emails', '').split(','))}
sub = None
cards = {}
if current_user.stripe_id:
try:
customer = stripe.Custome... |
class OSCIGeneralRankingSchema():
position = OSCIChangeRankingSchema.position
__ytd = 'YTD'
__dtd = 'DTD'
__mtd = 'MTD'
change_suffix = 'Change'
position_change = f'{OSCIChangeRankingSchema.position_change}'
position_change_ytd = f'{position_change}_{__ytd}'
position_change_dtd = f'{posi... |
def test_redis5_master_failed_sentinel_failover(pysoa_client: Client) -> None:
context = _new_context()
thread = threading.Thread(target=_work, name='test_redis5_planned_demotion', args=(pysoa_client, 'meta', context))
thread.start()
try:
while (len(context['results_before_failover']) < 50):
... |
class OptionSeriesColumnSonificationTracksMappingTremoloSpeed(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):
se... |
('/rules1.txt')
def handle_rules1(self):
if rpieGlobals.wifiSetup:
return self.redirect('/setup')
if (not isLoggedIn(self.get, self.cookie)):
return self.redirect('/login')
if (self.type == 'GET'):
responsearr = self.get
else:
responsearr = self.post
fname = 'files/ru... |
def split_star_expr_tokens(tokens, is_dict=False):
groups = [[]]
has_star = False
has_comma = False
for tok_grp in tokens:
if (tok_grp == ','):
has_comma = True
elif (len(tok_grp) == 1):
internal_assert((not is_dict), 'found non-star non-pair item in dict literal'... |
class TwoColumns(Layout):
def __init__(self, workspace_name: str, params: List[Any]):
super().__init__(LayoutName.TWO_COLUMNS, workspace_name)
try:
self.first_column_position = (HorizontalPosition(params[0]) if (len(params) > 0) else HorizontalPosition.LEFT)
except ValueError:
... |
def export_matlib_to_file(fname: str='matlib.json') -> None:
mat_lib_dict = {f'{mat.name} ("{mat_name}")': {var_name: json.loads(var.medium._json_string) for (var_name, var) in mat.variants.items()} for (mat_name, mat) in material_library.items() if (not isinstance(mat, type))}
with open(fname, 'w') as f:
... |
class SemanticReferenceListTeiElementFactory(SingleElementTeiElementFactory):
def get_tei_element_for_semantic_content(self, semantic_content: SemanticContentWrapper, context: TeiElementFactoryContext) -> etree.ElementBase:
LOGGER.debug('semantic_content: %s', semantic_content)
assert isinstance(sem... |
class GlobalFFTKernel():
def __init__(self, dtype, device_params, outer_shape, fft_size, curr_size, fft_size_real, inner_shape, pass_num, reverse_direction):
num_passes = len(get_global_radix_info(fft_size)[0])
real_output_shape = ((pass_num == (num_passes - 1)) and reverse_direction)
self.n... |
class LGBMClassifierTransformer(LGBMForestTransformer):
def __init__(self, model: LGBMClassifier, feature_names: List[str], classification_labels: List[str], classification_weights: List[float]):
super().__init__(model.booster_, feature_names, classification_labels, classification_weights)
self.n_es... |
def _optimal_param(threshold, num_perm, max_r, xq, false_positive_weight, false_negative_weight):
min_error = float('inf')
opt = (0, 0)
for b in range(1, (num_perm + 1)):
for r in range(1, (max_r + 1)):
if ((b * r) > num_perm):
continue
fp = _false_positive_pr... |
_metaclass(abc.ABCMeta)
class Activity(object):
def __init__(self, name=None):
self._name = name
if (self._name is None):
self._name = ('UnknownActivity: ' + str(time.time()))
self._child_thread_map = weakref.WeakValueDictionary()
self._child_activity_map = weakref.WeakVa... |
def _test_correct_response_of_loans(client):
resp = post(client, award_type_codes=list(loan_type_mapping.keys()), def_codes=['L', 'M'], geo_layer='county', geo_layer_filters=['45001', '45005'], spending_type='obligation')
expected_response = {'geo_layer': 'county', 'scope': 'recipient_location', 'spending_type'... |
def crop_frequencies(arr):
result_arr = Type(arr.dtype, (arr.shape[0], ((arr.shape[1] // 2) + 1)))
return Transformation([Parameter('output', Annotation(result_arr, 'o')), Parameter('input', Annotation(arr, 'i'))], '\n if (${idxs[1]} < ${input.shape[1] // 2 + 1})\n ${output.store_idx}(${idxs[0... |
class OptionPlotoptionsPictorialSonificationContexttracksMappingLowpassResonance(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, tex... |
class MyPluginDao(BaseDao):
def add(self, engity: MyPluginEntity):
session = self.get_raw_session()
my_plugin = MyPluginEntity(tenant=engity.tenant, user_code=engity.user_code, user_name=engity.user_name, name=engity.name, type=engity.type, version=engity.version, use_count=(engity.use_count or 0), ... |
class OptionSonificationGlobalcontexttracksMappingNoteduration(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):
s... |
def is_not_secure(secure_version, file_version, appname=None):
if (secure_version == 'N/A'):
return True
try:
if (not all((isinstance(x, str) for x in (secure_version, file_version)))):
raise TypeError('is_not_secure: input must be str when comparing. secure_version %s, file_version ... |
class OptionPlotoptionsFunnel3dSonificationTracksMappingHighpassFrequency(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 publish_hass_discovery(client, device_topic, expire_after_seconds: int, sample: BmsSample, num_cells, temperatures, device_info: DeviceInfo=None):
discovery_msg = {}
device_json = {'identifiers': [((device_info and device_info.sn) or device_topic)], 'manufacturer': ((device_info and device_info.mnf) or None... |
class GenericTimer(Thread):
interval = 1
stop_flag = None
callback = None
def __init__(self, _interval, _callback, _args=()):
Thread.__init__(self, name='generic_timer_thread')
self.interval = _interval
self.stop_flag = Event()
self.callback = _callback
self.args ... |
def extractRuxifielluBlogspotCom(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)... |
def annotate_prime_award_recipient_id(field_name, queryset):
return _annotate_recipient_id(field_name, queryset, "(\n select\n rp.recipient_hash || '-' || rp.recipient_level\n from\n rpt.subaward_search bs\n inner join recipient_lookup rl on (rl.ue... |
class Train():
def __init__(self):
self._opt = TrainOptions().parse()
self._model = ModelsFactory.get_by_name(self._opt.model, self._opt)
self._tb_visualizer = TBVisualizer(self._opt)
data_loader_train = CustomDatasetDataLoader(self._opt, mode='train')
data_loader_val = Custo... |
def bulk_delete_netloc(netloc, main=False, history=False):
commit_interval = 50000
step = 10000
with db.session_context() as sess:
print('Getting minimum row in need or update..')
start = sess.execute('SELECT min(id) FROM web_pages WHERE netloc=:netloc', {'netloc': netloc})
start = l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.