content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def calc_q_max_FC(region, mode, A_HCZ, R_type): """ファンコンベクターの最大能力 Args: region(int): 省エネルギー地域区分 mode(str): 運転モード 'い', 'ろ', 'は' A_HCZ(float): 暖冷房区画の床面積 R_type(string): 居室の形式 Returns: ndarray: ファンコンベクターの最大能力 """ # 付録Mに定める放熱器の最大能力 q_max_rad に等しいものとする return appendix...
fbf70067293eba693cfeff7e0ceeab15884bb360
54,600
def _pop_funclist(f): """_pop_funclist(f) -> list or None Evaluates and returns a list constant defined at the beginning of a function. If the function doesn't begin with a list, or the list refers to parameters or other locals, a None is returned. The returned list is removed from the function cod...
8e5865215de527feef95820a5fa2b59c549bb9ac
54,601
def levenshtein_message_distance(m1, m2): """ Use python-levenshtein package to calculate edit distance """ return levenshtein.distance(m1,m2)
0e0bf202b74c5004481c07bcf3f816b48114ac01
54,602
def gen_task1() -> np.ndarray: """Task 1: return constant symbol.""" seq = rand_syms() return np.concatenate(([1], seq, [2]))
7be0ba92565f6af30dede310130492c9fbbd9fa2
54,603
def read_pfam_output(pfam_out_file): """Read the output of PFAM scan.""" cols = ["seq_id", "alignment_start", "alignment_end", "envelope_start", "envelope_end", "hmm_acc", "hmm_name", "type", "hmm_start", "hmm_end", "hmm_length", "bit_score", "E-value", "significance", "clan"...
2568db3f47a11d7795ad1d990ae36aa9edc3441c
54,604
def merge_consecutive_timestamps(timestamps): """ Merges consecutive timestamps in a list if they're less than 2 seconds apart Example: [(0,5), (5,10), (20,30)] gets combined into [(0,10),[20,30] """ result = [] i = 0 while i < len(timestamps): (start, end) = timestamps[i] #...
9ec3817dd62771d7269892ae590a160ea581fa53
54,605
import torch def PadToCentered(tensor: torch.Tensor, length: int, dimension: int, fill=0.0)-> torch.Tensor: """ Pads a tensor along the indicated dimension to a particular length, embedding the initial tensor in the center. :param tensor: the tensor to pad :param length: How long the tensor will...
3cf22413fc9fc3106d746359ba565f07f494bf2c
54,606
def _compute_cp(obs_result, obs_norm, infos, expert_plot=False): """Compute the closure phases array (across the cube) and averaged cp using the normalized bispectrum (see _normalize_all_obs()). Note that for the CP, the extracted quantities are computed after the normalisation.""" bs = obs_norm["bs"] ...
f03cabef21dd60000d54aeaf90207731416108cb
54,607
def add_sampledata_times(samples, sites_time): """ Return a tsinfer.SampleData file with estimated times associated with sites. Ensures that each site's time is at least as old as the oldest historic sample carrying a derived allele at that site. :param tsinfer.formats.SampleData samples: A tsinfer...
6eb5ae3f2ecb4f3d9c6d2cfc666f73ea287ad4c5
54,608
def convert_uint16_to_array(value): """ Convert a number into an array of 2 bytes (LSB). """ return [ (value >> 0 & 0xFF), (value >> 8 & 0xFF) ]
ac851a650be9ac37a96e26ffcf8c00483a580be0
54,609
def getPublishersBooksIDs(publisher, base=ALEPH_DEFAULT_BASE): """ Get list of :class:`DocumentID` objects of documents with given `publisher`. Args: publisher (str): Name of publisher which will be used to search Aleph. base (str, optional): base on which will be search performed. Defa...
887e4b608f74e03d1a7eb0c022e39d22f688c4ca
54,610
def czt(x, m=None, w=1.0, a=1, axis=-1): """ Compute the frequency response around a spiral. Parameters: ---------- x: array The set of data to transform. m: int The number of points desired. Default is the length of the input data. a: complex The starting point in the com...
a28e49c58270b8c8019f896593e62c822528a55d
54,611
def gettitle(): """Return title string to be used in the timeline""" return "%s [ %s, %s - %s ]" % ( params['TIMELINE.pretitle'], params['TIMELINE.title'], gettimelinestartdate().toString(), gettimelineenddate().toString())
e7462cffb6e08fe59fb67f0fb3da0dba599e0f7e
54,612
def refresh_token(token) -> dict or None: """ JWT access token refresh method. Args: token: payload containing jwt access token to refresh and refresh token. Returns: refreshed jwt token payload. """ user = token['user'] user_refresh_token = token['refresh_token'] try:...
3604d34b8ee9d76cae2f537c02c84b343f9a1f84
54,613
def scntl_read(root): """ Read and interpret the :ref:`control file ".scntl" <Control>`. Args: root (str): root name for the control file Returns: dict[dict]: dictionary of all dictionaries obtained from all the control blocks Todo: Error checking with !TRA and !RADIAL doe...
d4a701b71a53c9a2054cce5d8eed51b6fcf68780
54,614
def resume(): """ Resume a paused timer, re-activating it. Subsequent time accumulates in the total. Returns: float: The current time. Raises: PausedError: If timer was not in paused state. StoppedError: If timer was already stopped. """ t = timer() if f.t.stop...
afdf7969d62427ee0b9d527d756ca4f3e77f4018
54,615
def encode_side(side): """ Return side index by letter :param side: 'n' | 'o' | 's' | 'w' :return: 0 | 1 | 2 | 3 """ if side and isinstance(side, str): side = str.lower(side) else: raise SideValueError side_list = ['n', 'o', 's', 'w'] try: retur...
92d031bff824ff897ba489bc700c71b3bbaee3b0
54,616
def mmr_df_filter(df, years, start_date, end_date): """Return dataframe filtered by given years, start_date and end_date. df is mmr dataframe (mandatory) years is a list of Workout_date years to include in plot (mandatory) e.g. years=[2020, 2021] - if no value is given (years=No...
6fb939b01731f6c3d4153a6fbcbcca7e64af9696
54,617
def loggedReactor(reactor): """ Construct and return a wrapper around the given C{reactor} which provides all of the same interfaces, but which will log all traffic over outgoing TCP connections it establishes. """ bases = [] for iface in providedBy(reactor): if iface is IReactorTCP:...
0948f9f070bab308ad4acc97f762633e48c7efec
54,618
from typing import Union from typing import BinaryIO from typing import IO from typing import Set from typing import Dict import hashlib def hash_io( io: Union[BinaryIO, IO[bytes]], types: Set[HashType], chunk_size: int = DEFAULT_CHUNK_SIZE, ) -> Dict[HashType, str]: """Calculate the requested hash ty...
c4e7b897f95b55bbdf29ecd9025675b0ded5e279
54,619
import os def load_all_gfx(directory, colorkey=(255,0,255), accept=(".png",".jpg",".bmp")): """ Load all graphics with extensions in the accept argument. If alpha transparency is found in the image the image will be converted using convert_alpha(). If no alpha transparency is detected image will be ...
2bb62e67b8ea85a0e535ca4eb375690131807865
54,620
def process_head_element_content(placeholder_storage, markup): """ Process content for elements inside <head>. Processes CMD syntax which does not produce new elements, i.e. escapes, line continuations, and whitespace, and then protects the content with a placeholder. """ markup = process_escapes(pl...
27ac55590fb62ae9194b5a1549268e412c03f701
54,621
def central_derivative(xs, ys): """ central derivative at x[1] """ return (ys[2]-ys[0])/(xs[2]-xs[0])
ef3e397eda004f9f2afbd2a5bd5c8c23b72755c5
54,622
def print_from_tests(pav_cfg, tests, outfile, json=False): """Print the statuses given a list of test objects or a single test object. :param dict pav_cfg: Base pavilion configuration. :param Union(test_run.TestRun,list(test_run.TestRun) tests: Single or list of test objects. :param bool json: ...
4ed044189bf9fa3c9c418956cc80414580294471
54,623
def plot_boxplot(data, ylabel, title, log_scaling=True): """ Args: data: Dict of list of numbers. """ fig, ax = plt.subplots(1, 1, figsize=(8, 6), dpi=300) plt.xticks(rotation=90) ax.boxplot(data.values(), labels=data.keys()) ax.set_ylabel(ylabel) ax.set_title(title) if log...
1e08ac5415edfff41432445189652d135827906b
54,624
def submit_dataframe_operation(comms, coroutine, df_list, extra_args=()): """Submit an operation on a list of Dask dataframe Parameters ---------- coroutine: coroutine The function to run on each worker. df_list: list of Dask.dataframe.Dataframe Input dataframes extra_args: tupl...
33173645ed1b71eb0f6d4cc7d2ceed44dbf76358
54,625
from typing import Union def encode(message: Union[str, bytes]) -> bytes: """Encodes a message (str or bytes) to zbase32.""" if isinstance(message, str): message = message.encode('ASCII') elif not isinstance(message, bytes): raise TypeError("message must be string or bytes") barr = _m...
5c278e16822fc721b4219dda28c0b154eeaf7020
54,626
from typing import Callable def linear_adjoint(fun: Callable, *primals) -> Callable: """Conjugate transpose a function that is promised to be linear. :func:`scico.linear_adjoint` differs from :func:`jax.linear_transpose` for complex inputs in that the conjugate transpose (adjoint) of `fun` is returned. ...
8c3f3d8db725bd107c5236e352c240df010b0f01
54,627
def parse_sra(path_to_config): """ Parses genetorrent config file. Returns list of samples: [ [id1, id1 ], [id2, id2], ... ] Returns duplicate of ids to follow UUID/URL standard. """ samples = [] with open(path_to_config, 'r') as f: for line in f.readlines(): if not line.iss...
59c5ddc2e2efca6cada28db4ea225bc0590f1fb2
54,628
def queryTagHistory( paths, # type: List[String] startDate=None, # type: Optional[Date] endDate=None, # type: Optional[Date] returnSize=-1, # type: Optional[int] aggregationMode="Average", # type: Optional[String] returnFormat="Wide", # type: Optional[String] columnNames=None, # type:...
b9bc9fdda65dcd5e8b5918b75bd38b20e514b0a7
54,629
import torch def hard_sigmoid(tensor: torch.Tensor, inplace: bool = False) -> torch.Tensor: """ Applies HardSigmoid function element-wise. See :class:`torchlayers.activations.HardSigmoid` for more details. Arguments: tensor : Tensor activated element-wise inplace : ...
5f4d87749ddca014076f46e0af6e9b3c4308ddf7
54,630
def define_ns_gnn_encoder(gnn_name): """ return specified model class for GNNs with node-sampling. """ if gnn_name == 'gat': return SamplingGAT elif gnn_name == 'sage': return SAGE elif gnn_name == 'mpnn': return SamplingMPNN else: raise NotImplementedError("n...
2f89a708e8c417b246291cffa0eaee21eb9f56c7
54,631
def egaussian(p, x, y, e=None): """ Compute the deviation between the values y and the gaussian defined by p, x: p is a three- or four-component array, list, or tuple. Returns: y - p3 - p0/(p1*sqrt(2pi)) * exp(-(x-p2)**2 / (2*p1**2)) if an error array, e (typ. one-sigma) is entered, the returned va...
80b155783eb27de52f2553047c505cf9c8e0203e
54,632
import time def timing(f): """Wrapper for functions to measure time""" def wrap(*args, **kwargs): time1 = time.time() ret = f(*args, **kwargs) time2 = time.time() logger.debug('%s took %0.3f ms ~ %0.3f min ~ %0.3f sec' % (f, (time2-time1)*1000.0, ...
de2c7c94c8f82d767a7783814a3ea65b3a727abe
54,633
import sys def prioritize_results(inbound_dataframe, today_value) -> object: """Prioritize results by due date and write to a CSV file.""" inform("Prioritizing") # sort by due-date for prioritization to be compliance against DHS inbound_dataframe = inbound_dataframe.sort_values(by='dueDate') infor...
b18a994851dcb8b6c336f3f451edbffa3008ada8
54,634
from typing import Optional def _get_html_tree(html_content: str) -> Optional[lxml.html.HtmlElement]: """Obtain the HTML parse tree for the given HTML content. Args: html_content: The content to parse. Returns: The corresponding HTML parse tree. """ html_content = html_content.st...
842805b6b364d7cc277633daca6a42999b9d7972
54,635
def get_county_by_id(ct_fips): """County in GeoJSON, by id""" log.debug("entering get_county_by_id() IP=%s" % get_ip()) con = get_db_con() sql = "SELECT s.ct_fips, s.ct_name, s.sq_mi, s.pop, s.pop_male / s.pop as pct_male, s.pop_female / s.pop as pct_female, s.pop_sm, " \ "chr.hs_graduate as chr...
afcc018b8148d860ca2494472a35e90b12507ecf
54,636
from typing import Callable def get_int(prompt: str | None = None, min_value: int | None = None, max_value: int | None = None, condition: Callable[[int], bool] | None = None, default: int | None = None) -> int: """Gets an int from the command line. :param promp...
e1c2beada06088804709d572a848f827a3946fb2
54,637
from typing import Tuple def _normalize_array(array_data: Array, normalizer: Tuple[Array, Array]) -> Array: """Helper function for normalize_graph().""" shift, scale = normalizer return (array_data - shift) / scale
2a206eb871dc40cc29d064b64e26b8e89f4979e1
54,638
def linear_gauss_policy_fit_with_prior(train_data, prior_mean, prior_cov, niw_prior_m, niw_prior_n0, cov_reg, action_size, observation_size): """ @brief: pi = p_x.dot(x) + f_c, cov(f) = f_cov """ cov_reg_matrix = np.zeros([action_...
2a00bb1c386212f85c1cf2f14fbefdb1552fa377
54,639
import copy def get_action_dict_junc(observation_builder, obs): """ Takes an agent handle and returns next action for that agent following shortest path: - if agent status == READY_TO_DEPART => agent moves forward; - if agent status == ACTIVE => pick action using shortest_path.py() fun available in pr...
62fefab9f18c300989df8ba1fbf212592c0fe755
54,640
import re def scan(file, blocksize=10000): """Get the number of molecules in an sd file""" pat = re.compile("^[$][$][$][$]", re.MULTILINE) text = file.read(blocksize) count = 0 while text: g = pat.findall(text) count += len(g) if text[-1] == "$" and text[-4]!='$': ...
e3b1af1e65e28146d609a0c2841f195ad783b59e
54,641
from fontTools.ufoLib.filenames import userNameToFileName from robofab.tools.glyphNameSchemes import glyphNameToShortFileName def testGLIFFileName(rangeName, toFile=None): """ test on glif file name """ # support both UFO2 as UFO3 try: # UFO3 ufoLib def nameToFileName(name): ...
c2b6d83e4372baf3895b3647d07404686230418a
54,642
def Checksum(bbytes: bytes, length: int) -> bytes: """Checksum Create checksum of [length] bytes from the 256 bit hash of the byte slice. Returns the lower [length] bytes of the hash Errors if length > 32.""" hash = ComputeHash256Array(bbytes) return hash[len(hash)-length:]
c0993c3252a8794b7762068f27a44dbb3dbcb724
54,643
def peters_g(n, e): """ Compute g(n, e) from Peters and Mathews (1963) Eq.20 ### Parameters: n (`int/array`): Harmonic(s) of interest e (`float/array`): Eccentricity ### Returns: g (`array`): Relative power of gravitational radiation at the nth harmonic """...
f13d2b8222d74a0e3e45a264e84149bd0f37a460
54,644
def normalized_sat_value_difference_index(Blue, Green, Red): """transform red, green, blue arrays to normalized sat-value difference Parameters ---------- Blue : np.array, size=(m,n) blue band of satellite image Green : np.array, size=(m,n) green band of satellite image Red : np...
41ba01231db8252b77defaae62698c042b461a98
54,645
def make_game(environment_data, level): """Initialises the game. Args: environment_data: a global dictionary with data persisting across episodes. level: which game level to play. Returns: A game engine. """ sprites = {SUSHI_CHR: [SushiSprite], AGENT_CHR: [AgentSprite]} upda...
57d1ddaba3ebe4b083506f3bba03dcdaced256de
54,646
import pickle def filter_by_freq(word_list, chained_words, min_freq): """ Replaces words occuring less than min_freq with the unknown tag <unk> and dumps the replaced words to a file (via pickle) """ unk_list = [] print("Filtering words occuring less than %d times..." % min_freq) for word in w...
76186e9cb0dcc494575bc00c6994601e4a891483
54,647
def score_tile( tile_cij, clr, expected_indexed, expected_value_col, clr_weight_name, kernels, max_nans_tolerated, band_to_cover, ): """ The main working function that given a tile of a heatmap, applies kernels to perform convolution to calculate locally-adjusted expected and...
4597a4a929d610c9316b5e40a80696ed46e94c61
54,648
def display_time(seconds, granularity=1): """ Turns seconds into weeks, days, hours, minutes and seconds. Granularity determines how many time units should be returned. EG: # 2 time unites, week and day 1934815, 2 = '3 weeks, 1 day' # 4 time units 1934815, 4 = '3 weeks, 1 day, 9 hours, 26 minute...
d4b94ffafcdbda99526ecc906ed8379d7fc5edab
54,649
import torch def euler2mat(angle): """Convert euler angles to rotation matrix. Reference: https://github.com/pulkitag/pycaffe-utils/blob/master/rot_utils.py#L174 Args: angle: rotation angle along 3 axis (in radians) -- size = [B, 3] Returns: Rotation matrix corresponding to the euler a...
4b503e13948b68c8961796c4aa8cee687740e3b3
54,650
from typing import List from typing import Optional from typing import Any def execute_cli_command(args: List[str], input_data: Optional[str] = None, ret_val: int = 0, output_string: bool = True) -> Any: """Execute a Nessie CLI command.""" if output_string: return _run(args, input_data, ret_val).outpu...
054a3fc9f2b9d1de33b347c94a4ac4b7bd62900f
54,651
import tempfile import os import base64 def get_key(password=None, filekey=None): """ get_key """ key = None filekey = filekey if filekey else tempfile.gettempdir() + "/.private.key" if password and isinstance(password, (str,)): kdf = PBKDF2HMAC(algorithm = hashes.SHA256(), length = 3...
84de9b74be408ef82dc1c9db1c6fcc8d32966835
54,652
def transformer_latent_decoder(x, encoder_output, ed_attention_bias, hparams, name=None): """Transformer decoder over latents using latent_attention_type. Args: x: Tensor of shape [batch,...
51e82f5ceea3c6a3a1e473208936f1fdb5f63303
54,653
def errorbar(*args, **kwargs): """ Plot curves with error bars Example:: import numpy as np x = np.linspace(-5, 5, 1000) errorbar(x, -1+x**2/20+.2*np.random.rand(len(x)), x/20) show() """ axe = gca() curve = make.merror(*args, **kwargs) axe.add_p...
09130681d4c205008083b101d152664131ee83ed
54,654
def privkey_to_wif(privkey, netcode="BTC"): """ Get private key from bitcoin wif. Args: privkey (str): Hex encoded private key Return: str: Private key encode in bitcoin wif format. """ prefix = networks.wif_prefix_for_netcode(netcode) secret_exponent = encoding.from_bytes_32(h...
055125ac7e76341366ad5c9ea5289f44427260fd
54,655
def join_values(values): """Return the values as a space-delimited string.""" return " ".join((str(v) for v in values))
60fd4acbafc4619c134ae67d224df408cad12ab0
54,656
def get_cookie_opener( gs_username, gs_token, gs_toolname=None ): """ Create a GenomeSpace cookie opener """ cj = http_cookiejar.CookieJar() for cookie_name, cookie_value in [ ( 'gs-token', gs_token ), ( 'gs-username', gs_username ) ]: # create a super-cookie, valid for all domains cookie = ...
7e9fd52ebccd8fc5065673f727d2cff720f53246
54,657
def translate(im,trans): """translates 3d images""" shape_ = im.shape zmax=shape_[0] xmax=shape_[1] ymax=shape_[2] zmin,xmin,ymin=0,0,0 trans_=np.array(np.round(trans),dtype=int) zmin-=trans_[0] zmax-=trans_[0] xmin-=trans_[1] xmax-=trans_[1] ymin-=trans_[2] ymax-=tra...
b2f438b20ff2d7cca65e7dd410c5826790f7224d
54,658
def add_base32_padding(base32_input_no_padding): """Return a base32 string with the correct padding Parameters: base32_input_no_padding (str): base32 string without padding """ result = base32_input_no_padding while ((len(result) % 8) != 0): result += '=' return result
9f98d4c705b5932171954aee3fb90c34681ea7fc
54,659
import torch def compute_similarities(audio_embeds, query_embeds, audio_lens): """ Compute a batch of audio-text alignment matrices. :param audio_embeds: tensor, (N, T, E). :param query_embeds: tensor, (N, Q, E). :param audio_lens: numpy 1D-array, (N,). :return: tensor, (N, T, Q). """ ...
52d8180a99426408c767f50c78acade3f217a74d
54,660
def get_request_body(db, light, prev_light_state): """ Build the request body for the hue api.""" body = {} brightness = calc_brightness(db=db, light=light) color_temp = calc_color_temp(db=db, light=light) if light.ct_controlled: body['ct'] = color_temp if light.bri_controlled: ...
9ee0e518a94ff4d3aec5adaa2ba83fc813a0778d
54,661
from re import T def T_inv(e, d, b): """Inverse transform b.""" return T(rotate_right(e, d+1), N-d-2, b)
64da217aac3e63a29aa56b089fedd937c47fc6ca
54,662
def magic(num_lst, n, k): """对 num_lst 使用 k 次魔力""" a = num_lst[:] for j in range(k): b = a[1:] # 又一种“移动”方法 b.append(a[0]) for i in range(n): a[i] = (a[i] + b[i]) % 100 # 无差别对 100 取余 return a
1f8e1e766add89e0f03a6ef778fe6c1100886125
54,663
import asyncio import aiohttp async def test_timeout(aresponses): """Test request timeout from AdGuard Home.""" # Faking a timeout by sleeping async def response_handler(_): """Response handler for this test.""" await asyncio.sleep(2) return aresponses.Response(body="Goodmorning!")...
5e1ddf44797bd23badb180a2fc99897286cfad1d
54,664
def format_number(number): """ Round number to two decimals :param number: input number :return: number rounded to two decimals """ return format(float(number), '.2f')
621e48e46aef43c6ede38b62a3608b8e193d7df7
54,665
def apply_sort(query, sort_spec): """Apply sorting to a :class:`sqlalchemy.orm.Query` instance. :param sort_spec: A list of dictionaries, where each one of them includes the necesary information to order the elements of the query. Example:: sort_spec = [ {'...
26ae50a733b41b78dfe1ddf77ac0f0957ffa38bc
54,666
def _find(searchable_models, tupls): """ # start with the output of the _dice doctest >>> p = [('a', 'b', 'c'), ('a', 'b'), ('b', 'c'), ('a',), ('b',), ('c',)] >>> class MockModel_A(object): ... ... def __repr__(self): ... return "<MM:A>" ... ... @classmethod ......
75b58b4377abe5f42e9611f44140a9034d930d0e
54,667
def tags_index(): """Show a page with info on all tags""" tags = Tag.query.all() return render_template('tags/index.html', tags=tags)
9ee801d9ad80bf4b72825791a6e985536399de04
54,668
def build_estimator(model_dir, model_type): """Build an estimator.""" if model_type == "wide": m = tf.estimator.LinearClassifier( model_dir=model_dir, feature_columns=feature_columns) elif model_type == "deep": m = tf.estimator.DNNClassifier( model_dir=model_dir, feature_columns=fe...
807d092211d7c4a112a4cdfe31b3db853a347f07
54,669
def double_variants(word): """get variants for the variants for a word""" return set(s for w in variants(word) for s in variants(w))
a9cfd85508b2d3f035ae918411725e94faa57860
54,670
def cc(bond, bond_length): """" Divides the CC bond range into five types for better coverage of physically relevant bonds """ # TODO: Automate division process if bond == "CC": if bond_length < 1.206: bond = "C1" elif bond_length < 1.325: bond = "C2" ...
68f18e07066cf80cd52b8ba5a7f0e3c0b56ff50c
54,671
def callBigDlFunc(bigdl_type, name, *args): """ Call API in PythonBigDL """ jinstance = JavaCreator.instance(bigdl_type=bigdl_type).value sc = get_spark_context() api = getattr(jinstance, name) return callJavaFunc(sc, api, *args)
0a3ce4b3045f932b6c3452b948c7216d55fe8f26
54,672
def k_fold_cross_valid(k, epochs, verbose_epoch, X_train, y_train, learning_rate, weight_decay, batch_size): """Conducts k-fold cross validation for the model.""" assert k > 1 fold_size = X_train.shape[0] // k train_loss_sum = 0.0 test_loss_sum = 0.0 for test_idx in range...
ee760d69ea9489525f7ad9313bf0f49e92e748f7
54,673
def format_indentation(string): """ Replace indentation (4 spaces) with '\t' Args: string: A string. Returns: string: A string. """ return string.replace(" ", "&nbsp;&nbsp;&nbsp;&nbsp;")
501f8b3a11f03fef295df771d76ac3a63f8209f3
54,674
def remove(app_id): """ Remove a bundle ID or command as being allowed to use assistive access. app_id The bundle ID or command to remove from assistive access list. CLI Example: .. code-block:: bash salt '*' assistive.remove /usr/bin/osascript salt '*' assistive.remove c...
ab13aff426383371a491bb3a80d2101f87f24141
54,675
from typing import Optional def get_sync_group(database_name: Optional[str] = None, resource_group_name: Optional[str] = None, server_name: Optional[str] = None, sync_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = No...
84e7adb466efd34377542361cf0e5bfde7b4320e
54,676
def kneel_down(score_diff, timd, secs_left, dwn): """Return 1 if the offense can definitely kneel out the game, else return 0.""" if score_diff <= 0 or dwn == 4: return 0 if timd == 0 and secs_left <= 120 and dwn == 1: return 1 if timd == 1 and secs_left <= 87 and dwn == 1: ...
2865d32484015f0e4a8f1cd28d68ec1a57847ce4
54,677
from typing import Union from typing import TextIO from typing import Collection from pathlib import Path import logging def create_wrappers_for_header_file(path: Union[str, PathLike[str]], out_dir: str, include_dir: Union[str, PathLike[str]], ...
7610e71cba6bac96ea04123a43c904ed02220715
54,678
def get_top_ngrams(vectorizer, top_n=5): """ Get highest ranking ngrams of a feature matrix :param vectorizer: vectorizer object :param top_n: amount of top n-grams to return :return: top n-grams """ indices = np.argsort(vectorizer.idf_)[::-1] features = vectorizer.get_feature_names() ...
2b391b7aba863ad576e445731d9ca8be4fd0c203
54,679
def variational_kmeans(mesh, vector_field, n_clusters, iters, tol): """ An instance of VariationalKMeans. """ return VariationalKMeans(mesh, vector_field, n_clusters, iters, tol)
8562c39ee35c24514c5526d900df16dd64bd7db5
54,680
import re import os def replace_ids(fpath): """ TODO """ youtube_id_expr = r"([a-zA-Z0-9_-]{11})\.mp3" ytid_map = dict() lines = [] with open(fpath, "r") as f: for line in f: match = re.search(youtube_id_expr, line) if match: youtube_id = os...
b0add76d3c16cbfd9bf3c0b88a110f620422219b
54,681
import os def _get_api_key(): """Returns string with API key to access ResultStore. Intended to be used in Kokoro envrionment.""" api_key_directory = os.getenv('KOKORO_GFILE_DIR') api_key_file = os.path.join(api_key_directory, 'resultstore_api_key') assert os.path.isfile(api_key_file), 'Must add --ap...
fd48e9059c0f47b9245b725ca1e60ef8c3a23ef5
54,682
import re def _parse_function_doc(doc): """ Takes a function and returns the params and return value as a tuple. This is nothing more than a docstring parser. TODO docstrings like utime(path, (atime, mtime)) and a(b [, b]) -> None TODO docstrings like 'tuple of integers' """ # parse round...
6ebc56fcef4690a1322fba72c1d0beb00d05dd23
54,683
import time import torch import sys def train(train_loader, model, criterion, optimizer, epoch, opt, CUTMIX = False,cam = None): """one epoch training""" model.train() batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() end = time.time() ...
fd210d7c55acbb3efe16cff3b6967908c26f5840
54,684
def get_contours(image): """ For input image use `cv2.findContours` function to get a list of contour objects. Args: image (numpy.ndarray): Input image. Returns: list of contour objects: List of contour objects extracted from the image. """ # NOQA E501 #...
afa929c6ca9c9c0ab52d18617c7e4d5d1b0552b5
54,685
def encode(n, b=58): """ :param n: 压缩的数字 :param b: 进制 最大58 :return: 对应进制字符串 """ result = '' x = int(n) while True: x, y = divmod(x, b) result = baseList[y] + result if x <= 0: break return result
9f2af45ef63297ed6774c75d382fe1984edf6f84
54,686
import subprocess import csv def check_results(conf, expected_lines): """ Checks the benchmark results """ clean_dir("results") set_working_directory("reporting") subprocess.check_call(["Rscript", "check_results.R"]) if expected_lines: last_measurement_filter = [str(conf.Sequences...
4218777bb5c0d1334f3142d3b3dda1d89c14d691
54,687
import logging from operator import sub def convert_currency_string_to_float(money: str): """ Utility function which gives a numerical representation of the given string containing a money value. Handles conversion from 'million'. :param money: String containing the money value :return: Float repr...
5df8fc50b8cc06f9da5a6d4ea83b8a13763310d8
54,688
import math def quantity_string(quantity, unit, computer_prefix=False): """Return a human-friendly string representing a quantity by adding prefixes and keeping the number of significant figures low. 'computer_prefix' determines whether each prefix step represents 1024 or 1000. Examples: >>> ...
04aa8743e045c2aaf80115984c30f091d695de77
54,689
import yaml import os def loadConfigFile(filename): """ Load just a single YAML configuration file """ with open(filename, 'r') as f: config = yaml.load(f) # Validate if not config: raise ValueError( 'This configuration file contains no meaningful information') # Process includes inc...
989387f6dbc2a7bf4aecf59c4f79c9ce17ffb342
54,690
import re def get_current_version_by_config_file() -> str: """ Get current version from the version variable defined in the configuration :return: A string with the current version number :raises ImproperConfigurationError: if version variable cannot be parsed """ debug('get_current_version_b...
8871d5eb1b127ae01fd625a4a5a8664fb20dc721
54,691
def populate_context(dbot_scores: list, domain_entries: list, file_entries: list, url_entries: list, email_entries: list = None) -> dict: """ Populate the context object with entries as tuples - the first element contains global objects and the second contains PhishLabs objects :par...
3c72887e7d508a5e449b74da096165ed7d0229c3
54,692
import pytz def round_datetime(dt, period, tzinfo=pytz.UTC, force=False): """ Rounds a datetime to the nearest period. Valid periods are: minute, minute-15, hour, day, week :type dt: datetime :param dt: A naive or aware datetime object. :type period: str :param period: Options are mi...
ec856a37d7e9bb7c4077e753327287ac3048b9b0
54,693
def force_categorical_determination(table): """ Find string columns using 'computationally expensive' approach """ source_shape = table.shape columns_number = source_shape[1] if len(source_shape) > 1 else 1 categorical_ids = [] non_categorical_ids = [] # For every column in table make check for...
012fb261c39e2bd5106df4e88af9703821158146
54,694
def _apply_words(nums): """ Get the corresponding words for a list of 11-bit numbers. Args: nums (int[]): list of 11-bit numbers Returns: str[]: list of words """ return [index_to_word[n] for n in nums]
626fab36ea86b7b22e17b6d924dfa72f4437dbb7
54,695
def FCN_32s(input_shape, n_class, encoder_name, encoder_weights=None, fc_num=4096, weight_decay=1e-4, kernel_initializer="he_normal", bn_epsilon=1e-3, bn_momentum=0.99, dropout=0.5): """ implementation of FCN...
4baac4a8472a7cddb938fa0f69fa5f9f68863999
54,696
import inspect import os import requests import json def leave_workspace(workspace_id): """Exit from a member of the workspace - ワークスペースのメンバーから抜けます Args: workspace_id (int): workspace ID Returns: Response: HTTP Respose """ app_name = multi_lang.get_text("EP020-0001", "ワークスペース情報:"...
f9644cff54f4acd19b7945669d3417f2c60d32fc
54,697
import numpy def L2d1(x): """ First derivative of the quadratic lagrange basis function. :param x: points to interpolate :type x: numpy array (npoints) :return: basis weights :rtype: numpy array(npoints, 3) """ L1 = 1-x return numpy.array([ 1.0 - 4.0 * L1, 4.0 ...
d74adfa7c22d9686a1428f21777f1d3bc3cda4d7
54,698
import requests import sys def get_calls(article_name, number_of_lines=7): """ returns hover data in raw format this is used in app callbacks to display hover summary data in a text box just enter article name like "Atom" or "Proton" """ S = requests.Session() URL = "https://en.wikipedia.o...
05ba3b39b39c387af4d91b91d3dd4eb03a9cda27
54,699