code
stringlengths
281
23.7M
class FontStretch(BaseCFloat): default_value = 100.0 def __init__(self, default_value=NoDefaultSpecified, **metadata): if (default_value != NoDefaultSpecified): default_value = self.validate(None, None, default_value) super().__init__(default_value, **metadata) def validate(self,...
class mac_lte_tags(IntEnum): MAC_LTE_PAYLOAD_TAG = 1 MAC_LTE_RNTI_TAG = 2 MAC_LTE_UEID_TAG = 3 MAC_LTE_FRAME_SUBFRAME_TAG = 4 MAC_LTE_PREDEFINED_DATA_TAG = 5 MAC_LTE_RETX_TAG = 6 MAC_LTE_CRC_STATUS_TAG = 7 MAC_LTE_EXT_BSR_SIZES_TAG = 8 MAC_LTE_SEND_PREAMBLE_TAG = 9 MAC_LTE_CARRIE...
class TestESP8266FlashHeader(BaseTestCase): def test_2mb(self): ELF = 'esp8266-nonossdkv20-at-v2.elf' BIN = 'esp8266-nonossdkv20-at-v2-0x01000.bin' try: self.run_elf2image('esp8266', ELF, version=2, extra_args=['--flash_size', '2MB', '--flash_mode', 'dio']) with open(...
def browsesingle(type, heading, shares='', mask='', useThumbs=False, treatAsFolder=False, defaultt=None): from xbmcgui import Dialog if (not heading): heading = ADDON.getAddonInfo('name') return to_unicode(Dialog().browseSingle(type=type, heading=heading, shares=shares, mask=mask, useThumbs=useThumb...
def extractKneeslappingtlWordpressCom(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_...
class Chunk(Op): __slots__ = ('_size', '_list') def __init__(self, size, source=None): Op.__init__(self, source) self._size = size self._list = [] def on_source(self, *args): self._list.append((args[0] if (len(args) == 1) else (args if args else NO_VALUE))) if (len(se...
class TimeChecker(): def __init__(self): self.start = 0.0 self.data = [] self.begin() def begin(self): self.start = time.time() del self.data[:] def print_time(self, restart=True): print(f'Time elapsed: {self.get_time(restart)}') def get_time(self, restart...
def test_sync_streaming_response(test_client_factory): async def app(scope, receive, send): def numbers(minimum, maximum): for i in range(minimum, (maximum + 1)): (yield str(i)) if (i != maximum): (yield ', ') generator = numbers(1, 5) ...
class CriticModel(nn.Module): def __init__(self, inputs_shape): super().__init__() self.inut_shape = inputs_shape self.features = nn.Sequential(nn.Conv2d(inputs_shape[1], 32, kernel_size=8, stride=4), nn.ReLU(), nn.Conv2d(32, 64, kernel_size=4, stride=2), nn.ReLU(), nn.Conv2d(64, 64, kernel_...
class DebugListener(FdListener): def __init__(self, evtype, fileno, cb, tb, mark_as_closed): self.where_called = traceback.format_stack() self.greenlet = greenlet.getcurrent() super().__init__(evtype, fileno, cb, tb, mark_as_closed) def __repr__(self): return ('DebugListener(%r, ...
class SampleSheetPredictor(): def __init__(self, sample_sheet=None, sample_sheet_file=None): self.projects = [] self._predict_for_package = 'bcl2fastq2' self._predict_paired_end = False self._predict_no_lane_splitting = False self._predict_for_lanes = None self._predi...
def extractImemotranslationsCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Hone to Issho', 'Hone to Issho no Isekai Seikatsu', 'translated'), ('PRC', 'PRC', 'translated'),...
def collect_topics(account): cmd_help_topics = [] if (not (str(account) == 'AnonymousUser')): puppets = (account.characters.all() + [account]) for puppet in puppets: for cmdset in puppet.cmdset.get(): cmdset.make_unique(puppet) for cmd in cmdset: ...
class CompoundVolumeVolumeToken(CompoundToken): def valid_volume_1(self, parse_ascii): return self.is_valid_1(parse_ascii) def valid_volume_2(self, parse_ascii): return self.is_valid_2(parse_ascii) def get_volume_1(self, parse_ascii): return self.to_number_1(parse_ascii) def get_...
_in_both(Foo2) def test_get_event_handlers(): foo = Foo2() def bar(*events): pass bar = foo.reaction('!x', bar) print([r.get_name() for r in foo.get_event_handlers('x')]) def zz1(*events): pass def zz2(*events): pass zz1 = foo.reaction('!x', zz1) zz2 = foo.reactio...
class HealthServicer(object): def Check(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def Watch(self, request, context): context.set_code(grpc.StatusCode...
class View(flx.Widget): def init(self): with flx.VBox(): with flx.HBox(): self.first_edit = flx.LineEdit(placeholder_text='first name', text='Jane') self.last_edit = flx.LineEdit(placeholder_text='last name', text='Doe') flx.Widget(flex=1) ...
class OLD_SequenceFace(Face): def __init__(self, seq, seqtype, fsize=10, aafg=None, aabg=None, ntfg=None, ntbg=None): Face.__init__(self) self.seq = seq self.fsize = fsize self.fsize = fsize self.style = seqtype if (not aafg): aafg = _aafgcolors if...
.parametrize('events, expected', [(((0, left_click),), 'no action'), (((0.4, left_click),), 'leftclick'), (((0.4, left_click), (0.4, left_click)), 'leftclick'), (((0.2, left_click), (0, left_click)), 'doubleleftclick'), (((0.2, left_click), (0, left_click), (0.3, left_click)), 'leftclick'), (((0.2, left_click), (0, rig...
class ParseCrawler(object): helper = None log = None def __init__(self, helper): self.helper = helper self.log = logging.getLogger(__name__) def pass_to_pipeline_if_article(self, response, source_domain, original_url, rss_title=None): if self.helper.heuristics.is_article(response...
class AdAssetFeedSpecAssetLabel(AbstractCrudObject): def __init__(self, fbid=None, parent_id=None, api=None): self._isAdAssetFeedSpecAssetLabel = True super(AdAssetFeedSpecAssetLabel, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): id = 'id' name = 'name' ...
class BenchController(): def __init__(self, bus): self.bus = bus def reboot(self): self.bus.regs.ctrl_reset.write(1) def load_rom(self, filename, delay=0): from litex.soc.integration.common import get_mem_data rom_data = get_mem_data(filename, endianness='little') for...
def test_partitioned_analyses_update_raises_error_if_shapes_are_inconsistent(): d = DumbPartDistinguisher() traces = np.random.randint(0, 255, (10, 200), dtype='uint8') data = np.random.randint(0, 8, (50, 64), dtype='uint8') with pytest.raises(ValueError): d.update(traces=traces, data=data) ...
def _calculate_strategy(state: ShortDeckPokerState, I: str, strategy: DefaultDict[(str, DefaultDict[(str, float)])], count=None, total_count=None) -> str: sigma = collections.defaultdict((lambda : collections.defaultdict((lambda : (1 / 3))))) try: sigma[I] = strategy[I].copy() if (sigma[I] == {}...
class VegaChart(JsPackage): lib_alias = {'js': 'vega', 'css': 'vega'} def parse(self, data): return JsUtils.jsWrap(('vega.parse(%s)' % JsUtils.jsConvertData(data, None))) def toSVG(self, scale_factor): pass def toImageURL(self, kind, scale_factor): pass def toCanvas(self, sca...
class GlossaryViewSet(APIView): endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/references/glossary.md' _response() def get(self, request: Request) -> Response: models = [{'name': 'page', 'key': 'page', 'type': 'integer', 'default': 1, 'min': 1}, {'name': 'limit', 'key': 'limit', 'type': ...
def extractWwwThekingdomsofevilCom(item): badwords = ['Book Review'] if any([(bad in item['tags']) for bad in badwords]): return None (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None ...
def rollback_task_definition(deployment, old, new, timeout=600, sleep_time=1): click.secho(('Rolling back to task definition: %s\n' % old.family_revision), fg='yellow') deploy_task_definition(deployment=deployment, task_definition=old, title='Deploying previous task definition', success_message='Rollback succes...
.parametrize('is_sampled', [pytest.param(True, id='is_sampled-True'), pytest.param(False, id='is_sampled-False')]) .parametrize('instance_headers', [pytest.param(True, id='instance-headers-set'), pytest.param(False, id='instance-headers-not-set')]) .parametrize('header_arg,header_kwarg', [pytest.param(True, False, id='...
(Output('radar-chart', 'figure'), [Input('music-intensity-selector', 'value'), Input('music-time-selector', 'value'), Input('music-sport-selector', 'value')], [State('music-intensity-selector', 'value'), State('music-time-selector', 'value'), State('music-sport-selector', 'value')]) def update_radar_chart(*args): c...
def test_stream_get_admin(db, client, admin_jwt): (room, stream, session) = get_room_session_stream(db, name='Test Stream') response = client.get(f'/v1/video-streams/{stream.id}', content_type='application/vnd.api+json', headers=admin_jwt) assert (response.status_code == 200) assert (json.loads(response...
def test_transition_list_or_operator(): s1 = State('s1', initial=True) s2 = State('s2') s3 = State('s3') s4 = State('s4', final=True) t12 = s1.to(s2) t23 = s2.to(s3) t34 = s3.to(s4) cycle = ((t12 | t23) | t34) assert ([(t.source.name, t.target.name) for t in t12] == [('s1', 's2')]) ...
class ModelDockerHubFetcher(ErsiliaBase): def __init__(self, overwrite=None, config_json=None): ErsiliaBase.__init__(self, config_json=config_json, credentials_json=None) self.simple_docker = SimpleDocker() self.overwrite = overwrite def is_docker_installed(self): return DockerRe...
class ClientList(): def __init__(self, prodj): self.clients = [] self.client_keepalive_callback = None self.client_change_callback = None self.media_change_callback = None self.log_played_tracks = True self.auto_request_beatgrid = True self.auto_track_download...
class TestECSHelpers(unittest.TestCase): def test_is_intermediate_field(self): pseudo_field = {'field_details': {}} self.assertEqual(ecs_helpers.is_intermediate(pseudo_field), False) pseudo_field['field_details']['intermediate'] = False self.assertEqual(ecs_helpers.is_intermediate(ps...
def _replace_writes(ir, fwd, c, sym, repl, only_replace_attrs=True): cur_fwd = (lambda x: x) c = fwd(c) matches = (match_pattern(c, f'{repr(sym)} = _', use_sym_id=True) + match_pattern(c, f'{repr(sym)} += _', use_sym_id=True)) for block in matches: assert (len(block) == 1) s = cur_fwd(bl...
class Plugin(plugin.PluginProto): PLUGIN_ID = 17 PLUGIN_NAME = 'RFID - PN532' PLUGIN_VALUENAME1 = 'Tag' def __init__(self, taskindex): plugin.PluginProto.__init__(self, taskindex) self.dtype = rpieGlobals.DEVICE_TYPE_I2C self.vtype = rpieGlobals.SENSOR_TYPE_TEXT self.valu...
class OptionSeriesAreasplinerangeLabelStyle(Options): def fontSize(self): return self._config_get('0.8em') def fontSize(self, num: float): self._config(num, js_type=False) def fontWeight(self): return self._config_get('bold') def fontWeight(self, text: str): self._config(...
class OsherFuncCoef(ObjectiveFunction_base): def __init__(self, LHS_s, RHS_s, fFunc, t, x, useShallowCopy=True): ObjectiveFunction_base.__init__(self, LHS_s, RHS_s) self.xi = old_div(x, t) self.t = t self.x = x self.c = {('u', 0): numpy.zeros((1,), 'd'), ('m', 0): numpy.zeros...
def get_referenced_missing_keys(taxonomy: Taxonomy) -> Set[FidesKey]: referenced_keys: List[Set[FidesKey]] = [find_referenced_fides_keys(resource) for resource_type in taxonomy.__fields_set__ for resource in getattr(taxonomy, resource_type)] key_set: Set[FidesKey] = set(reduce((lambda x, y: set().union(x).union...
class OptionSeriesFunnelSonificationContexttracksMappingRate(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): sel...
class GithubCodeView(generics.GenericAPIView): serializer_class = GithubCodeSerializer permission_classes = [permissions.AllowAny] def post(self, request): ACCESS_URL = ' payload = {'code': request.data['code'], 'client_id': os.environ['GITHUB_CLIENT_ID'], 'client_secret': os.environ['GITHUB...
class init_cond(object): def __init__(self, L, scaling=0.75): self.radius = 0.15 self.xc = 0.5 self.yc = 0.75 self.scaling = scaling def uOfXT(self, x, t): import numpy as np return (self.scaling * (self.radius - math.sqrt((((x[0] - self.xc) ** 2) + ((x[1] - self....
class TestCompareLatestGeneratorOutputWithTestProtocolWithNoCustomTypes(): def setup_class(cls): cls.cwd = os.getcwd() cls.t = tempfile.mkdtemp() os.chdir(cls.t) def test_compare_latest_generator_output_with_test_protocol(self): path_to_generated_protocol = self.t dotted_...
class Instance(object): def __init__(self, index: int, dataloader: Optional[Union[(SpeechToTextDataloader, TextToTextDataloader)]], args: Optional[Namespace]): self.index = index self.finish_prediction = False self.dataloader = dataloader if (self.dataloader is not None): ...
class TestNoCmdLineKwargRaise(): def test_cmd_line_kwarg_raise(self, monkeypatch): with monkeypatch.context() as m: with pytest.raises(TypeError): config = ConfigArgBuilder(*all_configs, no_cmd_line=True, configs='./tests/conf/yaml/test.yaml') return config.genera...
def _measure_for_children_in_entity(request, measure, parent_entity_code, parent_entity_type): parent = _get_entity(parent_entity_type, parent_entity_code) child_entity_type = {'pcn': 'practice', 'ccg': 'practice', 'stp': 'ccg', 'regional_team': 'ccg'}[parent_entity_type] measure = get_object_or_404(Measure...
class InfoWindow(QtWidgets.QDialog): def __init__(self, parent): QtWidgets.QDialog.__init__(self, parent, QtCore.Qt.Tool) self.setContentsMargins(0, 0, 0, 0) self._cfg = Config.get() self.layout = QtWidgets.QVBoxLayout(self) self._textedit = QtWidgets.QTextEdit() self...
class IsSameUser(IsAuthed): def __init__(self, topic_or_post=None): self._topic_or_post = topic_or_post def fulfill(self, user): return (super(IsSameUser, self).fulfill(user) and (user.id == self._determine_user())) def _determine_user(self): if (self._topic_or_post is not None): ...
class All2All_Scatter_Wait(Function): def forward(ctx, myreq, *output): ctx.a2ai = myreq.a2ai ctx.myreq = myreq myreq.req.wait() myreq.req = None myreq.tensor = None return output def backward(ctx, *grad_output): import torch.distributed as dist my...
class AEAProject(): old_cwd: str temp_dir: str def __init__(self, name: str='my_aea', parent_dir: Optional[str]=None): self.name = name self.parent_dir = parent_dir def __enter__(self) -> None: self.old_cwd = os.getcwd() self.temp_dir = tempfile.mkdtemp(dir=self.parent_di...
class KfpPipelineParameter(PipelineParameter): property_id = 'KFP_PIPELINE_PARAMETERS' property_attributes = [ListItemPropertyAttribute(attribute_id='name', description='The name of the parameter. This must be a valid Python identifier and not a keyword.', display_name='Parameter Name', allowed_input_types=[Pro...
class TestUpdateGetBugKarma(BasePyTestCase): def test_feedback_wrong_bug(self): update = model.Update.query.first() bk = model.BugKarma(karma=1, comment=update.comments[0], bug=update.bugs[0]) self.db.add(bk) bug = model.Bug(bug_id=12345, title='some title') update.bugs.appen...
class Ad(AbstractCrudObject, HasAdLabels): def __init__(self, fbid=None, parent_id=None, api=None): self._isAd = True super(Ad, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): account_id = 'account_id' ad_active_time = 'ad_active_time' ad_review_fe...
class DockerPack(BasePack): def __init__(self, model_id, config_json): BasePack.__init__(self, model_id, config_json) self.docker = SimpleDocker() self.docker_org = self.cfg.EXT.DOCKERHUB_ORG self.docker_tag = self.cfg.ENV.DOCKER.REPO_TAG self.logger.debug('Initializing docke...
class HeatmapDrawer(TracksDrawer): def __init__(self, the_poster: Poster): super().__init__(the_poster) self._center = None self._radius = None self._heatmap_line_width_low: float = 10.0 self._heatmap_line_width_upp: float = 1000.0 self._heatmap_line_width_lower: List...
def _swap_abilities(caller, raw_string, **kwargs): if raw_string: (abi1, *abi2) = raw_string.split(' ', 1) if (not abi2): caller.msg("That doesn't look right.") return (None, kwargs) abi2 = abi2[0] (abi1, abi2) = (abi1.upper().strip(), abi2.upper().strip()) ...
class NodeMatcher(Matcher): def __init__(self, structure: dict[(str, Any)], group: dict[(str, Any)]) -> None: super().__init__(structure, group) self.draw: bool = True if ('draw' in structure): self.draw = structure['draw'] self.shapes: Optional[IconDescription] = None ...
_builds_ns.route('/<int:build_id>') class GetBuild(Resource): _builds_ns.doc(params=get_build_docs) _builds_ns.marshal_with(build_model) def get(self, build_id): build = ComplexLogic.get_build(build_id) result = to_dict(build) result['build_id'] = result['id'] return result
class SchemaspaceExport(SchemaspaceBase): schema_name_option = CliOption('--schema_name', name='schema_name', description='The schema name of the metadata instances to export', required=False) include_invalid_flag = Flag('--include-invalid', name='include-invalid', description='Export valid and invalid instance...
.parametrize('params', (['t', 'u'], ['u', 't'])) .parametrize('levels', ([500, 850], [850, 500])) .parametrize('source_name', ['indexed-directory']) def test_indexing_pickle(params, levels, source_name): request = dict(level=levels, variable=params, date=, time='1200') (ds, __tmp, total, n) = get_fixtures(sourc...
def variate(oid, tag, value, **context): if (('snmpEngine' in context) and context['snmpEngine']): snmpEngine = context['snmpEngine'] if (snmpEngine not in moduleContext): moduleContext[snmpEngine] = {} if (context['transportDomain'] not in moduleContext[snmpEngine]): ...
def panel_with_localization_on(qtbot): def func(settings, ensemble_size): widget = AnalysisModuleVariablesPanel(settings, ensemble_size) qtbot.addWidget(widget) check_box = widget.findChild(QCheckBox, name='localization') qtbot.mouseClick(check_box, Qt.LeftButton) return (set...
class Solution(object): def toHex(self, num): curr = [] ret = [] for i in xrange(32): curr.append(str((num & 1))) num = (num >> 1) if (len(curr) == 4): n = int(''.join(reversed(curr)), 2) if (n < 10): ret...
def get_primary_entity(options, cfg): if options.primary_entity: primary_entity = options.primary_entity else: primary_entity = cfg.style_config['copyright_primary_entity'] if ((not primary_entity) and (len(cfg.style_config['copyright_entity']) == 1)): primary_entity = list(cfg.style...
class Blueprint(BlueprintT): routes: List[FutureRoute] static_routes: List[FutureStaticRoute] view_name_separator: str = ':' def __init__(self, name: str, *, url_prefix: Optional[str]=None) -> None: self.name = name self.url_prefix = url_prefix self.routes = [] self.stati...
class FixObserveTrueTest(unittest.TestCase): def test_fix_observe_true(self) -> None: self.maxDiff = None observations = {observation(0): tensor(1.0), observation(1): tensor(1.0)} queries = [] bmg = BMGInference() observed = bmg.to_dot(queries, observations) expected ...
class TestCandidateTotalsDetail(ApiBaseTest): candidate_totals_fields = {'candidate_election_year': 2020, 'offsets_to_operating_expenditures': 100.0, 'political_party_committee_contributions': 110.1, 'other_disbursements': 120.0, 'other_political_committee_contributions': 130.0, 'individual_itemized_contributions':...
def make_uniform_grid(dims, extent, center=0, has_center=False): num_dims = max(np.array([dims]).shape[(- 1)], np.array([extent]).shape[(- 1)], np.array([center]).shape[(- 1)]) dims = (np.ones(num_dims) * dims).astype('int') extent = (np.ones(num_dims) * extent).astype('float') center = (np.ones(num_dim...
class Migration(migrations.Migration): dependencies = [('core', '0005_auto__1301')] operations = [migrations.AlterField(model_name='location', name='residents', field=models.ManyToManyField(related_name='residences', to=settings.AUTH_USER_MODEL, blank=True)), migrations.AlterField(model_name='locationemailtempl...
class PointEncoder(fl.Chain): def __init__(self, embedding_dim: int=256, scale: float=1, device: ((Device | str) | None)=None, dtype: (DType | None)=None) -> None: assert ((embedding_dim % 2) == 0), 'embedding_dim must be divisible by 2.' self.embedding_dim = embedding_dim self.scale = scale...
class SwaggerView(MethodView): parameters = [] responses = {} definitions = {} tags = [] consumes = ['application/json'] produces = ['application/json'] schemes = [] security = [] deprecated = False operationId = None externalDocs = {} summary = None description = Non...
def extractNovicetranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if (item['tags'] == ['Translations']): titlemap = [('The Little Princess Imprisoned by the...
def get_read_last_n_days(delta_days: int) -> Dict[(int, Tuple[(int, str)])]: assert (delta_days >= 0) stamp = utility.date.date_x_days_ago_stamp(abs(delta_days)) conn = _get_connection() res = conn.execute(f"select counts.c, counts.nid, notes.title from notes join (select count(*) as c, nid from read wh...
def _modify_hypothesis_settings(settings, name, parent=None): settings = settings.copy() if (parent is None): parent = hp_settings._current_profile if ('phases' in settings): try: settings['phases'] = [getattr(Phase, k) for (k, v) in settings['phases'].items() if v] excep...
def test_ipaddress(): f = field.Ip() assert (f.deserialize('127.0.0.1') == ipaddress.ip_address('127.0.0.1')) assert (f.deserialize('::1') == ipaddress.ip_address('::1')) assert (f.serialize(f.deserialize('::1')) == '::1') assert (f.deserialize(None) is None) with pytest.raises(ValueError): ...
class GamePlayers(): def __init__(self, players: List[Player]): self._players: Dict[(str, Player)] = {player.id: player for player in players} self._player_ids: List[str] = [player.id for player in players] self._folder_ids: Set[str] = set() self._dead_player_ids: Set[str] = set() ...
class OptionPlotoptionsScatterSonificationTracksActivewhen(Options): def crossingDown(self): return self._config_get(None) def crossingDown(self, num: float): self._config(num, js_type=False) def crossingUp(self): return self._config_get(None) def crossingUp(self, num: float): ...
def test_context_manager_negative(): testutil.add_response('login_response_200') testutil.add_response('query_response_200') client_args = {'username': testutil.username, 'password': testutil.password, 'client_id': testutil.client_id, 'client_secret': testutil.client_secret, 'version': '37.0'} def logou...
def encode_sleb128(num): bs = bytearray() b = (num & 127) num = (num >> 7) more = (not (((num == 0) and ((b & 64) == 0)) or ((num == (- 1)) and ((b & 64) != 0)))) if more: b = (b | 128) bs.append(b) while more: b = (num & 127) num = (num >> 7) more = (not (((n...
def test_dimensions(): fpath = 'data/chap4-7/iflr/multidimensions-ints-various.dlis' with dlis.load(fpath) as (f, *_): frame = f.object('FRAME', 'FRAME-DIMENSION', 11, 0) curves = frame.curves() np.testing.assert_array_equal(curves[0][1], [[1, 2, 3], [4, 5, 6]]) np.testing.assert...
.parametrize('value', [10, (- 10)], ids=(lambda v: ('(f = %d)' % v))) .parametrize('expr', ['f', '2*f']) def test_math_functions(expr, value): mesh = UnitSquareMesh(2, 2) V = FunctionSpace(mesh, 'CG', 1) f = Function(V) f.assign(value) actual = Function(V) actual.assign(eval(expr)) f = value...
.EventDecorator() def derivative(form, u, du=None, coefficient_derivatives=None): if isinstance(form, firedrake.slate.TensorBase): raise TypeError(f'Cannot take the derivative of a {type(form).__name__}') u_is_x = isinstance(u, ufl.SpatialCoordinate) if (u_is_x or isinstance(u, Constant)): u...
class TestGetKrbConf(): def test_all_config_items_missing(self): config = {'some_meaningless_other_key': 'boring_value'} config = buildsys.get_krb_conf(config) assert (config == {}) def test_complete_config(self): config = {'some_meaningless_other_key': 'boring_value', 'krb_ccach...
class SerializableBase(abc.ABCMeta): def __new__(cls, name, bases, attrs): super_new = super(SerializableBase, cls).__new__ serializable_bases = tuple((b for b in bases if isinstance(b, SerializableBase))) has_multiple_serializable_parents = (len(serializable_bases) > 1) is_serializa...
class MarketPriceDataContainer(AbstractPlayerInfoDataContainer): DEFAULT_VAL = float('nan') galactic_market_indicator_key = 'traded_on_galactic_market' internal_market_indicator_key = 'traded_on_internal_market' def __init__(self, country_perspective, resource_name, base_price, resource_index): ...
class NavierStokesPressureCorrection(object): def __init__(self, L, prefix=None): self.L = L self.pc = p4pyPETSc.PC().create() if prefix: self.pc.setOptionsPrefix(prefix) self.pc.setFromOptions() self.hasNullSpace = True self.nsp = p4pyPETSc.NullSpace().cr...
() def create_multiple(doctype, docname): if ((not doctype) or (not docname)): frappe.throw(_('Sales Invoice or Patient Encounter is required to create Lab Tests'), title=_('Insufficient Data')) lab_test_created = False if (doctype == 'Sales Invoice'): lab_test_created = create_lab_test_from...
(scope='session') def commit_search_cls(es_version): if (es_version >= (7, 2)): interval_kwargs = {'fixed_interval': '1d'} else: interval_kwargs = {'interval': 'day'} class CommitSearch(FacetedSearch): index = 'flat-git' fields = ('description', 'files') facets = {'fi...
.skipif((not has_mxnet), reason='needs MXNet') .parametrize('data,n_args,kwargs_keys', [(numpy.zeros((2, 3), dtype='f'), 1, []), ([numpy.zeros((2, 3), dtype='f'), numpy.zeros((2, 3), dtype='f')], 2, []), ((numpy.zeros((2, 3), dtype='f'), numpy.zeros((2, 3), dtype='f')), 2, []), ({'a': numpy.zeros((2, 3), dtype='f'), 'b...
class BoundingBoxDistanceBetween(NamedTuple): bounding_box_distance: BoundingBoxDistance bounding_box_ref_1: BoundingBoxRef bounding_box_ref_2: BoundingBoxRef def get_sort_key(self): return self.bounding_box_distance.get_sort_key() def is_better_than(self, other: Optional['BoundingBoxDistanc...
('ner.fuzzy.manual', dataset=('The dataset to use', 'positional', None, str), spacy_model=('The base model', 'positional', None, str), source=('The source data as a JSONL file', 'positional', None, str), patterns=('Phrase patterns', 'positional', None, str), label=('One or more comma-separated labels', 'option', 'l', s...
def _get_dynamic_fee_txn_intrinsic_gas(klass: Union[(DynamicFeeTransaction, UnsignedDynamicFeeTransaction)]) -> int: core_gas = calculate_intrinsic_gas(ISTANBUL_TX_GAS_SCHEDULE, klass) num_addresses = len(klass.access_list) preload_address_costs = (ACCESS_LIST_ADDRESS_COST_EIP_2930 * num_addresses) num_...
.benchmark(group='import/export') def test_benchmark_xtgregsurf_import(benchmark, tmp_path, benchmark_surface): fname = (tmp_path / 'benchmark_surface.xtgregsurf') fn = benchmark_surface.to_file(fname, fformat='xtgregsurf') surf2 = None def read(): nonlocal surf2 surf2 = xtgeo.surface_fr...
class OptionPlotoptionsScatterSonificationDefaultinstrumentoptionsMappingTremoloSpeed(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...
class OptionPlotoptionsBellcurveSonificationDefaultinstrumentoptionsMappingHighpassFrequency(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 map...
def test_comp5(): string = write_rpc_request(1, 'initialize', {'rootPath': str(test_dir)}) file_path = ((test_dir / 'subdir') / 'test_free.f90') string += comp_request(file_path, 10, 22) string += comp_request(file_path, 14, 27) string += comp_request(file_path, 28, 15) (errcode, results) = run_...
class Card(QWidget): def __init__(self, context: ListContext, row: Any, parent: Any=None): super().__init__(parent) self._context = context self._row = row image_filename = self._context.get_entry_image_filename(row) image_text = self._context.get_entry_image_text(row) ...
def log_jsonl(line_json: Any, default_level: int=logging.INFO) -> None: try: level = line_json['level'].upper() except (NameError, TypeError): level = default_level else: try: level = int(logging.getLevelName(level)) except ValueError: level = default_...
def find_cusp(a: float, b: float, lms_to_rgb: Matrix, ok_coeff: List[List[Vector]]) -> Vector: s_cusp = compute_max_saturation(a, b, lms_to_rgb, ok_coeff) (r, g, b) = oklab_to_linear_rgb([1, (s_cusp * a), (s_cusp * b)], lms_to_rgb) l_cusp = alg.nth_root((1.0 / max(max(r, g), b)), 3) c_cusp = (l_cusp * s...