content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _SquaredDifferenceGrad(op, grad): """Returns the gradient for (x-y)^2.""" x = op.inputs[0] y = op.inputs[1] sx = array_ops.shape(x) sy = array_ops.shape(y) # pylint: disable=protected-access rx, ry = gen_array_ops._broadcast_gradient_args(sx, sy) # pylint: enable=protected-access # .op works with ...
474d506e51b72971e3532d701365f1f18d3ac8ee
55,435
def keep_only_this_derivation(name_of_set_to_make,connections_list_of_dics): """ """ new_connection_list_of_dics=[] # print(name_of_set_to_make) for connection_dic in connections_list_of_dics: # print(connection_dic["derivation name"]) if (connection_dic["derivation name"]==name_of_set_to_make): ...
4ec8a010055d6f3740c489184f8b123bcd8780ee
55,436
def decompose_z_matrix(z_matrix, fixed): """Decompose the z-matrix into blocks to allow parallel (batched) reconstruction of cartesian coordinates starting from the fixed atoms. Parameters ---------- z_matrix : np.ndarray Z-matrix definition for the internal coordinate transform. Ea...
0c0c8ce05f4735101308885eb156e60f87f44cb6
55,437
from typing import Tuple from typing import List from typing import cast def search(database: str, expression: str) -> 'Tuple[int, List[int]]': """ Прямой поиск по словарю :param database: имя базы данных :param expression: поисковое выражение :return: пара "код возврата-найденные MFN" """ ...
0619e289a3e6904686aff7b13f91047c49600c2e
55,439
def make_ngmlr_index_cmd(in_fa): """return cmd string which generates ngmlr indices""" assert is_fasta(in_fa) return 'ngmlr -x pacbio --no-progress -t 1 -R 0.01 -r %s -q /dev/null 1>/dev/null' % in_fa
f00162068f1d21f0190107aa3ba4f3f16e779a03
55,441
import typing def get_group_member_ids(group_id: int) -> typing.List[int]: """ Returns a list of the user IDs of all members of the group with the given group ID. :param group_id: the ID of an existing group :return: the member ID list :raise errors.GroupDoesNotExistError: when no group with ...
027d00b349c54ac6d5eb5e4a943a9e0acd43e61e
55,442
def tone3_to_normal(tone3, v_to_u=False): """将 :py:attr:`~pypinyin.Style.TONE3` 风格的拼音转换为 :py:attr:`~pypinyin.Style.NORMAL` 风格的拼音 :param tone3: :py:attr:`~pypinyin.Style.TONE3` 风格的拼音 :param v_to_u: 是否使用 ``ü`` 代替原来的 ``v``, 当为 False 时结果中将使用 ``v`` 表示 ``ü`` :return: :py:attr:`~pypinyi...
3cd3db860d008adbabec0d3931bd0e63c4b41ec1
55,443
def check_purchase(paykey): """ When a purchase is complete checks paypal that the purchase has gone through. """ with statsd.timer('paypal.payment.details'): try: response = _call(settings.PAYPAL_PAY_URL + 'PaymentDetails', {'payKey': paykey}) ...
0d0ac7c6dc79eaf5e3ec60c7542adc2529e62840
55,444
def deblend(net, images, normalised = False): """ Deblend the image using the network parameters: net: neural network used to do the deblending images: array of images. It can contain only one image normalised: boolean to indicate if images need to be normalised """ if normal...
a9dd536826dfb90f17be7c8783f54f08111b693d
55,445
from typing import Union from typing import Tuple from typing import Optional def roll( x: Union[ivy.Array, ivy.NativeArray], shift: Union[int, Tuple[int, ...]], axis: Optional[Union[int, Tuple[int, ...]]] = None, *, out: Optional[ivy.Array] = None, ) -> ivy.Array: """Rolls array elements alon...
2c6dacce51fc0924ad9fda8dfb0d311a2617c5f9
55,446
def assessors_detail(request): """Managerial Detail View on the status, progress and returned review for each Expert Assessor.""" return render(request, 'review/assessors_detail.html', {})
db5e2214f468faac612d4a62b76b5b0a7cfd864d
55,447
def convert_plf_to_transition_points(plf): """ identify mid points of intervals and return them as transition points :param plf: :return: """ plf_transition_points = plf.transition_points mid_points = [] for index, point in enumerate(plf_transition_points): if point < LARGE_NUMBE...
8b20f084074584795f97d4c2645a3f31fcd633aa
55,448
def make_task(func): """make decorated function a task-creator""" func.create_doit_tasks = func return func
4a7d23765aa47f4c87723efc080913ff0c126205
55,449
import numpy def CalculateAllSumSquareCharge(mol): """ ################################################################# The sum of square charges on all atoms -->Qass Usage: result=CalculateAllSumSquareCharge(mol) Input: mol is a molecule object. Outpu...
7a115bee67a2b3ecff53a4b220fe8119e7adc6b7
55,450
def ifelse(condition, then_expression, else_expression): """Controls if else logic flow inside a computational graph """ if condition: output = then_expression else: output = else_expression return output
69190f0f9c51cd97db97d64203f51ae66370e3ff
55,455
def mat4_scale(factor, origin=None, direction=None): """Return matrix to scale by factor around origin in direction. Use factor -1 for point symmetry. >>> v = (np.random.rand(4, 5) - 0.5) * 20 >>> v[3] = 1 >>> S = scale_matrix(-1.234) >>> np.allclose(np.dot(S, v)[:3], -1.234*v[:3]) True ...
c3151f37bbcba584505d1c5a090ba4d5fa38942a
55,456
from .settings import has_channels def create_schema(): """ Root schema object that graphene is pointed at. It inherits its queries from each of the specific type mixins. """ query_mixins = [] for fn in hooks.get_hooks("register_schema_query"): fn(query_mixins) # ensure graphene...
b506155bcecc39d8b651ce365a8bc3c4af7d3804
55,457
from model import CaptchaModel from kaptcha_model import CaptchaModel def predict(captcha, model_dir='./model/model-latest.pkl', use_gpu=True, mode='captcha'): """ :param captcha: :param model_dir: :param use_gpu: :param mode: :return: """ gpu_available = torch.cuda.is_available() ...
74d9f3310c659c2347e71c04b535ef77594a2fb3
55,459
import logging def map_significance(filename, ap_radius=2, Npix=100, data_hdu=0): """ Make a full significance map of the data in 'filename'. :param filename: A string giving the path to a fits file to analyze :param ap_radius: The aperture radius to use. Default = 2 pixels :param Npix: The numb...
b519b54a9c0f8d5399d4efeaae295cef1ab909a8
55,460
def instrLeakAddr(): """Build the Leak Kernel Address instruction. Args: (none) Return Value: string containing the serialized instruction """ return addHeader(SCOUT_INST_LEAK_ADDR, b'')
6f4fbcc3254e7f0f28445178e2b9e1d46199166e
55,461
def create_media_types( tator_api: tator.api, project: int) -> list: """ Create the media types """ spec = { "name": "Image", "description": "Image type", "dtype": "image", "attribute_types": [ { "name": "Trip ID", "dtype": "stri...
552411718da7d651dcd089606a4b7495d915cf02
55,462
def entradas(): """faz as perguntas sobre o contato e retorna os dados""" contato = {} nome = input("qual o nome do contato: ") contato['nome'] = nome contato["numero"] = input("qual o telefone/celular: ") contato["endereco"] = input("qual o endereço: ") contato["email"] = input("qual o emai...
dbcb82d91facf4c324db6cff07d2080ca3330c6a
55,463
def sigmoid(x): """Compute the sigmoid function. We don't bother with clipping the input value because IEEE floating point behaves reasonably with this function even for infinities.""" return 1.0/(1.0+np.exp(-x))
df95d9cadde13ddbcadcf3bb55d6b250fd48c219
55,464
import numpy def get_N_colors(N, cmap_name='Dark2'): """ given N and a colormap, get N evenly spaced colors""" try: color_map = plt.get_cmap(cmap_name) return [color_map(c) for c in numpy.linspace(0, 1, N)] except ValueError: # try reversing the colormap name color_map = pl...
220ef94d832064519015c39b8fa2ad2b57e73607
55,465
def hopf_bifurcation_modified(beta): """Return a systems of equations relating to the hopf bifurcation""" return lambda t, X : [ beta*X[0]-X[1]+X[0]*(X[0]**2+X[1]**2)-X[0]*(X[0]**2+X[1]**2)**2, X[0]+beta*X[1]+X[1]*(X[0]**2+X[1]**2)-X[1]*(X[0]**2+X[1]**2)**2, ]
42003966274c0cda99630f1b86d746c965caa149
55,466
def Sparsity_unit(*args): """ Create the sparsity pattern for a unit vector of length n and a nonzero on unit(int n, int el) -> Sparsity position el. """ return _casadi.Sparsity_unit(*args)
12a1dc895f915918ef100575d4cdff10a95e054b
55,468
import warnings def exponential(start=None, end=None, startt=None, endt=None, dt=None, t=None, extend="constant"): """ ``exponential`` is deprecated. Use ``ease_in(... method='exponential')`` instead. """ warnings.warn("exponential is deprecated. Use " "ease_in(... method='ex...
f0b52c1fccf6714598967e079d72b2b2c7142a5e
55,469
from typing import Optional from typing import Union from typing import List def list_contacts(connection: 'Connection', to_dictionary: bool = False, limit: Optional[int] = None, **filters) -> Union[List['Contact'], List[dict]]: """Get all contacts as list of Contact objects or dictionaries. ...
be14351740d882f8e73a637921c4a5c94a6920d3
55,470
def show_asm_context(occurrence: adsk.fusion.Occurrence, prefix: str, msg_list) -> None: """Walks up assembly tree for selected item Args: occurrence: input occurrence then recursively sm context prefix: continue building up parent contexts as you recursively move up the tree """ app = ...
385456a773908dce1ea3788e257149f883c7e1e8
55,471
def pass_exchange(request): """Display the list of sites one can exchange a voucher for a pass at.""" state = request.GET.get('state') if state: sites = get_active_pass_exchange_sites(state) form = PassSiteStateForm(initial={'state': state}) state_name = STATES[state] else: ...
e16aa1ecd01b4e67a0b4e5b033d5dd71285a8304
55,472
def cotes_combine_all_sites(*matches, freebet=False): """ Calcule les cotes combinées de matches dont on connait les cotes sur plusieurs bookmakers """ sites = set(matches[0]["odds"].keys()) for match in matches: sites = sites.intersection(match["odds"].keys()) combine_dict = {"date"...
b17c019e19d839c51c070bb99d63edb695685317
55,473
import re def find_title(text): """ This function extracts and returns title case words found in a string variable. :param text: a string variable :return: a list of characters """ return re.findall(r'\b[A-Z][a-z]+', text)
9b599f6e0d708bce041ac7764f514457bd384a4f
55,474
from pathlib import Path def read_image_scipy2(input_filename: Path) -> np.array: # type: ignore """ Read an image file with scipy and return a numpy array. :param input_filename: Source image file path. :return: numpy array of shape (H, W), (H, W, 3). """ numpy_array = imageio.imread(input_...
54d3aa7d8a3043e5a79e2668be1e971b543669d9
55,475
def get_rule_by_id(neutron, sec_grp, rule_id): """ Deletes a security group object from OpenStack :param neutron: the client :param sec_grp: the SNAPS SecurityGroup domain object :param rule_id: the rule's ID :param sec_grp: a SNAPS SecurityGroupRule domain object """ rules = neutron.lis...
00afc40d003279cbd347678db0b56b4be8222568
55,476
def parse_image_names(data): """ Returns list of the Images names grouped by type. @parameter{data,dict} dictionary with keys: @val{images_private}, @val{images_public}, @val{images_group} @returns{list} Images names. """ emty_category_counter = 1 categories = [] categories.append([_(...
562d70988ce264bbadec571979c70cb6a123f98c
55,477
import torch import random from pathlib import Path from datetime import datetime import socket import logging def init_train(args, cfg, dataset): """ Training initialization. Including Data generator, model, optimizer initialization. """ '''Cuda''' args.cuda = not args.no_cuda and torch.cuda.is...
5da29b76803cacb8435d85fb202388efca2fb512
55,478
def select_distinct_best_records(records: list[Record], n_records: int) -> list[Record]: """ Select records related to highest scores (without duplicates). :param records: original records :param n_records: number of unique records to select :return: best records """ ...
ae37db4ce36cb3f04f9c2912719b3dcfcbb97caf
55,479
from typing import OrderedDict def list_ports(): """Return an alphabetically-sorted list of ports.""" return OrderedDict(sorted( (port.device, { 'name': port.name, 'device': port.device, 'description': port.description, 'hwid': port.hwid, 'vi...
a3f92dfe35e7d21cc9b9b2ce443da75970b2ee9c
55,481
def LE(ccs_sample, energy_sample): """Finds the lowest energy conformer of a sample. """ idx = np.argmin(energy_sample) return ccs_sample[idx]
2b0b649086632fb2a4127185a600631eaa9a6129
55,482
from typing import Dict def get(id_: int, type_: str, api_name: str, session: scoped_session, recursive: bool = False) -> Dict[str, str]: """Retrieve an Instance with given ID from the database [GET].""" object_template = { "@type": "", } # type: Dict[str, Any] try: rdf_class = session...
23790cdd15279331feeb5da94340ca09c412e5c4
55,483
from typing import List from typing import Tuple def sentence_from_tokens( tokens: List[str], pos_list: List[str] ) -> Tuple[str, List[Tuple[int, int]]]: """ Apply some heuristics to create a sensible text text from the tokens. Unfortunately the original whitespace information is not available. "...
df212e0324efb4135f7674ea7d598d73fea7d2cb
55,486
import logging def read_labels(label_file): """ Reads a labels.csv file into memory and converts columns to their appropriate dtype. Parameters ---------- label_file: str Path to labels.csv Returns ------- data: list of OrderedDict A list of the rows of the csv, w...
82f65eed0395295bb8aaa6fd3c4294204e52905e
55,487
def euler2dcm2(angles, sequence='321'): """euler rotation sequence utilizing predefined matrix :param a1st: angle for first rotation axis (rad) :param a2nd: angle for second rotation axis (rad) :param a3rd: angle for third rotation axis (rad) :param sequence: euler sequence; default='321' :retur...
8428aa98da4f3e3aea11b8244cac36267ac2045e
55,488
def condition_ndm_nfe(data, nr, nc, upper, lower, NDM, NFE, p, kk, dlimit, average, normalize, ndm, nfe): """ fcndm = cndm(data, 0.1, 0.1, 1) for test Construct the CSN for sepecified cells Parameters: `cells` Construct the CSNs for all cells, set ...
69eba8829462fed03554db9589f438538326430f
55,489
def generator_executor(func): """ Decorator for running generator function through GeneratorThread. """ def wrapper(*args, **kwargs): with GeneratorExecutor() as executor: return executor.submit(func, *args, **kwargs) return wrapper # class BaseTask(object): # pass ...
cfb6cdc57db1841491b2fc296eaa18b6f579b941
55,492
def check_hdr(hdr): """ :param hdr: Header from a NIRPS image to be cheked against a number of QCs We'll need to add more checks with time. :return: """ keys_to_check = ['OBJECT'] output = '' for key in keys_to_check: if key not in hdr: output+='missing:'+...
9626f472d5194217a7d6f794e6192aea7112154b
55,494
def load_script(filename): """ Loads a python script as a module. This function is provided to allow applications to load a Python module by its file name. :param string filename: Name of the python file to be loaded as a module. :return: A |Python|_ module loaded from the specifi...
954c42d53164963bfa02d3d8abd305b973f602fd
55,495
def has_prefix(sub_s): """ :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid :return: (bool) If there is any words with prefix stored in sub_s """ for s in dic: if s.startswith(sub_s): return True return False
c73940feb94158377cafeaf6f2f6414fc9829969
55,496
def get_partition_disk(ns, partition): """ Return a device on which is located the given partition. :type partition: LMIInstance/CIM_GenericDiskPartition or string :param partition: Partition to examine. :rtype: LMIInstance/CIM_StorageExtent. """ partition = common.str2device(ns, partition)...
01e3b25d1f0fc3c8802f3ab3ef07286d247764da
55,497
def checkParts(coordsList): """ Builds the part status dictionaries for each plane part and other part (bear, cloud and colours) Then generates the list of blocks to be placed (newCoordsList). Also calls calculateFlightDistance() to generate the flight score. """ global planePartStatus, otherPar...
2e7504cb8870c5a46d6be53ec70077ba2b637b4f
55,498
import warnings def _insul_diamond_dense(mat, window=10, ignore_diags=2, norm_by_median=True): """ Calculates the insulation score of a Hi-C interaction matrix. Parameters ---------- mat : numpy.array A dense square matrix of Hi-C interaction frequencies. May contain nans, e.g. in...
493785d9430e39d9708f5bc65a13495bbcfb78ad
55,499
def is_gate_this_standard_unitary(gate_unitary, standard_gate_name): """ Whether a unitary is, up to a phase, the standard gate specified by the name `standard_gate_name`. The correspondence between the standard names and unitaries is w.r.t the internally-used gatenames (see internal_gate_unitaries())....
2fa182c31172e498103491e2da0029bb0bcbbd6f
55,500
def topodic_supported_languages(): """ Show supported languages. This will show the user which languages are currently supported. And this path operation will: * return a dictionary of supported languages along with their ISO2 language codes """ return settings.LANGUAGE_DICT
dcdc366f2e795e64897f65350b7d8bb9eca483b0
55,501
def find_values(result): """ extract values from resultset returns <dict>[instance] = <tuple>values """ values = {} for metric_series in result.value: instance = metric_series.id.instance values[instance] = metric_series.value return values
50e2206eb46ff3594658ff7f87461dc778dedd3e
55,502
def process_results(results): """ Gets user choice that needs to be played :param results: stores the results which we got from get_items :return: user choice """ if len(results) >= 1: temp_data = {} count = 1 print("Here are the top {} results for your query, which one w...
23d3087ddf39ab6fa94072fabaa2bcde68add2a9
55,503
def get_fun_inter_sequence_diagram(fun_inter_str, **kwargs): """ Check and get all "show sequence Fun_inter" strings, find Fun_inter obj and then get/filter needed lists for plantuml_adapter. Args: fun_inter_str: functional interface name/alias from input cell **kwargs: whole lists ...
aa1e1eec5c63e1115530407fc1544d06807dc7db
55,504
def sia_thickness_via_optim(slope, width, flux, shape='rectangular', glen_a=None, fs=None, t_lambda=None): """Compute the thickness numerically instead of analytically. It's the only way that works for trapezoid shapes. Parameters ---------- slope : -np.gradient(hgt, dx...
4ed34ecac2a1ffcfaa287a268a88eccb396365e8
55,505
def generate_alpha(scores, length): """ Generates a scoring vector with given length from a list of scores. """ assert isinstance(scores, list) len_scores = len(scores) if len_scores > length: return np.array(scores)[:length] return np.pad(scores, (0, length-len_scores), 'constant', constan...
1d31ccc730468fff434640d91ff38467f616372d
55,506
def speech_to_text(file): """ Applies SpeechRecognition to the audio files """ recognizer = sr.Recognizer() a = '' with sr.AudioFile(file) as source: #recognizer.adjust_for_ambient_noise(source) # adjust for noisy audio audio = recognizer.record(source) try: ...
d26597e88d84b7b1b0e886dbec251ef8b8c4a0a5
55,508
def create_socket(app): """Create a socketio object""" # We don't want to monkey patch the naive python functions # which destuct some of the PyPPL functionalities # We might be swtiching to gevent or eventlet if PyPPL is # switching to greenlet. namespace = RootNamespace('/') socketio = Soc...
8c6a1872dd43a4a4e83720b2ca1a56c104c93cc9
55,509
import numpy def svdown(omega, wvno, d, a, b, rho): """ Find the values of the Haskell vectors for Rayleigh-wave. Values are calculated at each layer boundaries from top layer downward. """ mmax = len(d) aa0 = numpy.zeros(4, dtype=numpy.float64) vv = numpy.zeros((mmax, 4), dtype=numpy.f...
11cd910813324b9f5f2de3147f53d598975849f4
55,510
def load_train_valid_test_data(DisNet_dataDict_save_path): """ load train valid test data from npy file :param DisNet_dataDict_save_path: npy file which contains training data :return: """ data_dict = np.load(DisNet_dataDict_save_path).item() X_train_distance = data_dict["X_train_distance"] ...
6024ee6629eb938738e8b7b571c01621646818c5
55,511
import re def pem_as_string(cert): """ Only return False if the certificate is a file path. Otherwise it is a file object or raw string and will need to be fed to the file open context. """ if hasattr(cert, 'read'): # File object - return as is return cert cert = cert.encode('utf-8...
c4ada5957115fce9a31775d33e1787482fab8c9f
55,512
def bit_perm_2_mat(a): """transforms a permutation into a bit matrix. Representation of permutations and bit matrices see comment on module. """ if isinteger(a): return a return [1 << x for x in a]
d58ba0ebc38690ad23b7972b634f29674419faaa
55,513
def box_refinement(box, gt_box): """Compute refinement needed to transform box to gt_box. box and gt_box are [N, (center_x, center_y, center_z, l, w, h)] """ box = tf.cast(box, tf.float32) gt_box = tf.cast(gt_box, tf.float32) dz = (gt_box[:,2] - box[:,2]) / (box[:,5]+1e-8) dy = (gt_box[:,1]...
146b261033cba10df109eeb5956aa637c566932f
55,514
def initializer(name, storage_socket, meta, molecule): """Initializes a service from a API call Parameters ---------- name : str Description storage_socket : StorageSocket A StorageSocket to the currently active database meta : dict A JSON blob with the required keys for...
a3c6a49f70062f66ebce08807bea376ab3f69dc6
55,515
def preprocess_image(x, mode='caffe'): """ Preprocess an image by subtracting the ImageNet mean. Args x: np.array of shape (None, None, 3) or (3, None, None). mode: One of "caffe" or "tf". - caffe: will zero-center each color channel with respect to the ImageNet data...
4b17cd2db37aa037d1e773823ee796899d7be2f2
55,516
def slice_score_path(filepath, exp_str): """ Highest-level selection function; creates a selection from a MusicXML filepath and EMA expression string. :param filepath: A filepath to a MusicXML score. :type filepath: str :param exp_str: A string describing an EMA selection. :type exp_str: str :r...
ec3705434ba529c671e968a127d8e0a140eb21ef
55,517
def format_secret(secret): """ Format secret to compatible decrypt string Args: secret (string): KMS secret hash Returns: formatted ef resolvable KMS decrypt string Raises: None """ return "{{aws:kms:decrypt,%s}}" % secret
274a0686db07621d657ebc29eda21ec18c1d0afa
55,518
import types def arrangeDictbySecondaryKey(data, labels, sep='__'): """Re-arrange a dict of dicts by each records secondary keys""" newdata = {} if not type(data) is types.DictType: return data key1 = data.keys()[0] if type(data[key1]) is types.DictType: fields = data[key1].keys()...
47381c90ccb624015ad0bb936b01e0eec33aa19a
55,519
def mmr_load_params(param_config): """ Loads parameters for the MMR algorithm from YAML configuration Parameters ---------- param_config: dict YAML config dict containing parameters for the MMR algorithm Returns ------- params: dict a dictionary of loaded parameters for...
ce726a5ae22ef53b393ec36915072a6405770df6
55,520
from typing import Sequence def compute_success( ground_truth: pd.DataFrame, prediction: pd.DataFrame, iou_thresholds: Sequence[float] = np.linspace(0.5, 0.95, 10), mode: str = "take_max_stiou", ) -> np.ndarray: """Compute success %, i.e., the % of cases where there is sufficient overlap betwe...
ee5fb6956faff7f223fd1494996e912221a9cfbc
55,522
from datetime import datetime def get_patched_is_natively_supported(mpl): """Returns a patched version of `matplotlib.units._is_natively_supported`""" mpl_native = mpl.units._is_natively_supported def is_natively_supported(x, *args, **kwargs): # returns false if x is a timedelta # cal...
5b03616ffc0a65af83f359ba11f696c93127ee20
55,523
def get_projected_coords(c, ref_c): """ Parameters ---------- c : `astropy.coordinates.SkyCoord` The coordinates that you want to project. ref_c : `astropy.coordinates.SkyCoord` The reference coordinates, e.g., could be of the progenitor like in the case of Pal 5. Return...
45caebd1b04d8bcd8fe9245b0be4a31ec28fa148
55,524
def to_jraph(neighbor: NeighborList, mask: Array = None) -> jraph.GraphsTuple: """Convert a sparse neighbor list to a `jraph.GraphsTuple`. As in jraph, padding here is accomplished by adding a ficticious graph with a single node. Args: neighbor: A neighbor list that we will convert to the jraph format. Mu...
cf9c3016684d02ac7a69c4e454a2698868627f10
55,526
async def search(request: Request, args: SearchJSON): """Handles search query""" args = args.dict() if not is_valid_payload(args): return Response(content="Invalid data", status_code=400) offers = await parse_offers(**args, parsers=config.PARSERS, semaphore=app.semaphore) return app.templat...
b9773d4891d2fcea6dbcb8a74176ee55c139b7e7
55,527
def standardize_colorfulness(img, c=DEFAULT_COLOR_STD_C, h=0): """Give image constant colorfulness and hue Image is converted to cylindrical CAM-16UCS assigned a constant hue and colorfulness, and then coverted back to RGB. Parameters ---------- img : ndarray Image to be processed ...
ce49cf179454454b2e79705a72453c45bb7a2d78
55,528
def randomTerminals(PCSFInputObj, seed, excludeT): """ Selects nodes with a similar degree distribution to the original terminals, and assigns the prizes to them. INPUT: a PCSFInput object seed - number to give to the random number generator RETURNS: a new PCSFInput object with a new lis...
c1050dbf8b5a110c1b557442aec05bb6c25b6c63
55,529
from typing import Tuple from typing import List def opr_test( cases, func, mode=("eager", "static", "dynamic_shape"), compare_fn=_default_compare_fn, ref_fn=None, **kwargs ): """ mode: the list of test mode which are eager, static and dynamic_shape will test all the cases if...
fb305714f48db0e22f0c46f673982e5c00531253
55,530
import torch def le(a, b, square=False, **kwargs): """ Encodes the loss function for "a <= b". If square is false d = |a - b| is used, else d = (a - b)^2. """ if square: return torch.clamp((a - b).sign() * (a - b) * (a - b), min=0) else: return torch.clamp(a - b, min=0)
02c8a2f5255255f754be6335a7ed8c55a1910192
55,531
def split_list(l, sizes): """ Split a list into several chunks, each chunk with a size in `sizes`. """ chunks = [] offset = 0 for size in sizes: chunks.append(l[offset:offset + size]) offset += size return chunks
cac573660717e9b1782810ef948f510c07f530c1
55,532
def randomize_box(bit_array, targets, epsilon): """ The object detection unary encoding method. """ assert isinstance(bit_array, tensor) img = symmetric_tensor_encoding(bit_array, 1) label = symmetric_tensor_encoding(bit_array, epsilon) targets_new = targets.clone() targets_new = targets...
dbef8e3b08a0a5fd684a4c7eaeff9e39142fb72c
55,533
def make_tensor_list_set_item_tests(options): """Make a set of tests to do TensorListSetItem.""" test_parameters = [ { "element_dtype": [tf.float32, tf.int32], "num_elements": [4, 5, 6], "element_shape": [[], [5], [3, 3]], "index": [0, 1, 2, 3], }, ] def bui...
ffac8496c96434da912a00514053983cd2dbb0e5
55,536
import random def get_fixed_samples(a_list, num=20000): """ 固定数量的样本 """ if num <= 0: return a_list a_n = len(a_list) n_piece = num // a_n + 1 x_list = a_list * n_piece random.seed(47) random.shuffle(x_list) x_list = x_list[:num] return x_list
fe7c22329001ea0cde155a6077c28aeaffeb0a65
55,537
def SI_prefix_and_scale_factor(val, unit=None): """ Takes in a value and unit and if applicable returns the proper scale factor and SI prefix. If the unit is None, no scaling is done. If the unit is "SI_PREFIX_ONLY", the value is scaled and an SI prefix is applied without a base unit. Para...
045e844be712f03b5fe65826cc103f34da8de072
55,538
def amp_ppm(moms): """ Amplitude for k^+(k) -> pi^+(p1) + pi^+(p2) + pi^-(p3) Parameters ---------- moms : ndarray[dim=2] moms[0] = pi moms[1] = pi moms[2] = pi """ p1 = moms[0] p2 = moms[1] p3 = moms[2] k = p1 + p2 + p3 s0 = (1.0 / 3.0) * (mk ** 2 ...
dd4a89a3916e5ef418501d8c97fb3bd463071458
55,539
def template_json(data): """Returns json as a str Normally json is rendered as bytes, but putting bytes in a template that is itself encoded to bytes causes problems when trying to re-read the json from the template (with javascript). :arg data: the data to jsonify. :returns: str """ ...
098f0de06ad6bdffe1ab3bef92bd7e9f79ff7c48
55,540
def csrf(): """Provide a csrf token for the registration form. https://medium.com/@iaincollins/csrf-tokens-via-ajax-a885c7305d4a """ form = RegistrationForm() return flask.jsonify({"token": form.csrf_token.current_token})
1a13b013a29f152c775f4020ca801d9ec3ca2381
55,541
import torch def get_junction_loss_and_weight(model_cfg, global_w_policy): """ Get the junction loss function and weight. """ junction_loss_cfg = model_cfg.get("junction_loss_cfg", {}) # Get the junction loss weight w_policy = junction_loss_cfg.get("policy", global_w_policy) if w_policy == "s...
f528f43f4ec5cb540a30bbee6e304c53b3e11b64
55,543
def scatter_geo( data_frame=None, lat=None, lon=None, locations=None, locationmode=None, geojson=None, featureidkey=None, color=None, text=None, symbol=None, facet_row=None, facet_col=None, facet_col_wrap=0, facet_row_spacing=None, facet_col_spacing=None, ...
481b6c326ace1411fe6465ea714eda42b5c5e40d
55,544
import io def bytes_image_output(f): """ Decorator which marks that function returns images stored as bytes objects. :param f: function to decorate :return: decorated function """ @wraps(f) def inner(*args, **kwargs): im = f(*args, **kwargs) buffer = io.BytesIO() ...
03b82f74ea00d66c4485c0605ce5bf9c3da1b473
55,545
def remove_item(commons: dict = Depends(common_parameters)): """ Endpoint. Removes an item from cart. :param Depends(common_parameters) commons: args from `common_parameters` function :return: dict with cart and message :rtype: dict """ logger.info(f'Request@/remove_item/{commons["cart_id"]...
ae5453f86d157d11b429a3f68fc08cb794ef4b31
55,546
def intersect(*selects, **kwargs): """Return an ``INTERSECT`` of multiple selectables. The returned object is an instance of :class:`.CompoundSelect`. \*selects a list of :class:`.Select` instances. \**kwargs available keyword arguments are the same as those of :func:`select`. ...
f394fa6f0ba621858bacc7c7bb3cfbc89e9e32bc
55,547
import numpy def CalculateSimpleTopoIndex(mol): """ ################################################################# Calculation of the logarithm of the simple topological index by Narumi, which is defined as the product of the vertex degree. ---->Sito Usage: ...
9d8ebb84d491fd91cd1d9e2ebd2198dd731de0f2
55,548
def num2date(num): """num2date wrapper""" return mpl.dates.num2date(num).replace(tzinfo=None)
a8b5ed7d89a67a28b053e955658240164bc46eac
55,550
def replace_question_mark_with_nan(data_table: pd.DataFrame) -> pd.DataFrame: """ Replace question mark with NaN :return: None """ return data_table.replace(Values.RAW_DATA_NULL.value, np.nan)
bd4723f03de8e770fee671273e62520bf3b4d4aa
55,551
import itertools def infer_impact_of_variables_2by2(tabnum, protocols): """Builds the first table of my report""" for n, p in enumerate(protocols): print( "\nTable %d: Variable combinations, 2x2 for Protocol `%s`:" % (n + tabnum, p) ) print(60 * "-") ...
0d6fff2d8ad52a01a9a1767d9aee152154b2e0d7
55,552
from typing import Dict def create_security_context_xsuaa(token, service_credentials: Dict[str, str]): """ Creates the XSUAA Security Context by validating the received access token. :param token: string containing the access_token :param service_credentials: dict containing the uaa/ias credentials ...
0e1ce70f7ce32844107b420516e3d0c18d316a92
55,553
def read_distributed_data(db, cursor, mode='promiscuous', normalize=None, load_history=False, exclude_keys=None, format='dask', npartitions=None, spark_context=None, data_tag=None): """ This function should be used to read an entire dataset that is to be handled by subsequent paral...
bdfdce3a86bf2eb195f824da426b32ca422343a3
55,554
import random from functools import reduce def diceroll (dice, sides): """ Simulate rolling d dice of s sides each From Python Cookbook1st Edn pg 531 See the Python Cookbook entry on this function for the non-standard use of 'reduce' for example diceroll(5, 6) would be 5 rolls of a 6 sided...
ad51a53a9df1df2c64e7ad7f361365ff8df219c6
55,555