content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def orders(request): """显示用户的所有订单""" username = request.user.get_username() # 获取所有的uesername=用户名的记录,然后将记录按照time逆序排列 all_orders = Order.objects.filter(username=username) times = all_orders.values('time') # 获取不同的时间,因为对于不同的用户按照时间分类即可,相同的时间下的肯定是同一单 distinct_times = set() for distinct_time in...
4aa980465fb63e6e28d1020567cb0f6b4b607143
33,982
def convert_filename(filename): """Fix a filename""" # Try and replace illegal characters filename = replace_characters(filename) # Remove remaining illegal characters filename = remove_characters(filename) return filename
6a55ed29842ef08f19ec64db24ebcbe62f3849d9
33,983
from typing import Optional from pathlib import Path def create( path_or_url: str, output_dir: Optional[Path] = None, ) -> Path: """ Generate a new project from a composition file, local template or remote template. Args: path_or_url: The path or url to the composition file or template ...
37dcc2ebb5c918afaf851f02a5202399947e2c63
33,984
def get_camera_index(glTF, name): """ Return the camera index in the glTF array. """ if glTF.get('cameras') is None: return -1 index = 0 for camera in glTF['cameras']: if camera['name'] == name: return index index += 1 return -1
0ffee8f036f5223f419fc3e5f95184c15f1b75d4
33,985
def local_se(df, kernel, deg, width): """ This function is used to calculate the local standard errors, based on estimation results of a local polynomial regression. """ if deg != 1: print( "WARNING: function local_se is currently hard-coded for ", "polynomials of degree...
7b8fbc2d8edb2f572d0a5b06766c0e57d26b2a6a
33,986
import pickle def data(get_api_data): """Get Weather data. For testing I used pickle to """ GET_API_DATA = get_api_data if GET_API_DATA: weather_data = WeatherData() with open('today_weather_data.tmp', 'wb+')as f: pickle.dump(weather_data, f) else: with ope...
0cf4e45a3129df323ed2089a6c27b8bb0a0e2831
33,987
def json_format(subtitle, data): """ Format json to string :param subtitle: description to text :type subtitle: string :param data: content to format :type data: dictionary """ msg = subtitle+':\n' for name in data: msg += name+': '+data[name]+'\n' return msg.strip()
bb3392d7ad57a482b4175838858d316ecc5f56e1
33,988
def _nSentencesInWordMap(wtm): """Return the number of valid word sequence in wtm""" result = [0] * len(wtm) + [1] for i_ in xrange(len(wtm)): i = len(wtm) - i_ - 1 for j in wtm[i].iterkeys(): result[i] += result[j] return result[0]
9a771693ec572ad99ee7007efbf9d18e393b2c6c
33,989
def hflip(img): # type: (Tensor) -> Tensor """Horizontally flip the given the Image Tensor. Args: img (Tensor): Image Tensor to be flipped in the form [C, H, W]. Returns: Tensor: Horizontally flipped image Tensor. """ if not _is_tensor_a_torch_image(img): raise TypeError...
e551cfe143bc823ff046bd57b524a262b3ecdb8b
33,991
import numpy def gfalternate_gotnogaps(data,label,mode="verbose"): """ Returns true if the data series has no gaps, false if there are gaps """ return_code = True if numpy.ma.count_masked(data)==0: if mode=="verbose": msg = " No gaps in "+label logger.info(msg) ...
bf31bf4da5896ebe37e76d26054d7b7cac8e4a4b
33,992
def expm_tS_v2(t, S): """ Compute expm(t*S) using AlgoPy eigendecomposition and an identity. t: truncated univariate Taylor polynomial S: symmetric numpy matrix """ # Compute the eigendecomposition using a Taylor-aware eigh. L, Q = eigh(t * S) return dot(Q * exp(L), Q.T)
3d5512e3b9fc00b765538c6f1bdb3ea0d460a896
33,993
def command(): """ Return the tested command. """ return module.Command()
bd79175d169372283fca9e4555ce762f80f60f18
33,994
def computeSWC(D, cl_cores, ncl, shortpath): """ :param D: 2D dataset of n*d, i.e. n the number of cores (initial clusters) with d dimension :param cl_cores: cluster label of each cores :param ncl: the number of clusters :param shortpath: the shortest path length matrix of core-based graph :retu...
fca3dd6166867cd5d1f41c4dc0e85750f0339086
33,995
import warnings def stable_cumsum(arr, axis=None, rtol=1e-05, atol=1e-08): """Use high precision for cumsum and check that final value matches sum Parameters ---------- arr : array-like To be cumulatively summed as flat axis : int, optional Axis along which the cumulative sum is c...
0a6956461b1870c92a4a1b3556fb0889320fcac5
33,996
def read_data_min(server, port, user, pwd, instrument): """从mongo中读取分钟数据(含实时)""" #取数据 client = py_at.MongoDBClient.DBConn(server, port) client.connect(user, pwd) db = client.get_database("future_min") coll = client.get_collection("future_min", instrument) docs = coll.find() coll_real = client.get_collection("...
7dfd30a63268318a8339c3c91fc4a477891b908e
33,997
from textwrap import dedent def _demo(seed=None, out_fc=False, SR=None, corner=[0, 0], angle=0): """Generate the grid using the specified or default parameters """ corner = corner # [300000.0, 5000000.0] dx, dy = [1, 1] cols, rows = [3, 3] if seed is None: # seed = rectangle(dx=1, dy=1...
194582b64bc279ab51c54107811e052019bc862e
33,998
def measure_bb_tpdm(spatial_dim, variance_bound, program, quantum_resource, transform=jordan_wigner, label_map=None): """ Measure the beta-beta block of the 2-RDM :param spatial_dim: size of spatial basis function :param variance_bound: variance bound for measurement. Right now thi...
0b5ec56b6f0b6bb20d30e3d4bbe76b723a0dc631
33,999
def singlepass(fn): """ Will take the mean of the iterations if needed. Args: fn (Callable): Heuristic function. Returns: fn : Array -> Array """ @_wraps(fn) def wrapper(self, probabilities): if probabilities.ndim >= 3: # Expected shape : [n_sample, n_...
81052f3daf498e119cd953144da6ae76ef5bdf7d
34,000
def remove_dihedral(mol, a, b, c, d): """ utils.remove_dihedral Remove a specific dihedral in RDkit Mol object Args: mol: RDkit Mol object a, b, c: Atom index removing a specific dihedral (int) Returns: boolean """ if not hasattr(mol, 'dihedrals'): return ...
7e26e995fec97c5c6d2304e11d06fec03b990942
34,001
import inspect def load_mo(elem): """ This loads the managed object into the current name space Args: elem (str): element Returns: MangedObject """ mo_class_id = elem.tag mo_class = load_class(mo_class_id) mo_class_params = inspect.getargspec(mo_class.__init__)[0][...
07738ce084cc0c6a51a6445eaa361c5c38daf312
34,002
import collections def partialdot(mpa1, mpa2, start_at, axes=(-1, 0)): """Partial dot product of two MPAs of inequal length. The shorter MPA will start on site ``start_at``. Local dot products will be carried out on all sites of the shorter MPA. Other sites will remain unmodified. mpa1 and mpa2 ...
2051e1e9e5023ee5e9724e62d0a123937ece7fb3
34,003
import torch def thresh_ious(gt_dists, pred_dists, thresh): """ Computes the contact intersection over union for a given threshold """ gt_contacts = gt_dists <= thresh pred_contacts = pred_dists <= thresh inter = (gt_contacts * pred_contacts).sum(1).float() union = union = (gt_contacts | p...
9bd6244325acae0d3ebb5ffca46e0453a71000d1
34,004
def encode_sentences(sentences, tokenizer, language, mode): """对句子进行编码 @param sentences: 要编码的句子列表 @param tokenizer: 使用的字典 @param language: 语言 @param mode: 模式 @return: 编码好的句子列表,最大句子长度 """ if language == 'zh': return _encode_sentences_keras(sentences, tokenizer) elif language =...
8bb0d2143b73c02f1fac600ce322012da0bbdb05
34,005
def calc_scores(line_executions=LINE_EXECUTIONS, prior=PRIOR): """Return 'fault' score for each line, given prior and observations.""" return { line: float( execution_counts.negative_cases + prior.negative_cases ) / ( execution_counts.positive_cases + prior.positive_cases...
985fb4ccc193135e5aa8b5637fc8878c9314e74e
34,006
def symmetric_variable_summaries(var, metrics=None): """ Set summaries for a symmetric variable, e.g., the output of tanh. Args: var: tensorflow variable. metrics: set a list of metrics for evaluation. Support: mean, stddev, max, min, histogram. Default: mean, stddev. Returns: summaries: a li...
8ba02b426c73e939aa2797bdc32dc988b07191b0
34,007
def normalize_parameters(raw_parameters, minvals, maxvals): """takes in a list of parameters and does simple min/max normalization according to min/max values INPUTS raw_parameters: length n, containing parameters for a star minvals: length n, minimum parameter values maxvals: length n, max paramete...
53249bcecc8c3fd88beae7f377c6d5490693fba9
34,008
from typing import Any def read_users( db: Session = Depends(deps.get_db), skip: int = 0, limit: int = 100, current_user: models.User = Depends(deps.get_current_active_superuser) ) -> Any: """ Retrieve users. """ users = crud.user.get_multi(db, skip=skip, limit=limit) return users
0f4f6eed8fc181165b261cb2f325e2dd38d14cf8
34,009
from numpy import cos, sin, array def euler(a, b, c): """ Calculate a three dimensional rotation matrix from the euler angles. @param a: alpha, angle between the x-axis and the line of nodes @param b: beta, angle between the z axis of the different coordinate systems @param c: gamma, angle betwee...
406786a62b798b8e7dbbf57bd33f7243b5671e06
34,010
from pathlib import Path def guardar_imagen_cv2(img_path, filtro, filtro_name="", output_dir=""): """ img_path: directorio de la imagen filtro: funcion para aplicar filtro file_path: directorio donde guardaremos las imagen """ try: imagen_preprocesada = aplicar_preproceso(img_path, fil...
ede6ede0080df8b0ab1d99f348c014710f37c254
34,011
def create_begin_files(params): """Create initial files for HADDOCK3 run.""" run_dir = params['run_dir'] data_dir = run_dir / 'data' begin_dir = run_dir / 'begin' run_dir.mkdir() begin_dir.mkdir() data_dir.mkdir() copy_files_to_dir(params['molecules'], data_dir) copy_molecules_to_b...
8c80a2bc084cb7573948055d2e04c1fb54eb93da
34,012
import torch from typing import Optional def dump_sender_receiver_with_noise(agent_1: torch.nn.Module, agent_2: torch.nn.Module, dataset: 'torch.utils.data.DataLoader', noise_prob: float, ...
0fde105094d2fdf1b15247b80533bd6f2714d9dd
34,013
def split_list(xs, at): """Split a list into sublists by a specific item value E.g split_list(['a', 'b', '.', 'c', '.', 'd') = [['a', 'b'], ['c'], ['d'] Parameters ---------- x A list at The item value to split by Returns ------- List[List] A list of sublists split...
5fd0d3f0c9417481918c36203fc84db8be33b104
34,014
def do(the_state_machine, pre_context_sm, BeginOfLinePreContextF, BeginOfStreamPreContextF): """Sets up a pre-condition to the given state machine. This process is entirely different from any concatenation or parallelization of state machines. Here, the state machine representing the pre- condi...
bd6bdfa6826b74b036c2b7514e78a34b0b68404e
34,015
def Sexp(x,G,N): """ Stochastic exponentiation function Note: G should be such that G<<N Parameters ---------- x: Stochastic bit-stream G: Positive integer N: Integer specifying the number of states Returns ------- A stochastic bit-stream approximating exp(-2Gx) ""...
7815c2a2310593db651bad3e7922fc289d13597a
34,016
def truncate(s: str, length: int = DEFAULT_CURTAIL) -> str: """ Truncate a string and add an ellipsis (three dots) to the end if it was too long :param s: string to possibly truncate :param length: length to truncate the string to """ if len(s) > length: s = s[: length - 1] + '…' re...
90eb3cb1a26f525f8bc6076421a85d2f86af365c
34,017
def amp_kd_calc(amph_sites_ff, element): """ aem_calc calculates the partition coefficient for a specified trace element that is in equilibrium with a given amphibole composition according to Humphreys et al., 2019. supported elements = ['Rb','Sr','Pb','Zr','Nb','La','Ce','Nd','Sm', 'Eu','Gd','Dy','...
8c1f4f4b82ba24801770fffc1b8a127183a63428
34,018
def _compute_errors_and_split(p, bezier, u): """Compute the maximum and rms error between a set of points and a bezier curve""" dists = np.linalg.norm(bezier.xy(u)-p,axis=1) i = np.argmax(dists) rms = np.sqrt(np.mean(dists**2)) if i==0: return 0.0, rms, len(p)//2 elif i==len(p)-1: return 0.0, rms, len(p)//2 ...
d97c06a0924e6a0d26a57d4fd0bd4e7322e74206
34,019
def rebin_flux(target_wavelength, source_wavelength, source_flux): """Rebin a flux onto a new wavelength grid.""" targetwl = target_wavelength originalwl = source_wavelength originaldata = source_flux[1:-1] # The following is copy-pasted from the original fluxcal.py originalbinlimits = ( origina...
361484666824c7b8f23997812822cadaf57bcf47
34,020
def rate_match(residue, bead, match): """ A helper function which rates how well ``match`` describes the isomorphism between ``residue`` and ``bead`` based on the number of matching atomnames. Parameters ---------- residue : networkx.Graph A graph. Required node attributes: ...
474c2a4fb8be84935088dd1984445c4d0dccb980
34,021
def isNotEmptyString(input:str): """ this function check a string is not empty. :param input:str: given string """ if isNotNone(input): tmp = input.lstrip(' ') return isStr(input) and (len(tmp) > 0) else: return False
53c9fecea08947b500047962f609236ebc9bbb7f
34,022
def show_queue(event_id): """ Pokazuje listę osób chętnych do rezerwacji wydarzenia (kolejka). Działa tylko dla właściciela wydarzenia. :type event_id: int :param event_id: id wydarzenia """ try: with conn: with conn.cursor() as cur: cur.execute("""select...
d617a4d71a925d6f6f000fb481e7afbf9ee4ff66
34,023
def _load_contact_template(user_email, email_details): """ Loads the email contents and returns the template for contact us """ ##Email Template Init### email_template = EmailMessage( subject=email_details['subject'], from_email="Questr <hello@questr.co>", to=["Questr <hello@...
4534c0ae8ad01c3abff20e8478589c0b7863118f
34,024
def create_index(files, include_metadata=False, multi_run=False): """creates the index from list of files, by crawling over each file""" ecpps = None ecpps = run_func_on_files(ElChemPathParser, files, multi_run=multi_run) ecds = None if include_metadata: ecds = run_func_on_files( ...
ccba3c031d2b763be19f4148162fc5cb39210625
34,025
def save_partnership_contact_form(request): """ Saves the requests coming from the Partnership Contact form on the home page """ if request.method == 'POST': form = PartnershipRequestForm(request.POST) if form.is_valid(): form.save() send_partnership_request_email(req...
f22958204b3edd587e4d6a3ea6c9f6dee12f1705
34,026
def check_and_format_value(v): """ Formats all Pythonic boolean value into XML ones """ booleans = {'True': 'true', 'False': 'false'} clean = strip(v) if clean in booleans: return booleans.get(clean) return clean
26beca017621efe425a99d5f7af0645953b83870
34,027
def name_exists(name, id=-1): """Check if category name exists in db. Arguments: name as String, optional id as Integer Public categories are not allowed to appear more than once. Private categories can be duplicates. """ try: c = db_session.query(Category).filter(Category.name==name,\ ...
36d2d8597431b62425d1270c9b82c5940eb6cbf0
34,028
def perimeter_nd(img_np, largest_only=False): """Get perimeter of image subtracting eroded image from given image. Args: img_np (:obj:`np.ndarray`): Numpy array of arbitrary dimensions. largest_only (bool): True to retain only the largest connected component, typically the outer...
8957efb818c3d17485c88a0864c06f14b091c169
34,029
def get_storing_type(): """Return the storing type of the data file. One of the following integers: 0 --> ST_ALWAYS_FAST 1 --> ST_ALWAYS_SLOW 2 --> ST_FAST_ON_TRIGGER 3 --> ST_FAST_ON_TRIGGER_SLOW_OTH A STORING_TYPE dict is provided by this module. Wraps: int DWGetStoringType...
aa10f947e55c0731e9fb6446a9c102198954b09a
34,030
from typing import Optional import requests def transactions(api_url : str, network_id : NetworkIdentifier, operator : Optional[Operator] = "and", max_block : Optional[int] = None, offset : Optional[int] = None, limit : Optional[int] = None, transaction_id : Optional[TransactionIdent...
76b4a64f24dc54a7e6f1a37761b82ec2222e4fbb
34,031
def _normalize_3dinputs(x, y, z): """Allow for a variety of different input types, but convert them all to componentwise numpy arrays that the functions in this module assume.""" # Handle different forms in input arguments x = np.atleast_2d(x) # Assure a numpy array for componentwise or array versions...
f6162959cee8c4e5efa6fff5f9d81a63bacb396b
34,032
import phono3py._phono3py as phono3c def get_grid_point_from_address(address, D_diag): """Return GR grid-point indices of grid addresses. Parameters ---------- address : array_like Grid address. shape=(3, ) or (n, 3), dtype='int_' D_diag : array_like This corresponds to me...
86a6bb7385dfeb6553e1784ca656c7fbfebd30e4
34,033
def _generate_interpreted_layer(diagnostic_layer): """Generate interpreted layer from diagnostic test band Parameters ---------- diagnostic_layer: numpy.ndarray Diagnostic test band Returns ------- interpreted_layer : numpy.ndarray Interpreted la...
9810ec9306d967993881d5b94701239dbd862727
34,034
def get_evaluations(filename): """Return a list of all evaluations within an ENDF file. Parameters ---------- filename : str Path to ENDF-6 formatted file Returns ------- list A list of :class:`openmc.data.endf.Evaluation` instances. """ evaluations = [] with o...
469153dd3385f8f9ca3008c410d7b039e7167868
34,037
def svm_ova(): """Multiclass (One-vs-All) Linear Support Vector Machine.""" return CClassifierMulticlassOVA(CClassifierSVM)
064338ae0824225ad9fcd1dafc842bd2fee5180a
34,038
import re def parse(filename): """ Dict of Data """ to_return = {} f = open(filename,'r') for line in f.readlines(): m = re.match(parse_regex, line) result = m.groups() if result[0] == '+': to_return[result[1]] = True else: to_return[result[1]] =...
dbf4f25583913e1c99d70f99084a0aad2b6f618e
34,039
def get_Theta_wtr_d(region, Theta_ex_prd_Ave_d): """日平均給水温度 (℃) (12) Args: region(int): 省エネルギー地域区分 Theta_ex_prd_Ave_d(ndarray): 期間平均外気温度 (℃) Returns: ndarray: 日平均給水温度 (℃) """ # 日平均給水温度を求める際の会期係数 a_wtr, b_wtr = get_table_7()[region - 1] # 日平均給水温度 (12) Theta_wtr_d = ...
d038da7a01f6acc7ac4204e8ef8c0ac99a74027a
34,040
def get_FAAM_flights_df(): """ Retrieve DataFrame of FAAM BAe146 flights """ # Flights to use... DataRoot = get_local_folder('DataRoot') folder = '/{}/FAAM/core_faam_NetCDFs/'.format(DataRoot) filename = 'FAAM_BAe146_Biomass_burning_and_ACISIS_flights_tabulated.csv' df = pd.read_csv(fold...
0a60f9cdc61479da29de9ee93102af1abc9354b2
34,041
def get_facebook_customisations(token, aiid): """load customisations for the page""" return fetch_api( '/ai/{aiid}/facebook/custom', token=token, aiid=aiid, timeout=config.API_FACEBOOK_TIMEOUT )
067e3f30143238053ba796fe3f0bac4fd4f7a751
34,042
def plot_profile_base( x, y, err, label_x, label_y, annotate, categorical, scale_x, scale_y ): """Make a scatter plot of eval metric `y` vs training config param `x`""" f, ax = plt.subplots() if scale_y is not None: ax.set_yscale(scale_y) if scale_x is not None: ax.set_xscale(scale...
6c23989b4eaa380d5955279e1e1ba8b2eb3b85be
34,044
def train_one_step( train_batch_i, bvae_model, genmo_optimizer, infnet_optimizer, prior_optimizer, grad_variable_dict, grad_sq_variable_dict): """Train Discrete VAE for 1 step.""" metrics = {} input_batch = process_batch_input(train_batch_i) (genmo_grads, prior_grads, infnet_grads, ...
b1a4dff6dd43f1569908718bef50eacf77fe84a8
34,045
def make_stepped_schedule(steps): """ Helper to generate a schedule function to perform step-wise changes of a given optimizer hyper-parameter. :param steps: List of tuples (start_epoch, value); start_epochs should be increasing, starting at 0. E.g. momentum_sche...
33fcd823bba6bcbd5fbf9edfbad780d79a1875f5
34,046
def sepfirnd(input,filters,axes,output=None,mode='reflect',cval=0.0,origin=0): """Apply multiple 1d filters to input using scipy.ndimage.filters.convolve1d input : array_like filters : sequence of array_like Sequence of filters to apply along axes. If length 1, will apply the same filter to all axes...
3b2cc1687343121c3b93805efdadb467c0dd9e34
34,047
import json def daily_treasury(request): """ Get daily treasury. Data is from https://fiscaldata.treasury.gov/datasets/daily-treasury-statement/operating-cash-balance """ pd.options.display.float_format = '{:.2f}'.format daily_treasury_stats = pd.read_sql_query("SELECT * FROM daily_treasury", conn...
6b5f14edf68858683727b3c8a640674c4499e4e3
34,048
def list_representations(): """list available server-side objects""" try: response = get_bus().list_representations() return JsonResponse({'type': 'list', 'list': response}) except Exception as exception: message, status = handle_exception(exception) return JsonResponse({'mes...
01241939634c3eff088c1d3c6b2caac8847d1f9f
34,049
def format_endpoint_argument_doc(argument): """Return documentation about the argument that an endpoint accepts.""" doc = argument.doc_dict() # Trim the strings a bit doc['description'] = clean_description(py_doc_trim(doc['description'])) details = doc.get('detailed_description', None) if detai...
7acb21e3abafb188e3850ee9c78803e55d33fc8d
34,050
import scipy def from_edgelist(filename, directed=False, num_vertices=None, **kwargs) -> Graph: """ Construct an ``sgtl.Graph`` object from an edgelist file. The edgelist file represents a graph by specifying each edge in the graph on a separate line in the file. Each line looks like:: id1 i...
e425169eadb405458ffe3e72629409cb67e563db
34,051
def shn_shelter_rheader(r, tabs=[]): """ Resource Headers """ if r.representation == "html": rheader_tabs = shn_rheader_tabs(r, tabs) record = r.record rheader = DIV(TABLE( TR( TH(Tstr("Name") + ": "), record.name ...
d802f68d89e04ec420e366ef651df278025d9822
34,052
from operator import xor def usig1(bitarray: UBitArray32) -> UBitArray32: """ (uppercase sigma 1) Computes the XOR of three sets of bits which result from rotating the input set rightwards by 6, then 11, and then 25. Args: bitarray: (UBitArray32) The set of bits to operate on. R...
62aa93fa77dde53aecfe5bfd335ec919eedbbdb2
34,054
def fullRadar(dicSettings, mcTable): """ Calculates the radar variables over the entire range Parameters ---------- dicSettings: a dictionary with all settings output from loadSettings() mcTable: McSnow data output from getMcSnowTable() Returns ------- specXR: xarray dataset with t...
c7de880a159b80c60ec030a926f9d6278103c8cb
34,055
def connect_db(uri, default_db_name=None, factory=pymongo.MongoClient): """ Use pymongo to parse a uri (possibly including database name) into a connected database object. This serves as a convenience function for the common use case where one wishes to get the Database object and is less concerned...
2ccb233aec3f9df9da1e4a9b82c7c4e5dbbfd0d9
34,056
from pathlib import Path import re def parse_path(path: Path): """Obtain filename, task, framework and engine from saved path. """ if re.match(r'^.*?[!/]*/[A-Za-z]+-[A-Za-z]+/[A-Za-z_]+/\d+$', str(path.with_suffix(''))): filename = path.name architecture = path.parent.parent.parent.stem ...
310d7bccb6f54147cb2214da45f339243be99620
34,058
import requests def check_newer_version(command: str): """ Query for the latest release of the chaostoolkit to compare it with the current's version. If the former is higher then issue a warning inviting the user to upgrade its environment. """ try: command = command.strip() r ...
0998818229f2cb0de5abb6bf9c9de0ba765fdbe9
34,059
def prettyprint(s, toUpper=False): """Given a string, replaces underscores with spaces and uppercases the first letter of each word ONLY if the string is composed of lowercased letters. If the param, toUpper is given then s.upper is returned. Examples: "data_quality" -> "Data Quality" "copy_number...
18a57e74a2e3df66db4ede337663f9d8993a986b
34,060
def doFilter(rule, dstPath): """ 过滤 """ global useStart global useEnd global useConatins global searchInChild # 文件名后缀(可以包含 点号) global fileNameSuffix temp = rule.get("searchInChild", False) if True == temp: searchInChild = True print "searchInChild is " + s...
9de196537753ffabd288f1aa64d0fe6b63a4225e
34,061
import json def generate(schema_id: str) -> tuple: """Generates sample data from a schema :param str schema_id: Schema id :return: A http response :rtype: tuple """ search = [{'schema': schema_id}] if ObjectId.is_valid(schema_id): search.append({'_id': ObjectId(schema_id)}) ...
1caaa15753d0e33cb62d0d3c0f7cdf68945bb938
34,062
def recombine_edges(output_edges): """ Recombine a list of edges based on their rules. Recombines identical Xe isotopes. Remove isotopes. :param output_edges: :return: """ mol = Chem.MolFromSmiles(".".join(output_edges)) # Dictionary of atom's to bond together and delete if they come in ...
b3ffbb9d3cf15c0f411fb83a8f1013a1988ae7ec
34,063
def to_num_groups(word_groups): """ This function returns the a list of 24 numbers from a list of 24 words representing the payload """ with open('wordlist.txt', 'rb') as (file): words = file.readlines() words = [word.decode('utf8').strip() for word in words] num_groups = [words.inde...
4286c584bb2f32d9c5ed0f3bcf2d0ee225b84ce4
34,065
import math def _rsqrt(step_number, tail_start, body_value): """Computes a tail using a scaled reciprocal square root of step number. Args: step_number: Absolute step number from the start of training. tail_start: Step number at which the tail of the curve starts. body_value: Value relative to which ...
99138c88ae8d0fc0d49a5ac55e389cd5a40d5f90
34,066
def set_formula_in_row(ws, num, row, mr_col=1): """ This "loops" through single cells in a column and applies mixing ratio formulas. The format of the formulas is quite convulted for legacy reasons. Existing procedures made adhering to this format easier, but the gist is below. Samples come in sets of ...
2d4d438670e0760ce0158d5930390824634cce52
34,067
from typing import Union import pathlib from typing import List from typing import Tuple import json def prepare_ablation_from_path( path: Union[str, pathlib.Path], directory: Union[str, pathlib.Path], save_artifacts: bool, ) -> List[Tuple[pathlib.Path, pathlib.Path]]: """Prepare a set of ablation stu...
39e043ed3a9cb82a85610c4b6df0d2d718895fb1
34,068
def currentTime(*args, **kwargs): """ Modifications: - if no args are provided, the command returns the current time """ if not args and not kwargs: return cmds.currentTime(q=1) else: return cmds.currentTime(*args, **kwargs)
89b6d0c8abbea29b4a1f1f9f0f6458735313b400
34,070
def get_shapes(gdf: gpd.GeoDataFrame, colname: str) -> list: """ Extract and associate and format geometry and data in GeoDataFrame. """ assert "geometry" in gdf.columns, f"Expected `geometry` in {gdf.columns=}" assert colname in gdf.columns, f"Expected {colname!r} in {gdf.columns=}." return [(...
bf65d6a2caeee7d82b2b84f2b07722445beefb58
34,071
def _decodeUserData(byteIter, userDataLen, dataCoding, udhPresent): """ Decodes PDU user data (UDHI (if present) and message text) """ result = {} if udhPresent: # User Data Header is present result['udh'] = [] udhLen = next(byteIter) ieLenRead = 0 # Parse and store U...
91a259e2482ee654cc3fc1388138695ed975d778
34,072
from NexposeAPI import VulnData from skaldship.exploits import connect_exploits def import_all_vulndata(overwrite=False, nexpose_server={}): """ Uses the NexposeAPI and imports each and every vulnerability to Kvasir. Can take a looooong time. Args: overwrite: Whether or not to overwrite an existi...
d87bfc3e1a12de4e4c65bf0961be4b74787c5393
34,073
import json def add_category(category_name): """ REST-like endpoint to add a category :returns: Customized output from GIPHY :rtype: json """ user = ( models.database.session.query(models.users.User) .filter( models.users.User.token == flask.request.cookies["X-Auth...
e5ff14ef56f628df982c524c27a7a7b61719be2c
34,074
from typing import Optional from datetime import datetime from typing import List from typing import Tuple import re async def send_embed( channel: Messageable, embed_text: str, title: str = "", url: Optional[str] = None, colour: Colour = Colour(settings.embed_color_normal), ...
f102bb7a5737519d5d6f9cbda48feb1a0337ffba
34,076
from ucscsdk.mometa.comm.CommSyslogMonitor import \ def syslog_local_monitor_disable(handle): """ This method disables logs on local monitor. Args: handle (UcscHandle) Returns: CommSyslogMonitor: Managed Object Raises: UcscOperationError: If CommSyslogMonitor is not pres...
40d48a4932c7e79221aba95ba5f0a4d8b5ba446c
34,077
def git_push_obj(verbose, remote, obj=None): """ Push given object to git :param obj: object wich will be pushed to git :type obj: any one implements the interface of pushing to git :rparam boolean: If success return True """ try: LOGGER.info("%s: pushing to remote - %s", verbose, ...
4139e93ff714baf70e50ff43329b6d3618508ede
34,078
from datetime import datetime import random def partial_generator(api_list, seed = datetime.now().microsecond): """ Randomly denys access to certain API functions :param api_list: The list of functions in the api :param seed: An int, allows for seeding the tests with a certain seed to create predictab...
c32f8e072d35a79028cd9dcbe1edb2b28edf867c
34,079
def get_key_from_event(*, event: dict) -> str: """Return S3 Object's Key from Lambda event Args: event (dict): Lambda event object """ record = event['Records'][0] obj_key = record['s3']['object'].get('key') if obj_key: return obj_key else: raise ObjectKeyError('KeyE...
274eef78eb646fd10d3f5970051de24a0f273e1e
34,080
def import_buffer_to_ast(buf, module_name): """ Import content from buf and return a Python AST.""" return hy_compile(import_buffer_to_hst(buf), module_name)
b9bf33808e6951f3c6e49223f77c8cd8b1db07b6
34,082
def svn_wc_delete(*args): """ svn_wc_delete(char const * path, svn_wc_adm_access_t * adm_access, svn_cancel_func_t cancel_func, svn_wc_notify_func_t notify_func, apr_pool_t pool) -> svn_error_t """ return _wc.svn_wc_delete(*args)
fb93c2989f65001a5e0ef012801a7c66582c815b
34,083
import functools import warnings def deprecated(func): """ A decorator used to mark functions that are deprecated with a warning. """ @functools.wraps(func) def wrapper(*args, **kwargs): # https://stackoverflow.com/questions/2536307/decorators-in-the-python-standard-lib-deprecated-specific...
b79556e9ef0c7b8fb877788ab53b198807f782ee
34,084
def queryAnnotations( paths, # type: List[String] startTime=None, # type: Optional[Date] endTime=None, # type: Optional[Date] types=None, # type: Optional[List[String]] ): # type: (...) -> List[Annotation] """Queries user stored annotations from the Tag history system for a set of paths,...
e68b2a94ae54f7cfba854cf295dfbaf9e148e391
34,085
def has_other_useful_output(content_text): """Returns whether |content_text| has other useful output. Namely, console errors/warnings & alerts/confirms/prompts. """ prefixes = ('CONSOLE ERROR:', 'CONSOLE WARNING:', 'ALERT:', 'CONFIRM:', 'PROMPT:') def is_useful(line): retu...
c1abfdaf681816314134ae33b5fd0fc48757dcc5
34,086
import re def scrape(pagelim, endpoint, term=''): """ Retrieves all pages of the specified URL format up to the page limit. Most of this code is spent on the loop structure to make sure we can automatically get all the pages needed without storing empty data. The latter half of thi...
16c0d026e7f320549d77b1a6655aa8db35f6521e
34,087
def TransformContainerAnalysisData(image_name, occurrence_filter=None): """Transforms the occurrence data from Container Analysis API.""" occurrences = FetchOccurrencesForResource(image_name, occurrence_filter) analysis_obj = container_analysis_data_util.ContainerAnalysisData(image_name) for occurrence in occur...
99edfe655884a2932b4e84d6ce370df7dde7412e
34,088
import random def cluster_randomly_weigthed(document, prob_coref=0.03): """ Randomly creates a coreferring link between a mention, m2, and any preceding mention, m1. Probability of selecting a closer antecedent is higher, according to a geometric distribution Probability of selecting an ante...
d7223c9594ba5689e69f47048cf53f10b04bb85a
34,091
def getOffset(self,name): """ get the offset """ return [self.xoffset,self.yoffset]
b7b8d9c5da6bb38751e579583a8a5bd118cb1f67
34,092
def to_nbsphinx(s): """Use the sphinx naming style for anchors of headings""" s = s.replace(" ", "-").lower() return "".join(filter(lambda c : c not in "()", s))
87b266c84f9b32c1d7357c5ed23ba4058ba33673
34,093