content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def if_else(cond, a, b): """Work around Python 2.4 """ if cond: return a else: return b
4b11328dd20fbb1ca663f272ac8feae15a8b26d9
4,200
def _update_machine_metadata(esh_driver, esh_machine, data={}): """ NOTE: This will NOT WORK for TAGS until openstack allows JSONArrays as values for metadata! """ if not hasattr(esh_driver._connection, 'ex_set_image_metadata'): logger.info( "EshDriver %s does not have function '...
2733a809ac8ca7d092001d2ce86a9597ef7c8860
4,201
from datetime import datetime def timedelta_to_time(data: pd.Series) -> pd.Series: """Convert ``datetime.timedelta`` data in a series ``datetime.time`` data. Parameters ---------- data : :class:`~pandas.Series` series with data as :class:`datetime.timedelta` Returns ------- :cla...
d660e7fea7e9e97ae388f3968d776d9d08930beb
4,202
def nms(boxes, scores, iou_thresh, max_output_size): """ Input: boxes: (N,4,2) [x,y] scores: (N) Return: nms_mask: (N) """ box_num = len(boxes) output_size = min(max_output_size, box_num) sorted_indices = sorted(range(len(scores)), key=lambda k: -scores[k]) select...
c6fe28e44d4e4375af39c22edd440e8cdff44917
4,203
def get_db(): """Connect to the application's configured database. The connection is unique for each request and will be reused if this is called again """ if 'db' not in g: g.db = pymysql.connect( host='localhost', port=3306, user='root', password='', database='qm', charset='utf8' ) return...
8a8ce077f98e1e6927c6578e7eff82e183cea829
4,204
def read_stb(library, session): """Reads a status byte of the service request. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :return: Service request status byte. """ status = ViUInt16() library.viReadSTB(session, byref(status)) ...
96d74ae6909371f2349cc875bd5b893d41d550f8
4,205
import os from datetime import datetime def will_expire(certificate, days): """ Returns a dict containing details of a certificate and whether the certificate will expire in the specified number of days. Input can be a PEM string or file path. .. versionadded:: 2016.11.0 certificate: ...
fb97236c2a47d4fee3a363ddc91700176bc0c91b
4,206
def one_particle_quasilocal(sp, chli, chlo, Es=None): """ Calculate the one-particle irreducible T-matrix T(1). Parameters ---------- s : Setup Setup object describing the setup chi : int Input schannel cho : int Output channel Es : ndarray List of partic...
089204f48c9decb3bf58e909ec46e7ffb844ebf1
4,207
import logging def _CreateIssueForFlake(issue_generator, target_flake, create_or_update_bug): """Creates a monorail bug for a single flake. This function is used to create bugs for detected flakes and flake analysis results. Args: create_or_update_bug (bool): True to create or update monorail bug, ...
8f233b91f72bd3f48c67a4c53c6ec6d3c50d52e6
4,208
from typing import List def get_spilled_samples(spills: List, train_dataset: Dataset): """ Returns the actual data that was spilled. Notice that it returns everything that the __getitem__ returns ie. data and labels and potentially other stuff. This is done to be more general, not just work with d...
04414e59ed43b6068188bc3bb0042c4278bd3124
4,209
from typing import List from pathlib import Path import logging def reshard( inputs: List[Path], output: Path, tmp: Path = None, free_original: bool = False, rm_original: bool = False, ) -> Path: """Read the given files and concatenate them to the output file. Can remove original files on...
8c90c2d0e42d4e6d1bbb59d541284450d59f0cd1
4,210
def on_intent(intent_request, session): """ Called when the user specifies an intent for this skill """ print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) intent = intent_request['intent'] intent_name = intent_request['intent']['name'] # Dispatch t...
040c0d80802503768969859a9fe6ccef8c9fdf06
4,211
def load_twitter(path, shuffle=True, rnd=1): """ load text files from twitter data :param path: path of the root directory of the data :param subset: what data will be loaded, train or test or all :param shuffle: :param rnd: random seed value :param vct: vectorizer :return: :raise ValueE...
863f39faef6f4175dc18d076c3c9601d09331523
4,212
def parse_vtables(f): """ Parse a given file f and constructs or extend the vtable function dicts of the module specified in f. :param f: file containing a description of the vtables in a module (*_vtables.txt file) :return: the object representing the module specified in f """ marx_module = Mod...
01786447982c15b55ee1411afe71990a1752dec3
4,213
import datasets def getCifar10Dataset(root, isTrain=True): """Cifar-10 Dataset""" normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) if isTrain: trans = transforms.Compose([ transforms.RandomHorizontalFlip(), tra...
b5c103838e4c46c445e39526b61bb9c8fa3832ee
4,214
import pyclesperanto_prototype as cle def histogram(layer, num_bins : int = 256, minimum = None, maximum = None, use_cle=True): """ This function determines a histogram for a layer and caches it within the metadata of the layer. If the same histogram is requested, it will be taken from the cache. :ret...
65197010bfaec66a58798772e61f4e1640b7ea89
4,215
import re def get_tbl_type(num_tbl, num_cols, len_tr, content_tbl): """ obtain table type based on table features """ count_very_common = len([i for i, x in enumerate(content_tbl) if re.match(r'^very common',x) ]) count_common = len([i for i, x in enumerate(content_tbl) if re.match(r'^common',x) ]) count...
19c06766c932aab4385fa8b7b8cd3c56a2294c65
4,216
def decode_EAN13(codes): """ คืนสตริงของเลขที่ได้จากการถอดรหัสจากสตริง 0/1 ที่เก็บใน codes แบบ EAN-13 ถ้าเกิดกรณีต่อไปนี้ ให้คืนสตริงว่าง (สาเหตุเหล่านี้มักมาจากเครื่องอ่านบาร์โค้ดอ่านรหัส 0 และ 1 มาผิด) codes เก็บจำนวนบิต หรือรูปแบบไม่ตรงข้อกำหนด รหัสบางส่วนแปลงเป็นตัวเลขไม่ได้ เลขหลักที่ 13...
2f65b488c61cbafae0c441d68f01e261141569dd
4,217
def GiveNewT2C(Hc, T2C): """ The main routine, which computes T2C that diagonalized Hc, and is close to the previous T2C transformation, if possible, and it makes the new orbitals Y_i = \sum_m T2C[i,m] Y_{lm} real, if possible. """ ee = linalg.eigh(Hc) Es = ee[0] Us0= ee[1] Us = matrix(e...
d4ba72e57079ab18f7e29b9d1b2ce68f2c112fb4
4,218
import unicodedata def normalize(form, text): """Return the normal form form for the Unicode string unistr. Valid values for form are 'NFC', 'NFKC', 'NFD', and 'NFKD'. """ return unicodedata.normalize(form, text)
6d32604a951bb13ff649fd3e221c2e9b35d4f1a1
4,219
def handle_internal_validation_error(error): """ Error handler to use when a InternalValidationError is raised. Alert message can be modified here as needed. :param error: The error that is handled. :return: an error view """ alert_message = format_alert_message(error.__class__.__name__...
996552cf26b01f5a4fd435a604fe1428669804bd
4,220
def bbox_encode(bboxes, targets): """ :param bboxes: bboxes :param targets: target ground truth boxes :return: deltas """ bw = bboxes[:, 2] - bboxes[:, 0] + 1.0 bh = bboxes[:, 3] - bboxes[:, 1] + 1.0 bx = bboxes[:, 0] + 0.5 * bw by = bboxes[:, 1] + 0.5 * bh tw = targets[:, 2] -...
547c098963b9932aa518774e32ca4e42301aa564
4,221
def cipher(text: str, key: str, charset: str = DEFAULT_CHARSET) -> str: """ Cipher given text using Vigenere method. Be aware that different languages use different charsets. Default charset is for english language, if you are using any other you should use a proper dataset. For instance, if you are ci...
ef6ac915f0daf063efbc587b66de014af48fbec6
4,222
def product_delete(product_id): """ Delete product from database """ product_name = product_get_name(product_id) res = False # Delete product from database if product_name: mongo.db.products.delete_one({"_id": (ObjectId(product_id))}) flash( product_name + ...
600a4afa9aab54473cdeb423e12b779672f38186
4,223
import sys def alpha_072(enddate, index='all'): """ Inputs: enddate: 必选参数,计算哪一天的因子 index: 默认参数,股票指数,默认为所有股票'all' Outputs: Series:index 为成分股代码,values为对应的因子值 公式: (rank(decay_linear(correlation(((high + low) / 2), adv40, 8.93345), 10.1519)) / rank(decay_linear(correlati...
f700619046d6f9d484f47345d82a03cfed1907ed
4,224
def getBoxFolderPathName(annotationDict, newWidth, newHeight): """ getBoxFolderPathName returns the folder name which contains the resized image files for an original image file. Given image 'n02085620_7', you can find the resized images at: 'F:/dogs/images/n02085620-Chihuahua/boxes_64_64/' ...
75d5470373e4c119e7bb8bd327f6d83884680a9d
4,225
def _download_artifact_from_uri(artifact_uri, output_path=None): """ :param artifact_uri: The *absolute* URI of the artifact to download. :param output_path: The local filesystem path to which to download the artifact. If unspecified, a local output path will be created. """ ...
219c4be3cd41741e6e93a1ca46696284c9ae1b80
4,226
import json def api_get_project_members(request, key=None, hproPk=True): """Return the list of project members""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: if not settings.PIAPI_REALUSERS: users = [generate_user(pk=...
653a60fccf7e81231790e4d00a1887c660f5ad4f
4,227
def random(n, mind): """Does not guarantee that it's connected (TODO)!""" return bidirectional({i: sample(range(n), mind) for i in range(n)})
0a64941c59173172c9e343a2e38c5e068a4c347c
4,228
import os import json def process_tare_drag(nrun, plot=False): """Processes a single tare drag run.""" print("Processing tare drag run", nrun) times = {0.2: (15, 120), 0.3: (10, 77), 0.4: (10, 56), 0.5: (8, 47), 0.6: (10, 40), 0.7: (8, 33), ...
bc5fa8d3e6878f36c676084e7c0a2c03a45ca0aa
4,229
import re def clean_weight(v): """Clean the weight variable Args: v (pd.Series): Series containing all weight values Returns: v (pd.Series): Series containing all cleaned weight values """ # Filter out erroneous non-float values indices = v.astype(str).apply( lamb...
7bcfb05fdb765ad0cc7a6b3af48f8b6cfa2f709b
4,230
def get_yield(category): """ Get the primitive yield node of a syntactic category. """ if isinstance(category, PrimitiveCategory): return category elif isinstance(category, FunctionalCategory): return get_yield(category.res()) else: raise ValueError("unknown category type with instance %r" % cat...
54fbbc67ea70b7b194f6abd2fd1286f7cd27b1f2
4,231
def box(type_): """Create a non-iterable box type for an object. Parameters ---------- type_ : type The type to create a box for. Returns ------- box : type A type to box values of type ``type_``. """ class c(object): __slots__ = 'value', def __init...
5b4721ab78ce17f9eeb93abcc59bed046917d296
4,232
def rssError(yArr, yHatArr): """ Desc: 计算分析预测误差的大小 Args: yArr:真实的目标变量 yHatArr:预测得到的估计值 Returns: 计算真实值和估计值得到的值的平方和作为最后的返回值 """ return ((yArr - yHatArr) ** 2).sum()
429dd6b20c20e6559ce7d4e57deaea58a664d22b
4,233
def initialize_vocabulary(vocabulary_file): """ Initialize vocabulary from file. :param vocabulary_file: file containing vocabulary. :return: vocabulary and reversed vocabulary """ if gfile.Exists(vocabulary_file): rev_vocab = [] with gfile.GFile(vocabulary_file, mode="rb") as f:...
fcfbed41c5d1e34fcdcc998f52301bff0e1d5dd8
4,234
def mock_create_draft(mocker): """Mock the createDraft OpenAPI. Arguments: mocker: The mocker fixture. Returns: The patched mocker and response data. """ response_data = {"draftNumber": 1} return ( mocker.patch( f"{gas.__name__}.Client.open_api_do", return_...
43f5fdc7991eefbf965662ccd0fadaa5015c2e00
4,235
import tqdm def to_csv(data_path="data"): """Transform data and save as CSV. Args: data_path (str, optional): Path to dir holding JSON dumps. Defaults to "data". save_path (str, optional): Path to save transformed CSV. Defaults to "data_transformed.csv". """ elements = [] for dat...
a6a28c4d2e1e1dfad9b7286e49289d012de0a9b4
4,236
def do_on_subscribe(source: Observable, on_subscribe): """Invokes an action on subscription. This can be helpful for debugging, logging, and other side effects on the start of an operation. Args: on_subscribe: Action to invoke on subscription """ def subscribe(observer, scheduler=None)...
266bdecb1dd4d567069be1e52cccc87a1d6cada1
4,237
def get_language_file_path(language): """ :param language: string :return: string: path to where the language file lies """ return "{lang}/localization_{lang}.json".format(lang=language)
9be9ee9511e0c82772ab73d17f689c181d63e67c
4,238
from typing import Union from typing import Dict import os import json def json_loader(path: str = None) -> Union[Dict, list]: """ Loads json or jsonl data Args: path (str, optional): path to file Returns: objs : Union[Dict, list]: Returns a list or dict of json data json_for...
09082ccdb0d5aa66a8321c01144dac49a416243f
4,239
def handle_response(request_object): """Parses the response from a request object. On an a resolvable error, raises a DataRequestException with a default error message. Parameters ---------- request_object: requests.Response The response object from an executed request. Returns ...
7778a0971fd991dd4e3eaef31379895b9c74d6f2
4,240
from typing import List import os def _get_zoom_list_recordings_list() -> List[str]: """Get the list of all the recordings.""" # The local path for zoom recording is ~/Documents/Zoom # Get the home directory file_list = os.listdir(ZOOM_DIR) files = [] for f in file_list: files.append(f...
10f8c6f4b1aca23aebd3575639ba07ec1003ca71
4,241
def evaluate(expn): """ Evaluate a simple mathematical expression. @rtype: C{Decimal} """ try: result, err = CalcGrammar(expn).apply('expn') return result except ParseError: raise SyntaxError(u'Could not evaluate the provided mathematical expression')
94518c3a225f62540e045336f230a5fb2d99dcaf
4,242
import os def is_device_removable(device): """ This function returns whether a given device is removable or not by looking at the corresponding /sys/block/<device>/removable file @param device: The filesystem path to the device, e.g. /dev/sda1 """ # Shortcut the case where the device an SD ca...
02aa63734a011bda7d5c63d96a063e643118f6bb
4,243
from typing import Optional def get_user(is_external: Optional[bool] = None, name: Optional[str] = None, username: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetUserResult: """ Use this data source to retrieve information about a Ranch...
c15a13e6a0633bc46fd1bdc8a3d914bfbd1d6b34
4,244
import random def randbytes(size) -> bytes: """Custom implementation of random.randbytes, since that's a Python 3.9 feature """ return bytes(random.sample(list(range(0, 255)), size))
0ea312376de3f90894befb29ec99d86cfc861910
4,245
def path_to_model(path): """Return model name from path.""" epoch = str(path).split("phase")[-1] model = str(path).split("_dir/")[0].split("/")[-1] return f"{model}_epoch{epoch}"
78b10c8fb6f9821e6be6564738d40f822e675cb6
4,246
def _cpp_het_stat(amplitude_distribution, t_stop, rates, t_start=0.*pq.ms): """ Generate a Compound Poisson Process (CPP) with amplitude distribution A and heterogeneous firing rates r=r[0], r[1], ..., r[-1]. Parameters ---------- amplitude_distribution : np.ndarray CPP's amplitude dist...
fd62c73f5ef6464d61b96ebf69b868f12245c305
4,247
def validate_uncles(state, block): """Validate the uncles of this block.""" # Make sure hash matches up if utils.sha3(rlp.encode(block.uncles)) != block.header.uncles_hash: raise VerificationFailed("Uncle hash mismatch") # Enforce maximum number of uncles if len(block.uncles) > state.config[...
5a0d51caae5ca42a31644316008cd949862713cb
4,248
def quote_index(q_t,tr_t): """Get start and end index of quote times in `q_t` with the same timestamp as trade times in `tr_t`.""" left, right = get_ind(q_t,tr_t) right[left<right] -=1 # last quote cannot be traded on, so shift index left -=1 # consider last quote from before the timestamp of the trad...
2de223b3d08e99113db56c8e9522a1d0066c76b7
4,249
def calculate_learning_curves_train_test(K, y, train_indices, test_indices, sampled_order_train, tau, stop_t=None): """Calculate learning curves (train, test) from running herding algorithm Using the sampled order from the sampled_order indexing array calculate the ...
d7bf3484e95d7e97eac4ba8b68b485e634b2f7f2
4,250
def removeString2(string, removeLen): """骚操作 直接使用字符串替换""" alphaNums = [] for c in string: if c not in alphaNums: alphaNums.append(c) while True: preLength = len(string) for c in alphaNums: replaceStr = c * removeLen string = string.replace(rep...
57d01d7c2a244b62a173fef35fd0acf1b622beed
4,251
from typing import Union from datetime import datetime import hashlib def process_filing(client, file_path: str, filing_buffer: Union[str, bytes] = None, store_raw: bool = False, store_text: bool = False): """ Process a filing from a path or filing buffer. :param file_path: path to proc...
aafbe010615b6aeb1a21760a43a9680fa9c2a37f
4,252
import os import glob def metadata_file(): """ Return the path to the first (as per a descending alphabetic sort) .csv file found at the expected location (<ffmeta_package_dir>/data/*.csv) This is assumed to be the latest metadata csv file. :return: The absolute path of the latest metadata csv...
6020667119ca48ec2312c6b854936d0236b9f3f2
4,253
def _get_anchor_negative_triplet_mask(labels): """Return a 2D mask where mask[a, n] is True iff a and n have distinct labels. Args: labels: tf.int32 `Tensor` with shape [batch_size] Returns: mask: tf.bool `Tensor` with shape [batch_size, batch_size] """ # Check if labels[i] != labels...
4c67bcc4e17e091c039c72a1324f501226561557
4,254
def random_k_edge_connected_graph(size, k, p=.1, rng=None): """ Super hacky way of getting a random k-connected graph Example: >>> from graphid import util >>> size, k, p = 25, 3, .1 >>> rng = util.ensure_rng(0) >>> gs = [] >>> for x in range(4): >>> G = ...
98609e31790fc40229135f3a2c0dedd2eb123e9b
4,255
import os from datetime import datetime from shutil import copyfile import csv def finish_round(): """Clean up the folders at the end of the round. After round N, the cur-round folder is renamed to round-N. """ last_round = get_last_round_num() cur_round = last_round + 1 round_dir = os.path.j...
0529f3a7edec1eee67288420c85403db02003801
4,256
from typing import Optional from typing import Dict from typing import Any from typing import FrozenSet import json def _SendGerritJsonRequest( host: str, path: str, reqtype: str = 'GET', headers: Optional[Dict[str, str]] = None, body: Any = None, accept_statuses: FrozenSet[int] = frozenset([2...
81bd115083c1d8ae4a705270394cf43ca1918862
4,257
def readTableRules(p4info_helper, sw, table): """ Reads the table entries from all tables on the switch. :param p4info_helper: the P4Info helper :param sw: the switch connection """ print '\n----- Reading tables rules for %s -----' % sw.name ReadTableEntries1 = {'table_entries': []} Read...
267bb6dcdf2d3adf37bcfa62f8d4581d9a9deda7
4,258
import sys def alpha_043(code, end_date=None, fq="pre"): """ 公式: SUM((CLOSE>DELAY(CLOSE,1)?VOLUME:(CLOSE<DELAY(CLOSE,1)?-VOLUME:0)),6) Inputs: code: 股票池 end_date: 查询日期 Outputs: 因子的值 """ end_date = to_date_str(end_date) func_name = sys._getframe().f_code.co_n...
ef6cacc33efd4f66b0b9661bd55be7694fd2c737
4,259
def binary_to_string(bin_string: str): """ >>> binary_to_string("01100001") 'a' >>> binary_to_string("a") Traceback (most recent call last): ... ValueError: bukan bilangan biner >>> binary_to_string("") Traceback (most recent call last): ... ValueError: tidak ada yang diinput...
f22dd64027ee65acd4d782a6a1ce80520f016770
4,260
from faker import Faker import json def create_fake_record(): """Create records for demo purposes.""" fake = Faker() data_to_use = { "access": { "record": "public", "files": "public", }, "files": { "enabled": False, }, "pids": { ...
0a9b2618745273def5d6030b74dca769f35dbd5d
4,261
def load_texture_pair(filename): """Function what loads two verions of the texture for left/right movement""" return [ arcade.load_texture(filename), arcade.load_texture(filename, flipped_horizontally=True) ]
782a79395fe25c8f391877dc9be52bf9d29f63f9
4,262
from typing import Tuple def bytes2bson(val: bytes) -> Tuple[bytes, bytes]: """Encode bytes as BSON Binary / Generic.""" assert isinstance(val, (bytes, bytearray)) return BSON_BINARY, pack_i32(len(val)) + BSON_BINARY_GENERIC + val
2c481d6585c12732f4b26a2c25f5738a5f8352bb
4,263
def tabindex(field, index): """Set the tab index on the filtered field.""" field.field.widget.attrs["tabindex"] = index return field
c42b64b3f94a2a8a35b8b0fa3f14fe6d44b2f755
4,264
def compute_GridData(xvals, yvals, f, ufunc=0, **keyw): """Evaluate a function of 2 variables and store the results in a GridData. Computes a function 'f' of two variables on a rectangular grid using 'tabulate_function', then store the results into a 'GridData' so that it can be plotted. After calcula...
64c95b4ce6e7735869a31eb29e06c6e6c324a844
4,265
import functools from typing import Any import collections def decorator_with_option( decorator_fn, ): """Wraps a decorator to correctly forward decorator options. `decorator_with_option` is applied on decorators. Usage: ``` @jax3d.utils.decorator_with_option def my_decorator(fn, x=None, y=None): ...
2e9a4a772d7c072b579ac49e183d6ca00e9feacf
4,266
import math def chebyshev_parameters(rxn_dstr, a_units='moles'): """ Parses the data string for a reaction in the reactions block for the lines containing the Chebyshevs fitting parameters, then reads the parameters from these lines. :param rxn_dstr: data string for species in reaction bl...
fb1ae476d17a7f6546f99c729139bf55b4834174
4,267
def _gen_matrix(n, *args): """Supports more matrix construction routines. 1. Usual contruction (from a 2d list or a single scalar). 2. From a 1-D array of n*n elements (glsl style). 3. From a list of n-D vectors (glsl style). """ if len(args) == n * n: # initialize with n*n scalars dat...
eea482c20dfa5c30c9077185eba81bc3bd1ba8ce
4,268
import time import math def temperature(analog_pin, power_pin = None, ground_pin = None, R = 20000, n = 100): """Function for computing thermister temperature Parameters ---------- adc_pin: :obj:'pyb.Pin' Any pin connected to an analog to digital converter on a pyboard ...
a526595bcab6e824a82de7ec4d62fbfc12ee39f8
4,269
import json def submit_form(): """ Submits survey data to SQL database. """ if request.method == "POST": data = request.data if data: data = json.loads(data.decode("utf-8").replace("'",'"')) student, enrollments, tracks = processSurveyData(data) insert = '...
2d5a10c5af906a7993559cf71f23eea1a35ec993
4,270
def get_target_external_resource_ids(relationship_type, ctx_instance): """Gets a list of target node ids connected via a relationship to a node. :param relationship_type: A string representing the type of relationship. :param ctx: The Cloudify ctx context. :returns a list of security group ids. ""...
27077d3118ca10a6896ba856d9d261f1b8ab9d56
4,271
def split_multibody(beam, tstep, mb_data_dict, ts): """ split_multibody This functions splits a structure at a certain time step in its different bodies Args: beam (:class:`~sharpy.structure.models.beam.Beam`): structural information of the multibody system tstep (:class:`~sharpy.utils.datas...
25d3d3496bdf0882e732ddfb14d3651d54167adc
4,272
def qname_decode(ptr, message, raw=False): """Read a QNAME from pointer and respect labels.""" def _rec(name): ret = [] while name and name[0] > 0: length = int(name[0]) if (length & 0xC0) == 0xC0: offset = (length & 0x03) << 8 | int(name[1]) ...
d08a6c286e2520807a05cbd2c2aa5eb8ce7a7602
4,273
def coordinates_within_board(n: int, x: int, y: int) -> bool: """Are the given coordinates inside the board?""" return x < n and y < n and x >= 0 and y >= 0
6359343bde0c9d7658a484c45d9cd07893b4e00d
4,274
import sys def check_for_header(header, include_dirs, define_macros): """Check for the existence of a header file by creating a small program which includes it and see if it compiles.""" program = "#include <%s>\n" % header sys.stdout.write("Checking for <%s>... " % header) success = see_if_compiles(program, incl...
1d5ec438a96580de8d3b4f75544d37764cd4a75f
4,275
def hook_name_to_env_name(name, prefix='HOOKS'): """ >>> hook_name_to_env_name('foo.bar_baz') HOOKS_FOO_BAR_BAZ >>> hook_name_to_env_name('foo.bar_baz', 'PREFIX') PREFIX_FOO_BAR_BAZ """ return '_'.join([prefix, name.upper().replace('.', '_')])
b0dabce88da8ddf8695303ac4a22379baa4ddffa
4,276
def get_coefficients(): """ Returns the global scaling dictionary. """ global COEFFICIENTS if COEFFICIENTS is None: COEFFICIENTS = TransformedDict() COEFFICIENTS["[length]"] = 1.0 * u.meter COEFFICIENTS["[mass]"] = 1.0 * u.kilogram COEFFICIENTS["[time]"] = 1.0 * u.yea...
7acd77fdbb0604ff97aa24bb7ce4f29bb32889b0
4,277
def get_distance_from_guide_alignment(data, guide_data, reference_index_key="position", minus_strand=False): """Calculate the distance of input data alignment to the guide alignment. :param data: input data with at least "raw_start", "raw_length", and reference_index_key fields :param guide_data: guide alig...
1a1150a470c75e4e836278fafb263839a67f7da4
4,278
def get_info(font): """ currently wraps the infoFont call, but I would like to add a JSON represenation of this data to better display the individual details of the font.""" return pyfiglet.FigletFont.infoFont(font)
40ae5238701754a12c4b1c75fff54412f7e33d4f
4,279
def readline_skip_comments(f): """ Read a new line while skipping comments. """ l = f.readline().strip() while len(l) > 0 and l[0] == '#': l = f.readline().strip() return l
c4b36af14cc48b1ed4cd72b06845e131015da6c6
4,280
def _verify_weight_parameters(weight_parameters): """Verifies that the format of the input `weight_parameters`. Checks that the input parameters is a 2-tuple of tensors of equal shape. Args: weight_parameters: The parameters to check. Raises: RuntimeError: If the input is not a 2-tuple of tensors wit...
9ec018c66d48e830250fd299cd50f370118132cc
4,281
import requests def send_notification(lira_url, auth_dict, notification): """Send a notification to a given Lira. Args: lira_url (str): A typical Lira url, e.g. https://pipelines.dev.data.humancellatlas.org/ auth_dict (dict): Dictionary contains credentials for authenticating with Lira. ...
1f6c28f9b12458cd2af6c3f12f5a9a6df6e64f49
4,282
from exojax.spec.molinfo import molmass from exojax.utils.constants import kB, m_u def calc_vfactor(atm="H2",LJPparam=None): """ Args: atm: molecule consisting of atmosphere, "H2", "O2", and "N2" LJPparam: Custom Lennard-Jones Potential Parameters (d (cm) and epsilon/kB) Returns: ...
a48fe55216bcf9848eece92d45f03d2c1e3fdee3
4,283
def _crc16_checksum(bytes): """Returns the CRC-16 checksum of bytearray bytes Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html Initial value changed to 0x0000 to match Stellar configuration. """ crc = 0x0000 polynomial = 0x1021 for byte ...
2b00d11f1b451f3b8a4d2f42180f6f68d2fbb615
4,284
import os def is_absolute_href(href): """Determines if an HREF is absolute or not. Args: href (str): The HREF to consider. Returns: bool: True if the given HREF is absolute, False if it is relative. """ parsed = urlparse(href) return parsed.scheme != '' or os.path.isabs(parse...
44aa394f34f4d7d36e546593ea627d79dd3c7e23
4,285
from typing import Callable from typing import Dict import select import math def method_get_func(model, fields="__all__", need_user=False, **kwargs)->Callable: """生成一个model的get访问""" async def list(page: Dict[str, int] = Depends(paging_query_depend), user: User = Depends(create_current_act...
2a9b31aa6261d99da94f7a971a9096dfec291e86
4,286
def get_mysqlops_connections(): """ Get a connection to mysqlops for reporting Returns: A mysql connection """ (reporting_host, port, _, _) = get_mysql_connection('mysqlopsdb001') reporting = HostAddr(''.join((reporting_host, ':', str(port)))) return connect_mysql(reporting, 'scriptrw')
25fb3cba8db11d28450e142a35ff763313c4c360
4,287
def _get_params(conv_layer, bn_layer, relu_layer=None): """Retrieve conv_bn params within wrapped layers.""" if 'use_bias' in conv_layer['config']: if conv_layer['config']['use_bias']: raise ValueError( 'use_bias should not be set to True in a Conv layer when followed ' 'by BatchNormal...
e2bca5b31d12196efae30af455644a39bb257bea
4,288
def reverse(segment): """Reverses the track""" return segment.reverse()
74632b8a8a192970187a89744b2e8c6fa77fb2cf
4,289
def rmse(y, y_pred): """Returns the root mean squared error between ground truths and predictions. """ return np.sqrt(mse(y, y_pred))
c3d2e20d1e9ebf40c704c5f14fb0dd35758f2458
4,290
from typing import Dict from typing import Any def cdm_cluster_location_command(client: PolarisClient, args: Dict[str, Any]): """ Find the CDM GeoLocation of a CDM Cluster. :type client: ``PolarisClient`` :param client: Rubrik Polaris client to use :type args: ``dict`` :param args: arguments...
b0001969177dcceb144d03edece589a84af48dc1
4,291
def prepare_cases(cases, cutoff=25): """ clean cases per day for Rt estimation. """ new_cases = cases.diff() smoothed = new_cases.rolling(7, win_type='gaussian', min_periods=1, center=True).mean(std=2).round(...
71b41959178e6fb8480ba2f6549bfeb6f02aded4
4,292
def utility(board): """ Returns 1 if X has won the game, -1 if O has won, 0 otherwise. """ if winner(board) == 'X': return 1 elif winner(board) == 'O': return -1 else: return 0
77f4e503882a6c1a6445167d2b834f342adbc21e
4,293
def shard(group, num_shards): """Breaks the group apart into num_shards shards. Args: group: a breakdown, perhaps returned from categorize_files. num_shards: The number of shards into which to break down the group. Returns: A list of shards. """ shards = [] for i in range(num_shards): shar...
635af47ac15c5b3aeeec8ab73ea8a6a33cd0d964
4,294
def is_bond_member(yaml, ifname): """Returns True if this interface is a member of a BondEthernet.""" if not "bondethernets" in yaml: return False for _bond, iface in yaml["bondethernets"].items(): if not "interfaces" in iface: continue if ifname in iface["interfaces"]: ...
521186221f2d0135ebcf1edad8c002945a56da26
4,295
def get_id(group): """ Get the GO identifier from a list of GO term properties. Finds the first match to the id pattern. Args: group (List[str]) Returns: str """ return first_match(group, go_id).split(':',1)[1].strip()
de99e159c3de1f8984cce40f952ff14568c8a1a5
4,296
import random import math def generateLogNormalVariate(mu, sigma): """ RV generated using rejection method """ variateGenerated = False while not variateGenerated: u1 = random.uniform(0, 1) u2 = random.uniform(0, 1) x = -1*math.log(u1) if u2 > math.exp(-1*math.pow(...
048bc1c2123fbdd9a750aac86bd6922aaf42de27
4,297
import re def replace_color_codes(text, replacement): """Replace ANSI color sequence from a given string. Args: text (str): Original string to replacement from. replacement (str): String to replace color codes with. Returns: str: Mutated string after the replacement. """ ...
a0c3e1b1060ae475a16b936c237669edab8cfc91
4,298
def get_uti_for_extension(extension): """get UTI for a given file extension""" if not extension: return None # accepts extension with or without leading 0 if extension[0] == ".": extension = extension[1:] if (OS_VER, OS_MAJOR) <= (10, 16): # https://developer.apple.com/doc...
50e147d9fb267d7c4686dd9e53cd3404a9eaae6f
4,299