content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def read_parameters_start(config): """ Read info on starting parameter values. The distributions can be 'gauss', 'uniform', or 'log-uniform'. """ section = 'EMCEE starting' parameters_to_fit = [var for var in config[section]] starting = {} for param in parameters_to_fit: words = ...
4dc2c3660f0de3b96eeadb4b792c2ff40fab6822
3,615,400
from typing import Dict from typing import Any def list_third_party_asi_vulnerable_components_command(client_obj: Client, args: Dict[str, Any]) -> CommandResults: """ Retrieves the attack surface vulnerable component information of the given third-party account. :param client_obj: client object which is ...
fa5676b5570614ea05109cd63f8e53b5ce901491
3,615,401
def get_lon(da, errors="raise"): """Get the longitude coordinate Parameters ---------- da: xarray.DataArray {errors} Return ------ xarray.DataArray or None See also -------- get_lat get_depth get_altitude get_level get_vertical get_time xoa.cf.CFSpe...
f83dde7507b5cc14784466e932969fa47317dc2d
3,615,402
import mimetypes def bundle_media_description(key, filename): """Bundle the media description necessary for uploading. :param key: form-data key name :param filename: Local file name or path. :return: tuple of ('key name', ('file name', 'file object', 'MIME content-type') :rtype: tuple """ ...
8c160a9c767d86a1c1867d22f018d6342239e68d
3,615,403
def _getColor(*color): """Analyzes the color arguments and returns a proper 4-float tuple or None""" if len(color) == 1 and type(color[0]) == tuple: # a tuple, i.e., a value of type color, was passed rather than in-line values: # no transformation takes place assert (len(color[0]) =...
0e8b9c9c0ef1dc60ae30c4e5499888f28b22c845
3,615,404
import os def load_csv_data(file_path): """ Load csv file asa numpy array :param file_path: path to csv file :return: numpy array """ dir_name = os.path.dirname(os.path.abspath(os.path.abspath(__file__))) path = dir_name + file_path data = np.loadtxt(path, dtype=np.float32, delimiter='...
30cf7e32cf69e1d446d16cf1bccc5b7fa9736758
3,615,405
def format_write_request(address, value): """ Format a write request based on an address and the value to write to the FPGA. :param address: address at which to write date. :param value: data to write to the address. :return: formatted request. """ if address >= 2**(4 * 8): raise Va...
8425b7ff3422162cb0127c64069dbf68a414becf
3,615,406
def get_prob(board, policy_val): """Return the probabilities of selecting the children of a node given the policy and removing illegal moves""" x = (board[:, :, 0] == board[:, :, 1]).reshape(225,) * policy_val return x / np.sum(x)
a275188ebda5397c6a3b2cda80652d52501c0460
3,615,407
import hashlib import ray def get_actor_method_function_id(attr): """Get the function ID corresponding to an actor method. Args: attr (str): The attribute name of the method. Returns: Function ID corresponding to the method. """ function_id_hash = hashlib.sha1() function_id_hash.update(attr.enco...
1627d2635e2dfcce088d1848d5832c113f0b9960
3,615,408
def tangent_basis_transposed(v): """ """ return v[:,:-1,...] - v[:,-1:,...]
e2cd1c0c398ba58e76541aa9976bae64cdecf339
3,615,409
from PIL import ImageFilter import subprocess def process(im, fname, params=None): """Processes the given image in some way, and returns rendered HTML. 'im' is the uploaded Image. 'fname' is the path to the image. 'params' is an optional dict with other parameters. To refer to the uploaded image i...
39d936ef2bea0593829d2e9146ef0527a8857c9d
3,615,410
import warnings def headloss_manifold(FlowRate, Diam, Length, KMinor, Nu, Roughness=None, NumOutlets=None, *, PipeRough=None): """Return the total head loss through the manifold. :param FlowRate: flow rate through manifold :type FlowRate: u.m**3/u.s :param Diam: diameter of manifold :type Diam: u...
332b1fca8f54dfa2adc699727afc911f6c03ba55
3,615,411
import logging def get_pending_jobs_info(max_slots_filter=None, skip_if_state=None, log_pending_jobs=True): """ Retrieve the list of pending jobs. :param max_slots_filter: discard jobs that require a number of slots bigger than the given value :param skip_if_state: discard jobs that are in the given ...
d534d6a2cc901687344e2f68af59193c09b8eb01
3,615,412
def reduce_squeeze(m): """Reduce model by removing length=one dimensions.""" out = m.copy() print('input model has shape:{}'.format(m.param_shape())) keep = np.array(m.param_shape()) != 1 for k,p in zip(keep,m.parameters): if not k: del out.param_values[p] out.parameters =...
9ef37448207756ca490401da80cfe032b4fe4538
3,615,413
def recreate_phage(phage_row): """ Input: the list of prophages for a particular timepoint (i.e phage[-1], where phages is read in above) Output: the same line formatted as a list of lists of integers """ phage_list = [] phages_string = phage_row.decode("utf-8").split('[')[2:] for phage...
8dc38ee643e4c8b59a4ea985aedf7def54b8c64d
3,615,414
def get_chan_nbrs(geom, nbr_dist=70, n_nbrs=7, keep_less_nbrs=False, chans_exclude=None): """Get the channels with n_nbrs neightbors within nbr_dist radius on the electrode array. Returns an array of such channels and a mapping of each channel to its neighbors. Have the option to keep chennels with less ...
49bc361d188d416fdd0a71e24dcf9067eef2ef96
3,615,415
def getHashes(): """ Returns an element with the given itemid :param str i: ItemID of the element :return: the returned object from Monogo less the mongo object ID :rtype: dict or None """ collection = asdb["hashes"] e = collection.find({}, {"_id": False, "hash": True}) return list(e)
12f7172e1aa8761b297eb78c5076ba23a1b0e5c1
3,615,416
def generate_default_function(node, base_name, func_counter): """Generate a default function from the given node """ ft = onnx_optype_to_nnabla_function_type.get(node.op_type) if ft is None: raise ValueError( "op_type {} is currently not supported for NNP conversion".format(node.op_t...
a59826061f21c6ad8f65947face0f35502e6b45d
3,615,417
def unicycle_to_single_integrator(dxu, poses, projection_distance=0.05): """A function for converting from unicycle to single-integrator dynamics. Utilizes a virtual point placed in front of the unicycle. dxu: 2xN numpy array of unicycle control inputs poses: 3xN numpy array of unicycle poses proje...
6872e73ecfbf5e2181f18bb748c656ae68968490
3,615,418
def lloyd_fix(T, Rref, E0): """ Lloyd & Taylor (1994) Arrhenius type with T0=-46.02 degC and Tref=10 degC T Temperature [k] Rref Respiration at Tref=10 degC [umol(C) m-2 s-1] E0 Activation energy [K] """ Tref = 283.15 # 10 [degC] T0 = 227.13 # -46.02 [degC] ...
6e654c119bf882a3db9dd7c7a4c4b4b9bb5493f4
3,615,419
def merge(left, right): """ Merges two linked list, sorting by data in nodes Returns a new, merged list Runs in linear time """ #Create new linked list that contains node from #merging left and right merged = LinkedList() #Add fake head discarded later merged.add(0...
cd3a03770a07276fa604a9653159d0567c5bd51d
3,615,420
def safe_interval_insert(M_new, interval): """ Deal with interval overlaps when adding a new one to the list """ for i, (a, b) in enumerate(M_new): # overlap found, construct the larger interval if (b >= interval.lower_bound) and (a <= interval.upper_bound): lb = min(a, int...
5f0ba60e6ae8c486dca3e22fd69e6f6002b0ef17
3,615,421
def nms(bboxes, iou_threshold, sigma=0.3, method='nms'): """ :param bboxes: (xmin, ymin, xmax, ymax, score, class) Note: soft-nms, https://arxiv.org/pdf/1704.04503.pdf https://github.com/bharatsingh430/soft-nms """ classes_in_img = list(set(bboxes[:, 5])) best_bboxes = [] for cls...
469e5a4c27bb43dbeb9ce9ee619ac2a81f6f1781
3,615,422
from datetime import datetime def create_envelope(payload: dict) -> dict: """ Creates a dictionary with event label, timestamp and message field :param payload: The payload dict :return: An event message dictionary """ payload['timestamp'] = datetime.utcnow().timestamp() if 'event' not in...
593a2b60a667dece41f10031d13ad98018d9f881
3,615,423
def ConsValue(t,ma,st,ra,ds,m,sol,par,idx,ad=0,ad_min=0): """ interpolate consumption and value (ad and ad_min are only so the couple model can look up in this function) """ # a. unpack solution ad_idx = ad+ad_min D = transitions.d_plus(t+ad-1,ds,par) # t-1 so we get choice set today ra_look ...
bda95a033115d50e7fd3f424f465c29d37edc8c8
3,615,424
def decipher(ciphered_name: str, key: int) -> str: """Decipher the room name.""" return "".join(shift(char, key) for char in ciphered_name)
bf46a62ce88941a00407027a681d72fe03367865
3,615,425
import os def os_path_separators(): """ list path spearators of current OS """ seps = [] for sep in os.path.sep, os.path.altsep: if sep: seps.append(sep) return seps
e3e18f5a77bbb6c76e1e7d602f1c32a36bbb237d
3,615,426
import requests import traceback import sys def get_request(request_url: str, token: str) -> dict: """ Wrapper for HTTP GET requests. """ session = requests.Session() # Define the maximum number of retries and the time between each one retries = Retry(total=5, backoff_factor=0.1) # Moun...
799bff2f4adbef774e22634e3c65702cd3f6bf60
3,615,427
def tensor_to_local(tensor): """ to local """ tensor = tensor.to_consistent(sbp=flow.sbp.broadcast).to_local() return tensor
59a8859e301fa1179f0a19ae54c32a8857425b58
3,615,428
def proceed(request): """ This is a fake "Terms" view that we overlay the login. We link here from the Developer Hub landing page. """ if request.user.is_authenticated(): return submit(request) agreement_form = forms.DevAgreementForm({'read_dev_agreement': True}, ...
36faa7fbcbd758ef23828dcee0ff32cce3f9d50a
3,615,429
def angle(v1, v2): """Angular separation between two vectors.""" dot = vdot(hat(v1), hat(v2)) if np.ndim(dot) == 0 and dot > 1: return 0 if np.ndim(dot) > 0: dot[dot > 1] = 1 return np.degrees(np.arccos(dot))
81132ac90f5bbcf612f565ce2a26028b2a579801
3,615,430
def flex_convolution(features, position, neighborhood, theta, bias, name=None): """Flex-Convolution computation. Computes a convolution over arbitrary neighborhoods with elements of arbitrary positions: ...
a8cc9ec48a9b945e2e6ab7d0c0304bfb33747f8d
3,615,431
import glob def collect_factories(rootpath): """ Will collect (recursively) and return all factories found under given root path """ factories_collected = {} # <factory name> : <factory class> factory_files = glob.glob(f"{rootpath}/**/factories.py", recursive=True) for factory_file in factor...
73563107e620d5c6d6419600ebf51bc267710cca
3,615,432
from typing import Optional from typing import List import tqdm def extract( # pylint: disable=too-many-locals, too-many-branches, too-many-statements pdf_path: str, pages: Optional[List[int]], smart_page_crop: bool, save_figures: bool, figure_dir: Optional[str], no_chapters: bool, no_par...
0215539de527562c4c3fdf354d5a6a73e28805ba
3,615,433
def _get_hop_2_neighbours(graph, input_list: list, hop_n: int) -> list: """ Find hop_n neighbours of each item in input_list :param graph: NetworkX graph object :param input_list: Input list :param hop_n: Hop hop_n :return: hop_n hop neighbours of the input list's items """ full_list = ...
a51f1286aec2719b72665e35fec29d7d2b93b38e
3,615,434
import asyncio def create_worker(host='localhost', port=4730, loop=None): """XXX :param host: :param port: :param loop: :return: """ loop = loop or asyncio.get_event_loop() conn = yield from create_connection(host=host, port=port, loop=loop) return GearmanWorker(conn)
8ee679baf652476f520df75b3dc4fa3bf6728031
3,615,435
import re def prepare_template_data(fill_pairs): """ Prepares formatted data for filling template. It produces mutliple variants of keys (key, Key, KEY) to control format of filled template. Args: fill_pairs (iterable) of tuples (key, value) Returns: ...
a6082093bcbe39ba429decd2735fb2797c6c11dd
3,615,436
def get_tokens(): """ Returns a tuple of tokens in the format {{site/property}} that will be used to build the dictionary passed into execute """ return (SECURITY_ENABLED_KEY, KERBEROS_EXECUTABLE_SEARCH_PATHS_KEY, HIVE_PRINCIPAL_KEY, HIVE_PRINCIPAL_KEYTAB_KEY, HIVE_USER_KEY, STACK_ROOT, LLAP_APP_NAM...
6c05f16b3707d31af797fdb7bfc65fe8a1b78482
3,615,437
def largest_cc(mask): """ Return the largest connected component of a 3D mask array. Parameters ----------- mask: 3D boolean array 3D array indicating a mask. Returns -------- mask: 3D boolean array 3D array indicating a mask, with only one connected component. """ ...
617d7a1474ab6b7a5a9ad6393c942cb874d49744
3,615,438
def _expand_to( a: tp.Union[np.number, np.ndarray, Variable], ndim_or_shape: tp.Union[int, tp.Tuple[int, ...]], axis: tp.Union[None, int, tp.Tuple[int, ...]] = None, keepdims: bool = False, ) -> tp.Union[np.ndarray, Variable]: """Return expanded array. Parameters ---------- a : tp.Tuple...
fe1c979ba9c5c781edc4a525c0b87a13b0d39f8d
3,615,439
def get_feedback_average(action): """returns the average feedback rating for the given action.""" return ActionFeedback.objects.filter( action=action).aggregate(avg=Avg('rating'))['avg'] #query_set = get_action_feedback(action) #total = 0 #for i in xrange(1, 6): # total += query_set....
f42125f7fdf7d3f8ee3ef97fe34fbb7f40567cb8
3,615,440
def display_method_to_choose_etfs(selected_method_choose_dates, all_etfs, etf_data, sl_obj): """ Generates various streamlit options for selecting which ETFs to display. Parameters ---------- selected_method_choose_dates : list of str Strings of the various methods of selecting ETFs. al...
6f2c65a5472b445dcdeb921d10c8c13397ef5d97
3,615,441
import sys def find_asset_for_pathrow(sqlite_path, **kwargs): """Find asset from database for pathrow The querying is done inside a loop, so that if the query returns no results, it can be repeated with relaxed parameters. Args: - sqlite_path: Path to sqlite database - kwargs: Argume...
74d2c51b11f3a8a11c9fb885045ba49e4aab62f9
3,615,442
def cband(): """Pre-define idealized critical band filter bank. :return: idealized critical band filter bank """ return np.array( [ 0, 100, 200, 300, 400, 510, 630, 770, 920, ...
1648adff3d9dce05be2f4879e34d4a6aa9acc8f2
3,615,443
def get_power_spectrum(array): """Calculate DFT and power spectrum from the given array. :param array: a 2D array :return: DFT array and the power spectrum """ fourier = np.fft.fft(array) power = abs(fourier)**2 return fourier, power
14066876f7b0d4925477e96301def89fc856b1b4
3,615,444
import scipy def compute_intensity_features(im_label, im_intensity, num_hist_bins=10, rprops=None): """ Calculates intensity features from an intensity image. Parameters ---------- im_label : array_like A labeled mask image wherein intensity of a pixel is th...
9a064d70028417f83368083fc488939a17aa747f
3,615,445
from pathlib import Path from typing import Callable from typing import Any def readFileLines(filepath: Path, f: Callable[[str], Any] = str) -> list: """Reads the lines in a file Args: filepath (Path): The path of the file to be read. f (Callable[[str], Any], optional): Transformation for the lines. ...
21df2445f6132085d7da36276f371170ff0f2a4e
3,615,446
def get_default(arr, idx, default_value): """get arr[idx] or return default_value """ try: return arr[idx] except IndexError: return default_value
038b943da7fa1d36038444880264160da8e031f4
3,615,447
def chat_words_conversion(text): """ converts common chat acronyms into it's fully spelled out phrase """ new_text = [] for w in text.split(): if w.upper() in chat_words_list: new_text.append(chat_words_map_dict[w.upper()]) else: new_text.append(w) retur...
5d97ce53a2103190ff0abb585e62923c0fad8f21
3,615,448
def second(xs): """ Returns the second element of a list, or None if the list is empty """ if not xs: return None return xs[1]
e5a915116d61e01842f86623aafcf6e2e6c8b5a3
3,615,449
import logging def get_logger(module: str, file: str) -> logging.Logger: """Configure a file logger for use in a script. Parameters ---------- module : str The name of the module from which the logger is called file : str The name of the log file to which the logger will write ...
c9a68d216ca9a04ccb208dd546621e051dd37e36
3,615,450
def filled_grasp_grid(empty_grasp_grid, grid_file): """Return a GraspGrid instance filled from the grid_file.""" empty_grasp_grid.read(grid_file) grid_file.close() return empty_grasp_grid
97ed623c09b9d42642a208451b004e5bec4910ed
3,615,451
import warnings def calculate_boot_stats(sample, rep, n="auto", level=0.95, estimator="mean", random_seed=None, pass_dist=False): """Calculates a bootstrapped confidence interval for a sample. A bootstrapped confidence interval for the desired estimator for the provided sample is calculated for a confide...
354cf103105f3bc22decb3b27cbab694f7a7d9c9
3,615,452
import pickle def get_camera_params(): """ Return a default camera parameter matrix """ pickle_in = open("config.pickle", "rb") data_dict = pickle.load(pickle_in) return data_dict['mtx'] # return np.array([[800, 0, 320], [0, 800, 240], [0, 0, 1]])
51292054e8db77058ea37b2dbe06bf105183969b
3,615,453
def _distributed_edge_access(g, edges, issue_remote_req, local_access): """A routine that fetches local edges from distributed graph. The source and destination nodes of local edges are stored in the local machine and others are stored on remote machines. This code will issue remote access requests fir...
1217fcce3a7b1256587298ec266627caa208c28b
3,615,454
import itertools def queue_drain(orig_pre_list, orig_post_list, pre_line_changes, post_line_changes): """ Function to drain the remaining data :param orig_pre_list: :param orig_post_list: :param pre_line_changes: :param post_line_changes: :return: A List pre_queue p...
02b0d852ccd77e015019d1c6bd0c4c5b5732f035
3,615,455
def graph_entropy(DAG, forward_entropy=False): """ Parameters ---------- DAG: NetworkX Graph Directed Acyclic Graph forward_entropy: Bool, default: False if True, calculates entropy from maximal nodes (k_in = 0) nodes to others. Otherwise calculates using paths from the botto...
dbf610cf6a49a9a954199066959937b0345e1527
3,615,456
def check_letters(): """ Check if all letters from input is in other string """ word = input("Give me a word: ").lower() letters = input("Give letters to check for in word: ") for l in letters: if l not in word: print("No match") return 0 print("Match")
4c419e5c3c70c383d06079ead7e105b38e6ca91e
3,615,457
def case_json(ses): """ returns a list of JSON fomratted output for case object """ return _get_case_json(ses, '/case')
00447375c926521001f0b3039251a86ce6bc1336
3,615,458
def bernoulli_action_log_prob(logit, action): """Calculate the log p of an action with respect to a Bernoulli distribution. Use logit rather than prob for numerical stability.""" if action == 0: return F.logsigmoid(-logit) else: return F.logsigmoid(logit)
a1974fbe2d12fe878f875c5e1364cf3cc36d676c
3,615,459
def get_1d_coords(p, i, j): """ Finds index of site in 1d chain from 2d lattics based on snake decomposition, ie 1d coords on 2d lattice look like: 0, 1, 2, 3, 7, 6, 5, 4, 8, 8, 10, 11 Args: p - dictionary that contains the relevant system parameters i - row index...
2852ec9d57c99f922380fc8b671bdd757e8decf4
3,615,460
def unpack_offset(msr_response): """ Extract the offset component of the response and unpack to voltage. >>> from undervolt import unpack_offset >>> unpack_offset(0x0) 0.0 >>> unpack_offset(0x40000000000) 0.0 >>> unpack_offset(0x100f3400000) -99.609375 """ plane_index = int(m...
408ba805fe92fbc0c7fd4498d2e16d6701180eb3
3,615,461
def check_early_stop( perf_history, minimum_length=20, short_history=3, long_history=5, fail_function=np.less_equal): """ Determine whether to stop early. Using deepgaze criteria: We determine this point by comparing the performance from the last three epochs to ...
f730004bf4cbac1cfd12e260bdc8240193c4197d
3,615,462
import math def getAngle(v1,v2,prec=1E-6): """ Helper function to get angle between two vectors inputs -------- v1,v2 (list,list): two vectors outputs -------- angle (float, radians): angle between v1,v2 """ return(math.acos((np.dot(v1,v2))/np.l...
19e54f1bdd3b2ea95e77188eb383f98e6300d5ce
3,615,463
def evaluate_cdr_hit(query, target, result={}, same_length=False): """ Compare query and target sequence positions in CDR3 and framework regions, return number of matches and % identity If previous 'result' is provided, return (None, None) if an improvement has not been found. """ if same_lengt...
1cc292c28ea5209f01cae9472cf20a13cf0864fa
3,615,464
from typing import Sequence import random def make_burst_emitter( center_xy: Point, filenames_and_textures: Sequence[FilenameOrTexture], particle_count: int, particle_speed: float, particle_lifetime_min: float, particle_lifetime_max: float, particle_scale: float...
63a2b4cc0975f03711dc4824e8cdf431e3d61db6
3,615,465
from datetime import datetime import os def download_ccd(idx, ccd, base_url, ccd_image_dir, auth): """Faz o Download de um CCD do serviço do DES. Args: idx (int): Posição do registro no array de ccds a serem baixados ccd (dict): Um dicionario que representa uma instancia do Model des/Ccd ...
7bb4c3b9ceee0e29ba75a1b5e1405a87fda23961
3,615,466
import ctypes def cusolverDnSsyevd_bufferSize(handle, jobz, uplo, n, a, lda, w): """ Calculate size of work buffer used by culsolverDnSsyevd. References ---------- `cusolverDn<t>gebrd <http://docs.nvidia.com/cuda/cusolver/index.html#cuds-eigensolver-reference>`_ """ lwork = ctypes.c_int(...
a16df1725e6db9471836bf517e7efa977c50fdf7
3,615,467
from typing import Dict def get_github_repo_url(project_urls: Dict[str, str]) -> [str, None]: """ Get repo url for github. :param project_urls: project urls to get github repo url from :return: repo url if one is available, else None """ source_code_url = get_attribute(project_urls, ["Source ...
358f35544c50ad65c7f276a2fdbdbf1abb91f039
3,615,468
import json def abrir_freq(file): """ Abre o ficheiro json com o dicionário das frequências das regras. :param file: ficheiro json :return: dicionário com as frequências das regras no corpus. """ with open(file) as f: freq_svo_dict = json.load(f) return freq_svo_dict
b1cbb7c98146cf72390b511428d7734881f0b944
3,615,469
def update_user_phone(): """ 用户修改电话号码 """ userid = g.userinfo.get("id") requstsData = request.get_json() phone = requstsData.get("phone") code = requstsData.get("code") if phone and code: dbres = db.query("select id,code from tb_sms_log where phone = '{}' and status = '0' and c...
1b7fb8763a35f9fc2e221e4c03788b3827bd7a67
3,615,470
from pathlib import Path import json import toml import sys import os def update( expanded_dir: str = ".", cookiecutter_input: bool = False, skip_apply_ask: bool = False, skip_update: bool = False, ) -> bool: """Update specified project's cruft to the latest and greatest release.""" expanded_d...
9475a00f8cb718205aabc2e1e1768e560c2574ad
3,615,471
import common.api as api import base64 def file_update_complete_response( volume, reply ): """ Sign a protobuf ms_reply structure, using Syndicate's private key """ # sign each directory entry in the reply with the Syndicate key, # so the MS attests to its index information for ent_pb in reply.l...
607b9fe4f155b39de72c5c8d9dafcd1ba8bfe7ce
3,615,472
def destructure_decorated_lambda(tree): """Get the AST nodes for ([f, g, h], lambda) in f(g(h(lambda ...: ...))) Input must be a tree for which ``is_decorated_lambda`` returns ``True``. This returns **the original AST nodes**, to allow in-place transformations. """ def get(tree, lst): if t...
1c7a63fb7497a26f5a841556dbdb1114880c7388
3,615,473
from datetime import datetime def get_data_type(v): """ Infers type from value. Returns tuple of (type, value) """ if isinstance(v, datetime.datetime): return ("date", msecs_since_epoch(v)) elif isinstance(v, bool): return ("boolean", str(v).lower()) elif isinstance(v, float): ...
8e6d65ca328859e4b9c6a1493cf732e4a9b17c64
3,615,474
def replace_around(i, l, r, f_nones=True): """Replace the three elements centered at i with r.""" if f_nones: r = filter_nones(r) return l[: max(i - 1, 0)] + r + l[i + 2 :]
4e1c6b002714b07385f5f4871ca001aa956b3e06
3,615,475
def dictionariesToDataframe(): """converts dictionaries on CSPP holdings to dataframes return: - [holdingsECB, holdingsECBDates]""" matrixData = [] # 2D array with row per ISIN and columns for different data for ISIN, dataInDictionary in dictionaryBondsECB.items(): item = [ISIN] + dat...
8fa2afd551d337e52808cbecac4ec411cfb7360f
3,615,476
import time def runAndCheckCommandComplete(cmd): """ This function will run a Command and return False if ssh was too busy. It will return True if the command completed, successfully or not, if ssh wasn't busy. """ retValue = True cmd.run(validateAfter = False) if sshBusy(cmd)...
c07e0dfe647fefc309703e5a720fbf544c79f16b
3,615,477
def get_model_parameters(model): """Extract model arguments that were used during training""" params = ModelParameters() names = [layer.name for layer in model.layers] params.num_codes = model.get_layer(name='embedding').input_dim-1 params.emb_weights = model.get_layer(name='embedding').get_weights...
b216b3d8f010d33f767e76252d1422ffa778b4df
3,615,478
def transpone(l): """transpones a list of multiple lists if the entrys do not have the same length, an empty string will be put in their place""" nestedlist=[] length=[] transponedlist=[] for i in range(len(l)): length.append(len(l[i])) for i in range(max(length)): for j in...
27d904910be743d4116fba5ba7479cfdc62ec18b
3,615,479
def to_df(records_tree, event_name, instrument_name): """ Converts a `get_records_tree()[event][instrument]` to a pandas DataFrame """ # get instrument records records = records_tree[event_name][instrument_name] # build dataframe rows from records acc = [] for s, entries in records.item...
91805a4878eedeab3d5efdb1a4277966728543f3
3,615,480
def compare(value1, value2, comparison): """ Compare 2 values """ if isnum(value1) and isnum(value2): comparison = comparison.lower() if comparison == 'equals': return value1 == value2 elif comparison == 'not equal': return value1 != value2 elif co...
49c6c3806224f864670f8078733d2baeea653792
3,615,481
def get_minsep_range(minseps, cap=None): """ Create ranged minseps from an ensemble of minsep entries Args: minseps (list): A list of minsep dictionaries cap (tuple): Minimum-maximum caps Returns: minsep (dict): A minsep where values are minimum and maximum values """ ...
e60392fa70f7f2b0989f4894ce90c7bd78aac7d2
3,615,482
def ga_exp(B, verbose = False): """ This is an expansion of the exponential of a general rotation and translation Presented by R. Wareham (Applications of CGA) B must be a general rotation object on the format $ \phi*P + t n_{\inf}} $ $P$ is a 2 blade in real space. $$\phi \in \mathcal{...
3abcadbcffe625bf473d28d5698fbf94e1d3318a
3,615,483
import tqdm def get_progress_bar(percentage, increment): """Get a progress bar string given a percentage.""" initial = percentage total = 100 bar_format = generateProgressbar( percentage) + "\n" + "{percentage:04.1f}%" + f"[{increment:+03.1f}]" with tqdm(initial=initial, total=total, bar_...
29957960090063903d1f231dd5f41532691dd05b
3,615,484
def elsym(edgelen, order=1): """ Elementary symmetric polynomial of a given order """ l = len(edgelen) if order == 0: return 1 r = 0 for v in combinations(range(l), order): r += np.product([edgelen[vv] for vv in v]) return r
6939704c2bfcec935e762d23a1cb05f2cd8c593f
3,615,485
def shorturl(request, key): """ Redirect the client. """ return redirect(get_object_or_404(ShortURL, pk=key).url)
7f6700215f8cc60f5e090fa3ef1a3d4e7035ff6e
3,615,486
import itertools def group_by_day(list_all_objects): """ Recebe uma lista de objetos onde cada um deles possui um atributo tipo date e logo ordena eles por dia. :param: list_all_objects: Register.objects.all(): django.db.models.query.QuerySet :return: objects_day_ordered: [[objetos_do_dia_1][objetos_d...
39feb54a2232e9e7a0965b72f2c6eb2509c7b610
3,615,487
import os from pathlib import Path def get_dirtree(directory): """ Get the directory tree of the `directory`. :param directory: The root directory from where to generate the directory tree. :return: The list of paths with appropriate indenting """ element_list = [] ignore_patterns = [] ...
42137bb2a3d9a8686ba75c00e9d38d782d45d8f6
3,615,488
def get_root_model(models): """ Get a root model class from an iterator over `obj_tables.Model` classes The root model is obtained by name, rather than from `core.Model`, because `models` may have been obtained from `obj_tables` migration, which loads other versions of `wc_lang.core` in private imports...
aabe0e445ff96036008eddc4c2127516554a4adc
3,615,489
def datetime_to_iso(date, only_date=True): """ Convert datetime format to ISO 8601 time format This function converts a date in datetime instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` to ISO format, e.g. ``2017-09-14`` :param date: datetime instance to convert :type date: datetime :param ...
676a7e65de2c9e4de60cfe8d832ab342aa46af4f
3,615,490
def _copy_agave_agave(src_uri, dest_uri, agave): """ Copy Agave data using AgavePy Wrapper. Args: src_uri: Source URI parsed into dict with URIParser. dest_uri: Destination URI parsed into dict with URIParser. agave: dict that contains: agave_wrapper: Agave wrapper objec...
0dd5e5627cd4adc87b83b22cb63e5eda1f3dae11
3,615,491
import subprocess def cli_call(context, arg_list, expect_success=True): """Executes a CLI command in a subprocess and return the results. @param context: the behave context @param arg_list: a list command arguments @param expect_success: use False to return even if an error occurred when executing th...
19378a1651923d4fe3423bf1a0d6a744586ff7a6
3,615,492
def load(path_or_strm, container, **opts): """ :param path_or_strm: input config file path or file/file-like object :param container: callble to make a container object :param opts: keyword options passed to :class:`configobj.ConfigObj` """ return container(configobj.ConfigObj(path_or_strm, **op...
cccc2d780ab7d16996ac9b6658550773b307a4df
3,615,493
import numpy def default_unexpected(x): """Define unexpected values.""" large = 1.e3 small = -numpy.float('inf') return (x is None) or x > large or x < small or numpy.isnan(x)
4afe63f1969b568c691fcc4e4fbfa91ace53fdfb
3,615,494
def predict_hot_pxl(sqr, model): """takes a numpy array (colour image) size 64x64 and a ML model, returnes float number between 0 - 1 for hot pixel detection, for 0 no hot pixel detected, 1 hot pixel detected""" predict = model.predict(sqr.reshape(1,64,64,3)) y_pred = [i[0] for i in predict] ret...
e533c2b27df280f0f62b2727b1dd960a828fdee0
3,615,495
import traceback def write_to_file(file_name, dir_path, content): """ Rewrite or create and write to file. Parameters: file_name (string): file name dir_path (string): root path which file contains content (string): content to be written ...
b3ade139d6455f57e54d3ae03ab4988dc5718644
3,615,496
from typing import Tuple from typing import Optional from typing import Dict def _build_meta_block( payload_spec: PayloadSpec, ) -> Tuple[Optional[Block], Block, Dict]: """ Performs validations in the meta specification and returns o Args: payload_spec (dict): Payload specifications. Ret...
33ae726c2c73e964c8e157b00cb1a417446b7b9a
3,615,497
def _unit_state_progress(uid, current, target): """ This method will ensure a unit state progression in sync with the state model defined above. It will return a tuple: [new_state, passed_states] where 'new_state' is either 'target' or 'current', depending which comes later in the state model, and ...
6549118b894a3f475200e08b74a4042f4b75c805
3,615,498
from typing import List from datetime import datetime def search( bounds: List[float], min_cloud: float = 0, max_cloud: float = 100, min_date='2013-01-01', max_date=datetime.today(), period: str = None, period_qty: int = 1, stac_collection_limit: int = 5...
a807308439d1ba3ce2a52890f7da43f2b6a831a4
3,615,499