content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_app_by_id(app_id): """ 查询业务信息 :param app_id :return dict: {host_info} """ if app_id: cc_result = bk.cc.get_app_by_id(app_id=app_id) if cc_result: return cc_result[0] return {}
5c4303110b62b5606d13ea5aeb4a835eb7865bef
3,598,600
def add_tag(row, tag_key, capitalize=False): """ Looks up the correct tag based on the row, and appends it to the list of tags :param row: :param tag_key: the tag key (string of tag) to add :param capitalize: True to initial cap the tag key :return: the updated row """ if not tag_key: ...
f8a84d4eeb82f516a301553528c3f66741879a7a
3,598,601
def get_host_fsids(node_metadata): """ Return all the cluster FSIDs found for each socket in a host """ all_fsids = [] for socket_metadata in node_metadata['ceph']['sockets'].values(): config = socket_metadata.get('config', {}) if not config: continue fsid = confi...
543cf63d563fe5993dae343cc662084f51147162
3,598,602
def form_hall_insert(request, cinema_id): """ Returns Hall's insert form :param request: :param cinema_id: linked Hall's ID :return: web-page for creating new entity """ if request.user.is_staff is True: if request.method == "POST": form = HallForm(request.POST) ...
f20aaa64e1e5ae2848caa8eef06a1d617253dece
3,598,603
from typing import Optional def unexpected_case(cl: Classifier, p0: Perception, p1: Perception, time: int) -> Optional[Classifier]: """ The classifier does not anticipate the resulting state correctly. In this case the classifier is marked by the...
3dfb408a8dddc5f8f9240b586c9bf47e1f4884b6
3,598,604
from typing import Any from typing import Optional def plot_psd( df: pd.DataFrame, y_col: str = None, time_col: str = None, nfft: int = None, fs: int = 1, min_period: int = 0, max_period: int = np.inf, plot_time: bool = False, title: str = None, show: bool = True, **kwargs:...
5d59ad17a9e2ba461cda1291acf2de8088c8b105
3,598,605
import typing def _aggregate_config_values(config_values: typing.List[ConfigValue]) -> dict: """ Returns a (sorted) :param config_values: :type config_values: :return: :rtype: """ _keys: defaultdict = _nested_default_dict() _sorted_values = sorted(config_values, key=lambda x: x.na...
e44793653bd8e294aa006d1772541907bb4ea12d
3,598,606
from typing import List def find_non_prime(instructions: List[Instruction]) -> int: """ The algorithm behind the instructions is a counter of non prime numbers between two given values The set of instructions can be broken down into three nested loops. Concerning the registry values: - a is t...
eb5bf42bef3a5a1cd65f218c81e3fd5ef1615544
3,598,607
def new_apikey( request: Request, apikey_params: schemas.APIKeyRequestParams, principal=Security(get_current_principal, scopes=["apikeys"]), settings: BaseSettings = Depends(get_settings), ): """ Generate an API for the currently-authenticated user or service.""" # TODO Permit filtering the ...
d947b249f72ddc298627ee658d186cd1701e2351
3,598,608
def full_fft(): """FFT of waveform where independent axis is evenly spaced and a power of 2.""" wobj, fsample, finc = fft_wave() # Compute reference solution npoints = len(wobj.indep_vector) ret_indep_vector = barange(-fsample / 2.0, +fsample / 2.0, finc) ret_dep_vector = fft(wobj.dep_vector, np...
925c2f4a8d29248069b0e60a8f5a7d7416d9f31e
3,598,609
def piecewise_linear_mapping(x, knots): """ A piecewise linear mapping function, defined by the boundary points of each segment. For example, a function consisting of 3 segments is defined by 4 points. The x-coordinate of each point need to be greater that the x-coordinate of the previous point, the y-c...
0da3164fd13be15626e1b1d3a9b81d1bb5fc0a85
3,598,610
import re import os def get_fileinfo(filespec, cache_dir='/tmp', download=False): """ Parse a file specification and return information about it. """ numhdu = None # User specified an HDU using bracket notation at end of path? match = re.match(r'^(.+)\[(\d+)\]$', filespec) if match: ...
aefe952409f86d8132b6d9e7330367ab9cb34315
3,598,611
def specific_heat_capacity_moist_air(spec_hum): """ Calculate the specific heat capacity of moist air. Parameters ---------- spec_hum : numeric Specific humidity (kg kg-1). Returns ------- spec_heat_cap_moist_air : numeric Specific heat capacity of moist air (J kg-1 K-1...
c464c572cfd483c22934f8934f81f8524ae924ee
3,598,612
def message(id): """Issue #2: permalink for message.""" found = Msg.query.get(id) if not found: return 'message not found', 404 # TODO: Issue #11: ACL if current_user not in found.room.users: logout_user() return current_app.login_manager.unauthorized() # TODO: Don't s...
ba3833dab3e1af213a870bc093cb13a22370bf85
3,598,613
import warnings def resample(image, voxel_spacing, new_spacing=None, new_shape=None, order=1): """ Resamples the scan according to the either new spacing or new shape When new_spacing and new_shape are provided, new_shape has the priority use order = 1 for nearest neighbor and order = 3 for cubic ...
a9b3585874626cbc8bcc34d76e41f03efc7f5eb5
3,598,614
def parse_kde(args, hough_transform: HoughTransform): """Get vanishing points using the KDE method""" vps, kdes = hough_transform.find_vps_kdes( weight_threshold=args.weight_threshold, filter_threshold=args.filter_threshold, kde_width=args.kde_width, kde_height=args.kde_height, ...
81f5050c733b6a4d695b95dfa8fc0fedb8eafdd0
3,598,615
def read_formatted_file(file, listmat=None, listmf=None, listmt=None): """Read formatted file and return either Errorr, Gendf or Endf6 instance according to file format. Returns ------- `Errorr` or `Gendf` or `Endf6` """ ftype = get_file_format(file) if ftype is "errorr": re...
d5b0ad84ef7bf3490b3bacbf8225548eecbf8922
3,598,616
def get_strains(known_origin=False, issues=False): """ Returns a list of strains; Represents all strains Args: known_origin: Returns only strains with a known origin issues: Return only strains without issues """ ref_strain_list = Strain.query.filter(Strain.isotype_ref_strain == True...
4c4e2f699f68726da574861c9fb5db1ecb3503e4
3,598,617
def nested_dict_traverse(path, d): """Uses path to traverse a nested dictionary and returns the value at the end of the path. Assumes path is valid, will return KeyError if it is not. Warning: if key is in multiple nest levels, this will only return one of those values.""" val = d for p in path: val...
1f7e4744585ae134ab1f2eface9284756526ed65
3,598,618
import os def read_spike_times(session_path: str, shankn: int, fs: float = 20000.): """Read .res files to get spike times. Parameters ---------- session_path: str | path shankn: int shank number (1-indexed) fs: float sampling rate. default = 20000. Returns ------- ...
f068519ae4092a40bb3767cac5cb36cceabd9a1e
3,598,619
def compute_recommendation_cdf(table_offers): """Approach 1: compute the salary recommendation based on the CDF, it was designed to be called in a groupby. Args: table_offers: pandas Dataframe containing every offers of a single job group. Returns: a list of namedtuple containi...
af700938006fbde18a0acda687dcb231addd9afc
3,598,620
import torch def box_planar_dir(box: torch.Tensor, eps: float = 1e-4) -> torch.Tensor: """ Finds the unit vector n which is perpendicular to each plane in the box and points towards the inside of the box. The planes are defined by `_box_planes`. Since the shape is convex, we define the interior to...
5cdb68dbf93f1b0bf91e0467a101198f86e1fcdf
3,598,621
from qharv.reel import ascii_out def get_jk_kvecs(fout, header = 'kSpace coefficient groups', trailer = 'QMCHamiltonian::addOperator'): """ parse QMCPACK output for kSpace Jastrow kvecs """ mm = ascii_out.read(fout) text = ascii_out.block_text(mm, header, trailer) data = [] for line in text.split('\...
c0bbaff7e31754bab904d509d4c51ee1a3eb7a46
3,598,622
import os def get_default_provider(): """Get the default provider to use.""" return os.environ.get('DRIFTER_PROVIDER', DEFAULT_PROVIDER)
744313a64cfa39a93830ea01c2131523ec5c9c21
3,598,623
import torch def squeeze(x, axis=None): """ Remove single-dimensional entries from the shape of a tensor. Parameters: ----------- x : ht.DNDarray Input data. axis : None or int or tuple of ints, optional Selects a subset of the single-dimensional entries in the shape. ...
a80c56b95e12f0cc43e3a27df509b4059f4da14d
3,598,624
import io import sys def sfdx(command, username=None, log_note=None): """Call an sfdx command and capture its output. Be sure to quote user input that is part of the command using `sarge.shell_format`. Returns a `sarge` Command instance with returncode, stdout, stderr """ command = "sfdx {}".for...
92c00ec6dd869a1287d9ab59acd94169f58eec82
3,598,625
import os import logging import sys def set_cookie(username, password, output): """Logs into JGI Genome Portal. Args: username (str): JGI Genome Portal username password (str): JGI Genome Portal password output (str): output dir where cookie file will be written Returns: ...
81f5be25c3b75352bc1b5e417b3640f4e572b143
3,598,626
import os def get_atoms_from_generated_file(species, xyz_filename): """ Get atoms from a previously generated .xyz file, if the atoms match Arguments: species (autode.species.Species): xyz_filename (str): Returns: (list(autode.atoms.Atoms)) or None: Atoms from file """ ...
7a217b8cf143d5fc4082437fd39dcbe77c593f8a
3,598,627
def extract( config_file=None, data_dirs=None, file_format=None, annotation_file=None, labels_to_use=None, feature_group=None, feature_list=None, output_dir=None, spect_params=None, save_features=None, save_prefix=None, return_features=None, ): """high-level function ...
0d95490ad71609643ef426163f61265e43df162b
3,598,628
import importlib def possible_words( words=None, include=None, only=False, require=None, match_count=False, exclude=None, length=None, at_least=False, mask=None, ): """Return words from that meet the filter criteria. Parameters ---------- words : [str], optional ...
1f2f6fbcfc67464d4f194d43a2f39957075ea4d7
3,598,629
def is_file_download_finish(file_name): """ 判断文件是否下载完 判断文件后缀为xltd即未下载完 :param file_name: :return: """ return not file_name.endswith('.xltd')
b782d358359c03f50efb6d791bd4403a4190aac0
3,598,630
def delete_vip_request(vip_request_ids, keep_ip='0'): """Delete vip request.""" for vip_request_id in vip_request_ids: try: vip = get_vip_request_by_id(vip_request_id) bypass_ip = True if keep_ip == '1' else False vip.delete_v3(bypass_ipv4=bypass_ip, bypass_ipv6=bypa...
2b5d1b699b1631ed664f605c74c041d8e7145633
3,598,631
import os import subprocess def run_picorv32(pmem): """ Run the given memory file in the riscvpicorv32 iverilog project. """ # Make a run file with the same name as the mem file: simv = pmem[:-4] + '.run' if not os.path.exists(simv): print() print('======') print('Compiling v...
7d7813a3f73653101bf7999a976d3612edfa623a
3,598,632
def survey(survey_name): """Render the survey page with the requested survey name to the client""" return render_template('survey.html', survey_name=survey_name)
b827350bb7d78087589ebdcab0af532171fc9fbe
3,598,633
def normalize2(numbers): """Normalize list of numbers, caching names""" thr = Config.threshold fact = Config.factor norm = [] for num in numbers: if num > thr: num /= fact norm.append(num) return norm
fb0c8c8843e760196dcfde1ea5e6dfcd4fe1ab53
3,598,634
def check_antonym_suffix_wrapper(row): """Wrapper for check_antonym_is_token_suffix function""" return check_antonym_is_token_suffix(str(row.token), str(row.pos))
90d311da4c480301590ec6fc9612501d8c9d3758
3,598,635
def sample_par_from_list(probs, size=1, replace=False): """ Take a parameter or multiple parameters, with or without replacement, at random from a list of possible options """ idx = np.arange(len(probs)) # Ensure probabilities add up to 1 probs = np.array(probs) probs /= probs.s...
0facee157a52edf4ca416a416790224d09f96a10
3,598,636
def fix_zip5(zip5): """add leading zeros if they have been stripped by the scorecard db""" if len(zip5) == 4: return "0{0}".format(zip5) if len(zip5) == 3: return "00{0}".format(zip5) else: return zip5[:5]
ff781562c97c297dde7a05740436b5d668d7fbb8
3,598,637
from typing import Any import scipy def problem(request: Any) -> Problem: """Simulate a fixed effect problem against which algorithms can be compared.""" covariates, scales, levels, singletons = request.param # simulate the data state = np.random.RandomState(hash(tuple(request.param)) % 2**32) id...
8b0466ffe5e6e96b5c4e5d11addcc24a29a1eb28
3,598,638
def create_qdisc_root(interface): """ Creates a root htb qdisc in traffic control for a given interface """ return shell.execute_suppressed('{} qdisc add dev {} root handle 1:0 htb'.format(BIN_TC, interface)) == 0
02dadebb82d2806151f58778bb377c6471582d58
3,598,639
def constant_case(s: str): """ Transform into upper case string with an underscore between words. Parameters ---------- s : str Original string to transform. Returns ------- Transformed string. """ return _change_case(s, '_', str.upper)
3ea3f4c5e9570da9cdd1359b9dfaf80cef266b5b
3,598,640
def eigenvectors_from_displacements(disp, masses): """ Calculate the eigenvectors from the atomic displacements """ nphonons, natoms, ndirections = disp.shape sqrt_masses = np.sqrt(masses) return np.einsum("nax,a->nax", disp, sqrt_masses)
15bf112d22e705de8b8064ca297cb1cad612b6f9
3,598,641
def count_bit_differences(s1, s2): """number of positions at which the corresponding bits are different""" assert len(s1) == len(s2), 'len(s1) ({}) != len(s2) ({})'.format(len(s1), len(s2)) return (~(~s1 ^ s2)).count(True)
618a469cf6be2386b13950813102a18ed73ba68d
3,598,642
def round_preserving_sum(iterable): """Rounds an iterable of floats while retaining the original summed value. Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and description of each parameter is optional, but should be included if not o...
5da1dd917ce7b69938e255d44ae729b1d3755ede
3,598,643
def train_and_gen_result(clf, X, y, X_test, use_proba=False, save_url=None, n_splits=1, random_state=None): """ train and generate result with specific clf Args: clf: classifier X: vectorized data y: target X_test: test data use_proba: predict probabilities of labels ins...
8c07355caf76f02e4d2e0cb268c391f7cb1faa5e
3,598,644
def create_path_payment_op(destination, send_code, send_issuer, send_max, dest_code, dest_issuer, dest_amount, path, source=None): """ This method creates a Stellar path payment operation. This operation can be used to use the Stellar decentralized exchange (SDEX) to a...
4ed8dca0c875d964ea84cff479fba0eddb23c712
3,598,645
import tqdm def calc_accessibility_load(tracts, pois, G, weight='length', func=acc_cumulative_gaussian, k=5, random_seed=None,func_kws={}, pois_weight_column=None, tracts_weight_column=None, ...
6b5ef37858296eac85161f80c0020a0b5c9d3af2
3,598,646
def flag_callback(): """JS callback for the flagging button Returns ------- code : :obj:`str` """ code = """ //f_sources: Flagged data source //n_ax: number of figures available //uf_sources: unflagged data source for (let n=1; n<=n_ax; n++){ for (l...
6fdc9abbfe103bdd40ce02e009f9c59be7b32c9f
3,598,647
import string def topic(): """Topic name used for this specific test.""" topic = get_random_string(string.ascii_letters, 10) logger.debug('Using Topic: %s', topic) return topic
7986a4c893702810ecb92ae46698ebb5ae04ca5f
3,598,648
def export_cropobject_graph(cropobjects, validate=True): """Collects the inlink/outlink CropObject graph and returns it as a list of ``(from, to)`` edges. :param cropobjects: A list of CropObject objects. :param validate: If set, will raise a ValueError if the graph defined by the CropObjects ...
2caf2d70352c275d503a06c3e57c0cb10c9ac9db
3,598,649
import os def runHECResults(minDepth, optionsfile = "", scenariosfile = "", geometryfile = "", RASfile = "", cellsfile = "", facesfile = "", faceptsfile = "", HECresultsfile = "" ): """ runHECResults takes the inputs for HEC-RAS file, scenarios, and results locations. HEC-RAS runs through each scenario ...
5011aeb5857d00162d4b5e5b435a0f5c45e4836d
3,598,650
import itertools def list_flatten(_l): """Flatten a complex nested list of nested lists into a flat list """ return itertools.chain(*[list_flatten(j) if isinstance(j, list) else [j] for j in _l])
05d1e4018accfe850c07504f123d85949a2ced60
3,598,651
import os def check_libcxxabi(default="clang++"): """Compile a basic C++11, libc++ binary, including cxxabi.h.""" executable = os.getenv("CXX", default) return check_bin(executable, "-x c++ -std=c++11 -stdlib=libc++ - -o /dev/null".split(), what="libc++abi", ...
33efb08118448f0468efafa0bbf79553d62af58e
3,598,652
def get_create_indexes_queries(graph_name, backend): """Format all SQlite CREATE INDEXES statements with the name of the RDF graph to insert.""" if backend == "sqlite" or backend == "sqlite-catalog": return [ f"CREATE UNIQUE INDEX IF NOT EXISTS {graph_name}_spo_index ON {graph_name} (subject...
445a13ee13f7ae7dc3bd8d260ebf7deed6f0709c
3,598,653
import os def complete_path(wdir, path): """returns the joined path""" return os.path.join(wdir, path)
7fab8fad99f10b267e58cbe05b885d6fbd44dc86
3,598,654
def generateChatbotNameSentences(): """Returns generated lines with chatbot's name.""" contexts = [] answers = [] for length in range(1, MAX_TOKENS + 1): context = "" for _ in range(length): context += "{} ".format(CHATBOT_NAME) contexts.append(context) an...
c4d212779d67654a883943d16062673b25eb1c10
3,598,655
def handle_2_columns(datalist, return_list = False): """This function has the intent of changing: ('A8', '2') => ('A8', '', '2') ('A8', '', '2') => ('A8', '', '2') [('E2', '5')] => [('E2', '', '5')] [('G1', '', '5')] => [('G1', '', '5')] with the purpose of handling 2 column csv part file inputs...
57a9c1dbad9484a3513cebab68069983d3ae9f35
3,598,656
def singledispatch_on(idx): """Helper to dispatch on any argument, not only the first one.""" # It works by wrapping the function to include the relevant # argument as first argument as well. def decorator(func): @ft.wraps(func) def wrapper(*args, **kwargs): dispatch_obj = a...
7f7a149458c71c81a001a4e0b0c0ec6e8703b6ef
3,598,657
def get_auc(fprs, tprs): """Computes AUC under a ROC curve""" sorted_fprs, sorted_tprs = zip(*sorted(zip(*(fprs, tprs)))) sorted_fprs = list(sorted_fprs) sorted_tprs = list(sorted_tprs) if sorted_fprs[-1] != 1.0: sorted_fprs.append(1.0) sorted_tprs.append(sorted_tprs[-1]) return ...
6953047b35b3205bbc237d6f67e34f0b7650fbac
3,598,658
import time def so_special(treatment_feature, extra_filter): """helper""" if extra_filter: qs1 = SampledStackOverflowPost.objects.filter( has_wiki_link=True, sample_num__in=[0,1,2], has_c_wiki_link=True).order_by('uid') qs2 = SampledStackOverflowPost.objects.filter( has...
689f843c1941528e5ec6c5297fed8d9b69924ce8
3,598,659
def stellarmass_from_halomass(log_Mhalo,z=0): """ Stellar mass from Halo Mass from Moster+2013 https://doi.org/10.1093/mnras/sts261 Args: log_Mhalo (float): log_10 halo mass in solar mass units. z (float, optional): halo redshift. Assumed to be 0 by default. Ret...
f7b7e5f6cba5fe452b84274e10f77ea6a7788c84
3,598,660
import logging def GetParentList(start_unit, end_unit=None, path=[]): """ Returns one or more lists, each giving a path from a start unit to a supertype parent unit. example: for path in GetParentList( Unit.GetUnit("Restaurant") ): pprint.pprint(', '.join([str(x.id) for ...
38b1d24e22b2b051b331879c933e3d0e442c848b
3,598,661
from typing import List from typing import Dict from typing import Tuple import tqdm def add_data_edges( base_graph: nx.Graph, distributions: List[Dict[str, np.ndarray]], alpha: int, image: np.ndarray, partition: Dict[int, set], params: dict, verbose: float = True, ) -> Tuple[nx.Graph, Lis...
d9ca4e643dfee29b2a426fad74053b73d894bb84
3,598,662
def format_button(recipient_id, button_text, buttons): """ Ref: https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template """ return { "recipient": {"id": recipient_id}, "message": { "attachment": { "type": "template", ...
a05f6d08b87d0897a65b291c539b3cbd883c0799
3,598,663
def calibration_gravity_parameters(signals:NDArray) -> NDArray: """calibration_gravity_parameters. :param signals: :type signals: NDArray :rtype: NDArray """ n = signals.shape[0] # row number of 2D array A = np.zeros((n, 6)) row_unit = np.ones((1, n)) for i in range(n): ...
575d9c78ac68e117ef0f5555985c60eb3c146899
3,598,664
def vis_gauss(u, v, sigma_lm, A=1., i=0., pa=0., l0=0., m0=0.): """ The visibility model of a Gaussian profile, which is inclined to the line of sight with the inclination angle i and position angle pa. The coordinates transformation is consistent with 2017ApJ...839...99P. Parameters ---------...
d8ab15159852ec14f0788405e538f8de5aec096b
3,598,665
import random def meme_rand(): """Generate a random meme.""" img = random.choice(imgs) quote = random.choice(quotes) path = meme.make_meme(img, quote.body, quote.author) return render_template('meme.html', path=path)
06d6ad5f1d61fed82338c04408f1fe7b050bbb9b
3,598,666
def deriveDictEntry(obj, names=False, objectlist=[], logging=True, adjust=True): """Derives a phobos dictionary entry from the provided object. Args: obj(bpy_types.Object): The object to derive the dict entry (phobos data structure) from. names(bool, optional): use object names as dict entries inst...
b132b7ebda71b6a5f0b59163d53729848cc65eb4
3,598,667
def GPA_from_letter_grades(letterGrades): """ Computes a floating point GPA for a student given a list of their letter grades. """ letter2number = {'A':4.0, 'B':3.0, 'C':2.0, 'D':1.0, 'F':0.0} return np.mean([letter2number[letter] for letter in letterGrades if letter != '0'])
bf688457930fe0753bb4f3aefa6ca02497f1ba14
3,598,668
def distribute_first_fillers(places_available, num, num_places): """ Chooses places for a first batch of fillers For a first batch of fillers, places in the second half of the sequence are chosen. This is done to limit the predominance of repeat trials late in the sequence. :param places_available...
c23816e89c9fdf34cdaa5cf6de78fb7485ad6fec
3,598,669
def scenario_to_age_distribution(s): """ scenarios see above, every dict provides the name of the scenario and age mass distribution. here we convert it to the initial values for the ODE solver """ ages = s[1] a = np.zeros((n_days)) for ag in ages: a[ag[0]] = ag[1] return a
6c6253c22722cd92f817227c8e5ee0f050207296
3,598,670
def get_quotation_items_rows(*args, **kwargs): """ 获取列表 :param args: :param kwargs: :return: """ return db_instance.get_rows(QuotationItems, *args, **kwargs)
7719567882a8bd478d227d1490c0f8be624b388c
3,598,671
import requests import json def submit(url, job, headers, inputs=[]): """ Submits a job to the given URL, which can be the ".../jobs" URL or a ".../sites/site_name/" URL If inputs is not empty, the listed input data files are uploaded to the job's working directory, and a "start" command is sent ...
cd4642a86b1dadf48b5a32ff777e0e0e4af17ab7
3,598,672
from pathlib import Path import os def get_active_lab(eveng_directory: str): """get active lab from eve-ng directory Args: eveng_directory (str): path to eve-ng directory Returns: [str]: return lab path or None """ # ensure directory exists Path(eveng_directory).mkdir(exist_o...
921cfe1b9e6456a30ec19623e59fc0e5325193f0
3,598,673
def conv(in_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=True, batch_norm=True): """Creates a 2D convolutional layer (for downscaling width and height of the input tensor) with an attached optional batch normalization layer. Arguments: in_channels: input ch...
50b0dcc7dde113ab1cce2b7d51d8de9ed82e4354
3,598,674
def prof(d, pres=5e2, desc=False): """Calculate profile (prof) from points (pts). d - Points (pts) dataset (dict). pres - Pressure resolution (float). desc - Descending profile (bool). """ pmin, pmax = np.nanmin(d['p']), np.nanmax(d['p']) phalf_min = pmin - (pmin % pres) phalf_max = pmax + pres - (pmax % pres)...
4427883d325cb9d70504047b7bb951c7e9f9d5dc
3,598,675
import re def remove_line_comment(old_str: str, comment_mode: str): """ 去除行内注释 :param old_str: 原字符串 :param comment_mode: 注释符号 :return: """ temp_str = new_str = old_str if comment_mode not in old_str: return new_str for regex in ["\".+\"", "\'.+\'"]: for s in re.fin...
b5b53f909bf04da8688b7ef54d56815dfadbf993
3,598,676
def try_get_element_from_xml(elem: str, xml_elem): """ Wraps a try-except call to fetch elements from an xml element TODO: is it correct to use all global namespaces here? Args: elem: xml_elem: Returns: ret_val: The found element(s), otherwise None """ ret_val = None ...
896db9c8d563cc124bd99bc544ae9df677e01148
3,598,677
def CalculateSLOGPVSA(mol, bins=None): """ ################################################################# MOE-type descriptors using LogP contributions and surface area contributions. logpBins=[-0.4,-0.2,0,0.1,0.15,0.2,0.25,0.3,0.4,0.5,0.6] You can specify your own bins to compute some des...
27533151c58cd9aeaed498589226c36b7c5384c5
3,598,678
def identity_partition_selector(context, partition_set_def): """Utility function for supplying a partition selector when creating a schedule from a partition set made of ``datetime``s that assumes the schedule always executes at the partition time. It's important that the cron string passed into ``crea...
ebc59c2a54b20256a8bd2a779fd2036df6346081
3,598,679
import numpy def ComputeGeodesicSphereMesh(radius=1.0,level=2): """Computes a geodesic sphere to a specified level. Returns the vertices and triangle indices""" GTS_M_ICOSAHEDRON_X = numpy.sqrt(numpy.sqrt(5)+1)/numpy.sqrt(2*numpy.sqrt(5)) GTS_M_ICOSAHEDRON_Y = numpy.sqrt(2)/numpy.sqrt(5+numpy.sqrt(5)) ...
d823f621b23d04c1f195968337649d03468366e0
3,598,680
def get_position_key(atom): """ Get atom position as tuple of integers to be used as lookup key. Rounds the coordinates to 4 decimal places before multiplying by 50 to get unique integer-space coordinates, and avoid floating point errors. :param atom: Atom to get key for :type atom: :class:`nan...
b367fd851a0afa903c2d73548849cc8864233f56
3,598,681
def get_unity(): """ Returns the unity global object of the current connection. If no connection is present, automatically launch a localserver connection. """ if not is_connected(): launch() assert is_connected(), ENGINE_START_ERROR_MESSAGE return __UNITY_GLOBAL_PROXY__
e7653b1a28cc61aedee1723cac979c6ba772f4a9
3,598,682
from typing import List def syncall_from_blobs(dry_run: bool = False, *, session: Session) -> List[Exception]: """ Sync all trials from the JSON blobs in TrialMetadata to the new relational tables. Handles ClinicalTrial, CollectionEvent, Cohort, Shipment, Participant, and Sample. Return a list of all ...
8ecf342830e1b241b7fe3a864fb025b89fbd8172
3,598,683
def sample_uint32(random_key: PRNGKey) -> int: """Returns an integer uniformly distributed in 0..2^32-1.""" iinfo = jnp.iinfo(jnp.int32) # randint only accepts int32 values as min and max. jax_random = jax.random.randint( random_key, shape=(), minval=iinfo.min, maxval=iinfo.max, dtype=jnp.int32) return ...
6098738a052ca56e8e81adee78ae1cdebae63da2
3,598,684
def create_item(user,cmd_args): """ cmd_args: url """ item = Item.objects.create( owner = user, image_url =cmd_args['img_url'][0]['payload']['url'], description = cmd_args.get("description",DEFAULT_DESCRIPTION), date_created = timezone.now() ) user.last_state = S...
6949c9ba9cf5226f916acc59823407fb21612ac6
3,598,685
import sys def scan(package, tables=()): """Scan a package or module and return a :class:`~mortar_rdb.controlled.Source` containing the tables from any declaratively mapped models found, any :class:`~sqlalchemy.schema.Table` objects explicitly passed in and the :mod:`sqlalchemy-migrate` repository...
1df4fe4195886be6804e640fb4ac433ad2df1d8c
3,598,686
def get_all_geom_set(): """ Returns a set of all component classes used in the assembly. """ return set(instances_by_class.keys())
6706d1822b34c15f79ceef214d82ccfb3a0d6e51
3,598,687
def AtrousResBlock(x, n_filters, ksize, scope='arb'): """ DAVANet: Stereo Deblurring with View Aggregation https://arxiv.org/pdf/1904.05065.pdf """ with tf.variable_scope(scope): net = slim.conv2d(x, n_filters, [ksize, ksize], scope='conv1') net = slim.conv2d(net, n_filters, [ksize, ...
e2d223d8d6b067e1e55b046729195f69250f383a
3,598,688
def check_horizontal_visibility(board: list): """ Check row-wise visibility (left-right and vice versa) Return True if all horizontal hints are satisfiable, i.e., for line 412453* , hint is 4, and 1245 are the four buildings that could be observed from the hint looking to the right. >>> che...
c32ad3a5a31636b48f73d884d4c6af90dec91e3d
3,598,689
def _str_eval_break(eval, act, ctxt) : """Passes through [break] so that the writer can handle the formatting code.""" return ["[break]"]
2da4059adb4305a3d7e2183c29d89c9539f3c63b
3,598,690
from typing import Tuple def parse_entry_point_string(entry_point_string: str) -> Tuple[str, str]: """ Validate the entry point string and attempt to parse the entry point group and name :param entry_point_string: the entry point string :return: the entry point group and name if the string is valid ...
c2ec3eda2fca341580ff5a8d2d952e7c66fa1a0b
3,598,691
from typing import Sequence import glob async def pool_remove(p: 'Player', c: Messageable, msg: Sequence[str]) -> str: """Remove a map from a mappool in the database.""" if len(msg) != 2: return 'Invalid syntax: !pool remove <name> <pick>' name, mods_slot = msg # separate mods & slot if ...
7d74bfa42af8a84c932f022592af13c393411648
3,598,692
def int32(v) -> Int32: """Shorthand for `Int32(v)`.""" return Int32(v)
335f9f181a89bec5433cc3497f8098c7df2ee8be
3,598,693
import math def tuning_score_size(performance_space, peak): """ Computes TS_s, the tuning score based on the size of the performance space compared to the achievable performance. """ return math.sqrt(performance_space.top() / peak)
9e5386932fa164f0d33e65dd41d57d7a22ebe4d6
3,598,694
import logging def get_user(): """generateba single user :return: str:user """ logging.info("Generating user ") return f"{fake.first_name()} {fake.last_name()}"
3a8e535e185864ceff652f4048c75378d3c7fa33
3,598,695
def delete_record(tableName, query): """ Function to delete a DynamoDB table Params: tableName::str The table name to get the record query::dict The query to fetch the record Returns: bool If the record was deleted or not """ if not ta...
d819a99a1955dcafec5947bdd5eaae76cc55ae69
3,598,696
def transform_pixels_to_meters(body, pixels): """Transforms pixels to meters using scale of the given body. Note this does NOT take into account the warping at the edges. So really must take a weight... Radii from Stern, S.A. et al. (2015) "The Pluto System: Initial results from its exploration by...
374e4d766d42382d43a8f21889ff90c0f5ff8151
3,598,697
import os import codecs def namegen(text, bot, notice): """[generator|list] - generates some names using the chosen generator, or lists all generators if 'list' is specified :type bot: cloudbot.bot.CloudBot """ # clean up the input inp = text.strip().lower() # get a list of available name ge...
8b854b436fc622b07f7f916f4ce7cc44d4488a78
3,598,698
def bin_to_revstr(x, digits=16): """ >>> bin_to_revstr(10, 6) '010100' """ return "".join(reversed(bin_to_str(x, digits)))
5640237a15014bc780f06d67e75b284ac86e64d7
3,598,699