content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_short_description(dict, value): """Get layout class based on value.""" return dict.get(value, {}).get('short_description')
f5885f10ce009db925d552f8a0b0f40ab1ccaa2a
3,623,900
def cdlconcealbabyswallow( client, symbol, timeframe="6m", opencol="open", highcol="high", lowcol="low", closecol="close", ): """This will return a dataframe of conceal baby swallow for the given symbol across the given timeframe Args: client (pyEX.Client): Client ...
04cea2169f0fc1dc9e173fea66d5c341aac4224c
3,623,901
def rectangular_hollow_section(b: float, d: float, t: float, r_out: float, n_r: int, material: pre.Material = pre.DEFAULT_MATERIAL) -> Geometry: """Constructs a rectangular hollow section (RHS) centered at *(b/2, d/2)*, with depth *d*, width *b*, thickness *t* and outer radius *r_out*, using *n_r* points to con...
a0639d8674485ba31e2e7c7b4df1c78e5980dcc8
3,623,902
def _is_subexpansion_optional(query_metadata, parent_location, child_location): """Return True if child_location is the root of an optional subexpansion.""" child_optional_depth = query_metadata.get_location_info(child_location).optional_scopes_depth parent_optional_depth = query_metadata.get_location_info(...
29391226258e75d434e07c291fe9590c1810d85b
3,623,903
import uuid def get_uuid(key, value, is_list=False, is_optional=False, default=None, options=None): """ Get the value corresponding to the key and converts it to `uuid`/`list(uuid)`. Args: key: the dict key. value: the value to parse. is_list: If this is one element or a list of e...
8325f288f580ed0b47fefc144cb16f71d4b1e742
3,623,904
import torch from typing import Sequence def to_tensor(data): """Convert objects of various python types to :obj:`torch.Tensor`. Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`, :class:`Sequence`, :class:`int` and :class:`float`. """ if isinstance(data, torch.Tensor): r...
3d9aa7cb8424e6ee07412449ee890ce174cbc5b8
3,623,905
def _filter_labels(text, labels, allowed_labels): """Keep examples with approved labels. :param text: list of text inputs. :param labels: list of corresponding labels. :param allowed_labels: list of approved label values. :return: (final_text, final_labels). Filtered version of text and labels ...
e17ed7659acbdadc71a6b3f5b522af1e34d40370
3,623,906
def _Itype(): """Loop iterator data type.""" return tf.int32 if use_xla() else tf.int64
484c51f53226f7ebb0cf9738c8b16ad99438289b
3,623,907
import math def Q(fastev,lagev,fastrc,lagrc): """Following Wuestefeld et al. 2010""" omega = math.fabs((fastev - fastrc + 3645)%90 - 45) / 45 delta = lagrc / lagev dnull = math.sqrt(delta**2 + (omega-1)**2) * math.sqrt(2) dgood = math.sqrt((delta-1)**2 + omega**2) * math.sqrt(2) if dnull < dgo...
fe975fb234297a6f25100bb85aa6639590a010d8
3,623,908
def w_median(a, weights): """ Compute the weighted median of a 1D numpy array. Parameters ---------- a : ndarray Input array (one dimension). weights : ndarray Array with the weights of the same size of `data`. Returns ------- median : float The output value. ...
f259dd036777380e50f9030d728c1d80c1f5ebaa
3,623,909
import os def find_source_files( path, extensions=(".ts", ".py"), skip_folders=("tests", "test", "node_modules", "lib", ".git", ".ipynb_checkpoints"), ): """ Find source files in given `path`. Parameters ---------- extensions: sequence FIXME: skip_folders: sequence ...
010af90119329cc1f69343900ef2f28d8f494136
3,623,910
def from_trends_top_query_by_category(n=NUM_KEYWORDS): """ Get a set of keyword objects by querying Google Trends Each keyword obj is a dict with keys: keyword, category """ keyword_objs = [] for cid in POPULAR_CATEGORIES: yearmonth = '2016' pytrends = TrendReq(hl='en-US', t...
bf2582d60cf1f720b9f4b88838e9a22852f1f36f
3,623,911
import re def get_document_type(doc): """ Return the document type lowercased Parameters ---------- doc : str The document string Returns ------- doc_type : str The document type lowercased """ type_pattern=re.compile(r'<TYPE>[^\n]+') type_i=[x[len('<TYPE>...
ea9d25e1bb414fe16f9eb1cabfad1699aa90d79f
3,623,912
from typing import List def list_vpc_cidrs(vpc_id: str, account_id: str, region: str) -> List[str]: """ Returns a list of vpc cidrs associated with a given vpc. Example use cases: 1. Get the CIDRs to install on other side of a peering. 2. See if there are any common CIDRs between two VPCs :pa...
bed0b41ff5d86fa87a89ee2aa1770871545e745e
3,623,913
from typing import Optional def _cmd_debugger_getcontext(shell, _args: [str]) -> Result: """ Print basic set of registers for the active thread context.""" if not shell._debugger: print("ERROR: /attach debugger first.") return Result.HANDLED info: Optional[Thread.Context] = shell._de...
d4cf6a4fd407a2575f065b1d1ab0825fc3ffd259
3,623,914
def _multi_dot(arrays, order, i, j, precision): """Actually do the multiplication with the given order.""" if i == j: return arrays[i] else: return np.dot(_multi_dot(arrays, order, i, order[i, j], precision), _multi_dot(arrays, order, order[i, j] + 1, j, precision), ...
fa3e01e611d2897387452af6afb785087a0e46eb
3,623,915
import time def creation_date_demographics(route, label): """Return tweet creation dates.""" dataset = {'hateval': Tweet.objects.filter(hateval=True), 'offenseval': Tweet.objects.filter(offenseval=True), 'all': Tweet.objects.all()} db = dataset.get(route) if label == 'ab...
176f48ddf37b35d4acfd82e48e00e1be3b657072
3,623,916
def array_check(lst): """ Function to check whether 1,2,3 exists in given array """ for i in range(len(lst)-2): if lst[i] == 1 and lst[i+1] == 2 and lst[i+2] == 3: return True return False
ef60b52a9d7300fa458b503f49996aec0f0831ad
3,623,917
def fastmri_unet_transform_multicoil( kspace=None, mask=None, ground_truth=None, attrs=None, fname=None, slice_id=None ): """Transform to use as input to fastMRI's Unet model for multicoil data. This is an adapted version of the code found in `fastMRI <https://github.com/facebookresearch/fastMRI/blob/m...
c420979fc7b329972abf62b5a13996d98d2f1038
3,623,918
def stylize_cartoon(image, blur_ksize=3, segmentation_size=1.0, saturation=2.0, edge_prevalence=1.0, suppress_edges=True, from_colorspace=colorlib.CSPACE_RGB): """Convert the style of an image to a more cartoonish one. This function was primarily desi...
25db74f3ffb1548ccdc0f3af98c7ea0375150c94
3,623,919
def tca_model (image: Image.Image, order: int=2) -> ndarray: """ Compute a lens model which corrects transverse chromatic aberration. Parameters: image (PIL.Image): Input image. order (int): Polynomial order of lens model. Quadratic or cubic model is ideal. Returns: ndarray: Re...
2973e69d2896a918803bdaea3e2993048ecbcf2f
3,623,920
def _group_result_from_fields(json, fields): """Helper that creates a group response object from the given fields. :param json: original JSON string :param fields: the JSON fields :return: the created group response :rtype: GroupResult """ result = api.GroupResult() result.child_group...
a3ca4c71a4231b9a537d59c04a0c471db8785c83
3,623,921
def debounce(wait): """ Decorator that will postpone a function's execution until after `wait` seconds have elapsed since the last time it was invoked. """ def decorator(fn): timer = None def debounced(*args, **kwargs): nonlocal timer def call_it(): ...
270dc56653afde86c7874ad06a18e51ef195a80c
3,623,922
from typing import List from typing import Any def list_difference(list_1: List[Any], list_2: List[Any]) -> List[Any]: """ This Function that takes two lists as parameters and returns a new list with the values that are in l1, but NOT in l2""" differ_list = [values for values in list_1 if values no...
3831d799bb40080b828ee90e2929f77ff8aeb7ba
3,623,923
def truncate_msg(msg, max_len=2000): """ Truncate a message string so it doesn't get lost (todo: automatically do this in realtime logger class) """ if len(msg) <= max_len: return msg else: trunc_info = '<log message truncated to fit buffer>' assert len(trunc_info) < max_len ...
9084975e1eee570923c01a04e7c9f170e9904909
3,623,924
def rlsp( _run, mdp, s_current, p_0, horizon, temp=1, epochs=1, learning_rate=0.2, r_prior=None, r_vec=None, threshold=1e-3, check_grad_flag=False, solver="value_iter", reset_solver=False, solver_iterations=1000, ): """The RLSP algorithm.""" check_in("...
12449a66b430f3ad6d869184a9e954e520066232
3,623,925
def load_vsmi() -> pd.DataFrame: """ """ vsmi = pd.read_csv("../statistics/h_vsmi_30.csv", sep=";") vsmi.columns = vsmi.columns.str.lower() vsmi.rename(columns={"indexvalue": "VSMI"}, inplace=True) vsmi["date"] = pd.to_datetime(vsmi["date"], format="%d.%m.%Y") vsmi.set_index("date", inplace=...
ccd3ff8d0c728108b1556860e98c1723819cd778
3,623,926
def create_app(context: GhiaContext = None) -> Flask: """ Create the Flask app. Args: context (GhiaContext, optional): If no context is provided a new default one is automatically created. Defaults to None. Returns: Flask: Newly created Flask application. """ return ghia_web_logic.create_app(context=cont...
7df41acbc2babf6f25debac1a035a74b95fdd606
3,623,927
def shift_until_PSD(M, tol): """ Add the identity until a p x p matrix M has eigenvalues of at least tol""" p = M.shape[0] mineig = np.linalg.eigh(M)[0].min() if mineig < tol: M += (tol - mineig) * np.eye(p) return M
de2cf1060a32a487c5f6c3024ce294803f60b6da
3,623,928
def iris_to_df(iris): """ Make dataframe for multiclass classification from iris data""" X, y = iris.data, iris.target iris_column_data = X.T.tolist() iris_column_names = ["col" + str(idx) for idx in range(X.shape[1])] data = {} for ind, iris_data_column in enumerate(iris_column_data): d...
f158502b90a9a1afa8ac2e48b5446f42d18ca9f0
3,623,929
def format_feedback(feedback_row, study): """Updates the feedback dict with the new information.""" formatted_feedback_row = { "success": { study.get_single_field(field["field_id"]).field_name: field["field_value"] for field in feedback_row["success"] }, "failed":...
3d6d52d6a5340b13e81ca19ee28bff28b189cbc1
3,623,930
def build_geometry(self): """Compute the curve (Line) needed to plot the object. The ending point of a curve is the starting point of the next curve in the list Parameters ---------- self : SlotW11 A SlotW11 object Returns ------- curve_list: list A list of 7 Segmen...
c27bdfe1b1d80e4a1d9c664244cfc420b14c1742
3,623,931
def validcolor(c): """Takes a color and makes it valid by clamping each value between 0 and 255""" try: ret = [clamp(int(v+0.5), 0, 255) for v in c] return type(c)(ret) except TypeError: return clamp(int(v+0.5), 0, 255)
9a3b8e869c009c7c5c71ef8a4c9b1c0692abc856
3,623,932
def give_me_the_record(primary_id, swissprot_file): """ Return a single record given with the primary id :param primary_id: A primary id :param swissprot_file: A swissprot file :return: A record with accession == primary id """ with open(swissprot_file, 'r') as fh: for record in Swis...
9272ae10c3fb6faa2abec4638a8edb36a9bd7985
3,623,933
import os import re import logging def fetch_local_files(stime, etime, localdirfmt, localdict, outdir, fnamefmt, back_time=relativedelta(years=1), remove=False): """ A routine to locate and retrieve file names from locally stored SuperDARN radar files that fit the input criteria. ...
c11cfaa01cd3a022327b5ffbaa2da819ba965191
3,623,934
import requests def ms_graph_users(licensed=False): """Query the Microsoft Graph REST API for on-premise user accounts in our tenancy. Passing ``licensed=True`` will return only those users having >0 licenses assigned. """ token = ms_graph_client_token() headers = { "Authorization": "Beare...
976ebf632e1dd6bb7eee6acc7379617e2eac082a
3,623,935
def protect_def_name(defName): """Convert a DEF name to be supported in Webots.""" protectedDefName = clean_string(defName) if len(protectedDefName) > 0 and protectedDefName[0].isdigit(): protectedDefName = "_" + protectedDefName return protectedDefName
838d66ec3d0e88bff99d63f933f079df635777fb
3,623,936
from typing import Tuple def get_blog(id: str) -> Tuple: """ Function used to fetch particular blog or return error if it is doesn't exist. :param id: blog id :return: tuple of (blog object or any error) """ blog, error = _get_blog_obj(id) if not error: blog = [blog_schema.dum...
73bd9d679d2dd50a37ff6bd46fd31be677e3f5cc
3,623,937
def padded_cross_entropy_loss(logits, labels, smoothing, vocab_size): """Calculate cross entropy loss while ignoring padding. Args: logits: Tensor of size [batch_size, length_logits, vocab_size] labels: Tensor of size [batch_size, length_labels] smoothing: Label smoothing constant, used to det...
826a53fd6af931b33b7b7ac773310d2143db8597
3,623,938
import io import os import logging import re def ATL06_to_dataframe(FILENAME, beams=DEFAULT_BEAMS, groups=DEFAULT_GROUPS, **kwargs): """ Reads ICESat-2 ATL06 (Land Ice Along-Track Height Product) data files Arguments --------- FILENAME: full path to ATL06 file Keyword Arguments ...
237af4c636465629050f6c55db6f2570efd44144
3,623,939
from typing import List def get_neighboring_connectivity(cm: np.ndarray) -> List[float]: """ Get how strong neighboring classes are connected. Parameters ---------- cm : np.ndarray Returns ------- con : List[float] """ con = [] n = len(cm) for i in range(n - 1): ...
ba92b09ed1845eb5545d353df59f52f8032fab13
3,623,940
def autocov(x): """ Calculate the auto-covariance of a signal. This assumes that the signal is wide-sense stationary Parameters ---------- x: 1-d float array The signal Returns ------- nXn array (where n is x.shape[0]) with the autocovariance matrix of the signal x Not...
6f4f1855b9e0b4f237fbcaecdd911f51cf9c8707
3,623,941
import os import torch def set_apex_params(local_rank): """ Setting distributed parameters for Apex """ if 'WORLD_SIZE' in os.environ: world_size = int(os.environ['WORLD_SIZE']) global_rank = int(os.environ['RANK']) print('GPU {} has Rank {}'.format( local_rank, gl...
f7fcf48c560e29e408286fa7923576b5c6086f83
3,623,942
def correlation(self, column_a, column_b): """ Calculate correlation for two columns of current frame. Parameters ---------- :param column_a: (str) The name of the column from which to compute the correlation. :param column_b: (str) The name of the column from which to compute the correlation....
b8f1600e0b2968ca4013418b2fbfda0b13f5911a
3,623,943
import platform import os import ctypes def load_library(): """Loads the MagickWand library. :returns: the MagickWand library and the ImageMagick library """ libpath = None system = platform.system() magick_home = os.environ.get('MAGICK_HOME') if magick_home: if system == 'Windo...
d4037d7a8a404076f5a86a26ad28db0bb369b38d
3,623,944
def get_ax(rows=1, cols=1, size=8): """Return a Matplotlib Axes array to be used in all visualizations in the notebook. Provide a central point to control graph sizes. Change the default size attribute to control the size of rendered images """ _, ax = plt.subplots(rows, cols, figsize=(size...
c5d16b65dc5e505143062c49847b54b1e84717e6
3,623,945
import logging def workflow(func, **kwargs): """ Desc :param func: :param kwargs: :return: """ def inner(*args, **kwargs): """ Desc :param args: :param kwargs: :return: """ logging.debug("workflow args: %s %s",str(args), str(kwargs)) ...
3bb746bb2ab0190d9f5fc35e332ebcc3ee5407fe
3,623,946
def multiply(a, b, out=None, increment=False, stream=None): """Element-wise product of `a` and `b`.""" dtype = a.dtype if out is None: out = gpuarray.zeros(a.shape, dtype=dtype) assert a.size == b.size assert a.dtype == b.dtype == out.dtype block = (min(a._block[0], a.size), 1, 1) ...
0886834e18d6c6ba7abab5e41943d752d9c8fd6c
3,623,947
import numpy as np def uv2spd_dir(u,v): """ converts u, v meteorological wind components to speed/direction where u is velocity from N and v is velocity from E (90 deg) usage spd, dir = uv2spd_dir(u, v) """ spd = np.zeros_like(u) dir = np.zeros_like(u) spd = np.sqrt(u**2 + v**2) ...
21525616f97974ba7463fe137f07ef7e7a728fe1
3,623,948
def adjacency_mat(x_all, y_all, ox, oy, rr): """ Function that creates the adjacency matrix from the edges and points with the no restriction method """ n = len(x_all) A = np.zeros((n, n)) road_map = [] for i in range(n): temp = [] for j in range(n): if i ==...
f66af74b37d8d2385720e71be31cef3446155afd
3,623,949
import os import string def get_file_list(dir, pattern, suffix, sort_order): """ Makes a sorted list of files with fully-qualified path which have pattern in the filename, and end with suffix. Sorted in the order specified. NOTE: does NOT use index files to make list. """ dir_list = os.listdi...
afe475dcfc06a1b207773cb55ed989e3a4429221
3,623,950
from typing import Counter def calcEOAutomorphisms(tree) : """ Computes the size of the automorphism group of the input :py:obj:`tree`. We think of :py:obj:`tree` as a rooted tree, whose vertices are decorated by degrees and which has additional "exterior" edges of two distinct types, corresponding to the bounda...
c10d579df582444339c0d0fe5859f37ed1bad4bd
3,623,951
def cisco_ios_simple_config(): """Creares raw cisco config of comments etc.""" with open( CISCO_IOS_SIMPLE_CONFIG_PATH, mode="r", errors="ignore", encoding="ascii" ) as config_file: raw_config = config_file.readlines() config = [] for line in raw_config: line = line.rstrip() ...
48e7177a99b5b2b2f196a9fff6f8e175f37dd389
3,623,952
def RRIMAPublicDashboard(request,id=0): """ :param request: :param id: :return: """ ## retrieve program model = Program program_id = id getProgram = Program.objects.all().filter(id=program_id) ## retrieve the coutries the user has data access for countries = getCountry(requ...
c5c9273d5017397eecdd99ee78bf318d45440f17
3,623,953
def get_workflows_requests(module): """Returns all requests for specified workflow""" return Request.objects.filter(module_ref=module)
6e634ded8f7c0b1dc147d276a8d9749205e9d991
3,623,954
def cwd_hg_version(short=False): """Get the Mercurial changeset hash of the repository that contains the current working directory. If ``short`` is True, the short (12-character) form of the changeset hash will be returned. If the current working copy of the repository is modified, a plus sign is append...
4a1f369cd635230c44d4725b13b9704700d5bf3b
3,623,955
from typing import List from typing import Dict def parse_idf(content: str) -> dict: """Parse an IDF file into a dictionary.""" sections = content.rstrip().split(';') sub_sections: List[List[str]] = [] obj_dict: Dict[str, List[List[str]]] = {} for sec in sections: sec_lines = sec.splitline...
9232964d590745482bb0552520b7ad42ebce8d94
3,623,956
from pathlib import Path import joblib def _make_item_rec_sys_data(review_data): """ Generates item_rec_sys_data by obfuscating customer ids. Parameters ---------- review_data: combined_data. Yields ------ item_rec_sys_data.csv Returns ------- item_rec_sys_da...
868cae8a54513be3a129fdf7f38320652f265733
3,623,957
def system_order(tf: scipysig.dlti) -> tuple: """Returns the order of the numerator and denominator of a transfer function Parameters ---------- tf : scipy.signal.dlti discrete time rational transfer function Returns ---------- (num, den): tuple Tuple containing the o...
d432e61758ceed35f3f5f1eeadf41c2080d137c6
3,623,958
def drvit_small_patch16_384(pretrained=False, **kwargs): """ ViT-Small (ViT-S/16) NOTE I've replaced my previous 'small' model definition and weights with the small variant from the DeiT paper """ model_kwargs = dict(patch_size=16, embed_dim=384, depth=12, num_heads=6, **kwargs) model = _create_visi...
e9c59e19c98f17318fb058a8c2262fb8d40f0e79
3,623,959
def pdist_block(pdist_vec, i, j): """Slice the pdist ndarray as if it were a squareform matrix. Args: pdist_vec: ndarray output from pdist() i: ndarray row index of matrix j: ndarray col index Returns: (i.size, j.size) ndarray from distance matrix """ col_ind, row_ind = np.meshgrid(...
4ad2ba8694aa1fb6396d1c396c33264642451d25
3,623,960
def ufile_put_url(bucket, key): """ 采用普通上传方法上传UCloud UFile文件的url :param bucket: string类型, 待创建的空间名称 :param key: string类型, 在空间中的文件名 :return: string类型, 普通上传UFile的url """ return 'http://{0}{1}/{2}'.format(bucket, config.get_default('upload_suffix'), key)
a5bc7ab0bed9dc6368b7ca985c9f5bcb004378e4
3,623,961
from typing import Optional def build_assemblenet_model( input_specs: tf.keras.layers.InputSpec, model_config: cfg.AssembleNetModel, num_classes: int, l2_regularizer: Optional[tf.keras.regularizers.Regularizer] = None): """Builds assemblenet model.""" input_specs_dict = {'image': input_specs} ba...
017347267a768b58609c9bb24faefe0bcb0b5cd5
3,623,962
import httpx async def post_donation(donation_id: str) -> tuple: """Post donations to their respective third party APIs If the donation has already been posted, it will not be posted again. """ donation = await get_donation(donation_id) if not donation: return (jsonify({"message": "Donati...
84fd0e7a975cf913b79b2fa91a1569b25f4bdb8d
3,623,963
import transformers from typing import List import torch import tqdm def predict_in_batches( model: transformers.models, tokenizer, dataset: List[str], batch_size: int = 4 ) -> List[int]: """Predicts the labels for the entries in dataset using the model passed :param model: the model to use for prediction...
e21a668c2181acd076b565bbde379b028cbeead6
3,623,964
def remove_punctuation(sentence: str, punctuation: str = None): """ Default Punctuation -> [',', '!', '#', '$', '%', "'", '*', '+', '-', '.', '/', '?', '@', '\\', '^', '_', '~'] """ punctuation = punctuation or ''.join(PUNCTUATION) for x in punctuation: sentence = sentence.replace(x, '') ...
2b421a69efdb2bb58f1c778725953ceb2357394d
3,623,965
def get_digest_for(changelogs, before_date=None, after_date=None, limit_versions=5): """Before date and after date are inclusive.""" # search packages which have changes after given date # we exclude unreleased changes from digest # because they ...
73dd266b3a02d9a4a1f499937f630605e2918582
3,623,966
import os import time def count_time(func): """类中使用的计时装饰器""" def inner(*args, **kwargs): print('{} 进程数据处理开始'.format(os.getpid())) start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print('{} 进程数据处理完成,处理数据用时:{}'.format(os.getpid(), end_time -...
2b7cdff3e308500b9c3509bc0d4c626b118eca36
3,623,967
import pkg_resources def get_version(): """Returns version""" return pkg_resources.get_distribution("rosetta-cipher").version
4a9e67434e8a1884e44dafaa30ffaf8c5ec5025d
3,623,968
def good_fft_number(goal): """pick a number >= goal that has only factors of 2,3,5. FFT will be much faster if I use such a number""" assert goal < 1e5 choices = [2**a * 3**b * 5**c for a in range(17) for b in range(11) for c in range(8)] return min(x for x in choic...
e469a37f28869dca520aea3520fa0d763e9bb8ae
3,623,969
def adjust_image_resolution(data): """Given image data, shrink it to no greater than 1024 for its larger dimension.""" output_large = cStringIO.StringIO() output_default = cStringIO.StringIO() output_tiny = cStringIO.StringIO() try: im0 = Image.open(cStringIO.StringIO(data)) ...
06a6048efbc11fdc7c151feacbb4eddfa46ad90a
3,623,970
def connect_to_ecs(env): """ Return boto connection to the ecs in the specified environment's region. """ rh = env.resource_handler.cast() wrapper = rh.get_api_wrapper() client = wrapper.get_boto3_client( 'ecs', rh.serviceaccount, rh.servicepasswd, env.aws_region ...
e4c0b7ad80c18fd6d2a90df6670ca9bfa6f1cbe3
3,623,971
import random def dsa_sign(message, private, constants=None): """DSA signs the bytestring `message` with the given private key and returns the signature (r, s) using the hash SHA1""" p, q, g = get_dsa_constants(constants) while True: k = random.randint(1, q - 1) r = pow(g, k, p) % q ...
780fd6370f0a73ca6ee3d761ffb21b5f6d6efaf1
3,623,972
def _pytesmo_to_qa4sm_results(results: dict) -> dict: """ Converts the new pytesmo results dictionary format to the old format that is still used by QA4SM. Parameters ---------- results : dict Each key in the dictionary is a tuple of ``((ds1, col1), (d2, col2))``, and the values...
f4f36562a65dd140a16b3969fe26a3450e7f9037
3,623,973
import argparse import json import os from pathlib import Path def provision_greengrass(arguments: argparse) -> dict: """Orchstrates and completes all provisioning processes based on incoming validated argument list :param arguments: Validated command line arguments :type arguments: argparse ...
d51b90604962c89449df4cf5fe6a2bc8904f0fd3
3,623,974
def infotodict(seqinfo): """Heuristic evaluator for determining which runs belong where allowed template fields - follow python string module: item: index within category subject: participant id seqitem: run number during scanning subindex: sub index within group """ info = {'test':[]...
ea5c334452cbc3e5fd700c38f258578b26f9cf56
3,623,975
def load_vgg(sess, vgg_path): """ Load Pretrained VGG Model into TensorFlow. :param sess: TensorFlow Session :param vgg_path: Path to vgg folder, containing "variables/" and "saved_model.pb" :return: Tuple of Tensors from VGG model (image_input, keep_prob, layer3_out, layer4_out, layer7_out) """...
f754449adf355e3462bafb6ecb6fbed2ad0b5c6f
3,623,976
def grab_svg(scene): """ Return a SVG rendering of the scene contents. Parameters ---------- scene : :class:`CanvasScene` """ svg_buffer = QBuffer() gen = QSvgGenerator() gen.setOutputDevice(svg_buffer) items_rect = scene.itemsBoundingRect().adjusted(-10, -10, 10, 10) if ...
a4292ff99062be7a110f31aafc4ee50f88618b58
3,623,977
def get_bel_node_uniprot(): """Get UniProt related eBEL nodes.""" b = Bel() conf = { 'rid': "@rid.asString()", 'name': "name", 'namespace': "namespace", 'bel': "bel", 'uniprot_accession': "uniprot" } sql = "SELECT " sql += ', '.join([f"{v} as {k}" for k, v...
ff38ba4f8daaa12549c482a2b7b7bd7444e21750
3,623,978
import torch def decode_ori_batch(ori, b): """Decode a batch of orientation (ori) using the pre-computed orientation decode variable (b) based on the histogram (see pre_compute_ori_decode) """ ori = ori.cpu() batch_size = ori.size(0) ori_avg = torch.zeros((batch_size, 4), dtype=torch.float32...
a6acac339d3cf0613b733d0258ba21d1c8c57d9f
3,623,979
from datetime import datetime def receive_email(msg_str): """ Given a string representation of an email message, parses it into a :class:`~kiki.message.KikiMessage`. Returns a (message, created) tuple, where ``created`` is False if the message was already in the database. """ received = datetime.now() python_m...
58a7bbc758be4eb48d71794452dab18a2ae307b4
3,623,980
def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array """ high = len(input_list) - 1 low = 0 while low <= high: mid = (low + high) // 2 if input_list[mid] == number: return mid elif input_list[mid] < number <= ...
c3deb50e608c58e5e11665d949a602cc661305ae
3,623,981
def parse_sentence_spacy(sentence_text, sentence_entities): """ :param sentence_text: :param sentence_entities: :return: """ # Use spacy to parse a sentence for e in sentence_entities: idx = sentence_entities[e][0] sentence_text = sentence_text[:idx[0] - 1] + sentence_text[...
b6da3a1f5dc02196286c666fa268ad7cfadb4c40
3,623,982
def check_for_deprecated_generators(main, file): """ Check if the conan file if using some deprecated generator :param main: Output stream :param file: Conanfile path """ conan_instance, _, _ = conan_api.Conan.factory() dict_generators = conan_instance.inspect(path=file, attributes=["generators...
a281e6b7e3ff48a49830a19c2bbb2fe9907d1e8d
3,623,983
def get_chat_members_count(chat_id, **kwargs): """ Use this method to get the number of members in a chat. :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :param kwargs: Args that get passed down to :class:`TelegramBotRPCRequest` ...
1cec0d216fd3c1f28c1592cf2be170c26f32780a
3,623,984
def sample_tag(user, name='Sample tag'): """Create and reutn a sample tag""" return Tag.objects.create(user=user, name=name)
985d40292258efa4fb997a1f68a1ca523c43df02
3,623,985
def _unpack_keypoints(keypoints): """Unpack the keypoints into an array of coordinates. Args: keypoints: a list of `cv2.KeyPoint`s Returns: an n x 2 array of [row, col] coordinates """ return np.array([[kp.pt[1], kp.pt[0]] for kp in keypoints])
a594c580729750f493703310e067abe3196650a4
3,623,986
def get_videos(): """Return a json array of all videos available on the site, built by fetching each page sequentially until there are no more pages.""" videos = [] page = 0 end_of_pages = False while not end_of_pages: page += 1 url = "http://pyvideo.org/api/v2/video?page=%s" % s...
8e3e5e2cea320fcdaf9ce819d06d59db97881ec5
3,623,987
import click def input_mon(ctx): """ Monitors all pins for changes. Expects ANSI terminal color. """ click.echo("Ctrl-\\ to quit") d = CM119_IO(ctx.obj["vid"], ctx.obj["pid"]) d.set_dir({pin: "I" for pin in range(1, 9)}) # All GPIOs as inputs def pin_formatter(pin_name, state): """Helpe...
905ad5433fcb5c774f43b0ac143326367ab46bbd
3,623,988
def make_fake_symbol_from_data_type( data_type, symbol_pragma_text, *, name='$(SYMBOL)', pragma_name: str = 'pytmc', data_area_index=0, tmc=None, create_data_area_if_needed=True): """ Create a :class:`_FakeSymbol` from the given data type. Parameters ---------- data_...
d3bfde296814d4ba3327707225f40aa19ee08357
3,623,989
from typing import Optional def has_at_least_one_share_class(filing_json, filing_type) -> Optional[str]: # pylint: disable=too-many-branches """Ensure that share structure contain at least 1 class by the end of the alteration or IA Correction filing.""" if filing_type in filing_json['filing'] and 'shareStruc...
ce0e324edd1fb4e427aafdedcdecafc736fdb8d0
3,623,990
def get_image_table(nova_endpoint=None): """ :param nova_endpoint: :return: """ image_list = PrettyTable() image_list.field_names = ["ID", "Name", "Format", "Size", "Min Ram", "Mind Disk", "location", "adpter type", "status", "checksum"] glance_list = nova_en...
4d2b0c7d0d2bc222c3d57e38f2483e5165999a5f
3,623,991
def color_thresholding(img, thresh_h=None, thresh_s=None, thresh_l=None): """ Crete image mask using color thresholding. :param img: source bgr image :param thresh_h: tuple(min,max), hue threshold in HSL color space :param thresh_s: tuple(min,max), saturation threshold in HSL color space :retur...
387de7a3935431659de8b45e56efed0e4d38dc0f
3,623,992
import builtins def no_matplotlib(monkeypatch): """ Mock an import error for matplotlib""" import_orig = builtins.__import__ def mocked_import(name, globals, locals, fromlist, level): """ """ if name == 'matplotlib.pyplot': raise ImportError("This is a mocked import error") ...
681ba8c0e70387e46ad7ed42ffb11ce8aa7f23bc
3,623,993
def _get_center_context( context_window_type, walks, n_walks, walk_len, window_length, padding_id ): """Get center and context pairs from a sequence window_type = {-1,0,1} specifies the type of context window. window_type = 0 specifies a context window of length window_length that extends both left ...
d09b224341e3ceec2eb69ad3e7d0a03a1ea2035b
3,623,994
def get_files(pga_id): """ Get all uploaded YAML files as a dictionary. :return: dict of uploaded YAML files as JSON """ files_dict = utils.get_uploaded_files_dict(pga_id) return jsonify(files_dict)
b2ab923de32a9ac9eee42dbebb218f075f4ea266
3,623,995
def convert_mask_to_pick(mask, sample_rate, threshold): """Convert a first breaks `mask` into an array of arrival times. The mask has shape (n_traces, trace_length), each its value represents a probability of corresponding index along the trace to follow the first break. A naive approach is to define the f...
615c168bb119a8db1acb5581fa391ef6384c3f44
3,623,996
import tqdm def create_tqdm_reader(reader, max_reads=None): """Wrap an iterable in a tqdm progress bar. Args: reader: The iterable to wrap. max_reads: Max number of items, if known in advance. Returns: The wrapped iterable. """ return tqdm.tqdm(reader, total=max_r...
29bd93b85ace167f5586ac275510e82f7bbe8223
3,623,997
def calc_U_slip_quasisteady(eps, E, x, mu): """ Slip velocity (quasi-steady limit) """ u_slip_quasisteady = -eps*E**2*x/(2*mu) return u_slip_quasisteady
0b5eebc9333b36cbd4b8179731e5998f7cb2739a
3,623,998
def momentum(df, column='close', n=20, add_col=False, return_struct='numpy'): """ Momentum Parameters ---------- df : Pandas DataFrame A Dataframe containing the columns open/high/low/close/volume with the index being a date. open/high/low/close should all be floats. volume ...
72d4c5746e40d2ea70a9527d443249fe850401f7
3,623,999