content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def default(typ, default=None, frm=None): """ optional value """ def _internal(val): if typ(val) is Consts.Fail: return default else: return val return u_condition_checker(frm, _internal)
07374d4e71693640eacf7ccf003843d37284231b
27,400
def fltflag(*args): """fltflag() -> flags_t""" return _idaapi.fltflag(*args)
1cb3f8849523c9811c0e3fa2b4bf50e5f72750cc
27,401
import io def get_mopac_deltaH0(lines): """ Return delta H in kcal/mol from mopac output. #>>> s = io.read_file('test/input.out') #>>> print(get_mopac_deltaH(s)) -13.02534 """ if isinstance(lines, str): lines = lines.splitlines() keyword = 'FINAL HEAT OF FORMATION' n = io.g...
a5b01de232b8e3f8c6d74c1e48095af8b9880696
27,403
def abstract(f): """ make method abstract. class Foo(object): @abstract def bar(self): pass foo = Foo() foo.bar() # NotImplementedError: can't invoke abstract method 'bar' """ @wraps(f) def wrapper(*args, **kwargs): msg = "can't invoke abstract m...
a652e2440a2b9b0606f18dd91ea77b3ebafb25fe
27,404
def capitalize_1(string): """ Capitalizes a string using a combination of the upper and lower methods. :author: jrg94 :param string: any string :return: a string with the first character capitalized and the rest lowercased """ return string[0].upper() + string[1:].lower()
9ad830a6d38e19b195cd3dff9a38fe89c49bd5c8
27,405
def edit_current_stock(current_stock_id, current_stock_data): """ 修改信息 :param current_stock_id: :param current_stock_data: :return: Number of affected rows (Example: 0/1) :except: """ return db_instance.edit(STCurrentStock, current_stock_id, current_stock_data)
bdc96043b74c2c02ae633700e0ec9860b61c7f11
27,406
def fit_via_yule_walker(x, order, acf_method="mle", demean=True): """ Estimate AR(p) parameters of a sequence x using the Yule-Walker equation. Parameters ---------- x : 1d numpy array order : integer The order of the autoregressive process. acf_method : {'unbiased', 'mle'}, optiona...
c96f29d72d88427fa4c9e345e22e41913218113f
27,407
def beta_create_Bookstore_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None): """The Beta API is deprecated for 0.15.0 and later. It is recommended to use the GA API (classes and functions in this file not marked beta) for all further purposes. This function was generated o...
91f15dc278a8f273232334e75e729819ec33f521
27,409
import yaml import json def domain_parser_yml_to_json(path_to_domain_yml, path_to_domain_json): """ Chatbot Domain Parser, will parse 'domain.yml' file to json object and write to file :param path_to_domain_yml: Complete path to YML domain file :param path_to_domain_json: Complete path to file where J...
9ea6459136eba27d1b60cfc590a3d3f526e9222b
27,410
def get_url_and_token(string): """ extract url and token from API format """ try: [token, api] = string.split(":", 1) [_, _, addr, _, port, proto] = api.split("/", 5) url = f"{proto}://{addr}:{port}/rpc/v0" except Exception: raise ValueError(f"malformed API string : {string}"...
f3abd327c9de2d098100e539f701bf2fff1742f5
27,411
def checkZone(false, usrdata): """ Check the cloudflare zone record for entries to remove """ # Call api request = [('a', 'rec_load_all')] json_data = callAPI(request, usrdata) # Dicts and Lists for later falserecs = {} names = {} recs = [] falsedata = {} recdata = {} # Par...
4f36ba5c7f20b15bfe80a80eda41ae8bf6141e16
27,412
import io def read_temp(buffer: io.BytesIO, offset: int = None) -> float: """Retrieve temperature [C] value (2 bytes) from buffer""" if offset: buffer.seek(offset) value = int.from_bytes(buffer.read(2), byteorder="big", signed=True) return float(value) / 10
e7cb28977af49fd3c52438357b02eb11f05d1e9d
27,413
def convert_netaddr(netaddr: str) -> str: """ Converts network address from hex_ip:hex_port format to ip:port e,g: 573B1FAC:BE46 to 172.31.59.87:48710 """ try: if check_netaddr_pattern(netaddr): addr, port = netaddr.split(':') addr = convert_addr(addr) po...
9d6979f0303ede07fcb7b92a4cfc8579b90fca84
27,414
def make_bsa_2d(betas, theta=3., dmax=5., ths=0, thq=0.5, smin=0, method='simple',verbose = 0): """ Function for performing bayesian structural analysis on a set of images. Parameters ---------- betas, array of shape (nsubj, dimx, dimy) the data used Note that...
37d2727ce71530e70750696fb1e852b822e5d54e
27,416
def test_hhs_hospital_dataset_non_default_start_date(): """Tests HHSHopsitalStateDataset imports adult_icu_beds_capacity correctly for a state with a non-default start date (Alaska) verifying that data prior to its start date (2020-10-06) is dropped.""" variable = ccd_helpers.ScraperVariable( va...
19de6db3884f5d0fea55c72bfee01502462fd029
27,419
def fibonacci(n: int) -> int: """ Iteratively compute fibonacci of n """ if n==0: return 0 if n==1: return 1 fp2 = 0 fp1 = 1 for _ in range(1,n): f = fp1 + fp2 fp2 = fp1 fp1 = f return f
e9f60ad7ae5187c516dba5e473fec86b154347d5
27,420
from typing import List from typing import Dict from typing import Any from typing import Tuple def do_make_label_group( text: List[str], **kwargs: Dict[str, Any] ) -> Tuple[int, List[RAMSTKLabel]]: """Make and place a group of labels. The width of each label is set using a natural request. This ensures...
200f65febc4dddf9c2f72e64963a34c2295bfcc8
27,421
def _variable_with_weight_decay(name, shape, stddev, wd, index): """Helper to create an initialized Variable with weight decay. Note that the Variable is initialized with a truncated normal distribution. A weight decay is added only if one is specified. Args: name: name of the variable shape: list of i...
bdd51083cb93557c3588c5b6dea75968f000a02f
27,423
def make_admin_versionable(cls): """Make Admin class versionable""" class AdminVersionable(AdminVersionableMixIn, cls): pass return AdminVersionable
c36d1a18aba44baddbd449b9f673241923251a01
27,425
def generate_model (d): """Returns a set of (random) d+1 linear model coefficients.""" return np.random.rand (d+1, 1)
b7b6e85cdd033e5e89aaaae5db258d97a1a61534
27,427
import json def handle_error(ex, hed_info=None, title=None, return_as_str=True): """Handles an error by returning a dictionary or simple string Parameters ---------- ex: Exception The exception raised. hed_info: dict A dictionary of information. title: str A title to b...
4b7bc24c9b4fd83d39f4447e29e383d1769e6b0f
27,428
def get_parent_epic(issue): """Get the parent epic of `issue`. Different boards have different meta data formats. """ return ( # DEV board getattr(ticket.fields, JIRA_FIELD_EPIC_LINK, None) # BS board or getattr(getattr(ticket.fields, 'parent', None), 'key', None) )
807763ee13fb1dd639155f6b9efca057a0d2b5a1
27,430
def get_elements(driver, selector, text='', selector_type=By.CSS_SELECTOR, timeout=DEFAULT_TIMEOUT, must_be_visible=True): """ Pauses execution until one or more elements matching the selector is visible. :param driver: we...
a9b3a5bad8ad8a9d32e6460ff72b089b20b5b713
27,432
import re def get_date_from_folder(file_str): """ get datetime from file folder of .et3, .erd, i.e., 'DATA2015-01-29-16-57-30/', '2020-10-11-03-48-52/' """ f = file_str.strip() f = f[:-1] # remove trailing '/' f = f.replace("DATA", "") # replace the 3rd occurrence of '-' w = [m.st...
1176501b771e1f7b9721f8b78516c69878417ab5
27,433
def translate_api2db(namespace, alias): """ >>> translate_api2db("ga4gh", "SQ.1234") [('VMC', 'GS_1234')] """ if namespace.lower() == "refseq": return [("NCBI", alias)] if namespace == "ensembl": return [("Ensembl", alias)] if namespace == "lrg": return [("LRG", ali...
843f67f12024222f271f9f1826e2530b5a7834b4
27,434
import requests def register_view(request): """Renders the register page.""" if request.method == 'GET': # Get signup form to display form = SignUpForm() return render(request, 'myroot/registration/register.html', {'form': form, 'title': "R...
aa854a427f8900a6b19ffef37598d1fa8f7b8d4d
27,435
def make_environment(): """Creates an OpenAI Gym environment.""" # Load the gym environment. environment = fakes.ContinuousEnvironment( action_dim=1, observation_dim=2, episode_length=10 ) return environment
61156d212a14f5214e017f34792532c1dfa8d6b8
27,436
def device_get(context, device_id): """get a device according to specify device_id""" return IMPL.device_get(context, device_id)
6bdc60e0fd177b29568c181870b1825746953751
27,437
import scipy def convolve_gaussian_2d(image, gaussian_kernel_1d): """Convolve 2d gaussian.""" result = scipy.ndimage.filters.correlate1d( image, gaussian_kernel_1d, axis=0) result = scipy.ndimage.filters.correlate1d( result, gaussian_kernel_1d, axis=1) return result
00046cd47d324a3f391ad0a84f31eb0368857afb
27,438
from unittest.mock import call def refresh_viewer(viewer, pdf_path, tm_bundle_support=getenv('TM_BUNDLE_SUPPORT')): """Tell the specified PDF viewer to refresh the PDF output. If the viewer does not support refreshing PDFs (e.g. “Preview”) then this command will do nothing. This comman...
629e5b8677ad8355acf7372690abff8c7864cd5f
27,439
def getLineagesFromChangeo(changeodb, print_summary): """subsets the changeo_db output by bracer by only those cells which are within lineages (non singletons)""" df = changeodb _df = df[df.CLONE != "None"] # get rid of unassigned cells (no BCR reconstructed) _df = (df.CLONE.value_counts() > 1) #find cl...
1a497b084118ce0993cf6509889831cab78d2a36
27,440
def pop(): """ Clear the current execution environment for whatever parallel mechanism is used. """ with _lock: ident = identifier() envs = _current_envs.get(ident) if envs: env = envs.pop() env.deactivate() if _current_envs[ident]: c...
70192457f7ac15eeb763650415ee82ac2b6409e8
27,441
def _run_cnvkit_cancer(items, background, access_file): """Run CNVkit on a tumor/normal pair. """ paired = vcfutils.get_paired_bams([x["align_bam"] for x in items], items) work_dir = _sv_workdir(items[0]) ckout = _run_cnvkit_shared(items[0], [paired.tumor_bam], [paired.normal_bam], ...
99ac686b0a24cfd87fdebd59fc691fbbe839323e
27,442
def meanAdjustELE(site_residuals, azSpacing=0.5,zenSpacing=0.5): """ PWL piece-wise-linear interpolation fit of phase residuals cdata -> compressed data """ tdata = res.reject_absVal(site_residuals,100.) del site_residuals data = res.reject_outliers_elevation(tdata,5,0.5) del tdata ...
5c543247d64e9c644f6b9401f2d662f62de23bd7
27,443
import math def rotateImage(input_img, angle): """ Rotate the input_img by angle degrees, Rotate center is image center. :param input_img:np.array, the image to be rotated :param angle:float, the counterclockwise rotate angle :return:np.array, the rotated image """ radian = angle * math.pi...
4c16e6a0af3637d21ffb27fbe0f5fad8e72c5bd2
27,444
def get_content_model_prefetch(content_model, content_attr='content'): """ Returns the fields that should be prefetched, for a relation that starts with '<content_attr>__'. If the model has MTURK_PREFETCH, then that is used. Otherwise, some common attributes are tested (photo, shape) and used if those...
5abeb44353723ffc8cd17ab9509e5a747d01dd24
27,445
def dispatch(obj, replacements): """make the replacement based on type :param obj: an obj in which replacements will be made :type obj: any :param replacements: the things to replace :type replacements: tuple of tuples """ if isinstance(obj, dict): obj = {k: dispatch(v, replacements...
8542214f83b6f04f1bbe21baa0710e7885a3b259
27,446
def process( mode, infile, outdir, genes, genes_drop, genes_bed, igh, mmrf, bolli, lohr, normals, mytype): """Main function to process myTYPE SNV and indel output""" ## IMPORTING DATA variants = import_variants(i...
606cbf58fa9974e968897a9c8289fbe5f1197d77
27,447
def set_axis_formatter(axis, params=None, **kwargs): """ Set axis formatter. :param axis: Matplotlib axis instance. :type axis: :class:`matplotlib.axes.Axes` :param params: Axis formatter parameters. :type params: dict, optional Example config: .. code-block:: python 'formatt...
8e5a1ca49b1ed6c29950a8d357664a7902f793ba
27,448
import time from datetime import datetime def convert_tzaware_time(t: time, tz_out: tp.Optional[tzinfo]) -> time: """Return as non-naive time. `datetime.time` should have `tzinfo` set.""" return datetime.combine(datetime.today(), t).astimezone(tz_out).timetz()
8dd59b59d4679789687b3c94d28e4dafbbc1fd01
27,449
def total_posts(): """ A simple template tag that shows the number of posts that have been uploaded so far """ return Post.published.count()
77ebf33ec5e646e461e57ae18e606766e4679a82
27,450
from typing import Tuple def make_policy_prior_network( spec: specs.EnvironmentSpec, hidden_layer_sizes: Tuple[int, ...] = (64, 64) ) -> networks.FeedForwardNetwork: """Creates a policy prior network used by the agent.""" action_size = np.prod(spec.actions.shape, dtype=int) def _policy_prior_fn(observatio...
7720bb9b182a3c19d80e3ecd241e7197fdec6c14
27,451
def simulate_moment_contributions(params, x, y): """Calculate moment contributions for example from Honore, DePaula, Jorgensen.""" y_estimated = x.to_numpy() @ (params["value"].to_numpy()) x_np = x.T.to_numpy() residual = y.T.to_numpy() - stats.norm.cdf(y_estimated) mom_value = [] length = ...
b3c38c3fb85d353eecf4185bd600cb3a6eade732
27,452
def get_app_host_list(app_id): """ 获取指定业务所有主机信息 :param app_id :return dict: {"InnerIP": host_info} """ cc_result = bk.cc.get_app_host_list(app_id=app_id) return cc_result
ce5b305c76b320c60963fa135734ac55e2960896
27,453
def staking_product_quota(self, product: str, productId: str, **kwargs): """Get Personal Left Quota of Staking Product (USER_DATA) Weight(IP): 1 GET /sapi/v1/staking/personalLeftQuota https://binance-docs.github.io/apidocs/spot/en/#get-personal-left-quota-of-staking-product-user_data Args: ...
64587a64a25fedea39e53aa8d5f8857d1844da89
27,454
def softmax(x): """ 개선된 softmax 함수 """ max_x = np.max(x) y = np.exp(x - max_x) / np.sum(np.exp(x-max_x)) return y
8912601dd73a10dfeb0391b9e292be0de6c1165a
27,456
def _FloatTraitsBaseClass_write_values_attribute(a, v): """_FloatTraitsBaseClass_write_values_attribute(hid_t a, Floats v)""" return _RMF_HDF5._FloatTraitsBaseClass_write_values_attribute(a, v)
8e93038969b901dc9b2696e89a6c8110ed5becb4
27,458
def get_cifar(root, dataset, transform, mode = 'train'): """Get cifar data set Args : --root: data root --dataset: dataset name --transform: transformation --mode: 'train'/'test' """ assert dataset.count('cifar') if dataset == 'cifar10': dataset = tv.datasets...
daf68549c2d6719f4a1fe7ae8c252e264288a5da
27,459
from pathlib import Path import textwrap def config(base_config): """:py:class:`nemo_nowcast.Config` instance from YAML fragment to use as config for unit tests.""" config_file = Path(base_config.file) with config_file.open("at") as f: f.write( textwrap.dedent( """\ ...
9c23b47ff355a68562446d41bca3d01b5a90d2d1
27,460
def mark_cell_function(fun, mesh, foc, regions): """ Iterates over the mesh and stores the region number in a meshfunction """ if foc is None: foc = calculus.estimate_focal_point(mesh) for cell in dolfin.cells(mesh): # Get coordinates to cell midpoint x = cell.midpoint...
0d91fa752350de5f51cf841770234675712f6f06
27,462
import json def incorrect_format(): """for handling incorrect json format""" js = json.dumps({'error': 'Incorrect format.'}) return Response(js, status=422, mimetype='application/json')
971096fde565d66786196773d99d3d7849fd6d14
27,463
import multiprocessing def start_multiprocessing(function_list, data_list): """ Creates and runs a multiprocessing pool for (1..n) functions all of which use the same data_list (e.g. YouTube video links). Returns a dictionary of results indexed by function. """ with multiprocessing.Pool(initi...
d02e00107f52bf0fa0a6bbc0da834c5c7638b33c
27,464
def GetNodeProperty(line): """ Get node property from a string. :param line: a string :return: name, size, and position of the node """ name, attr = NameAndAttribute(line) name = ProcessName(name, False) position = GetAttributeValue("pos", attr)[:-1].replace(",", "-") attr = CleanAt...
2f63af91864236033783d773439f829b9d7f405a
27,465
def login(request): """ Logs in a user. """ if request.method != "GET": return _methodNotAllowed() options = _validateOptions(request, {}) if type(options) is str: return _response(options) user = userauth.authenticateRequest(request, storeSessionCookie=True) if type(user) is...
abde5c258899cc8fcfdef0e0286e5e846d075a27
27,466
def wavenumber(f, h, g=9.81): """ solves the dispersion relation, returns the wave number k INPUTS: omega: wave cyclic frequency [rad/s], scalar or array-like h : water depth [m] g: gravity [m/s^2] OUTPUTS: k: wavenumber """ omega = 2*np.pi*f if hasattr(omega, '__len__...
a07541e5327cd778cf34b792380f2f25f9617c05
27,467
def command(cmd, label, env={}): """Create a Benchpress command, which define a single benchmark execution This is a help function to create a Benchpress command, which is a Python `dict` of the parameters given. Parameters ---------- cmd : str The bash string that makes up the command ...
487e7b8518ae202756177fc103561ea03ded7470
27,468
def adcp_beam_northward(b1, b2, b3, b4, h, p, r, vf, lat, lon, z, dt): """ Description: Wrapper function to compute the Northward Velocity Profile (VELPROF-VLN) from beam coordinate transformed velocity profiles as defined in the Data Product Specification for Velocity Profile and Echo ...
9f7c427a7f3ddbbfbdfe1f56269ddf04f99ea2bb
27,469
import re def get_text(string): """ normalizing white space and stripping HTML markups. """ text = re.sub('\s+',' ',string) text = re.sub(r'<.*?>',' ',text) return text
5ef04effe14ee9b0eee90de791b3e3f3be6c15e3
27,470
import struct def decode_ia(ia: int) -> str: """ Decode an individual address into human readable string representation >>> decode_ia(4606) '1.1.254' See also: http://www.openremote.org/display/knowledge/KNX+Individual+Address """ if not isinstance(ia, int): ia = struct.unpack('>H', ...
6f107f47110a59ca16fe8cf1a7ef8f061bf117c7
27,471
import array def dd_to_dms(deg): """Return degrees, minutes, seconds from degrees decimal""" mins, secs = divmod(deg * 3600, 60) degs, mins = divmod(mins, 60) return array((degs, mins, secs), dtype='i4')
f0bb8287ffb14f5d5643d5f9709dbad37381a8ae
27,472
def _compare_labels(primary, label1, label2): """ Compare two labels disposition :param primary: the primary label :param label1: the first label :param label2: the second label :return A tuple containing True if there is no difference False otherwise and the output text """ ...
9b1802d4b9bab0a71e1509bb5e49388267a96a29
27,473
def set_pause(df, index, ts_name): """ :param df: Spark DataFrame object with timestamp data :param index: fix index type: 'i1', 'i2', 'i3', 'j1', 'j2', 'j3' :param ts_name: column with timestamp data :return: Spark DataFrame object with timestamp data """ ...
cd7356ca134b5b0d3c91351478a9bd202cf2fcad
27,474
from pathlib import Path def _validate_magics_flake8_warnings(actual: str, test_nb_path: Path) -> bool: """Validate the results of notebooks with warnings.""" expected = ( f"{str(test_nb_path)}:cell_1:1:1: F401 'random.randint' imported but unused\n" f"{str(test_nb_path)}:cell_1:2:1: F401 'IPy...
4baa419ad4e95bf8cc794298e70211c0fa148e5b
27,475
def _drop_index(index, autogen_context): """ Generate Alembic operations for the DROP INDEX of an :class:`~sqlalchemy.schema.Index` instance. """ text = "%(prefix)sdrop_index(%(name)r, "\ "table_name='%(table_name)s'%(schema)s)" % { 'prefix': _alembic_autogenerate_prefix(autogen_...
43b6b5391b69896b1e7409108d79661a13697391
27,476
def add_metabolite_drain_reactions(mod_, metab_list, prefix_id="MDS"): """Take in a model and add metabolite drain reactions for a list of metabolites in the model. These metabolite drain reactions will have the identification of (MDS)__(metabolite id). (i.e., MDS__atp_c for the atp_c metabolite) """ ...
ea8cdf76896d4ab70dbb5f7fd4c15f4e83be7ba5
27,477
def tax_total(par): """ Finds total tax burden in a log normal distributed population Args: par: simplenamespace containing relevant parameters phi (float): C-D weights epsilon (float): public housing assement factor r (float): mortgage interest ...
f3a2ace349bcf25bffda855d3bad11cbeef9b6c0
27,478
def _split_uri(uri): """ Get slash-delimited parts of a ConceptNet URI. Args: uri (str) Returns: List[str] """ uri = uri.lstrip("/") if not uri: return [] return uri.split("/")
91b48fff83041fe225a851a9e3016e3722bd9771
27,479
def file_len(fname): """ Calculate the length of a file Arguments: Filename: Name of the file wanting to count the rows of Returns: i+1: Number of lines in file """ with open(fname) as f: for i, l in enumerate(f): pass return i + 1
d571b048649c636c359e731d72693aed26ef1595
27,480
def create_initializer(initializer_range=0.001): """Creates a `truncated_normal_initializer` with the given range.""" return tf.compat.v1.truncated_normal_initializer(stddev=initializer_range)
70eb43744202c5abb34fca4bb0bce6b2b2d31d72
27,481
from typing import List def collapse_columns( df: ContactsTable, names: List[str], new_name: str ) -> ContactsTable: """ This function assumes that df has both columns and indexes identified by the same `names`. They will all be added together to create a new column and row named `new_name`. Eg.: ...
7dd38ec18ca26b4757f7b743813401e6d7b2a7d4
27,482
import time def current_date(pattern="%Y-%m-%d %H:%M:%S"): """ 获取当前日期 :param: pattern:指定获取日期的格式 :return: 字符串 "20200615 14:57:23" """ return time.strftime(pattern, time.localtime(time.time()))
9a554e91e0842fe52f822f4403366695c92a609b
27,483
def ubi(funding_billions=0, percent=0): """ Calculate the poverty rate among the total US population by: -passing a total level of funding for a UBI proposal (billions USD), -passing a percent of the benefit recieved by a child and the benefit recieved by an adult AND taking into account that funding wil...
3cdb9ea40085dce37f5746ff74b37f18c87e6c48
27,484
def local_disp_centr(x, y, image, disp_n, size_k, mode): """ Returns a tuple: (disp_l, centr_l) """ border_pixels = image[x-size_k//2 : x+size_k//2+1, y-size_k//2 : y+size_k//2+1] if mode == 'robust': percentiles = np.percentile(border_pixels, [75, 50, 25]) disp_l = percentiles[2] ...
c74c72d732b3c7ec9cf7c4b10a13e9b38af1a3d9
27,486
import aiohttp async def get_music_list() -> MusicList: """ 获取所有数据 """ async with aiohttp.request("GET", 'https://www.diving-fish.com/api/maimaidxprober/music_data') as obj_data: if obj_data.status != 200: raise aiohttp.ClientResponseError('maimaiDX曲目数据获取失败,请检查网络环境') else: ...
44b6f42377391ab3eccda8f8fb770dc2ab238019
27,487
import csv import ast def split_data(data_index,data_dir,amount): """ Split data into 'train' and 'test' sets. Data index = csv filename Data dir = directory in which data is stored Amount = percentage of data to be imported ( to reduce memory usage ) """ lfiles = [] ...
70aa1df0b666b231b0ec5d8b3d6bfec7409e26c9
27,488
def isValidPasswordPartTwo(firstIndex: int, secondIndex: int, targetLetter: str, password: str) -> int: """ Takes a password and returns 1 if valid, 0 otherwise. Second part of the puzzle """ bool1: bool = password[firstIndex - 1] == targetLetter bool2: bool = password[secondIndex - 1] == targetLetter ...
81f85c3848909b5037f13ed641ec3a1b77dff3b1
27,489
import json from typing import OrderedDict def read_yaml_or_json(url: str) -> dict: """Read a YAML or JSON document. :param url: URL or path; if `url` ends with '.yaml', the document is interpreted as YAML, otherwise it is assumed to be JSON. :return: a dictionary with the document contents. ...
27cb578e7194e1f1635cfd4d083c846f4bb5fdf2
27,492
def diagEst(matFun, n, k=None, approach='Probing'): """ Estimate the diagonal of a matrix, A. Note that the matrix may be a function which returns A times a vector. Three different approaches have been implemented: 1. Probing: cyclic permutations of vectors with 1's and 0's (defaul...
631d11b6f9201404ec75d9ffbc04b8c77b82e244
27,493
def delete_a_recipe(category_id, recipe_id): """Method to handle delete permanently a single recipe""" user_id = decode_auth_token(request.headers.get("Authorization")) if isinstance(user_id, int): recipe = Recipe() response = recipe.delete_recipe(category_id, recipe_id) return respo...
216e1b40a49bd477d4bdd5c748672ae4286b8e46
27,494
def hydrate_datatrust_state(data={}): """ Given a dictionary, allow the viewmodel to hydrate the data needed by this view """ vm = State() return vm.hydrate(data)
69091f66cce513eafb7e14c13e43fa5a4ce9d2f6
27,495
def preprocess_data(X, Y): """ This method has the preprocess to train a model """ X_p = X # changind labels to one-hot representation Y_p = K.utils.to_categorical(Y, 9) return (X_p, Y_p)
f2288be9fdb752ea67ddd0d493375d019a5981ca
27,496
import json def readLog(logPath): """Reads a file containing an array of json objects. \ Used with the 'gcloudformatter' function. Args: logPath: file system path to map file Returns: An array of json objects """ logger.info("Reading log {}".format(logPath)) with ope...
9e946ae1735025be2f9b4b5f271c19bbc64d4a61
27,497
from typing import List import csv from datetime import datetime def save_traces_file(traces_file_name, animals_list: List[Animal]): """ Saves TRACES compatible import file, based on animals in animals_list :param traces_file_name: :param animals_list: :return: """ def save_traces_file_ca...
8af33024ee413300147c7dcb6cd34a211609ef03
27,498
def get_KNN(X, k): """Identify nearest neighbours Parameters ---------- D : array, [n_samples, n_features] input data k : int number of nearest neighbours Returns ------- knn_graph : array, [n_samples, n_samples] Connectivity matrix ...
9b62be61837a0c500451f286eb1a043a81939e19
27,499
def createMode(): """Required to initialize the module. RV will call this function to create your mode.""" return AudioForSequence()
aa3095a7b0754da8cb4739c3e3198f8304a21661
27,500
def pre_process(cpp_line): """预处理""" # 预处理 cpp_line = cpp_line.replace('\t', ' ') cpp_line = cpp_line.replace('\n', '') cpp_line = cpp_line.replace(';', '') return cpp_line
4c0db8ae834286106472aba425c45a8eeded3183
27,501
def actions_db(action_id): """ replaces the actual db call """ if action_id == 'not found': return None elif action_id == 'state error': return { 'id': 'state error', 'name': 'dag_it', 'parameters': None, 'dag_id': 'state error', ...
cd9e8e87ce5535648b4e7a5e58d0333b80e9ae1c
27,502
def parse(argv): """ Parse command line options. Returns the name of the command and any additional data returned by the command parser. May raise CommandParsingError if there are problems. """ # Find the command if len(argv) < 1: full = None cmd = command_dict[None...
09867eeb1a17f7609c5f99fc9c5b2d80442a7b44
27,504
def _get_answer_spans(text, ref_answer): """ Based on Rouge-L Score to get the best answer spans. :param text: list of tokens in text :param ref_answer: the human's answer, also tokenized :returns max_spans: list of two numbers, marks the start and end position with the max score """ max_s...
aa99c85dec40bcb01457b31b358aac9b50238284
27,505
from functools import cmp_to_key def order(list, cmp=None, key=None, reverse=False): """ Returns a list of indices in the order as when the given list is sorted. For example: ["c","a","b"] => [1, 2, 0] This means that in the sorted list, "a" (index 1) comes first and "c" (index 0) last. """ ...
7bcc6f44f02be4fb329b211b5caadf057d6d9b9a
27,506
import requests def curl_post(method, txParameters=None, RPCaddress=None, ifPrint=False): """ call Ethereum RPC functions """ payload = {"jsonrpc": "2.0", "method": method, "id": 1} if txParameters: payload["params"] = [txParameters] headers = {'Content-ty...
1b403e91cf542127038b7a79b54a28b69105be39
27,508
def intRoexpwt2(g1, g2, p, w, t): """ Integral of the roexpwt filter Oxenham & Shera (2003) equation (3) Parameters ---------- g1, g2 - Limits of the integral in normalized terms (eg.: g1=0.1,g2=0.35) p - SLope parameter t - Factor by which second slope is shallower than first w - relative ...
fc6e312a5f5134e43d63569b35fc1e6e7af74084
27,509
def create_connection(query): """ クエリを発行するためのデコレータ :param query: クエリストリング :return: """ def wrapper(*args, **kargs): config = Config() connection = pymysql.connect(host= config.nijo_db_host, user= config.nijo_db_user, password= config...
8e6d0733eef3210b2ee074430cf79dd3bdbf8dfc
27,510
def numentries(arrays): """ Counts the number of entries in a typical arrays from a ROOT file, by looking at the length of the first key """ return arrays[list(arrays.keys())[0]].shape[0]
e3c9f2e055f068f12039741ff9bb1091716263d5
27,511
import torch def gen_gcam_target(imgs, model, target_layer='layer4', target_index=None, classes=get_imagenet_classes(), device='cuda', prep=True): """ Visualize model responses given multiple images """ # Get model and forward pass gcam, probs, ids, images = gen_model_forward(imgs, model, d...
f685b17b030643fbd29eed0b69be140422b3e730
27,513
def get_insert_query(table_name): """Build a SQL query to insert a RDF triple into a PostgreSQL dataset""" return f"INSERT INTO {table_name} (subject,predicate,object) VALUES (%s,%s,%s) ON CONFLICT (subject,predicate,object) DO NOTHING"
423ccbf1d69e85316abdb81207d6e0f04729c2b8
27,514
import torch def q_mult(q1, q2): """Quaternion multiplication.""" w = q1[0] * q2[0] - q1[1] * q2[1] - q1[2] * q2[2] - q1[3] * q2[3] x = q1[1] * q2[0] + q1[0] * q2[1] + q1[2] * q2[3] - q1[3] * q2[2] y = q1[0] * q2[2] - q1[1] * q2[3] + q1[2] * q2[0] + q1[3] * q2[1] z = q1[0] * q2[3] + q1[1] * q2[2] ...
cafafa392d9e41e7680c703415ed6df87207f0d0
27,515
def is_object_group(group): """True if the group's object name is not one of the static names""" return not group.name.value in (IMAGE, EXPERIMENT, OBJECT_RELATIONSHIPS)
d111781f39feef74698b625186f3937a85fa8713
27,516
import time def plugin_poll(handle): """ Extracts data from the sensor and returns it in a JSON document as a Python dict. Available for poll mode only. Args: handle: handle returned by the plugin initialisation call Returns: returns a sensor reading in a JSON document, as a Python d...
05f3974c919fdd9c5ee4b853b37bf07bbd45738c
27,517
def info(token, customerid=None): """ Returns the info for your account :type token: string :param token: Your NodePing API token :type customerid: string :param customerid: Optional subaccount ID for your account :return: Return contents from the NodePing query :rtype: dict """ ur...
d106bf166e846bc2b3627af4e43e74074a519cd1
27,519