code
stringlengths
281
23.7M
class OptionSeriesOrganizationSonificationDefaultinstrumentoptionsPointgrouping(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, fl...
class ShardStats(TelemetryDevice): internal = False serverless_status = serverless.Status.Internal command = 'shard-stats' human_name = 'Shard Stats' help = 'Regularly samples nodes stats at shard level' def __init__(self, telemetry_params, clients, metrics_store): super().__init__() ...
def get_linked_anki_notes_around_pdf_page(siac_nid: int, page: int) -> List[Tuple[(int, int)]]: conn = _get_connection() nps = conn.execute(f'select page from notes_pdf_page where siac_nid = {siac_nid} and page >= {(page - 6)} and page <= {(page + 6)} group by nid').fetchall() conn.close() if ((not nps)...
class OptionSeriesColumnpyramidDataDatalabelsFilter(Options): def operator(self): return self._config_get(None) def operator(self, value: Any): self._config(value, js_type=False) def property(self): return self._config_get(None) def property(self, text: str): self._config...
def test_copy(): original = UnaryOperation(neg, [a]) copy = original.copy() assert ((id(original) != id(copy)) and (original == copy)) assert ((id(original.operands) != id(copy.operands)) and (original.operands == copy.operands)) assert (id(original.operands[0]) != id(copy.operands[0])) original...
class TestRotation2D(object): def setup_class(cls): pass def teardown_class(cls): pass def setup_method(self, method): self.aux_names = [] self.meshdir = os.path.dirname(os.path.abspath(__file__)) self._scriptdir = os.path.dirname(os.path.abspath(__file__)) def te...
class LiteEthPHYRGMIICRG(LiteXModule): def __init__(self, platform, clock_pads, with_hw_init_reset, hw_reset_cycles=256, n=0): self._reset = CSRStorage() self.cd_eth_rx = ClockDomain() self.cd_eth_tx = ClockDomain() self.specials += ClkInput(i=clock_pads.rx, o=f'auto_eth{n}_rx_clk_in...
class BaseEnvEvents(ABC): _epoch_stats(np.max, input_name='sum', output_name='max') _epoch_stats(np.min, input_name='sum', output_name='min') _epoch_stats(np.mean, input_name='sum', output_name='mean') _epoch_stats(np.std, input_name='sum', output_name='std') _epoch_stats(sum, input_name='count', ou...
def cap(geom, high_frag): high_set = set(high_frag) ind_set = set(range(len(geom.atoms))) rest = (ind_set - high_set) bonds = get_bond_sets(geom.atoms, geom.coords3d) bond_sets = [set(b) for b in bonds] break_bonds = [b for b in bond_sets if (len((b & high_set)) == 1)] capped_frag = high_set...
def get_gnome_version() -> Optional[str]: gnome_version = '' if (sys.platform != 'linux'): return None if ((not os.environ.get('GNOME_DESKTOP_SESSION_ID', '')) and ('gnome' not in os.environ.get('XDG_CURRENT_DESKTOP', '').lower())): return None if (not shutil.which('gnome-shell')): ...
def test_moving_mean_returns_correct_array_with_1d_data(data_1d): moved_data = scared.signal_processing.moving_mean(data_1d, 10) reference_data = [] for i in range(((data_1d.shape[(- 1)] - 10) + 1)): reference_data.append(data_1d[i:(i + 10)].mean()) reference_data = np.array(reference_data) ...
class OptionPlotoptionsDependencywheelSonificationTracksMappingPlaydelay(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 _SaverDict(_SaverMutable, MutableMapping): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._data = kwargs.pop('_class', dict)() def has_key(self, key): return (key in self._data) _save def update(self, *args, **kwargs): self._data.update(...
class EventolSetting(models.Model): background = models.ImageField(null=True, blank=True, help_text=_('A image to show in the background of')) logo_header = models.ImageField(null=True, blank=True, help_text=_('This logo will be shown in the right corner of the page')) logo_landing = models.ImageField(null=...
class Matrix_Expression(Expression): def __init__(self, t_open): super().__init__() assert isinstance(t_open, MATLAB_Token) assert (t_open.kind == 'M_BRA') self.t_open = t_open self.t_open.set_ast(self) self.t_close = None self.n_content = None def loc(sel...
class TestObserveAddNotifier(unittest.TestCase): def test_add_trait_notifiers(self): observable = DummyObservable() notifier = DummyNotifier() observer = DummyObserver(notify=True, observables=[observable], notifier=notifier) graph = ObserverGraph(node=observer) call_add_or_r...
class StateNormalization(object): def __init__(self): env = UAVEnv() M = env.M self.high_state = np.array([500000.0, env.ground_length, env.ground_width, (100 * 1048576)]) self.high_state = np.append(self.high_state, (np.ones((M * 2)) * env.ground_length)) self.high_state = n...
class VerilogHeader(Generator, Jinja2): def __init__(self, rmap=None, path='regs.vh', prefix='CSR', **args): super().__init__(rmap, **args) self.path = path self.prefix = prefix def generate(self): self.validate() j2_template = 'verilog_header.j2' j2_vars = {} ...
def test_changing_default_block_identifier(w3, math_contract): assert (math_contract.caller.counter() == 0) assert (w3.eth.default_block == 'latest') math_contract.functions.incrementCounter(7).transact() assert (math_contract.caller.counter() == 7) assert (math_contract.functions.counter().call(blo...
def get_list_of_purchase_orders_for_center(center, date=None): if date: start_date = end_date = date else: end_date = frappe.utils.nowdate() start_date = add_to_date(end_date, days=(- 1)) route = 'inventory/purchase_orders?center_id=' url_end = '&show_delivery_details=true&date_c...
class TestDecisionMaker2(BaseTestDecisionMakerDefault): decision_maker_handler_cls = DecisionMakerHandler decision_maker_cls = DecisionMaker def _patch_logger(cls): cls.patch_logger_warning = mock.patch.object(aea.decision_maker.gop._default_logger, 'warning') cls.mocked_logger_warning = cls...
def make_hist_for_num_plot(curr: pd.Series, ref: pd.Series=None): result = {} if (ref is not None): ref = ref.dropna() bins = np.histogram_bin_edges(pd.concat([curr.dropna(), ref]), bins='doane') curr_hist = np.histogram(curr, bins=bins) result['current'] = make_hist_df(curr_hist) if (re...
def write_df_to_relation(adapter, dataframe, relation, if_exists) -> AdapterResponse: assert (adapter.type() == 'athena') if isinstance(adapter.config.credentials, FalCredentialsWrapper): creds = adapter.config.credentials._db_creds else: creds = adapter.config.credentials temp_relation ...
class CombatActionFlee(CombatAction): def execute(self): combathandler = self.combathandler if (self.combatant not in combathandler.fleeing_combatants): combathandler.fleeing_combatants[self.combatant] = self.combathandler.turn current_turn = combathandler.turn started_fl...
def extends(cls): def wrapper(f): if isinstance(f, property): name = f.fget.__name__ else: name = f.__name__ if isinstance(cls, type): setattr(cls, name, f) elif isinstance(cls, list): for c in cls: setattr(c, name, f) ...
class OrganizationField(BaseObject): def __init__(self, api=None, active=None, created_at=None, description=None, id=None, key=None, position=None, raw_description=None, raw_title=None, regexp_for_validation=None, title=None, type=None, updated_at=None, url=None, **kwargs): self.api = api self.activ...
class bsn_sff_json(bsn): type = 65535 experimenter = 6035143 exp_type = 6 def __init__(self, data_json=None): if (data_json != None): self.data_json = data_json else: self.data_json = '' return def pack(self): packed = [] packed.append(...
def supported_extension(file: FileWrapper, accepted_extensions: List[str]): extensions = audio_format(file.file_path, file.file_info.file_extension) if (len(extensions) == 1): if (extensions[0] in accepted_extensions): return (True, *extensions) return (False, 'nop') if (len(exte...
class TestTransactionCache(): def setup_class(cls): unique_name = os.urandom(8).hex() cls.db_filename = DatabaseContext.shared_memory_uri(unique_name) cls.db_context = DatabaseContext(cls.db_filename) cls.db = cls.db_context.acquire_connection() create_database(cls.db) ...
def test_execution_metadata(): scheduled_at = datetime.datetime.now() system_metadata = _execution.SystemMetadata(execution_cluster='my_cluster') parent_node_execution = _identifier.NodeExecutionIdentifier(node_id='node_id', execution_id=_identifier.WorkflowExecutionIdentifier(project='project', domain='dom...
def test_many_logical_files(): path = 'data/chap4-7/many-logical-files-error-in-last.dlis' errorhandler = ErrorHandler() errorhandler.critical = Actions.LOG_ERROR with dlis.load(path, error_handler=errorhandler) as files: assert (len(files) == 2) errorhandler.critical = Actions.RAISE ...
(IView) class MView(MWorkbenchPart, PerspectiveItem): busy = Bool(False) category = Str('General') image = Image() visible = Bool(False) def _id_default(self): id = ('%s.%s' % (type(self).__module__, type(self).__name__)) logger.warning(('view %s has no Id - using <%s>' % (self, id))...
class TestActionShrink_exclude_node(TestCase): def builder(self): self.client = Mock() self.client.info.return_value = {'version': {'number': '8.0.0'}} self.client.cat.indices.return_value = testvars.state_one self.client.indices.get_settings.return_value = testvars.settings_one ...
def test_base_representations(): x = Fxp(0.0, True, 8, 4) x(2.5) assert (x.bin() == '') assert (x.hex() == '0x28') assert (x.hex(padding=False) == '0x28') assert (x.base_repr(2) == '101000') assert (x.base_repr(16) == '28') x((- 7.25)) assert (x.bin() == '') assert (x.bin(frac_do...
def custom_500(request): (type_, value, traceback) = sys.exc_info() reason = 'Server error' if ('canceling statement due to statement timeout' in str(value)): reason = 'The database took too long to respond. If you were running ananalysis with multiple codes, try again with fewer.' if ((request...
class ModeratorModel(): def __init__(self): self.id: int = None self.username: str = None self.roles: 'List[str]' = [] self.boards = None def from_username(cls, username: str): m = cls() m.username = username return m def from_orm_model(cls, model: Mod...
def extractONLINE(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None if ('Great Tang Idyll' in item['tags']): return buildReleaseMessageWithType(item, 'Great Tang Idyll', vol,...
class BertBaseUncased(nn.Module): def __init__(self, batch_size, seq_len, vocab_size=30522, max_position_embeddings=512, type_vocab_size=2, num_hidden_layers=12, hidden_size=768, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', layer_norm_eps=1e-12, attention_probs_dropout_prob=0.0, hidden_dropout...
.integration_test def test_surface_param_update(tmpdir): ensemble_size = 5 with tmpdir.as_cwd(): config = f''' NUM_REALIZATIONS {ensemble_size} QUEUE_OPTION LOCAL MAX_RUNNING 5 OBS_CONFIG observations SURFACE MY_PARAM OUTPUT_FILE:surf.irap INIT_FILES:surf.irap BASE_SURFACE:surf.irap FORWARD_INIT:True GE...
class UDPPacket(Packet): def __init__(self, init=[]): Packet.__init__(self, init) def decode(self): header = [] for byte in self[:udp_header.length]: header.append(self.pop(0)) for (k, v) in sorted(udp_header.fields.items()): setattr(self, k, get_field_dat...
def fetch_live_price(zone_key: ZoneKey, session: Session, logger: Logger=getLogger(__name__)): data_list = fetch_live_data('price', session)['giaBiens'] result_list = PriceList(logger) for data in data_list: result_list.append(datetime=(datetime.fromisoformat(data['thoiGian']).replace(tzinfo=tz) - t...
class OptionSeriesPieTooltip(Options): def clusterFormat(self): return self._config_get('Clustered points: {point.clusterPointsAmount}') def clusterFormat(self, text: str): self._config(text, js_type=False) def dateTimeLabelFormats(self) -> 'OptionSeriesPieTooltipDatetimelabelformats': ...
def _run_simpson_tests(backend, _precision): simp = Simpson() N = 100001 (errors, funcs) = compute_integration_test_errors(simp.integrate, {'N': N, 'dim': 1}, integration_dim=1, use_complex=True, backend=backend) print(f'1D Simpson Test passed. N: {N}, backend: {backend}, Errors: {errors}') for (err...
def test_settings_server_url_is_empty_string(): stdout = io.StringIO() with override_settings(ELASTIC_APM={'SERVER_URL': ''}): call_command('elasticapm', 'check', stdout=stdout) output = stdout.getvalue() assert ('Configuration errors detected' in output) assert ('SERVER_URL appears to be em...
class OptionSeriesVectorStatesInactive(Options): def animation(self) -> 'OptionSeriesVectorStatesInactiveAnimation': return self._config_sub_data('animation', OptionSeriesVectorStatesInactiveAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): se...
class SqlConnOdbc(): def __init__(self, database=None, **kwargs): self.query = {} pyodbc = requires('pyodbc', reason='Missing Package', install='sqlalchemy', source_script=__file__) dbAttr = {'Driver': kwargs['driver'], 'DBQ': database} for opt in [('password', 'PWD'), ('username', '...
class OptionSeriesDumbbellSonificationContexttracksMappingLowpass(Options): def frequency(self) -> 'OptionSeriesDumbbellSonificationContexttracksMappingLowpassFrequency': return self._config_sub_data('frequency', OptionSeriesDumbbellSonificationContexttracksMappingLowpassFrequency) def resonance(self) -...
def test_daily_working_hours_attribute_is_set_to_a_number_bigger_than_24(): wh = WorkingHours() with pytest.raises(ValueError) as cm: wh.daily_working_hours = 25 assert (str(cm.value) == 'WorkingHours.daily_working_hours should be a positive integer value greater than 0 and smaller than or equal to ...
class Field(): def __init__(self, type_: Type, name: str, default_value_string: Optional[str]=None): if (not isinstance(type_, Type)): raise TypeError(("the field type '%s' must be a 'Type' instance" % type_)) self.type = type_ if (not is_valid_field_name(name)): rais...
class TestHSV(util.ColorAssertsPyTest): COLORS = [('red', 'color(--hsv 0 1 1)'), ('orange', 'color(--hsv 38.824 1 1)'), ('yellow', 'color(--hsv 60 1 1)'), ('green', 'color(--hsv 120 1 0.50196)'), ('blue', 'color(--hsv 240 1 1)'), ('indigo', 'color(--hsv 274.62 1 0.5098)'), ('violet', 'color(--hsv 300 0.45378 0.9333...
class TestLinearA98RGB(util.ColorAssertsPyTest): COLORS = [('red', 'color(--a98-rgb-linear 0.71513 0 0)'), ('orange', 'color(--a98-rgb-linear 0.82231 0.37626 0.01549)'), ('yellow', 'color(--a98-rgb-linear 1 1 0.04116)'), ('green', 'color(--a98-rgb-linear 0.06149 0.21586 0.00889)'), ('blue', 'color(--a98-rgb-linear ...
class Fail(RuleResult): def __init__(self, test: Any=None) -> None: RuleResult.__init__(self, test) def is_success(self) -> bool: return False def is_fail(self) -> bool: return True def expect_success(self) -> Any: raise ValueError('Expected success but rewrite rule patte...
class File(Input): input_type = 'file' def __init__(self, upload: FileUpload, default: Any=None, null: bool=False, disabled: bool=False, help_text: Optional[str]=None): super().__init__(null=null, default=default, input_type=self.input_type, disabled=disabled, help_text=help_text) self.upload = ...
def _create_item_dict(uni_item): item_dict = {'weight_uom': DEFAULT_WEIGHT_UOM} _validate_create_brand(uni_item.get('brand')) for (uni_field, erpnext_field) in UNI_TO_ERPNEXT_ITEM_MAPPING.items(): value = uni_item.get(uni_field) if (not _validate_field(erpnext_field, value)): con...
class FullScreen(MovieLayout): def __init__(self): super().__init__() self.scale = (1 / 2) def video_width(self): return int(max(self.cameras('front').width, ((self.cameras('left').width + self.cameras('rear').width) + self.cameras('right').width))) def video_height(self): pe...
def extractSegmetonTranslation(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None tagmap = [('Seirei Tsukai to Shinjuu Tsukai no Shounen', 'Seirei Tsukai to Shinjuu Tsukai no Shounen'...
def parse_barcode_file(fp, primer=None, header=False): tr = trie.StringTrie() reader = csv.reader(fp) if header: next(reader) records = (record for record in reader if record) for record in records: (specimen, barcode) = record[:2] if (primer is not None): pr = pr...
class ProjectTestDBCase(UnitTestDBBase): def setUp(self): super(ProjectTestDBCase, self).setUp() import datetime import pytz self.start = datetime.datetime(2016, 11, 17, tzinfo=pytz.utc) self.end = (self.start + datetime.timedelta(days=20)) from stalker import User ...
def draw_bboxes(image, bboxes, line_thickness): line_thickness = (line_thickness or (round(((0.002 * (image.shape[0] + image.shape[1])) * 0.5)) + 1)) list_pts = [] point_radius = 4 for (x1, y1, x2, y2, cls_id, pos_id) in bboxes: color = (0, 255, 0) check_point_x = x1 check_point_...
def ovlp3d_42(ax, da, A, bx, db, B): result = numpy.zeros((15, 6), dtype=float) x0 = (0.5 / (ax + bx)) x1 = ((ax + bx) ** (- 1.0)) x2 = ((- x1) * ((ax * A[0]) + (bx * B[0]))) x3 = ((- x2) - A[0]) x4 = ((ax * bx) * x1) x5 = numpy.exp(((- x4) * ((A[0] - B[0]) ** 2))) x6 = (1. * numpy.sqrt(...
class SVProxy(SOCKSProxy): kinds = {'SOCKS4': SOCKS4a, 'SOCKS5': SOCKS5} def __init__(self, address, kind, auth): protocol = self.kinds.get(kind.upper()) if (not protocol): raise ValueError(f'invalid proxy kind: {kind}') if isinstance(auth, list): auth = SVUserAut...
class CmdBan(COMMAND_DEFAULT_CLASS): key = 'ban' aliases = ['bans'] locks = 'cmd:perm(ban) or perm(Developer)' help_category = 'Admin' def func(self): banlist = ServerConfig.objects.conf('server_bans') if (not banlist): banlist = [] if ((not self.args) or (self.sw...
class TestOFPQueuePropHeader(unittest.TestCase): property_ = 1 len_ = 10 def test_init(self): c = OFPQueuePropHeader(self.property_, self.len_) eq_(self.property_, c.property) eq_(self.len_, c.len) def _test_serialize(self, property_, len_): c = OFPQueuePropHeader(propert...
def get_miso_exchange(session: Session) -> tuple: map_url = ' res: Response = session.get(map_url) soup = BeautifulSoup(res.text, 'html.parser') find_div = soup.find('div', {'id': 'body_0_flow1', 'class': 'flow'}) miso_flow = find_div.text miso_flow_no_ws = ''.join(miso_flow.split()) miso_ac...
def get_code_with_retry(req, headers={}): for attempts in range(10): try: resp = requests.get(req, headers=headers, timeout=10) if (resp.status_code < 500): return resp.status_code print(f'get_code_with_retry: 5xx code {resp.status_code}, retrying...') ...
.skipif((sys.version_info < (3, 10)), reason='ignore_cleanup_errors requires Python 3.10 or later') def test_mars_labeling(): data = np.random.random((40320,)) with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: path = os.path.join(tmp, 'a.grib') f = cml.new_grib_output(path, da...
def pre_process_header(filename, remove_function_bodies=False): print(('Pre-processing ' + filename)) file = open(filename, 'r') filetext = ''.join([line for line in file if ('#include' not in line)]) command = ['gcc', '-CC', '-P', '-undef', '-nostdinc', '-DRL_MATRIX_TYPE', '-DRL_QUATERNION_TYPE', '-DRL...
def test_adding_a_nodePort(): config = '' r = helm_template(config) assert ('nodePort' not in r['service'][uname]['spec']['ports'][0]) config = '\n service:\n nodePort: 30001\n ' r = helm_template(config) assert (r['service'][uname]['spec']['ports'][0]['nodePort'] == 30001)
def test_dyn_signal(): def t1(a: int) -> int: return (a + 5) def t2(a: int) -> int: return (a + 6) def dyn(a: int) -> typing.Tuple[(int, int, int)]: x = t1(a=a) s1 = wait_for_input('my-signal-name', timeout=timedelta(hours=1), expected_type=bool) s2 = wait_for_input('...
class EarlyStopper(): def __init__(self, max_epochs_without_improvement: int, epsilon: float, minimize: bool): self.max_epochs_without_improvement = max_epochs_without_improvement self.epsilon = epsilon self.minimize = minimize self.current_best_value: Optional[float] = None ...
class LeftNavigationMenu(ft.Column): def __init__(self, gallery): super().__init__() self.gallery = gallery self.rail = ft.NavigationRail(extended=True, expand=True, selected_index=0, min_width=100, min_extended_width=200, group_alignment=(- 0.9), destinations=self.get_destinations(), on_cha...
class OptionSeriesTreemapPointEvents(Options): def click(self): return self._config_get(None) def click(self, value: Any): self._config(value, js_type=False) def drag(self): return self._config_get(None) def drag(self, value: Any): self._config(value, js_type=False) d...
class This(BaseType): default_value_type = DefaultValue.constant fast_validate = (ValidateTrait.self_type,) info_text = 'an instance of the same type as the receiver' def __init__(self, value=None, allow_none=True, **metadata): super().__init__(value, **metadata) if allow_none: ...
def _viewControllerDescription(viewController): vc = ('(%s)' % viewController) if fb.evaluateBooleanExpression(('[(id)%s isViewLoaded]' % vc)): result = fb.evaluateExpressionValue(('(id)[[NSString alloc] initWithFormat:"<%%: %%p; view = <%%; %%p>; frame = (%%g, %%g; %%g, %%g)>", (id)NSStringFromClass((i...
class TestOFPActionSetNwTos(unittest.TestCase): type_ = {'buf': b'\x00\x08', 'val': ofproto.OFPAT_SET_NW_TOS} len_ = {'buf': b'\x00\x08', 'val': ofproto.OFP_ACTION_NW_TOS_SIZE} tos = {'buf': b'\xb6', 'val': 182} zfill = (b'\x00' * 3) buf = (((type_['buf'] + len_['buf']) + tos['buf']) + zfill) c ...
class TestStorageConfigModel(): (scope='function') def storage_details_s3(self) -> Dict[(str, str)]: return {StorageDetails.BUCKET.value: 'some bucket', StorageDetails.NAMING.value: 'some naming', StorageDetails.MAX_RETRIES.value: 0, StorageDetails.AUTH_METHOD.value: S3AuthMethod.SECRET_KEYS.value} ...
class LabeledVideoPaths(LabeledVideoPaths_): labels = None def from_path(cls, data_path: str) -> LabeledVideoPaths: if (g_pathmgr.isfile(data_path) and data_path.endswith('.csv')): return LabeledVideoPaths.from_csv(data_path) elif (g_pathmgr.isfile(data_path) and has_file_allowed_ext...
_config(route_name='latest_builds', renderer='json') def latest_builds(request): builds = {} koji = request.koji package = request.params.get('package') for (tag_type, tags) in models.Release.get_tags()[0].items(): for tag in tags: try: for build in koji.getLatestBuil...
def add_d2_quant_mapping(mappings): import torch.ao.quantization.quantization_mappings as qm for (k, v) in mappings.items(): if (k not in qm.get_default_static_quant_module_mappings()): qm.DEFAULT_STATIC_QUANT_MODULE_MAPPINGS[k] = v if (k not in qm.get_default_qat_module_mappings()):...
class TargetMeanRegressor(BaseTargetMeanEstimator, RegressorMixin): def fit(self, X: pd.DataFrame, y: pd.Series): if (type_of_target(y) == 'binary'): raise ValueError('Trying to fit a regression to a binary target is not allowed by this transformer. ') return super().fit(X, y) def pr...
class LiteEthPHYRGMIICRG(LiteXModule): def __init__(self, clock_pads, pads, with_hw_init_reset, tx_delay=2e-09): self._reset = CSRStorage() self.cd_eth_rx = ClockDomain() self.specials += [Instance('BUFG', i_I=clock_pads.rx, o_O=self.cd_eth_rx.clk)] self.cd_eth_tx = ClockDomain() ...
class OptionPlotoptionsBarLabel(Options): def boxesToAvoid(self): return self._config_get(None) def boxesToAvoid(self, value: Any): self._config(value, js_type=False) def connectorAllowed(self): return self._config_get(False) def connectorAllowed(self, flag: bool): self._...
.dict('foremast.securitygroup.create_securitygroup.DEFAULT_SECURITYGROUP_RULES', DEFAULT_SG_RULES) ('foremast.securitygroup.create_securitygroup.get_details') ('foremast.securitygroup.create_securitygroup.get_properties') def test_merge_security_groups(mock_properties, mock_details): app_ingress = {'test_app': [{'s...
class WorkspaceView(WorkspaceBase): def __init__(self, user_id: Optional[UserID], project_manager: ProjectManager, team_id: Optional[TeamID]=None): self.project_manager = project_manager self.user_id = user_id self.team_id = team_id def create_project(self, name: str, description: Option...
def run_perf(dim, num_rep, sample_size): wmg = WeightedMinHashGenerator(dim, sample_size=sample_size) logging.info(('WeightedMinHash using %d samples' % sample_size)) data = np.random.uniform(0, dim, (num_rep, dim)) durs = [] for i in range(num_rep): start = time.clock() wmg.minhash(...
('/') def homepage(): logfile = logFile(loggingDir) logs = file_read(logfile) body = '' body += ("<h3>Recent logs</h3><p><strong>File</strong>: %s</p><pre style='height: 400px;' id='logWindow' class='pre-scrollable small text-nowrap'>%s</pre>" % (logfile, logs)) passTable = genPassTable(satellites, ...
def extractNovelGilegatiCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Spirit Conductor', 'Spirit Conductor', 'translated')] for (tagname, name, tl_type) in tagmap: ...
def _compute_var(query_samples: Tensor) -> Tuple[(Tensor, Tensor)]: (n_chains, n_samples) = query_samples.shape[:2] if (query_samples.dtype not in [torch.float32, torch.float64]): query_samples = query_samples.float() if (n_chains > 1): per_chain_avg = query_samples.mean(1) b = (n_sa...
class FileObjectEntry(Base): __tablename__ = 'file_object' uid = Column(UID, primary_key=True) sha256 = Column(CHAR(64), nullable=False) file_name = Column(VARCHAR, nullable=False) depth = Column(Integer, nullable=False) size = Column(BigInteger, nullable=False) comments = Column(MutableList...
class ManualShortcut(QDialog): def __init__(self, parent, shortcut_item): QDialog.__init__(self, parent=parent) self.shortcut_item = shortcut_item button_box = QDialogButtonBox((QDialogButtonBox.Ok | QDialogButtonBox.Cancel)) button_box.accepted.connect(self.accept_clicked) b...
def get_group_stats(dp, waiters, group_id=None): if (group_id is None): group_id = dp.ofproto.OFPG_ALL else: group_id = str_to_int(group_id) stats = dp.ofproto_parser.OFPGroupStatsRequest(dp, group_id, 0) msgs = [] ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG) gro...
class DailyAggTarget(): def __init__(self, data_key: str, col: str, horizon: int=100, foo: Callable=np.mean, n_jobs: int=cpu_count()): self.data_key = data_key self.col = col self.horizon = horizon self.foo = foo self.n_jobs = n_jobs self._data_loader = None def _...
def extractOnlyok19WordpressCom(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) ...
class OptionPlotoptionsSplineSonificationTracksMappingTremoloDepth(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 OptionSeriesDependencywheelSonificationTracksMappingTremolo(Options): def depth(self) -> 'OptionSeriesDependencywheelSonificationTracksMappingTremoloDepth': return self._config_sub_data('depth', OptionSeriesDependencywheelSonificationTracksMappingTremoloDepth) def speed(self) -> 'OptionSeriesDepen...
def _aspectDict(obj1, obj2, aspList): if ((obj1 == obj2) or (obj1.id == const.SYZYGY)): return None orbs = _orbList(obj1, obj2, aspList) for aspDict in orbs: asp = aspDict['type'] orb = aspDict['orb'] if (asp in const.MAJOR_ASPECTS): if ((obj1.orb() < orb) and (ob...
def test_create_model(client: TestClient): test_model = {'name': 'another_test_model', 'address': 'another_test_address', 'stateless': True, 'batch_size': 256, 'run_on_gpu': False} response = client.post('/models', json=test_model) assert (response.status_code == 200) assert (response.json() == test_mod...
def test_can_register_option(): MY_OPTION = Config.register_option(name='tests:MY_OPTION', help='Test option, value should be True or False, default = True', default=True, parse=(lambda v: (v in ('True', 'true', 1, True))), validate=(lambda v: ((v == True) or (v == False)))) assert (MY_OPTION.name == 'tests:MY_...
class AwardDownloadValidator(DownloadValidatorBase): name = 'award' def __init__(self, request_data: dict): super().__init__(request_data) self.request_data = request_data self._json_request['download_types'] = self.request_data.get('award_levels') self._json_request['filters'] =...
class OptionPlotoptionsWordcloudSonificationContexttracksMappingTime(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): ...