code
stringlengths
281
23.7M
def get_event_stages_current() -> dict[(str, Any)]: unknown_val = next_int(1) total_sub_chapters = (next_int(2) * unknown_val) stars_per_sub_chapter = next_int(1) stages_per_sub_chapter = next_int(1) clear_progress = get_length_data(1, 1, (total_sub_chapters * stars_per_sub_chapter)) clear_progr...
def create_save_pdf(pdf_data, key, dir_path='/static/uploads/pdf/temp/', identifier=get_file_name(), upload_dir='static/media/', new_renderer=False, extra_identifiers=None): if (extra_identifiers is None): extra_identifiers = {} filedir = (current_app.config.get('BASE_DIR') + dir_path) if (not os.pa...
def test_same_windows_data_and_sources(): spacing = 1 region = (1, 3, 1, 3) coordinates = vd.grid_coordinates(region=region, spacing=spacing, extra_coords=0) sources_region = (1, 2, 1, 3) points = vd.grid_coordinates(region=sources_region, spacing=spacing, extra_coords=(- 10)) eqs = EquivalentSo...
def extractRintranstudioWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('WATTT' in item['tags']): return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=...
class TestAcceptanceNormalSearch(): def _show_search_get(self, test_client): rv = test_client.get('/database/search') assert (b'<h3 class="mb-3">Search Firmware Database</h3>' in rv.data), 'search page not rendered correctly' def _show_browse_db(self, test_client): rv = test_client.get('...
def fetch_consumption_forecast_7_days(zone_key: str='US-PJM', session: Session=Session(), target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list: if target_datetime: raise NotImplementedError('This parser is not yet able to parse past dates') if (not session): sessi...
class Migration(migrations.Migration): initial = True dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL)] operations = [migrations.CreateModel(name='Lecture', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', mode...
def zip_dir(target, directory): with zipfile.ZipFile(target, 'w') as z: for (root, _, files) in os.walk(directory): for f in files: fullpath = os.path.join(root, f) relpath = os.path.relpath(fullpath, start=directory) z.write(fullpath, arcname=relp...
def setup_knowledge_base(product_catalog: str=None): with open(product_catalog, 'r') as f: product_catalog = f.read() text_splitter = CharacterTextSplitter(chunk_size=10, chunk_overlap=0) texts = text_splitter.split_text(product_catalog) llm = OpenAI(temperature=0) embeddings = OpenAIEmbeddi...
class Module(): name: str standard_library: bool = False local_module: bool = False package: (str | None) = None top_levels: (list[str] | None) = None dev_top_levels: (list[str] | None) = None is_provided_by_dependency: (bool | None) = None is_provided_by_dev_dependency: (bool | None) = ...
class DisplayTransaction(): def __init__(self, block: Block) -> None: if ((not block) or (not block.root_field)): raise ValueError('no block') self.block: Block = block self.timestamp = (datetime.datetime.now().strftime('%H:%M:%S'),) def unsupported_call(self) -> bool: ...
.asyncio .workspace_host class TestUpdateRole(): async def test_unauthorized(self, unauthorized_dashboard_assertions: HTTPXResponseAssertion, test_client_dashboard: test_data: TestData): role = test_data['roles']['castles_visitor'] response = (await test_client_dashboard.post(f'/access-control/role...
def ros1_msgdef_to_ros2(msgdef: str) -> str: COUNT = 9999 msgdef = re.sub('^Header', 'std_msgs/Header', msgdef, COUNT, re.MULTILINE) msgdef = re.sub('^time', 'builtin_interfaces/Time', msgdef, COUNT, re.MULTILINE) msgdef = re.sub('^duration', 'builtin_interfaces/Duration', msgdef, COUNT, re.MULTILINE) ...
def main(): if Util.is_conflicting_process_running(Notify.CONFLICTING_PROCESSES): sys.exit(1) if (Util.can_obtain_lock(Updater.LOCK_FILE) is False): sys.exit(1) lock_handle = Util.obtain_lock(Notify.LOCK_FILE) if (lock_handle is None): sys.exit(1) warning_should_be_shown = No...
class TestBstMin(unittest.TestCase): def test_bst_min(self): min_bst = MinBst() array = [0, 1, 2, 3, 4, 5, 6] root = min_bst.create_min_bst(array) self.assertEqual(height(root), 3) min_bst = MinBst() array = [0, 1, 2, 3, 4, 5, 6, 7] root = min_bst.create_min_b...
class OptionPlotoptionsBulletSonificationDefaultspeechoptionsActivewhen(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, nu...
def assert_curves_approx_equal(actual_curves, expected_curves): assert (len(actual_curves) == len(expected_curves)) for (acurve, ecurve) in zip(actual_curves, expected_curves): assert (len(acurve) == len(ecurve)) for (apt, ept) in zip(acurve, ecurve): assert (apt == pytest.approx(ept...
class OptionSeriesSankeySonificationDefaultinstrumentoptionsMappingTremolo(Options): def depth(self) -> 'OptionSeriesSankeySonificationDefaultinstrumentoptionsMappingTremoloDepth': return self._config_sub_data('depth', OptionSeriesSankeySonificationDefaultinstrumentoptionsMappingTremoloDepth) def speed(...
def textbox(text, box='user', pattern_match_id=''): (image_src, instance) = replace_instance_with_image(text) style = {'max-width': '60%', 'width': 'max-content', 'padding': '5px 10px', 'border-radius': 25, 'margin-bottom': 20} if (box == 'user'): style['margin-left'] = 'auto' style['margin-...
class BaseSelector(Graphic): feature_events = ('selection',) def __init__(self, edges: Tuple[(Line, ...)]=None, fill: Tuple[(Mesh, ...)]=None, vertices: Tuple[(Points, ...)]=None, hover_responsive: Tuple[(WorldObject, ...)]=None, arrow_keys_modifier: str=None, axis: str=None, name: str=None): if (edges ...
def main(page: Page): page.title = 'Flet Colors Browser' page.window_min_width = 245 page.window_min_height = 406 page.theme_mode = 'light' page.window_width = 562 page.window_height = 720 page.splash = ProgressBar(visible=False) def change_theme(e): page.splash.visible = True ...
def test_category_delete_with_user(topic): user = topic.user forum = topic.forum category = topic.forum.category assert (user.post_count == 1) assert (forum.post_count == 1) assert (forum.topic_count == 1) category.delete([user]) assert (user.post_count == 0) category = Category.quer...
def train(batch_size, exp_name, actor_weights, critic_weights): cfg = get_configs('gpt2-medium') cfg.actor_weights = actor_weights cfg.critic_weights = critic_weights cfg.reward_model_weights = cfg.critic_weights cfg.sft_model_weights = cfg.actor_weights cfg.batch_size = batch_size cfg.total...
class BaseTypeclassFilterSet(FilterSet): name = CharFilter(lookup_expr='iexact', method='filter_name', field_name='db_key') alias = AliasFilter(lookup_expr='iexact') permission = PermissionFilter(lookup_expr='iexact') def filter_name(queryset, name, value): query = Q(**{f'{name}__iexact': value}...
class Node(ABC): def __init__(self) -> None: super().__init__() self._attrs: Dict[(str, Any)] = {'name': None, 'depth': 0, 'nop': False} def __str__(self) -> str: return pformat(self._attrs, indent=2, depth=2) def __repr__(self) -> str: return self.__str__() def pseudo_co...
_os(*metadata.platforms) def main(): if (Path(ISO).is_file() and Path(PS_SCRIPT).is_file()): print(f'[+] - ISO File {ISO} will be mounted and executed via powershell') for arg in ["'/c reg.exe add hkcu\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run /v FromISO /d test.exe /f'", "'/c SCHTASKS.exe ...
def test_missing_auth(): msg = replace(make_msg(), header=HeaderData(1, 1, V3Flags(True), 1)) with pytest.raises(usm.UnsupportedSecurityLevel) as exc: usm.verify_authentication(msg, V3(b'', None, None), usm.USMSecurityParameters(b'', 1, 1, b'', b'', b'')) exc.match('auth.*missing')
def errorfill(x, y, y_err_pos, y_err_neg=None, color=None, alpha_fill=0.25, ax=None, **kwargs): import matplotlib.pyplot as plt if (ax is None): ax = plt.gca() if (y_err_neg is None): y_err_neg = y_err_pos y_min = (np.array(y) - np.array(y_err_neg)) y_max = (np.array(y) + np.array(y_...
class OptionPlotoptionsXrangeAccessibility(Options): def description(self): return self._config_get(None) def description(self, text: str): self._config(text, js_type=False) def descriptionFormat(self): return self._config_get(None) def descriptionFormat(self, text: str): ...
def test_get_surface_from_grd3d_porosity(tmpdir, generate_plot): surf = xtgeo.surface_from_file(RTOP1) print(surf.values.min(), surf.values.max()) grd = xtgeo.grid_from_file(RGRD1, fformat='egrid') surf.values = 1700 zsurf = surf.copy() surfr = surf.copy() surf2 = surf.copy() phi = xtgeo...
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 FaucetSingleStackStringOf3DPExtLoopProtUntaggedTest(FaucetMultiDPTestBase): NUM_DPS = 3 NUM_HOSTS = 3 def test_untagged(self): self.set_up(stack=True, n_dps=self.NUM_DPS, n_untagged=self.NUM_HOSTS, switch_to_switch_links=2, use_external=True) self.verify_stack_up() (int_hosts, ...
class OptionPlotoptionsColumnSonificationTracksMappingTremoloSpeed(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 reset_fledge_remote(remote_user, remote_ip, key_path, remote_fledge_path): if (remote_fledge_path is None): remote_fledge_path = '/home/{}/fledge'.format(remote_user) subprocess.run(["{} {} {}{} 'cd {}/tests/system/python/scripts/package/ && ./reset'".format(ssh_cmd, key_path, remote_user, remote_ip...
def test_session_using_server_name_port_and_path(app, client): app.config.update(SERVER_NAME='example.com:8080', APPLICATION_ROOT='/foo') ('/') def index(): flask.session['testing'] = 42 return 'Hello World' rv = client.get('/', ' assert ('domain=example.com' in rv.headers['set-cooki...
class CampaignGroupBrandConfiguration(AbstractObject): def __init__(self, api=None): super(CampaignGroupBrandConfiguration, self).__init__() self._isCampaignGroupBrandConfiguration = True self._api = api class Field(AbstractObject.Field): brand_product_name = 'brand_product_name'...
def twist(pt: Point2D[FQP]) -> Point2D[FQ12]: if (pt is None): return None (_x, _y) = pt xcoeffs = [(_x.coeffs[0] - _x.coeffs[1]), _x.coeffs[1]] ycoeffs = [(_y.coeffs[0] - _y.coeffs[1]), _y.coeffs[1]] nx = FQ12(((([xcoeffs[0]] + ([0] * 5)) + [xcoeffs[1]]) + ([0] * 5))) ny = FQ12(((([ycoe...
class Directories(): tmp: List[str] dst: Optional[List[str]] = None tmp2: Optional[str] = None def dst_is_tmp(self) -> bool: return ((self.dst is None) and (self.tmp2 is None)) def dst_is_tmp2(self) -> bool: return ((self.dst is None) and (self.tmp2 is not None)) def get_dst_dire...
class flow_stats_request(stats_request): version = 3 type = 18 stats_type = 1 def __init__(self, xid=None, flags=None, table_id=None, out_port=None, out_group=None, cookie=None, cookie_mask=None, match=None): if (xid != None): self.xid = xid else: self.xid = None ...
class AWSGateway(): def __init__(self, region: Optional[str]=None, access_key_id: Optional[str]=None, access_key_data: Optional[str]=None, config: Optional[Dict[(str, Any)]]=None, session_token: Optional[str]=None) -> None: self.logger: logging.Logger = logging.getLogger(__name__) self.region = regi...
class Downsample2D(nn.Module): def __init__(self, channels, use_conv=False, out_channels=None, padding=1, name='conv'): super().__init__() self.channels = channels self.out_channels = (out_channels or channels) self.use_conv = use_conv self.padding = padding stride = ...
class EchoAction(Action): request_schema = fields.SchemalessDictionary() response_schema = fields.Dictionary({'request_body': fields.SchemalessDictionary(), 'request_context': fields.SchemalessDictionary(), 'request_switches': fields.List(fields.Integer()), 'request_control': fields.SchemalessDictionary()}) ...
.parametrize('value,is_valid', ((hex(((2 ** 256) - 1)), True), (hex((2 ** 256)), False))) def test_validate_inbound_storage_slot_integer_value_at_limit(value, is_valid): if (not is_valid): with pytest.raises(ValidationError, match='Value exceeds maximum 256 bit integer size'): DefaultValidator.v...
def test_image_to_video() -> None: commands = [sys.executable, 'run.py', '-s', '.assets/examples/source.jpg', '-t', '.assets/examples/target-1080p.mp4', '-o', '.assets/examples', '--trim-frame-end', '10', '--headless'] run = subprocess.run(commands, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) assert (...
def fill_vm_test(filler: Dict[(str, Any)], *, call_creates: Any=None, gas_price: Union[(int, str)]=None, gas_remaining: Union[(int, str)]=0, logs: Iterable[Tuple[(bytes, Tuple[(int, ...)], bytes)]]=None, output: bytes=b'') -> Dict[(str, Dict[(str, Any)])]: test_name = get_test_name(filler) test = filler[test_na...
def load_lookup_from_config(config: Optional[dict], download_manager: DownloadManagerProtocol) -> Optional[TextLookUp]: if (not config): return None paths = config.get('paths', []) LOGGER.info('loading lookup from: %r', paths) return MergedTextLookUp([load_lookup_from_path(path, download_manager...
class RandomStringGenerator(): script = None def __init__(self, name, regex): self.name = name self.elements = [] self.total = 1 if regex: self._find_elements(regex) def __repr__(self): return '<evennia.contrib.utils.random_string_generator.RandomStringGen...
class Backing(models.Model): resource = models.ForeignKey(Resource, related_name='backings') money_account = models.ForeignKey(Account, related_name='+') drft_account = models.ForeignKey(Account, related_name='+') subscription = models.ForeignKey(Subscription, blank=True, null=True) users = models.M...
def convert_values_to_image(image_values, display=False): image_array = np.asarray(image_values) image_array = image_array.reshape(32, 32).astype('uint8') image_array = np.flip(image_array, 0) image_array = rotate(image_array, (- 90)) new_image = Image.fromarray(image_array) if (display == True)...
def download_literal(file_access: FileAccessProvider, var: str, data: Literal, download_to: typing.Optional[pathlib.Path]=None): if (data is None): print(f'Skipping {var} as it is None.') return if data.scalar: if (data.scalar and (data.scalar.blob or data.scalar.structured_dataset)): ...
def dispaly_best_test_stat(conf, coordinator): current_time = time.strftime('%Y-%m-%d %H:%M:%S') conf.logger.log_metric(name='runtime', values={'time': current_time, 'comm_round': conf.graph.comm_round, 'best_perfs': coordinator()}, tags={'split': 'test', 'type': 'aggregated_model'}, display=False) for (nam...
class BaseDrive(DatClass): drive_id: str = None used_size: int = None total_size: int = None drive_name: str = field(default=None, repr=False) owner: str = field(default=None, repr=False) description: str = field(default=None, repr=False) drive_type: str = field(default=None, repr=False) ...
class OptionPlotoptionsOrganizationSonificationDefaultinstrumentoptionsMappingTremoloDepth(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...
class OptionSeriesDumbbellSonificationDefaultspeechoptionsMappingPitch(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('undefined') def mapTo(self, text: ...
class AuthExtension(Extension): namespace = 'auth' default_config = {'models': {'user': AuthUser, 'group': AuthGroup, 'membership': AuthMembership, 'permission': AuthPermission, 'event': AuthEvent}, 'hmac_key': None, 'hmac_alg': 'pbkdf2(2000,20,sha512)', 'inject_pipe': False, 'log_events': True, 'flash_messages...
def parse_channels(color: list[str], boundry: tuple[(Channel, ...)], scaled: bool=False) -> tuple[(Vector, float)]: channels = [] alpha = 1.0 length = len(boundry) for (i, c) in enumerate(color, 0): c = c.lower() if (i < length): bound = boundry[i] if (bound.flags...
def plot_surface_append(viz, env, withnames=False): win = plot_surface_basic(viz, env, withnames) viz.heatmap(X=np.outer(np.arange(6, 9), np.arange(1, 11)), win=win, update='appendRow', opts=dict(rownames=(['y6', 'y7', 'y8'] if withnames else None)), env=env) viz.heatmap(X=np.outer(np.arange(1, 9), np.arang...
class GracefulKiller(): signal_names = {signal.SIGINT: 'SIGINT', signal.SIGTERM: 'SIGTERM'} def __init__(self): self.kill_now = False signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) def exit_gracefully(self, signum, frame): ...
class TestQuarterlyFeatures(): .parametrize('data', datas) .parametrize(['tickers', 'columns', 'quarter_counts', 'max_back_quarter', 'min_back_quarter', 'stats'], [(['AAPL', 'TSLA'], ['ebit'], [2], 10, 0, None), (['NVDA', 'TSLA'], ['ebit'], [2, 4], 5, 2, {'mean': np.mean}), (['AAPL', 'NVDA', 'TSLA', 'WORK'], ['...
def kong_61_2007(): dlf = DigitalFilter('Kong 61', 'kong_61_2007') dlf.base = np.array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.0, 1., 1., 1., 1., 1., 2., 2., 2., 3., 3., 3., 4., 5., 5., 6., 7., 8., 9., 10., 12., 13., 15., 17., 20...
def test_set_nonblocking(): sock = _orig_sock.socket(socket.AF_INET, socket.SOCK_DGRAM) fileno = sock.fileno() orig_flags = fcntl.fcntl(fileno, fcntl.F_GETFL) assert ((orig_flags & os.O_NONBLOCK) == 0) greenio.set_nonblocking(sock) new_flags = fcntl.fcntl(fileno, fcntl.F_GETFL) assert ((new_...
class ExternalProjectAccessRulesEngine(bre.BaseRulesEngine): def __init__(self, rules_file_path, snapshot_timestamp=None): super(ExternalProjectAccessRulesEngine, self).__init__(rules_file_path=rules_file_path) self.rule_book = None def build_rule_book(self, global_configs=None): self.ru...
def compress_scripts(source_path: str, destination: str, module_name: str): with tempfile.TemporaryDirectory() as tmp_dir: destination_path = os.path.join(tmp_dir, 'code') visited: typing.List[str] = [] copy_module_to_destination(source_path, destination_path, module_name, visited) t...
class Wrapper(object): def __init__(self, estimator, method): (n_classes, n_features) = estimator.theta_.shape model = numpy.ndarray(shape=(n_classes, n_features, 3), dtype=float) if hasattr(estimator, 'var_'): variance = estimator.var_ elif hasattr(estimator, 'sigma_'): ...
class HCT(LChish, Space): BASE = 'xyz-d65' NAME = 'hct' SERIALIZE = ('--hct',) WHITE = WHITES['2deg']['D65'] ENV = Environment(WHITE, ((200 / math.pi) * lstar_to_y(50.0, util.xy_to_xyz(WHITE))), (lstar_to_y(50.0, util.xy_to_xyz(WHITE)) * 100), 'average', False) CHANNEL_ALIASES = {'lightness': 't...
class PluginManagerBase(object): def namespaces(self): return (self.app.config['plugin_namespaces'] if self.app else []) def __init__(self, app=None): if (app is None): self.clear() else: self.init_app(app) def init_app(self, app): self.app = app ...
class ItemRemoveHelper(): def __init__(self, ctx: Context, ignore_non_vendor: bool=False) -> None: self._ctx = ctx self._agent_config = ctx.agent_config self._ignore_non_vendor = ignore_non_vendor def get_agent_dependencies_with_reverse_dependencies(self) -> Dict[(PackageId, Set[PackageI...
('foremast.iam.create_iam.attach_profile_to_role') ('foremast.iam.create_iam.boto3.session.Session') ('foremast.iam.create_iam.construct_policy') ('foremast.iam.create_iam.get_details') ('foremast.iam.create_iam.get_properties') ('foremast.iam.create_iam.resource_action') def test_create_iam_resources(resource_action, ...
class StringRemovePrefix(StringTransform): def __init__(self, prefix: str, *, reversible: bool=True): super().__init__(reversible) self.prefix = prefix def _apply(self, string: str) -> str: return re.sub(f'^{re.escape(self.prefix)}', '', string) def _revert(self, string: str) -> str:...
class LeaderAssignor(Service, LeaderAssignorT): def __init__(self, app: AppT, **kwargs: Any) -> None: Service.__init__(self, **kwargs) self.app = app async def on_start(self) -> None: if (not self.app.conf.topic_disable_leader): (await self._enable_leader_topic()) async d...
def greet_user(): path = Path('username.json') if path.exists(): contents = path.read_text() username = json.loads(contents) print(f'Welcome back, {username}!') else: username = input('What is your name? ') contents = json.dumps(username) path.write_text(conte...
def extractZettairyouikitransWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Mushoku Tensei Redundancy Chapters', 'Mushoku Tensei Redundancy', 'translated'), ('PRC...
def results(): global computer_points, user_points, flag flag = 0 if (computer_choice == 'Snake'): if ((user_choice == 's') or (user_choice == 'snake')): print(yellow('AWWW...!!'), emojize(':neutral_face:'), yellow('\nTWO SNAKES HAD BITTEN EACH OTHER :/')) elif ((user_choice == '...
def parse_rtttl(rtttl_str, strict_note_syntax=False): rt = rtttl_str.split('=') pp = (- 1) try: pp = rt[3].find(':') except: return {'title': False, 'notes': False} if (pp == (- 1)): rt[3] = rt[3].replace(',', ':', 1) rtttl_str = ((((((rt[0] + '=') + rt[1]) + '=') + r...
class TestTVTKBase(unittest.TestCase): def test_tvtk_name(self): v_name = ['vtkFooBar', 'vtkXMLDataReader', 'vtk3DSReader', 'vtk2000Bug'] t_name = ['FooBar', 'XMLDataReader', 'ThreeDSReader', 'Two000Bug'] for (i, vn) in enumerate(v_name): tn = get_tvtk_name(vn) self.a...
def test_same_reaching_condition_but_not_groupable(task): vertices = [BasicBlock(0, instructions=[Branch(Condition(OperationType.less, [variable(name='a'), Constant(10)]))]), BasicBlock(1, instructions=[Branch(Condition(OperationType.less, [variable(name='b'), variable(name='d')]))]), BasicBlock(2, instructions=[As...
class Migration(migrations.Migration): dependencies = [('frontend', '0055_auto__1335')] operations = [migrations.AddField(model_name='measure', name='denominator_type', field=models.CharField(default='CHANGEME', max_length=20), preserve_default=False), migrations.AddField(model_name='measure', name='numerator_t...
def grid_heads(draw, gridtype=types_of_grid, nx=indices, ny=indices, nz=indices, index=st.integers(min_value=0, max_value=5), coordinatesystem=coordinate_types): return xtge.GridHead(draw(gridtype), draw(nx), draw(ny), draw(nz), draw(index), 1, 1, draw(coordinatesystem), draw(st.tuples(indices, indices, indices)), ...
def create_system_app(param: Dict) -> SystemApp: app_config = param.get('app_config', {}) if isinstance(app_config, dict): app_config = AppConfig(configs=app_config) elif (not isinstance(app_config, AppConfig)): raise RuntimeError('app_config must be AppConfig or dict') test_app = FastAP...
class Migration(migrations.Migration): dependencies = [('admin_interface', '0006_bytes_to_str')] operations = [migrations.AddField(model_name='theme', name='favicon', field=models.FileField(blank=True, help_text='(.ico|.png|.gif - 16x16|32x32 px)', upload_to='admin-interface/favicon/', verbose_name='favicon'))]
def dashed_to_camel(dashed_data): data = {} for (key, value) in dashed_data.items(): if isinstance(value, dict): value = dashed_to_camel(value) dashed_key = dashed_to_camel_regex.sub((lambda match: match.group(1).upper()), key) data[dashed_key] = value return data
class NpmjsBackendtests(DatabaseTestCase): def setUp(self): super().setUp() create_distro(self.session) self.create_project() def create_project(self): project = models.Project(name='request', homepage=' backend=BACKEND) self.session.add(project) self.session.comm...
class Jzazbz(Labish, Space): BASE = 'xyz-d65' NAME = 'jzazbz' SERIALIZE = ('--jzazbz',) CHANNELS = (Channel('jz', 0.0, 1.0), Channel('az', (- 0.5), 0.5, flags=FLG_MIRROR_PERCENT), Channel('bz', (- 0.5), 0.5, flags=FLG_MIRROR_PERCENT)) CHANNEL_ALIASES = {'lightness': 'jz', 'a': 'az', 'b': 'bz', 'j': ...
def find_gridprop_from_init_file(init_filelike, names: Union[(List[str], Literal['all'])], grid, fracture: bool=False) -> List[Dict]: init_stream = (not isinstance(init_filelike, (str, Path))) if init_stream: orig_pos = init_filelike.tell() get_actnum_from_porv(init_filelike, grid) if init_strea...
class _MakeStyle(Style): def __init__(self, style): super().__init__(style) def foreground(self, color): colors = {'default': 39, 'black': 30, 'red': 31, 'green': 32, 'yellow': 33, 'blue': 34, 'magenta': 35, 'cyan': 36, 'light_gray': 37, 'dark_gray': 90, 'light_red': 91, 'light_green': 92, 'ligh...
def cof(t): if (t.shape[0] == 1): return numpy.array([[1.0]]) elif (t.shape[0] == 2): tcof = numpy.zeros(t.shape, 'd') tcof[(X, X)] = t[(Y, Y)] tcof[(X, Y)] = (- t[(Y, X)]) tcof[(Y, X)] = (- t[(X, Y)]) tcof[(Y, Y)] = t[(X, X)] return tcof else: ...
class RLEIterator(): def __init__(self, A: List[int]): self.A = A self.curr = 1 self.start = 0 def next(self, n: int) -> int: while (n > 0): if ((self.curr - 1) < len(self.A)): remain = (self.A[(self.curr - 1)] - self.start) else: ...
def get_wealth_if_needed(address: Address, fetchai_api: FetchAIApi=None): if (fetchai_api is None): fetchai_api = make_ledger_api(FetchAICrypto.identifier, **FETCHAI_TESTNET_CONFIG) balance = fetchai_api.get_balance(address) if (balance == 0): FetchAIFaucetApi().get_wealth(address) t...
def test_configure(la: LogicAnalyzer, uart: UART): baudrate = 1000000 uart.configure(baudrate) la.capture(1, block=False) uart.write_byte(WRITE_DATA) la.stop() (txd2,) = la.fetch_data() start_to_stop = 9 period = ((txd2[(- 1)] - txd2[0]) / start_to_stop) assert (((period * MICROSECON...
def client_error(message, exc: Exception=None, debug=None, ctx: click.Context=None, file=None, err=None) -> NoReturn: config_debug = (True if (ctx and ctx.ensure_object(dict) and (ctx.obj.get('debug') is True)) else False) debug = (debug if (debug is not None) else config_debug) if debug: click.echo...
class OptionSeriesWaterfallLabel(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....
class LayoutShape(DataClass): def add_path(self, points, color: str=None): self._attrs.update({'type': 'path', 'path': points}) self.fillcolor = (color or self.page.theme.warning.light) return self def add_line(self, x, y, x1, y1, opacity=0.2, color=None): self._attrs.update({'ty...
(scope='function') def sql_server() -> Iterator[str]: d = tempfile.TemporaryDirectory() try: db_path = os.path.join(d.name, 'tracks.db') with contextlib.closing(sqlite3.connect(db_path)) as con: con.execute('create table tracks (TrackId bigint, Name text)') con.execute("i...
def generate_launch_description(): ld = LaunchDescription() config = os.path.join(get_package_share_directory('f1tenth_gym_ros'), 'config', 'sim.yaml') config_dict = yaml.safe_load(open(config, 'r')) has_opp = (config_dict['bridge']['ros__parameters']['num_agent'] > 1) teleop = config_dict['bridge']...
def extractFluffystranslationsBlogspotCom(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,...
def catch_exception(func): (func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except AIFlowRpcServerException as e: return Response(return_code=str(e.error_code), error_msg=traceback.format_exc()) except Exception as ex: return Resp...
class OptionSeriesArcdiagramSonificationTracksMappingFrequency(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 test_periodic(shapify, direction, space): mesh = UnitSquareMesh(3, 4) mesh_p = PeriodicUnitSquareMesh(3, 4, direction=direction) ele = shapify(FiniteElement(space[0], mesh.ufl_cell(), space[1])) V = FunctionSpace(mesh, ele) V_p = FunctionSpace(mesh_p, ele) f = Function(V) f.interpolate(g...
class OptionSeriesBarDataAccessibility(Options): def description(self): return self._config_get(None) def description(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(flag, js_...
def get_software_names(yara_file_path): scanned_software = [] for line in get_string_list_from_file(yara_file_path): line = line.strip() parts_of_line = line.split('=') if (parts_of_line[0].strip() == 'software_name'): software_name = parts_of_line[1].strip() soft...