content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from odc.io.text import parse_slice from typing import List def parse_all_tasks( inputs: List[str], all_possible_tasks: List[TileIdx_txy] ) -> List[TileIdx_txy]: """ Select a subset of all possible tasks given user input on cli. Every input task can be one of: <int> -- 0 based ...
a7b428764b8d894c8c51a838864e4643bb9e77a8
44,700
import time import os def Starter(valuelist): """ :param: list of imported parameters :return: MinOverlapBlocks, MinOverlapMST, MinArea, MinBdgCount, MinPatchSize, MaxHoleSize, MaxGapSize, partstart, partend, partlist - checks whether all needed files are present - coverts valuelist to single var...
9b825e5a75daf948e507724332afac9e322a29d2
44,701
import gzip import numpy def extract_labels(f, one_hot=False, num_classes=10): """Extract the labels into a 1D uint8 numpy array [index]. Args: f: A file object that can be passed into a gzip reader. one_hot: Does one hot encoding for the result. num_classes: Number of classes for the one hot encoding...
89984977f7dff0e3ccce82395295b4bd1fa0a209
44,702
def head(filename, numlines=200): """Route: head the contents of a file given the numlines""" return process_file(tailer.head, filename, int(numlines))
549a85a8ccc663f5a48f97d4b6601b12a74cd833
44,703
def get_rpm_properties(input_file: str): """ Summary: processes the structured name of the rpm file to get the arch, release, version, and name Parameters: input_file (str): the file Returns: dictionary containing arch, release, version, and name """ #get prope...
291171913e80ede385a464c525fc44e87aeaf41b
44,704
def get_sig_symbol(corr_p_val, ctrl=False, percentile=False, sensitivity=None, side=1, tails=2, p_thresh=0.05): """ get_sig_symbol(corr_p_val) Return significance symbol. Required args: - corr_p_val (float): corrected p-value (e.g., corrected for multiple compa...
bb7ea437252979f46ff435493a927cec8cfef1e8
44,705
def equalize_hist_rgb(rgb_img: np.ndarray) -> np.ndarray: """ Equalize the histogram of a RGB image. :param rgb_img: RGB image :return: equalized RGB image """ ycrcb_img = cv2.cvtColor(rgb_img, cv2.COLOR_RGB2YCrCb) # convert from RGB color-space to YCrCb ycrcb_img[:, :, 0] = cv2.equalizeHi...
05dbd9927beca59db290fbc6620174c4ce41ae16
44,706
def move_file(cpu_context, func_name, func_args): """ Moves an existing file (or directory) to new location. """ old_name_ptr, new_name_ptr, *_ = func_args old_path = cpu_context.read_data(old_name_ptr).decode("utf8") new_path = cpu_context.read_data(new_name_ptr).decode("utf8") logger.debug...
c513eb686dc4c7e74fd47508f8b00fc0b35fa3f9
44,707
def get_artists_in_genre(incl_genres, lydir: str=LYRICDIR): """ creates and displays a list of all artists for genres selected via incl_genres parm. selects all genres if incl_genres is left blank or if 'all' is passed as str or list :param incl_genres: :param lydir: folder for lyric files :retu...
0f6ada98b7f639565536ffd5f57227ca38255be5
44,708
def authenticate(): """Sends a 401 response that enables basic auth""" return ( jsonify({"description": "Incorrect Credentials"}), 401, {'WWW-Authenticate': 'Basic realm="Credentials Required"'})
6ce6133062ec68d32343da1cc9a574166235ab39
44,709
def update_batch_flow(): """ 手动置批处理节点为完成状态 """ form = BusinessBatchFlowForm() if form.validate_on_submit(): db_info = EnvironMapping.query.filter_by(tms_ip=form.test_env.data).first() engine = OracleEngine('BATCH', db_info=db_info) engine.update_business_batch_flow(form.trad...
945d2490dfc8378f5baa3004f1e621c26952fbc3
44,710
def spherical_to_cartesian(spherical: np.ndarray) -> np.ndarray: """Returns the cartesian form of the spherical vector. spherical_vector can be a numpy array where rows are spherical vectors (or a single vector)""" cartesian = np.empty_like(spherical, dtype=float) cartesian[..., 0] = spheri...
8e8703e798d5a5c32b5866ededd1d20c45d01e6a
44,711
def max_flow_rule(mod, l, tmp): """ **Constraint Name**: TxSimple_Max_Flow_Constraint **Enforced Over**: TX_SIMPLE_OPR_TMPS_W_MAX_CONSTRAINT Transmitted power should not exceed the defined maximum flow in each operational timepoint. """ var = mod.tx_simple_max_flow_mw[l, tmp] if var == ...
4448aca8c59392d2977b79dd24c3c2dd19ea823b
44,712
def blink() -> str: """Returns 'bright/blink text' ANSI-command string.""" return _format_rich_text(TextAttributes.blink)
6a46732d3f6d62bb40bd42f798583acfc06b236c
44,713
def CachedPropertyParamRegistry(): # noqa: N802 """Registry with cached property and a keyword parameter.""" class CachedPropertyParamRegistry: registry = Registry('kwparam', cached_property=True) return CachedPropertyParamRegistry
b1dcdee8012051765d5eb76bde3d0647dcc51efa
44,714
def map_to_representative(state, lp_metric, representative_states, n_representatives, min_dist, scaling, accept_new_repr): """ Map state to representative s...
168b919939b6135747d2484637a62f0a04eb8b32
44,715
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...
f7fd8da601300aef722eb6706d111a54383648c0
44,716
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...
3d47831a946d73050032ee11f518f1f401fb8a99
44,717
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...
ecaf54467529b8d36f2af25c65c557520bf59711
44,718
def has_pipeline(model): """ Tells if a model contains a pipeline. """ return any(map(lambda x: isinstance(x[1], Pipeline), enumerate_model_names(model)))
d7d559035548f2feb8302ed1a17da74029135be6
44,719
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": ...
964fefb61c1e304bd80e446b662f6f23c85d2361
44,720
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...
51bc68e7b3034b20eac474edf9e5b172d005a39d
44,721
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: ...
d3d611a8457341e959c831a653acb00e44495471
44,722
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...
adad372562d30d561027722f9ad7e8b15a40960c
44,723
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...
4c549d56fd67b6d12ad5262780bd7a5744d9b7a2
44,724
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...
b02ce4e748387ced2e6fda87732a226eb8bbfc51
44,725
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...
51f4d697f63737c2d0253562da68df0ab2d110df
44,726
import torch 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:...
cfa87a57d4cb6b194da4ae6316433adefb8cfbe1
44,727
import unicodedata 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_2...
61c016606b83483ac25b407d53e6fd82fb1344dd
44,728
import torch 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_...
10fee68c5aa58bb35c1b924cb7922c9809e39cc8
44,729
from typing import Union from pathlib import Path import yaml 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 ....
a0ed543d6f8c4372a51c8da25154fbe17eef64bb
44,730
from datetime import date def get_current_year(): """ return: the current year. """ return date.today().isocalendar()[0]
0ba2fd73f596fd40c290dcda5b18bdcc1afa5c62
44,731
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
9322cb00268f010f43c772fbb15a8b2d3ec8aef0
44,732
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...
a32eddd26ebba511a49561f806a96ee5f5933a62
44,733
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 ...
823a2da076b1ed10c8db0bf0ea1ae64006cdf2d7
44,734
from typing import List 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
10ddb81bba45147bbac0cc8589f768f3cad87e2f
44,735
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...
35bcc430571243a6cde197cee581ec2533ead400
44,736
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...
dbd9d8cceee1cd99198b0e4ae1d5e7aee5d98d6f
44,737
import torch 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 = ...
b71e546d459ee1bb57f68278edef852c466cd4e6
44,738
import os import io 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 ' ...
04d641c4834f96f45a52371173b3aa36d9c8fa40
44,739
import sys 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 ...
8d96c8592d055504449123befb1c8e35ec9bbec3
44,740
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...
8eef02a88a12e9c61f721eb698195b8bb9493b7a
44,741
def hello(): """Return a friendly HTTP greeting.""" return 'Deep Neural Network (DNN) heart failure prediction'
7f30a185fccbabe9d1f06fbff34e51492239a2f9
44,742
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) ...
24585de78337884c2ae19651f8b86cdf795c4676
44,743
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_...
cc71061147b0a3135ef78655822dda68a4dd8e44
44,744
import json import csv 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() func...
dd7842e4273492e7a3d09e8b71b0a04523e8f259
44,745
import random 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) ...
fe71dd71646ce229b7e690cacd7b747e5e536293
44,746
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...
90efbf9face70ef1de6511be841d310ebfc5516c
44,747
import socket 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
254c8ce2820e3b9aef952b8ee48b0bd7b0aaed9f
44,748
import re import logging 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...
7f34d14929d366f318b4a750c9321a979ac08547
44,749
from typing import Union from typing import Dict from typing import Any import typing 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]] = {}, st...
6e4d3b63985aa1557a2e42927593ab2b282f5657
44,750
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...
cf695fa985e0c4519ed191d4ffd45d551ae3c598
44,751
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'...
5d6f27d6bff8643e37398b4c3c31a0340585b88d
44,752
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...
ead981fe505cab8836dac19bdd2ff7c79d36e1bc
44,753
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-...
0fb8ae6444a752d26fea656115ce63e75915c59f
44,754
import os def script_path(): """Return path to CGI script.""" result = os.getenv('PATH_TRANSLATED') if '.py' in result: result = os.path.dirname(result) return result
92c0a16add7ae7ee4546c0c8b2eb3e8260828114
44,755
import logging 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['s...
95e057baa90728881ca6cf0622bc652b05da4c77
44,756
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 = { 'ó': 'ó', 'ż': 'ż', 'Ä™': 'ę', 'Å‚': 'ł', 'Å›': 'ś', 'ć': 'ć', 'Ä…': 'ą', '...
ec847f50bc074f8f9ff081c55afccf3311037cd0
44,757
from django.db.models import Model 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). ...
2c2e79abed39ceebfb7c4b1b1d19fa71957704f3
44,758
import pandas 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 = ser...
72a2cef21cfa593992f4cce21ca2af6a400b9ff7
44,759
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,...
147825802c531ba49c10a4e3fde1dfaccfffcad5
44,760
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
c4ddfdb8e0358d4b98e708a271d8413b508b4f9d
44,761
import uuid 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()
3a102c945d2d315bc9c3fb68d3cdaeb932769929
44,762
import logging from pathlib import Path import csv 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 ASD...
a57af9e8cd2cb442c4cc432ed602bccc390cef6e
44,763
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 ...
11517c30f1e4b82eeddef0970fdbc80d06dbe348
44,764
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...
f90d7f070f540f8ff13aa7217d4ef6648b055958
44,765
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...
aedfa2d3f036ba632275cda2702c1e2272df7cb0
44,766
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)
cb56fe02cb68c1d626df12763b2773c00c0cdaac
44,767
import time 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): ext...
626b2e08fea0c0e875ac290a0865e853e75ce518
44,768
import os 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).completeB...
5c03f3c3d03a410f28c1952ced5e0516de5b871a
44,769
from typing import Type 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 Mo...
deec984a9e5d89687bee77bd3733dc4261a403bc
44,770
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 ...
cd0e0eb2d10f1bb8f3fd3940df1da05c5cfb8fbd
44,771
from typing import Iterable from typing import Dict from typing import Any import collections from typing import List import torch 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 s...
c58f4479fd10119fd28326c654ce0fce534c910c
44,772
from urllib import parse import logging 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}") L = [] for i in dict(parse.parse_qsl(parse.urlsplit(url).query)).keys()...
623b1c11dd5f71310c56106073e21ade5bf9d9fc
44,773
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...
3ed9453a3bb18d489d9b01f3ccc720006c4f6ad4
44,774
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...
f2f29f9a0d957d092cf8b471070416c9c6d4463d
44,775
import ast 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, Value...
f5060d709587cfbd17804c7fee39ae62e4c88ec5
44,776
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...
302b51377a0fb396e9a9cb08a80aa9eed56ccfc8
44,777
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 & BACKGROUND_GREY...
b5172d5b1e12f9d8bfa602514459a68bd6b005a7
44,778
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 ...
0ec3fce6b3e0522697dadbaa634e3c81f82303b8
44,779
from typing import Dict def get_headers(token_scope: str = TIMER_SERVICE_SCOPE) -> Dict[str, str]: """ Assemble any needed headers that should go in all requests to the timer API, such as the access token. """ token = get_access_token_for_scope(token_scope) if not token: raise ValueErr...
76e547ced14f1f37a7dc6287132e42db6cd9a3a4
44,780
import string def unrank(n, sequence=string.ascii_lowercase): """Unrank n from sequence in colexicographical order. >>> [''.join(unrank(i)) for i in range(8)] ['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc'] >>> unrank(299009) ['a', 'm', 'p', 's'] """ return list(map(sequence.__getitem__, in...
6deca92730cb7147d8e857fec4f8575580bb3142
44,781
import pkgutil import json def waste_schema(): """Provides schema validation to tests""" schema_file_contents = pkgutil.get_data("atomic6ghg.schemas", "waste.json") schema = json.loads(schema_file_contents) v = Draft7Validator(schema=schema) return v
211eda76983c6e4e51c5f6bd1cbf40efb284ea0f
44,782
def min_threshold_dist_from_shapefile(shapefile, radius=None, p=2): """ Kernel weights with adaptive bandwidths. Parameters ---------- shapefile : string shapefile name with shp suffix. radius : float If supplied arc_distances will be calculated ...
700322eb1e4bc11fefd56e571c7123fc1b5dadbf
44,783
def datetimetodatetime64(t): """ Convert a vector of datetime64 to datetime objects """ #return np.array([np.datetime64(tt) for tt in t]).astype('datetime64[us]') return np.array([np.datetime64(tt) for tt in t]).astype('<M8[ns]')
d201df8bfbed9cb61b7e2093c42fe00b39123031
44,784
def check_session(): """ Checks validity of session using only required() decorator """ return '{}'
fd02e0f8ffd76d8eb6f69148142108320864bade
44,785
def gaussian(area, mean=0, sigma=0.8): """ mean 均值, sigma 標準差 輸出縮限到0~1之間 """ noise = np.random.normal(mean, sigma, area) return np.clip(noise, 0, 1)
014164a21bac23486916f78fd599ad2fcc15b651
44,786
import torch def direction_to_index(direction: str) -> int: """Converts string representation of direction into integer Parameters ---------- direction: str "UP", "DOWN", "LEFT", "RIGHT Returns ------- direction_onehot: torch.LongTensor Integer representation of the direc...
708eed0c994cd5f45ee1833caa9459f8d1d6f0bc
44,787
def histo_analysis(hist_data): """ Calculates the mean and standard deviation of derivatives of (x,y) points. Requires at least 2 points to compute. parameters: hist_data: list of real coordinate point data (x, y) return: Dictionary with (mean, deviation) as keys to corresponding values """ if len(hist_data[0...
7f15610d86ece2480b61b65013a0762f7a73f56b
44,788
import typing def check_if_object_exists( local_uri: str, file_loc: str, obj_type: str, search_data: typing.Dict, token: str = None, ) -> str: """Checks if a data product is already present in the registry Parameters ---------- local_uri : str local registry endpoint f...
30e4abf082add8047e39d7774ec3d6b79bfd8263
44,789
def platform(): """ :return (string): returns the name of the platform """ return "circadia sunrise lamp"
a4d4fdda93687d80e679420d92512d08988566d7
44,790
from re import T def Adam(loss, all_params, learning_rate=0.001, b1=0.9, b2=0.999, e=1e-8, gamma=1-1e-8): """ ADAM update rules Default values are taken from [Kingma2014] References: [Kingma2014] Kingma, Diederik, and Jimmy Ba. "Adam: A Method for Stochastic Optimization." arXiv p...
88470e40ce9b6510a8ea634e30c0b2c2c109d093
44,791
def _ggm_prob_wait_whitt_z(ca2, cs2): """ Equation 3.8 on p139 of Whitt (1993). Used in approximation for P(Wq > 0) in GI/G/c/inf queue. See Whitt, Ward. "Approximations for the GI/G/m queue" Production and Operations Management 2, 2 (Spring 1993): 114-161. Parameters ---------- ca2 : flo...
91cbf519541411dec095b710e7449f3a183c20d3
44,792
def get_market_orders(region_id='10000030', type_id='34'): """Get the current market orders for an item in a region. API has 6 min cache time.""" crest_order_url = 'https://crest-tq.eveonline.com/market/{}/orders/{}/?type=https://public-crest.eveonline.com/inventory/types/{}/' dfs = [] for order_...
76a5e103a2a4079a1596d5e33b35d7e678156452
44,793
def date(m=0,d=0): """ returns all the fun holidays on the specified date """ holidays = holidays_date(m, d) if not holidays: return jsonify(holidays), status.HTTP_400_BAD_REQUEST return jsonify({"day": d, "month": m, "holidays": [h.holiday for h in holidays]})
b0441a8636f5fb7a1261917625b788f6836da162
44,794
def pproc_Mindlin_2d(size, shape: nparray, points: nparray, solution: nparray, D: nparray, S: nparray): """ JIT-compiled function that calculates post-processing quantities at selected ponts for multiple left- and right-hand sides. Parameters ---------- size : tuple...
ca027a6c13e52a48a8ddfe4e14b8d13e1b8ed9da
44,795
import os def addanovap_real1(): """ addanovap_real1 description: Uses the raw data from real_data_1.csv to compute ANOVA p-values for all 5 of the defined groups Test fails if the shape of the resulting "test_anova" statistic array in the Dataset object does not have the proper shape...
a6623e6bcd4c8d3f2f35ce0d1fa1e4875577faa2
44,796
from typing import Tuple from typing import Optional def test_error_bounded_no_exception() -> None: """Test error bounded decorator during happy case.""" def mock_fun() -> Tuple[Optional[AppError], bool]: return AppError(ErrorCode.GOOGLE_API_ERROR, "google error"), False wrapper = error_bounded(...
ebcd9112900256a97ca4fce9f0bd0fcf6d19ac2c
44,797
def attack_single_target(caller,target, attack): """ Launch an attack on a single EC2 instance. :param caller: Calling menu to return to. :param target: Target EC2 instance id :param attack: The attack to launch. :return: True """ global ec2instances target_id = '' target_platfor...
8fc019536196d915a91a5f843c54159cd49d7d4d
44,798
from bs4 import BeautifulSoup def get_repost_list(html, mid): """ Get repost details :param html: page source :param mid: weibo mid :return: list of repost infos """ cont = get_html_cont(html) if not cont: return list() soup = BeautifulSoup(cont, 'html.parse...
4c7893b52a69ae9a66737a7d567bd0f4960f6461
44,799