content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def score_by_label (y_test, y_predict): """ calculate score of prediction by label type: bas, reasonable and good Parameters ---------- y_test : pd.Series y value to predict y_predict : list y value predicted return ---------- score_list : list score li...
d904fe67c15ea1f18b009bb21f2f9a791a00d23b
44,900
import importlib import unittest def skipUnlessImported(module, obj): """如果对象不在导入的模块中,跳过被装饰的测试 . @skipUnlessImported('airflow.operators.mysql_operator', 'MySqlOperator') @skipUnlessImported('xTool.utils.tests', 'skipUnlessImported') """ try: m = importlib.import_module(module) except I...
84b1fbf970f3fb538a4c7efbf1ae43db0bf67cd7
44,901
def get_owned_assets(addresses): """Gets a list of owned assets for one or more addresses""" result = config.mongo_db.tracked_assets.find({ 'owner': {"$in": addresses} }, {"_id": 0}).sort("asset", pymongo.ASCENDING) return list(result)
0a541bd67477b8a8f3ed8cfca51ff31b8845705e
44,902
def rgb2hed(rgb): """RGB to Haematoxylin-Eosin-DAB (HED) color space conversion. Parameters ---------- rgb : array_like The image in RGB format, in a 3-D array of shape ``(.., .., 3)``. Returns ------- out : ndarray The image in HED format, in a 3-D array of shape ``(.., .....
a0477444901ebc2f5b7b524aa048de28d8cacfa6
44,903
def get_role_type_and_id(role, role_id=''): """ Return both type and ID of a role. Args: role (obj): string or role instance. role_id (str): string ID or None. Returns: tuple: type and ID of role. """ if isinstance(role, str): return role, role_id return get...
805022ead2de77828b7e3e6636278f6d8685ed44
44,904
def is_user_context(context): """Indicate if the request context is a normal user.""" if not context: return False if context.is_admin: return False if not context.user or not context.project: return False return True
48565db931a7ccc25608d86b8e075b2a39af62fd
44,905
async def get_genomes_dict(): """ **Private endpoint**, which returns the entire 'genomes' part of the config """ _LOGGER.info(f"serving genomes dict: '{rgc[CFG_GENOMES_KEY]}'") return rgc[CFG_GENOMES_KEY]
8f181d14f57ab37da22503df6ea640f5d25e05f7
44,906
def type_description(name, types): """ Returns a dictionary description the given type. See `types.yml` for more information about keys and values there. """ return types[dereference_type(name)]
411875bc2f00c5dcd0765afac27c41ec325a021c
44,907
from typing import Union from typing import Sequence from typing import Optional from typing import Mapping def rank_features_groups_heatmap( adata: AnnData, groups: Union[str, Sequence[str]] = None, n_features: Optional[int] = None, groupby: Optional[str] = None, feature_symbols: Optional[str] = ...
dc08f608fe8c3cc898432e40c8a9989f374e80bf
44,908
def median_ci(pop, n, ci=0.95): """ Estimate the approximate ci 95% error margins for the median using a rule of thumb based on Hollander and Wolfe (1999). Parameters ---------- pop : numpy array a sorted dataset n : scalar, positive int the sample size ci : float, scalar ...
49461ecffb9b31c10ab9d2647d8e4325ce6df8c4
44,909
def find_source(function_key, data, functions): """ Finds the source of the 'function_key' in 'data' or in 'functions', and returns it """ # To fund sources in regular triples maps for tm in data['TriplesMap']: if len(data['TriplesMap'][tm]['Predicate_Object']['Function']) != 0: ...
f24e09f325e716dcfaea9488902ece0e12f0fa00
44,910
def _interpret_emr_bootstrap_stderr(fs, matches, partial=True): """Extract errors from bootstrap stderr. If *partial* is true, stop when we find the first match. (In practice, we usually target a single file anyway.) """ result = {} for match in matches: stderr_path = match['path'] ...
d03c7636e1c03c786d413c8de7c7c429f3329541
44,911
from typing import Any def wrap_strictly(value: Any, type_: type) -> StrictSmartWrapper: """Less-code style version of StrictSmartWrapper constructor call.""" return StrictSmartWrapper(value, type_)
11908716fd101e5d22411f6de94cb0c9fa578bef
44,912
def check_slurm_queue_id(job_id): """Returns true if the job whose id is job_id is in the slurm queue. Args: job_id (int): The ID of the job. Returns: A boolean indicating whether or not the slurm job is running. """ try: return string_in_output("squeue", str(int(job_id))) ...
56526b6724f6b93f965f67d4dd0cca97907f6b1c
44,913
def make_undirected(mat): """ Takes an input adjacency matrix and makes it undirected (symmetric). Parameter ---------- mat: array Square adjacency matrix. """ if not (mat.shape[0] == mat.shape[1]): raise ValueError('Adjacency matrix must be square.') sym = (mat + mat.t...
e2b1eea14822c84a13e632a8532263bf465ed4cd
44,914
def inc(n): """Increment an integer.""" return -~n
694ba6320b842985f87a36e452eb0f30e39442b4
44,915
import copy def task_update(context, task_id, values): """Update a task object""" global DATA task_values = copy.deepcopy(values) task_info_values = _pop_task_info_values(task_values) try: task = DATA['tasks'][task_id] except KeyError: LOG.debug("No task found with ID %s", task...
861ca08dd7ef80a50649300677296c605f862b8b
44,916
def get_neighbor_in_filter(neigh_ip_address): """Returns a neighbor in_filter for given ip address if exists.""" core = CORE_MANAGER.get_core_service() peer = core.peer_manager.get_by_addr(neigh_ip_address) return peer.in_filters
b66cc494a9bc6a2071fa3aca57f974db8e93ae01
44,917
def Vowel_or_Consonant(char = ''): """ A boolean function, which return either True or False """ # Determine whether each letter in the text is a vowel or a # consonant. if it is a vowel, set test to True, otherwise, set test to false. for i in char: if str(i)in 'aeiouy': te...
7b4d07a90b858983bd6f92d61b97592fcb748608
44,918
def make_coord_dict(coord): """helper function to make a dict from a coordinate for logging""" return dict( z=int_if_exact(coord.zoom), x=int_if_exact(coord.column), y=int_if_exact(coord.row), )
ace7086884296f076354f4b652393a3ed85bc3b5
44,919
def validate_signature_fragments(fragments, hash_, public_key): # type: (Sequence[TryteString], Hash, TryteString) -> bool """ Returns whether a sequence of signature fragments is valid. :param fragments: Sequence of signature fragments (usually :py:class:`cornode.transaction.Fragment` instances). :...
b898e26acf90ce28e78e8c0f9587114394dba5de
44,920
def ImageRotate(image, angle, scale): """ :param image: :param angle: :param scale: :return: """ H, W, C = image.shape center = (H / 2, H / 2) # H: rows # 获得旋转矩阵 M = cv2.getRotationMatrix2D(center, angle, scale) # 进行仿射变换,边界填充为255,, borderValue=(255, 255, 255) image_ro...
faee6df2b35606cb2f94870897ed1db143ecbc41
44,921
def deserialize(name, custom_objects=None): """Returns a policy function or class denoted by input string. Arguments: name : String Returns: Policy function or class denoted by input string. For example: >>> softlearning.policies.get({ ... 'class_name': 'ContinuousUniformP...
8f4a74485be608acad711f0631bb610605bf5e21
44,922
def do_stuff4(): """ This is right """ first, second = 1, 2 return first + second
b0f762b37e43330358d24a2fecd9282dd77f35da
44,923
def sqrt(argument: _Union[_Real, Expression]) -> Expression: """ Returns square root of the argument: exact if it is a perfect square, symbolic instead. >>> sqrt(0) == 0 True >>> sqrt(1) == 1 True >>> square_root_of_two = sqrt(2) >>> square_root_of_two ** 2 == 2 True >>>...
fa066df35022fd63f62da4aa1c160d5c0b71c582
44,924
def windowedAverage(window, step, sample): """ Input is a sample, with a list of CHROM, POS, mel, sim, sec Output is a list of CHROM, POS, mel, sim, sec, but a window average around that point """ entryDict = {} ## best to get this in a dict, since things are going to get looked up several times ...
fc93abdf9392f2183767de105ef1ff00e5f039a2
44,925
def post_bundle(name, action): # noqa: E501 """post_bundle # noqa: E501 :param name: :type name: str :param action: :type action: str :rtype: None """ return 'do some magic!'
239ec47c8380b3e04e614508d3bdf96c6b757a4f
44,926
from operator import eq def non_obs_walko(relation, a, b): """Construct a goal that applies a relation to all nodes above an observed random variable. This is useful if you don't want to apply relations to an observed random variable, but you do want to apply them to every term above one and ultimate...
a849710c340057789d7e56397ecc9b9f939479cb
44,927
def get_project_config_file_name(): """ :returns: config file basename """ return SteveConfig.file_name
e402f23f9bd864ba5cf7949e556d28b363981a4c
44,928
from typing import Union def is_close(a: Union[util.number, list], b: Union[util.number, list], rel_tol=1e-8, abs_tol=1e-8) -> bool: """Checks if the specified numbers are close enough to be considered equal. Due to the usage of IEEE754 floating points number in Python, formulae like 0.1+0.2 can lead to ...
c7a3528be61617b74901155fd9dd64c6eb2e57f1
44,929
def epw_header(epw): """ Given an EPW, get the header """ with open(epw, "r") as f: header = f.readline().strip().split(",") return { "city": header[1], "state": header[2], "country": header[3], "source": header[4], "WMO": header[5], "lat": f...
257640179a3659c7dc142b79c6fa8a9a5f55ea39
44,930
from typing import Dict from typing import Any def prepare_single_asset_payload(args: Dict[str, Any], operation: str) -> Dict[str, Any]: """ Prepare payload for post data in case user wants to add or update single asset. Throws error if valid values are not provided in arguments. :param args: args pa...
52938294645de04e546bcd0bc47b9b9e4fff144c
44,931
def repeat(s: str, n: int) -> str: """ Return s repeated n times; if n is negative, return the empty string. >>> repeat('yes', 4) 'yesyesyesyes' >>> repeat('no', 0) '' >>> repeat('no', -2) '' >>> repeat('yesnomaybe', 3) 'yesnomaybeyesnomaybeyesnomaybe' """ return s * n
67c31e1d824442c5cc388f190e6dd222f1b2cf83
44,932
def rearange_books_by_category(books_json): """rearange_books_by_category. Returns JSON with following structure: { "Beginner":[ { "title": "author": "url" } ], "Intermediate":[ { "title": "auth...
95c85e1c948e0e2daaf90915544bb7f3bd96b633
44,933
import math def GetTileMatrix(layout, tile_size, values, viewport): """For the given tile layout and per-tile bench values, returns a matrix of bench values with tiles outside the given viewport set to 0. layout, tile_size and viewport are given in string of format <w>x<h>, where <w> is viewport width or num...
9abd5077fef10da86177b938c3219e006ee1cc44
44,934
def reverse(view_name, lang=None, use_lang_prefix=True, *args, **kwargs): """ Similar to django.core.urlresolvers.reverse except for the extra parameter: @param lang: anguage code in which the url is to be translated (ignored if use_lang_prefix is False). @param use_lang_prefix: Is changed to False, get an url wit...
58cae5a47f7fed63acd80addcadc9c6b782fdff7
44,935
import os import time from datetime import datetime def train(): """Training model.""" logger.info("Loading data...") logger.info("Training data processing...") train_students = np.load("data/train" + number + ".npy", allow_pickle=True) logger.info("Validation data processing...") test_...
a190184ae7c71f939fe5957d08175ee67cbae2e2
44,936
import numpy def cal_pop_fitness(target_chrom, pop): """ This method calculates the fitness of all solutions in the population. """ qualities = numpy.zeros(pop.shape[0]) for indv_num in range(pop.shape[0]): # Calling fitness_fun(...) to get the fitness of the current solution. qual...
2c524322afe9fdd11b70c22ca80cb213288a0941
44,937
def upload_folder(directory, project_id=None, subject_id=None, session_id=None, scan_id=None, assessor_id=None, resource=None, remove=False, removeall=False, extract=True): """ Upload a folder to some URI in XNAT based on the inputs :param directory: Full path to directo...
9ecead99dd395c8e91040c1b8ee40034ebc1b3b0
44,938
def get_ldap_vpn_schema_settings(api_client, **kwargs): # noqa: E501 """Get LDAP VPN schema settings # noqa: E501 Get LDAP VPN schema settings # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> response = aw...
883442ee8b936e7d26fcc3a8ece144d5e451fcc3
44,939
def aes_encrypt(AES_KEY, AES_IV, data): """ aes_key: 密钥 aes_iv: iv 提交表单加密 """ aes_key = bytes(AES_KEY, 'utf-8') aes_iv = bytes(AES_IV, 'utf-8') data = bytes(data, 'utf-8') data = aes_pkcs7padding(data) cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) encrypted = b64encode(ciph...
135866c4261ad77580a0dc171362da0abf82ec52
44,940
import os def dap_control(tool, reg_map, cpu_id, desired_state, jwt_not_required, filename): """ Calls DAPControl SysCall over IPC :param tool: Programming/debugging tool :param reg_map: Device register map :param cpu_id: CPU ID (0-CM0, 1-CM4, 2-SYS) :param desired_state: The s...
e1688ce6343c00e67c2e0ccb6dcf91198b40eb8e
44,941
def _rating_weighted_avg_jk_std(iur, item, sims, use): # JACKKNIFE ESTIMATE OF STANDARD DEVIATION FOR WEIGHTED-AVERAGE """ Sum aggregate Args: iur(matrix._CSR): the item-user ratings matrix item(int): the item index in ``iur`` sims(numpy.ndarray): the similarities for the users who ...
905bdb574cd5854dc7aa69ccc0ca982318d82894
44,942
def dummy_null_python(): """ Equatorial Reverse & Capture """ q0 = [2.5, np.pi / 2, 0.] p0 = [0., 0., -8.5] a = 0.9 end_lambda = 10. step_size = 0.005 julia = False return q0, p0, a, end_lambda, step_size, julia
382803d40bd694a0fc0b21d5e3064748cc900059
44,943
import logging def generate_graph(generate_configuration) -> pgv.AGraph: """ Walk a NiFi flow and produce an AGraph. Configuration options will be used to control the depth of the process group recursion, load templates to overload subgraph settings, and set properties on processors If the generat...
0df6867472b31201202f56541436b3883a9303ec
44,944
def set_or_callable(value): """Convert single str or None to a set. Pass through callables and sets.""" if value is None: return frozenset() if callable(value): return value if isinstance(value, (frozenset, set, list)): return frozenset(value) return frozenset([str(value)])
d7ef01016ea0ac679cdf13e78432f5a99d991522
44,945
from typing import Sequence def _isotonic_partial_errors(sequence: Sequence[float], weights: Sequence[float]) -> np.ndarray: """Finds the partial errors of isotonic regression over subsequences. O(n). Pool adjacent violators, but we track the squared error at each step. This is equ...
b31a262b623201ab2b5d3989a1617d7108487a47
44,946
def solve_sqrt_lasso_skinny(X, Y, weights=None, initial=None, **solve_kwargs): """ Solve the square-root LASSO optimization problem: $$ \text{minimize}_{\beta} \|y-X\beta\|_2 + D |\beta|, $$ where $D$ is the diagonal matrix with weights on its diagonal. Parameters ---------- y : ...
5cd7700a8b9ecb192a5fbe39cb3b258d2aa2071f
44,947
from typing import List def generate_courtyard( uuid: str, max_x: float, max_y: float, excess_x: float, excess_y: float, ) -> List[str]: """ Generate a rectangular courtyard polygon. Args: uuid: The polygon UUID max_x: The half width (x) of the ...
85e00a45b3dacdcf08062a5605480807ea6a429b
44,948
import json def loginView(request): """Verifies login information and then authenticates user into Django system.""" data = json.loads(request.body) username = data.get('username') password = data.get('password') if username is None or password is None: return JsonResponse({"Info": "User...
52123f9bfe1cc25d7d0d7dad4ca8f9bd71f21c7e
44,949
def add_id(pos_list, image_id=0): """ Add id for gather feature, for inference. """ new_list = [] for item in pos_list: new_list.append((image_id, item[0], item[1])) return new_list
47cfdb55392eac141a796f74c539c4b12a39cdb9
44,950
def det_solve_3(m, b): """Решение системы c 3 неизвестными по методу Крамера""" m = np.array(m) det_1 = det(np.column_stack([b, m[:, 1], m[:, 2]])) det_2 = det(np.column_stack([m[:, 0], b, m[:, 2]])) det_3 = det(np.column_stack([m[:, 0], m[:, 1], b])) return (det_1 / det(m), det_2 / det...
428e0982c620640f46bd678e1bbd912f7b55b1a5
44,951
def render_inner_single(items): """render_inner callback for --is-primary""" items = list(items) if len(items) != 1: raise BadInputError("--is-primary specified but specified key matches " "more than one record: %r" % items) return items[0]
d7117ea5f458ce40050ed1493633191248c33f36
44,952
def legendre_poly(n, x=None, **args): """Generates Legendre polynomial of degree `n` in `x`.""" if n < 0: raise ValueError("can't generate Legendre polynomial of degree %s" % n) poly = dup_legendre(int(n), QQ) if x is not None: poly = Poly(poly, x, domain=QQ) else: poly = P...
04359d39e31363f2f0c15398307fa1fd8b706b87
44,953
def read_sig(path, n_channels, header=None, sep='\t', rem_len=5): """ Read signal in tabular format (csv, tsv) :param path: path of the tabular data file :param n_channels: number of channels to be handled. Extra channels will be ignored :param sep: tabular data separator. Default `tab` :param r...
e714d0e8750ce57ad72e8e2ccee22528f833da1b
44,954
def find_max_sentence_length(sequences: list) -> int: """ returns the longest sequence, which will be used as the maximum sequence. :param sequences : list[list[int]] :return int """ max_length = None for seq in sequences: if max_length is None or len(seq) > max_length: m...
c537e645271b5576ad7dcab2aeb7f79cb69ceff9
44,955
def _load_missing_region_edges(regions): """Fill in the missing Has_Parent_Region edges.""" # Existing regions whose parent region is Westeros. westeros_children = [ 'Beyond the Wall', 'The North', 'Iron Islands', 'The Riverlands', 'The Vale of Arryn', 'The We...
76949e203cee5d87c115d9cf8ab1e56bb33b6659
44,956
def is_empty_tensor(t): """Returns whether t is an empty tensor.""" return len(t.size()) == 0
f0caf9a7b21c77a01dc088314f2d8fbbe49cf1f3
44,957
def admin_ide_list(): """ List all active ide sessions :return: """ # Get all active sessions sessions = TheiaSession.query.filter( TheiaSession.active == True, TheiaSession.course_id == course_context.id, ).all() # Hand back response return success_response({"sess...
46f5a391bee2a3a4165322461c1f5baf88770163
44,958
import os import sys import shlex import subprocess import numpy as np from qatoolspython.createScreenshots import createScreenshots def evaluateHypothalamicSegmentation(SUBJECT, SUBJECTS_DIR, OUTPUT_DIR, CREATE_SCREENSHOT = True, SCREENSHOTS_OUTFILE = []): """ A function to evaluate potential missegmentation...
912ab90f5e4ffd4936bf1580947c2d9caa3d4650
44,959
def construct_sampling_ops(model): """Builds a graph fragment for sampling over a TransformerModel. Args: model: a TransformerModel. Returns: A tuple (ids, scores), where ids is a Tensor with shape (batch_size, max_seq_len) containing one sampled translation for each input sentence...
264d557c14c954b358e2a4635b1c4defa632001f
44,960
from typing import Optional from datetime import datetime def format(datatype: str, value: Optional[Value], default: Optional[str] = None) -> str: """ Format a column *value* based on its *field*. If *value* is `None` then *default* is returned if it is given (i.e., not `None`)....
828311e58750b389beadfc228cef590528144120
44,961
import numpy def sinusoid( frequency, sampling_frequency=16000, duration=0.025 ): """Generate a sinusoid signal. Args: frequency (int): the frequency of the sinusoidal signal. sampling_frequency (int, optional): sampling frequency in Hz. Defaults to 16000. duration (flo...
b8c71c285b1e9f43806d7eb41d2e91278362b7d5
44,962
import requests def Delete_Portfolio_Holdings(portfolio_name,timestamp,rev): """ Deletes a portfolio. """ BASEURL = "https://investment-portfolio.mybluemix.net/api/v1/portfolios/" + str(portfolio_name) + "/holdings/" + str(timestamp) + "?rev=" + str(rev) print(BASEURL) headers = { 'Con...
a76ea0c3f1eba90883b7c3e7ab1d683ea76b7d3d
44,963
def get_refs(data: list, num=3): """获取参考音频,和所有同一个说话人的embed余弦相似度最小。""" sim_mat = pairwise_distances(data, metric='cosine') sim_vec = np.mean(sim_mat, axis=0) ids = range(len(sim_vec)) outs = [k for k, v in clt.Counter(dict(zip(ids, 1 - sim_vec))).most_common(num)] # outs = sorted(ids, key=lambda ...
05d6a614de062ada8a575520b4f7c1583a2f2de2
44,964
import logging def add_light_area(xyz=(0, 0, 0), rot_vec_rad=(0, 0, 0), name=None, energy=100, size=0.1): """ Add area light that emits light rays the lambertian way Args: xyz: Location 3-tuple of floats Optional; defaults to (0, 0, 0) rot_vec_rad: Rotation angle i...
279be5febf93dd18daa1bf209c8125ecdf501a45
44,965
def get_last_table_stations(): """ Return date from the last row of stations table :return: date returned from database or None """ connection = psycopg2.connect(dbname='air_data', user='docker', password='docker', host='dbserver') cursor = connection.cursor() expression = f"SELECT date FROM...
a33ea279a10a3ea4eb3e118d976119b7b3b5fbe2
44,966
def average_trial(trial, isotropic=False): """Take average of thermal conductivities for multiple runs. Assumes all runs have the same number of directions. Args: - isotropic (bool): Isotropy of thermal flux, if True aveage is taken for each direction Returns: - dict: Trial data averag...
0aaeab14533c339aa791cf702113e66c1e41fee2
44,967
def is_approved(given_user): """ Helper template function to check if a user is approved. given_user: The User object that we are checking to see if they are approved or not. """ # try getting the RegisteredUser of the current user try: get_registered_user = RegisteredUser.objects....
0358015c7c4c392755f790b54e4face5f6bac309
44,968
from typing import Callable def all_exception_handler(handler_input: HandlerInput, exception: Exception) -> Response: """Catch all exception handler, log exception and respond with custom message. """ _logger.error(exception, exc_info=True) _: Callable = handler_input.attributes_manager.request_at...
33dc46d0f6381cfa14f028988d84812e07f64ed8
44,969
from typing import Callable from typing import Optional from typing import Iterable from typing import Tuple from typing import Sequence from typing import List def rna_cofold_strand_pairs_constraint( threshold: float, temperature: float = dv.default_temperature, weight: float = 1.0, s...
0b6d98a18ab39b03b92d3b36d41b435b023e53fa
44,970
import builtins import this def round(x): """Rounds the given number to a globally constant precision.""" return builtins.round(x, this._precision_digits)
17d20da912fd4547742e4292bc5dd0125aee1391
44,971
import requests def activate_svc(svc): """ Activates a service. """ resp = requests.post( svc['links']['self'], auth=AUTH, params=dict(action='activate') ) resp.raise_for_status() return resp.json()
b2269718613cbe22a4a47572589b4c55231b8183
44,972
def isNotTrue (b) : """return True if b is not equal to True, return False otherwise >>> isNotTrue(True) False >>> isNotTrue(False) True >>> isNotTrue("hello world") True """ # take care: not(X or Y) is (not X) and (not Y) if b is not True and b != True : # base case: b ...
91b7aa18d6e60f13f31e3826d520f5c4083ca089
44,973
def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 35x35 resnet block.""" with tf.variable_scope(scope, 'Block35', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1') with tf.varia...
5303bce6730a1012d11615abd8825f58ec8bb8b5
44,974
def search(variable: str, target: str) -> str: """Search serice using mwapi on wikidata Args: variable (str): variable name (?film, ?director...) target (str): value to search for Returns: str: service query """ if variable is None or target is None: return "" ...
3959a6c7d93e5f61f237a019ae941702df35eb31
44,975
def collect_name(etok,s): """ Make a list of all subtokens with name s. >>> collect_name(pstream(r.tdop_rel_prop(),'x,y,z PRIM_BINARY_RELATION_OP u PRIM_BINARY_RELATION_OP x'),'VAR') [Etok(VAR,x,'x'), Etok(VAR,u,'u'), Etok(VAR,y,'y'), Etok(VAR,u,'u'), Etok(VAR,z,'z'), Etok(VAR,u,'u'), Etok(VAR,u,'u'), E...
f0edd5eb737f439fbd92349507b6eff117dfd598
44,976
def indexresample(adjacency, distance=[], samples=[], percentage=[]): """ Bootstrap method to resample neighborhood indices. For a given adjacency list, sample indices that are at most a distance=k units away from a vertex. Parameters: - - - - - adjacency: surface adjacency list ...
f90bf19728ac25ca8b5563c13f2494d0d4d61c48
44,977
def scrub_df(df: DataFrame) -> DataFrame: """Prepare DataFrame for loading into Sqlite db """ df.loc[:, 'timestamp_created'] = pd.to_datetime(df['timestamp_created'], unit='s') df.loc[:, 'is_OC'] = df['is_OC'].astype(int) for col in df.select_dtypes(include=np.number).columns: df.loc[:, col...
d5dfd85a5a5b265d7e9c0fb57743a771e4a8b59e
44,978
def dameraulevenshtein(seq1, seq2): """Calculate the Damerau-Levenshtein distance between sequences. This distance is the number of additions, deletions, substitutions, and transpositions needed to transform the first sequence into the second. Although generally used with strings, any sequences of ...
d51f69ce30ec7104020cb8fd9572acc11f690298
44,979
import json def to_json(value): """ Serialize a value as an HTML-safe JSON string. The resulting value can be safely used inside a <script> tag in an HTML document. See http://benalpert.com/2012/08/03/preventing-xss-json.html for an explanation of why JSON needs to be escaped when embedding ...
d9955aa9f231ed9d8af2b26fb25a1d31783de949
44,980
def postprocess_question(text): """postprocess the output of question generation model for fair readable. output. Args: text (text): generated question to be processed. Returns: str: clean readable text. """ output = text.replace("question: ", "") output = output.strip()...
292a0aa92cc86e411b5700352028e3d5858b3511
44,981
import math def get_point_at_line_in_distance(p1, p2, distance): """ Get the coordinates of a point lying on the line p1 - p2 with distance to point p1. """ linelength = math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2) x = (distance / linelength) * (p2.x - p1.x) + p1.x y = (distance / li...
ea7c6c196443f783ad914baa55d0d716eb27d112
44,982
import time import requests import json import math import tqdm def macro_cons_gold_change(): """ 全球最大黄金 ETF—SPDR Gold Trust 持仓报告, 数据区间从 20041118-至今 :return: pandas.Series """ t = time.time() res = requests.get( JS_CONS_GOLD_ETF_URL.format( str(int(round(t * 1000))), str(in...
05684b5ae9d130783d1323af3a91a83f34947920
44,983
def selection(population, n_best): """ """ return sorted(population, key=fmgls, reverse=False)[:n_best]
fbc0dc2874401cd935d347c4b42edd62c6c7c206
44,984
from typing import List def unique_filter(posts: List[Post], _: ImgurConfig): """Filter out published posts.""" ids_list = [p.imgur_id for p in posts] ids_in_db = set(Post.objects.filter(imgur_id__in=ids_list).values_list('imgur_id', flat=True)) return [ post for post in posts if post....
ba543b1f05d4f11567386e28bfcd4b22ddf036ee
44,985
def clip_probs(original_probs): """ Makes sure probabilities are in certain range. Rescale sum probabilities to 1. """ min_p = 1e-5 max_p = 1 - min_p clipped_probs = np.clip(original_probs, min_p, max_p) clipped_probs = clipped_probs / np.sum(clipped_probs) return clipped_probs
110b7e5546ee83e73ad5186db5faba055507f1fd
44,986
from typing import Tuple import os def parse_xml(file_path: str) -> Tuple[Article, ArticleComponentCheck]: """ Parse xml files Parameters ---------- file_path: File name Returns ------- article: Article, component check: ArticleComponentCheck """ file_path = os.path.normpath(...
c2ed5aa551db069f67bf3e552d49c055f6933871
44,987
def get_block_offset(default, vis, res): """Returns offset for selected visualization (vis). """ if vis.lower() == "hillshade": return 1 elif vis.lower() == "shadow": return 1 elif vis.lower() == "slope gradient": return 1 elif vis.lower() == "multiple directions hillshade": ...
4e186ef14a7ce8f4394ed6532983efbdd74e7b0c
44,988
def bbox_from_fast_rcnn(anchor, fast_rcnn): """ Convert Fast-R-CNN-like representation relative to `anchor` to a `bbox`.""" anchor_height = anchor[...,SVHN.BOTTOM] - anchor[...,SVHN.TOP] anchor_width = anchor[...,SVHN.RIGHT] - anchor[...,SVHN.LEFT] anchor_y_center = 0.5 * (anchor_height) + anchor[...,SV...
2302f7362923e0a30cc9da4938f726d258617175
44,989
def directional_variance(X, w): """向量集 X 在非零向量 w 方向上的方差""" return sum(directional_variance_i(x_i, w) for x_i in X)
c8d8d8e52d4f35f03400f95bb377cbf8cfe24fba
44,990
import shlex import logging import subprocess def run_command(command, capture_output=True, log_error=True, env=None, timeout=None): """Execute shell command.""" if isinstance(command, str): command = shlex.split(command) logging.info("Executing command: " + " ".join(command)) try: res...
fced776245b1dd0f949028680276f8c01ecc57fc
44,991
def get_job_data(job, average, qubit_idx, scale_factor): """ Retrieve data from a job that has already run. """ job_results = job.result(timeout=120) # Timeout after 120 s result_data = [] for i in range(len(job_results.results)): if average: # Get avg data result_data.appe...
748871f547d15911c889d72e6969caedc773e18f
44,992
import os from typing import Container import json async def performDrop(cls:"PhaazeDatabase", DBDropRequest:DropRequest) -> Response: """ Used to drop/delete container from DB (automaticly deletes supercontainer if necessary) """ container_location = f"{cls.container_root}{DBDropRequest.container}.phaazedb" #do...
fe741590ba9c944e4dc67a4014b695ab15335b18
44,993
def chebyshev(a, b): """Chebyshev Distance Arguments: a (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space. b (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space. Returns: The distance between points a and b with L-...
54ecaacd5a1c0d8acc72dd4c56663a4a6a10a7f0
44,994
import warnings def convert_units(ds): """convert units for use in the preprocessor""" try: if ds.sftlf.units == "%": print("converting sftlf units to fractional") attrs = ds.sftlf.attrs ds["sftlf"] = ds.sftlf * 0.01 attrs["units"] = 1 ds.sft...
e8186de20a7a4266b7d1d8b602ed58b5dd79a404
44,995
def new_figure_manager_given_figure(num, figure): """ Create a new figure manager instance for the given figure. """ canvas = FigureCanvasPickle(figure) manager = FigureManagerPickle(canvas, num) return manager
353d68b99afbbe9be4845fa3898eb6bedf26ef78
44,996
def get_rest_kwargs(service): """ REST API 呼び出しキーワード引数を取得する Args: service: Returns: """ return service.execute_rest.call_args[1]
619f7ff0a20b01572d70f94338634e7ed490ad20
44,997
def expand_url(url, protocol): """ Expands the given URL to a full URL by adding the magento soap/wsdl parts :param url: URL to be expanded :param service: 'xmlrpc' or 'soap' """ if protocol == 'soap': ws_part = 'api/?wsdl' elif protocol == 'xmlrpc': ws_part = 'index.php...
9cf96886dc6101c562a7c091ebeb12349ce52219
44,998
def create_dict_searchers(g, v0: list, capture_range=0, zeta=None): """Create searchers (dictionary with id number as keys). Nested: initial position, capture matrices for each vertex""" # set of searchers S = {1,..m} S = ext.get_set_searchers(v0)[0] # create dict searchers = {} for...
7801d33ab2d3fb9e103935f6fd0bda9a5cc92fb7
44,999