content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def norm_except(param, dim, power): """Computes the norm over all dimensions except dim. It differs from pytorch implementation that it does not keep dim. This difference is related with the broadcast mechanism in paddle. Read elementeise_mul for more. """ shape = param.shape ndim = len(shap...
0c985766df8e8af0b979e4ec4cf54718506042b7
47,000
from pathlib import Path def file_hasher(file_path: Path, hash_method: str) -> FileHash: """ Convenience method to hash a file path. Parameters ---------- file_path : Path The `pathlib.Path` to a file. hash_method : {'blake2b','blake2s','md5','sha1','sha224','sha256','sha384','sha...
5a6ebcf3d077014f669bf6f7967ea310de2c25a7
47,001
def ClusterRemoveNodes(node_ips, by_node, remove_drives, mvip, username, password): """ Remove nodes from the cluster Args: node_ips: the MIPs of the active nodes to remove ...
0d74f828bb497d91d2718c24097c39160489dd6c
47,002
def get_network_detach_config_spec(client_factory, device, port_index): """Builds the vif detach config spec.""" config_spec = client_factory.create('ns0:VirtualMachineConfigSpec') virtual_device_config = client_factory.create( 'ns0:VirtualDeviceConfigSpec') virtual_device_co...
b937b290398dd04f48c1d7b7ec0bc5e2d496c97b
47,003
def sec_title(default_str: str) -> str: """Reads in a section title""" name = input('What would you like to title this section? ' + '(default is ' + default_str + ')\n') if name: return name return default_str
3dfc0ddcdc9cb9beb22b02892959334516b2a90b
47,004
import collections def _binary(ctx, srcs, tags, substitutions): """Shared implementation for the “elisp_binary” and “elisp_test” rules. The rule should define a “_template” attribute containing the C++ template file to be expanded. Args: ctx: rule context srcs: list of File objects denot...
9874f5e6f0ca87abe003ba0522a0c6603e2a1d60
47,005
def e_timeToString(dateString): """ input: string output: string description: format dateString to yyyymmddHHMM example: Wed Aug 29 07:23:03 CST 2018 ->> 201808290723 """ # define month list for get digital month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", ...
1a0c3f014bbd95a9da0eb767e1ce219cb0c70195
47,006
def bayesdb_variable_number(bdb, population_id, generator_id, name): """Return the column number of a population variable.""" cursor = bdb.sql_execute(''' SELECT colno FROM bayesdb_variable WHERE population_id = ? AND (generator_id IS NULL OR generator_id = ?) ...
75baa84cc0c0cd79712d48b31e3647011f5dd774
47,007
def continue_mof(): """ Update ASE Atoms object after failed job Returns: mof (ASE Atoms object): reset ASE Atoms object """ try: mof = read('CONTCAR') mof = continue_failed_magmoms(mof) except: mof = reset_mof() return mof
6cabce67e9c0b960e3457c102452b71750a4316f
47,008
def tachycardic_detector(patient_age, patient_heart_rate): """ Determines if patient is tachycardic based on their age and heart rate Args: patient_age: integer extracted from patient database entry patient_heart_rate: integer posted to patient database entry Returns: tachycardic...
595bf87d913cd94b9f4aa089a3f1cf32f342ccbf
47,009
import requests from io import StringIO def bond_repo_zh_tick(code="sz131802", trade_date="20201028"): """ 成交明细-每个交易日16:00提供当日数据 http://stockhtm.finance.qq.com/sstock/ggcx/131802.shtml :param code: 带市场标识的债券-质押式回购代码 :type code: str :param trade_date: 需要提取数据的日期 :type trade_date: str :ret...
4bac9f3aaedb9e4c8679e56d2daecb5b2fbe025a
47,010
def linear_bn_lrelu_dropout_block(in_feat, out_feat, normalize=True, alpha=0.2, p=0.5): """ linear + batchnorm + leaky relu """ layers = [nn.Linear(in_feat, out_feat)] if normalize: layers.append(nn.BatchNorm1d(out_feat)) layers.append(nn.LeakyReLU(alpha, inplace=True)) layers.append(nn.Drop...
3cd4d5a54cbbf7ef5f96d776b411e975376c1cdb
47,011
def detect_style(docstr): """Detect docstr style from existing docstring Parameters: docstr (str): docstring whose style we want to know Returns: class: one of [GoogleDocstring, NumpyDocstring, None]; None means no match """ docstr = dedent_docstr(docstr) for c in ...
a1b8c053d84bbf23d549de72f2dac7eab9f66398
47,012
async def prepare_mail(client: Facade, recipient: Portfolio) -> Mail: """Generate one mail to recipient using a facade saving the mail to the outbox.""" message = CreateMail().perform(client.data.portfolio, recipient).message( Generate.lipsum_sentence(), Generate.lipsum(100).decode()).done() envelop...
509ab91c92858fe0401f4861faf958cc7553f4b6
47,013
def resolve_doi(rec): """Resolve the doi of a given record""" doi = _get_doi(rec) if doi is not None: res = None try: res = urlopen(DOI_ORG + doi) except HTTPError as e: res = e return res.url
150b2855a18d0865c68140989114910672344942
47,014
import argparse def parse_args(): """ parsing and configuration :return: parse_args """ desc = "TensorFlow implementation of fast-style-GAN" parser = argparse.ArgumentParser(description=desc) parser.add_argument('--module', type=str, default='test', help='Module to...
fa256927a5b1c0e4cb34b341b7960617f8d238d1
47,015
def reject(): """ Reject the Tic-Tac-Toe Challenge """ global currentGame, resp, slackResponse, message, srb status = None obj = {"response_type": "ephemeral"} challenger = None opponent = None if slackResponse is not None: challenger = "@"+slackResponse['user_name'] oppon...
9dbe2dce9b027790d2b20d381964d79c1cd9c3a8
47,016
def make_string(seq): """ Don't throw an exception when given an out of range character. """ string = '' for c in seq: # Screen out non-printing characters try: if 32 <= c and c < 256: string += chr(c) except TypeError: pass # I...
422cedb92ad325438f76df32d4e184fd5aba3fb3
47,017
from typing import Any from typing import Dict def verify_params( handler: Any, request: HttpRequest, may_path_params: Dict[str, Any] ) -> Dict[str, Any]: """ Verify the parameters, and convert the parameters to the corresponding type. """ if is_class_view(handler): return _verify_params( ...
73e72c5ee9bff4ac98625b854308d2416dab4d9b
47,018
import re def get_short_name_for_type(instance): """ <class 'datatypes.strings.Smiles'> to smiles :return: short name """ try: return (re.search('\w+\'', str(instance)).group(0)[:-1].lower()) except: return None
9d98d95f712383a461623ce07ed3a0b4fcd521f6
47,019
import math def _CalcOrderedCorners(orig, inc, size, gpiline, gpxline, gpx, gpy): """ Convert three arbitrary control points to 4 ordered corner points ordered first il, first xl; last il, first xl, first il, last xl, last il, last xl. Also return the same 4 corners in annotation- and ordinal coordina...
57f61111639823b7f5f807c2105742dd99153b07
47,020
import pickle def save_to_pkl(pkl, obj): """Save experiment resource to file.""" with open(pkl, 'wb') as f: pickle.dump(obj, f) return obj
cf8c71617faa88a192e8214bd71a43e78c6acb67
47,021
def _from_json(dct): """convert string keys back to tuples""" if not isinstance(dct, dict): return dct for key in dct: break if isinstance(key, str) and key.startswith('('): return {_str2inttuple(key): dct[key] for key in dct} return dct
12d5a71db0074e74bab706fc9d7bdf556d6880e0
47,022
def pen(turtle, pen=None): """Return or set the pen's attributes. Arguments: turtle -- the turtle pen -- a dictionary with some or all of the below listed keys. **pendict -- one or more keyword-arguments with the below listed keys as keywords. ...
aa5563b5c487a4f7bc0e6afe4b9ad3a36799c97d
47,023
def upsample(cam, im_hw): """ Upsamples CAM to appropriate size Params: - cam: a x_x_ tf.Tensor - im_hw: target size in [H, W] format Returns: - Upsampled CAM with size _xHxW """ '''TODO: upsampling function call. Hint: look at resize functions in tf.image''' ...
5d8da93a55cc5ce8664f52697bbd2f59044cc475
47,024
def get_temp_exposure(fname): """Given a filename of a phenocam image Returns the temperature and exposure extracted from the image. """ title, temperature_line, exposure_line = _get_lines(fname) binary_temperature = _get_binary(temperature_line) temp_str = _extract_digits(binary_temperature) ...
e4cfc65a1f2cb54f8ac91fb879e3ed168ae92845
47,025
from typing import Tuple from typing import Dict import json def test_API_doc(): """Should work as expected.""" app = proxy.API(name="test") @app.route("/test", methods=["POST"]) def _post(body: str) -> Tuple[str, str, str]: """Return something.""" return ("OK", "text/plain", "Yo") ...
4522a932eba8e2e8968b920c2c2c9aeafeea532c
47,026
import torch import os def get_scores(): """Cacluates the BLEU and ROUGE scores for the configurations selected.""" opt = Opt.get_instance() read_in_jsons() mkdir() preprocess_json() write_source_and_target() perfect_trans_summary() if opt.proper_method: model = load_translator...
f8a84a2552abd1c9f02174afae886f045e3b68aa
47,027
import torch def gelu_fast(x): """ Faster approximate form of GELU activation function """ return 0.5 * x * (1.0 + torch.tanh(x * 0.7978845608 * (1.0 + 0.044715 * x * x)))
39f2e888b8e01edf0aaca4987c8a070850f58484
47,028
def get_pr_from_gh(pr_name, all_prs): """try to obtain existing open PR with name in GH""" prs = [ pr for pr in all_prs if pr_name in pr.title ] if len(prs) > 1: print(f'Warning: Too many PRs matched query "{pr_name}": {[p.html_url for p in prs]}. Returning first.') retur...
a55424610fe53225cab0e8fa9b477306ee39f6db
47,029
def mme_matches(case_obj, institute_obj, mme_base_url, mme_token): """Show Matchmaker submission data for a sample and eventual matches. Args: case_obj(dict): a scout case object institute_obj(dict): an institute object mme_base_url(str) base url of the MME server mme_token(str)...
31990111f6fd0289edc3a2d4a6747e24f42b6e6d
47,030
def size(archiveentry_handle, p5_connection=None): """ Syntax: ArchiveEntry <handle> size Description: Returns the list of sizes in bytes for each instance of the given archive entry. Return Values: -On Success: the list of file sizes """ method_name = "size" return exec_nsdchat([...
63da4e08792c7a589baf8f431f3bd8879834f512
47,031
from itertools import product def run_tntblast(nproc, fwd_list, rev_list, output_name, database_name, min_tm, max_tm, primer_conc, mv_conc, dntp_conc = 0.8, ...
8a8c3dfa22cd4d8b2c37874c8dad184c5ae9422b
47,032
def projects(request): """Display projects.""" return {}
749b2a1d5de2427d7059b04c72d28c49f7792187
47,033
def manage_github_orgs_add(request): """ Add an organization slot if the plan allows """ # # Redir https # if request.headers.get('X-Forwarded-Proto') is not None: # if request.headers['X-Forwarded-Proto'] != 'https': # return HTTPMovedPermanently(location="https://%s%s" % ( # ...
0e37a660926c43bf9a516de3b1e2c4eb9b4b011d
47,034
import argparse from pathlib import Path def get_args(): """ function to parse command line arguments Returns: _type_: parsed arguments """ parser = argparse.ArgumentParser() model_group = parser.add_mutually_exclusive_group(required=True) model_group.add_argument("--ckpt-path", type...
15c8b0926ba43c6caa509b725778fb63533e001b
47,035
def an(state, i, s, N): """Application of c_i,s on a given state (a linear superposition of |m>). Spin should be 0 for up and 1 for down.""" new_state = {} for basis_state in state: prefactor_an, state_an = fmulti_an(basis_state, i, s, N) if state_an != None: try: new_state[state_an] += prefactor_an * ...
65191266867355476931c42d8f50c53f7f48e790
47,036
from datetime import datetime def worker_function(event_type, assignment_id, participant_id): """Process the notification.""" db.logger.debug("rq: worker_function working on job id: %s", get_current_job().id) db.logger.debug('rq: Received Queue Length: %d (%s)', len(q), ...
72048a9abcfb03e8f6c65dafe5d0e8c5a09d5e47
47,037
def load_data(database_filepath): """ Load the CLEAN_MESSAGES table from the given SQLite Database """ # load data from database engine = create_engine('sqlite:///' + database_filepath) df = pd.read_sql_table("CLEAN_MESSAGES", engine) X = df['message'] Y = df.iloc[:,4:] return X, Y, Y.colu...
49a498a5ee978cf0ee555867382768d65e8871e3
47,038
import os def create_client(config, logger: Logger): """Generates an athena client object Args: config ([type]): [description] logger (Logger): [description] Returns: cursor: athena client object """ logger.info("Attempting to create Athena session") # Get the requi...
d8b5e66dad02518f05ff84d5146a82831637c96a
47,039
from typing import Optional def load_library(lib_location: Optional[str] = None): """Loads the `snap7.dll` library. Returns: cdll: a ctypes cdll object with the snap7 shared library loaded. """ return Snap7Library(lib_location).cdll
5dc6e6118bf58bdff5ffee9643c5029a9e440257
47,040
from typing import List def _interval_index(intervals: List[Interval], interval: Interval) -> int: """Find the index of an interval. Args: intervals: A sorted list of non-overlapping Intervals. interval: The interval for which the index into intervals will be found. Returns: The ...
aa1b1cf84a20d82a378307979ea0d31d48e33e2b
47,041
def diff_field(field1, field2): """returns true if field1 == field2""" return field1 == field2
6439d8c06c1d5b460141831acf83275795d19ccc
47,042
def block_layer(inputs, filters, bottleneck, block_fn, blocks, strides, training, name, data_format): """Creates one layer of blocks for the ResNet model. Args: inputs: A tensor of size [batch, channels, height_in, width_in] or [batch, height_in, width_in, channels] depending on data_form...
1331ce44f32d819ec8e66967676ba2e21f2ae9ae
47,043
import logging def unlock(password): """Unlock vault Returns: session (bytes) or False on error, Error message """ res = run(["bw", "unlock", "--raw", password], capture_output=True, check=False) if not res.stdout: logging.error(res) return (False, res.stderr) return res....
91fe38c23a0486e9b9634cfd2d5ef2da22202422
47,044
import random def example_classifier( task_info, mode="demo", default_split_prob={ "train": 0.9, "dev": 0.01, "test": 0.09, }, ): """ This will return the split this data belongs to. """ if mode == "demo" or mode == "all": if random.random() < default_s...
51aa25630158a4c295df85afc8684be59aca9d25
47,045
import os import logging import re def mol2_to_dataframe(mol2_file, parse_multi_model=False, parse_coord=False, columns=('serial', 'name', 'x', 'y', 'z', 'resSeq', 'resName', 'attype', 'charge', 'model')): """ Parse a Tripos MOL2 file format to a Pandas DataFrame Uses the same colum...
1cc0cb3c7867124713716b395641b702a6ff8b62
47,046
import os import copy import mmap def extractLogData(fname): """ Given a filename of a job file "path/job.NUMBER.out" extract the statistics of the job duration, etc. @param fname: Filename to extract @return: a dictionary with keys: - glidein_duration - integer, how long did the glidein ...
f0cf06b8257029f8620c774c59f4e7fdd54b618f
47,047
from typing import Optional def set_file_input_files( files: list[str], nodeId: Optional[NodeId] = None, backendNodeId: Optional[BackendNodeId] = None, objectId: Optional[runtime.RemoteObjectId] = None, ) -> dict: """Sets files for the given file input element. Parameters ---------- f...
4375b1b94fefc5d1039b99c013985681c3f92f0a
47,048
def islist(item): """Check if an is item is a list - not just a sequence. Args: item (mixed): The item to check as a list. Returns: result (bool): True if the item is a list, False if not. """ return isinstance(item, list)
02c4157e1867e7b113e9695f2fa8fd4aaccc043d
47,049
def group_parameters(model_params_dict_expanded): """Groups the parameters to be estimates in flat dictionary structure""" model_params_dict_flat = dict() model_params_dict_flat["gamma_0s"] = list( model_params_dict_expanded["const_wage_eq"].values() ) model_params_dict_flat["gamma_1s...
deb566114d1b40610bf6e1e814e85b1d8d3e3351
47,050
import pandas def read_static_info(static_tracks_file): """ This method reads the static info file from highD data. :param static_tracks_file: the input path for the static csv file. :return: the static dictionary - the key is the track_id and the value is the corresponding data for this track ""...
295757466640f90b0d3f95dd1d68aab0c90b329b
47,051
def nullify(grammar, state, visiting): """Return a list of results: each is the parsed part of reduced(state) if state can derive the empty string.""" parsed, chain = state = reduced(state) if not chain: return [parsed] (tag, x), tail = chain[0], chain[1:] if tag == 'push': if x in visit...
ec7b6a209b9562d6d4dcb08044fe8b832cb675e2
47,052
def positional_encoding(tensor, start_index, omega): """ tensor: a reference tensor we use to get shape. actually only T and C are needed. Shape(B, T, C) start_index: int, we can actually use start and length to specify them. omega (B,): speaker position rates return (B, T, C), position embedding ...
2f9132a4844a8255bc65f9ed5531808c2b2cf22f
47,053
def draw_smopy_basemap(G, figsize=(8, 6), zoom=10, ax=None): """Draw a basemap with the extent given by graph G""" pos_wgs = nx_coordinate_layout(G) lon = [coords[0] for coords in pos_wgs.values()] lat = [coords[1] for coords in pos_wgs.values()] lon_min = min(lon) lon_max = max(lon) lat_m...
96b65fd0de1ebcd373ddc0e521bf4eb87f23ad7e
47,054
def get_conversation_by_name(conversation_name: str) -> dict: """ Get a slack conversation by its name. Order of operation is: 1. Check the COMMON_CHANNEL parameter for the conversation 2. Check the integration context for the conversation 3. If DISABLE_CACHING is false, then we will paginate the ap...
03634e5c15227f1513fcb594ab710651ee185b48
47,055
import os def get_file_extension(fname): """ Returns the extension from a filepath string ignoring the '.' character """ return os.path.splitext(fname)[-1][1:]
44c751df76fe34d2df81cc98a2c140556ddfbcf3
47,056
def cloud_remove(img, bandnumber): """ img: image bandnumber: bandnumber """ if bandnumber < 1 | bandnumber > 11: print 'ValueError: bandnumber should be 1~11.' return 0 # TODO D中元素表示各通道截至频率,需要修改一下 D = [0.4, 0.4, 0.4, 0.4, 0.4, 0.4,\ 0.4, 0.4, 0.4, 0.4, 0.4] img1 ...
fa821500201bfccf553bd576881444056297dd42
47,057
def _apply_laplacian(nx, ny, alpha, image): """ Apply isotropic Laplacian to an image. Parameters ---------- nx, ny: int Dimensions of 2D image alpha: float Diffusion parameter image: ndarray, ndim=1 Image as a 1D vector Returns ------- output: ndarray, ndim...
28a92c250ff0a16a803bd94447c53dbd1bf6bae5
47,058
def get_tree(): """You probably want to use ET.fromstring""" root = ET.fromstring(xmlstring) return ET.ElementTree(root)
d57f907d8929fb0bb448a1b8000677db6646c97a
47,059
def standard_rated_expenses_emiratewise(data, filters): """Append emiratewise standard rated expenses and vat.""" total_emiratewise = get_total_emiratewise(filters) emirates = get_emirates() amounts_by_emirate = {} for emirate, amount, vat in total_emiratewise: amounts_by_emirate[emirate] = { "legend": emirat...
8d8ca250e03b0126176ae5cab165441f2109f6d1
47,060
def MPIBroadcast(inputs, root, mpi_ranks=None, **kwargs): """Broadcast a tensor to all nodes in the ``MPIGroup``. Parameters ---------- inputs : Tensor The tensor to broadcast. root : int The world rank of root node. mpi_ranks: sequence of int, optional The world rank of...
42fa38c70e984d92d93c73833a10f44fcd3c4bef
47,061
import numpy def calc_namp(tors_names, nsamp_par, cnf_save_fs, cnf_run_fs): """ Determine the number of samples to od """ tors_ranges = tuple((0, 2*numpy.pi) for tors in tors_names) tors_range_dct = dict(zip(tors_names, tors_ranges)) nsamp = util.nsamp_init(nsamp_par, len(tors_names)) iop...
7394d3536d161f2195c5ad1fa80b81a6f85def62
47,062
def _add_loss_summaries(total_loss): """Add summaries for losses. Generates moving average for all losses and associated summaries for visualizing the performance of the network. Args: total_loss: Total loss from loss(). Returns: loss_averages_op: op for generating moving averages of l...
05e3841aae8b3ed823eaca31f40a985d6ea1a9e9
47,063
import os def check_extension(fname, extension = ".csv"): """ Checks whether the fname includes an extension. Adds an extension if none exists. fname - the name of the file to check. extension - the extension to append if necessary. >> Default: ".csv". """ root, ending = os.path.spl...
05bb018453101d0017be4dade0bc9199e67e7dfb
47,064
import array def lock2key(lock): """ Generates response to $Lock challenge from Direct Connect Servers Borrowed from free sourcecode online. """ lock = array.array('B', lock) ll = len(lock) key = list('0'*ll) for n in xrange(1,ll): key[n] = lock[n]^lock[n-1] key[0] = lock[0...
f7bf7c2a4881bfeb44b230d030711e684a674a2e
47,065
def get_channel_count(ods, hw_sys, check_loc=None, test_checker=None, channels_name='channel'): """ Utility function for CX hardware overlays. Gets a channel count for some hardware systems. Provide check_loc to make sure some data exist. :param ods: OMAS ODS instance :param hw_sys: string ...
9d26666dd611125a41e067bc405b3bbc7705ed3e
47,066
def get_bundle_files_cached(bundle_uuid, bundle_version=None, draft_name=None): """ Get the list of files in the bundle, optionally with a version and/or draft specified. """ if draft_name: return get_bundle_draft_files_cached(bundle_uuid, draft_name) else: if bundle_version is N...
1a8d761f6f93139f9efadc7700b63ab403a40ff5
47,067
from typing import Dict def get_token_header(user_id: UUID) -> Dict[str, str]: """Get an authentication token header.""" token = encode_token(user_id, FAKE_KEY) return {"Authorization": f"Bearer {token}"}
e11ee664bd4ae10dbcbedf6ade887d151e8c9d8d
47,068
from typing import Union def _add_prefix(key_type: Union[PublicKeyTypeAgreement, PublicKeyTypeAuthentication], data: bytes) -> bytes: """ Adds prefix to a data :param key_type: type of key :param data: data to be prefixed :return: prefixed data """ prefix = varint.encode(key_type.value) ...
3e0a4f97e59a0f02cb2e6066ec04b6a4c3c690bf
47,069
def tshirt_code(tshirt_string): """ convert tshirt size strings into a code for us""" if not tshirt_string: return "" tshirt_code = "" if tshirt_string[0] == "f": tshirt_code += "0" tshirt_string = tshirt_string[1:] else: tshirt_code += "1" size_code = {"s": "1"...
f66d908528c6caa47ca878e4115eec00c52e3046
47,070
import os def get_scanloc_msg(picks_file,origins_file,origins_loc={"LOCSAT":"iasp91"}, db="sysop:sysopp@10.100.100.13/seiscomp3"): """ Parameters: picks_file: str Path of the xml picks file origins_file: str Path of the xml origins file origins_loc: dict (defaul...
3686631f2dd3eb59c6437b1f90bb3b603281e29c
47,071
import time import calendar def dates_to_epoch(d): """Recursively converts all dict values that are struct_times to Unix timestamps.""" for key, value in d.iteritems(): if hasattr(value, 'iteritems'): d[key] = dates_to_epoch(value) elif type(value) is time.struct_time: ...
6a0a9a8f1a1636376973e65c4d3b4ff8a3603d3d
47,072
def get_lineage(dag_id: str, execution_date: str): """ Get Lineage details for a DagRun """ # Convert string datetime into actual datetime try: execution_dt = timezone.parse(execution_date) except ValueError: error_message = ( 'Given execution date, {}, could not be identifie...
27bbf233d249944300b96064ef6d513f06141b41
47,073
def get_release_versions(script_bool): """Prompt the user for the current and next release versions.""" version = vinfo['version'] if version.endswith('.dev'): logger.info('Current development version: {0}'.format(version)) relver = version[:-4] if not script_bool: overri...
c1d2b451231d5d28b44c59a5008e96bcda59be47
47,074
from typing import Dict from typing import Any import logging def build_log_config(level: str) -> Dict[str, Any]: """Build a log config from a level.""" return { "version": 1, "disable_existing_loggers": False, "formatters": { "basic": {"format": "%(asctime)s %(name)s %(lev...
e20a419ee6c69f6fa0eefbd51e5542349b1a1e8b
47,075
def sum2(n): """ sum of n numbers - recursion n - unsigned """ if n == 0: return 0 if n == 1: return 1 else: return n + sum2(n-1)
0ea4cea90c51077fdd0a2ea8a57f156c5096445e
47,076
def i2n(i): """ip to number """ ip = [int(x) for x in i.split('.')] return ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3]
14496c2e7c83794a8364732c512f2d3cfdaba1d9
47,077
def compute_dist_with_visibility(array1, array2, vis1, vis2, dist_type='cosine', avg_by_vis_num=True): """Compute the euclidean or cosine distance of all pairs, considering part visibility. In this version, if a query image does not has some part, don't calculate distance for this part. If a query has one p...
02b78a74e1971b1b18dfa8271dfca8edb8c89c31
47,078
def count_increases(report): """Meh >>> count_increases([199, 200, 208, 210, 200, 207, 240, 269, 260, 263]) 7 """ return sum((1 if report[n] < report[n + 1] else 0 for n in range(len(report) - 1)))
bb38ae2de0f5e7a8f7f2904cdca62a7de80543ab
47,079
def all_qos_for_topic(topic: str): """Build a list of (topic, QoS) pairs that covers all quality of service levels.""" return [(topic, QOS_0), (topic, QOS_1), (topic, QOS_2)]
03efc78b3783b072e306dc4cab41bfe98ab11cd0
47,080
import numpy def unumpy_to_numpy_matrix(arr): """ If arr in a unumpy.matrix, it is converted to a numpy.matrix. Otherwise, it is returned unchanged. """ if isinstance(arr, matrix): return arr.view(numpy.matrix) else: return arr
1ae6cc435d2b17da3859ccb8ae62e17652e6b6e5
47,081
def abtest_power( group_sizes, baseline, alt_lift, alpha=0.05, null_lift=0.0, power=score_power, lift="relative", ): """Power associated with an A/B Test Parameters ---------- group_sizes : array_like Number of experimental units in each group. baseline : float...
dab28f575f61f7515fffdef3165d7aa4c229c9e9
47,082
from datetime import datetime def get_image_creation_timestamp(client: Client, image: str, digest: str,) -> datetime: """ Return an image's creation timestamp. Args: client (Client): A client instance authenticated with a Bearer token and pointed at version 2 of the Docker registry AP...
3eb487d98bd07fd7479d3f496328a9a62949731c
47,083
def _deconv_rl_gpu_fft(data_g, h_g, Niter=10): """ using fft_convolve """ if data_g.shape!=h_g.shape: raise ValueError("data and h have to be same shape") # set up some gpu buffers u_g = OCLArray.empty(data_g.shape, np.complex64) u_g.copy_buffer(data_g) tmp_g = OCLArray.empt...
c94a02407fd1689e42610262a26081a76ebfe9f8
47,084
def pretty_entry(team): """Formats a single team entry in a PrettyTable""" fields = ["Property", "Value"] table = PrettyTable(field_names=fields) table.align = "l" table.title = team.name + " - " + team.player_first_name + " " + team.player_last_name for attr, value in team.__dict__.items(): ...
3bc536787b0c509c28c1dc40936c6a27e97d9e1d
47,085
def has_conflicts(path): """Does repository at path have any conflicts?""" global svn changed = svn.status(path, ignore_externals=True) for f in changed: if f.text_status == pysvn.wc_status_kind.conflicted: return True return False
dcb64e2c12d6b305318eb363889e5221dcdbd26c
47,086
def first_n_false_reducer(data_list, n=0, **kwargs): """Reduce a list of boolean values to a single boolean value. Parameters ---------- data_list : list A list of dicts containing a "result" key which should correspond with a boolean value. n: int The first n results in `d...
df845f4d195ba1e677f88c8176b22b85554aa51d
47,087
def echo_msmt_induced_dephasing(qubits: list, angles: list, platf_cfg: str, wait_time: float=0): """ Ramsey sequence that varies azimuthal phase instead of time. Works for a single qubit or multiple qubits. The coherence of the LSQ is measured, while the whole list of qub...
b332e438792b8f9b3f6d4029e94f1f13dc352988
47,088
import torch def compute_huber_loss(predictions, labels, reduction='mean', delta=None): """Compute the Huber loss. Args: predictions (tensor): a batch of point predictions. labels (tensor): the labels, an array of shape [batch_size]. reduction (str): the method to aggregate the result...
a4d72134366c1bb254a41823f7508a933dab2666
47,089
import inspect import os def report_template(name, raise_error=True): """Evaluation report template found in ../templates/ """ filename = inspect.getframeinfo(inspect.currentframe()).filename this_dir = os.path.dirname(os.path.abspath(filename)) template_file = os.path.join(this_dir, 'templates/',...
28c8754cb11436da76c413db3767d6189d204c7a
47,090
def get_hosted_zones(): """ list domains """ client = boto3.client("route53", region_name="us-east-1") response = client.list_hosted_zones() LOGGER.debug(response) zones = response["HostedZones"] store("zones", zones) return zones
d6bd906184db89420583d28cf34efd35b185d6c1
47,091
def serialize(hashObject): """ Serializes the internal state of the hash object passed in. Calling restore() on the serialized value afterward will return an equivalent hash object to the one passed. :param hashObject: The hash object to serialize. :type hashObject: _hashlib.HASH :returns: ...
84757accf3ec9ed01e5c06d764a41c4a7a5d4421
47,092
import dash import dash_core_components as dcc import dash_html_components as html import omegaml as om def create_app(context=None, server=None, uri=None, **kwargs): """ the script API execution entry point :return: result """ external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'...
c74426e790f2bcf88d55594ab8795408733041ab
47,093
import os def example_gdal_path(data_folder): """Return the pathname of a sample geotiff file Use this fixture by specifiying an argument named 'example_gdal_path' in your test method. """ return str(os.path.join(data_folder, 'sample_tile_151_-29.tif'))
a2cbc0b7d50ecfd38d0aad02befc5cd1e38c9f4e
47,094
import torch def overall_accuracy(input, target): """Overall accuracy for batches""" if input.is_cuda: s = torch.FloatTensor(1).cuda().zero_() else: s = torch.FloatTensor(1).zero_() for i, c in enumerate(zip(input, target)): s = s + OverallAccuracy().forward(c[0], c[1]) r...
8d7cee43a27ede3cf61d041d12c9309eac328ef7
47,095
def _dataset_object_metadata(dataset_object): """Return mapping of dataset metadata key to value. Args: dataset_object: ArcPy geoprocessing describe data object for dataset. Returns: dict. """ meta = {"object": dataset_object} meta["name"] = getattr(meta["object"], "name", None...
20b9ea45cbb3e754072ad47e2e1c8ad763e35ab7
47,096
def solve_set_based(discretization, rect_size, obs_cpd=1): """ """ disc = discretization.copy() Q_ref = disc.get_output().get_reference_value() simpleFunP.regular_partition_uniform_distribution_rectangle_size( data_set=disc, Q_ref=Q_ref, rect_size=...
7caca954e1bb82dab70580d84b540f6099f93f32
47,097
from typing import Iterable from typing import Optional def effective_sample_size( weights: Iterable[float], total_weight: Optional[float] = None, ) -> float: """Computes the "effective sample size" of the given weights This value represents how "healthy" the underlying samples are. The lower thi...
6915abd0484dc4b08b47c1c88b6e19e2af5dd1c4
47,098
def split_pair_occurrence(input_str): """ Q9HD36.A79T (x11) → (Q9HD36.A79T, 11) """ if '(x' not in input_str: return input_str, 1 pair, occurrence = [item.strip() for item in input_str.split()] occurrence = int(occurrence[2:-1]) return pair, occurrence
0812e907a97894ff6f2d94722874b3917ce30ad8
47,099