content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List import collections import heapq def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int: """ >>> Dijkstra's Algorithm Variation The differences are: 1. Also track the number of stops so far; 2. Now since ...
27a06b0ebce16e3b2389ce28d9a6548bfd1bdf8c
3,608,900
def get_row_col(i, axes): """Get the ith element of axes """ if isinstance(axes, np.ndarray): # it contains subplots if len(axes.shape) == 1: return axes[i] elif len(axes.shape) == 2: nrow = axes.shape[0] ncol = axes.shape[1] row_i = i ...
20c3af7e27072225699d61e16ed7968850205a28
3,608,901
from typing import Match from typing import Optional from typing import Union async def rise_score_data(payload: dict, match: Match, nickname: Optional[str] = None) -> Union[MessageSegment, str]: """ 上分数据 - `payload` : 传递给查分器的数据 - `match` : 正则结果 - `nickname` : 用户昵称 """ dx_ra_lowest = 999 ...
b6d6bba6b75779aafcd0ce8cc530c0e086ff43da
3,608,902
from ecdsa import numbertheory, ellipticcurve, util import base64 def verify_message(address, signature, message): """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """ curve = curve_secp256k1 G = generator_secp256k1 order = G.order() # extract r,s from signature sig = base...
d4d37d5aa93cb2e02ae956204bcb850e14bb649a
3,608,903
from typing import Iterable from re import T from typing import Tuple def grouped(iterable: Iterable[T], n=2) -> Iterable[Tuple[T, ...]]: """s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), ...""" return zip(*[iter(iterable)] * n)
38caab13c4e26cb504e3155765316da9235e2a3a
3,608,904
import requests import json def get_cards_done(board_id, app_key, user_token, board_name): """Fetches and returns the number of cards in the Trello list under the passed name""" # Constructing GET request to get all lists on the board url = "https://api.trello.com/1/boards/%s/lists?cards=all&key=%s&token...
e957313ac72fdfc3b1499a09496bece614ba7a6f
3,608,905
import numpy def w_conj_kernel_fn(kernel_fn): """Wrap a kernel function for which we know that kernel_fn(w) = conj(kernel_fn(-w)) Such that we only evaluate the function for positive w. This is benificial when the underlying kernel function does caching, as it improves the cache hit rate. ...
c5ba5bb741e9e696a94535c4373e84268a7ab95d
3,608,906
def loadWorld(worldName, store): """ Load an imaginary world from a file. The specified file should be a Python file defining a global callable named C{world}, taking an axiom L{Store} object and returning an L{ImaginaryWorld}. This world (and its attendant L{Store}) should contain only a sing...
801c98b5be82e9d5c9ca19db9adbe3078f500674
3,608,907
def _cosine_dist(u, v, w=None): """ :purpose: Computes the cosine similarity between two 1D arrays Unlike scipy's cosine distance, this returns similarity, which is 1 - distance :params: u, v : input arrays, both of shape (n,) w : weights at each index of u and v. array of shape (n,)...
d4252f6d79e4b1254bf79d1933ef123ff8fadc16
3,608,908
import matplotlib.pyplot as plt from pathlib import Path def save_fig(fig, dest=None, close=True, **savefig_kw): """ Saves a figure and, optionally, closes it. The way in which the destination path is specified differs from the one used by :meth:`~matplotlib.figure.Figure.savefig`. Moreover, if t...
c4d23a378a461f4e4dbd4a4e982d31be505b30b2
3,608,909
import torch def full(*args, **kwargs): """ In ``treetensor``, you can use ``ones`` to create a tree of tensors with the same value. Example:: >>> import torch >>> import treetensor.torch as ttorch >>> ttorch.full((2, 3), 2.3) # the same as torch.full((2, 3), 2.3) tensor...
8c6df708b76a799c27a45979e9a43b3d3678ac8d
3,608,910
def funnel(base, test): """Tests string against the base string to determine if it can be constructed by removing one character from the base string str, str -> bool >>> funnel("leave", "eave") True >>> funnel("eave", "leave") False """ return test in get_shortened_string_list(base)
03e0b0e223ed9c1fabdf4411eb3ea3a938917d08
3,608,911
from bs4 import BeautifulSoup from typing import Dict from typing import List def extract_back_matter_from_tei_xml( sp: BeautifulSoup, bib_dict: Dict, ref_dict: Dict, cleanup_bracket: bool ) -> List[Dict]: """ Parse back matter from soup :param sp: :param bib_dict: ...
7f830bcd4588a29281ea96e90fdba5d00f4c75c4
3,608,912
def kearsley_rotation(reference_sites, other_sites): """ Kearsley, S.K. (1989). Acta Cryst. A45, 208-210. On the orthogonal transformation used for structural comparison Added by Peter H. Zwart, Nov 3rd, 2006. Converted to C++ by Gabor Bunkoczi, Apr 2008. """ return matrix.sqr(superpose_kearsley_rotation...
2833704e69a380d1c91c2448cb39a37e49bdb941
3,608,913
def lc_virus(playing_field): """ From https://leetcode.com/contest/weekly-contest-63/problems/contain-virus/ A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. The world is modeled as a 2-D array of cells, where 0 represents uninfected cells, and 1 repre...
fb3991a8c19d7cbc3599231fd7fa6a9bf0c5b7e0
3,608,914
import math def tan(x): """Get tan(x)""" return math.tan(x)
112b52faee2f08262515086fe59b2ff978001200
3,608,915
def gelu_ad_custom(head, in_data, target="cce"): """ Automatic differentiation of gelu with customize function. In order to achieve higher precision, we could also self-define tanh part differentiate with simplify calculation. """ dtype = in_data.dtype const1 = akg.tvm.const(0.044715, dtype) ...
aec594eed9954e79cf16a36a4e50911c9a7991f1
3,608,916
def ParticleFactory(variables, name="SamplingParticle", BaseClass=parcels.JITParticle): """Create a Particle class that samples the specified variables. The variables that should be sampled will be prepended by ``var_`` as class attributes, in case there are any namespace clashes with existing variable...
5c09acf1cc4a1ce3a3fdad7cbaf026cb5533a467
3,608,917
def piece_placed(x, y, player, board): """This function determines the piece played. It takes the coordinates of the piece, the player number, and the board. The pieces are zeros or ones and the function returns the piece on the board based on the number.""" if player == 0: board[x][y] = 1 e...
ffcd46e11c3e5b0704ed66d6010dfc227106c752
3,608,918
def get_max_unsecured_debt_ratio(income): """Return the maximum unsecured-debt-to-income ratio, based on income.""" if not isinstance(income, (int, float)): raise TypeError("Expected a real number.") # Below this income, you should not have any unsecured debt. min_income = 40000 if income <...
ffff63807842197e2f60ebfd29b54ecf895f6279
3,608,919
import glob import shutil def merger(): """ Function to combine all results csv into a single file. """ #import csv files from folders path = r'C:/Users/luxon/OneDrive/Research/McQuade/Projects/NSF/OKN/phase1/Work/ml-hte-results-20200207' # Adam's tablet. will vary by OS, computer # path = r'C:/Use...
8b96d569cef54636cc009df797061b45c31c264b
3,608,920
def calc_other_bias(probs): """ :param probs: list of negative log likelihoods for a corpus :return: gender bias in corpus """ bias = 0 for idx in range(0, len(probs), 16): bias -= probs[idx + 1] + probs[idx + 3] + probs[idx + 5] + probs[idx + 7] bias += probs[idx + 8] + probs[id...
2ceb6788e22277192475218db6e3175f259dc9ba
3,608,921
def pubkey_to_merkletree(key, hashfunction, salt, prefix=""): """Convert a full signing-key pubkey into a merkletree dictionary""" drval = dict() part1 = key[0] part2 = key[1] if len(key) > 2: breakpoint = int(len(key)/2) part1, dpart1 = pubkey_to_merkletree(key[:breakpoint], hashfun...
50e5283a7189aa0202e93201d70f7343719f1f13
3,608,922
import os def images_data_set(data_set, args, session_file): """Adding images information when the data_set contains the images directory. """ try: args.images_dir = None args.images_file = None if os.path.isdir(data_set): # When data_set is a directory, we assume ...
4612e8946b37bbe2b52ae7756a5cfa6294039db4
3,608,923
def generate_test_case(num_nodes=500, num_edges=1000, num_communities=5, connecting_strength_among_communities=0.01, random_state=None): """ :param num_nodes: int :param num_edges: int :param num_communities: int :param connecting_strength_among_communities: float :param r...
417f4bf0a4c2089796dcdd2de749225c86bdb7b0
3,608,924
def deprocess_image(x): """normalize tensor: center on 0., ensure std is 0.1""" x -= x.mean() x /= (x.std() + K.epsilon()) x *= 0.1 # clip to [0, 1] x += 0.5 x = np.clip(x, 0, 1) # convert to RGB array x *= 255 if K.image_data_format() == 'channels_first': x = x.transpo...
3ecf94411855e3a212fc0ebe2b60ff76bf30efd3
3,608,925
def DFFN_3tower_5depth(x_dict, dropout, reuse, is_training, n_classes): """Three towers. Each depth 5. This is the train_paviaU network when input is 23. 20 steps/second. 94.5% on PaviaU 2%, lr 5e-5, within 10k """ with tf.variable_scope('DFFN', reuse=reuse): x = x_dict['s...
9945092ba2c983b218c0c8d9351aaede6f807a80
3,608,926
def build_list_all_request( **kwargs # type: Any ): # type: (...) -> HttpRequest """List scan rulesets in Data catalog. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. :return: Returns an :class:`~azure.purview.scanning.core.res...
4b2cbf297ec89855f794bd0bb9046f525f23a7fa
3,608,927
from typing import Any import json def is_jsonable(x: Any): """ Check if an object is json serializable. Source: https://stackoverflow.com/a/53112659 """ try: json.dumps(x) return True except (TypeError, OverflowError): return False
3735de8bd1940d84c185142c0a4387366d7cd9c2
3,608,928
def plot_cumvar_pca(data,title): """Plots the cumulative variance explained by PCA for different number of components""" fig,axes = plt.subplots(nrows=2,ncols=2,figsize=(10,8)) pca = PCA().fit(data) axes[0,0].plot(np.cumsum(pca.explained_variance_ratio_),'bx',alpha=0.6) axes[0,1].plot(np.cumsu...
e2e6758af3bc203df76f12d60be0b83ad8163036
3,608,929
def add_number_of_different_roles(dev_type: str) -> int: """ INPUT dev_type - dev_type answer (separeted by ';') OUTPUT numeric value - number of different dev types """ try: return len(dev_type.split(';')) except: return 0
78872b9101b128cc107a0194fc85b353f1d2f836
3,608,930
import time def try_models(models, X_train, y_train, preprocessor): """ Fits different regression models on the given dataset and evaluates the mean absolute error. ​ Parameters ---------- models : dict Dictionary of various regression models to try. X_train : DataFrame Traini...
4d7c1acd19ef425ebb7185cb805ddf805af55619
3,608,931
def FormatCommentWithAnnotations(comment, type_name=''): """Format a comment string with additional RST for annotations. Args: comment: comment string. type_name: optional, 'message' or 'enum' may be specified for additional message/enum specific annotations. Returns: A string with additional ...
accf33ab834e9aeada2c3edfbd83427935e5e130
3,608,932
def _todict(matobj): """ A recursive function which constructs from matobjects nested dictionaries. """ dict = {} for strg in matobj._fieldnames: elem = matobj.__dict__[strg] if isinstance(elem, spio.matlab.mio5_params.mat_struct): dict[strg] = _todict(elem) else:...
cc5c594cecdb88183b36ce4be5b8c01424847936
3,608,933
def create_network_with_bn(): """Creates a network contains both QConv2D and QDepthwiseConv2D layers.""" xi = Input((28, 28, 1)) x = Conv2D(32, (3, 3))(xi) x = BatchNormalization()(x) x = Activation("relu")(x) x = DepthwiseConv2D((3, 3), activation="relu")(x) x = BatchNormalization()(x) x = Activation(...
22a167a15326cc6d8830c6498402b45c91587c02
3,608,934
def GetBigQueryTableID(tag): """Returns the ID of the BigQuery table associated with tag. This ID is appended at the end of the table name. """ # BigQuery table names can contain only alpha numeric characters and # underscores. return ''.join(c for c in tag if c.isalnum() or c == '_')
0fe659fd3c7ca3df5f061289dad5635841146901
3,608,935
import os def _dst_path(config, entry): """Construct output path for entry.""" return os.path.join(config["dst"], entry["slug"], MAIN_DST_FILE)
0b13cd7257e6fc3e92c5c533de7781d6b435e28d
3,608,936
import timeit from typing import DefaultDict def dnscl_rpz(ip_address: str) -> str: """Return RPZ names queried by a client IP address. Args: ip_address (str): IP address to search. Returns: str: Search results found. """ start_time = timeit.default_timer() rpz_dict: Default...
0916933d64f5fca1145f3c1d31bbc6e8ae82c139
3,608,937
def rf_local_unequal_int(tile_col, scalar): """Return a Tile with values equal 1 if the cell is not equal to a scalar, otherwise 0""" return _apply_scalar_to_tile('rf_local_unequal_int', tile_col, scalar)
ca9200dd94b786ae258ec2f91dca9934f280dd01
3,608,938
def get_process_list(node: Node): """Analyse the process description and return the Actinia process chain and the name of the processing result :param node: The process node :return: (output_objects, actinia_process_list) """ input_objects, process_list = check_node_parents(node=node) output_o...
e14ecb3d43c1329cf707a21bb11c933e84875712
3,608,939
def run_text(query_string): """Run a query that should only return string contents.""" contents, types, result = run(query_string) assert types is None assert result is None return contents
6201bdde6a5fb42603b3d9a7e67629bb368dfc72
3,608,940
def Value_getNullValue(): """Value_getNullValue() -> Value""" return _yarp.Value_getNullValue()
efae2c7810f2ae277e10d68c0e6640e7d760982b
3,608,941
def transform_landmark(landmark, t): """ Function applies transformation t to a single landmark represented by its coordinates in space. It first creates poly data from its positions and then applies given transformation. :param landmark: (x, y, z) coordinates of landmark to be transformed :param t...
f058ba9060ba1e7f718c8c9d87e7cf332592ce27
3,608,942
import requests def find_location(location): """ Takes a location as a string, and returns a dict of data :param location: string :return: dict """ params = {"address": location, "key": dev_key} if bias: params['region'] = bias json = requests.get(geocode_api, params=params).j...
44381de26b3db10e00b0f03be2a5b2da14dcf812
3,608,943
import token import time def sign_url_path(url, secret_key, expire_in=None, digest=None): # type: (str, bytes, int, Callable) -> str """ Sign a URL (excluding the domain and scheme). :param url: URL to sign :param secret_key: Secret key :param expire_in: Expiry time. :param digest: Specif...
946d0ae6d704d5a6b9da8517f1b37563471761cb
3,608,944
from typing import Dict from typing import List def get_label_colour_map() -> Dict[str, str]: """converts a comma seperated list of organizations/repositories into a list of tuples. """ def _preproc(label_colour: str) -> List[str]: return label_colour.lower().split(sep="/") return { ...
440092d8f31fab679761453ec7abc8fb37b5f5d8
3,608,945
def log_modulo(a, b, m): """Computes discrete logarithm i.e. finds x such that a^x = b (mod m) Uses Shanks algorithms which takes O(sqrt(m)) time """ # find x in form x = np - q for some (n, p) # => a^x = b ~ a^np = a^q * b a, b = a % m, b % m n = isqrt(m) + 1 # compute all a^q * b ...
6f2c2afd9858ba7d3baaaa2e871cc336396d2042
3,608,946
import os def temp_video_path(): """ Defines default video path to write to for testing. """ return os.path.join(robomimic.__path__[0], "../tests/", "tmp.mp4")
724af72e70f87de3c3fdfd985e7240243853726c
3,608,947
def _linear_transform(src, dst): """ Parameters of a linear transform from range specifications """ (s0, s1), (d0,d1) = src, dst w = (d1 - d0) / (s1 - s0) b = d0 - w*s0 return w, b
7f55a2617721fdefcc724bcb8ce9f880d7bcd846
3,608,948
def feature_within_s(annolayer, list_of_s): """Extracts all <annolayer> from all sentence-elements in list_of_s; returns a flat list of <annolayer>-elements; """ list_of_lists_of_feature = [s.findall('.//' + annolayer) for s in list_of_s] list_of_feature = [element for sublist in list_of_lists_of_fe...
df6ed3603381a4b8d2ea12fc483fa37ea3068372
3,608,949
def _permute_facets(facets, ori, ori_map): """ Return a copy of `facets` array with vertices sorted lexicographically. """ assert_((in1d(nm.unique(ori), ori_map.keys())).all()) permuted_facets = facets.copy() for key, ori_map in ori_map.iteritems(): perm = ori_map[1] ip = nm.wh...
0e09ad2b7555be8e77e564266e3920e5413d851e
3,608,950
def showname(keyvalue): """filter koji za neku od prosledjenih kljuceva vraca vrednost""" key_dict ={'P':'Accepted','C': 'Created','Z': 'Closed','O': 'On Wait'} return key_dict[keyvalue]
59453d5e0dd31696b99d01c8b927297adddec10c
3,608,951
def findDomainRanges(r,r_surf_index,W,oldMiddleRange): """ Because the islands grow and shrink, the location of the boundaries are in constant flux. This code figures out the boundaries and returns the indices associates with all three regions. """ innerBCIndex=findNearest(r,r[r_surf_index]-W/2) if innerB...
db213209e4bed1daf9d3e18ceb8f0e30db5d875e
3,608,952
def create_taperedvia(AR, dr, Nseg): """Return the areas and view factor of a rectangular trench, where the vertical wall is divided into identical sections. Parameters ---------- AR : float Aspect ratio, defined as the width to top diameter ratio dr : Float Ratio between the bo...
408077ec50272236da497b93ec897213ae6b30eb
3,608,953
import torchvision import torch def get_train_val_loaders(train_dir, collate_fn, height, width, no_data_augmentation=False, max_trainset_size=np.infty, seed=0, ...
675be081fa34ad2c282674dbb59a9e81cb36581d
3,608,954
def adjust_learning_rate(optimizer, epoch, gammas, schedule): """Sets the learning rate to the initial LR decayed by 10 at 600 and 900 epochs""" lr = args.lr_ assert len(gammas) == len(schedule), "length of gammas and schedule should be equal" for (gamma, step) in zip(gammas, schedule): if (epoc...
5fb413f4403aa9606758134929f684d2dd03a621
3,608,955
def get_organizations_from_ckan(portal_url, verify_ssl=False, requests_timeout=REQUESTS_TIMEOUT): """Toma la url de un portal y devuelve su árbol de organizaciones. Args: portal_url (str): La URL del portal CKAN de origen. verify_ssl(bool)...
fd280b3106d84b66c893877657f5ec0b3b2dc635
3,608,956
def processPostMessage(post_message, status_type): """ Check if the message is >500 characters If it is, shorten it to 500 characters Ouput: a tuple of strings: read_more (empty if not shortened), post text """ if len(post_message) > 500: post_message = post_message[:500] last_sp...
2d21ec04ef863b57f95bb4b8256f2195559e6f8e
3,608,957
def linkHasRel(link_attrs, target_rel): """Does this link have target_rel as a relationship?""" # XXX: TESTME rel_attr = link_attrs.get('rel') return rel_attr and relMatches(rel_attr, target_rel)
f2a264dbb922d7c2c5318e9564744334f994454e
3,608,958
def _focus_measurement_3d(image, neighborhood_size): """Helmli and Scherer’s mean method used as a focus metric. Parameters ---------- image : np.ndarray, np.uint8 A 3-d tensor with shape (z, y, x). neighborhood_size : int The size of the square used to define the neighborhood of ea...
f830fc867177fdc4232938da03e433a2a5aa9d0a
3,608,959
from mmdet.models import SSDHead def get_ssd_head_model(): """SSDHead Config.""" test_cfg = mmcv.Config( dict( nms_pre=1000, nms=dict(type='nms', iou_threshold=0.45), min_bbox_size=0, score_thr=0.02, max_per_img=200)) model = SSDHead( ...
d46ea93f0245be1636f0f10497154724c9564f3c
3,608,960
def save_gan_images(generator, epoch, examples=100, dim=(10, 10), figsize=(10, 10)): """ Generate a sample of examples. """ noise = get_noise(examples) generated_images = generator.predict(noise) generated_images = generated_images.reshape(examples, 28, 28) plt.figure(figsize=figsize) f...
2ad954a072e85247990204061566f9bbf6238094
3,608,961
import datasets def load(dataset_info: datasets.DatasetInfo) -> testbed_base.TestbedProblem: """Load a regression problem from a real dataset specified by config.""" num_enn_samples = 1000 # We set it to the number we use for our testbed train_data, test_data = load_dataset(name=dataset_info.dataset_name) d...
de7700759da4aa8b18fc87f8d663720fd3fc4962
3,608,962
def calc_blue(historys): """ { 1: [0.16, 0.16, 0.15, ...], 2: [0.16, 0.16, 0.22, ...], ... 12: [0.16, 0.16, 0.3, ...], } """ blues = [history['result']['blue'] for history in historys] result = dict() for num in range(1,13): #12选2 # result.setdefault(n...
44e391adc8db7c85ecd45c533ce0e12485866113
3,608,963
def get_transition_analysis_matrices(odf_order, angle_max, angle_weight="flat", angle_weighting_power=1.): """ Convenience function that creates and returns all the necessary matrices for iodf1 and iodf2 Parameters: ----------- odf_order: "odf4", "odf6", "odf8" or "odf1...
aab9fa68b11e2f47acb32507e3e72422fdaea1b0
3,608,964
def condition_match(row, condition): """Return whether a condition matches a row :param row An OVSDB Row :param condition A 3-tuple containing (column, operation, match) """ col, op, match = condition val = get_column_value(row, col) matched = True # TODO(twilson) Implement othe...
49bdf006fc47e5eda628798033b9eabeb0551034
3,608,965
def expected_wait_time_random_arrival(xdata,wdata,headway, nsims = 5000000, ntrips=3, q_half=None): """ Given R-Vector xdata representing instances and R-Vector wdata representing weighted probabilities of those instances (need not add ...
ee1369516d3ee13e48c1b185fdab5b0b4278e6fc
3,608,966
def main(global_config, **settings): """ Returns a Pyramid WSGI application. Apart from the clld boilerplate, it orders the home sub-navigation and registers the get_map_marker hook. """ config = Configurator(settings=settings) config.include('clld.web.app') config.registry.settings['home_c...
71c845c2b6d190cfc7ac1845ddc7f3152c838ebd
3,608,967
import yaml def open_yaml(yfile): """ This function opens file with YAML configuration. :param yfile: Name of file. :return: Python object ( nested lists / dicts ). """ with open(yfile, 'r') as stream: yamlobj = yaml.load(stream) return yamlobj
0a76866a8430cd917518fe620fa7c346cdca7edb
3,608,968
def get_instance_path(index_instance): """ Return a platform formated filesytem path corresponding to an index instance """ names = [] for ancestor in index_instance.get_ancestors(): names.append(ancestor.value) names.append(index_instance.value) return assemble_path_from_list(...
5144a9f6bf9b88b36bec6d6c556448a2450b788c
3,608,969
def download_media_suite(request, domain, app_id): """ See Application.create_media_suite """ if not request.app.copy_of: request.app.set_media_versions(None) return HttpResponse( request.app.create_media_suite() )
bbbefb1eb20a404811baf70d42b389b74301e869
3,608,970
def current_token() -> object: """Return a backend specific token object that can be used to get back to the event loop.""" return get_asynclib().current_token()
d456fef0117d64ce51050171dfb4ae82f8dba45c
3,608,971
import base64 def _derive_sha256_key(passwd): """Derive a base64 encoded urlsafe digest from password. Using the given password, an irreversible hash is derived using cryptography algorithm. To make use of this for Fernet encryption, it is transformed to base64 encoded urlsafe digest. :param str...
4e92a76dca0f99ee0f38d5ba922762396da51d91
3,608,972
def runAllTces(tceFile,sector,outfile): """ Run for all TCEs """ df=p.read_csv(tceFile,comment='#') for index,row in df[37:38].iterrows(): clip = runOneDv(sector,row.ticid,row.planetNumber) text,header = outputInfo(clip) #Write out decision with open(ou...
c1474d79041b904d36fc4a4c2e2b3c90258a00fc
3,608,973
def data_for_keys(data_dict, data_keys): """ Return a dict with data for requested keys, or empty strings if missing. """ return {x: data_dict[x] if x in data_dict else '' for x in data_keys}
b844ae2dba804e179e7e8dd08166f392a90e7f7a
3,608,974
def new_uniformly_random_array_list(low, high, shapes): """ This function returns a list whose kth entry is an array with shape= shapes[k] and with entries selected uniformly at random from the interval [low, high]. Parameters ---------- low : float high : float shapes : list[tuples...
5e4d1a9d2ed1a5e367ef14a6b6941a5429bd6edf
3,608,975
def distinct_values_bt(bin_tree): """Find distinct values in a binary tree.""" distinct = {} result = [] def _walk(node=None): if node is None: return if node.left is not None: _walk(node.left) if distinct.get(node.val): distinct[node.val] =...
8d84d57559a0c813e7ac12199680172a9b591be9
3,608,976
import subprocess def runshell(cmd): """ Run a shell command. if fails, raise an exception. """ p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if p.returncode != 0: err = "Subprocess: \"{0}\" failed, std err = {1}".format(str(cmd), str(p.stderr)) raise RuntimeError...
d5a617cec03fe70d601f496f9f62b6c30fcdbd1e
3,608,977
def create_filename_template(request): """creates a new FilenameTemplate """ logged_in_user = get_logged_in_user(request) # get parameters name = request.params.get('name') target_entity_type = request.params.get('target_entity_type') path = request.params.get('path') filename = request...
5cdf50e32ce3b26c86735c8e93aafea880f6ab91
3,608,978
def custom_slugify(data, suffix=True, offset=15): """ Using django util methods create a slug. Append a random string at the end of the slug if necessary for making it unique """ # slugify the source_field passed to the function new_slug = slugify(data)[:offset] if suffix: # get a ...
f4119e3fd6c3e2089376a93cc8dc360983b428f6
3,608,979
def filter_output(filter_callbacks, kwargs, obj, missing_ok=False): """Filter ouput. For each key in filter_callbacks, if it exists in kwargs, kwargs[key] tells what we need to filter. If the call of filter_callbacks[key] returns False, it tells the obj should be filtered out of output. """ ...
cd9f6b1b68b0155a8f00986ae4619ffd4119dabf
3,608,980
def fix_iobtag(iob, DESC_DECISION): """ This is specific to the BBN Corpus; the reason some of the entity labels are being modified: 1) Errors in the original labeling, or 2) Not enough labels of the given category The parameter DESC_DECISION can be 'keep', 'merge' or 'remove', which determine...
2743e7d36c7d8153a7cf6694a69e9a212219ae8f
3,608,981
from typing import List def get_answered_questions(question_list: List[List[bytes]]) -> list: """Dont let the type hint confuse you, problem of not using classes. It takes the result of get_question_list(file_list) Returns a list of questions that are answered. """ t = [] for q in quest...
d485b374721f445ab62853eaa67de65bd2a893e2
3,608,982
import gettext def profile_update(): """ 用户信息更新 :return: """ gender = request.argget.all('gender', 'secret') birthday = request.argget.all('birthday') homepage = request.argget.all('homepage') address = json_to_pyseq(request.argget.all('address', {})) info = request.argget.all('inf...
e7fa3fe06c2fd7f76cf4f39f71001af3630dc308
3,608,983
def keywords_volume_query_id(request, keywd, query_id, format=None): """ Retrieve related queries """ ip_address = request.META['REMOTE_ADDR'] if valid_ip(ip_address) is False: return Response("Not authorised client IP", status=status.HTTP_401_UNAUTHORIZED) print "in view:" + str(keywd...
e94514c5cf58ff31c22205ad4c96f5caeb943212
3,608,984
def drafts(request): """ The function is used to get all the files created by user(employee). It gets all files created by user by filtering file(table) object by user i.e, uploader. It displays user and file details of a file(table) of filetracking(model) in the template of 'Saved f...
d9993ba1c69c5abfc52e14096759bad0a51868b4
3,608,985
from typing import Union def _data_period(index) -> Union[pd.Timedelta, Number]: """Return data index period as pd.Timedelta""" values = pd.Series(index[-100:]) return values.diff().dropna().median()
87d00003072dd364efee89c3f1b6d4a3843211b0
3,608,986
def chain_callbacks(f): """Decorate to mimic the promise pattern via an yield expression. Decorator function to make a wrapper which executes functions yielded by the given generator in order. """ @wraps(f) def wrapper(*args, **kwargs): chain = f(*args, **kwargs) try: ...
616914636a806c5e92ffbc5b79b3b97f20d03490
3,608,987
import json def well_known_did (mode) : """ did:web https://w3c-ccg.github.io/did-method-web/ https://identity.foundation/.well-known/resources/did-configuration/#LinkedDomains """ address = mode.owner_talao # secp256k pvk = privatekey.get_key(address, 'private_key', mode) key = helpe...
15610de05d529b4721790c8e2dd89c93cb64d8ce
3,608,988
def generate_blobimage(shape, blobs): """function to generate blob images from an image shape and blob coordinates and sigmas :param shape:shape of image to generate :param blobs: array with blob coordinates and sigma in last column""" img = np.zeros(shape, dtype=np.float) if blobs is None: ...
2e046e53163058dbda3cb2df490cbe1ef1a7433e
3,608,989
def _update_or_delete(host, ipaddr, secure=False, logger=None, _delete=False): """ common code shared by the 2 update/delete views :param host: host object :param ipaddr: ip addr (v4 or v6) :param secure: True if we use TLS/https :param logger: a logger object :param _delete: True for delet...
1011c455d0d3ca6e484a29e9b9147333f687ff76
3,608,990
def split_data_list(list_data, num_split): """ list_data: list of data items returning: list with num_split elements, each as a list of data items """ num_data_all = len(list_data) num_per_worker = num_data_all // num_split print("num_data_all: %d" % num_data_all...
7282d1ae89f830d5b48fa73ea3d355cd63344f5c
3,608,991
import re def _find_breakpoint(line, break_pattern=', ', nmax=80): """ determine where to break the line """ line = _remove_comment(line) locs = [m.start() for m in re.finditer(break_pattern, line)] if len(locs) > 0: break_loc = locs[np.where( np.asarray(locs) < (nmax - len(break_p...
553dfe3a088fb16b5abb52ace1078b18917904ae
3,608,992
import argparse def get_input_args(): """ Retrieves and parses the command line arguments created and defined using the argparse module. This function returns these arguments as an ArgumentParser object. 3 command line arguments are created: dir - Path to the pet image files(default- 'pet_...
7ab44bbbd2163c96eb337beff4fd2eb5e2a0ffba
3,608,993
def patch_set_approved(patch_set): """Return True if the patchset has been approved. :param dict patch_set: De-serialized dict of a gerrit change :return: True if one of the patchset reviews approved it. :rtype: bool """ approvals = patch_set.get('approvals', []) for review in approvals: ...
af7e56be45e537be9308f0031fe3923425afd48c
3,608,994
def _load_one_df(date): """Helper function for load_merged_summary in multiproc pool.""" # print(f'({date}) ', end='', flush=True) print('.', end='', flush=True) return load_casus_summary(date).reset_index()
8ad388d312359a6e77439d90d1189d5a47f424cd
3,608,995
import torch def mean_tour_len_edges(x_edges_values, y_pred_edges): """ Computes mean tour length for given batch prediction as edge adjacency matrices (for PyTorch tensors). Args: x_edges_values: Edge values (distance) matrix (batch_size, num_nodes, num_nodes) y_pred_edges: Edge predicti...
dc15b22fb6625ef7c8fcf4e518a617dd0a109c55
3,608,996
import os def get_files_with_ext(path, str_ext, flag_walk=False): """ get files with filename ending with str_ext, in directory: path """ list_all = [] if flag_walk: # 列出目录下,以及各级子目录下,所有目录和文件 for (root, dirs, files) in os.walk(path): for filename in files: ...
1a8ade0b5efead0b6260430145e601d98f6fa057
3,608,997
import requests import time import re def nrel_bcl_api_request(data): """Send a request to the Building Component Library API via HTTP GET and return the JSON response. Args: data (dict or OrderedDict): key-value pairs of parameters to post to the API Returns: dict: the j...
e0a32ce733f97dda0302a14b160af2eefb5f565d
3,608,998
import shutil def install( kernel_spec_manager=None, user=False, kernel_name=KERNEL_NAME, display_name=None, prefix=None, ): """Install the Picky kernelspec for Jupyter Parameters ---------- kernel_spec_manager: KernelSpecManager [optional] A KernelSpecManager to ...
7360f8b23f4b2ee8b005b3e3bb6e5de1fd88fb9d
3,608,999