code stringlengths 281 23.7M |
|---|
def test_disposing_handler5():
m1 = MyComponent4()
m2 = MyComponent4()
m1.set_other(m2)
loop.iter()
m2_ref = weakref.ref(m2)
del m2
gc.collect()
assert (m2_ref() is not None)
m2_ref().dispose()
m1.set_other(None)
loop.iter()
gc.collect()
assert (m2_ref() is None) |
def add_moredoc(app, objtype):
cls = autodoc.AutoDirective._registry[objtype]
documenter = type(('More' + cls.__name__), (MoreInfoDocumenter, cls), {})
autodoc.AutoDirective._registry[('more' + objtype)] = documenter
app.add_directive(('automore' + objtype), autodoc.AutoDirective)
dirname = getattr(... |
class AnonymizerStageService(PrivateComputationStageService):
def __init__(self, onedocker_svc: OneDockerService, onedocker_binary_config_map: DefaultDict[(str, OneDockerBinaryConfig)]) -> None:
self._onedocker_svc = onedocker_svc
self._onedocker_binary_config_map = onedocker_binary_config_map
... |
class DirParamType(click.ParamType):
name = 'directory path'
def convert(self, value: typing.Any, param: typing.Optional[click.Parameter], ctx: typing.Optional[click.Context]) -> typing.Any:
p = pathlib.Path(value)
remote_directory = (None if getattr(ctx.obj, 'is_remote', False) else False)
... |
def test_gradient_computation():
(in_matrix, result_matrix) = construct_pre_processing_matrix()
adj_hat_torch = GraphConvBlock.preprocess_adj_to_adj_hat(in_matrix)
assert (adj_hat_torch.requires_grad is False)
self_scaling_param = torch.tensor(1.0, requires_grad=False)
adj_hat_torch = GraphConvBlock... |
class InclinedDiskModel(FunctionModel2DScalarDeformedRadial):
def __init__(self, inc=0, pa=0, degrees=True, **kwargs):
super(InclinedDiskModel, self).__init__('sersic', **kwargs)
self.n = 1
if degrees:
self.incdeg = inc
self.padeg = pa
else:
self.i... |
def find_free_port(preferred_port=None):
if (preferred_port is not None):
if (not is_port_in_use(preferred_port)):
return preferred_port
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(('', 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, ... |
class OptionSeriesPyramidSonificationContexttracksPointgrouping(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):
... |
class OptionPlotoptionsPolygonOnpointConnectoroptions(Options):
def dashstyle(self):
return self._config_get(None)
def dashstyle(self, text: str):
self._config(text, js_type=False)
def stroke(self):
return self._config_get(None)
def stroke(self, text: str):
self._config(t... |
class SOLARAdapter(NewHFChatModelAdapter):
support_4bit: bool = True
support_8bit: bool = False
def do_match(self, lower_model_name_or_path: Optional[str]=None):
return (lower_model_name_or_path and ('solar-' in lower_model_name_or_path) and ('instruct' in lower_model_name_or_path)) |
class TestEmptySearch():
def setup_class(cls):
cls.node = LocalNode()
cls.node.start()
cls.address_1 = 'address_1'
cls.public_key_1 = 'public_key_1'
cls.multiplexer = Multiplexer([_make_local_connection(cls.address_1, cls.public_key_1, cls.node)])
cls.multiplexer.conn... |
def _author(forenames=None, surname=LAST_NAME_1, email=EMAIL_1, affiliation=None):
if (forenames is None):
forenames = [FIRST_NAME_1]
author = TEI_E.author()
persName = TEI_E.persName()
author.append(persName)
for (i, forename) in enumerate(forenames):
persName.append(TEI_E.forename(... |
class DemoController(Handler):
view = Instance(DemoView)
def init(self, info):
self.view = info.object
return True
def save(self, ui_info):
ui = self.view.edit_traits(view='save_file_view')
if (ui.result == True):
self.view._save()
def load(self, ui_info):
... |
class OptionSeriesWindbarbSonificationDefaultinstrumentoptionsMappingLowpassFrequency(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... |
def get_rules():
cwd = os.path.split(__file__)[0]
rulepath = os.path.join(cwd, 'rules')
items = os.listdir(rulepath)
items.sort()
ret = []
specials = {}
for item in [os.path.join(rulepath, item) for item in items if item.endswith('.yaml')]:
with open(item, 'r', encoding='utf-8') as f... |
def create_scope_ws(path='/', query_string='', headers=None, host=DEFAULT_HOST, scheme=None, port=None, remote_addr=None, root_path=None, include_server=True, subprotocols=None, spec_version='2.1') -> Dict[(str, Any)]:
scope = create_scope(path=path, query_string=query_string, headers=headers, host=host, scheme=(s... |
_view(['GET'])
_classes([IsAuthenticated])
def open(request):
queue = Jupyter_queue.objects.all()
if (len(queue) > 0):
if (queue[0].user.id == request.user.id):
return Response({'status': 'Success', 'message': 'opened Successfully'}, status=status.HTTP_200_OK)
now = datetime.now()
... |
class Frame():
def __init__(self, idx):
self.idx = idx
self.throws = []
def total_pins(self):
return sum(self.throws)
def is_strike(self):
return ((self.total_pins == 10) and (len(self.throws) == 1))
def is_spare(self):
return ((self.total_pins == 10) and (len(sel... |
class RCareWorldGymWrapper(RCareWorldBaseEnv, gym.Env):
def __init__(self, executable_file: str=None, scene_file: str=None, custom_channels: list=[], assets: list=[], **kwargs):
RCareWorldBaseEnv.__init__(self, executable_file=executable_file, scene_file=scene_file, custom_channels=custom_channels, assets=a... |
class GetDeletedDbTest(TestModelMixin, TestBase):
databases = {'default', 'mysql', 'postgres'}
def testGetDeletedDb(self):
with reversion.create_revision(using='postgres'):
obj = TestModel.objects.create()
obj.delete()
self.assertEqual(Version.objects.get_deleted(TestModel).c... |
class BackgroundThread(object):
KEYPAD_ESC = 10
KEYPAD_ENT = 11
def __init__(self, callbackaddr, interval=0.005, WiegandOBJ=None):
self.interval = interval
self.pin = ''
self.enablerun = True
self.callbackfunc = callbackaddr
self.WR = WiegandOBJ
thread = threa... |
def build_config(name):
errors = 0
os.system(f'rm -rf examples/{name}')
os.system(f'mkdir -p examples/{name} && cd examples/{name} && python3 ../../litedram/gen.py ../{name}.yml')
errors += (not os.path.isfile(f'examples/{name}/build/gateware/litedram_core.v'))
os.system(f'rm -rf examples/{name}')
... |
def grouped_data_per_team(data):
teams = {}
for (name, members) in app.config['USAGE_TREEMAP_TEAMS'].items():
for member in members:
teams[member] = name
result = {}
for (user, value) in data.items():
key = teams.get(user, user)
result.setdefault(key, {})
resu... |
class TestDefaultAccountEv(BaseEvenniaTest):
def test_characters_property(self):
self.account.db._playable_characters = [self.char1, None]
self.assertEqual(self.account.characters.all(), [self.char1])
self.assertEqual(self.account.db._playable_characters, [self.char1])
def test_add_chara... |
class FirewallDConfigZone(DbusServiceObject):
persistent = True
default_polkit_auth_required = config.dbus.PK_ACTION_CONFIG
_exceptions
def __init__(self, parent, conf, zone, item_id, *args, **kwargs):
super(FirewallDConfigZone, self).__init__(*args, **kwargs)
self.parent = parent
... |
class WebsocketProvider(JSONBaseProvider):
logger = logging.getLogger('web3.providers.WebsocketProvider')
_loop = None
def __init__(self, endpoint_uri: Optional[Union[(URI, str)]]=None, websocket_kwargs: Optional[Any]=None, websocket_timeout: int=DEFAULT_WEBSOCKET_TIMEOUT) -> None:
self.endpoint_uri... |
class OSDWindow(Gtk.Window):
__hide_id = None
__fadeout_id = None
__autohide = True
__options = None
geometry = dict(x=20, y=20, width=300, height=120)
def __init__(self, css_provider, options, allow_resize_move):
Gtk.Window.__init__(self, type=Gtk.WindowType.TOPLEVEL)
self.__opt... |
class NameExcludeTestCase(IncludeExcludeMixIn, unittest.TestCase):
def test_filter_id(self):
expected = self.sequences[2:]
actual = list(transform.name_exclude(self.sequences, 'sequenceid[12]'))
self.assertEqual(3, len(actual))
self.assertEqual(expected, actual)
def test_filter_d... |
def test_get_dataframe():
g = xtgeo.grid_from_file(GFILE1, fformat='egrid')
names = ['SOIL', 'SWAT', 'PRESSURE']
dates = []
x = xtgeo.gridproperties_from_file(RFILE1, fformat='unrst', names=names, dates=dates, grid=g)
df = x.get_dataframe(activeonly=True, ijk=True, xyz=False)
print(df.head())
... |
def test_multiple_tickets_discount(db):
ticket_a = TicketSubFactory(price=50.0)
ticket_b = TicketSubFactory(price=495.8, event=ticket_a.event)
ticket_c = TicketSubFactory(price=321.3, event=ticket_a.event)
ticket_d = TicketSubFactory(price=500.0, event=ticket_a.event, type='free')
discount = Discoun... |
def input_bot_token(data: DataModel, default=None):
prompt = _('Your Telegram Bot token: ')
if default:
prompt += f'[{default}] '
while True:
ans = input(prompt)
if (not ans):
if default:
return default
else:
print(_('Bot token ... |
class OptionSeriesNetworkgraphSonificationTracksMappingHighpassFrequency(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 create_and_populate_bq_table(client, name, schema, table_data):
table = client.get_or_create_table(name, schema)
if (not table_data):
return
with tempfile.NamedTemporaryFile('wt') as f:
writer = csv.writer(f)
for item in table_data:
writer.writerow(dict_to_row(item, s... |
_renderer(wrap_type=TestNumberOfColumnsWithMissingValues)
class TestNumberOfColumnsWithMissingValuesRenderer(BaseTestMissingValuesRenderer):
def render_html(self, obj: TestNumberOfMissingValues) -> TestHtmlInfo:
info = super().render_html(obj)
metric_result = obj.metric.get_result()
return s... |
('flytekit.configuration.plugin.FlyteRemote', spec=FlyteRemote)
def test_pyflyte_backfill(mock_remote):
mock_remote.generate_console_url.return_value = 'ex'
runner = CliRunner()
with runner.isolated_filesystem():
result = runner.invoke(pyflyte.main, ['backfill', '--parallel', '-p', 'flytesnacks', '-... |
def fortios_extender(data, fos):
fos.do_member_operation('extender', 'lte-carrier-list')
if data['extender_lte_carrier_list']:
resp = extender_lte_carrier_list(data, fos)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'extender_lte_carrier_list'))
return ((not is_successful_s... |
class OptionSeriesHeatmapSonificationTracksMappingTime(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._con... |
def __cookVacmViewInfo(snmpEngine, viewName, subTree):
mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder
(vacmViewTreeFamilyEntry,) = mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyEntry')
tblIdx = vacmViewTreeFamilyEntry.getInstIdFromIndices(viewName, subTree)
... |
def create_file_object_entry(file_object: FileObject) -> FileObjectEntry:
sanitize(file_object.virtual_file_path)
return FileObjectEntry(uid=file_object.uid, sha256=file_object.sha256, file_name=file_object.file_name, root_firmware=[], parent_files=[], included_files=[], depth=file_object.depth, size=file_objec... |
def rows_by_other_config(manager, system_id, key, value, table='Bridge', fn=None):
matched_rows = match_rows(manager, system_id, table, (lambda r: ((key in r.other_config) and (r.other_config.get(key) == value))))
if (matched_rows and (fn is not None)):
return [fn(row) for row in matched_rows]
retur... |
class TestZ3LogicCondition():
.parametrize('z3_term, length', [(Z3LogicCondition.initialize_true(context), 0), (Z3LogicCondition.initialize_false(context), 0), (z3_x[1].copy(), 1), ((~ z3_x[1].copy()), 1), ((z3_x[1].copy() | z3_x[2].copy()), 2), ((z3_x[1].copy() & z3_x[2].copy()), 2), (((z3_x[1].copy() & z3_x[2].co... |
def test_custom_training():
(task_config=SagemakerTrainingJobConfig(training_job_resource_config=TrainingJobResourceConfig(instance_type='ml-xlarge', volume_size_in_gb=1), algorithm_specification=AlgorithmSpecification(algorithm_name=AlgorithmName.CUSTOM)))
def my_custom_trainer(x: int) -> int:
return x... |
class RequestInformation():
def __init__(self, method: 'RPCEndpoint', params: Any, response_formatters: Tuple[(Callable[(..., Any)], ...)], subscription_id: str=None):
self.method = method
self.params = params
self.response_formatters = response_formatters
self.subscription_id = subs... |
class FaqSchema(SoftDeletionSchema):
class Meta():
type_ = 'faq'
self_view = 'v1.faq_detail'
self_view_kwargs = {'id': '<id>'}
inflect = dasherize
id = fields.Str(dump_only=True)
question = fields.Str(required=True)
answer = fields.Str(required=True)
event = Relations... |
class AttributionSpec(AbstractObject):
def __init__(self, api=None):
super(AttributionSpec, self).__init__()
self._isAttributionSpec = True
self._api = api
class Field(AbstractObject.Field):
event_type = 'event_type'
window_days = 'window_days'
_field_types = {'event_... |
def get_scene_preferences():
pref = preference_manager.preferences
res = {}
res['stereo'] = ast.literal_eval(pref.get('tvtk.scene.stereo'))
res['magnification'] = ast.literal_eval(pref.get('tvtk.scene.magnification'))
res['foreground'] = ast.literal_eval(pref.get('tvtk.scene.foreground_color'))
... |
def getgw(iface):
result = ''
try:
output = os.popen(('route -n | grep ' + str(iface)))
for line in output:
l = line.split()
if ((l[2].strip() == '0.0.0.0') and (l[1].strip() != '0.0.0.0')):
result = l[1]
break
except:
result = ... |
class SX1262(SX126X):
TX_DONE = SX126X_IRQ_TX_DONE
RX_DONE = SX126X_IRQ_RX_DONE
ADDR_FILT_OFF = SX126X_GFSK_ADDRESS_FILT_OFF
ADDR_FILT_NODE = SX126X_GFSK_ADDRESS_FILT_NODE
ADDR_FILT_NODE_BROAD = SX126X_GFSK_ADDRESS_FILT_NODE_BROADCAST
PREAMBLE_DETECT_OFF = SX126X_GFSK_PREAMBLE_DETECT_OFF
PRE... |
(IProviderExtensionRegistry)
class ProviderExtensionRegistry(ExtensionRegistry):
_providers = List(IExtensionProvider)
def set_extensions(self, extension_point_id, extensions):
raise TypeError('extension points cannot be set')
def add_provider(self, provider):
events = self._add_provider(pro... |
class OptionSeriesBubbleMarker(Options):
def fillColor(self):
return self._config_get(None)
def fillColor(self, text: str):
self._config(text, js_type=False)
def fillOpacity(self):
return self._config_get(0.5)
def fillOpacity(self, num: float):
self._config(num, js_type=F... |
def test_override_hydra_config_value_from_config_file() -> None:
config_loader = ConfigLoaderImpl(config_search_path=create_config_search_path('hydra/test_utils/configs'))
cfg = config_loader.load_configuration(config_name='overriding_output_dir.yaml', overrides=[], run_mode=RunMode.RUN)
assert (cfg.hydra.r... |
class CheckJsonFormat(object):
def __init__(self, use_tabs=False, allow_comments=False):
self.use_tabs = use_tabs
self.allow_comments = allow_comments
self.fail = False
def index_lines(self, text):
self.line_range = []
count = 1
last = 0
for m in re.findit... |
class HeuristicsManager(object):
cfg_heuristics = None
log = None
__sites_object = {}
__sites_heuristics = {}
__heuristics_condition = None
__condition_allowed = ['(', ')', ' and ', ' or ', ' not ']
def __init__(self, cfg_heuristics, sites_object, crawler_class):
self.cfg_heuristics ... |
class OptionPlotoptionsVariwideSonificationDefaultinstrumentoptionsMappingHighpass(Options):
def frequency(self) -> 'OptionPlotoptionsVariwideSonificationDefaultinstrumentoptionsMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsVariwideSonificationDefaultinstrumentoptions... |
class Camera():
selectable_shutter_speeds = {(1 / 4): (1 / 4), (1 / 8): (1 / 8), (1 / 15): (1 / 16), (1 / 30): (1 / 32), (1 / 60): (1 / 64), (1 / 125): (1 / 128), (1 / 250): (1 / 256), (1 / 500): (1 / 512)}
selectable_film_speeds = (25, 50, 100, 200, 400, 800)
def __init__(self):
self.back = Back(ca... |
class Gzip(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
return {'cache_condition': (str, none_type), 'conte... |
def test_not_force_defaults_radio_checked():
html = '<input type="radio" name="radio-1" class="my_radio" value="cb">'
expected_html = '<input type="radio" name="radio-1" class="my_radio" value="cb" checked="checked">'
rendered_html = htmlfill.render(html, defaults={'radio-1': 'cb'}, force_defaults=False)
... |
_deserializable
class PineconeDB(BaseVectorDB):
BATCH_SIZE = 100
def __init__(self, config: Optional[PineconeDBConfig]=None):
if (config is None):
self.config = PineconeDBConfig()
else:
if (not isinstance(config, PineconeDBConfig)):
raise TypeError('config... |
def get_connections(wire, wire_info, conn, idx, coord_to_tile, tiles):
pair = conn['wire_pairs'][idx]
wire_tile_type = wire_info['type']
tile_types = conn['tile_types']
shortname = wire_info['shortname']
grid_deltas = conn['grid_deltas']
wire1 = ((tile_types[0] == wire_tile_type) and (shortname ... |
class Clocks(dict):
def names(self):
return list(self.keys())
def add_io(self, io):
for name in self.names():
print(((name + '_clk'), 0, Pins(1)))
io.append(((name + '_clk'), 0, Pins(1)))
def add_clockers(self, sim_config):
for (name, desc) in self.items():
... |
def process() -> None:
DATA_RAW_DIR = 'data/raw'
DATA_FEATURES_DIR = 'data/features'
files = ['green_tripdata_2021-01.parquet', 'green_tripdata_2021-02.parquet']
print('Load train data')
for file in files:
path_source = f'{DATA_RAW_DIR}/{file}'
data = pd.read_parquet(path_source)
... |
_common_aws_errors
def describe_dynamo_tables(client: Any, table_names: List[str]) -> List[Dict]:
describe_tables = []
for table in table_names:
described_table = client.describe_table(TableName=table)
describe_tables.append(described_table['Table'])
return describe_tables |
class TestWildcard(util.PluginTestCase):
def setup_fs(self):
config = self.dedent("\n matrix:\n - name: python\n sources:\n - '{}/**/*.txt'\n aspell:\n lang: en\n d: en_US\n hunspell:\n d: ... |
class JSONEncoderTests(TestCase):
def setUp(self):
self.encoder = JSONEncoder()
def test_encode_decimal(self):
d = Decimal(3.14)
assert (self.encoder.default(d) == float(d))
def test_encode_datetime(self):
current_time = datetime.now()
assert (self.encoder.default(cur... |
def test_static_files_only(app_static_files_only, elasticapm_client):
client = TestClient(app_static_files_only)
response = client.get(('/tmp/' + file_name), headers={constants.TRACEPARENT_HEADER_NAME: '00-0af7651916cd43dd8448eb211c80319c-b7ad6b-03', constants.TRACESTATE_HEADER_NAME: 'foo=bar,bar=baz', 'REMOTE_... |
_type(ofproto.OFPTMPBF_TIME_CAPABILITY)
class OFPBundleFeaturesPropTime(OFPBundleFeaturesProp):
def __init__(self, type_=None, length=None, sched_accuracy=None, sched_max_future=None, sched_max_past=None, timestamp=None):
super(OFPBundleFeaturesPropTime, self).__init__(type_, length)
self.sched_accu... |
class BuildingMenuCmdSet(CmdSet):
key = 'building_menu'
priority = 5
mergetype = 'Replace'
def at_cmdset_creation(self):
caller = self.cmdsetobj
menu = caller.ndb._building_menu
if (menu is None):
menu = caller.db._building_menu
if menu:
me... |
class OptionPlotoptionsStreamgraphAccessibilityPoint(Options):
def dateFormat(self):
return self._config_get(None)
def dateFormat(self, text: str):
self._config(text, js_type=False)
def dateFormatter(self):
return self._config_get(None)
def dateFormatter(self, value: Any):
... |
class Animator(HasTraits):
start = Button('Start Animation')
stop = Button('Stop Animation')
delay = Range(10, 100000, 500, desc='frequency with which timer is called')
timer = Any
traits_view = View(Group(Item('start'), Item('stop'), show_labels=False), Item('_'), Item(name='delay'), title='Animati... |
class AtariPPORNDModel(PPORNDModel):
def __init__(self, num_actions: int, network: str='nature') -> None:
super().__init__()
self._num_actions = num_actions
self._network = network.lower()
if (self._network == 'nature'):
self._ppo_net = NatureCNNBackbone()
sel... |
def uninstall_system():
files = [os.path.join(SYSTEM_EXTENSION_DIR, EXTENSION_FILE), os.path.join(SYSTEM_EXTENSION_DIR, (EXTENSION_FILE + 'c')), os.path.join(SYSTEM_GLIB_SCHEMA_DIR, GLIB_SCHEMA_FILE)]
for file_ in files:
if os.path.isfile(file_):
os.remove(file_)
if is_glib_compile_schem... |
.parametrize('transaction,expected,key_object,from_', TEST_SIGNED_TRANSACTION_PARAMS, ids=['with set gas', 'with no set gas', 'with mismatched sender', 'with invalid sender', 'with gasPrice lower than base fee', 'with txn type and dynamic fee txn params', 'with dynamic fee txn params and no type'])
def test_signed_tran... |
class _InterceptGeneratorMeta(type):
def __new__(cls, name, bases, dict):
return super().__new__(cls, name, (bases + (tuple,)), dict)
def __call__(cls, *args, **kwargs):
if ((len(args) == 1) and (kwargs == {}) and isinstance(args[0], Generator)):
args = tuple(args[0])
obj = s... |
class ZenithNovelsPageProcessor(HtmlProcessor.HtmlPageProcessor):
wanted_mimetypes = ['text/html']
want_priority = 80
loggerPath = 'Main.Text.ZenithNovels'
def wantsUrl(url):
if re.search('^ url):
print(("zenith novels Wants url: '%s'" % url))
return True
return F... |
def handle_it(exception_details):
access_violation_flag = False
if ('access-violation' == exception_details['type']):
memory = exception_details['memory']
if (int(memory['address'], 16) in range(data.break_point_info['break_addr'], (data.break_point_info['break_addr'] + data.break_point_info['br... |
.EventDecorator()
def compile_coordinate_element(ufl_coordinate_element, contains_eps, parameters=None):
if (parameters is None):
parameters = tsfc.default_parameters()
else:
_ = tsfc.default_parameters()
_.update(parameters)
parameters = _
element = tsfc.finatinterface.creat... |
class DesktopCoverPlugin():
def __init__(self):
self.__desktop_cover = None
def enable(self, _exaile):
self.__migrate_anchor_setting()
def on_gui_loaded(self):
self.__desktop_cover = DesktopCover()
def disable(self, _exaile):
self.__desktop_cover.destroy()
self.__... |
class ConvDepthwiseTestCase(unittest.TestCase):
def test_fp16(self, batch=4):
groups = 32
size = (12, 12)
target = detect_target()
X = Tensor(shape=[IntImm(batch), *size, 32], dtype='float16', name='input_0', is_input=True)
W = Tensor(shape=[32, 3, 3, 1], dtype='float16', nam... |
class TestOIDCProviderConfig():
VALID_CREATE_OPTIONS = {'provider_id': 'oidc.provider', 'client_id': 'CLIENT_ID', 'issuer': ' 'display_name': 'oidcProviderName', 'enabled': True, 'id_token_response_type': True, 'code_response_type': True, 'client_secret': 'CLIENT_SECRET'}
OIDC_CONFIG_REQUEST = {'displayName': '... |
def extractIlover18NovelHomeBlog(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [("It's Purely an Accident to Love Again", "It's Purely an Accident to Love Again", 'translated'),... |
def test_mask_sha512():
configuration = HashMaskingConfiguration(algorithm='SHA-512')
masker = HashMaskingStrategy(configuration)
expected = '527ca44f5c95400d161c503e6ddad7be01941ec9e7a03c2201338a16ba8a36bb765a430bd6b276af3f743a3a91efecd056645b4ea13b4b8cf39e8e3'
secret = MaskingSecretCache[str](secret='... |
class DefaultArgumentsMultiple(Argument):
def __init__(self, *args: Any, **kwargs: Any) -> None:
kwargs['nargs'] = (- 1)
default = kwargs.pop('default', tuple())
super().__init__(*args, **kwargs)
self.default = default
def full_process_value(self, ctx: Context, value: Any) -> Any... |
def _gen_tensor_modal(tensor) -> str:
content = {}
content['shape'] = _get_tensor_shape_str(tensor)
content['is_view_of'] = ('None' if (tensor._attrs['is_view_of'] is None) else tensor._attrs['is_view_of']._attrs['name'])
content['is_input'] = str(tensor._attrs['is_input'])
content['is_output'] = st... |
def check_pubkey(pubkey_path, user, project, opts):
if os.path.exists(pubkey_path):
log.info('Pubkey for %s/%s exists: %s', user, project, pubkey_path)
return True
else:
log.info('Missing pubkey for %s/%s', user, project)
try:
get_pubkey(user, project, log, opts.sign_... |
def get_current_version(app, bench_path='.'):
current_version = None
repo_dir = get_repo_dir(app, bench_path=bench_path)
config_path = os.path.join(repo_dir, 'setup.cfg')
init_path = os.path.join(repo_dir, os.path.basename(repo_dir), '__init__.py')
setup_path = os.path.join(repo_dir, 'setup.py')
... |
class FormAssembler(abc.ABC):
def __init__(self, form, tensor, bcs=(), form_compiler_parameters=None, needs_zeroing=True, weight=1.0):
assert (tensor is not None)
bcs = solving._extract_bcs(bcs)
self._form = form
self._tensor = tensor
self._bcs = bcs
self._form_compil... |
class CounterData():
label: str
value: str
def __init__(self, label: str, value: str):
self.label = label
self.value = value
def float(label: str, value: float, precision: int) -> 'CounterData':
return CounterData(label, f'{value:.{precision}}')
def string(label: str, value: ... |
class MakeMenu():
cur_id = 1000
def __init__(self, desc, owner, popup=False, window=None):
self.owner = owner
if (window is None):
window = owner
self.window = window
self.indirect = getattr(owner, 'call_menu', None)
self.names = {}
self.desc = desc.sp... |
def extractFoitinstlWordpressCom(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 funcparser_callable_crop(*args, **kwargs):
if (not args):
return ''
(text, *rest) = args
nrest = len(rest)
try:
width = int(kwargs.get('width', (rest[0] if (nrest > 0) else _CLIENT_DEFAULT_WIDTH)))
except (TypeError, ValueError):
width = _CLIENT_DEFAULT_WIDTH
suffix =... |
.django_db
class TestUserForumPermission(object):
def test_cannot_target_an_anonymous_user_and_a_registered_user(self):
user = UserFactory.create()
with pytest.raises(ValidationError):
perm = ForumPermissionFactory.create()
user_perm = UserForumPermissionFactory.build(permiss... |
def test_normalize_items_from_objects():
class Function():
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
functions = ['printf', '__libc_start_main']
assert (normalize_lief_items([Function(name) for name in functions]) == functions) |
def gen_profiler(func_attrs, workdir, profiler_filename, dim_info_dict, src_template, problem_args_template, args_parser_template, support_split_k=False, output_addr_calculator='', bias_ptr_arg=None, extra_code='', problem_args_template_cutlass_3x=None):
import cutlass_lib
op_type = func_attrs['op']
op_inst... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'profile-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'}, 'membe... |
def microsoft_ocr_tables_standardize_response(original_response: dict) -> OcrTablesAsyncDataClass:
num_pages = len(original_response['pages'])
pages: List[Page] = [Page() for _ in range(num_pages)]
for table in original_response.get('tables', []):
std_table = _ocr_tables_standardize_table(table, ori... |
def find_(root: str, rbase: str, include_files: List[str], include_dirs: List[str], excludes: List[str], scan_exclude: List[str]) -> List[str]:
files = []
scan_root = os.path.join(root, rbase)
with os.scandir(scan_root) as it:
for entry in it:
path = os.path.join(rbase, entry.name)
... |
def main():
ledger = LedgerClient(NetworkConfig.fetchai_stable_testnet())
faucet_api = FaucetApi(NetworkConfig.fetchai_stable_testnet())
initial_stake =
total_period = 60000
req = QueryValidatorsRequest()
resp = ledger.staking.Validators(req)
total_stake = 0
validators_stake = [int(vali... |
class OptionSeriesBarSonificationDefaultinstrumentoptionsMappingTremoloDepth(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: s... |
def log_fortianalyzer2_override_filter(data, fos):
vdom = data['vdom']
log_fortianalyzer2_override_filter_data = data['log_fortianalyzer2_override_filter']
filtered_data = underscore_to_hyphen(filter_log_fortianalyzer2_override_filter_data(log_fortianalyzer2_override_filter_data))
return fos.set('log.fo... |
('rocm.gemm_rcr.gen_function')
def gemm_gen_function(func_attrs, exec_cond_template, dim_info_dict):
return common.gen_function(func_attrs, exec_cond_template, dim_info_dict, '', input_addr_calculator=common.INPUT_ADDR_CALCULATOR.render(accessor_a=func_attrs['input_accessors'][0], accessor_b=func_attrs['input_acces... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.