content
stringlengths
22
815k
id
int64
0
4.91M
def modified_action(elem, sony, paperpile, modtime, *, dry_run=True, verbose=True): """Perform appropriate action when a file has been modified. Parameters ---------- elem : db element (dictionary) sony, paperpile : string The paths to the Sony Box file and corresponding...
65,400
def blink() -> str: """Returns 'bright/blink text' ANSI-command string.""" return _format_rich_text(TextAttributes.blink)
65,401
def CachedPropertyParamRegistry(): # noqa: N802 """Registry with cached property and a keyword parameter.""" class CachedPropertyParamRegistry: registry = Registry('kwparam', cached_property=True) return CachedPropertyParamRegistry
65,402
def map_to_representative(state, lp_metric, representative_states, n_representatives, min_dist, scaling, accept_new_repr): """ Map state to representative s...
65,403
def chimera(args): """ %prog chimera bamfile Parse BAM file from `bwasw` and list multi-hit reads and breakpoints. """ import pysam from maize.utils.natsort import natsorted p = OptionParser(chimera.__doc__) p.set_verbose() opts, args = p.parse_args(args) if len(args) != 1: ...
65,404
def withRequest(f): """ Decorator to cause the request to be passed as the first argument to the method. If an I{xmlrpc_} method is wrapped with C{withRequest}, the request object is passed as the first argument to that method. For example:: @withRequest def xmlrpc_echo(self, r...
65,405
def add_xy_pos_to_strides(tracks, lr_paw_xy, rr_paw_xy): """ add X/Y paw strike positions to strides """ for track in tracks: for stride in track.strides: if stride.rr_paw_strike_frame is not None: stride.rr_paw_strike_xy = rr_paw_xy[stride.rr_paw_strike_frame, :] ...
65,406
def get_functional_enrichment(enrichment_file, go, remove_parents=False, only_biological_processes=False, only_slim=False, logodds_cutoff=0): """ Read functional enrichment file. If there are multiple functional enrichment analyses it takes the comment as the key and returns a dictionary con...
65,407
def test_can_work_on_iframes_by_webelement(get_new_browser, browser_name): """can work on iframes and switch back to the page""" browser = get_new_browser(browser_name) browser.visit(EXAMPLE_APP) elem = browser.find_by_id('iframemodal').first with browser.get_iframe(elem) as frame: value =...
65,408
def analysis_line_linearity(target_list, measure_list_mm, boundary_index_list, linearity_list): """ analysis line boundary/center linearity """ boundary_max_linearity = [0, [0, 0]] center_max_linearity = [0, [0, 0]] for i in range(len(linearity_list)): for j in range(len(linearity_list...
65,409
def main(session): """Perform queries and print the result.""" # Query all movies, using the session factory movies = session.query(Movie).all() # Print movies' details print("\n### All movies:") for movie in movies: print(f"{movie.title} was released on {movie.release_date}") print...
65,410
def has_pipeline(model): """ Tells if a model contains a pipeline. """ return any(map(lambda x: isinstance(x[1], Pipeline), enumerate_model_names(model)))
65,411
def add_permission(lambda_client, function_name, statement_id, action, principal, source_arn, source_account=None): """https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html#Lambda.Client.add_permission""" kwargs = { "FunctionName": function_name, "StatementId": ...
65,412
def dither_spikes(spiketrain, dither, n_surrogates=1, decimals=None, edges=True, refractory_period=None): """ Generates surrogates of a spike train by spike dithering. The surrogates are obtained by uniformly dithering times around the original position. The dithering is performed ind...
65,413
def dist(): """Calculate advantage/disadvantage probability distributions.""" pa = np.zeros(20) pd = np.zeros(20) for k in range(20): for i in range(20): for j in range(20): if max(i, j) >= k: pa[k] += 1.0 if min(i, j) >= k: ...
65,414
def modelconfigurationsetups_id_delete(id, user=None): # noqa: E501 """Delete an existing ModelConfigurationSetup Delete an existing ModelConfigurationSetup (more information in https://w3id.org/okn/o/sdm#ModelConfigurationSetup) # noqa: E501 :param id: The ID of the ModelConfigurationSetup to be retriev...
65,415
def eprint(*args, **kwargs): """ Shorthand for using print(file=sys.stderr) """ print(*args, file=sys.stderr, **kwargs)
65,416
def parse_sacct(sacct_stream): """Parse out information from sacct status output.""" rows = (line.split() for line in sacct_stream) # filter rows that begin with a SLURM job id relevant_rows = (row for row in rows if row[0].isdigit()) jobs = [convert_job(row) for row in relevant_rows] return job...
65,417
def test_atomic_decimal_fraction_digits_3_nistxml_sv_iv_atomic_decimal_fraction_digits_4_4(mode, save_output, output_format): """ Type atomic/decimal is restricted by facet fractionDigits with value 12. """ assert_bindings( schema="nistData/atomic/decimal/Schema+Instance/NISTSchema-SV-IV-ato...
65,418
def assert_almost_equal(left, right, **kwargs): """Asserts left and right are almost equal. Left and right can be scalars, series, dataframes, etc """ if isinstance(left, (ed.DataFrame, ed.Series)): left = left.to_pandas() if isinstance(right, (ed.DataFrame, ed.Series)): right = righ...
65,419
def create(profile, name, subnets, tags=None): """Create a DB subnet group. Args: profile A profile to connect to AWS with. name The name you want to give to the group. subnets A list of subnet IDs to put in the group. tags A l...
65,420
def save_mesh(mesh, name, eval_dir): """Save a mesh to disk. Args: mesh: trimesh.Trimesh, the mesh to save. name: Tensor, hash name of the mesh as recorded in the dataset. eval_dir: string, path to the directory to save the mesh. """ cls_name, obj_name = mesh_name_helper(name) cls_dir = path.join...
65,421
def format_output(template_string): """ Formats the value according to template_string using django's Template. Example:: @allow_tags @format_output('{{ value|urlize }}') def object_url(self, obj): return obj.url """ tpl = Template(template_string) def dec...
65,422
def calc_init_centroid(images, num_spixels_width, num_spixels_height): """ calculate initial superpixels Args: images: torch.Tensor A Tensor of shape (B, C, H, W) num_spixels_width: int A number of superpixels in each column num_spixels_height: int ...
65,423
def slugify_camel_iso(old_string: str) -> str: """Slugify a string with camel case, underscores and ISO date/time formats. >>> slugify_camel_iso("some name Here 2017_12_30") 'Some_Name_Here_2017-12-30' >>> slugify_camel_iso("DONT_PAY_this-bill-10-05-2015") 'Dont_Pay_This_Bill_2015-05-10' >>> sl...
65,424
def test_list_unsigned_byte_enumeration_3_nistxml_sv_iv_list_unsigned_byte_enumeration_4_4(mode, save_output, output_format): """ Type list/unsignedByte is restricted by facet enumeration. """ assert_bindings( schema="nistData/list/unsignedByte/Schema+Instance/NISTSchema-SV-IV-list-unsignedByte-...
65,425
def showSegModelInference(model, img_path, display=True): """ @func img_path -> 3 np arrays of results label assign refer https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/helpers/labels.py """ img = Image.open(img_path) img_p = np.array(img) img_p = cv2.resize(...
65,426
def load_yaml(path: Union[str, Path], pure: bool = False) -> dict: """config.yaml file loader. This function converts the config.yaml file to `dict` object. Args: path: .yaml configuration filepath pure: If True, just load the .yaml without converting to EasyDict and exclude extr...
65,427
def get_current_year(): """ return: the current year. """ from datetime import date return date.today().isocalendar()[0]
65,428
def _run_toplevel(config, config_file, work_dir, parallel, fc_dir=None, run_info_yaml=None): """ Run toplevel analysis, processing a set of input files. config_file -- Main YAML configuration file with system parameters fc_dir -- Directory of fastq files to process run_info_yaml --...
65,429
def seed(request): """ Sets the seed for in numpy.random. Return the seed value, so it can be used by plots as part of the label. """ seed = request.param np.random.seed(seed) return seed
65,430
def show( vector_data: VectorData, show_axes: bool, show_grid: bool, show_pen_up: bool, hide_legend: bool, colorful: bool, unit: str, ): """ Display the geometry using matplotlib. By default, only the geometries are displayed without the axis. All geometries are displayed wi...
65,431
def denoise_timeseries(timeseries_data, fsampling, fmin=2, fmax=45): """Filters timeseries_data with a band pass filter designed with cutoff frequencies [fmin, fmax] Args: timeseries_data (dict): [N x t time series data, with N brain regions for source localized data or ...
65,432
def make_roof(): """this function makes the roof """ lb.filling() lb.begin_fill() lb.fillcolor("red") lb.penup() lb.goto(-100, 100) lb.pd() lb.right(-230) lb.forward(150) lb.rt(45) lb.fd(410) lb.rt(135) lb.forward(180) lb.end_fill() lb.filling() lb.begin_...
65,433
def attempt_all(function, items): """ Call `function` on each item in `items`, catching any exceptions. Yields an iterator of (item, exception) for each item that raised an exception. """ for i in items: try: function(i) except Exception as e: yield i, e
65,434
def _disable_nodes(graph): """ Toggle disable on selected nodes. """ graph.disable_nodes(graph.selected_nodes())
65,435
def main(): """Register all test dataset DRS Objects on local Starter Kit DRS server""" add_bed_to_drs() add_ref_to_drs() add_1k_genomes_highcov_dataset_to_drs()
65,436
def get_def_port(ports: List[int], default: int) -> int: """Returns default or first unused in system and in run configs port.""" port = default if len(ports) > 0: ports.sort() port = ports[-1] + 1 while is_open_port(port): port += 1 return port
65,437
def _prepare_lookup(keywords_file=None, stopwords_file=None, ngram_size=None, lemmatize=False, stemmer=None): # pylint: disable=too-many-arguments """Prepare resources for keywords lookup. :param keywords_file: keywords file to be used :param stopwords_file: stopwords file to be use...
65,438
def test_list_unsigned_long_max_length_nistxml_sv_iv_list_unsigned_long_max_length_1_4(mode, save_output, output_format): """ Type list/unsignedLong is restricted by facet maxLength with value 5. """ assert_bindings( schema="nistData/list/unsignedLong/Schema+Instance/NISTSchema-SV-IV-list-unsign...
65,439
def scratch_then_cache(request): """# remove the tests/temp folder if it already exists so we start fresh with tests""" # request is a special parameter known to pytest. It passes whatever is in # params=do. Ids are there to give the test a human readable name. if request.param: dirs = [ ...
65,440
def statistics(r, b=None, rf=None, freq=12): """ Generate the portfolio return matrix from the monthly P&L including the following: Total return: Annual Return: Volatility Sharpe Ratio Percentage Positive Month/Day MDD Skewness Kurtosis If b is...
65,441
def weightedDLTmatrix(Ps,weight): """ Input: Ps = [1,1,N,5 (X,Y,Z,x,y) ], Weights = [1,N] P_world-3Dpoint (N,[X,Y,Z]) p_img-2Dpoint (N,[x,y]) Weight (N,) OutpuT: weighted DLT matrix A^T*W*A """ # DLT matrix N = Ps.shape[2] A = torch.zeros([2*N,12]) W = torch...
65,442
def build_theory(meths,tss, zedoptions, oneoptions, adiabatic): """ Builds theory.dat meth[0] is module, meth[1] is program, and meth[2] is theory/basis """ theory = '' tsopt = ' opt=(ts,calcfc,noeig,intern,maxcyc=50) \n ' rzpopt = ' opt=(' + zedoptions + ') \n ' rpopt = ' opt=(' ...
65,443
def brute_xor_file(filename: str, keylen: int, verbose: bool = False) -> (int, str, str): """Applies the brute force algorithm on an entire file where each file has been XOR encrypted line by line to find which line was encrypted and what the decrypted message reads as. :param filename The file containi...
65,444
def game(request, event_id): """Game view. If the request type is POST and the user is logged in, save the user score and redirect the user to the profile page. Otherwise, display the game. Arguments: request - Django object containing request information. event_id - ID of event to use. R...
65,445
def hello(): """Return a friendly HTTP greeting.""" return 'Deep Neural Network (DNN) heart failure prediction'
65,446
def generate_shard_prune_playbook(migration): """Create a playbook for deleting unused files. :returns: List of nodes that have files to remove """ full_plan = {plan.db_name: plan for plan in migration.shard_plan} _, deletable_files_by_node = get_node_files(migration.source_couch_config, full_plan) ...
65,447
def course_instances_from(results_page_tree, subject_code): """Takes the ElementTree of a course search results HTML page and the subject code searched for. Returns a list of course instances on the page and the URL of the next search results page (or None if this was the last page)""" next_page_url = next_...
65,448
def test_note_exists(mk_creoson_post_dict, mk_getactivefile): """Test exists.""" c = creopyson.Client() result = c.note_exists(file_="file", name="name") assert isinstance(result, (bool)) result = c.note_exists(name=["name", "other name"]) assert isinstance(result, (bool))
65,449
def get_binned_motifs_iterator(fobj): """ :param fobj: :return: """ rdl = _read_ovl_line init = rdl(fobj.readline()) curr_chrom = init[0] curr_index = init[1] fobj.seek(0) collect = col.Counter() for line in fobj: if not line: continue chrom, index...
65,450
def calc_cpds(lcfile1, lcfile2, fftlen, save_dyn=False, bintime=1, pdsrebin=1, outname='cpds' + MP_FILE_EXTENSION, normalization='Leahy', back_ctrate=0., noclobber=False): """Calculate the CPDS from a pair of input lig...
65,451
def parse_mitx_json_data(course_data, force_overwrite=False): """ Main function to parse edx json data for one course Args: course_data (dict): The JSON object representing the course with all its course runs force_overwrite (bool): A boolean value to force the incoming course data to overw...
65,452
def add_packages_to_bundle(bundle_working_dir, cli_dist_dir): """ Add the CLI packages (and all dependencies) to bundle """ packages_dest = os.path.join(bundle_working_dir, 'packages') _create_dir(packages_dest) cli_packages = os.listdir(cli_dist_dir) for p in cli_packages: shutil.copy(os.pa...
65,453
def num_of_rows(infile): """ Compute the number of rows. Args: file: Infile file. Returns: The number of rows. """ numrows = 0 if metadata['format'] == JSON: with open(infile, 'r') as fp: numrows = len(json.load(fp)) # Use len() function to get length of dic...
65,454
def uoc_hill_genkey(size): """ Hill Key Generation :size: matrix size :return: size x size matrix containing the key """ matrix = [] L = [] # Relleno una lista con tantos valores aleatorios como elementos a rellenar en la matriz determinada por size (size * size) for x in range(s...
65,455
def study_demo(request): """ Redirect to a list to study (the first public one). """ lis = TranslationsList.objects.filter(public = True).order_by('pk') if not lis: return notification(request, 'There is no public list to study, sorry...') return redirect(reverse('study_list_ask', kwargs = {'pk': lis[0].pk, 's...
65,456
def api_config(): """Build api endpoint for config data.""" read_config(config_file, srv_config) resp = make_response(jsonify(srv_config)) resp.headers['Server-IP'] = socket.gethostbyname(localhost) return resp
65,457
def is_youtube_video(link): """Identify youtube video's.""" content = urllib2.unquote(link).decode('utf8') # shortened YT url result = re.search('http://youtu.be', content, flags=re.IGNORECASE) if result is None: result = re.search('www.youtube.com', content, flags=re.IGNORECASE) if ...
65,458
def ColorPicker( concise: bool = False, description: str = "", description_tooltip: str = None, disabled: bool = False, layout: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]] = {}, style: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_description.DescriptionStyl...
65,459
def sample_parameters_binary(boundaries): """ sample parameter values from the boundary conditions for binary encoding Parameters ---------- 'boundaries' (pandas df): boundary conditions for model parameters'ncpu' (int): number of cpu's to be used for computation, -1 is all cpu available o...
65,460
def print_help(): """Print help screen of this executable.""" print(""" Usage: {0} [options] [--] <command> [options of command] {0} help <command>... {0} [options] Description: This executable is a wrapper for the MIRTK commands. The name of the command to execute must be given as first argument. A...
65,461
def deepmerge(a, b): """ Merge dict structures and return the result. >>> a = {'first': {'all_rows': {'pass': 'dog', 'number': '1'}}} >>> b = {'first': {'all_rows': {'fail': 'cat', 'number': '5'}}} >>> import pprint; pprint.pprint(deepmerge(a, b)) {'first': {'all_rows': {'fail': 'cat', 'number'...
65,462
def _element_to_string(element): """Get a string that can be used to recognize the element. If the element has an id, use it as it will uniquely identify the element. Otherwise, fall back to the text. If it has no text, to the value. Fallback to outerHTML as a last resort. """ element_id = ele...
65,463
def get_package_list(only_debuggable=False): """Return list of 3rd packages.""" post_cmd = '' cmd = 'pm list packages -3 | sort | sed \'s/^package://\'{post_cmd}' if only_debuggable: # This post command is executing slowly. Can we do any better? post_cmd = ' | xargs -n1 sh -c \'if run-...
65,464
def render_emosqpmodule(variables, output): """ Render emosqpmodule.c file """ python_ext_name = variables['python_ext_name'] f = open(os.path.join(files_to_generate_path, 'emosqpmodule.c')) filedata = f.read() f.close() filedata = filedata.replace("PYTHON_EXT_NAME", str(python_ext_na...
65,465
def script_path(): """Return path to CGI script.""" result = os.getenv('PATH_TRANSLATED') if '.py' in result: result = os.path.dirname(result) return result
65,466
def on_session_ended(session_ended_request, session): """ Called when the user ends the session. Is not called when the skill returns should_end_session=true """ logging.info("on_session_ended requestId=" + session_ended_request['requestId'] + ", sessionId=" + session['sessionId']) ...
65,467
def clean_data(text): """Fixes broken symbols in poems. :param text: Broken text that has to be fixed :return: Text with correct UTF8 symbols""" corrections = { 'ó': 'ó', 'ż': 'ż', 'Ä™': 'ę', 'Å‚': 'ł', 'Å›': 'ś', 'ć': 'ć', 'Ä…': 'ą', '...
65,468
def model_instance_diff(old, new, serializer_mapping=None): """ Calculate the differences between two model instances. One of the instances may be None (i.e., a newly created model or deleted model). This will cause all fields with a value to have changed (from None). serializer_mapping are used to dete...
65,469
def _dataframe_reduce_columns_codegen_head(func_name, func_params, series_params, df): """ Example func_text for func_name='head' columns=('float', 'string'): def _df_head_impl(df, n=5): data_0 = df._data[0][0] series_0 = pandas.Series(data_0) result_0 = series_0.head(n=n) ...
65,470
def translate_rev_to_sha(llvm_config: LLVMConfig, rev: Rev) -> str: """Translates a Rev to a SHA. Raises a ValueError if the given Rev doesn't exist in the given config. """ branch, number = rev if branch == 'master': if number < base_llvm_revision: return translate_prebase_rev_to_sha(llvm_config,...
65,471
def cmd(ctx, log_level: str, verbosity_level: int, locale: str, seed: int): """ Faker for Elasticsearch """ ctx.obj[Context.LOG_LEVEL] = LogLevel.INFO if log_level is None else log_level ctx.obj[Context.VERBOSITY_LEVEL] = verbosity_level ctx.obj[Context.LOCALE] = locale ctx.obj[Context.SEED...
65,472
def get_env_config_path(): """return ocio config path from the environment """ blender_config_path = envconfig().get_blender_ocio_config() ociopath = envconfig().getenv('OCIO', blender_config_path) return ociopath
65,473
def uuid4(): """ Generates uuid4's exactly like Python's uuid.uuid4() function. When ``fix_random_seed()`` is called, it will instead generate deterministic IDs. """ if _lhotse_uuid is not None: return _lhotse_uuid() return uuid.uuid4()
65,474
def generate_DDs(experiment_dir, asdp_dir, track_fpaths, dd_config): """ Create and save a diversity descriptor for a HELM experiment Parameters ---------- experiment_dir: str Path to experiment directory asdp_dir: str Path to ASDP directory where outputs will be saved track_fpa...
65,475
def prominent_points_new(x,y, features=["min","max","turnL","turnR","edgeL","edgeR","samples"], d2Lim=0, d3Lim=0, d4Lim=0): """ generate an ordered list of dict with prominent points entries each entry carries several infos { type:min,max, ... index: the index ...
65,476
def avatar_url(user, size=50, gravatar_only=False): """ A template tag that receives a user and size and return the appropriate avatar url for that user. Example usage: {% avatar_url request.user 50 %} """ if ( not gravatar_only and hasattr(user, "wagtail_userprofile") a...
65,477
def patch_location(r2, finfo, bb, from_addr, targets): """Generates patches for the basic block. Starts at the end and goes back as many bytes as needed. Returns patches as [(address, patch_bytes, r2 patch argument, r2 patch cmd""" dbg = False if dbg: print('patch_location(_, {}, {:x}, {}'.f...
65,478
def smart_quote(url): """ Like urllib.parse.quote, but quote non-ascii words only. Example :: smart_quote("http://whouz.com") # http://whouz.com smart_quote("喵.com") # %E5%96%B5.com """ l = [s if s in UNQUOTE else quote(s) for s in url] return ''.join(l)
65,479
async def test_socks5_request(): """ Send an HTTP request via a SOCKS proxy. """ network_backend = AsyncMockBackend( [ # The initial socks CONNECT # v5 NOAUTH b"\x05\x00", # v5 SUC RSV IP4 127 .0 .0 .1 :80 b"\x05\x00\x00\x01\...
65,480
def block_mine(block_template, coinbase_message, extranonce_start, address, timeout=None, debugnonce_start=False): """ Mine a block. Arguments: block_template (dict): block template coinbase_message (bytes): binary string for coinbase script extranonce_start (int): extranonce offset...
65,481
def create_default_config(path): """ Creates a default configuration for the given path. :param path: Path for which the default config must be created. :return: the default config. """ if os.path.isfile(path): return { 'name': QtCore.QFileInfo(path).completeBaseName(), ...
65,482
def test_names_pattern_wrong_subtype(test_df): """ Raise TypeError if `names_pattern` is a list/tuple and wrong subtype is supplied. """ with pytest.raises(TypeError): test_df.pivot_longer(names_to=["off", "pt"], names_pattern=[1, "pt"])
65,483
def run_vpt2(zma, geo, spc_info, thy_info, geo_save_fs, geo_run_path, geo_save_path, locs, script_str, overwrite, retryfail=True, **kwargs): """ Perform vpt2 analysis for the geometry in the given location """ # Set the run filesystem information run_fs = autofile...
65,484
def get_pydantic_field(field_name: str, model: Type["Model"]) -> "ModelField": """ Extracts field type and if it's required from Model model_fields by passed field_name. Returns a pydantic field with type of field_name field type. :param field_name: field name to fetch from Model and name of pydantic f...
65,485
def test_hush_if_test_teardown(u_boot_console): """Clean up environment variables used during the "if" tests.""" u_boot_console.run_command('setenv ut_var_exists')
65,486
def spin_down_rate(tq, R, M, period, dt): """ Calculate the new rotation period given a torque and a timestep. the rate of increasing rotation period for a given torque. torque = dL/dt dL = torque * dt dt: timestep (seconds) """ dL = tq * dt Omega = 2*np.pi/period I = R**2 * M ...
65,487
def test_model_save_load(): """ Tests for the model saving process """ X,y = random_data_constructor() filename = 'testing' _ = train_linear_model(X,y, filename=filename) #================================= # TEST SUITE #================================= # Chec...
65,488
def average_checkpoints(inputs: Iterable[str]) -> Dict[str, Any]: """Loads checkpoints from inputs and returns a model with averaged weights. Args: inputs: An iterable of string paths of checkpoints to load from. Returns: A dict of string keys mapping to various values. The 'model' key f...
65,489
def get_entries_ids(url): """ url : filled form url provider : form creator returns list of form entries ids """ logging.debug(f"get_entries_ids <-- {url}") from urllib import parse L = [] for i in dict(parse.parse_qsl(parse.urlsplit(url).query)).keys(): # n...
65,490
def pdf_pipeline(file: UploadFile = File(None)): """ Parses the file and returns various analytics about the pdf Parameters ---------- file: File A File stream Returns ------- JSON Returns a JSON where the key can be a section in the document with value as the text of the d...
65,491
def main(): """ Fetch parameter from config file or environment variables """ parser = ArgumentParser() parser.add_argument('config_file', help='Config file name') parser.add_argument('section', help='Section name') parser.add_argument('parameter', help='Argument name') parser.add_argume...
65,492
def makepath_hybrid(model,T,h,ode_method,sample_rate): """ Compute paths of model. """ voxel = 0. path = np.zeros((Nt,len(model.systemState))) path[0][:] = model.getstate(0) clock = np.zeros(Nt) for e in model.events: e.sethybridtype() e.updaterate() # for hybrid paths use c...
65,493
def eval_literal_value(value: str) -> ty.Any: """Evaluate a string to a literal value :param value: Value to evaluate :type value: str :return: Literal value the string is evaluated to :rtype: ty.Any """ try: return ast.literal_eval(value) except (SyntaxError, ValueError) as exc...
65,494
def test_postgresqlmanager_receive_sql_fetchall_not_string(): """ This test is to verify the test_receive_sql_fetchall can handle bad inputs """ database_manager: db.DatabaseManager = db.PostgreSQLManger() database_manager.set_connection_data("this is a test string") database_manager.cursor = Mo...
65,495
def section7(): """ ### Item Filtering Fields #### More Filter Options <div style="background-color: lightblue; color: black; width: 50%; padding: 10px; border-radius: 15px 5px 5px 5px;"> Use a dot to access parameters within curly brackets. For example use field='metadata.system.originalname' ...
65,496
def _load_off_stream(file) -> dict: """ Load the data from a stream of an .off file. Example .off file format: off 8 6 1927 { number of vertices, faces, and (not used) edges } # comment { comments with # sign } 0 0 0 { start of vertex...
65,497
def get_distinct_attr() -> (WORD, WORD, WORD, WORD): """Returns a tuple with 4 values: foreground color, foreground intensity, background color, and background intensity""" attr = get_text_attr() return ( attr & FOREGROUND_GREY, attr & FOREGROUND_INTENSITY, attr & BACKGROU...
65,498
def _full_simulation(exp, y0, pulse_sim_desc, pulse_de_model, solver_options=None): """ Set up full simulation, i.e. combining different (ideally modular) computational resources into one function. """ solver_options = PulseSimOptions() if solver_options is None else solver_options psi, ode_t ...
65,499