content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import warnings def mean_absolute_error(A, F): """Expects two, 2-D numpy arrays of forecast_length * n series. Returns a 1-D array of results in len n series Args: A (numpy.array): known true values F (numpy.array): predicted values """ mae_result = abs(A - F) with warnings.c...
70fa3ecb3d42a34656c70c021c281d77d5b8fe75
55,400
from collections import defaultdict def empty_dict(old_dict): """ Return a dictionary of empty lists with exactly the same keys as old_dict **Parameters** :old_dict: Dictionary of lists (identified by the key). :Author: Sirko Straube :Created: 2010/11/09 """ ...
fd63ee3e4600bdf8467ece9ea99f5f8e20399802
55,401
def batchnorm(in_planes, affine=True, eps=1e-5, momentum=0.1): """2D Batch Normalisation. Args: in_planes (int): number of input channels. affine (bool): whether to add learnable affine parameters. eps (float): stability constant in the denominator. momentum (float): running average dec...
61d658b0eae0faba43b2021931e5323f31c43592
55,402
def sampleQ(h_enc): """ Samples Zt ~ normrnd(mu,sigma) via reparameterization trick for normal dist mu is (batch,z_size) """ with tf.variable_scope("mu",reuse=DO_SHARE): mu=linear(h_enc,z_size) with tf.variable_scope("sigma",reuse=DO_SHARE): logsigma=linear(h_enc,z_size) ...
b079f0e0b7b5ba8602244c1dcf771e85049f3686
55,403
def lookup_wiktionary_search(search_term, language_name): """ This is a general lookup function for Wiktionary, updated and cleaned up to be better than the previous version. This function is used for all non-CJK languages. :param search_term: The word we're looking for information. :param language...
504bb93d2a18b5c0b9d77bbe6db1c2343634cbff
55,404
def is_off(filename): """Checks that the file is a .off file Only checks the extension of the file :param filename: path to the file """ return filename[-4:] == '.off'
91941a260448cee281d4a91ece46a64635a17e20
55,405
import requests def get_uid(token, name) -> int: """ Get UID by display name. The dumped user data is formed as below. Note that ``nick`` (i.e. "Display name" field in "Edit profile" page) is unique, but ``name`` (i.e "Name" field in "Edit profile" page) is not. Therefore, it is nothing diff...
bb4242b99c241740115149cbe5c7252c3a24c66a
55,406
def _to_str(obj: object) -> str: """Helper function for `_GenericAlias.__repr__`.""" if obj is Ellipsis: return '...' elif isinstance(obj, type) and not isinstance(obj, _GENERIC_ALIAS_TYPE): if obj.__module__ == 'builtins': return obj.__qualname__ else: return...
8f3778e2a6a6dfdadc975a582eb3f97e6432848f
55,407
def get_optimal_temperature(confidences, true_labels, log_input=True, eps=1e-8): """ Args: confidences (Array): An array with shape [N, K,]. true_labels (Array): An array with shape [N,]. log_input (bool, unused): Specifies whether confidences are already given as log values. eps...
f600ad544784cabb380edcef58844c05d6397df5
55,408
def compute_gc_content(nucleotide_sequence): """ GC content is the ratio of the count of characters that are G or C over the total sequence length. """ return compute_gc_count(nucleotide_sequence) / len(nucleotide_sequence)
9aeacd556d675a1e9a68a4f4c21906dfa9aa3634
55,409
def reward(world: World, cur_time_slot: int): """ agents = world.agents qoe_list = [] for agent in agents: avg_accuracy = agent.acc_sum / (cur_time_slot + 1) exe_efficiency = agent.arrived_tasks / agent.latency # normalize exe_efficiency in [0, 5] #exe_efficiency = exe_effici...
0b7a870bf88f8158a2c638c478d6981dc6e2ebb0
55,410
def basename(path): """Return the base name of pathname path. :type path: bytes | unicode | os.PathLike :rtype: bytes | unicode """ return path
7d3c67651deffdb3ad8913105fa7171f9702c92e
55,411
from typing import Optional from typing import Iterable from re import T from typing import Sequence from typing import Callable def ordered_procs(variant_arg: Optional[Iterable[T]] = None, variant_args: Optional[Iterable[Sequence]] = None): """ A decorator to create multiple ordered processes """ d...
be2153b33a4640530b54effd363b545c44ff7de5
55,412
def output_merge(cls, alpha_in, beta_in, out_in): """ Decorator to merge addition by a value on the output. This will find a pattern of `val * <yourop>(some, params, alpha, beta, out_like)` and update it so that the addtition happens as part of your op. The op needs to accept an alpha and a be...
0b5b204869a45b6c10c46e3d79b647f46184cd72
55,413
def get_input_data_as_list(file_name): """ Reads in data from the given file and returns them as list with one entry per line """ with open(file_name) as input_file: data_list = input_file.readlines() return data_list
b410147e263b49da02b9c157ff7cb82b11930930
55,414
import logging import google.auth from google.cloud import storage from googleapiclient import discovery from typing import NamedTuple def create_study_in_gcp_ai_platform_optimizer( study_id: str, parameter_specs: list, optimization_goal: str = 'MAXIMIZE', metric_specs: list = None, gcp_project_id...
ecc8e07b89e303c343cb0527b1b54205c698902c
55,415
import os def structpdf(): """Generation du bilan de la structure.""" if request.method == "POST": date = request.form["date"] year = date[0:4] month = date[5:7] filename = "bibl/" + year + "-" + month + "_STRUCT.pdf" if len(os.listdir('var/csv') ) == 0: re...
a9890c745eaea12a0208de64ef4491275dd37e62
55,416
from typing import Tuple from typing import Callable from typing import Dict def csv(remote_host: str=None, user_domain: str=None, user: str=None, password: str=None) \ -> Tuple[CommandLine, Callable[[str], Dict]]: """Systeminfo.exe with CSV formatted output. Args: remote_host: (Optional) Th...
5d5f7141eaf4c1a3b00e21c4f4ae88028d193c89
55,417
def search(values): """ Using depth-first search and propagation, try all possible values. Args: values: A sudoku in dictionary form. Returns: The resulting sudoku in dictionary form. False if no solution exists. """ # First, reduce the puzzle using the previous function val...
43f02781160f8de741895e8c63d2aa123e3762c7
55,418
def serialize_sc_ch_compatibility(spacecraft_ch, compatibility): """JSON serializer Serializes the compatibility of all the spacecraft channels. :param spacecraft_ch: channel of the spacecraft to be serialized :param compatibility: compatibility tuples (gs, gs_ch) :return: object with the {sc_ch, [(...
33ea954ae30906e2580fb1caba426db8189aa72c
55,419
import time def join_meeting(playwright: Playwright): """ Join the School Meeting from school's website :param playwright: playwright object :return: None """ global CNT, FILENAME browser = playwright.chromium.launch(headless=False) context = get_context(browser) page = login_sch...
51a95a772f402fb0438faa5b272299593e286fa6
55,420
def generateCDL(dlen, numOfelements, cdl_type): """ Construct CDL object """ if cdl_type=='cksvd': print("CKSVD selected") return CKSVD(dlen, numOfelements) else: pass
379d360e4ad8ace63c837e0aa7e5b506023535a1
55,421
def create_error_model(model_name, context): """ Create an error model instance for the given target context. """ return error_models[model_name](context.call_conv)
b7bcacaba38a73e60f34bc4801d709982185897d
55,422
import json def rename_file(): """ Function to rename a file. """ data=json.loads(request.data) try: return update.rename_file(current_user,data) except Exception as e: print(str(e)) return Response(str(e),422)
ab6676221158bb20af2140f86db3cabda1ca07cd
55,423
import tempfile import os def _load_model(data): """data - [str]. Passed as array because the member is popped to decrease the refcount of the string, allowing the gc to collect it if needed. """ _keras_pickle_pid_check() ofile = tempfile.NamedTemporaryFile('wb', dir=_SHM_DIR, suffix='.h5', ...
1b74f1924106c3a7ea341686cdc350750c6881d9
55,424
def amplitude_cutoff(amplitudes, num_histogram_bins=500, histogram_smoothing_value=3): """ Calculate approximate fraction of spikes missing from a distribution of amplitudes Assumes the amplitude histogram is symmetric (not valid in the presence of drift) Inspired by metric described in Hill et al. (2011) J...
ecba23aefbfc09382ffc0ff38f00406d4ae2cb3a
55,425
def instantiate_me(sciImg, spectrograph, par, caliBrate, **kwargs): """ Instantiate the Reduce subclass appropriate for the provided spectrograph. The class must be subclassed from Reduce. See :class:`Reduce` for the description of the valid keyword arguments. Args: sciImg (pypeit.ima...
552dbf87eafa88485e7c7c3cef91a01721181dfb
55,426
def delete_volume(module, volume): """ Delete Volume. Volume could be a snapshot.""" if not module.check_mode: volume.delete() changed = True return True
f463b4cd1325c1a67ff26009978e653e1354ebc8
55,427
def u4u1(u4): """ pixel pitch -> mm u4 = (pitch, pixel) """ u1 = round( u4[0] * u4[1], 2) return u1
d740975308f8c0723bd4a474cae883e8d6a0290a
55,428
def _check_NSBH_approximant(approximant, *args, _raise=True): """Check that the supplied NSBH waveform model is allowed """ if approximant.lower() == "imrphenomnsbh": return _IMRPhenomNSBH_properties(*args) msg = ( "You have supplied the waveform model: '{}'. Currently only the " ...
21149448e7afe561941c80933e4bf644a21d16cf
55,429
def make_pick(swami_name: str, game_id: int) -> int: """Print swami pick for specified game (simple test function) """ swami = Swami.get_by_name(swami_name) game = Game.get_by_id(game_id) pick = swami.make_pick(game.get_info()) info = game.get_info() results = game.get_results() pp_para...
2204b0d4387f1e6957cf6247c1b6336f89349065
55,430
def patient_import_interface(request): """ Import the data of one or multiple patient in the database """ ''' error_get = False error_sample = False samples_quantity = 0 # We take the file received if 'vcf' in request.GET: filename = request.GET['vcf'] else: error_get = ...
08c952413cdfbf8b671277fca4f3d67da1b29a45
55,431
import subprocess def get_gpu_memory_info(): """Records GPU used and total memory info in GB""" _output_to_list = lambda x: x.decode("ascii").split("\n")[:-1] info = { "total": None, "used": None, } for i in info.keys(): COMMAND = "nvidia-smi --query-gpu=memory."+i+" --form...
b0eaa30c4d18813e528cf938c4abb3f0898f9e2c
55,432
def _FilterNonCoreGoldenFiles(golden_file_list): """Filter out non-core API pbtxt files.""" filtered_file_list = [] filtered_package_prefixes = ['tensorflow.%s.' % p for p in _NON_CORE_PACKAGES] for f in golden_file_list: if any( f.rsplit('/')[-1].startswith(pre) for pre in filtered_package_prefixes...
19b71ec8ad0f01a44fffc5913f4ee68aa1c15ee7
55,433
def normalize_numpy(img_256_arr): """ Normalizes an image NumPy array so its values lie in the range [0, 1] Args: img_256_arr: a NumPy array (intended to be 2D or 3D) whose values lie in the range [0, 255], representing an image Returns: A NumPy array, with the same dimensions...
50fa2854c53a975487d501e6a6703b63e82def86
55,434
def _SquaredDifferenceGrad(op, grad): """Returns the gradient for (x-y)^2.""" x = op.inputs[0] y = op.inputs[1] sx = array_ops.shape(x) sy = array_ops.shape(y) # pylint: disable=protected-access rx, ry = gen_array_ops._broadcast_gradient_args(sx, sy) # pylint: enable=protected-access # .op works with ...
474d506e51b72971e3532d701365f1f18d3ac8ee
55,435
def keep_only_this_derivation(name_of_set_to_make,connections_list_of_dics): """ """ new_connection_list_of_dics=[] # print(name_of_set_to_make) for connection_dic in connections_list_of_dics: # print(connection_dic["derivation name"]) if (connection_dic["derivation name"]==name_of_set_to_make): ...
4ec8a010055d6f3740c489184f8b123bcd8780ee
55,436
def decompose_z_matrix(z_matrix, fixed): """Decompose the z-matrix into blocks to allow parallel (batched) reconstruction of cartesian coordinates starting from the fixed atoms. Parameters ---------- z_matrix : np.ndarray Z-matrix definition for the internal coordinate transform. Ea...
0c0c8ce05f4735101308885eb156e60f87f44cb6
55,437
import os def dist_path(*a: str) -> str: """Returns the path of the GoSubl package. """ return os.path.join(packages_dir(), "GoSubl", *a)
d941cf04b1cf2077eabd4f58723199bc57ea6195
55,438
from typing import Tuple from typing import List from typing import cast def search(database: str, expression: str) -> 'Tuple[int, List[int]]': """ Прямой поиск по словарю :param database: имя базы данных :param expression: поисковое выражение :return: пара "код возврата-найденные MFN" """ ...
0619e289a3e6904686aff7b13f91047c49600c2e
55,439
import time import os def cache(path): """Decorator to cache results """ def decorator(func): def wrapper(*args, **kw): time0 = time.time() if os.path.exists(path): result = load(path) cost = time.time() - time0 print('[cache]...
9f04f72930abbefafbd67d629f189d43dff6fb2b
55,440
def make_ngmlr_index_cmd(in_fa): """return cmd string which generates ngmlr indices""" assert is_fasta(in_fa) return 'ngmlr -x pacbio --no-progress -t 1 -R 0.01 -r %s -q /dev/null 1>/dev/null' % in_fa
f00162068f1d21f0190107aa3ba4f3f16e779a03
55,441
import typing def get_group_member_ids(group_id: int) -> typing.List[int]: """ Returns a list of the user IDs of all members of the group with the given group ID. :param group_id: the ID of an existing group :return: the member ID list :raise errors.GroupDoesNotExistError: when no group with ...
027d00b349c54ac6d5eb5e4a943a9e0acd43e61e
55,442
def tone3_to_normal(tone3, v_to_u=False): """将 :py:attr:`~pypinyin.Style.TONE3` 风格的拼音转换为 :py:attr:`~pypinyin.Style.NORMAL` 风格的拼音 :param tone3: :py:attr:`~pypinyin.Style.TONE3` 风格的拼音 :param v_to_u: 是否使用 ``ü`` 代替原来的 ``v``, 当为 False 时结果中将使用 ``v`` 表示 ``ü`` :return: :py:attr:`~pypinyi...
3cd3db860d008adbabec0d3931bd0e63c4b41ec1
55,443
def check_purchase(paykey): """ When a purchase is complete checks paypal that the purchase has gone through. """ with statsd.timer('paypal.payment.details'): try: response = _call(settings.PAYPAL_PAY_URL + 'PaymentDetails', {'payKey': paykey}) ...
0d0ac7c6dc79eaf5e3ec60c7542adc2529e62840
55,444
def deblend(net, images, normalised = False): """ Deblend the image using the network parameters: net: neural network used to do the deblending images: array of images. It can contain only one image normalised: boolean to indicate if images need to be normalised """ if normal...
a9dd536826dfb90f17be7c8783f54f08111b693d
55,445
from typing import Union from typing import Tuple from typing import Optional def roll( x: Union[ivy.Array, ivy.NativeArray], shift: Union[int, Tuple[int, ...]], axis: Optional[Union[int, Tuple[int, ...]]] = None, *, out: Optional[ivy.Array] = None, ) -> ivy.Array: """Rolls array elements alon...
2c6dacce51fc0924ad9fda8dfb0d311a2617c5f9
55,446
def assessors_detail(request): """Managerial Detail View on the status, progress and returned review for each Expert Assessor.""" return render(request, 'review/assessors_detail.html', {})
db5e2214f468faac612d4a62b76b5b0a7cfd864d
55,447
def convert_plf_to_transition_points(plf): """ identify mid points of intervals and return them as transition points :param plf: :return: """ plf_transition_points = plf.transition_points mid_points = [] for index, point in enumerate(plf_transition_points): if point < LARGE_NUMBE...
8b20f084074584795f97d4c2645a3f31fcd633aa
55,448
def make_task(func): """make decorated function a task-creator""" func.create_doit_tasks = func return func
4a7d23765aa47f4c87723efc080913ff0c126205
55,449
import numpy def CalculateAllSumSquareCharge(mol): """ ################################################################# The sum of square charges on all atoms -->Qass Usage: result=CalculateAllSumSquareCharge(mol) Input: mol is a molecule object. Outpu...
7a115bee67a2b3ecff53a4b220fe8119e7adc6b7
55,450
from os import path from numpy import nan, log from core.stats.reg import lin_reg import seaborn as sns from core.ts import w_resample from pandas import concat import matplotlib.pyplot as plt def reg_plot(x, y, freq='day', n_periods=1, fun='mean', min_ratio=0.75, digits=3, x_max=None, y_max=None, logs=False, export=...
9ba081f18939b1d35c4589878b75105d1e1329e9
55,451
import os def generate_node_map(nodes, roles, show_hostnames=True): """Generates a graphviz node map""" graph = KitchenDot(graph_type='digraph') clusters = {} graph_nodes = {} role_colors = {} color_index = 0 role_groups = get_role_groups(roles) + ['none'] for role in role_groups: ...
038148b9841aba8bfc7e4153c3d5263e4ee9ec66
55,452
import os import requests def clapack_header(clapack_h = "clapack.h"): """Return the clapack header as string (is downloaded if not found)""" clapack_url = "http://www.netlib.org/clapack/clapack.h" if not os.path.exists(clapack_h): r = requests.get(clapack_url) assert r.status_code == 200 ...
0a86f5b805430b1434ba28cec423c5d54aa89094
55,453
import argparse def wait(args): """Wait for the specified state on the given instances. args list of arg values """ # parse the command args parser = argparse.ArgumentParser(prog="swarm wait", description='This plugin waits for a state on the specified ins...
9bd97a5473d65ec5a114fd9de36f7fd5c0465c3f
55,454
def ifelse(condition, then_expression, else_expression): """Controls if else logic flow inside a computational graph """ if condition: output = then_expression else: output = else_expression return output
69190f0f9c51cd97db97d64203f51ae66370e3ff
55,455
def mat4_scale(factor, origin=None, direction=None): """Return matrix to scale by factor around origin in direction. Use factor -1 for point symmetry. >>> v = (np.random.rand(4, 5) - 0.5) * 20 >>> v[3] = 1 >>> S = scale_matrix(-1.234) >>> np.allclose(np.dot(S, v)[:3], -1.234*v[:3]) True ...
c3151f37bbcba584505d1c5a090ba4d5fa38942a
55,456
from .settings import has_channels def create_schema(): """ Root schema object that graphene is pointed at. It inherits its queries from each of the specific type mixins. """ query_mixins = [] for fn in hooks.get_hooks("register_schema_query"): fn(query_mixins) # ensure graphene...
b506155bcecc39d8b651ce365a8bc3c4af7d3804
55,457
import logging import os def setup_auto_startup_osx(command, cwd, plistname): """Uses launchd to start the command when the user logs in. This assumes the user is automatically logged in on OS startup. In case of failure like reboot loop, simply remove the file in ~/Library/LaunchAgents/. """ logging.in...
f625c21926ae178ca214bdc4ba1d965710a93a06
55,458
from model import CaptchaModel from kaptcha_model import CaptchaModel def predict(captcha, model_dir='./model/model-latest.pkl', use_gpu=True, mode='captcha'): """ :param captcha: :param model_dir: :param use_gpu: :param mode: :return: """ gpu_available = torch.cuda.is_available() ...
74d9f3310c659c2347e71c04b535ef77594a2fb3
55,459
import logging def map_significance(filename, ap_radius=2, Npix=100, data_hdu=0): """ Make a full significance map of the data in 'filename'. :param filename: A string giving the path to a fits file to analyze :param ap_radius: The aperture radius to use. Default = 2 pixels :param Npix: The numb...
b519b54a9c0f8d5399d4efeaae295cef1ab909a8
55,460
def instrLeakAddr(): """Build the Leak Kernel Address instruction. Args: (none) Return Value: string containing the serialized instruction """ return addHeader(SCOUT_INST_LEAK_ADDR, b'')
6f4fbcc3254e7f0f28445178e2b9e1d46199166e
55,461
def create_media_types( tator_api: tator.api, project: int) -> list: """ Create the media types """ spec = { "name": "Image", "description": "Image type", "dtype": "image", "attribute_types": [ { "name": "Trip ID", "dtype": "stri...
552411718da7d651dcd089606a4b7495d915cf02
55,462
def entradas(): """faz as perguntas sobre o contato e retorna os dados""" contato = {} nome = input("qual o nome do contato: ") contato['nome'] = nome contato["numero"] = input("qual o telefone/celular: ") contato["endereco"] = input("qual o endereço: ") contato["email"] = input("qual o emai...
dbcb82d91facf4c324db6cff07d2080ca3330c6a
55,463
def sigmoid(x): """Compute the sigmoid function. We don't bother with clipping the input value because IEEE floating point behaves reasonably with this function even for infinities.""" return 1.0/(1.0+np.exp(-x))
df95d9cadde13ddbcadcf3bb55d6b250fd48c219
55,464
import numpy def get_N_colors(N, cmap_name='Dark2'): """ given N and a colormap, get N evenly spaced colors""" try: color_map = plt.get_cmap(cmap_name) return [color_map(c) for c in numpy.linspace(0, 1, N)] except ValueError: # try reversing the colormap name color_map = pl...
220ef94d832064519015c39b8fa2ad2b57e73607
55,465
def hopf_bifurcation_modified(beta): """Return a systems of equations relating to the hopf bifurcation""" return lambda t, X : [ beta*X[0]-X[1]+X[0]*(X[0]**2+X[1]**2)-X[0]*(X[0]**2+X[1]**2)**2, X[0]+beta*X[1]+X[1]*(X[0]**2+X[1]**2)-X[1]*(X[0]**2+X[1]**2)**2, ]
42003966274c0cda99630f1b86d746c965caa149
55,466
import importlib def build_parts(path, file, version): """Generate all of the parts.""" module = importlib.import_module(version["file"]) wsdl_parser = WsdlParser(text=module.data) commands = wsdl_parser.get_commands() all_objects = wsdl_parser.get_objects() list_objects = [x for x in all_obj...
f8fd7c4cc333d345732001221df7923be039299e
55,467
def Sparsity_unit(*args): """ Create the sparsity pattern for a unit vector of length n and a nonzero on unit(int n, int el) -> Sparsity position el. """ return _casadi.Sparsity_unit(*args)
12a1dc895f915918ef100575d4cdff10a95e054b
55,468
import warnings def exponential(start=None, end=None, startt=None, endt=None, dt=None, t=None, extend="constant"): """ ``exponential`` is deprecated. Use ``ease_in(... method='exponential')`` instead. """ warnings.warn("exponential is deprecated. Use " "ease_in(... method='ex...
f0b52c1fccf6714598967e079d72b2b2c7142a5e
55,469
from typing import Optional from typing import Union from typing import List def list_contacts(connection: 'Connection', to_dictionary: bool = False, limit: Optional[int] = None, **filters) -> Union[List['Contact'], List[dict]]: """Get all contacts as list of Contact objects or dictionaries. ...
be14351740d882f8e73a637921c4a5c94a6920d3
55,470
def show_asm_context(occurrence: adsk.fusion.Occurrence, prefix: str, msg_list) -> None: """Walks up assembly tree for selected item Args: occurrence: input occurrence then recursively sm context prefix: continue building up parent contexts as you recursively move up the tree """ app = ...
385456a773908dce1ea3788e257149f883c7e1e8
55,471
def pass_exchange(request): """Display the list of sites one can exchange a voucher for a pass at.""" state = request.GET.get('state') if state: sites = get_active_pass_exchange_sites(state) form = PassSiteStateForm(initial={'state': state}) state_name = STATES[state] else: ...
e16aa1ecd01b4e67a0b4e5b033d5dd71285a8304
55,472
def cotes_combine_all_sites(*matches, freebet=False): """ Calcule les cotes combinées de matches dont on connait les cotes sur plusieurs bookmakers """ sites = set(matches[0]["odds"].keys()) for match in matches: sites = sites.intersection(match["odds"].keys()) combine_dict = {"date"...
b17c019e19d839c51c070bb99d63edb695685317
55,473
import re def find_title(text): """ This function extracts and returns title case words found in a string variable. :param text: a string variable :return: a list of characters """ return re.findall(r'\b[A-Z][a-z]+', text)
9b599f6e0d708bce041ac7764f514457bd384a4f
55,474
from pathlib import Path def read_image_scipy2(input_filename: Path) -> np.array: # type: ignore """ Read an image file with scipy and return a numpy array. :param input_filename: Source image file path. :return: numpy array of shape (H, W), (H, W, 3). """ numpy_array = imageio.imread(input_...
54d3aa7d8a3043e5a79e2668be1e971b543669d9
55,475
def get_rule_by_id(neutron, sec_grp, rule_id): """ Deletes a security group object from OpenStack :param neutron: the client :param sec_grp: the SNAPS SecurityGroup domain object :param rule_id: the rule's ID :param sec_grp: a SNAPS SecurityGroupRule domain object """ rules = neutron.lis...
00afc40d003279cbd347678db0b56b4be8222568
55,476
def parse_image_names(data): """ Returns list of the Images names grouped by type. @parameter{data,dict} dictionary with keys: @val{images_private}, @val{images_public}, @val{images_group} @returns{list} Images names. """ emty_category_counter = 1 categories = [] categories.append([_(...
562d70988ce264bbadec571979c70cb6a123f98c
55,477
import torch import random from pathlib import Path from datetime import datetime import socket import logging def init_train(args, cfg, dataset): """ Training initialization. Including Data generator, model, optimizer initialization. """ '''Cuda''' args.cuda = not args.no_cuda and torch.cuda.is...
5da29b76803cacb8435d85fb202388efca2fb512
55,478
def select_distinct_best_records(records: list[Record], n_records: int) -> list[Record]: """ Select records related to highest scores (without duplicates). :param records: original records :param n_records: number of unique records to select :return: best records """ ...
ae37db4ce36cb3f04f9c2912719b3dcfcbb97caf
55,479
import os import subprocess def get_gateway() -> JavaGateway: """ Gives the gateway with which we can communicate with the SystemDS instance running a JMLC (Java Machine Learning Compactor) API. :return: the java gateway object """ global JAVA_GATEWAY global PROC if JAVA_GATEWAY is No...
011efe3f61819b09ff10f4b886129bd1ca698bd0
55,480
from typing import OrderedDict def list_ports(): """Return an alphabetically-sorted list of ports.""" return OrderedDict(sorted( (port.device, { 'name': port.name, 'device': port.device, 'description': port.description, 'hwid': port.hwid, 'vi...
a3f92dfe35e7d21cc9b9b2ce443da75970b2ee9c
55,481
def LE(ccs_sample, energy_sample): """Finds the lowest energy conformer of a sample. """ idx = np.argmin(energy_sample) return ccs_sample[idx]
2b0b649086632fb2a4127185a600631eaa9a6129
55,482
from typing import Dict def get(id_: int, type_: str, api_name: str, session: scoped_session, recursive: bool = False) -> Dict[str, str]: """Retrieve an Instance with given ID from the database [GET].""" object_template = { "@type": "", } # type: Dict[str, Any] try: rdf_class = session...
23790cdd15279331feeb5da94340ca09c412e5c4
55,483
import os def parse_lang(filename): """ only support python and golang """ _, ext = os.path.splitext(filename) if ext == ".py": return "python" elif ext == ".go": return "go"
a923e048abbe5fff031ae066748e3d2fd094ddb4
55,484
import os def is_available(): """Returns `True` if shell logger socket available. :rtype: book """ path = _get_socket_path() if not path: return False return os.path.exists(path)
424e11af63a44b4bc8bdf89dfed36d03da9dc77b
55,485
from typing import List from typing import Tuple def sentence_from_tokens( tokens: List[str], pos_list: List[str] ) -> Tuple[str, List[Tuple[int, int]]]: """ Apply some heuristics to create a sensible text text from the tokens. Unfortunately the original whitespace information is not available. "...
df212e0324efb4135f7674ea7d598d73fea7d2cb
55,486
import logging def read_labels(label_file): """ Reads a labels.csv file into memory and converts columns to their appropriate dtype. Parameters ---------- label_file: str Path to labels.csv Returns ------- data: list of OrderedDict A list of the rows of the csv, w...
82f65eed0395295bb8aaa6fd3c4294204e52905e
55,487
def euler2dcm2(angles, sequence='321'): """euler rotation sequence utilizing predefined matrix :param a1st: angle for first rotation axis (rad) :param a2nd: angle for second rotation axis (rad) :param a3rd: angle for third rotation axis (rad) :param sequence: euler sequence; default='321' :retur...
8428aa98da4f3e3aea11b8244cac36267ac2045e
55,488
def condition_ndm_nfe(data, nr, nc, upper, lower, NDM, NFE, p, kk, dlimit, average, normalize, ndm, nfe): """ fcndm = cndm(data, 0.1, 0.1, 1) for test Construct the CSN for sepecified cells Parameters: `cells` Construct the CSNs for all cells, set ...
69eba8829462fed03554db9589f438538326430f
55,489
import os import yaml def load_yaml(yaml_file, vault_secret=None): """ Load a YAML file into a python dictionary. The YAML file can be fully encrypted by Ansible-Vault or can contain multiple inline Ansible-Vault encrypted values. Ansible Vault encryption is ideal to store passwords or encrypt th...
6e841608a24eb05d97586b035ec190a22ab753ff
55,490
import os import glob def FindTestFiles(): """Return a list of all test files in the project.""" file_list = [] pattern = '*_test.py' module_dir = os.path.join('.', 'plaso') for directory, _, _ in os.walk(module_dir): directory_pattern = os.path.join(directory, pattern) for pattern_match in glob.i...
f13ebfffa6c51cbaa90060356af82aeaba146e34
55,491
def generator_executor(func): """ Decorator for running generator function through GeneratorThread. """ def wrapper(*args, **kwargs): with GeneratorExecutor() as executor: return executor.submit(func, *args, **kwargs) return wrapper # class BaseTask(object): # pass ...
cfb6cdc57db1841491b2fc296eaa18b6f579b941
55,492
import tqdm from datetime import datetime def diff_meth_pos( meth_data, pheno_data, regression_method="linear", q_cutoff=1, impute='delete', **kwargs): """ This function searches for individual differentially methylated positions/probes (DMPs) by regressing the methylation M-value for each...
6baa3609196c4996b329d19646beae9e5a3cbde1
55,493
def check_hdr(hdr): """ :param hdr: Header from a NIRPS image to be cheked against a number of QCs We'll need to add more checks with time. :return: """ keys_to_check = ['OBJECT'] output = '' for key in keys_to_check: if key not in hdr: output+='missing:'+...
9626f472d5194217a7d6f794e6192aea7112154b
55,494
def load_script(filename): """ Loads a python script as a module. This function is provided to allow applications to load a Python module by its file name. :param string filename: Name of the python file to be loaded as a module. :return: A |Python|_ module loaded from the specifi...
954c42d53164963bfa02d3d8abd305b973f602fd
55,495
def has_prefix(sub_s): """ :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid :return: (bool) If there is any words with prefix stored in sub_s """ for s in dic: if s.startswith(sub_s): return True return False
c73940feb94158377cafeaf6f2f6414fc9829969
55,496
def get_partition_disk(ns, partition): """ Return a device on which is located the given partition. :type partition: LMIInstance/CIM_GenericDiskPartition or string :param partition: Partition to examine. :rtype: LMIInstance/CIM_StorageExtent. """ partition = common.str2device(ns, partition)...
01e3b25d1f0fc3c8802f3ab3ef07286d247764da
55,497
def checkParts(coordsList): """ Builds the part status dictionaries for each plane part and other part (bear, cloud and colours) Then generates the list of blocks to be placed (newCoordsList). Also calls calculateFlightDistance() to generate the flight score. """ global planePartStatus, otherPar...
2e7504cb8870c5a46d6be53ec70077ba2b637b4f
55,498
import warnings def _insul_diamond_dense(mat, window=10, ignore_diags=2, norm_by_median=True): """ Calculates the insulation score of a Hi-C interaction matrix. Parameters ---------- mat : numpy.array A dense square matrix of Hi-C interaction frequencies. May contain nans, e.g. in...
493785d9430e39d9708f5bc65a13495bbcfb78ad
55,499