content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def getDocument(html, css=None): """ returns a DOM of html, if css is given it is appended to html/body as pre.cssutils """ document = etree.HTML(html) if css: # prepare document (add css for debugging) e = etree.Element('pre', {'class': 'cssutils'}) e.text = css ...
cb496707972f3f2331a2f53361468b178d466d03
3,613,200
def using_cumisc(handle=None): """Temporarily set chainer's CUBLAS handle to scikit-cuda. The usage is similar to :func:`using_device`. Args: handle: CUBLAS handle. If ``None`` is specified, it uses CUBLAS handle for the current device. Returns: CumiscUser: Misc user objec...
8cb4bd00f63e8a856ea315eec9452b17f6ece08d
3,613,201
def remove_list_duplicates(my_list: list) -> list: """ Removes any duplicated values from a list. """ return list(dict.fromkeys(my_list))
e3dd86733117fce7bad2860d860b98b349efcfb5
3,613,202
from typing import Union from typing import Iterable def sql_from_binary_tree(X: Union[list, np.ndarray], children_left: Union[list, np.ndarray], children_right: Union[list, np.ndarray], feature: Union[list, np.ndarray], ...
177b6172846a8187fd398b2d098c46f522633eec
3,613,203
from typing import Callable import click def target_id_option(command: Callable[..., None]) -> Callable[..., None]: """ An option decorator for choosing a target ID. """ click_option_function: Callable[ [Callable[..., None]], Callable[..., None], ] = click.option( '--target...
1fe67f22e00b4d4930af347c482d28e30032508d
3,613,204
def tdnsresp(**kwargs) -> dns.Message: """ Returns: mitmproxy.dns.Message """ default = dict( timestamp=946681201, id=42, query=False, op_code=dns.op_codes.QUERY, authoritative_answer=False, truncation=False, recursion_desired=True, ...
ae4f0080b37fc7fd9f2efa6ec1daf85e990c130b
3,613,205
import builtins import os def complete_command(cmd, line, start, end, ctx): """ Returns a list of valid commands starting with the first argument """ space = ' ' out = {s + space for s in builtins.__xonsh_commands_cache__ if get_filter_function()(s, cmd)} if ON_WINDOWS: ...
35432f24e2620a6869de5614aac03aec1b1d612d
3,613,206
def __fetch_query_from_uuid(uuid: str) -> bigquery.BigQueryResult: """ Fetches a cached BigQuery result from its UUID. Args: uuid (str): The UUID of the query to be retrieved. Returns: (BigQueryResult): The corresponding BigQuery result object. """ # Fetch cached qu...
c7f0c5bb1ac94dea6c251a8ecf0c52cdad1fd6c7
3,613,207
def _get_keys(response): """ return lists of strings that are the keys from a client.list_objects() response """ keys = [] if 'Contents' in response: objects_list = response['Contents'] keys = [obj['Key'] for obj in objects_list] return keys
dfa1f066ac19138920509935b1dbbdde52591f18
3,613,208
def round_updown_to_x(num_in, x, direction="up"): """ Rounds a given value (num_in) to the nearest multiple of x, in a given direction (up or down) :param num_in: Input value :param x: Value to round to a multiple of :param direction: Round up or down. Default: 'up' :return: Rounded number ...
206b582843eea234b5b655dddd54eea6e32eec42
3,613,209
async def player_stop(): """ Full route: /music/player/resume Request (JSON): None Stop (unload) the current song. """ # no json expected was_playing = await player.player_stop() if was_playing: return with_status(None, 200, StatusType.OK) else: return with_status...
320c71a1ca669b6a2b386f8b3ab500b78a1b70b4
3,613,210
async def revocation_registries_created(request: web.BaseRequest): """ Request handler to get revocation registries that current agent created. Args: request: aiohttp request object Returns: List of identifiers of matching revocation registries. """ context = request.app["requ...
0adc59382ffc991fb7d5c7e191aa960b0db2d516
3,613,211
def vwap(bars): """ calculate vwap of entire time series (input can be pandas series or numpy array) bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ] """ typical = ((bars['high'] + bars['low'] + bars['close']) / 3).values volume = bars['volume'].values return pd.Series(index=ba...
06d6554b301c229f8679f5a987f651ac09956b4e
3,613,212
import jqmobile from xml.dom import minidom import re def get_svn_revision(path=None): """ Returns the SVN revision in the form SVN-XXXX, where XXXX is the revision number. Returns SVN-unknown if anything goes wrong, such as an unexpected format of internal SVN files. If path is provided, it...
20db6d1b3e4d9190d736ac43b93626eacb652a6d
3,613,213
def checkFrameRateChange_Lenient(op, graph, frm, to): """ Confirm frame rate has not changed. :param op: :param graph: :param frm: :param to: :return: """ if _checkFrameRateChange(op, graph, frm, to): return (Severity.WARNING, 'Frame Rate Changed between nodes')
f8e5a32906e2b1d231b20796ea8fb3481b6ee6d1
3,613,214
def img2port(img_url): """ mimvp.com的端口号用图片来显示, 本函数将图片url转为端口, 目前的临时性方法并不准确 """ code = img_url.split("=")[-1] if code.find("AO0OO0O")>0: return 80 else: return None
60768ee0723808ef7d1f3e74287b7a6e576f94c5
3,613,215
def coverage(tiles): """Sum of length of all tiles. """ accu = 0 for tile in tiles: accu = accu + tile[2] return accu
b2cbb6b926e070d9fc457523bb60169ef9b70821
3,613,216
import pytz from datetime import datetime async def stations(id: int, date_from: str = None, date_to: str = None, param: str = 'pm25'): """ Get pollution data for a specific station and a date range :return: json of format {"data": [{date, time, value}, ...] """ if not date_from or not date_to: ...
4971e81dc696c32f072f38b2da40f7a2a710bc7e
3,613,217
def update(head: str, td: Tag) -> Attr: """ Update a developing part dictionary based on a cell from the product table :param head: The head string from the <th> :param td: The <td> from the product table :return The applicable CSS class, and the dictionary with kvs to update. """ cl...
7f3ba66b1158f08f9e2f7f13afd7908a1c0ba6a9
3,613,218
import errno def load_doc(name, doctype = None, project = None): """Load document Args: name: Name of document (file must exist in :/username/project/docs.zip: file). doctype: Type of document. 'pdf', 'docx', etc. project: reference to ArthurProject object. Returns: list:...
31245e378be54c8933dfe1e38644c32f22bce110
3,613,219
def lognormalize_chroma(C): """Log-normalizes chroma such that each vector is between -80 to 0.""" C += np.abs(C.min()) + 0.1 C = C / C.max(axis=0) C = 80 * np.log10(C) # Normalize from -80 to 0 return C
977f8fac9b16bfd32c331d6ee713864a61f930d0
3,613,220
def kei_zeros(nt): """Compute nt zeros of the Kelvin function kei x """ if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): raise ValueError("nt must be positive integer scalar.") return specfun.klvnzo(nt,4)
0a92514543ee9ff0bacdd18a1eb9136be366f6f6
3,613,221
def _reflect_particle_diffusive(arr, **kwargs): """ Reflect particles given in a diffusive manner. Args: arr (np.ndarray): 2D-ndarray of shape *number of particles x 5*. Each particle is describes by : [x, y, vx, vy, vz] Returns: [np.ndarray]: returns the modified array by default (in most...
0b2fd08c2c6b367275ad139b0915432653fb164c
3,613,222
import urllib import logging import json def SearchTargets(query_term, base_url=BASE_URL, fout=None): """Search names.""" n_out=0; tags=None; df=None; offset=0; while True: url_next = (base_url+'/targets/?search={}&limit={}&offset={}'.format(urllib.parse.quote(query_term), NCHUNK, offset)) rval = rest.U...
57aa83d559b1f22df44ba440118750b783105d70
3,613,223
def get_int() -> int: """ Gets a lone integer from the console (the integer is on its own line) :return: The int value that was read in from the console """ line = input().strip() return int(line)
1bffcb1c5c1e7910a11358d4616a747b38ba3d73
3,613,224
import tqdm def plot_tract_profiles( X, groups, group_names, group_by=None, group_by_name=None, bins=None, quantiles=None, palette="colorblind", ci=95.0, subplot_positions=None, nrows=None, ncols=None, ): """Plot profiles for each bundle and each metric. Parame...
9a174dadabc0463b7072ad451b8a03d8c0610ed9
3,613,225
def regex_search_matches_output(get_output, search): """ Applies a regex search func to the current output """ return search(get_output())
6f054990d3454a447656567b3ceb12a38c2809a5
3,613,226
def crop(img, start_y, start_x, h, w): """ Crop an image given the top left corner. :param img: The image :param start_y: The top left corner y coord :param start_x: The top left corner x coord :param h: The result height :param w: The result width :return: The cropped image. """ ...
cb3a05989f1538bcec34102c33291d500a21c59d
3,613,227
def univariate (mu, alpha, omega, T, numEvents=None, seed=None): """ generates events based on univariate hawkes process with an exponential decay kernel Parameters: ----------- mu: float The base intensity. alpha: float The self-excitation. omega: float The bandwidth parameter. T: float The fi...
207c47cea8c3860e97ae81d6667d9721dae6f651
3,613,228
import sys def normalize_path(path): """ Normalizes the path separator to match the Unix standard. """ if sys.platform == 'win32': return path.replace('\\', '/') return path
b565b2eaefa21708005ecab3538cc34a410b8318
3,613,229
def validate_existing_delivery(start, end, queryset): """Validate if exists a deliver at that time by date""" delivery_exist = False msg = "" if len(queryset): for deliver in queryset: deliver_start = format_date(deliver.start) deliver_end = format_date(deliver.end) ...
5f8a612ed84e47f73fd084d2319e3f0c2b446204
3,613,230
def separate_by_class(train): """ For each dependent variable (last column of DF) value, map to corresponding rows of the DF """ classifications = set(train[:, -1]) return {c: train[train[:, -1] == c] for c in classifications}
1ed0fd5c077a0d7391955687ec190ded873a9bee
3,613,231
def plot_profile(datasets, fields=None, times=None, timerange=None, fig=None,ax=None, fieldlimits=None, heightlimits=None, fieldlabels={}, cmap=None, stack_by_datasets...
996d267a8bd21e24d26aad56e38e6d67fdec3997
3,613,232
def abs(v): """Create abs in the sense of distance instead of just vanishing the sign. Create abs in the sense of distance instead of vanishing the sign. Used to calculate the length of coordinates, or anything that can be interpreted as coordinate. Args ---- v: iterable of float, comp...
effdbb763a1b9e1f04137139eef3f94e662e3cc7
3,613,233
from pathlib import Path def confirm_index_opts(taxonomy_name, opts): """Confirm expected keys are present in opts for indexing.""" file_key = "taxonomy-%s-file" % taxonomy_name url_key = "taxonomy-%s-url" % taxonomy_name for key in {"taxonomy-path", file_key}: if key not in opts: ...
904412613fabe115d368d3dfa77ac9be3f355f15
3,613,234
import json def podcast_spider(site): """ 更新源内容 """ resp = get_with_retry(site.rss) if resp is None: logger.info(f"RSS 源可能失效了`{site.rss}") return None feed_obj = feedparser.parse(BytesIO(resp.content)) for entry in feed_obj.entries: # 有些是空的 if not entry: ...
6151350572181b0776b075af1daa80ac0559fcbf
3,613,235
import xml.etree.cElementTree as ET def getDataSetUuid(xmlfile): """ Quickly retrieve the uuid from the root element of a dataset XML file, using a streaming parser to avoid loading the entire dataset into memory. Returns None if the parsing fails. """ try: for event, element in ET.ite...
7386efea461056f8f4b472923b8f4a30d6d80d3b
3,613,236
def train_mnist_single_machine(data_dir, num_epochs, use_fake_data=False): """Train a ConvNet on MNIST. Args: data_dir: string. Directory to read MNIST examples from. num_epochs: int. Number of passes to make over the training set. use_fake_data: bool. If True, generate a synthetic dataset. Returns:...
ab4485e898d54122730b9cc82f9d8a7cd2c04140
3,613,237
def pick_word(probabilities, int_to_vocab): """ Pick the next word with some randomness :param probabilities: Probabilites of the next word :param int_to_vocab: Dictionary of word ids as the keys and words as the values :return: String of the predicted word """ return np.random.choice(list(int_to_vocab.values())...
84c9c46133d799313a490c7cc7a03b2dcb776415
3,613,238
def get_max_cost_matrix(a, bottom_right=True, top_left=False): """Return matrix with maximum cost for paths from all nodes""" maxcost = 9 * a.shape[0] * a.shape[1] cost = np.zeros(a.shape, int) + maxcost if bottom_right: cost[-1, -1] = 0 if top_left: cost[0, 0] = 0 return cost
156ef55507558d7b194d51f8dd6533bb6b34925e
3,613,239
def get_synthetic_data(data_size: int, features_num: int) -> (Matrix, ColumnVector): """ A method which creates a random matrix of ``size data_size x features_num`` and a ``random 1 x data_size`` random vector. Args: data_size(int): The number of samples in the data - ``n``. features_nu...
bddea3bff042d219f8b9992fa17aecadcbe41e0a
3,613,240
from typing import Union def injection_volume(val: Union[float, str]) -> Union[int, str]: """ Handle special case for injection volume of ``-1``, which indicates "As Method". :param val: :type val: :return: :rtype: """ if val in {-1, "-1"}: return "As Method" else: return int(val)
b09240b9c8bd0eebfb7880494f75b105e313b228
3,613,241
from typing import Optional def validate_charge_efficiency(charge_efficiency: Optional[float]) -> Optional[float]: """ Validates the charge efficiency of an object. Charge efficiency is always optional. :param charge_efficiency: The charge efficiency of the object. :return: The validated charge e...
46e40fcdc65ffec453f1bac9bd03f6a9297647fd
3,613,242
def get_module_info(*args): """ get_module_info(ea, modinfo) -> bool """ return _ida_dbg.get_module_info(*args)
3d93e2552418968fb9ad2f7343e7f826f00fbe7a
3,613,243
import sys import traceback def main(argv=None): """The main entrypoint to Coverage. This is installed as the script entrypoint. """ if argv is None: argv = sys.argv[1:] try: status = CoverageScript().command_line(argv) except ExceptionDuringRun: # An exception was ca...
e155231ded988ee4f54b9be1e8d44cf1c39eaeee
3,613,244
def set_graph_attributes(species): """ For a molecular species set the π bonds and stereocentres in the molecular graph. Arguments: species (autode.species.Species): """ logger.info('Setting the π bonds in a species') def is_idx_pi_atom(idx): return is_pi_atom(atom_label=sp...
1513a26fb657b6b318511156271eb7ad86eda8e5
3,613,245
def yices_check_context_with_model(ctx, params, mdl, n, t): """Check satisfiability modulo a model. Check whether the assertions stored in ctx conjoined with a model are satisfiable. - ctx must be a context initialized with support for MCSAT (see yices_new_context, yices_new_config, yices_set_c...
50b7204122de1d1eb295a1d04b9a3b1dd5e2b738
3,613,246
def is_abs_blank(str): """ To check out whether str is NONE or empty or blank. """ return not is_not_abs_blank(str)
f308b5c472a435a2d913d40213b247af304abc84
3,613,247
def get_vnf_package_data(vnf_package_obj, **kwargs): """Get the vnf package data from a FakeVnfPackage dict object. :param vnf_package_obj: A FakeVnfPackage dict object :return: A list which may include the following values: [{'packageContent': {'href': 'string'}, 'self': {'href': '...
7c95c8ac7885f3f468d599e6ff58597ec6bd80dd
3,613,248
def get_latest_pip_command() -> lib_bash.BashCommand: """ >>> assert get_latest_pip_command() is not None >>> assert 'pip' in get_latest_pip_command().command_string """ try: pip_command = lib_bash.get_bash_command('pip3') return pip_command except ValueError: pass ...
ee41c577725b8dfa05dbffe5dc6f663021990cd9
3,613,249
def desympify_homfly(p): """Takes a sympy HOMFLY polynomial p, and returns a tuple of (coefficient, index_a, index_z) tuples. """ if p == 1: return (1, ) p = p.expand() terms = p.as_terms()[0] coeffs = n.zeros((len(terms), 3), dtype=int) for i in range(len(terms)): entry ...
4ece442195ac11288153bffd4e97231fecb9f136
3,613,250
import json import random import os from bs4 import BeautifulSoup import re def gen_test_comments(max_samples=999999999): """ Generates sample dataset from parsing the SQuAD dataset and combining it with the SPAADIA dataset. The data is then shuffled, and two arrays are returned. One c...
4c7be653908d0e4e2216aaf3ca2eb9558eb1a90b
3,613,251
def triples_from_centre(k): """ Gets all the triples k positions from the centre :param k: The distance from the center. :return: A set of all the triples from the centre. """ return all_triples(neighbours_from_centre(k))
84592182ba2b197566e8c40142614bb9d5aea761
3,613,252
def _minmaxhash_add_ngrams( heap: list, heapmap: dict, maxsize: int, nsize: int, subs, nsubs: int, hashbuffer, heaptop, extracthash, make_elt, update_elt, replace, anynew, minmax_op) -> int: """ Process/add elements to the sketch (See warning below). ...
0a9000ab3f151c0c6621532930aa9c26fe3cdda8
3,613,253
def load_data(labels_fl, test_size=None): """ Load and split the data into training and testing sets. :param labels_fl: directory of the labels (measurement logs) CSV file :param test_size: size of the testing set :return: training and testing input and output sets if a test_size parameter is prov...
facd2a3ea47abb3a6b5e4e69831c044e687291e9
3,613,254
def stream_name_to_dict(stream_name, separator='-'): """Transform stream name string to dictionary""" catalog_name = None schema_name = None table_name = stream_name # Schema and table name can be derived from stream if it's in <schema_nama>-<table_name> format s_parts = stream_name.split(separ...
389826fe03f1f5e1c704e2ce54f90da443e1d23c
3,613,255
from typing import Union from typing import List from typing import Any from typing import Dict from typing import Optional def run_value_search_from_example( inputs: Union[List[Any], Dict[Text, Any]], output: Any, settings: Optional[settings_module.Settings] = None, **kwargs) -> ValueSearchResults: ...
13d90d6f22a188e8422fdba5aee47608234744af
3,613,256
import stat def compress(filename, output_filename=None, img_width=2048, img_format='png'): """Compress images in IPython notebooks. Parameters ---------- filename : string Notebook to compress. Will take any notebook format. output_filename : string If you do not want to overwrit...
1c6cd34271e69ae136c8a6521a7485bf730f55d6
3,613,257
def top_prior(name, z_shape, learn_prior="normal", temperature=1.0): """Unconditional prior distribution. Args: name: variable scope z_shape: Shape of the mean / scale of the prior distribution. learn_prior: Possible options are "normal" and "single_conv". If set to "single_conv", the g...
4dc849c8fb605f64f4f329d722d3a95933c8d23e
3,613,258
def create_label(text = ""): """ Create a Label. :param text: Label Text :return: QTWidget Label """ label = QLabel(text) return label
98fa4817ad7f76e2f5c77b808f7f58a75bbfd6a2
3,613,259
import re from re import DEBUG def getLatestStatus(logfile): """Read and parse MS Teams logfile to get the last presence status. Returns: (status, logTime) """ status = "" try: with open(logfile, "r") as f: for line in f: if "(current state: " not in l...
5057b94235149bbc3fe45d602293a5a809cb0274
3,613,260
import time def create_short_timestamp_uuid(): """ Generate short uuid plus timestamp """ short_uuid = create_short_uuid() return "{}{}".format(short_uuid, time.time())
fae722699c2f8c2e05deb32524f38aeb6845362e
3,613,261
def batch_action_list_assign_election_to_rows_process_view(request): """ :param request: :return: """ # admin, analytics_admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer authority_required = {'verified_volunteer'} if not voter_has_authority(requ...
0d74313a273dedc08c5c9925a5ec8986b8fc10eb
3,613,262
from typing import Union from typing import Optional import typing def best_partition(G: Union[nx.DiGraph, nx.Graph], starting_alpha: Optional[float] = 0.1, threshold_function: Optional[ typing.Callable] = np.mean, cluster_function: Optional[typing.Callable] = None, weight: Optional[str] = "wei...
ce4886490e1ee3c11b0f1cdd446be8d05f2eab82
3,613,263
import signal import time import json import textwrap def process_nick_list(nicks, platforms=None, rutaDescarga="./", avoidProcessing=True, avoidDownload=True, nThreads=12, verbosity=1, logFolder="./logs"): """ Process a list of nicks to check whether they exist. This method receives as a parameter a ser...
0af2ee1190b3b46dbf3742082b44d1b290941305
3,613,264
import copy def make_hash(o): """ Makes a hash from a dictionary, list, tuple or set to any level, that contains only other hashable types (including any lists, tuples, sets, and dictionaries). https://stackoverflow.com/questions/5884066/hashing-a-dictionary """ if isinstance(o, (set, tupl...
93b32d35f8c23886ae0cf0bae7cd3427ffc54599
3,613,265
def uivec4(x, y, z, w): """returns an ivec4-compatible numpy array""" return np.array([x, y, z, w], dtype=np.uint32)
783a316f883a07dfafca75d0743f1483e6b7489a
3,613,266
def compute_spectral_wcut(A, w=None, K=2, max_iter=50): """ Solves weighted ratio cut as a relaxed trace maximization problem with Yu and Shi postprocessing.""" N = A.shape[0] if w is None: w = np.ones(N) L = np.diag(np.sum(A, axis=1)) - A # Solve eigenvalue problem w_inv_sqrt = w ** (-...
65542b3acfb96b4c09ddc4a9490d680d31ca2a7a
3,613,267
def relpath(target, base=os.curdir): """ Return a relative path to the target from either the current dir or an optional base dir. Base can be a directory specified either as absolute or relative to current dir. """ if not os.path.exists(target): raise OSError, 'Target does not exist: '+tar...
73df64bd8e6f7b52a6b9ec9c3e6bf3e5afff89ba
3,613,268
def mock(connectable, replace_new_patch_aliases=None): """Creates a mock selector that can be patched. This is intended to be used as a context manager with a given SQLAlchemy connectable (e.g. an engine, session, connection, etc). For example:: with pgmock.mock(engine) as mocker: mock...
4320901a2c36eca2c331298aabee94ca18a8d2af
3,613,269
import os def read_img(pat_id): """ read in the raw images :param pat_id: the id if the patient to read in :return: the images and the ground truth """ assert os.path.exists('../input/PnpAda_release_data/test_ct_image_n_labels/image_ct_{}.nii.gz'.format(pat_id)), "The specified patid doesnot e...
a139a23988247a9411b29088a8759607efef16d2
3,613,270
def map_statements(stmts, source, outfile=None): """Tabulate valid, invalid, and mapped sites from a set of Statements.""" # Look for errors in database statements sm = SiteMapper(default_site_map) valid_stmts, mapped_stmts = sm.map_sites(stmts) # Collect stats from SiteMapper itself sites = [] ...
1106bd3c545e5447fe24b3bc17462936e71849f0
3,613,271
def getCriterion(): """Criterion (Loss function) for training and validation""" def loss_func(output, target, batch_size): output_for_loss = output.view(-1, output.size(2)) # seq_len * N, ntokens target_for_loss = target.view(-1) # seq_len * N loss = F.cross_entropy(output_for_loss, targ...
feb9ee8f8de675cadb793cfe75d5d732f2ead609
3,613,272
import struct def parse_variable_array(buf, lenbytes): """ Parse an array described using the 'Type name<x..y>' syntax from the spec Read a length at the start of buf, and returns that many bytes after, in a tuple with the TOTAL bytes consumed (including the size). This does not check that the arr...
b9c0f27975f852bb92634244eaba4762031d2ce3
3,613,273
import os def encode_features(feature_points, src, patch_size=(41, 41), display_img=True, save_img=False): """ feature_points: list of keypoint/feature point around which we will take a patch of size 41x41 src: input image patch_size: a small img which will be encoded as feature vector consider o...
5fec7bb37b945419df08e3fc46474fe24df6dd54
3,613,274
def snake_split(s): """ Split a string into words list using snake_case rules. """ s = s.strip().replace(" ", "") return s.split("_")
af70dfa1190ec783b8431630be2ae92434af146a
3,613,275
def task_estimates(iterations=None): """Discrete task iteration converted to array""" task_iteration_list = [] for _ in range(iterations): r_float = random_float() min_val, max_val, a_val, b_val = 24, 90, 2, 4 beta_value = beta_values( random_number=r_float, ...
2e96596957628ee60507c44558ffc981d5bfa513
3,613,276
from typing import Tuple from typing import Optional def subroutine_definition(line: str) -> Tuple[bool, Optional[list]]: """ Indicates whether a line in the program is the first line of a subroutine definition and extracts subroutine name and the arguments. Args: line Returns: (Tr...
a6d62db40631cf31ba315c76e39a8f13e3e2a8c5
3,613,277
import decimal from typing import Iterable def try_parse(text, valid_types=None): """try to parse a text string as a number. Returns (valid, value) where valid represents whether the conversion was successful, and value is the result of the conversion, or None if failed. Accepts a string, and one opt...
c210a88c86b55404cf620f504da7e229a033eeed
3,613,278
import time def throttle(wait): """Second order decorator for rate-limiting a function within an asyncio concurrent app - The first call will always happen *without* delay. - Subsequent calls, within wait seconds, are dropped, even if argurments differ. - The final call will always execute, sometimes...
272c638a836bf8892f2cbcad63e57c1ad80fff56
3,613,279
import warnings def plot_tsne( arrays, legends, filename=None, use_umap=False, **kwargs ): """ Plot tSNE and return the figure. Parameters: arrays (List of ndarray): Vectors to be plotted. Each array will be colored and named differently. legends (List of s...
84b51b897640e7e2d4ee84485dfb931ac3f5fd12
3,613,280
def find_from(board, word, y, x, seen): """Can we find a word on board, starting at x, y?""" # This is called recursively to find smaller and smaller words # until all tries are exhausted or until success. # Base case: this isn't the letter we're looking for. if board[y][x] != word[0]: pr...
0e1911f90dd4eb4729d7e896e62bdc2b70ff8ee9
3,613,281
def hello(): """ Basic hello world route to check if server is running. """ return "Welcome to Codenames."
0b12cc94bc266485199c9737d2cc016c8b4da8fd
3,613,282
import json def vm_clone_handler(si, logger, linked, vm_name, datacenter_name, cluster_name, resource_pool_name, folder_name, datastore_name, custom_mac, ipv6, maxwait, post_script, power_on, print_ips, print_macs, template, template_vm, template_snapshot, mac_ip_pool, mac_ip_pool_results, adv_parameters): """ ...
ff98cfed59f63ac09c036b0791f8aa71630f584d
3,613,283
import os def get_hashsum_dictionary(): """Return a dictionary of hashes of file contents in the current directory and all its subdirectories.""" return { f: generate_hashsum(f) for f in [ os.path.join(root, name)[2:] for root, dirs, files in os.walk(".") ...
7eb27312cabe4c5b25943ea52db5c6826d92738f
3,613,284
from typing import List def partition_labels(S: str) -> List[int]: """ consumed: 68ms 64ms :param S: :return: >>> partition_labels('ababcbacadefegdehijhklij') [9, 7, 8] >>> partition_labels('eccbbbbdec') [10] """ first_index: int = 0 res = [] while first_index < len(S):...
cdc1154ce54116edcc7df52ee97727964289b891
3,613,285
from typing import List def orderings2() -> List[List[int]]: """Enumerates the storage orderings an input with rank 2.""" return [[0, 1], [1, 0]]
f85f26b79aa25d980877e57cbcdbdb9f7295ac7d
3,613,286
def building_2d_to_3d(citygml_writer, zone_shp_path, district_shp_path, tin_occface_list, height_col, nfloor_col): """ This script extrudes buildings from the shapefile and creates intermediate floors. :param citygml_writer: the cityGML object to which the buildings are gonna be created. ...
9ab4580431610632647d0f21c759de196bbb5225
3,613,287
def get_sloc_lines(path): """Determine the lines in file `path` that are source code. i.e. Not space or comments. This requires a parser for this file type, which exists for most source code files in the Pygment module. Returns: If a Pygment lexer can be found for file `path` ...
b85f923556b071cfb2bf25a28ec76830d31c2eed
3,613,288
from typing import OrderedDict def alpha_canonicalize(equation): """Alpha convert an equation in an order-independent canonical way. Examples -------- >>> oe.parser.alpha_canonicalize("dcba") 'abcd' >>> oe.parser.alpha_canonicalize("Ĥěļļö") 'abccd' """ rename = OrderedDict() ...
b374d3ea508aa010160fd4a59b549b68d7870fa1
3,613,289
def get_raster_records(host=config.PYCSW_URL, params=config.PYCSW_GET_RECORD_PARAMS): """ This function will return all records of raster's data :param host: pycsw server's entrypoiny url :param params: request parameters for GetRecords API request with json result :return: Dict -> list of records -...
f13a21d1be84dadd032d0d5898e966846d3e69df
3,613,290
def read_file(filepath): """Reads text file and returns each line as a list element. Parameters: filepath (str): path to file Returns list: list of strings """ data = [] with open(filepath, 'r', encoding='utf-8') as file_obj: for line in file_obj.readlines(): ...
da1db5ffb99b746271b0fd0f9779da4e6f520246
3,613,291
from sys import path import json def get_template( template_name, template_path=GRAPH_TEMPLATE_PATH, logger=ps_helper.DEFAULT_LOGGER ): """Fetch R code/metadata for building plots Args: template_name (str): basename for template to graph to template_path (str, optional...
53a02b2646dfb4588b36fbafc5bd1ca5f1cd6293
3,613,292
def _get_table_index(data_group, table_id): """Get attr table.""" table = _get_table(data_group, table_id) return dict( zip( list(map(lambda d: d['entity_id'], table)), table, ) )
300c87d8474b38570487453fbbb6e8d5cf37278e
3,613,293
def xml_api() -> XMLClient: """ Sets up a client to communicate with UK Carbon Intensity API using XML structure as the response format. """ return XMLClient()
bf577ed3b4e5e422dd1aa111e6af802680ed3868
3,613,294
def clear(num: int, start: int, end: int) -> int: """ Sets zeros on bits of num from start to end non inclusive """ if start == end: raise ValueError('Start value same as end') # Builds group of 1s the size of the start - end mask: int = (1 << (end - start)) - 1 return num & ~(mask << start)
68dd669bd9df5ce260daf09375c6ed872580e475
3,613,295
def delete_coa(): """ Delete a certificate of analysis from storage. """ # Remove certificate from storage. # Remove the certificate data. return NotImplementedError
3e8248b6cf87521aae31b4b4eabb601411f38d54
3,613,296
import json def get_incident_by_query(query): """ Get a query and return all incidents details matching the given query. Args: query: Query for the incidents that should be returned. Returns: dict. The details of all incidents matching the query. """ # In order to avoid perform...
0c2ec5190321a9a21ff691512fd8c490c587522d
3,613,297
def bethe_bloch(KE, Z=3., A=6., rho=1., relativistic=True, I=None): """Returns the differential energy loss per depth for protons of speed v (not relativistic) in a medium with density rho as a function of the kinetic energy KE = m * v**2 / 2 in MeV units https://en.wikipedia.org/wiki/Bethe_formul...
b96976c2cdc735aafc5678ebb9b8f1ddb47ab798
3,613,298
from pathlib import Path from datetime import datetime def loadhires(fn: Path, downsample: int = None) -> xarray.DataArray: """ loads and modifies GOES data """ if netCDF4 is None: raise ImportError("netCDF4 needed for hires data. pip install netcdf4") with netCDF4.Dataset(fn, "r") as f...
c57fe19cb6071a0548a9b1003d826da28c334342
3,613,299