content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Dict from typing import Any import toml from pathlib import Path import textwrap def load_configuration() -> Dict[str, Any]: """ Return dict from TOML formatted string or file. Returns: The dict configuration. """ default_config = """ [key_bindings] ...
a7a53382dd43023b74fbb88b9c2540499c9beb4f
8,900
def type_weapon(stage, bin, data=None): """Weapon""" if data == None: return 1 if stage == 1: return (str(data),'') try: v = int(data) if 0 > v or v > 255: raise except: raise PyMSError('Parameter',"Invalid Weapon value '%s', it must be 1 for ground attack or not 1 for air attack." % data) return v
51ad1c627b05b57ad67f5558bb76de3fe6e48f27
8,901
def to_square_feet(square_metres): """Convert metres^2 to ft^2""" return square_metres * 10.7639
50510aad230efcb47662936237a232662fef5596
8,902
def middle_name_handler(update: Update, context: CallbackContext) -> str: """Get and save patronymic of user. Send hello with full name.""" u = User.get_user(update, context) name = (f'{context.user_data[LAST_NAME]} {context.user_data[FIRST_NAME]} ' f'{context.user_data[MIDDLE_NAME]}') cont...
dab2144282aeb63c2a3c4218236d04c3bb940ac8
8,903
def submit_barcodes(barcodes): """ Submits a set of {release1: barcode1, release2:barcode2} Must call auth(user, pass) first """ query = mbxml.make_barcode_request(barcodes) return _do_mb_post("release", query)
6e975e791196ed31ef6f52cdd0ca04d71a8d19eb
8,904
from typing import Counter def get_idf_dict(arr, tokenizer, nthreads=4): """ Returns mapping from word piece index to its inverse document frequency. Args: - :param: `arr` (list of str) : sentences to process. - :param: `tokenizer` : a BERT tokenizer corresponds to `model`. - :pa...
e98a9578695781e4965b36d713c4c0a4351e53da
8,905
import json def load_id_json_file(json_path): """ load the JSON file and get the data inside all this function does is to call json.load(f) inside a with statement Args: json_path (str): where the target JSON file is Return: ID list (list): all the d...
fd0f7fb73636cdf407b4de3e1aa3ae66dcc8f964
8,906
def check_github_scopes(exc: ResponseError) -> str: """ Parse github3 ResponseError headers for the correct scopes and return a warning if the user is missing. @param exc: The exception to process @returns: The formatted exception string """ user_warning = "" has_wrong_status_code = e...
ebb3fffcaddc792dac7c321d9029b5042a42be86
8,907
def user_login(): """ # 显示页面的设置 :return: 接收前端的session信息来显示不同的页面 """ # 获取参数 name = session.get("name") if name is not None: return jsonify(errno=RET.OK, errmsg="True", data={"name": name}) else: return jsonify(errno=RET.SESSIONERR, errmsg="用户未登入")
213ad2338260364186c0539a9e995b84ee889b42
8,908
def sample_conditional(node: gtsam.GaussianConditional, N: int, parents: list = [], sample: dict = {}): """Sample from conditional """ # every node ~ exp(0.5*|R x + S p - d|^2) # calculate mean as inv(R)*(d - S p) d = node.d() n = len(d) rhs = d.reshape(n, 1) if len(parents) > 0: rhs...
b9ab05ea50eea05a779c6d601db4643a86b343d5
8,909
def _liftover_data_path(data_type: str, version: str) -> str: """ Paths to liftover gnomAD Table. :param data_type: One of `exomes` or `genomes` :param version: One of the release versions of gnomAD on GRCh37 :return: Path to chosen Table """ return f"gs://gnomad-public-requester-pays/relea...
8da0f93c86568d56b3211bcb9e226b9cb495c8e2
8,910
def valueinfo_to_tensor(vi): """Creates an all-zeroes numpy tensor from a ValueInfoProto.""" dims = [x.dim_value for x in vi.type.tensor_type.shape.dim] return np.zeros( dims, dtype=onnx.mapping.TENSOR_TYPE_TO_NP_TYPE[vi.type.tensor_type.elem_type] )
b814373e7c9d4f1e43f9d1af0c6e48b82989602e
8,911
def signup_email(): """Create a new account using data encoded in the POST body. Expects the following form data: first_name: E.g. 'Taylor' last_name: E.g. 'Swift' email: E.g. 'tswift@gmail.com' password: E.g. 'iknewyouweretrouble' Responds with the session cookie via the `...
e3ecca4bd244d1d20ad166a153a6c3f5c80f4876
8,912
def calculate_multi_rmse(regressor, n_task): """ Method which calculate root mean squared error value for trained model Using regressor attributes Return RMSE metrics as dict for train and test datasets :param regressor: trained regression model object :param n_task: :type regressor: Traine...
53daee6abb97a96af44831df59767a447fd2786e
8,913
import torch from re import T def detr_predict(model, image, thresh=0.95): """ Function used to preprocess the image, feed it into the detr model, and prepare the output draw bounding boxes. Outputs are thresholded. Related functions: detr_load, draw_boxes in coco.py Args: model -- the...
394824358138eb66b69569963b21ccc2d0f5a4d3
8,914
def comp_fill_factor(self): """Compute the fill factor of the winding""" if self.winding is None: return 0 else: (Nrad, Ntan) = self.winding.get_dim_wind() S_slot_wind = self.slot.comp_surface_wind() S_wind_act = ( self.winding.conductor.comp_surface_active() ...
55be8ac7aa2961ad970cd16de961fdcf857016fd
8,915
def idewpt(vp): """ Calculate the dew point given the vapor pressure Args: vp - array of vapor pressure values in [Pa] Returns: dewpt - array same size as vp of the calculated dew point temperature [C] (see Dingman 2002). """ # ensure that vp is a numpy array ...
68b58d7702a50472a4851e1a7ecdd6ba13fe540a
8,916
def _hexify(num): """ Converts and formats to hexadecimal """ num = "%x" % num if len(num) % 2: num = '0'+num return num.decode('hex')
71fabff1191f670ec503c76a3be916636e8045ce
8,917
def syn_ucbpe(num_workers, gp, acq_optimiser, anc_data): """ Returns a recommendation via UCB-PE in the synchronous setting. """ # Define some internal functions. beta_th = _get_ucb_beta_th(gp.input_dim, anc_data.t) # 1. An LCB for the function def _ucbpe_lcb(x): """ An LCB for GP-UCB-PE. """ mu, sigm...
2c12a608c87d61f64b219aaf301189b6c8ee73a2
8,918
def get_reward(intervention, state, time): """Compute the reward based on the observed state and choosen intervention.""" A_1, A_2, A_3 = 60, 500, 60 C_1, C_2, C_3, C_4 = 25, 20, 30, 40 discount = 4.0 / 365 cost = ( A_1 * state.asymptomatic_humans + A_2 * state.symptomatic_humans ...
72803b1a5f09d0856d29601bc766b6787a8255e7
8,919
def array_of_floats(f): """Read an entire file of text as a list of floating-point numbers.""" words = f.read().split() return [builtin_float(x) for x in words]
8b357afb3f977761118f7df2632a4f1c198d721a
8,920
def change_currency(): """ Change user's currency """ form = CurrencyForm() if form.validate_on_submit(): currency = form.rate.data redirected = redirect(url_for('cashtrack.overview')) redirected.set_cookie('filter', currency) symbol = rates[currency]['symbol'] flash(...
08a23e47a603ee5d5e49cff0259a83f4a2ffc3e0
8,921
import subprocess def get_host_checks(): """ Returns lxc configuration checks. """ out = subprocess.check_output('lxc-checkconfig', shell=True) response = [] if out: for line in out.splitlines(): response.append(line.decode('utf-8')) info = { 'checks': respo...
d94b3b94ec6f32e2706eaf7b67f570de2fc34f14
8,922
def q2_1(df: pd.DataFrame) -> int: """ Finds # of entries in df """ return df.size[0]
d98a3d5592994e7dd3758dfab683cb96b532ce6d
8,923
def is_shell(command: str) -> bool: """Check if command is shell.""" return command.startswith(get_shell())
0cc1497dc17e1535fdfb23c1b160bfcd63141eb1
8,924
import argparse def parse_args(): """set and check parameters.""" parser = argparse.ArgumentParser(description="bert process") parser.add_argument("--pipeline_path", type=str, default="./config/fat_deepffm.pipeline", help="SDK infer pipeline") parser.add_argument("--data_dir", type=str, default="../da...
d93eca1a5c36d73944762967bf6557ee5e15d346
8,925
def board_init(): """ Initializes board with all available values 1-9 for each cell """ board = [[[i for i in range(1,n+1)] for j in range(n)] for k in range(n)] return board
e4b7192c02e298de915eb3024f32f194942a061b
8,926
def gen_int_lists(num): """ Generate num list strategies of integers """ return [ s.lists(s.integers(), max_size=100) for _ in range(num) ]
f1bd151a09f78b1eee9803ce2a077a4f01d34aaa
8,927
def is_blob(bucket: str, file:str): """ checking if it's a blob """ client = storage.Client() blob = client.get_bucket(bucket).get_blob(file) return hasattr(blob, 'exists') and callable(getattr(blob, 'exists'))
ba9bb07f1f15175a28027907634c37b402c6b292
8,928
def rotate(q, p): """ Rotation of vectors in p by quaternions in q Format: The last dimension contains the quaternion components which are ordered as (i,j,k,w), i.e. real component last. The other dimensions follow the default broadcasting rules. """ iw = 3 ii = 0 i...
da8c715276d5bef0340ad3378aa127c9ddb75f96
8,929
from typing import Union def _is_whitelisted(name: str, doc_obj: Union['Module', 'Class']): """ Returns `True` if `name` (relative or absolute refname) is contained in some module's __pdoc__ with a truish value. """ refname = doc_obj.refname + '.' + name module = doc_obj.module while modul...
c54c69ae0180c1764c8885d00e96640f1bfff0f8
8,930
import copy def permute_bond_indices(atomtype_vector): """ Permutes the set of bond indices of a molecule according to the complete set of valid molecular permutation cycles atomtype_vector: array-like A vector of the number of each atoms, the length is the total number of atoms. An A3B8C ...
ebf398e55d8a80a2e4ce2cef4f48d957e47d68a3
8,931
def get_cell_integer_param(device_resources, cell_data, name, force_format=None): """ Retrieves definition and decodes value of an integer cell parameter. The function can optionally force a specific encoding format if needed. ...
6ab281004f324e8c40e176d5676cd7e42f50eaa9
8,932
import hashlib def get_md5(filename): """ Calculates the MD5 sum of the passed file Args: filename (str): File to hash Returns: str: MD5 hash of file """ # Size of buffer in bytes BUF_SIZE = 65536 md5 = hashlib.md5() # Read the file in 64 kB blocks ...
c43538aee954f670c671c2e26e18f4a17e298455
8,933
import os def get_py_path(pem_path): """Returns the .py filepath used to generate the given .pem path, which may or may not exist. Some test files (notably those in verify_certificate_chain_unittest/ have a "generate-XXX.py" script that builds the "XXX.pem" file. Build the path to the corresponding "genera...
0bc97d23138c44e051282fdfa22517f1289ab65a
8,934
def is_recurrent(sequence): """ Returns true if the given sequence is recurrent (elements can exist more than once), otherwise returns false. Example --------- >>> sequence = [1,2,3,4,5] >>> ps.is_recurrent(sequence) False >>> sequence = [1,1,2,2,3] >>> ps.is_recurrent(sequence) True """ element_counts...
e123ddd960b262651b20e54ccbd3d5b11fe3695e
8,935
import torch def flex_stack(items, dim=0): """ """ if len(items) < 1: raise ValueError("items is empty") if len(set([type(item) for item in items])) != 1: raise TypeError("items are not of the same type") if isinstance(items[0], list): return items elif isinstance(it...
47ca0e47647ce86619f1cdc86eef560fbbb9304e
8,936
from pathlib import Path def download_image_data(gpx_file, padding, square, min_lat, min_long, max_lat, max_long, cache_di...
4ceef45da21622ab716031e8f68ed4724e168062
8,937
def find_nearest_values(array, value): """Find indexes of the two nearest values of an array to a given value Parameters ---------- array (numpy.ndarray) : array value (float) : value Returns ------- idx1 (int) : index of nearest value in the array idx2 (int) : index of s...
9c873692878ef3e4de8762bb89306e7ef907f90a
8,938
def channel_info(channel_id): """ Get Slack channel info """ channel_info = slack_client.api_call("channels.info", channel=channel_id) if channel_info: return channel_info['channel'] return None
260eeaa2849350e2ede331ddecd68aead798f76c
8,939
from typing import Callable from typing import Any import logging def log(message: str) -> Callable: """Returns a decorator to log info a message before function call. Parameters ---------- message : str message to log before function call """ def decorator(function: Callable) -> Cal...
c8ed8f8119be8d6e80935d73034f752ad2cb1dd9
8,940
def client(identity: PrivateIdentity) -> Client: """Client for easy access to iov42 platform.""" return Client(PLATFORM_URL, identity)
a0ad172765b50a76485bd3ec630a2c3ffeae85ef
8,941
def init_weights(module, init='orthogonal'): """Initialize all the weights and biases of a model. :param module: any nn.Module or nn.Sequential :param init: type of initialize, see dict below. :returns: same module with initialized weights :rtype: type(module) """ if init is None: # Base ...
e8cd95743b8a36dffdb53c7f7b9723e896d2071d
8,942
def getsoundchanges(reflex, root): # requires two ipastrings as input """ Takes a modern-day L1 word and its reconstructed form and returns \ a table of sound changes. :param reflex: a modern-day L1-word :type reflex: str :param root: a reconstructed proto-L1 word :type root: str :re...
8230e836e109ed8453c6fdbc72e6a4f77833f69b
8,943
def compute_normals(filename, datatype='cell'): """ Given a file, this method computes the surface normals of the mesh stored in the file. It allows to compute the normals of the cells or of the points. The normal computed in a point is the interpolation of the cell normals of the cells adiacent to ...
e0cfc90a299f6db52d9cec2f39eebfc96158265c
8,944
from typing import List from typing import Optional def build_layers_url( layers: List[str], *, size: Optional[LayerImageSize] = None ) -> str: """Convenience method to make the server-side-rendering URL of the provided layer URLs. Parameters ----------- layers: List[:class:`str`] The ima...
2cc7ab58af2744a4c898903d9a035c77accbae2e
8,945
def SyncBatchNorm(*args, **kwargs): """In cpu environment nn.SyncBatchNorm does not have kernel so use nn.BatchNorm2D instead""" if paddle.get_device() == 'cpu': return nn.BatchNorm2D(*args, **kwargs) else: return nn.SyncBatchNorm(*args, **kwargs)
f08a7141700b36286893bbbc82b28686d1ca88a9
8,946
def data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_peak_burst_size_get(uuid, local_id): # noqa: E501 """data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_peak_burst_size_get returns tapi.common.Capac...
340189bc76bdbbc14666fe542aa05d467c7d4898
8,947
import re def parse_path_length(path): """ parse path length """ matched_tmp = re.findall(r"(S\d+)", path) return len(matched_tmp)
762e2b86fe59689800ed33aba0419f83b261305b
8,948
def check_permisions(request, allowed_groups): """ Return permissions.""" try: profile = request.user.id print('User', profile, allowed_groups) is_allowed = True except Exception: return False else: return is_allowed
4bdb54bd1edafd7a0cf6f50196d470e0d3425c66
8,949
def kanji2digit(s): """ 1から99までの漢数字をアラビア数字に変換する """ k2d = lambda m, i: _kanjitable[m.group(i)] s = _re_kanjijiu1.sub(lambda m: k2d(m,1) + k2d(m,2), s) s = _re_kanjijiu2.sub(lambda m: u'1' + k2d(m,1), s) s = _re_kanji.sub(lambda m: k2d(m,1), s) s = s.replace(u'十', u'10') return s
27589cee8a9b4f14ad7120061f05077b736b8632
8,950
def calc_rdm_segment(t, c, segment_id_beg, segment_id_end, segment_id, ph_index_beg, segment_ph_cnt, debug=0): """ Function to calculate radiometry (rdm) Input: t - time or delta_time of ATL03, for a given gt num c - classification of ATL03 for a given gt num ensure that no nan...
47ac61f816a5f8e9c3f86c5b1e8ad2f9f660f8a2
8,951
def load_featurizer(pretrained_local_path): """Load pretrained model.""" return CNN_tf("vgg", pretrained_local_path)
1f39acdae01e484302d8f8051c2f55a178aa2301
8,952
import os import zipfile def create_zipfile(dir_to_zip, savepath=''): """Create a zip file from all the files under 'dir_to_zip'. The output zip file will be saved to savepath. If savepath ends with '.zip', then the output zip file will be saved AS 'savepath'. Necessary tree subdirectories are create...
dd18a1272a25c3fb272345fc8b71a303c6cc4053
8,953
from templateflow.conf import setup_home def make_cmdclass(basecmd): """Decorate setuptools commands.""" base_run = basecmd.run def new_run(self): setup_home() base_run(self) basecmd.run = new_run return basecmd
dc66370f19e2d1b3dbc2da3942f8923a07d8d9a6
8,954
def rmse(predictions, targets): """Compute root mean squared error""" rmse = np.sqrt(((predictions - targets) ** 2).mean()) return rmse
1a5fe824c5ef768f3df34463724fdd057d37901a
8,955
import math def format_timedelta(value, time_format=None): """ formats a datetime.timedelta with the given format. Code copied from Django as explained in http://stackoverflow.com/a/30339105/932593 """ if time_format is None: time_format = "{days} days, {hours2}:{minutes2}:{seconds2}...
0ee6a48e0eee5e553e665d44173f0a4843b4007f
8,956
def categorical_log_likelihood(probs: chex.Array, labels: chex.Array): """Computes joint log likelihood based on probs and labels.""" num_data, unused_num_classes = probs.shape assert len(labels) == num_data assigned_probs = probs[jnp.arange(num_data), jnp.squeeze(labels)] return jnp.sum(jnp.log(ass...
6209fc59dc6a76f8afc49788b9e5c5a11f58354f
8,957
def ask_name(question: str = "What is your name?") -> str: """Ask for the users name.""" return input(question)
1cc9ec4d3bc48d7ae4be1b2cf8eb64a0b4f94b23
8,958
from typing import Sequence def _maxcut(g: Graph, values: Sequence[int]) -> float: """ cut by given values $$\pm 1$$ on each vertex as a list :param g: :param values: :return: """ cost = 0 for e in g.edges: cost += g[e[0]][e[1]].get("weight", 1.0) / 2 * (1 - values[e[0]] * val...
1ca8d2cfce6a741fb4eab55f7fcd9d9db5e3578f
8,959
def cp_als(X, rank, random_state=None, init='randn', **options): """Fits CP Decomposition using Alternating Least Squares (ALS). Parameters ---------- X : (I_1, ..., I_N) array_like A tensor with ``X.ndim >= 3``. rank : integer The `rank` sets the number of components to be compute...
b6402f03ba4e8be7d0abb2b13232d88b07a73be9
8,960
import os def load_station_enu( station_name, start_date=None, end_date=None, download_if_missing=True, force_download=False, zero_by="mean", to_cm=True, ): """Loads one gps station's ENU data since start_date until end_date as a dataframe Args: station_name (str): 4 Lette...
208b6b6776ad3eb0ef765a5b56d287e7ed06e63f
8,961
def decode_hint(hint: int) -> str: """Decodes integer hint as a string. The format is: ⬜ (GRAY) -> . 🟨 (YELLOW) -> ? 🟩 (GREEN) -> * Args: hint: An integer representing the hint. Returns: A string representing the hint. """ hint_str = [] for _ ...
4180b847cd252a1e3c762431327b1b6d359dac3d
8,962
import os import tempfile import subprocess def validate_notebook(nb_path, timeout=60): """ Executes the notebook via nbconvert and collects the output Args: nb_path (string): path to the notebook of interest timeout (int): max allowed time (in seconds) Returns: (parsed nbformat....
475a11036a5330df8f82d9876731d3d688749aa8
8,963
def is_symmetric(arr, i_sym=True, j_sym=True): """ Takes in an array of shape (n, m) and check if it is symmetric Parameters ---------- arr : 1D or 2D array i_sym : array symmetric with respect to the 1st axis j_sym : array symmetric with respect to the 2nd axis Returns...
488744d34d851b690eb6114b06d754e46b04e36f
8,964
def linear_powspec(k, a): """linear power spectrum P(k) - linear_powspec(k in h/Mpc, scale factor)""" return _cosmocalc.linear_powspec(k, a)
9abe99ef5251b4b8ef04e7113a30dd26ed86d14a
8,965
def light_eff(Pmax, Iz, I0, Ik): """ Photosynthetic efficiency based on the light conditions. By definition, the efficiency has a value between 0 and 1. Parameters ---------- Pmax : numeric Maximum photosynthetic rate [-]. Iz : numeric Coral biomass-averaged light-intensity ...
a2e0de2cb0791d3afea15f4c78b7d673200504b3
8,966
import array import time def radial_kernel_evaluate(rmax, kernel, pos, wts, log=null_log, sort_data=False, many_ngb_approx=None): """ Perform evaluation of radial kernel over neighbours. Note you must set-up the linear-interpolation kernel before calling this function. ...
41c4600be3a5684c97d69acb4ebe15846dcc4b0d
8,967
def get_referents(source, exclude=None): """ :return: dict storing lists of objects referring to source keyed by type. """ res = {} for obj_cls, ref_cls in [ (models.Language, models.LanguageSource), (models.ValueSet, models.ValueSetReference), (models.Sentence, models.Senten...
2aeccbbe61cdcb2b3183682a5cce8ed959fc14c9
8,968
import array def asarray(buffer=None, itemsize=None, shape=None, byteoffset=0, bytestride=None, padc=" ", kind=CharArray): """massages a sequence into a chararray. If buffer is *already* a chararray of the appropriate kind, it is returned unaltered. """ if isinstance(buffer, kind) and...
346eaaa9ece9671f5b2fa0633552f72e40300adc
8,969
import zipfile import os import sys def _extract_symlink(zipinfo: zipfile.ZipInfo, pathto: str, zipfile: zipfile.ZipFile, nofixlinks: bool=False) -> str: """ Extract: read the link path string, and make a new symlink. 'zipinfo' is the link fi...
da3e470cb78474bf56b82f9deb2e1febdd53f668
8,970
import os def read_file(fname, ObsClass, verbose=False): """This method is used to read the file. """ if verbose: print('reading menyanthes file {}'.format(fname)) if ObsClass == observation.GroundwaterObs: _rename_dic = {'xcoord': 'x', 'ycoord': 'y', ...
c35b31048cd823fa1f0157cedd6ce88331be5bf0
8,971
def cumulative_gain_curve(df: pd.DataFrame, treatment: str, outcome: str, prediction: str, min_rows: int = 30, steps: int = 100, effect_fn: EffectFnType = linear_ef...
ca493a85d1aa7d74335b1ddb65f2f2a94fcaa152
8,972
def last(*args): """Return last value from any object type - list,tuple,int,string""" if len(args) == 1: return int(''.join(map(str,args))) if isinstance(args[0],int) else args[0][-1] return args[-1]
ad8d836597dd6a5dfe059756b7d8d728f6ea35fc
8,973
from matplotlib.patheffects import withStroke def load_ann_kwargs(): """emboss text""" myeffect = withStroke(foreground="w", linewidth=3) ann_kwargs = dict(path_effects=[myeffect]) return ann_kwargs
a4ff019fe234b44da20e3b8f686f852554018546
8,974
import sys def color_conversion(img_name, color_type="bgr2rgb"): """ 色空間の変換 Parameters ---------- img_name : numpy.ndarray 入力画像 color_type : str 変換のタイプ bgr2rgb, bgr2hsv, bgr2gray, rgb2bgr, rgb2hsv, rgb2gray, hsv2bgr, hsv2rgb Return ------- conversi...
66abc2c44721e262a948b86221063fb57bf1e148
8,975
def predict(self, celldata): """ This is the method that's to perform prediction based on a model For now it just returns dummy data :return: """ ai_model = load_model_parameter() ret = predict_unseen_data(ai_model, celldata) print("celldata: ", celldata) print("Classification: ", re...
435be195c765aa3823a710982bdc6f7954a24178
8,976
from typing import List def statements_to_str(statements: List[ASTNode], indent: int) -> str: """Takes a list of statements and returns a string with their C representation""" stmt_str_list = list() for stmt in statements: stmt_str = stmt.to_str(indent + 1) if not is_compound_statement(stm...
01bd0546be8b7a212dbb73fae3c505bbe0086b48
8,977
def _make_filter(class_name: str, title: str): """https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumwindows""" def enum_windows(handle: int, h_list: list): if not (class_name or title): h_list.append(handle) if class_name and class_name not in win32gui.GetCla...
3b9d5f3fe4afd666cfa7ed43f8abe103b9575249
8,978
def is_float(s): """ Detertmine if a string can be converted to a floating point number. """ try: float(s) except: return False return True
2df52b4f8e0835d9f169404a6cb4f003ca661fff
8,979
def build_lm_model(config): """ """ if config["model"] == "transformer": model = build_transformer_lm_model(config) elif config["model"] == "rnn": model = build_rnn_lm_model(config) else: raise ValueError("model not correct!") return model
03a84f28ec4f4a7cd847575fcbcf278943b72b8a
8,980
def __virtual__(): """ Only load if boto3 libraries exist. """ has_boto_reqs = salt.utils.versions.check_boto_reqs() if has_boto_reqs is True: __utils__["boto3.assign_funcs"](__name__, "cloudfront") return has_boto_reqs
63d2f1102713b8da66e75b28c4c642427fe69e8a
8,981
import glob import os def extract_binaries(pbitmap, psamples): """ Extract sample binaries from subdirectories according to dataset defined in bitmap. """ bins = glob.glob(psamples+'/**/*.bin', recursive=True) bitmap = pd.read_csv(pbitmap) if '.tsv' not in pbitmap else pd.read_csv(pbitmap, sep='\t...
e3086e1ec5dcda0b89f34fb917eb422c8cde285b
8,982
def search_range(nums, target): """ Find first and last position of target in given array by binary search :param nums: given array :type nums : list[int] :param target: target number :type target: int :return: first and last position of target :rtype: list[int] """ result = [-1...
8165e3a2f33741c15494d5d98a82a85c2fb610ff
8,983
def process_mean_results(data, capacity, constellation, scenario, parameters): """ Process results. """ output = [] adoption_rate = scenario[1] overbooking_factor = parameters[constellation.lower()]['overbooking_factor'] constellation_capacity = capacity[constellation] max_capacity = ...
0619c397a21d27440988c4b23284e44700ba69eb
8,984
def identify_ossim_kwl(ossim_kwl_file): """ parse geom file to identify if it is an ossim model :param ossim_kwl_file : ossim keyword list file :type ossim_kwl_file : str :return ossim kwl info : ossimmodel or None if not an ossim kwl file :rtype str """ try: with open(ossim_kwl_...
9a63a8b5e7ece79b11336e71a8afa5a703e3acbc
8,985
def conv_cond_concat(x, y): """ Concatenate conditioning vector on feature map axis. # Arguments x: 4D-Tensor y: 4D-Tensor # Return 4D-Tensor """ x_shapes = x.get_shape() y_shapes = y.get_shape() return tf.concat(3, [x, y * tf.ones([x_shapes[0], x_shapes[1], x_shape...
c30a4328d3a6e8cf2b1e38cf012edca045e9de69
8,986
def get(args, syn): """TODO_Sphinx.""" entity = syn.get(args.id) ## TODO: Is this part even necessary? ## (Other than the print statements) if 'files' in entity: for file in entity['files']: src = os.path.join(entity['cacheDir'], file) dst = os.path.join('.'...
61bb507faaa2821619e77972dc23158fdc3228ba
8,987
def swath_pyresample_gdaltrans(file: str, var: str, subarea: dict, epsilon: float, src_tif: str, dst_tif: str): """Reprojects swath data using pyresample and translates the image to EE ready tif using gdal Parameters ---------- file: str file to be resampled and uploaded to GC -> EE var: st...
b716a6b45cf48457d0c6ca5849997b7c37c6c795
8,988
def run_drc(cell_name, gds_name, sp_name=None, extract=True, final_verification=False): """Run DRC check on a cell which is implemented in gds_name.""" global num_drc_runs num_drc_runs += 1 write_drc_script(cell_name, gds_name, extract, final_verification, OPTS.openram_temp, sp_name=sp_name) (out...
ac44030fc343b50d1035f5b584fc4f64f319aa27
8,989
def getKeyPairPrivateKey(keyPair): """Extracts the private key from a key pair. @type keyPair: string @param keyPair: public/private key pair @rtype: base string @return private key PEM text """ return crypto.dump_privatekey(crypto.FILETYPE_PEM, keyPair)
0decc2dbb77343a7a200ace2af9277ee7e5717a5
8,990
def playbook_input(request, playbook_id, config_file=None, template=None): """Playbook input view.""" # Get playbook playbook = Playbook.objects.get(pk=playbook_id) # Get username user = str(request.user) # Check user permissions if user not in playbook.permissions.users: return playbooks(request) ...
4b01e08414f38bdaad45245043ec30adb876e40e
8,991
def _filter_gtf_df(GTF_df, col, selection, keep_columns, silent=False): """ Filter a GTF on a specific feature type (e.g., genes) Parameters: ----------- GTF_df pandas DataFrame of a GTF type: pd.DataFrame col colname on which df.loc will be performed type: str...
5f41141d69c0c837e396ec95127500a826013500
8,992
def validation_generator_for_dir(data_dir, model_dict): """Create a Keras generator suitable for validation No data augmentation is performed. :param data_dir: folder with subfolders for the classes and images therein :param model_dict: dict as returned by `create_custom_model` :returns: a generato...
57b0a83e98438b8e397377a5626094f69ea21083
8,993
def convert_cbaois_to_kpsois(cbaois): """Convert coordinate-based augmentables to KeypointsOnImage instances. Parameters ---------- cbaois : list of imgaug.augmentables.bbs.BoundingBoxesOnImage or list of imgaug.augmentables.bbs.PolygonsOnImage or list of imgaug.augmentables.bbs.LineStringsOnImage or i...
6eee2715de3bfc76fac9bd3c246b0d2352101be1
8,994
import zipfile import os import io import pickle def gen_stream_from_zip(zip_path, file_extension='wav', label_files=None, label_names=None, utt2spk=None, corpus_name=None, is_speech_corpus=True, is_rir=False, get_duration=False): """ Generate speech stream from zip file and utt2spk...
93a81a8d102c0b76593bcd44b64675c1c1e1fce7
8,995
def get_query_dsl( query_string, global_filters=None, facets_query_size=20, default_operator='and'): """ returns an elasticsearch query dsl for a query string param: query_string : an expression of the form type: person title:foo AND description:bar where type corresponds to an elastic sea...
9f6c1371e0de1f28737415c0454f645748af054f
8,996
def prune_visualization_dict(visualization_dict): """ Get rid of empty entries in visualization dict :param visualization_dict: :return: """ new_visualization_dict = {} # when the form is left blank the entries of visualization_dict have # COLUMN_NAME key that points to an empty list ...
fae81eb69fc25d61282eb151d931d740c51b8bae
8,997
def _LocationListToGoTo( request_data, positions ): """Convert a LSP list of locations to a ycmd GoTo response.""" try: if len( positions ) > 1: return [ responses.BuildGoToResponseFromLocation( *_PositionToLocationAndDescription( request_data, position ) ) for position in positi...
2ee39fdadd721920a3737561979308223a64b57a
8,998
def calculate_average_grades_and_deviation(course): """Determines the final average grade and deviation for a course.""" avg_generic_likert = [] avg_contribution_likert = [] dev_generic_likert = [] dev_contribution_likert = [] avg_generic_grade = [] avg_contribution_grade = [] dev_generi...
95b26efedba076e0b9b54c565fe2e0787d5fbb0e
8,999