content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def keyhas(archiveindex_name, key, attr, p5_connection=None): """ Syntax: ArchiveIndex <name> keyhas <key> <attr> Description: Checks whether the <key> has attribute <attr> defined Return Values: -On Success: the string "1" if yes, or "0" otherwise """ method_name = "keyhas" return ex...
7d789d9e84dfe892812acfeb5029f57cabc4022c
63,421
def _stream_split_iterators(stream, n=None): """Split stream of samples. """ iterators = list(map(Stream, _split_iterators(iter(stream.samples()), n))) return iterators
297a2d11b5a94e5d4cd520fb3be643a87c11df7c
63,422
def log10(x): """log10(x) -> the base 10 logarithm of Decimal x.""" return log(x, D(10))
3b2924fdc4045e640a691bd684ee70b910309f13
63,424
def imo_lookup(request): """ Function used to determine if a IMO already exists in the database """ data = request.data imo = data['imo'] try: vessel = Vessel.objects.get(imo=int(imo)) except Exception as e: # Some error occurred trying to get query Vessels return Re...
300b848ea459a55437fb1be3ef2cc22d6ab10527
63,425
import locale def json_categories_to_dict(flat_json): """Create a dictionary from the categories in a flat JSON dataframe. Args: flat_json (pandas.DataFrame): pandas dataframe which has been `flattened` by a previous call to `pandas.io.json.json_normalize`. Returns: ...
97306e98f6ff6e8cb0197cd489a7eb428e52a3ab
63,426
def rivers_with_station(stations): """rivers_with_station(stations) returns a sorted list of the rivers stations are on without repeats""" stationRivers = set() for station in stations: stationRivers.add(station.river) stationRivers = sorted(stationRivers) return stationRivers
d13044fef2a824d0d08e4419a13a2b22f1732175
63,427
def denormalize(tensor, means=IM_NORM_MEAN, stds=IM_NORM_STD): """Reverses the normalisation on a tensor. Performs a reverse operation on a tensor, so the pixel value range is between 0 and 1. Useful for when plotting a tensor into an image. Normalisation: (image - mean) / std Denormalisation: image...
8eb0787effdabd9ce7102dd1c920bfcc2a9ecbaf
63,428
def relu(x, out=None): """ Rectified linear (unit) transfer function. Parameters ---------- x : numpy array Input data. out : numpy array, optional Array to hold the output data. Returns ------- numpy array Rectified linear of input data. """ return...
3e7db377b7cc41743bee5c3fc64ed9fa643e980a
63,429
import csv def read_graph(filepath) -> Graph: """Reads a graph from an edge list file and returns a graph_tool Graph object. Parameters ---------- filepath : str Path to the edge list file. Returns ------ Graph A graph_tool Graph object. """ with open(filepath) as...
8190bb97a12f217e9b704205b04ce89a04b718ae
63,430
from typing import OrderedDict def make_df_dict(d): """Reduce the keys in data, and turn them into the keys need for the pandas dataframe.""" dout = {} for key, val in d.items(): data = val['data'] out = val['out'] dout[key] = OrderedDict([ ('tp', data['tp']), ...
31692f96ea6cdfdd51681913d2ede6f1bcf6e5fe
63,431
import textwrap def get_coin_twitter_timeline(coin_id: str = "eth-ethereum") -> pd.DataFrame: """Get twitter timeline for given coin id. Not more than last 50 tweets [Source: CoinPaprika] Parameters ---------- coin_id: str id of coin from coinpaprika e.g. Ethereum - > 'eth-ethereum' Retur...
cf362d5b41c801b9fcaa3ded53bd737b9f32bbe8
63,432
from io import StringIO def request_image(**kwargs): """ Creates image for OpenLayers overlay. Returns ------- StringIO Image in StringIO. """ global vmin global vmax global metadata global cmap if 'reg' in kwargs: region = kwargs['reg'] if 'src' in k...
edff59af47282ce770de7197f79b34128c4cb796
63,433
from datetime import datetime def get_timestamp(): """ Obtains current timestamp in standard format with milliseconds Examples: >>> get_timestamp() '2017-08-22 20:34:54,584' @retval string A consistent-length date and time string """ date_format = datetime.strftime(datetime....
5b3d1f8098233c09fc485d060b5903d2027df0c9
63,434
def tab_contents_dimensionality(tab_id): """ Callback to switch tabs based on user interaction in the dimensionality reduction tab of the analysis accordion. Here we make all divs hidden and then unhide the one we're interested in. This is done to persist the selection of hyper-parameters when switc...
a645baa342c216d5679d3aeae1cd5e304957c3d8
63,435
from datetime import datetime from typing import Literal def add_agents_and_provenances(your_fn, g, lexicon_uri, PROV, language, verbose=0): """ :param yo...
91f6f3e896475b02ac059cd63672b40b7c480255
63,436
def df2matrix(df, nrows, ncols, column_name="rating"): """ Returns a sparse matrix constructed from a dataframe This code assumes the df has columns: MovieID,UserID,Rating """ values = df[column_name].values ind_movie = df['movieId'].values ind_user = df['userId'].values return sparse.cs...
282f0e95d13b22bdeac1f3c0bc87e5dac4053cc0
63,437
import torch def count_acc(logits, labels): """Compute the accuracy (after adaptation) of MAML on the test/query points Parameters ---------- logits : `torch.FloatTensor` instance Outputs/logits of the model on the query points. This tensor has shape `(num_examples, num_classes)`. ...
661c2b0e3580bc1689bb6c1001ac234e866a1162
63,438
import functools def check_total_penetration(): """checks if penetrations for each ST together with which it can appear totals less than or equal to 1 """ ds_es = get_bottomup_ds_es() valid = True for ds, es in ds_es: DS_ES_ST_Map = loaders.get_parameter("DS_ES_ST_Map") STs = [...
7e244f7d818d32bd4a8d4b051a6ea785e7ce41fe
63,439
def _format_media_type(endpoint, version, suffix): """ Formats a value for a cosmos Content-Type or Accept header key. :param endpoint: a cosmos endpoint, of the form 'x/y', for example 'package/repo/add', 'service/start', or 'package/error' :type endpoint: str :param version: The version of th...
993e178fc2a91490544936e019342e6ab8f928ce
63,442
def sgl_psf(rho, wavelength, z, r_g=r_g_sun): """Returns the gain for a point of the PSF (rho: distance from axis)""" return 4 * pi**2 / (1-exp(1) ** (-4 * pi**2 * r_g / wavelength)) * r_g / \ wavelength * j0(2*pi*(rho/wavelength)*sqrt((2*r_g)/z))**2
970e9ab105684ae367237cad44158490c69a75b8
63,443
from make_regressors import load_all_regressors from ML_OOP_stratosphere_gases import regressor_shift import xarray as xr def produce_X(regressors=['qbo_cdas', 'anom_nino3p4'], lag={'qbo_cdas': 5}, add_co2=True, standertize=False, reg_shift=None, syear=None, eyear=None): """reg_shift i...
10c512eff26c14117518cf1846cbff8e93dda73d
63,444
def homography_warp(image, homography, height=None, width=None, clamp=True): """Warp an image according to an inverse homography. Args: image: [..., H, W, C] input image homography: [..., 3, 3] homography mapping output to input height: desired output height (or None to use input height) width: des...
02ace203a976e413ef7a8f62d8176e8d6aa8b2b8
63,445
def map_transmission_upgrades( scenario1, scenario2, b2b_indices=None, figsize=(1400, 800), x_range=None, y_range=None, state_borders_kwargs=None, legend_font_size=20, legend_location="bottom_left", **plot_kwargs, ): """Plot capacity differences for branches & HVDC lines betw...
374028c866aba722393e679415add0ea72e45fef
63,446
def get_dropbox_client(access_key): """ Attempts to create the Dropbox Client with the associated """ try: client = Dropbox(access_key) client.users_get_current_account() return client except AuthError as e: print(f'Failed to authenticate using key {access_key}') ...
9321d88f70f81087017fc05f090deafe259b823b
63,448
import itertools def fill_with_virtuals(glycans, libr = None, reducing_end = ['Glc-ol','GlcNAc-ol','Glc3S-ol', 'GlcNAc6S-ol', 'GlcNAc6P-ol', 'GlcNAc1P-ol', 'Glc3P-ol', 'Glc6S-ol', 'GlcOS-ol'], ...
212e669cac190d8f83159c24ab20091b455039a3
63,449
def fitsingletile(imshape, alg): """Returns whether a given image shape will fit in a single tile or not. This depends on the algorithm used and the GPU available in the system""" mx = maxtile(alg) return mx*mx >= np.prod(imshape)
44e794462f55bc8e35c91c321e2010f4f656d1f1
63,450
import math def approx_rocket_ode(dt, t, x0, y0, vx0, vy0, drag_coef, m): """ :param dt: time of sim step :param t: the start time :param x0: start x :param y0: start y :param v0: start v (size of velocity vector) :param theta0: start angle (argument of velocity vector) :param drag_co...
809786975ab32506d1c012c574f4e8339a4c28b7
63,451
def fill_result_from_objective_history(result, history): """ Overwrite function values in the result object with the values recorded in the history. """ # counters result.n_fval = history.n_fval result.n_grad = history.n_grad result.n_hess = history.n_hess result.n_res = history.n_r...
a2f1388c5d71a06f45369098039a3fa623a25735
63,452
import hashlib import sqlite3 def hash_blocks_until(db,n): """Returns combined hash of all block hashes in db until block_height n """ sha224 = hashlib.sha224() with sqlite3.connect(db) as ledger_check: ledger_check.text_factory = str h3 = ledger_check.cursor() for row in h3.execu...
6bb59b063e9512483783dab70322082247638f46
63,453
def Armijo_Rule(f_next,f_initial,c1,step_size,pg_initial): """ :param f_next: New value of the function to be optimized wrt/ step size :param f_initial: Value of the function before line search for optimum step size :param c1: 0<c1<c2<1 :param step_size: step size to be tested :param pg: inner p...
90462eda94244c10afdf34e1ad042118d793c4fd
63,454
def rotate_z(vec, theta: float): """ Rotate a 3d-vector around the third (z) axis :param vec: Vector object to rotate :param theta: Rotation angles (in degrees) :return: Rotated 3d vector Dimension of vector is not checked for faster execution """ theta = np.pi * theta / 180. x_ = ve...
7b02619938a43317c105dce2975973f11bc89471
63,455
from typing import TextIO import csv def process_icp_aes(fh: TextIO, collected_on: str, writer: csv.DictWriter, args: Args) -> int: """ Process the file into CSV """ reader = csv.DictReader(fh, delimiter=',') flds = reader.fieldnames num_written = 0 # Parse file into values f...
1f97c2fa09fb7159e4ac15a35db9f0b13efe1d56
63,457
def ar_or_single(x, y, nx, ny): """Dimensionless production rate for a gene regulated by one activator and one repressor with OR logic in the absence of leakage with single occupancy. Parameters ---------- x : float or NumPy array Concentration of activator. y : float or NumPy array...
c7f3b065cd6ff609e84622e97ebd4bdd43292377
63,458
def get_version(): """Return the version.""" return "0.1"
318c8ee9c5ecfb8b603e7d756879947145fcc242
63,459
import socket def connect(host, port): """Connect to remote host.""" # Create socket try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as msg: return (None, msg) # Get remote IP try: addr = socket.gethostbyname(host) except socket.gaierr...
ab03e5551f0fbf92c6e2417635bc753d5b77eae2
63,461
def topics(request): """"Show all topics.""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context)
195d2c708722cd030ecac55d2bc57254decdb057
63,462
import warnings def fitgaussian(x, y, weights=None, guess=None, return_fit=True, return_uncertainties=False): """ Fit a single gaussian to the data "y" at positions "x", points can be weighted by "weights" and an initial guess for the gaussian parameters :param x: numpy array (1D), the...
ce0ffe3f5886ca77b48ce1f7dc4edc2b60a92727
63,464
import requests def get_last_deploy_for_env(proj_id, env_id): """get_last_deploy_for_env will get the information about the last deploy that was run in an enviroment""" uri = config.OCTOPUS_URI + \ "/api/deployments?environments={0}&projects={1}&take=4".format( env_id, proj_id) r = req...
ff0e51e1360c0d3d35c9b5cfc003ff43f5721f65
63,465
import json def jsonify(data): """Dump data as JSON, like like :func:`flask.jsonify`.""" return current_app.response_class( json.dumps(data, ensure_ascii=False, default=extended_encoder) + "\n", mimetype=current_app.config["JSONIFY_MIMETYPE"], )
c088f5d4847ddc3147524054b5c20ec15924f5a4
63,467
def e2p0(tof,p1,p2,p3,p5,p6): """ Background function for TOF spectra Background function for TOF spectra Parameters ---------- tof : array-like The time-of-flight spectrum p1 : float constant background p2 : float multiplier on 1st exponential p3 : float ...
bb27e3178cf947d5d1ee7c9ca7fc6a8ae262b066
63,468
import pprint def pfomart(obj): """格式化输出某对象 :param obj: obj对象 :return: 格式化出处的字符串 """ return pprint.pformat(obj)
2f2c7d7df9de9bb65c72634e8ba9386365408445
63,471
from typing import Any from typing import Type def extend_class(base_cls: Any, cls: Any) -> Type: """Apply mixins""" base_cls_name = base_cls.__name__ return type(base_cls_name, (cls, base_cls), {})
5ed297f9115ec3940991b3536c207da3f6b036d0
63,472
import aiohttp async def retrieve_page(url: str, head=False, call=None, headers=None, **params): """ Download and return a website with aiohttp. :param url: Download url as str. :param head: Whether or not to head the function. :param call: Any attribute coroutine to call before returning. Eg: "text"...
5152857e51ac9a65589f123654f2d733854b42e7
63,475
def nx2nx_loader(extractor, stream, transformers, loader_json, graph): """ Loader for NetworkX graph. :returns: networkx.Graph """ extractor_json = extractor(graph) graph = extractor_json["graph"] node_type_attr = extractor_json["node_type_attr"] edge_type_attr = extractor_json["edge_ty...
bdf8d904edb80de3a4c91318be9e7dc307155a5f
63,477
def _ts_value_newton(position, counts, bkg, model, C_0_map): """ Compute TS value at a given pixel position using the newton method. Parameters ---------- position : tuple Pixel position. counts : `~numpy.ndarray` Count map. bkg : `~numpy.ndarray` Background ma...
adb27cda1d2c86f6f61d8353d913966cc700c6d3
63,478
def model_with_redis_field_without_pickling(r): """Class with RedisField attribute without pickling.""" class Model(object): redis_field = RedisTestListField(r, pickling=False) return Model
bd8f145c823894d0d6c91e2f6308e80f48555e01
63,479
def journal_info(): """Create a info dictionary for edit or create later.""" info = { 'title': 'testing', 'body': 'testing_body', 'creation_date': '2017-11-02' } return info
e596f42ec158b7635b248558c924e3af56ae33ea
63,480
def get_plugin_aac_definitions() -> str: """ Returns the CommandBehaviorType modeling language extension to the plugin infrastructure. Returns: string representing yaml extensions and data definitions employed by the plugin """ return get_resource_file_contents(__package__, "gen_plant_uml.y...
04c49fb7546e985b7a230685d98b1eadcd0a4bcf
63,481
def urls_without_scheme(src_list): """ Looks for urls/domains without scheme and if it exists, it returns true. otherwise false """ result = False for item in src_list: if validators.domain(item.replace('*.', '').replace(':*', '').split(':', 1)[0].split('/', 1)[0]): return Tr...
310cc42e1f6c4e56a68ef598a8d216cdc5e2daf5
63,482
from typing import Type def make_structured_name(se) -> StructuredName: """ Convert tuple form to StructuredName E.g. make_structured_name(("rev", ("f", Type.Integer))) """ if isinstance(se, str): return StructuredName(se) if isinstance(se, tuple): assert len(se) == 2 ...
68977cb2e0f260eb7dad3ff1ec313c501faf431e
63,484
def parse_single_file(content, CRLF=True, LTRB=True, withTranscription=False, withConfidence=False, img_width=0, img_height=0, sort_by_confidences=True): """ Returns all points, confindences and transcriptions of a file in lists. Valid line formats: xmin,ymin,xmax,ymax,[confidence],[transcription] x1,y1...
0b3ae4320760198d814bfb3c7a99e164be5d9c90
63,485
def distance(x1, y1, x2, y2): """ The Squared Euclidean Distance is given by the following formula: round(math.pow((x1-x2), 2) + math.pow((y1-y2), 2)) """ return pdist(np.array([[x1, y1], [x2, y2]]), metric='sqeuclidean')
92337d4f434311f807da151321e250f9dfb25813
63,486
import re def rle2cells(rle_str: str) -> str: """Convert lifeform string in RLE encoding to PlainText Args: rle_str (str): single line of RLE commands Returns: str: valid PlainText-encoded lifeform """ # drop the last part if "!" in rle_str: rle_str = rle_str[: rle_st...
e48ea40bd9032445e1aabe4753b7fbdcc62191ed
63,487
from typing import Union def _condition_counter(true: np.ndarray, predicted: np.ndarray, true_condition: Union[bool, int, str, list, tuple, set], predicted_condition: Union[bool, int, str, list, tuple, set]) -> int: """ count the number of i...
1a107584587875231d77d8b737988b5404aa8534
63,488
def script_extension(char): """ Return the script extension property assigned to the Unicode character 'char' as a set of string. >>> script_extension("a") == {'Latn'} True >>> script_extension(unichr(0x060C)) == {'Arab', 'Syrc', 'Thaa'} True >>> script_extension(unichr(0x10FFFF)) == {'Zzzz...
bfd6ee27272f3f4ae7014cea919a20abc2e97bf4
63,489
def format_list_of_floats(float_list, length_per_value=6, digit_after_point=4): """Returns a formatted string""" string = "[" str_format = " {:" + str(length_per_value) + "." + str(digit_after_point) + "f}," for value in float_list: string += str_format.format(value) string += "]" return...
622d20132d7e9af19fc3a143306268e8381c457c
63,490
def __apply_text_layer_filter(text_layer, text): """Return text with layer properties, applying uppercase, lowercase or capitalize. """ filtered_text = text char_sequence_case = CharSequenceCase.get_char_sequence_case( text_layer.text ) if char_sequence_case: filtered_text = ...
d140138fb26af25fd68592a681b1b4cf5058fb92
63,492
def add_metaclass(metaclass): """ Class decorator for creating a class with a metaclass. From `six` package source code: https://bitbucket.org/gutworth/six/overview. """ def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None:...
03cd1bef3ec908f380c2c6ac125ea82570e91587
63,493
import json def parse_config(): """ This helper function parses the config in /data/act_overseer_config :return: tuple (user, pass, log_path) obtained from the config. """ with open(filename('data/act_overseer_config'), 'r') as config: cfg = json.load(config) user = cfg['user'] ...
da4a315f4ee3c217d60ca0343faadb1c7bc2d3e3
63,494
def distance_matrix(points1, points2, norm=2, max_dist=None): """Calculate the distance between each combination of points in two sets. Parameters ---------- points1 : array_like 2-D array of `n1` points. points2 : array_like 2-D array of `n2` points. norm : int, optional ...
8fa6befb3d937de224cbd91b593a61fd30685291
63,495
def route(url): """装饰器工厂函数 接收路径参数""" def warpped(func): """装饰器函数 接收路径对应的函数 func就是被装饰器之前的函数的引用""" route_list.append((url, func)) def inner(): """在inner函数内部 才完成了func函数功能的拓展""" print("正在执行某些拓展功能") return func() return inner return warpped
69076756542e3077daab1670f0f42d30815163f0
63,497
def check_js_equal(expected=None, actual=None): """Minify the JavaScript and compare it""" with suppress_stderr(): print('Minifying expected JS') js0 = slimit.minify(expected) print('Minifying actual JS') js1 = slimit.minify(actual) if js0 == js1: return True prin...
fcee68200dc38778f019ef5f92be449a517999dd
63,499
import torch def __fan(mask, iter): """Fans out bitmask from input to output at `iter` stage of the tree See arrows in Fig. 1 (right) of Catrina, O. "Improved Primitives for Secure Multiparty Integer Computation" """ multiplier = (1 << (2 ** iter + 1)) - 2 if isinstance(mask, (int, float)) or...
e98679e04ff4b4cab2f281bfed0085dfab7a6484
63,501
import tokenize from typing import Counter def count_text(ngram, hash_size, doc_id, text=None): """Compute hashed ngram counts of text.""" row, col, data = [], [], [] # Tokenize tokens = tokenize(utils.normalize(text)) # Get ngrams from tokens, with stopword/punctuation filtering. ngrams = to...
ec7f004976a4726480ebf15246880ae97ae006d6
63,502
def gmtnow(): """ 現在時刻を aware GMT で取得します """ return utcnow().astimezone(gmt)
49131c0caf55105cac3b2a7e194e7b6af69a5cd8
63,503
def is_out_of_boundaries(state): """ Function that detects if the puck is out of the board limits. Returns: None: if is not out of the boundaries str: 'horizontal' or 'vertical' if is out of boundaries. """ # if next_pos_from_state(state)['x'] + state['puck_radius'] >= state['board_shap...
27f34c31086381dfceb8b48b23be68750bd66d1d
63,504
def pointcloud_normalization(ptc1): """Normalize pointcloud as out=(input-input.mean())/input.std()""" if ptc1[:, 0].std() == 0: ptc1[:, 0] = ptc1[:, 0] - ptc1[:, 0].mean() else: ptc1[:, 0] = (ptc1[:, 0] - ptc1[:, 0].mean()) / ptc1[:, 0].std() if ptc1[:, 1].std() == 0: ptc1[:, 1]...
cca4f23d810a56a0f06115de67d2f2ec6feee918
63,505
from typing import Optional def parse( header_text ): """Uses pyparsing to extract information from the header of a mcstas component file. Takes a string of the general form: * Component: componentname * * %I * copyright information * * simple description * * %D * ...
93b542e04358646492039bac99501ddbfa60a0aa
63,506
def all_punctuations_space(text: str) -> str: """ Add spaces after punctuations used in ``urdu`` writing Args: text (str): ``Urdu`` text Returns: str: Returns a ``str`` object containing normalized text. """ text = _SPACE_BEFORE_ALL_PUNCTUATIONS_RE.sub(' ', text) text = _SPA...
4c6b384def762a6ac0b591a8fa86a188bac94c9f
63,507
def selftest_function(opts): """ Placeholder for selftest function. An example use would be to test package api connectivity. Suggested return values are be unimplemented, success, or failure. """ try: options = opts.get("fn_hibp", {}) hibp = Hibp(options) test_url = "{0}/{1...
9f08521ed34f0ff402ef90c65d4a5dbc04ccbfb2
63,508
def duration_to_basic_name(duration, ppq): """ Gets a note duration name for a given duration. :param duration: duration :type duration: int :param ppq: ppq (midi pulses per quarter note) :type ppq: int :return: C128 BASIC name for the duration :rtype: str """ f = constants.Frac...
3c0cb19118da15267d562a38d1a0df24a54f85cc
63,509
import scipy def calc_fn_rate_override(M, N, m, s, rho, alpha, test_type, override_diff): """ :param M: :param N: :param m: :param s: :param rho: :param alpha: :param test_type: :param offset: :param sign: :param override_diff :return: """ if not is_iterable(s)...
5b880daa066cfec21832e3bc24ed3023a5f3b621
63,510
def create_single_choice_dom_from_option(option): """ Creates dom look for a specific option of a question """ doc = minidom.Document() li = doc.createElement("li") li.attributes["class"] = "choice" # Each list element has a 'selector', i.e the option that can be selected # and a 'resp...
5632c7253177aae52447b3686288cb5d01a4de12
63,511
def pow_sq(x, y): """ Compute x^y, without calling its pow, using exponentiation by squaring. """ r = 1 while y: if y & 1: r = r * x x = x * x y >>= 1 return r
f6d82257ff909d9c890360dcd9408db0d742b13d
63,513
def backend_table_spec(backend: Backend, db_name: str, table_name: str) -> TableSpec: """ >>> from jasmine.etl.backends import example_create_sqlite_schema_statements, tmp_mock_sqla_backend >>> from pprint import pprint >>> with tmp_mock_sqla_backend(example_create_sqlite_schema_statements) as backend:...
3ca68d3d6bf8c7ce52be0bcee11867b14b84005c
63,514
from typing import Any def _sort_key_source(item: CollectorItem) -> Any: """Return a sort key for 'source' sorting of CollectorItems.""" # if 'line_start' isn't found on the object, the item will go to # the start of the list. return item.get("source", {}).get("line_start", -1)
9f3a6ccbd43f171eeec466cc88f47234615791e3
63,515
def parse_ascii_input(filename): """Parse station info from an input file. This function will try to read Stations of from the input file, named filename. For this to work, the lines in the input file, should conform to the following format: "name lon lat Ve Vn Se Sn RHO T" ...
0e2c40b72d2ee02c8358aac515686568d7eb01d9
63,517
def current_minor_solar_term(date): """Return last Chinese minor solar term (jieqi) before date, date.""" s = solar_longitude(universal_from_standard(date, chinese_location(date))) return amod(3 + quotient(s - deg(15), deg(30)), 12)
9aa27324b8f42ef2aa6067416f46b760b595f75c
63,518
def discussions_to_df(discussions: list) -> pd.DataFrame: """Generates a discussion-centered DataFrame from the `discussions` list. Args: discussions (list): Designed to be the output of the `tree_mapping.map_as_tree` method. Returns: (pd.DataFrame): a DataFrame based on `discussions`. ...
02e4c4c0487d9ee5be3214f2ac519555ba7ed791
63,519
def pauli_group(number_of_qubits, case=0): """Return the Pauli group with 4^n elements. The phases have been removed. case 0 is ordered by Pauli weights and case 1 is ordered by I,X,Y,Z counting last qubit fastest. Args: number_of_qubits (int): number of qubits case (int): determin...
a927cea4741b7e872800e890a2d51929fb3526fd
63,521
from datetime import datetime def update_comment( comment_id: MatchCommentID, editor_id: UserID, body: str ) -> MatchComment: """Update a comment on a match.""" comment = _get_db_comment(comment_id) comment.body = body comment.last_edited_at = datetime.utcnow() comment.last_edited_by_id = edi...
f8327be177589714c06d44060959583733d1b7e0
63,522
import copy def walk_wproj(client: _w.WaapiClient, start_guids_or_paths: _StrOrSeqOfStr, properties: _StrOrSeqOfStr = None, types: _StrOrSeqOfStr = 'any') -> _t.Iterator[_t.Tuple[_WaapiValue]]: """ Walk through descendants of an object and yield their properties. ...
efa667e8f1e80b2fa8323dd1fbce6b5a4399debe
63,523
def endpoints_api( name, version, auth_level=None, allowed_client_ids=None, **kwargs): """Same as @endpoints.api but tweaks default auth related properties. By default API marked with this decorator will use same authentication scheme as non-endpoints request handlers (i.e. fetch a whitelist of O...
baf0f454a16de769dda4875774b71d35f3e005a4
63,524
def list_attributes(any_class): """List all public methods and attributes of a class sorted by definition order """ return [x for x in any_class.__dict__.keys() if not x.startswith("_")]
fb3d8624b318a13b40f7b6f70482671943c37fc0
63,525
def get_counts_string(match): """ Looks for keys matching top_events_X in matches, generated by get_top_counts, and returns a readable string about the various counts. """ message = '' for key, counts in match.items(): if key.startswith('top_events_'): message += '%s:\n' % (key[11:])...
28674902c488add7e5e50af7bcf1a555255a07f7
63,526
def set_tv_importation_as_birth_rates(model, importation_times, importation_n_cases): """ When imported cases are explicitly simulated as part of the modelled population. They enter the late_infectious compartment through a birth process """ # inflate importation numbers to account for undetected ca...
ac6e82ee72d482d453665885564d6546580436d4
63,527
def one_car_position_axis(position_1): """Create a one car position in time axis.""" data = dict( data=[position_1], y_label='position') return dacite.from_dict(Axis, data)
96f9656d755953070e9031550c55f1664d74c9bf
63,528
import re def parse_ldd_output(output): """Parses the output from a run of 'ldd' on a binary. Returns a dictionary of {path: address} for each library required by the specified binary. Arguments: output(str): The output to parse Example: >>> sorted(parse_ldd_output(''' ... ...
d056cb2f782e01db829b3f9d8433e18f49b69ab3
63,530
def get_target_pts(pts_path): """ 获取真实的牙龈线点 """ target_pts = np.loadtxt(pts_path) return target_pts
204aae53a8eb53f0020c22e3a418a1b4e29bf57b
63,531
def cancel_and_stop_intent_handler(handler_input): """Single handler for Cancel and Stop Intent.""" # type: (HandlerInput) -> Response speech_text = INTENT_ANSWERS['stop'] return handler_input.response_builder.speak(speech_text).response
208a0abe5df177f95c02c0f98532a3ca5df687db
63,532
def colorizer(x, y): """ Map x-y coordinates to a rgb color """ r = min(1, 1-y/3) g = min(1, 1+y/3) b = 1/4 + x/16 return (r, g, b)
6b135728e02148af5368bc21bfb7d1bed90200d5
63,533
from typing import Optional from typing import Tuple import re def parse_commit_heading(heading: str) -> Optional[Tuple[str, Version, Version]]: """Parse nixpkgs-style commit header.""" msg_pattern = re.compile(r"^(?P<attrname>[^:]+):\s*(?P<old_version>.+)\s*(?:→|->)\s*(?P<new_version>.+)$") match = msg_p...
46ef4db36caf34165cb28ce7d8997acba2d5dc77
63,534
def _append_attr_suffix(name): """ Append auto parallel suffix for distributed attribute name. """ return name + core.kAutoParallelSuffix()
75445809505a21b4d612aa454a6e58806fecb414
63,535
import math from functools import reduce def CalculateTruncatedMean(data_set, truncate_percent): """Calculates the truncated mean of a set of values. Note that this isn't just the mean of the set of values with the highest and lowest values discarded; the non-discarded values are also weighted differently de...
56792561096127992c978985a444e124fbe4c5be
63,536
import logging def imreproj(image_in, epsg_out, mode='nearest'): """ Reproject a raster in memory (without write on disk) :param image_in: path of input raster :param epsg_out: output epsg (int) :param mode: interpolation mode ['nearest' (default), 'bicubic', 'average', 'bilinear', 'l...
51d4813fe816542c66bfcd40041e7651e0b43bca
63,537
def min_max_scale(values, raise_error=True, default_value=scalar_pass_through): """Normalize values in a list using min-max feature scaling. Values that are not numeric are either replaced with a given default value or an error is raised if the raise error flag is True. Parameters ---------- va...
28551f46a0ae10057149cefac864a69f46f2887a
63,538
def get_multiformat_body(request, key, default=None): # type: (Request, Str, Optional[Any]) -> Any """ Obtains the value of :paramref:`key` element from the request body according to specified `Content-Type` header. .. seealso:: - :func:`get_multiformat_body_checked` - :func:`get_permis...
51ccae9457f0a390a9a6030e0448d1f604a996b7
63,539
def SimTK_version_SimTKcommon(major, minor, build): """ SimTK_version_SimTKcommon(int * major, int * minor, int * build) Parameters ---------- major: int * minor: int * build: int * """ return _simbody.SimTK_version_SimTKcommon(major, minor, build)
ed5b1a4fbcb2df30b9fe070fc5e71840c0085360
63,540
def base(n: float, alphabet: str, digits: int) -> str: """ Converts a real-valued number into its baseN-notation. Parameters ---------- n : float Number to be converted (decimal precision will be droped) alphabet : str Alphabet of the positional notation system digits : int ...
64b1a2e7315e24e584520b1975a843acce152b21
63,541
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer): """ Convert a list of `InputExample` to be labelled into a list of bert `InputFeatures` """ features = [] input_tokens = [] for (ex_index, example) in enumerate(examples): feature, tokens = convert_single_...
54f4fa4afe6edf4ca3bdc8c84d03ddd94f7bd3c3
63,543