content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def quote_dict(dct, tab): """ Recursively quotes dict values :param dct: :return: """ t = '\t' * tab # The middle arg here is a newline if value is another dict, otherwise it's a space dct_sring = '\n{0}'.format(t).join( [ '%s:%s%s' % ( camelize(k...
bef0627e4fae06ad8cce395c695e72b42da01eb7
57,700
import types def fit_state_preparation(create_u_func: types.FunctionType, vdagger: qiskit.QuantumCircuit, thetas: np.ndarray, num_steps: int, loss_func: types.FunctionType, optimizer: type...
ec02609b2f6bd7eb20b61a22114399efac5d1873
57,701
def get_provider_driver(provider=None, region=None): """ Gets the specified libcloud driver :param provider: Name of the driver :rtype: `libcloud.compute.base.NodeDriver` """ provider_driver = config.AVAILABLE_CLOUD_REGIONS.get(provider, {}).get(region, None) if not provider_driver: ...
d6260a86faa4c4f8d109418b5c95fb88bf2c27d6
57,702
import subprocess import sys import os def getKEAFlags(): """ Return the flags needed to link in GDAL as a dictionary """ extraargs = {} if sys.platform == 'win32': # Windows - rely on %KEA_HOME% being set and set # paths appropriately gdalhome = os.getenv('KEA_HOME') ...
1a8313ca9d622f55c57d15ccb77a4cdfe92194fc
57,703
def load_x_data_for_cnn(patient_name, keep_prob, input_x, sent_length, category_index, dropout_keep_prob): """Multiprocessing to fast speed""" pool = Pool(processes=HP.read_data_thread_num) generate_token_embedding_results = pool.map(generate_token_embedding, patient_name) pool.close() pool.join() ...
9c00d03f040851d39aad2c38db06e5aa3e1d6194
57,704
def reshape(a, newshape, order='C'): """ Gives a new shape to a tensor without changing its data. Parameters ---------- a : array_like Tensor to be reshaped. newshape : int or tuple of ints The new shape should be compatible with the original shape. If an integer, then t...
cbbb2c187a83afb8c1c5eea4c32dfbdd9ca59831
57,705
def generate_RIP_behavior_graph(records): """ :param records:list of tuples (process, RIP, API_called) :return: the graphs of API_calls of all subprocesses """ # Each subprocess is associated to one graph # LIC stands for Last I Checked forest_and_LIC = {} # forest_and_LIC = {subprocess : ...
1bf4a63cd8ab7d0b3d6e03b08cc4989b20c24aae
57,706
def render_mako_tostring_context(request, template_name, dictionary={}): """ Render mako tostring with RequestContext """ context_instance = get_context_processors_content(request) return render_mako_tostring(template_name, dictionary=dictionary, context_instance=context_instance)
0cad38e5e4c041014ff0675c607968af11beb3bf
57,707
def test_pointer_indexing(pointer_value, type_p): """ >>> a = np.array([1, 2, 3, 4], dtype=np.float32) >>> test_pointer_indexing(a.ctypes.data, float32.pointer()) (1.0, 2.0, 3.0, 4.0) >>> a = np.array([1, 2, 3, 4], dtype=np.int64) >>> test_pointer_indexing(a.ctypes.data, int64.pointer()) (1...
21f87a5ec840e3fd789c9e1ca9382d96f451e1e5
57,708
def _update_centroids(current_centroids, current_weights, new_cluster_sums, new_weights): """Computes a weighted combination of previous and new centroids. Args: current_centroids: A tensor whose rows represent the current centroids. current_weights: A tensor of integer weights associ...
09975fd6cd1bacdc51f50e910e3a5a6e6b83d07d
57,709
def bound_precision(y_actual: pd.Series, y_predicted: pd.Series, n_to_check=5): """ Accepts two pandas series, and an integer n_to_check Series are: + actual values + predicted values Sorts each series by value from high to low, and cuts off each series at n_to_check Determines how many hits...
15f78aa2d1ec4d54b1cef88632782f8dff40dc4e
57,710
import copy def reduce_parallelism(typ, roles, values,calc_set): """ calculation_set_yambo ={'resources': {"num_machines": 8,"num_mpiprocs_per_machine": 32}, 'max_wallclock_seconds': 200, 'max_memory_kb': 1*92*1000000 , 'custom_scheduler_commands': u"#PBS -A XXXX" , ' environme...
1b8893cdb0d1e949b8013ffd20fb3a5a8b893bd9
57,711
import re def clean_empty_sentences(df): """ Substitutes all the empty sentences with a customized sequence of characters """ return pd.DataFrame({ "sentence": df.sentence.apply(lambda x: re.sub("^ *$", "-", x)), "label": df.label })
a9f6d5a331e76ffacd324cc0b77170095e5a8f6e
57,712
def GetViewableStarredProjects( cnxn, services, viewed_user_id, effective_ids, logged_in_user): """Returns a list of viewable starred projects.""" starred_project_ids = services.project_star.LookupStarredItemIDs( cnxn, viewed_user_id) projects = list( services.project.GetProjects(cnxn, starred_pro...
2b0ddc93d27131a0d91833f470b03f2cdd7658f3
57,713
from .units_utils import convert_units def convert_g_per_liter_resin_to_cv(unitted_data, **kwargs): """ To convert to volume in CV, divide by the product concentration in g/L. """ if "concentration" not in kwargs: msg = "Trying to convert a volume in 'g per liter of resin' " \ "requ...
004cd3cf4769f6a982c6853a3367f04470f4c8c0
57,714
from typing import Union from typing import List from typing import Tuple def minimum_distances( left_arr: Union[np.ndarray, List], right_arr: Union[np.ndarray, List], return_indices: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]: """ Finds the minimum distance betw...
e90ad3cd5989a6740cc087d1f813f8b1cbf660a7
57,715
import torch def manhattan_loss(X, mu_tilde): """ Computes the Manhattan loss. Arguments: X: array-like, shape=(batch_size, n_features) Input batch matrix. mu_tilde: array-like, shape=(batch_size, n_features) Matrix in which each row represents the assigned mean vec...
6a913bfdeb558b67684b66e1e1f067a198202474
57,716
import json import traceback def json_data_wrapper(method): """ Load JSON data from HTTP request bodies if possible """ if request.data: try: values = json.loads(request.data) if values: values.update(request.values.items()) request.values = values except: traceback.print_exc() pass retu...
f2253e40196c0310699fbbe2f11f0c200f5b42cd
57,717
import functools def forest_enabled(func): """ Decorator for validating that Forest is enabled for this study. """ @functools.wraps(func) def wrapped(*args, **kwargs): try: study = Study.objects.get(id=kwargs.get("study_id", None)) except Study.DoesNotExist: ...
0656ef67a0fd7bf4c927dae0a4199e15bc5a91e9
57,718
def test_run_command(): """ . """ # pylint: disable=too-few-public-methods,no-self-use class FakeSession: """ Fake session """ command = None def exec_command(self, command): """ . """ self.command = command ...
dd85e9cb3250c381ff7ff27c8ef64d714a50b561
57,719
def find_by_id(object_id, items): """ Find an object given its ID from a list of items """ for item in items: if object_id == item["id"]: return item raise Exception(f"Item with {object_id} not found")
822bf82ea68bd94d0bb1ed2dd5db754aee9b0cba
57,720
def spectral_analyze(dataset, timeindex = 0, bands = ['red', 'green','blue'], dims = ['x','y'], height = 500, width = 500, clims = None, norm = 'eq_hist', cmap=['black', 'white'], nodata = 1): """Interactivly visualize the spectral profile of single pixels in a multi-band xarray dataset Description -----...
0c1e6cf36cf8d9d4a42dc6b2dd2b92c2c22480e8
57,721
def common_modulus_attack(modulus, exp1, exp2, msg1, msg2): """ Perform RSA Common Modulus Attack, given the modulus, two exponents and two ciphertexts as integers. Returns the plaintext as an integer. """ g, s, t = gmpy2.gcdext(exp1, exp2) if g != 1: print("Error: GCD of the two exp...
1a4a20cc70f3f6bd1fa4c7ed8cf65ee31184b406
57,722
def big_h(u: np.array, v: np.array) -> np.array: """ The big h-function according to 139 of the specs. Args: u: v: Returns: np.array """ left = (u + v + np.exp(-u - v)) / 2 diff = np.abs(u - v) right = (diff + np.exp(-diff)) / 2 return left - right
6f6873d3c9e4e229a9b38910f529da01ad57cb15
57,723
import json def _get_results_table(df: pd.DataFrame, json_file: str = PATHWAY_NAMES): """Generate generic results table.""" with open(json_file) as f: pathway_id_name_dict = json.load(f) if 'pathway_id' in df: df['Pathway'] = df.pathway_id.map(pathway_id_name_dict) df['Database'] ...
a92baf686400e64fbad9ebcb253ea297fc373e50
57,724
def _getApplicationConfigObject(applicationname, createifneeded = True): """Return the application config object for the named application. Throws exception if the application is not found. Returns None if createifneeded is False and there isn't one yet.""" # Get the application deployment object for th...
aa2b9573913b9ed35ea7f74be02e3c6ef6961689
57,725
def getPixmap(page, matrix=None, colorspace=csRGB, clip=None, alpha=False, annots=True): """Create pixmap of page. Args: matrix: Matrix for transformation (default: Identity). colorspace: (str/Colorspace) cmyk, rgb, gray - case ignored, default csRGB. clip: (irect-like) restrict renderi...
0968ebb22349a40d67892a805a6277bafd36288f
57,726
def get_atom_int(atmstr: str) -> int: """ Get atom number from atom label """ atom = atmstr.strip().lower() atom = ATOM_LIST.index(atom) + 1 return atom
a3401776e543153599613101b47fe576bf11b612
57,727
import requests import json def create_snippet(data, baseurl, timeout, raw): """ Creates snippet with the given data on the haste server specified by the baseurl and returns URL of the created snippet. """ try: url = baseurl + "/documents" response = requests.post(url, data.encode(...
eb34861909b61749ef2f29da16450a82dcc8d83e
57,728
import json def timeline(): """Fake endpoint.""" with open('{}/examples/timeline3.json'.format(cwd), 'r') as timelinejson: return jsonify(json.load(timelinejson)) return jsonify({})
5b42c906be66c0bc602e6de86646999b35c41470
57,729
import numpy def apply_cnn_soundings_only( model_object, sounding_matrix, num_examples_per_batch=100, verbose=False, return_features=False, feature_layer_name=None): """Applies CNN to soundings only. :param model_object: See doc for `apply_2d_or_3d_cnn`. :param sounding_matrix: numpy arra...
7e0b0dcce45457ea7e0fe6b420d046406ffe1c69
57,730
import torch def fuse_epic_sliding_windows(maps_dict): """ Since different sliding windows have overlap, we desigin this function to fuse sliding windows. Args: maps_dict (dict): { "start_map": (tensor) "end_map": (tensor) "verb_map": (te...
205ac18633fcfddd9ba9af6f7b82d89345bf96c3
57,731
def get_or_create_permission(codename, name=camel_or_snake_to_title): """ Get a Permission object from a permission name. @:param codename: permission code name @:param name: human-readable permissions name (str) or callable that takes codename as argument and returns str """ u...
6c6105f1d82a0b889e15623f6391e9227e540b01
57,732
import re import copy def get_params(group, content): """ check content validity in {% %} and return params list token : eval(string) used to generate params.json orgin: local variable name to be tuned """ token_list, origin_list = list(), list() pattern = INIT + SCOPE + TAIL param_lis...
c154ea153291496f2181dbb1f5eefdbc33f19cfb
57,733
import argparse def get_args(): """Process command-line arguments.""" parser = argparse.ArgumentParser( description='Tool to list all masters along with their hosts and ports.') parser.add_argument( '-l', '--list', action='store_true', default=False, help='Output a list of all ports in use by...
e2434453d3bb8a430966f78bfd7b7978628d0443
57,734
def add_osi_key(obj: "OSI License Object"): """ Add OSI License Key derived from OSI License Object `obj` """ licenses = licensedcode.cache.get_licenses_db() # find matching Scancode License Object for `obj` result = find_osi_map(obj) # derive OSI License Key from `obj` osi_key = obj['i...
3063e9e3d12f12931c7f019a555aeb49f8502130
57,735
def server_interaction(client, hostname): """The server interaction function.""" prompt = 'fots@fotsies-ubuntu-testlab:~\$ ' # Start a client interaction using the paramiko-expect class interact = paramikoe.SSHClientInteraction(client, timeout=10, display=F...
7c69b3a1ebd76d4c82205609d2e2fdbb2046627b
57,736
import glob import fcntl import errno import time import csv def write_monitoring_ts(start_time, np_t, values, quantiles, datatype, fname, rewrite=False): """ writes time series of data Parameters ---------- start_time : datetime object or array of date time objects ...
693a3d4de4ff718c3b4e744f0e69eba3e7d8e896
57,737
def compile_deposit_script(payer_pubkey, payee_pubkey, spend_secret_hash, expire_time): """ Compile deposit transaction pay ot script. Args: payer_pubkey (str): Hex encoded public key in sec format. payee_pubkey (str): Hex encoded public key in sec format. spe...
4aeb66857f4e848620e3fd00bf91ef59f32762d1
57,738
def get_error_rate(predictions): """ Returns the erro 0-1 classification prediction Parameters ---------- predictions: pd df with columns 'pred_prob' and 'y' """ cutoff = 0.5 # get list of predicted probs and citaiton indicators y_act = predictions['is_edge'].tolist() y_pred = ...
a126436ed29a69b1cd9726f76024a11701e9d23b
57,739
import tokenize def build_model(): """Build a machine learning pipeline Args: None Returns: cv: gridsearchcv object. Gridsearchcv object that transforms the data, creates the model object and finds the optimal model parameters. """ pipeline = Pipeline([ ('vect', C...
3839bfea30f55bc812cce8d3a0b22915d9e339cd
57,740
from typing import Sequence def nan_calc_percentiles( arr: np.ndarray, percentiles: Sequence[float] = None, axis=-1, alpha=1.0, beta=1.0, copy=True, ) -> np.ndarray: """Convert the percentiles to quantiles and compute them using _nan_quantile.""" if percentiles is None: percent...
99db92753d33b87c88aac2beebda7fcb370615a4
57,741
def list_todo_items(request_ctx, **request_kwargs): """ Returns the current user's list of todo items, as seen on the user dashboard. There is a limit to the number of items returned. The `ignore` and `ignore_permanently` URLs can be used to update the user's preferences on what items will...
cba1485daa747dc6e213642bb8f1ce1e362935bf
57,742
def gaussian_tensor(x, axes, m, s, a, normalize=True): """Generally a 3-tensor where the axes represent the following: axis 1 is the x-axis grid, axis 2 is the number of total functions (i.e. training data) and axis 3 is the number of Gaussian functions one desires to sum and normalize (if at all). ...
156fc322d92535afff2a81dd82f7ee507d22d75d
57,743
def logmon(nav, t, sat, cs, iu=None): """ log variables for monitoring """ _, tow = gn.time2gpst(t) if iu is None: cpc = cs.cpc prc = cs.prc osr = cs.osr else: cpc = cs.cpc[iu, :] prc = cs.prc[iu, :] osr = cs.osr[iu, :] if nav.loglevel >= 2: n ...
3385f9b9dd519cee8e9116f960b1f98b92fce2e1
57,744
def run(config_path, paths): """ The worker function that process the tiles. Args: config_path (str) paths (Iterator) """ # load config config = load_config(config_path) # load model model = load_model(config) # update config path config["loaders"]["test"]["fi...
d9818b48586023b938bf834160aa2d61737f60e9
57,745
def remove_stale_connectivity_entries(): """ @rtype : boolean """ deletecursor = _db.cursor() connectivitycursor = _db.cursor() connectivitycursor.execute("SELECT StorageUUID FROM Connectivity") connectivityresults = connectivitycursor.fetchall() for connectivityrow in connectivityres...
47938669e20543e5e20e2d44b4159c06d9278e7d
57,746
import tempfile import os import shutil import fnmatch import subprocess def parse_headers(): """Parse the header files of the LLVM-C API and produce a list of libraries and the CFFI cached data""" # Identify the C preprocessor # TODO: this is the only non-portable part of the code cpp = find_pro...
e82e25e8324d7f7c3ba3994b9fa95f131ef89691
57,747
def make_query_from_filter(sample_filter, require_meter=True): """Return a query dictionary based on the settings in the filter. :param filter: SampleFilter instance :param require_meter: If true and the filter does not have a meter, raise an error. """ q = {} if samp...
3ccea6e0253c159517f2f9d3379def00f97487e8
57,748
def wh_to_kwh(wh): """ Convert watt hours to kilowatt hours and round to two decimal places :param wh: integer or decimal value :return: two decimal spot kilowatt hours """ kw = float("{0:.2f}".format(wh / 1000.00)) return kw
19488960a9c7a4d2fc748f4d897d082cfdaee2b8
57,749
def _irafstarfind_objparams(imgcutouts, kernel, sky=None): """ Find the parameters for each source as defined by IRAF's ``starfind``. Parameters ---------- imgcutouts : list A list of ``findstars._ImgCutout`` objects containing the image cutout for each source. kernel : ``f...
c34a07f9141fcc325bc77962fd29b9cd4efa3e4b
57,750
def planck_energy_density(wavelength, temperature): """Spectral energy density according to Planck's law. Uses the SI unit system, so the wavelength must be in meters (m) and the temperature must be in Kelvin (K). Returns the spectral energy density form of the Planck's law in Joule per cubic meter per ...
758ee6ab7552e07ffc51eca436b433a2d11614ce
57,751
import random def get_background(dimensions: tuple[int, int], d_type: str = 'uint8', weights: tuple[int] = (1, 1, 1, 1, 1)) -> list: """ Generate a random background from one of 5 types Blank background. Random Color White Noise. Random picture of a grid or cityscape Procedurally generated li...
c4299dac551a0b8822934e25047efb7fa9344def
57,752
def unbox_numpy_null(d): """ Reverses box_numpy_null, replacing null_numpy_value with None. Recursively descends into a dictionary replacing None values. """ try: return {k: unbox_numpy_null(v) for k, v in d.items()} except Exception: return None if is_null_numpy_value(d) else d
84aa0bafc3df33819ec0a8a1d26d879ea9f21a42
57,753
def get_hms(): """ '2019-06-28 14:47:48' :return: """ hms = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S') return str(hms)
02871fafb61bc1448cdf29ca4a77f16fb4740712
57,754
def v4_add(matrix1, matrix2): """Add corresponding numbers in given 2-D matrices. Removing the variable - row - altogether. """ combined = [] for row1, row2 in zip(matrix1, matrix2): combined.append([ n + m for n, m in zip(row1, row2) ]) return combined
9c5408deb245d86b2f92fd74971a6a8ef0380023
57,755
import hashlib import urllib def gravatar_url(email: str, default_image="mp", size=None) -> str: """Creates a gravatar URL from the given e-mail address.""" if email is None: return None email = email.lower().strip().encode("utf-8") url = "https://www.gravatar.com/avatar/" url += hashlib...
53aad42a55537736fd88377359b6ce09b20662de
57,756
def isnumber(x): """Returns True, if x is a number (i.e. can be converted to float).""" try: float(x) return True except ValueError: return False
3e115928d8458d0034f032a56259e18be6c3383b
57,757
from typing import Union from typing import List from typing import Tuple def get_block_saturation_perf( data: Union[pd.DataFrame, List], col_to_use: str = None, prev_sat_val: float = None, window_len: int = None, ) -> Tuple[float, int, int]: """Calculates the saturation value, experiences to satu...
f3c597addd0b2de803a0fa5c04cd7e06835f12b4
57,758
def read_football(edgelist, community): """ Only takes the vertices in the community list, since we don't know the ground truth not in the list """ # Two files concatenated with ',' # Create a iGraph with first file: Edge-list G = ig.Graph.Read_Ed...
b4089d6ea3421b32afcd5c08b19f3ffbd7e105b0
57,759
def eh_posicao_livre (maze, conj_posicoes, posicao): """Esta funcao indica se uma posicao (o terceiro argumento dado, validado \ como tal) se encontra livre ao ser indicado um labirinto e um conjunto de \ posicoes (os dois primeiros argumentos, validados como tal)""" if not (eh_posicao (posicao) and eh_labirint...
68a889ab5f5ebcf5545ddc734f4820e12d00ace1
57,760
def delete_trunk(module, switch, switch_port, peer_switch): """ Method to delete a conflicting trunk on a switch. :param module: The Ansible module to fetch input parameters. :param switch: Name of the local switch. :param switch_port: The l3-port which is part of conflicting trunk for l3. :para...
72dfc4a128f291fbaf0379c5dae2a76d22dda143
57,761
def julio (string, number): """ I like this program. """ alpha_cod = "" codificated = "" i = 0 position = 0 alpha = "ABCDEFGHIKLMNOPQRSTVX" while i < len(alpha): if i + number >= len(alpha) or i + number <= -1: alpha_cod = alpha_cod + alpha [(i + number) % len(al...
676b6f12ddf5897171cc809de2275ec4972fa4a0
57,762
def rgb_rendering_of_mask(pred_img, writing_path=None): """ Returns a segmentation mask in red and blue display :param pred_img: segmented image - 3-class mask :param save_mask: Boolean: whether or not to save the returned mask :param writing_path: string: path where to save the mask if save_mask=Tr...
d780af5d18921669daa67d4841faf1d99961280f
57,763
from typing import Literal def can_cast_to(v: Literal, dt: str) -> bool: """ 5.4.3 Datatype Constraints Determine whether "a value of the lexical form of n can be cast to the target type v per XPath Functions 3.1 section 19 Casting[xpath-functions]." """ # TODO: rdflib doesn't appear to pay any a...
7d5918745970cc9ed2c0963f7f5779dca1faa950
57,764
from typing import Iterable def iscontainer(*items): """ Checks whether all the provided items are containers (i.e of class list, dict, tuple, etc...) """ return all(isinstance(i, Iterable) and not isinstance(i, basestring) for i in items)
7e40d20bd32187a7bbd74a1635b27460f07e0ea2
57,765
def createGUI(): """Creates the, well, GUI!""" root = Tk() root.title("Xovich") root.geometry("500x325") xovich = Main(root) return xovich
55fa9e76b158a593d36eed21a39473de6433b617
57,766
import torch def recall_at_k_batch_torch(X_pred, heldout_batch, k=100): """ Recall@k for predictions [B, I] and ground-truth [B, I]. """ batch_users = X_pred.shape[0] _, topk_indices = torch.topk(X_pred, k, dim=1, sorted=False) # [B, K] X_pred_binary = torch.zeros_like(X_pred) if torch.cu...
580305c0ed43a22e8cf64bee23e3e207516e9e2a
57,767
def write_binary(path, contents): """Open file, write binary, and close. Args: path (str or py.path.Local): Path of file to write to contents (bytes): New contents Returns: py.path.local: `filename` as :class:`py.path.Local` """ p = py_path(path) p.write_binary(contents...
988b48d6a7c06567af83f3462df2060cf2c202b3
57,768
def move(action): """Takes the player's input and performs the transformation""" global climb #If the person asks for help they will be displayed a list of possible commands if action == "help" or action == "h": print("""A list of possible commands (not case sensitive): Cardinal Directions (...
f6852aa5f4e05ee14038691bd6b69ef0346a65ea
57,769
def core_version(): """Return the SODAR Core version""" return projectroles.__version__
19bd2fdeaf9066a47d4fa0759e3efcaa9f5b34f8
57,770
def api_error_generator(): """ API error dict generator for Flask-restful Some are just standard from werkzeug.exceptions, others are custom defined above. :return: """ api_errors = { "BadRequest": {"status": 400, "error": "Invalid syntax in request"}, "NoJSON": {"status": 400, ...
53dbb9afd3b2c412590a24b225eda58e72e98dd8
57,771
import math def angle(vec, units, vec2=[0,0,1]): """ Angle between vectors (with z by default) """ if units=='degrees': return math.acos( dot( unit(vec), unit(vec2) ) )*180.0/math.pi elif units=='radians': return math.acos( dot( unit(vec), unit(vec2) ) ) else: print('\nSpecify valid angle unit ("deg...
ce88b5d0fa20ad309f496620eb5956cd0efd19b8
57,772
import numbers def scale_tensor(tensor, scale): """ Safely scale a tensor without increasing its ``.size()``. """ if is_identically_zero(tensor) or is_identically_one(scale): return tensor result = tensor * scale if not isinstance(result, numbers.Number) and result.shape != tensor.shap...
a97734bb077234b21cb71eb74b4bec3f2c4d6835
57,773
import sys import signal def run_test_cases(test_cases, procs, lock): """Runs the given test cases and returns a list of results.""" pool = mp.Pool( processes=procs, initializer=initialize_worker, initargs=(lock,) ) # Ensure that when the runner (= main process) is killed (eit...
a6dc86238d4bef221a790c8f0dc5d29b135a6704
57,774
def split_data(x, y, ratio, seed=10): """split the dataset based on the split ratio.""" # set seed np.random.seed(seed) # generate random indices num_row = len(y) indices = np.random.permutation(num_row) index_split = int(np.floor(ratio * num_row)) index_tr = indices[: index_split] i...
229716e4cab06ecafdfbc685158f6f0bd4b1594d
57,775
def validate_with_model(model, type_checks=None, ignore=None, ignore_missing=None, disallow=None): """ Decorator which will check the contents of the of the json request against a model for: * missing fields which are required * values which don't match their type(s)...
352a2332ccb35f3193979225b5ebfe633a319012
57,776
def run_validators(): """ Run all test validators """ # First, add the validator direcotry to the python path to allow # modules to be loaded by pylint # We also add the jenkins/test directory so that github_helpers can be properly loaded. pypath = os.getenv("PYTHONPATH", "") tools_test_path = O...
d5ddecbcb5edee8a189c8dc178251995c42e752b
57,777
def widthHeightDividedBy(image, value): """Divides width and height of an image by a given value.""" w, h = image.shape[:2] return int(w/value), int(h/value)
78bbe60c43a1bbf362c98125bfddc080cf568861
57,778
import time import site def _get_hazard( ensemble: gm_data.Ensemble, station_name: str, im: IM, exceedance: float, ix: int, n_stations: int, ): """Computes the ensemble hazard curve for the specific station""" start_time = time.time() site_info = site.get_site_from_name(ensemble, s...
6c43223b52385d1d08157d6655c9655608027b63
57,779
import collections def to_synapse_annotations(annotations): """Transforms a simple flat dictionary to a Synapse-style Annotation object.""" if is_synapse_annotations(annotations): return annotations synapseAnnos = {} for key, value in annotations.iteritems(): if key in ['id', 'eta...
47c25aa8d1bed9082e696ebf5811f6829f8d39e4
57,780
from pathlib import Path import os def DL(url): """ Entry point for YouTube-DL wrapper. Download best audio and video streams using youtube-dl and merge in .mkv .mp4 or .webm using FFMEG. Returns metadata in youtube-dl format. See: https://www.bogotobogo.com/VideoStreaming/YouTube/youtube-dl-emb...
5cf114e168e8cdbab582a12f6b01b664a922ceab
57,781
def analytical_pulse_energy(q, ekev): """ Estimate of analytical_pulse_energy from electron bunch charge and radiation energy :param q: electron bunch charge [nC] :param ekev: radiation energy [keV] :return P: pulse energy [J] """ P = 19*q/ekev return P/1e3
d81ddafcc41e0e8619922dce0583bf19579112bc
57,782
def batch_parallel(map_fn, devices, **kwargs): """ Parallelize map_fn across devices. :param map_fn: function that takes kwargs and returns a tuple of tensors :param devices: A list of devices to parallelize over :param kwargs: kwargs of input to map, will be split along axis 0. :return: The ou...
0f0fb6da8553b73d8aeaebaec076b34af4571523
57,783
def plot_airfoil(air_df): """Plot an airfoil Parameters ----------- air_df : pd.Dataframe Pandas Dataframe containing x- and y-coordinates of airfoil data. """ line, = plt.plot(air_df.x, air_df.y) plt.axis('equal') return line
2b5c87acd54f8680a50a7e894b1a9658e631cecd
57,784
def get_file_date(tree): """ Get publication date from dta file xml tree. :param tree: the xml tree :return: int, the publication date """ date = tree.find("{http://www.dspin.de/data/metadata}MetaData/{http://www.dspin.de/data/metadata}source/{http://www.clarin.eu/cmd/}CMD/{http://www.clar...
64b0e43b9926d94f1cec066af5bf58ecc10d5044
57,785
import string import random def random_string(string_length=10): """ Generate a random string of fixed length :param string_length: :return: """ letters = string.ascii_lowercase data = "" for character in range(string_length): data += random.choice(letters) return data
54600929a4250612ac6dda904778950a767bd654
57,786
import sys def open_file(path, mode='r'): """ Open file with an option to route from stdin or stdout as needed. """ if path == '-': if mode.count('r'): f = sys.stdin else: f = sys.stdout else: f = open(path, mode) return f
b304a8dc68f2b558e0d0dbd69158128bac103cc6
57,787
def format_version(version): """Converts a version specified as a list of integers to a string. e.g. [1, 2, 3] -> '1.2.3' Args: version: ([int, ...]) Version as a list of integers. Returns: (str) Stringified version. """ return '.'.join(str(x) for x in version)
fa85b122ce6fed4919ec87ad29847b0997493806
57,788
def find_keys_for_target(keys_left, keys_right, target): """ Finds a (left, right) pair of default rule keys in the respective keys dictionaries for the given target """ print("Searching for the specified build target...") print(target) target_pattern = '"' + target + '"' criteria = [ ...
35686f69e36da76d6514e138579a4ecb5f21d3d9
57,789
import yaml import os def read_config_file(filename): """ read yaml config file Parameters ---------- filename (string) Returns ------- dict (dictionary) boolean (boolean) """ flag = os.path.isfile(filename) if flag: with open(filename,'r') as handle: ...
28d20708faa26db9a1040444f04ee92af5523d9d
57,790
def padded_cross_entropy_loss(logits, labels, masks, smoothing=0.05, vocab_size=256): """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] masks: Tensor of size [batch_size, length_...
c29ea2f99e6485cd052ea1fb8bc868908cb91908
57,791
def get_open_title(win, message_id, oms): """Build title for File Open / Save dialog """ what = get_text(win, message_id) if oms: what = ' - '.join((what, oms)) return what
52e33e1c1d583f0fcf0050c1795440faa3d8c40f
57,792
def euler_moment(mxmymz, uv): """ Convert moment mxmymz coordinates from cif into eulerian basis :param mxmymz: [nx3] array, units of Bohr magneton, directed along a,b,c :param uv: [3x3] array, basis vectors [a,b,c] :return: moments [nx3] array, units of Bohr magneton, directed along x,y,z """ ...
ff011e4d3c0cc4dbf51fedfd4a14319627eccc52
57,793
from typing import OrderedDict def row_to_header(row): """Transform a table row (or dict) in a header.""" if isinstance(row, Row): rdict = OrderedDict((i, row[i]) for i in row.colnames if str(row[i]) != '--') else: rdict = OrderedDict(row) return fits.Header...
941476596cf7ff9b79daf9033eec5fd22d1b4cd9
57,794
def inchi(smi): """ Convert a SMILES string into an InChI string. :param smi: SMILES string :type smi: str :rtype: str """ ich = automol.inchi.base.hardcoded_object_to_inchi_by_key( 'smiles', smi, comp=_compare) if ich is None: rdm = rdkit_.from_smiles(smi) ...
35496535103ed385aafdb4c31da0a110336a42fe
57,795
def even_or_odd(n): """Return a string odd or even for odd or even values of n.""" if n % 2 == 0: return 'Even' else: return 'Odd'
956e071eeb4be5b9ec2851fc1b566ff1e3e2ef98
57,796
def count_zombies(game_state) -> tuple[bool, int]: """ Helper function used to check if inside shelter is one or more big zombies and count of all lesser zombies. :param game_state: GameState object with all game data inside :return: tuple with bool flag if inside is big zombie and int value with sum of...
cd1d6569d3be398492ee427c11bc67a4150ac2cd
57,797
import os def static_proxy(path): """ When using Flask, this server static files """ # send_static_file will guess the correct MIME type return app.send_static_file(os.path.join('js', path))
9b2324eef7680f83883500004500ba69af3de8e8
57,798
def _duration_to_nb_windows( duration, analysis_window, round_fn=round, epsilon=0 ): """ Converts a given duration into a positive integer of analysis windows. if `duration / analysis_window` is not an integer, the result will be rounded to the closest bigger integer. If `duration == 0`, returns `0`...
a188e0bad99d6840bd2e3e9416de62f04dbb1b3d
57,799