content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def group_sums_dummy(x, group_dummy): """sum by groups given group dummy variable group_dummy can be either ndarray or sparse matrix """ if data_util._is_using_ndarray_type(group_dummy, None): return np.dot(x.T, group_dummy) else: # check for sparse return x.T * group_dummy
2cfb448130b9c48b41dd491a4fe01ab11a38478b
3,641,906
def fixture_multi_check_schema() -> DataFrameSchema: """Schema with multiple positivity checks on column `a`""" return _multi_check_schema()
f2b95cda9d6cd3e5bf0055d22c4b8505370a9867
3,641,907
def get_featurizer(featurizer_key: str) -> ReactionFeaturizer: """ :param: featurizer_key: key of a ReactionFeaturizer :return: a ReactionFeaturizer for a specified key """ if featurizer_key not in FEATURIZER_INITIALIZERS: raise ValueError(f"No featurizer for key {featurizer_key}") retu...
15583e90a0691ce10df9d789f6decef5443efed2
3,641,908
from typing import List def is_negative_spec(*specs: List[List[str]]) -> bool: """ Checks for negative values in a variable number of spec lists Each spec list can have multiple strings. Each string within each list will be searched for a '-' sign. """ for specset in specs: if spe...
216e6db2e63a657ac95a31896b9b61329a10a3db
3,641,909
def is_np_timedelta_like(dtype: DTypeLike) -> bool: """Check whether dtype is of the timedelta64 dtype.""" return np.issubdtype(dtype, np.timedelta64)
b68d244d2d2c4d3029a93cbd8b3affca8c55f680
3,641,910
def pp2mr(pv,p): """ Calculates mixing ratio from the partial and total pressure assuming both have same unitsa nd no condensate is present. Returns value in units of kg/kg. Checked 20.03.20 """ pv, scalar_input1 = flatten_input(pv) # don't specify pascal as this will wrongly corrected p , sc...
97bd35658a54a53d7541aa0ee71f1b25cf8c2dbf
3,641,911
def initialize_database(app): """ Takes an initalized flask application and binds a database context to allow query execution """ # see https://github.com/mitsuhiko/flask-sqlalchemy/issues/82 db.app = app db.init_app(app) return db
11a9f6046f51239c071d3a61780d1edf775baa51
3,641,912
from typing import TextIO def decrypt(input_file: TextIO, wordlist_filename: str) -> str: """ Using wordlist_filename, decrypt input_file according to the handout instructions, and return the plaintext. """ encrypt = [] result = '' ans = '' plaintext = '' # store English wordlist ...
87fae6e252b57f9903cd4b46d18a625455761d62
3,641,913
def loadEvents(fname): """ Reads a file that consists of first column of unix timestamps followed by arbitrary string, one per line. Outputs as dictionary. Also keeps track of min and max time seen in global mint,maxt """ events = [] ws = open(fname, 'r').read().splitlines() events = [] for w in ws: ...
495dbd5d47892b953c139b27b1f20dd9854ea29a
3,641,914
def compute_relative_target_raw(current_pose, target_pose): """ Computes the relative target pose which has to be fed to the network as an input. Both target pose and current_pose have to be in the same coordinate frame (gloabl map). """ # Compute the relative goal position goal_position_difference = [targ...
efee9b6ef48bda67dfd42526c20e7d1de6a164da
3,641,915
import httpx def get_tokeninfo_remote(token_info_url, token): """ Retrieve oauth token_info remotely using HTTP :param token_info_url: Url to get information about the token :type token_info_url: str :param token: oauth token from authorization header :type token: str :rtype: dict """ ...
c0f72b47b97d2d9c57b8b7fe30a3cba9f29c2005
3,641,916
from datetime import datetime def make_site_object(config, seen): """Make object with site values for evaluation.""" now = datetime.today().strftime("%Y-%m-%d") subtitle = ( f'<h2 class="subtitle">{config.subtitle}</h2>' if config.subtitle else "" ) site = SN( autho...
762382446736a1815deae275db0d7485c0718a4e
3,641,917
from datetime import datetime import json import hashlib def map_aircraft_to_record(aircrafts, message_now, device_id): """ Maps the `aircraft` entity to a BigQuery record and its unique id. Returns `(unique_ids, records)` """ def copy_data(aircraft): result = { 'hex': aircraft.get('hex'), '...
d423b87e2018486de076cc94a719038c53c54602
3,641,919
def add_gaussian_noise(image, mean=0, std=0.001): """ 添加高斯噪声 mean : 均值 var : 方差 """ image = np.array(image / 255, dtype=float) noise = np.random.normal(mean, std ** 0.5, image.shape) print(np.mean(noise ** 2) - np.mean(noise) ** 2) out = image + noise if image.min() <...
1683ae5815e28ab0c3354be1623ec56e6058b449
3,641,920
def sub(xs, ys): """ Computes xs - ys, such that elements in xs that occur in ys are removed. @param xs: list @param ys: list @return: xs - ys """ return [x for x in xs if x not in ys]
8911bb2c79919cae88463a95521cf051828038e8
3,641,922
def create_folio_skill(request, folio_id): """ Creates a new folio skill """ if request.method == "POST": form = FolioSkillForm(request.POST) if form.is_valid(): skill = form.save(commit=False) skill.author_id = request.user skill.save() ...
7c1966f7a6b3c98e972da90abb5eb984a4af85a2
3,641,923
def reduce_tags(tags): """Filter a set of tags to return only those that aren't descendents from others in the list.""" reduced_tags = [] for tag_a in tags: include = True for tag_b in tags: if tag_a == tag_b: continue if not tag_before(tag_a, tag_b): ...
fa76e1cc5bd10ecd58bdc8f5277fa32d41484c17
3,641,925
def default_param_noise_filter(var): """ check whether or not a variable is perturbable or not :param var: (TensorFlow Tensor) the variable :return: (bool) can be perturb """ if var not in tf.trainable_variables(): # We never perturb non-trainable vars. return False if "full...
12817bf2c2b726d91d9d3cc838b52499e5382d80
3,641,926
def input_fn(request_body, request_content_type): """ An input_fn that loads the pickled tensor by the inference server of SageMaker. The function deserialize the inference request, then the predict_fn get invoked. Does preprocessing and returns a tensor representation of the source sentence ready t...
62d45e188d5537eaa566bd4b90bdb8abc7626621
3,641,927
def get_colors(k): """ Return k colors in a list. We choose from 7 different colors. If k > 7 we choose colors more than once. """ base_colors = ['b', 'r', 'g', 'c', 'm', 'y', 'k'] colors = [] index = 1 for i in range(0, k): if index % (len(base_colors) + 1) == 0: in...
6c4a38eb394254f57d8be9fca47e0b44f51f5f04
3,641,928
import logging def test_significance(stat, A, b, eta, mu, cov, z, alpha): """ Compute an p-value by testing a one-tail. Look at right tail or left tail? Returns "h_0 Reject """ ppf, params = psi_inf(A, b, eta, mu, cov, z) if np.isnan(params['scale']) or not np.isreal(params['sc...
f723a75c59a23d7110a41036d6873f6023b42333
3,641,929
def _get_cluster_group_idx(clusters: np.ndarray) -> nb.typed.List: """ Get start and stop indexes for unique cluster labels. Parameters ---------- clusters : np.ndarray The ordered cluster labels (noise points are -1). Returns ------- nb.typed.List[Tuple[int, int]] Tupl...
5bdae0228367868c201b8a399ca959bc50c715b2
3,641,930
from typing import Union from typing import Optional def genes_flyaltas2( genes: Union[str, list] = None, gene_nametype: Optional[str] = "symbol", stage: Optional[str] = "male_adult", enrich_threshold: Optional[float] = 1.0, fbgn_path: Optional[str] = "deml_fbgn.tsv.gz", ) -> pd.DataFrame: """...
651e3eb2ce58ae19d1785df1217b5434737b8bda
3,641,931
import torch import tqdm def _batch_embed(args, net, vecs: StringDataset, device, char_alphabet=None): """ char_alphabet[dict]: id to char """ # convert it into a raw string dataset if char_alphabet != None: vecs.to_bert_dataset(char_alphabet) test_loader = torch.utils.data.DataLoader...
43224296330e4516c530d65217edf6a4b12dc5d3
3,641,932
def get_adjacency_matrix(distance_df, sensor_ids, normalized_k=0.1): """ :param distance_df: data frame with three columns: [from, to, distance]. :param sensor_ids: list of sensor ids. :param normalized_k: entries that become lower than normalized_k after normalization are set to zero for sparsity. ...
b8acd5401dbf743294d52d71ddc97a0b0c74780b
3,641,933
def map_ids_to_strs(ids, vocab, join=True, strip_pad='<PAD>', strip_bos='<BOS>', strip_eos='<EOS>', compat=True): """Transforms `int` indexes to strings by mapping ids to tokens, concatenating tokens into sentences, and stripping special tokens, etc. Args: ids: An n-D numpy arra...
6e702d8c0d658bd822f0db6c4094ab093207b78e
3,641,934
import random def rand_ascii_str(length): """Generates a random string of specified length, composed of ascii letters and digits. Args: length: The number of characters in the string. Returns: The random string generated. """ letters = [random.choice(ascii_letters_and_digits) for _ in range(leng...
130e8dbe1eb8e60813b01cf08dc7e9fd388638cf
3,641,936
def set_achievement_disabled(aid, disabled): """ Updates a achievement's availability. Args: aid: the achievement's aid disabled: whether or not the achievement should be disabled. Returns: The updated achievement object. """ return update_achievement(aid, {"disabled": ...
2793e3576904f5b1498361f02e32fdf2642b734c
3,641,937
from datetime import datetime def get_block(in_dt: datetime): """Get the BlockNumber instance at or before the datetime timestamp.""" return BlockNumber.from_timestamp(in_dt.replace(tzinfo=timezone.utc).timestamp())
a77ca6c4021ebc0e5ef2e2c0294246415ccd9811
3,641,938
def get_channels(posts): """ <summary> Returns post channel (twitter/facebook)</summary> <param name="posts" type="list"> List of posts </param> <returns> String "twitter" or "facebook" </returns> """ channel = [] for i in range(0, len(posts['post_id'])): if len(posts['post_text'][i...
2bd67d13079ce115263ac46856d8a708f461cb7e
3,641,939
from bs4 import BeautifulSoup def clean_text(text): """ text: a string return: modified initial string """ text = BeautifulSoup(text, "lxml").text # HTML decoding text = text.lower() # lowercase text text = REPLACE_BY_SPACE_RE.sub(' ', text) # replace REPLACE_BY_SPACE_RE s...
b29f4b388bac55d04c824ad014a6b85e1c9c8ede
3,641,940
def ConvertToTypeEnum(type_enum, airflow_executor_type): """Converts airflow executor type string to enum. Args: type_enum: AirflowExecutorTypeValueValuesEnum, executor type enum value. airflow_executor_type: string, executor type string value. Returns: AirflowExecutorTypeValueValuesEnum: the execut...
04162b04719031ba6b96d981a7ffe8a82691bc31
3,641,941
import numpy def image2array(image): """PIL Image to NumPy array""" assert image.mode in ('L', 'RGB', 'CMYK') arr = numpy.fromstring(image.tostring(), numpy.uint8) arr.shape = (image.size[1], image.size[0], len(image.getbands())) return arr.swapaxes(0, 2).swapaxes(1, 2).astype(numpy.float32)
bb1ba38f2d27acb63ea7ccfb600720eee3d683a3
3,641,942
from typing import Type def enum_name_callback(ctx: 'mypy.plugin.AttributeContext') -> Type: """This plugin refines the 'name' attribute in enums to act as if they were declared to be final. For example, the expression 'MyEnum.FOO.name' normally is inferred to be of type 'str'. This plugin will ...
e7b34490625ad2c8cf55ed002592ed1194f96e2f
3,641,943
def is_forward_angle(n, theta): """ if a wave is traveling at angle theta from normal in a medium with index n, calculate whether or not this is the forward-traveling wave (i.e., the one going from front to back of the stack, like the incoming or outgoing waves, but unlike the reflected wave). For r...
9d90a84be42968eebb1dd89285019ddc10a2b140
3,641,944
import math def fit_cubic1(points,rotate,properties=None): """This function attempts to fit a given set of points to a cubic polynomial line: y = a3*x^3 + a2*x^2 + a1*x + a0""" r=mathutils.Matrix.Rotation(math.radians(rotate),4,'Z') rr=mathutils.Matrix.Rotation(math.radians(-rotate),4,'Z') S...
dea26481743546600bef54c58523746a638b63a5
3,641,946
def get_labelstats_df_list(fimage_list, flabel_list): """loop over lists of image and label files and extract label statisics as pandas.DataFrame """ if np.ndim(fimage_list) == 0: fimage_list = [fimage_list] if np.ndim(flabel_list) == 0: flabel_list = [flabel_list] columns = ['i...
e494212975641e8c9f9b2d786077e320d9096c02
3,641,948
def index(web): """The web.request.params is a dictionary, pointing to falcon.Request directly.""" name = web.request.params["name"] return f"Hello {name}!\n"
b717ac60d42b8161ed27f7e4156d8a5a03aea803
3,641,949
def process_object(obj): """ Recursively process object loaded from json When the dict in appropriate(*) format is found, make object from it. (*) appropriate is defined in create_object function docstring. """ if isinstance(obj, list): result_obj = [] for elem in obj: ...
f5410c6168d96eb153f08c824a98cf58fd80e1a0
3,641,950
def remove_role(principal, role): """Removes role from passed principal. **Parameters:** principal The principal (actor or group) from which the role is removed. role The role which is removed. """ try: if isinstance(principal, Actor): ppr = PrincipalRoleRe...
78b27631ee80b42a2ee8759315ef00f490c0e86c
3,641,951
def set_var_input_validation( prompt="", predicate=lambda _: True, failure_description="Value is illegal", ): """Validating user input by predicate. Vars: - prompt: message displayed when prompting for user input. - predicate: lambda function to verify a condition. - failure...
40cad55c5d07a405f946e9583c69029eb2ee4e65
3,641,952
def mad(data, axis=None): """Mean absolute deviation""" return np.mean(np.abs(data - np.mean(data, axis)), axis)
955763e5ee5d29e2b2b735d584d7a84b98affc23
3,641,953
from re import T def spatial_2d_padding(x, padding=((1, 1), (1, 1)), data_format=None): """Pad the 2nd and 3rd dimensions of a 4D tensor with "padding[0]" and "padding[1]" (resp.) zeros left and right. """ assert len(padding) == 2 assert len(padding[0]) == 2 assert len(padding[1]) == 2 top...
ba57f1f8462d7c3212379b9678364c5e2e2e6a5b
3,641,954
def doms_hit_pass_threshold(mc_hits, threshold, pass_k40): """ checks if there a at least <<threshold>> doms hit by monte carlo hits. retuns true or false""" if threshold == 0: return True if len(mc_hits) == 0: return bool(pass_k40) dom_id_set = set() for hit in mc_hits: dom_id = pm...
9f4157d202e2587232b13cfc9873400ab6ee6e5b
3,641,955
def _parseLocalVariables(line): """Accepts a single line in Emacs local variable declaration format and returns a dict of all the variables {name: value}. Raises ValueError if 'line' is in the wrong format. See http://www.gnu.org/software/emacs/manual/html_node/File-Variables.html """ paren = '...
39dc5130f47589e111e4b894cf293d446ac0eac0
3,641,957
from re import T def NLL(mu, sigma, mixing, y): """Computes the mean of negative log likelihood for P(y|x) y = T.matrix('y') # (minibatch_size, output_size) mu = T.tensor3('mu') # (minibatch_size, output_size, n_components) sigma = T.matrix('sigma') # (minibatch_size, n_components) mixing = T...
60a27f48d404af860cdbeac9e017a3df5ebca450
3,641,958
from typing import Optional import sqlite3 def get_non_subscribed_trainers(user) -> Optional[str]: """ returns all trainers the user is not subscrbed to """ conn = get_db() error = None try: trainers = conn.execute("""SELECT distinct u_name FROM user, trainer ...
6c728e1bd805047e20224c45fab81f546e291d27
3,641,959
def __clean_datetime_value(datetime_string): """Given""" if datetime_string is None: return datetime_string if isinstance(datetime_string, str): x = datetime_string.replace("T", " ") return x.replace("Z", "") raise TypeError("Expected datetime_string to be of type string (or No...
77afef31056365a47ea821de7a4979cb061920dc
3,641,960
def get_metric_by_name(metric: str, *args, **kwargs) -> Metric: """Returns metric using given `metric`, `args` and `kwargs` Args: metric (str): name of the metric Returns: Metric: requested metric as Metric """ assert metric in __metric_mapper__, "given metric {} is not found".form...
b1ecb1fe1fad330570abcf9abd3f12abd2a18193
3,641,961
def Square(inputs, **kwargs): """Calculate the square of input. Parameters ---------- inputs : Tensor The input tensor. Returns ------- Tensor The square result. """ CheckInputs(inputs, 1) arguments = ParseArguments(locals()) output = Tensor.CreateOperator...
5869ab81460b0a3b56194ec9829bf6ec36716b9a
3,641,962
def render_table(data, col_width=3.0, row_height=0.625, font_size=14, header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w', bbox=[0, 0, 1, 1], header_columns=0, ax=None, **kwargs): """[Taken from ref: https://stackoverflow.com/questions/...
597d8732ca86896d02d0df30d2a0808b88f02873
3,641,964
def segment_image(class_colours, pixel_classes, height, width, bg_alpha=0, fg_alpha=255): """visualise pixel classes""" segment_colours = np.reshape(class_colours[pixel_classes], (height, width, 3)) segment_colours = segment_colours.astype("uint8") img = Image.fromarray(segment_colours) # set backgr...
2dd1f70342cc101d3cf37d706ede8c55ded91629
3,641,965
def cross_replica_average(inputs, num_shards=None, num_shards_per_group=None, physical_shape=None, tile_shape=None, use_spatial_partitioning=False): """Customized cross replica sum op.""" ...
5486eae34e2e25966343a5e115541de7c734ec98
3,641,966
def edge_naming(col_list, split_collections=True): """ This function normalize the naming of edges collections If split_collections is True an edge collection name will be generated between each listed collection in order. So if col_list = [A, B, C] result will be [A__B, B__C] ...
47e0c7253a5a9f1c0df9488c54cca38b2264539f
3,641,968
def interactive_visual_difference_from_threshold_by_day(ds_ext): """ Returns: 1) xarray DataArray, with three variables, for each day in the dataset i) Highest value difference from the threshold, across the area ii) Lowest value difference from the threshold, across the area ...
2386f3564a105a44ff3cd12979f52e296e8293ac
3,641,969
def _parse_compression_method(data): """Parses the value of "method" extension parameter.""" return common.parse_extensions(data)
71901780aec98d8818a5296aa7b186c79b0f0e7b
3,641,970
def my_distance(drij): """ Compute length of displacement vector drij assume drij already accounts for PBC Args: drij (np.array) : vector(s) of length 3 Returns: float: length (distance) of vector(s) """ return np.linalg.norm(drij, axis=0)
45a29d7335e72dac68ddefcbf32b55b57e87b980
3,641,971
from typing import List def show(list_id): """Get single list via id.""" data = db_session.query(List).filter(List.id == list_id).first() if '/json' in request.path: return jsonify(data.as_dict()) else: return render_template('list/show.html', list=data)
9ed8de0dfc5621546dafe447fa83d33c00fa6b7e
3,641,972
def extract_smaps(kspace, low_freq_percentage=8, background_thresh=4e-6): """Extract raw sensitivity maps for kspaces This function will first select a low frequency region in all the kspaces, then Fourier invert it, and finally perform a normalisation by the root sum-of-square. kspace has to be of...
e40ec21c8e353e6352b65f35710d83857cc6c124
3,641,974
import io def tiff_to_mat_conversion(ms_path, pan_path, save_path, ms_initial_point=(0, 0), ms_final_point=(0, 0), ratio=4): """ Generation of *.mat file, starting from the native GeoTiFF extension. Also, a crop tool is provided to analyze only small parts of the image. Parameters ...
c0e1a03f82b97ecc8a3e33a1b84624b53c3efae7
3,641,975
def is_member(musicians, musician_name): """Return true if named musician is in musician list; otherwise return false. Parameters: musicians (list): list of musicians and their instruments musician_name (str): musician name Returns: bool: True if match is made; otherwise False....
6ef5b9bbccb17d9b97a85e3af7789e059829184b
3,641,976
def init(command): """ We assume the first command from NASA is the rover position. Assumetions are bad. We know that the command conists of two numbers seperated by a space. Parse the number so it matches D D """ if re.match('^[0-9]\s[0-9]\s[a-zA-Z]$', command): pos = command.split...
282bb4bababeb24e0fe8cb1f6f4a57d36b2339dd
3,641,978
def add_small_gap_multiply(original_wf, gap_cutoff, density_multiplier, fw_name_constraint=None): """ In all FWs with specified name constraints, add a 'small_gap_multiply' parameter that multiplies the k-mesh density of compounds with gap < gap_cutoff by density multiplier. Useful for increasing the k-...
4573ee33b1be21adfcca1e8be3337b1df51ab737
3,641,979
def _get_backend(config_backend): """Extract the backend class from the command line arguments.""" if config_backend == 'gatttool': backend = GatttoolBackend elif config_backend == 'bluepy': backend = BluepyBackend elif config_backend == 'pygatt': backend = PygattBackend else...
86374b3c19cbb3fa26434c18720288edf1c4fbe8
3,641,980
from time import time def kern_CUDA_sparse(nsteps, dX, rho_inv, context, phi, grid_idcs, mu_egrid=None, mu_dEdX=None, mu_lidx_nsp=None, ...
74b8d93f867fed536b3ba1f1f4f0fc6e33e3efe8
3,641,981
def _to_sequence(x): """shape batch of images for input into GPT2 model""" x = x.view(x.shape[0], -1) # flatten images into sequences x = x.transpose(0, 1).contiguous() # to shape [seq len, batch] return x
bb3b0bb478c924b520bf7bf991a028cf8aaea25f
3,641,982
def read_wav_kaldi(wav_file_path: str) -> WaveData: """Read a given wave file to a Kaldi readable format. Args: wav_file_path: Path to a .wav file. Returns: wd: A Kaldi-readable WaveData object. """ # Read in as np array not memmap. fs, wav = wavfile.read(wav_file_path, False) ...
50b2f5a848d387d4b1ca2764b7d30178d7ec5e28
3,641,983
def _testCheckSums(tableDirectory): """ >>> data = "0" * 44 >>> checkSum = calcTableChecksum("test", data) >>> test = [ ... dict(data=data, checkSum=checkSum, tag="test") ... ] >>> bool(_testCheckSums(test)) False >>> test = [ ... dict(data=data, checkSum=checkSum+1, tag=...
192785ca352eec4686e07f2f103283f6499b656f
3,641,984
def read_img(path): """ 读取图片,并将其转换为邻接矩阵 """ # 对于彩色照片,只使用其中一个维度的色彩 im = sp.misc.imread(path)[:, :, 2] im = im / 255. # 若运算速度太慢,可使用如下的语句来缩减图片的大小 # im = sp.misc.imresize(im, 0.10) / 255. # 计算图片的梯度,既相邻像素点之差 graph = image.img_to_graph(im) beta = 20 # 计算邻接矩阵 graph.data = np...
41e4d000f9a70a6b6e787c08bcced4083178da11
3,641,985
def createmarker(name=None, source='default', mtype=None, size=None, color=None, priority=None, viewport=None, worldcoordinate=None, x=None, y=None, projection=None): """%s :param name: Name of created object :type name: `str`_ :param source: A marker...
7afaec1d24aad89b85974c509cf7c0ed165f733b
3,641,986
from typing import List from typing import Optional from typing import Set from typing import Callable def get_parser(disable: List[str] = None , lang: str = 'en', merge_terms: Optional[Set] = None, max_sent_len: Optional[int] = None) -> Callable: """spaCy clinical tex...
175c4ea51417dc02b4a7f6f5a0c512464bd252c2
3,641,987
def block_device_mapping_get_all_by_instance(context, instance_uuid, use_slave=False): """Get all block device mapping belonging to an instance.""" return IMPL.block_device_mapping_get_all_by_instance(context, ...
16fc00068ad87d76831044d626a88960a0278817
3,641,988
def add_rain(img, slant, drop_length, drop_width, drop_color, blur_value, brightness_coefficient, rain_drops): """ From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library Args: img (np.uint8): slant (int): drop_length: drop_width: drop_color: ...
f864a46fc13e955baade855ae454249e3a514a03
3,641,989
def vrctst_tml(file_name): """ adds vrctst_tml extension, if missing :param file_name: name of file :type file_name: str :returns: file with extension added :rtype: str """ return _add_extension(file_name, Extension.VRC_TML)
92a084fc19c39c0797d573e01c90da28c0e1c11c
3,641,990
def get_pixel_coords(x, y, xres, yres, xmin, ymax): """ Translate x, y coordinates to cols, rows. Example: col, row = map_pixel(x, y, geotransform[1], geotransform[-1], geotransform[0], geotransform[3]) Parameters ---------- x : float, numpy.ndarray X coordinates. ...
ccf38618de9d24279ab4df6ba016804c6da926f7
3,641,991
import re def _boundary_of_alternatives_indices(pattern): """ Determines the location of a set of alternatives in a glob pattern. Alternatives are defined by a matching set of non-bracketed parentheses. :param pattern: Glob pattern with wildcards. :return: Indices of the innermost set of m...
707a4a02a362019db63277b01955bb54d31e51e7
3,641,992
def sim_DA_from_timestamps2_p2_2states(timestamps, dt_ref, k_D, R0, R_mean, R_sigma, tau_relax, k_s, rg, chunk_size=1000, alpha=0.05, ndt=10): """ 2-states recoloring using CDF in dt and with random number caching """ dt = np....
c268e49d7fc960c3f684d77fcbb4880be446a5b0
3,641,995
def get_cross_track_error(data, rate, velocity): """Returns the final cross-track position (in nautical miles) The algorithm simulates an aircraft traveling on a straight trajectory who turns according to the data provided. The aircraft instantaneously updates its heading at each timestep by Ω * Δt. ...
88fa42408090c94c9e3212517d89ba47afeedccb
3,641,996
async def get_list_address(): """Get list of address """ return await service.address_s.all()
4d0304e23243d7f151c0f09fc5e1896413daee1b
3,641,997
import pathlib from typing import Optional def load_xml_stream( file_path: pathlib.Path, progress_message: Optional[str] = None ) -> progress.ItemProgressStream: """Load an iterable xml file with a progress bar.""" all_posts = ElementTree.parse(file_path).getroot() return progress.ItemProgressStream( ...
26d6bd350dbe913855479c557c8881b03f90b266
3,641,998
def SNR_band(cp, ccont, cb, iband, itime=10.): """ Calc the exposure time necessary to get a given S/N on a molecular band following Eqn 7 from Robinson et al. 2016. Parameters ---------- cp : Planet count rate ccont : Continuum count rate cb : Background count r...
ffec688d6e760ace0fc1e38217ec91dc674ee83f
3,641,999
def create_index(conn, column_list, table='perfdata', unique=False): """Creates one index on a list of/one database column/s. """ table = base2.filter_str(table) index_name = u'idx_{}'.format(base2.md5sum(table + column_list)) c = conn.cursor() if unique: sql = u'CREATE UNIQUE INDEX IF...
38b71cededb8500452cd3eac53609cc4ee384566
3,642,001
from typing import Type from typing import Any import inspect def produce_hash(self: Type[PCell], extra: Any = None) -> str: """Produces a hash of a PCell instance based on: 1. the source code of the class and its bases. 2. the non-default parameter with which the pcell method is called 3. the name of...
859f51600a9cc4da8ba546afebf0ecdf20959ec8
3,642,002
def boxes3d_kitti_fakelidar_to_lidar(boxes3d_lidar): """ Args: boxes3d_fakelidar: (N, 7) [x, y, z, w, l, h, r] in old LiDAR coordinates, z is bottom center Returns: boxes3d_lidar: [x, y, z, dx, dy, dz, heading], (x, y, z) is the box center """ w, l, h, r = boxes3d_lidar[:, 3:4], bo...
139a3da3ac8e6c09a376d976d0e96a8d91f9a74a
3,642,003
def combine_per_choice(*args): """ Combines two or more per-choice analytics results into one. """ args = list(args) result = args.pop() new_weight = None new_averages = None while args: other = args.pop() for key in other: if key not in result: result[key] = other[key] else:...
63e482a60b521744c94d80b0b8a740ff74f4b197
3,642,004
import string def prepare_input(dirty: str) -> str: """ Prepare the plaintext by up-casing it and separating repeated letters with X's """ dirty = "".join([c.upper() for c in dirty if c in string.ascii_letters]) clean = "" if len(dirty) < 2: return dirty for i in range(len(d...
5c55ba770e024b459d483fd168978437b8d48c21
3,642,005
def calc_center_from_box(box_array): """calculate center point of boxes Args: box_array (array): N*4 [left_top_x, left_top_y, right_bottom_x, right_bottom_y] Returns: array N*2: center points array [x, y] """ center_array=[] for box in box_array: center_array.append...
1f713a2f6900678ad1760ea60456bbf44b9f06af
3,642,006
import scipy def getW3D(coords): """ ################################################################# The calculation of 3-D Wiener index based gemetrical distance matrix optimized by MOPAC(Not including Hs) -->W3D ################################################################# """ ...
25fb1596b0d818d7f7f120289a79ccbf9b4f1ae4
3,642,007
from typing import Any from typing import Sequence def state_vectors( draw: Any, max_num_qudits: int = 3, allowed_bases: Sequence[int] = (2, 3), min_num_qudits: int = 1, ) -> StateVector: """Hypothesis strategy for generating `StateVector`'s.""" num_qudits, radixes = draw( num_qudits_a...
b81059843f94cb1c36581ac0a7dd5d3c17f39839
3,642,008
def ProcessChainsAndLigandsOptionsInfo(ChainsAndLigandsInfo, ChainsOptionName, ChainsOptionValue, LigandsOptionName = None, LigandsOptionValue = None): """Process specified chain and ligand IDs using command line options. Arguments: ChainsAndLigandsInfo (dict): A dictionary containing information ...
0bdadbc08512957269a179df24c1202a56870d42
3,642,009
def oa_filter(x, h, N, mode=0): """ Overlap and add transform domain FIR filtering. This function implements the classical overlap and add method of transform domain filtering using a length P FIR filter. Parameters ---------- x : input signal to be filtered as an ndarray h : F...
41fa7aaf7a57e0f6c363eb1efa7413b2a1a34d47
3,642,010
from typing import Optional from typing import Iterable import re def get_languages(translation_dir: str, default_language: Optional[str] = None) -> Iterable[str]: """ Get a list of available languages. The default language is (generic) English and will always be included. All other languages wil...
a25c9c2672f4f8d96cffc363aa922424b031aea7
3,642,011
def calculate_direction(a, b): """Calculates the direction vector between two points. Args: a (list): the position vector of point a. b (list): the position vector of point b. Returns: array: The (unnormalised) direction vector between points a and b. The smallest magnitude of an e...
9e0297560bb48d57cd4e1d5f12788a62ae7d9b3b
3,642,012
import json def parse_game_state(gs_json: dict) -> game_state_pb2.GameState: """Deserialize a JSON-formatted game state to protobuf.""" if 'provider' not in gs_json: raise InvalidGameStateException(gs_json) try: map_ = parse_map(gs_json.get('map')) provider = parse_provider(gs_json['provider']) ...
d78868c24807a3cac469b87990e5a74f88876eb5
3,642,014
def state2bin(s, num_bins, limits): """ :param s: a state. (possibly multidimensional) ndarray, with dimension d = dimensionality of state space. :param num_bins: the total number of bins in the discretization :param limits: 2 x d ndarray, where row[0] is a row vector of the lower limit...
8c0a1d559a332b1a015bde78c9eca413eeae942c
3,642,015
def _fix_json_agents(ag_obj): """Fix the json representation of an agent.""" if isinstance(ag_obj, str): logger.info("Fixing string agent: %s." % ag_obj) ret = {'name': ag_obj, 'db_refs': {'TEXT': ag_obj}} elif isinstance(ag_obj, list): # Recursive for complexes and similar. ...
be73467edc1dc30ac0be1f6804cdb19cf5f942bf
3,642,016
def vflip(img): """Vertically flip the given CV Image. Args: img (CV Image): Image to be flipped. Returns: CV Image: Vertically flipped image. """ if not _is_numpy_image(img): raise TypeError('img should be CV Image. Got {}'.format(type(img))) return cv2.flip(img, 1)
7b678327a15876a98e0622eacc012f86a8ffd432
3,642,017
def list_pending_tasks(): """List all pending tasks in celery cluster.""" inspector = celery_app.control.inspect() return inspector.reserved()
3d1785dd9ac8fd91f1f0ceb72eeb7df5671b55d5
3,642,018
def get_attack(attacker, defender): """ Returns a value for an attack roll. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Returns: attack_value (int): Attack roll value, compared against a defense value to determine whe...
3ec24ab34a02c2572ee62d1cc18079bdb7ef10ee
3,642,019
def colored(s, color=None, attrs=None): """Call termcolor.colored with same arguments if this is a tty and it is available.""" if HAVE_COLOR: return colored_impl(s, color, attrs=attrs) return s
a8c4f56e55721ec464728fbe9af4453cd98400ba
3,642,020