content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from pathlib import Path def check_golden_results_for_task(config): """ Copies the latest task run's parse_results.txt into the config directory as golden_results.txt """ num_qor_failures = 0 run_dir = find_latest_run_dir(config) if not config.pass_requirements_file: print( ...
7c3fcc9babc286e735077442f507d44a42ed6353
3,601,270
import json def translate_header(df, dictionary, dictionary_type='inline'): """change the headers of a dataframe base on a mapping dictionary. Parameters ---------- df : `DataFrame` The dataframe to be translated dictionary_type : `str`, default to `inline` The type of dictionary,...
371443bc112fa2b0892bbcf945e3089aab995122
3,601,271
from typing import Optional from typing import Tuple from typing import List import yaml def clean(clean_data_basename: Optional[str] = default_file_name) -> Tuple[pd.DataFrame, List[BookType]]: """ data cleaning """ class_count: int = 0 label_list: List[BookType] = [] get_from_disk = clean_d...
787d9a3142dea915e1b7dc7d704ae8b7f9c8719b
3,601,272
def isHit(obbTree, pSource, pTarget): """ From https://blog.kitware.com/ray-casting-ray-tracing-with-vtk/ :param obbTree: :param pSource: :param pTarget: :return: """ code = obbTree.IntersectWithLine(pSource, pTarget, None, None) if code == 0: return False return True
6c37fcb3ffc6f33d308e9762b1b0c27b2b374ef7
3,601,274
def _gen_repo(): """Return OSTree repo body.""" return { 'id': utils.uuid4(), 'importer_type_id': 'ostree_web_importer', 'importer_config': {}, 'distributors': [], 'notes': {'_repo-type': 'OSTREE'}, }
1359e5f8238cf931aa444b2fa4695397e763d30f
3,601,275
from typing import Tuple def permute_systems(X: np.ndarray, Y: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """ Samples new matrices by randomly permuting the systems between X and Y. The original matrices will not be changed. """ assert X.shape == Y.shape # Do not modify the original matrice...
6568a0e82e2c23f74160a76090dee9c0cd91b331
3,601,276
import yaml def load_config_settings(logger, path_to_config_file): """ Load config settings from config file :param logger: the logger :param path_to_config_file: location of config file :return: settings dictionary containing values for: ...
dded0ea8a70bb4dee74e2498bf9cdaa2bd1b7676
3,601,277
import array def fit_sem_trans_fncs(G: MultiDiGraph, D_obs: dict) -> dict: """ Fit transition functions connecting time-slices in causal Bayesian network. OBS: this function assumes that transition relationships are first-order Markov only. The code needs to modified if longer-range dependencies need to ...
6766fa0e5f646f52a3206903d2fa0ac70741c040
3,601,278
def users_status_page(ids, **kwargs): """Wrapper for the `GET /api/users/status <https://github.com/ornicar/lila#get-apiusersstatus-fetch-many-users-online-and-playing-flags>`_ endpoint. Use :data:`~lichesspy.api.users_status` to avoid manual pagination. """ kwargs["ids"] = ",".join(ids) return _api...
b1bc3fbb5d1719297a5dff8614adce350a977ed9
3,601,279
import struct def _generate_bmv2_config(ctx): """Preprocesses P4 sources and runs p4c on pre-processed P4 file.""" # Preprocess all files and create 'p4_preprocessed_file'. p4_preprocessed_file = ctx.actions.declare_file( ctx.genfiles_dir.path + ctx.label.name + ".pp.p4", ) cpp_toolchain ...
185ddf0cbd4ae290079e416187b90c0b44f8fb8a
3,601,280
def county_data_cleaning(county_path): """Clean and relabel county data.""" county_df = pd.read_csv(county_path, index_col='county') return county_df
89c786f9f84fd3da29c1fd6b3bd32f64696d377d
3,601,282
def rect2pathd(rect): """Converts an SVG-rect element to a Path d-string. The rectangle will start at the (x,y) coordinate specified by the rectangle object and proceed counter-clockwise.""" x, y = float(rect.get('x', 0)), float(rect.get('y', 0)) w, h = float(rect.get('width', 0)), float(rect....
60827810118abb4de47b12457806199639626aee
3,601,283
from typing import List def harvest_as_atomic_result(input_model: OptimizationInput, nwout: str) -> List[AtomicResult]: """Parse each step in the geometry relaxation as a separate AtomicResult Args: input_model: Input specification for the relaxation nwout: Standard out from the NWChem simula...
adb9e88a0974f882ad90f08ad877a38cf3e33339
3,601,284
def remote_ip() -> IPAddress: """Return request's IP address (i.e. address of the client).""" addr = request.environ.get('HTTP_X_FORWARDED_FOR') or request.environ.get('REMOTE_ADDR') # nginx uses ::ffff: as a prefix for IPv4 addresses in ipv6only=off mode. return ip_address(cut_prefix(addr, '::ffff:'))
2399da700b487ba10d55d3a456535e4e8b3240f8
3,601,285
import numpy def weights(x, y, seeds, influences, decay=2): """ Calculate weights for the data based on the distance to the seeds. Use weights to ignore regions of data outside of the target anomaly. Parameters: * x, y : 1d arrays The x and y coordinates of the observations * seeds :...
2841c0740614cda25a157c3ff8a4eb0aa859e16c
3,601,286
def nonzero_item_mean(matrix, nan_symbol): """快速计算一个矩阵的列均值 """ return nonzero_user_mean(matrix.T, nan_symbol)
7dea1fafe106ecf1aca0c375dc9d3b9f6e910a06
3,601,287
def judge_same_month(input_month_list): """ 判断 数据 是否 在同一个月 :param input_month_list:list :return: str or bool """ month_list = [] for item in input_month_list: month_list.append(item["trade_date"].strftime("%Y-%m")) month_set = set(month_list) if len(month_set) != 1: r...
69082ac16150082bfe6cd9b384fa010a3849e682
3,601,288
def _create_trip_from_stack(temp_trip_stack, origin_activity, destination_activity): """ Aggregate information of trip elements in a structured dictionary Parameters ---------- temp_trip_stack : list list of dictionary like elements (either pandas series or python dictionary). C...
f2ddb6c19650c001c714ddeb8372b81ff40f2abe
3,601,289
def _print_behind_ahead(behind, ahead): """ Print Behind Ahead """ numcommits = "" if behind: numcommits += "-" + str(behind) if behind and ahead: numcommits += "/" if ahead: numcommits += "+" + str(ahead) return numcommits
816e761a7d31d41b13b32db4eb01e7ee8040087b
3,601,291
import socket def live_server(request, app, monkeypatch, pytestconfig): """Run application in a separate process. When the ``live_server`` fixture is applied, the ``url_for`` function works as expected:: def test_server_is_up_and_running(live_server): index_url = url_for('index', _ex...
45bc0d62c851840a8646b06373221ad1ab20ed79
3,601,292
from io import StringIO def writeObject(obj, outstream=None, indentStr=None, level=0): """ Writes an object to an output stream """ outstream = outstream or StringIO() return writerFor(obj)(obj, outstream, indentStr, level)
56b3180d1d205639a7c757e53658be6546b79a07
3,601,293
from dateutil import tz def make_lecture(link_page, zoom_location): """Create a 1hr lecture on zoom with 1 speaker from 2018.""" lecture_type = EventType.objects.get_or_create(name="Lecture")[0] start_time = timezone.datetime(2018, 4, 20, 16, 20, tzinfo=EST).astimezone(tz.utc) end_time = timezone.date...
c6dec160403a2ba81b452ab6eebb2d0d30a90c46
3,601,294
def precprint(prec_type, prec_cap, p): """ String describing the precision mode on a p-adic ring or field. EXAMPLES:: sage: from sage.rings.padics.misc import precprint sage: precprint('capped-rel', 12, 2) 'with capped relative precision 12' sage: precprint('capped-abs', 11...
b3eab5f0fd133ead8c413aded650d839a2c818b9
3,601,295
from typing import Callable def whitelisted_autolink() -> Callable[[commands.Command], commands.Command]: """Decorator to whitelist a guild for automatic linking.""" async def predicate(ctx: commands.Context) -> bool: cog: "GithubInfo" = ctx.bot.get_cog("GithubInfo") user, _ = await cog.fetch...
f0abec105c7b461bfaa88762f971b66cc19e8f3b
3,601,296
def valid(board, pos, num): """ Returns is the attempted move is valid :param board: 2d list of ints :param pos: (row, col) :param num: int :return: bool """ # Check Row for i in range(0, len(board)): if board[pos[0]][i] == num and pos[1] != i: return False #...
1d7754ac3789fb8ee1d23e0bebd265750e5a72f0
3,601,297
import math def random_quaternion(rand: np.ndarray = None) -> np.ndarray: """ Return uniform random unit quaternion. Args: ---- rand: Three independent random variables that are uniformly distributed between 0 and 1. """ if rand is None: rand = np.random.rand(3)...
746d8e0732c1052bd8ba6f1d40d6557f7decb4b1
3,601,298
def adjust_lag2_corrcoef1(gamma_1, gamma_2): """A simple adjustment of lag-2 temporal autocorrelation coefficient to ensure that the resulting AR(2) process is stationary when the parameters are estimated from the Yule-Walker equations. Parameters ---------- gamma_1 : float Lag-1 tempor...
54665f6c1d3dbda4c33ec01cdf24539e21a53bed
3,601,300
def zooms_string(z1, z2): """Prints 'zoom N' or 'zooms N-M'.""" if z2 != z1: return "zooms {}-{}".format(min(z1, z2), max(z1, z2)) else: return "zoom {}".format(z1)
2e433472d721767cfc152b75a74f9976ba340f7a
3,601,301
from PIL import ImageEnhance def enhance_brightness(image: napari.types.ImageData, enhancement_factor: float = 1, viewer: napari.Viewer = None) -> napari.types.ImageData: """ This function can be used to control the brightness of an image. An enhancement factor of 0.0 gives a black image. A factor of 1.0 ...
68004710ca752a05467fc4e91d14f2442ed31006
3,601,302
def collect(group, p, barrier_token): """ Collect partitions from partd, yield dataframes """ return p.get(group)
d3824864defbdec8b1712483b7b1e41ef7941268
3,601,303
def d_relu(X): """ Derivative of the ReLU activation function """ return np.where(X > 0, 1, 0)
ca01e2895a6bc2fcd9e3e44082df98afddfdac67
3,601,304
async def collect_messages(channel, *, mode, before=None): """Collects messages from a channel for Shirt Bot""" lst = [] async for x in channel.history(limit=50, before=before): context = await bot.get_context(x) if context.valid and context.command.name == "reset": break ...
2580d9143bc83843dd2f02d2d3abc1264d318d24
3,601,305
def ret_schema(): """Defines dictionary of schema.""" schema = { ('path to directory', str, 'path'): ('path', str, '/apps/homefs1/.*'), ('dict of stocks', str, 'stocks'): { ('ticker', str, '[A-Z]*', '+'): { ('stock price', str, 'price'): ('price', float), ...
83c66bc000a471ff0787eb98a1a8b4146b628911
3,601,306
def schemaToAvroType(schema): """Convert an Avro schema into a titus.datatype.AvroType. :type schema: avro.schema.Schema :param schema: schema object from the Avro library :rtype: titus.datatype.AvroType :return: AvroType object """ if schema.type == "null": return AvroNull() e...
3c275e2b44d42c9947afaa3c86f2e2c16b592b55
3,601,308
def augment_and_average_prediction(n, inp): """Augment input by rotating and flipping, and average network output to improve results. :param n: MS-D network :class:`.network.Network`. :param inp: input array (size: :math:`N_{c} \\times N_{x} \\times N_{y}`). :return: averaged output array. ...
9afc74a9110749c5082c72d2f84ce1e5cdf91f10
3,601,309
def _simulate_and_fit(exp_dep: np.ndarray, simulation_method: str='multinominal', lambda_:str='log-likelihood') -> float: """split off simulate function to allow for parallellization""" simdata = sim_data(exp_dep, method=simulation_method) simchi2 = get_chi2_using_dependent_frequency_estimates(simdata, lamb...
e832c05143f076cbb08254ef79c1b979f85ca1e1
3,601,310
def _imag_2d_func(x, y, func): """Return imag part of a 2d function.""" return func(x, y).imag
b95f64fb2bca54db89c85349ed3ca961d2b47b4c
3,601,314
from typing import List def get_interaction_matrix( cell_data, neighbourhood_bcs, neighbourhood_indices, all_set, sig_bool, L_bool, R_bool, cell_prop_cutoff, ): """Gets the interaction count matrix.""" # Now counting the interactions under 3 situations: # 1) sig spot with l...
6e057b67e7671904bb9915fc558b623e2b805b0c
3,601,315
def generate_dunder_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str: """Generates a wrapper for native __dunder__ methods to be able to fit into the mapping protocol slot. This specifically means that the arguments are taken as *PyObjects and returned as *PyObjects. """ gen = WrapperGenera...
b2788528f6c411a8209344cf769afe00a50a9289
3,601,316
def remove_monitor(nodenet_uid, monitor_uid): """ Delete the given monitor""" try: runtime.remove_monitor(nodenet_uid, monitor_uid) return dict(status='success') except KeyError: return dict(status='error', msg='unknown agent or monitor')
4a31a1726f081649f114f6eff4fb0519e4d5a5b4
3,601,317
def save_config( bkp_config, config_file, for_restart = False ): """ save the configuration to the file object passed as a parameter """ print("bucket =", bkp_config["bucket"], file=config_file) print("dirs = ", ";".join(bkp_config["dirs"]), file=config_file) print("exclude_files = ", bkp_config["exclud...
a4894cf29a44200442c6fb32b59eab9aefb5352c
3,601,318
def download_channel_csv(request): """ Writes list of channels to csv, which is then returned """ if not request.user.is_admin: raise SuspiciousOperation("You are not authorized to access this endpoint") response = StreamingHttpResponse(stream_csv_response_generator(request), content_type="text/csv...
892ae0fbd40510bd0ab7a0fc78973beb1e62c7df
3,601,319
def add_atom_map(molecule, in_place=True): """ Add canonical ordered atom maps to existing molecule Parameters ---------- molecule : oechem.OEMol in_place : bool, optional, default True Returns ------- mapped OEMol if in_place is False """ # First canonical order atoms ...
d1d9157ea0f6c51954480ec6e7b14d8b3b140423
3,601,320
def handle_single_copy_subtree( all_tips: list, terms: list, newtree, subgroup_counter: int, fasta: str, support: float, fasta_dict: dict, assigned_tips: list, ): """ handling case where subtree contains all single copy genes """ # prune subtree to get subtree of interest...
c991d4dfb470a53ada516057ab607c78f9c61204
3,601,321
def index(l, val, default=-1): """ find the index the val in list :param l: index list :param val: value to find index :param default: default value to return that value not in list :return: value index in list """ try: getattr(l, 'index') except: raise TypeError('ipn...
6c953b278cb65451879bbde19dfd4392a034b36f
3,601,322
def bandpass( nsamp: int, dt: float, f1: float, f2: float, f3: float, f4: float, norm: bool = True, precision: float = 0.1, ) -> WaveletDtype: """Create a bandpass wavelet Args: nsamp: Number of samples in wavelet dt: Sample rate in seconds f1: Lower freq...
02a711c75178ca89bd9b7377f86d8b7988b73f04
3,601,323
def get_pairs(word): """ Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length strings) """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
28a14f9b7502540c6645345c07e9be4bf1437960
3,601,324
import logging def node_weight_by_type(results, node_type): """ Extracts node weights (if exist) of all components of the specified `node_type`. Node weight are endogenous optimzation variables associated with the node and not the edge between two node, foxample the variable representing the ...
c7fd77deca090a2326bd24904cc026bffe4430a9
3,601,325
def new_file_archive(*args): """ Instantiates a new FileArchive, passing the given arguments to the constructor. """ return _file_archive_resource_type(*args)
c9f125b27409aa31d3754d7ece2b463da6e06f4c
3,601,326
def save_to_store(content, name, mime_type, location): """ Save named content to store by location. Returns location of saved content. """ content_location = Transcript.asset_location(location, name) content = StaticContent(content_location, name, mime_type, content) contentstore().save(con...
7d60ddc5b645348f2a5e4d9e151bd57a1111faf5
3,601,327
from typing import OrderedDict def dict_order(_dict): """Controls the print order of the dictionary """ new_dict = OrderedDict() new_dict['name'] = _dict.get('name') new_dict['type'] = _dict.get('type') new_dict['conditions'] = _dict.get('conditions') new_dict['scopes'] = _dict.get('scopes...
a4ed107403289093065ce169d549dda88b5dee5c
3,601,328
def batch_directions(z, y, Q, path_sizes, step_vals, subtract_projection=True): """ This function takes an input batch of z vectors (and corresponding class label vectors y) and applies the directions in Q to the batch of z vectors. :param z: (N, nz) tensor of base random noise to manipulate with direc...
4adeab5b8a9ded7b4a10affbb5427435dbd5a599
3,601,329
def build_reduced_city_lookup(): """ Convert city_lookup types and assert data is valid """ city_lookup = build_city_lookup() # First 12 rows are information about the cities city_lookup = build_city_lookup() city_lookup = city_lookup[["city", "country", "lat", "lng", "population"]] cit...
3aeb13655aefbbf4c03c100e9e7a1b14e670ebb7
3,601,330
from typing import Optional import requests def get_access_token( username=f"test_user{info.major}{info.minor}@example.com", password="testPass1-", scope: Optional[str] = None, ): """ NOTE: the followings setting in Auth0 dashboard is required - sidebar > Applications > settings > Advanced set...
9aa64bb3b474804ce3080ad4387e12e9184e18d4
3,601,331
import asyncio from typing import Optional async def run_tui( loop: asyncio.AbstractEventLoop, consoles_filepath: str, auth_mgr: Optional[AuthenticationManager] = None ) -> int: """ Main entrypoint for TUI Args: loop: Eventloop consoles_filepath: Console json filepath ...
b2ba9cee4d74bd706d42ac35d2cc3bcb322625eb
3,601,333
def rescale_logvalues(lst): """Rescales a list of log values by setting max value to 0.0 This function is necessary when working with list of log values. Without it, we could have overflows. This is a lot faster than using arbitrary precision math libraries. """ if not isinstance(lst, N.n...
bb97db53e89e6ebe6dec9c0ffed4c798af91f0d3
3,601,334
def check_rsync_stderr(err): """ Checks to see if the errors in the stderr of rsync are actual errors or can be ignored. :param err: stderr from an execution of rsync :return: True if errors can be ignored """ res = True for l in err.split('\n'): if not len(l): continue ...
5ae536d636010ec7cb23a8401c2c6f088182ba85
3,601,335
from typing import List from typing import Dict def current_passengers( driving: List[str], open_requests: List[Request], vehicle_positions: Dict[str, Vehicle], ) -> List[str]: """ store all personIDs that are in any vehicles - if person occurs for the first time: call req.enter - if perso...
a2c87c1afef29038c443b8dcafd6711af769ab6a
3,601,336
def update_tax_nodes(nodes, tax): """ nodes can be a list of strings: taxids or names or a list of tuples with (rank, taxid/name) Return a dictionary mapping nodes and updated nodes (or None) First look for id, if nothing found, lookup by unique name """ updated_nodes = {} for node in nodes...
7d292ddf43e39280e699f76765079799f61dc0dc
3,601,337
def collection_resolve_package_path(path): """Configure the Python package path so that pytest can find our collections.""" for parent in path.parents: if str(parent) == ANSIBLE_COLLECTIONS_PATH: return parent raise Exception('File "%s" not found in collection path "%s".' % (path, ANSIB...
8ef1fdabc36d66cda36978a2b74abf2f82843a1c
3,601,338
def vgg16(**kwargs): """ Constructs a VGG16 model. """ return VGG16(**kwargs)
85edc5232e51d7c8ebae4e9159d03260afe032c8
3,601,340
def calculate_background_cost(u, v, w, weights, u_back, v_back, Cb=0.01): """ Calculates the background cost function. The background cost function is simply the sum of the squared differences between the wind field and the background wind field multiplied by the weighting coefficient. Parameters ...
95c2cf0c3062f1d95061e78a53dc8c6309ac6e6a
3,601,342
def protocol_store(decoy: Decoy) -> ProtocolStore: """Get a mock ProtocolStore interface.""" return decoy.mock(cls=ProtocolStore)
3c2e8ec207d482ac46a85811298cf37266491e58
3,601,343
def _sparseconv(data, kernel, mode): """Returns the discrete, linear convolution of two 1D sequences This function returns the discrete, linear convolution of two one-dimensional sequences, where the length of the output is determined by ``mode``. Can run faster than ``np.convolve`` if: (1) ``d...
c4d239fa11ce52708b7fbe205fc01fc9cd7ad4a5
3,601,344
from typing import Union def parse_domain(domain: Union[Text, "Domain"]) -> "Domain": """ Transforms a domain as a text string into a Domain instance. Calling with a domain will return a copy of the said domain """ if isinstance(domain, Domain): return replace(domain) else: pa...
8f1f735813e1e5d730543935a00357c8afe5cff1
3,601,345
def value_formating(): """Format a value with the underlying format function.""" happy_value = type('HappyFormater', (object,), { '__format__': lambda _, template: template.replace('lol', '(^_^)')})() return "{:lol}".format(happy_value)
a637bace1337d73658eb667bc3eafc866e5cd9ba
3,601,346
import torch def keypoints_to_heatmap_gaussian(keypoints, rois, heatmap_size): """ input: keypoint的维度为[person_num, 17, 3], "3"代表(x, y, visibility) rois的维度为[person_num, 4], "4"代表(x1, y1, x2, y2) heatmap_size的大小等于cfg.MODEL.ROI_KEYPOINT_HEAD.RESOLUTION, 配置文件中为56 output: heatma...
ab4b571ae4ae1e3a8da8fa71a76db300d508e77c
3,601,347
def solve_equations_system(variables, equations, replace_values=None): """Solve linear and non linear equations system using Sympy library. Parameters ---------- variables : list of str Name of independent variable to solve for. equations : list of sympy equations objects Conform th...
cfc51a741f7ba080cf6f428e227e1dd41ed2040b
3,601,348
import json def _CanParseJSON(my_json): """Returns True if the input can be parsed as JSON, False otherwise.""" try: json.loads(my_json) except ValueError: return False return True
c8602b9e9544a70102135bd875d19c66664bdefc
3,601,349
def is_user_lockable(request): """Check if the user has a profile with nolockout If so, then return the value to see if this user is special and doesn't get their account locked out """ if hasattr(request.user, 'nolockout'): return not request.user.nolockout if request.method != 'POST':...
a505bcee65f758071ef97cdf378124a434c25df4
3,601,350
import csv def write_csv(f, items): """ :type items: list[OrderedDict] """ if len(items) == 0: # nothing to write return f fieldnames = items[0].keys() # this works as expected because we use OrderedDicts writer = csv.DictWriter(f, fieldnames) writer.writeheader() f...
1cabe109bb42e892cc85b40bc6c6930987c042ee
3,601,351
def get_list(sorted_by='name'): """Returns the pages list """ page_list = model.pages.find(sorted_by='name') if page_list: return dict(success=True, page_list=page_list) else: errors = [{ "message": "Error" }] return dict(success=False, errors=errors)
3b4270d9205e6a4e8c088652154a87be84b8805b
3,601,352
import json def get_brawl_cookie(request): """ Get brawl cookie """ return json.loads(request.cookies.get('brawl') or '[]')
e9264476a44bebfa9a43106678d1653ba86e555d
3,601,353
from mglutil.math.rotax import mat_to_quat def _interpolateMat(mat, percent): """called only by interpolate3DTransform()""" if mat.shape != (16,) and mat.shape != (4, 4): raise ValueError("matrix should be of shape (4,4) or (16,)") return None if mat.shape == (16,): mat = N.reshap...
ae2560328b97f32e684eb88288587f6932f45ba5
3,601,354
def str_istitle__Rope(space, w_self): """Return True if S is a titlecased string and there is at least one character in S, i.e. uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise.""" cased = False previous_is_cased = False iter = rop...
d5deba5615d85d245ac7743f42efdcff79841ee5
3,601,355
import copy def jordan_blocks_by_scale_and_unimodular(self, p, safe_flag=True): """ Returns a list of pairs `(s_i, L_i)` where `L_i` is a maximal `p^{s_i}`-unimodular Jordan component which is further decomposed into block diagonals of block size `\le 2`. For each `L_i` the 2x2 blocks are listed a...
4300e88c2a0711b4044054e762fa2e22efeb0da6
3,601,356
import copy def pp_init(local_X, k): """Do a version of KM++ initialization""" ind = np.random.choice(len(local_X), 1)[0] m, n = get_data_dims(local_X) X_flat = [np.matrix(x.reshape(1, m*n)) for x in local_X] first = X_flat[ind] xcopy = copy.deepcopy(local_X) del X_flat[ind] del xcopy[...
7f3c3d591dc51de391e21cfce8ead1c5b7fa88f1
3,601,357
def _AddTopicToResource(topic_name, new_config, resource, resource_name): """Add the PubsubConfig message to Repo/ProjectConfig message.""" if resource.pubsubConfigs is None: config_additional_properties = [] else: config_additional_properties = resource.pubsubConfigs.additionalProperties resource_msg_...
066b3b9ebda7b5921fbe4f2cbc577d6e86ac38e1
3,601,358
def addition_inputs( vocab_size=gin.REQUIRED, batch_size=gin.REQUIRED, train_length=gin.REQUIRED, eval_min_length=gin.REQUIRED, eval_max_length=gin.REQUIRED, pad_to_multiple=32, encdec=False): """Inputs for the add problem: <S>x+y<S>(x+y). Args: vocab_size: how many symbols to use. batch_size: ...
e6defb14f3fc6bfaf3197edd4001dca4d57469f0
3,601,359
import torch def label_smoothed_nll_loss( lprobs: torch.Tensor, target: torch.Tensor, epsilon: float, ignore_index=None, reduction="mean", dim=-1 ) -> torch.Tensor: """ Source: https://github.com/pytorch/fairseq/blob/master/fairseq/criterions/label_smoothed_cross_entropy.py :param lprobs: Log-probab...
5c85297cda97746413c747fe10fae1ecaa16dea9
3,601,361
async def update_guild(guild_id: int, request: UpdateGuildRequest) -> GuildResponse: """ Update a guild in the API. This operation will always succeed. If the guild does not exist it will be created. """ guild = await get_db_guild(guild_id, strict=False) guild = await guild.update(**request.di...
191ce7bad7cddff2ef3dc24156b73f67b572db67
3,601,362
import numpy def expm(Ci): """Return the matrix exponential of a covariance matrix defined by : .. math:: \mathbf{C} = \mathbf{V} \exp{(\mathbf{\Lambda})} \mathbf{V}^T where :math:`\mathbf{\Lambda}` is the diagonal matrix of eigenvalues and :math:`\mathbf{V}` the eigenvectors of :math:`\...
38b15e41c3b95ec8ed673dd8469d27f5f183cf05
3,601,363
def expand_list_element_locations(ctx, args, data): """Performs location-macro expansion on a list of string values. $(execroot ...) and $(location ...) are prefixed with ${pwd}, which process_wrapper and build_script_runner will expand at run time to the absolute path. See [`expand_location`](htt...
d14182843e96770ea694ef42753f6e5a63fd3d13
3,601,364
def select_latest(engine, ticker, time_x): """ 获取离time_x最近的一个 :param engine: :param ticker: :param time_x: :return: """ sql = 'select price,adj_factor from security_lookup_cn_wave_10 where ticker="{}" and time_x<="{}" ORDER BY time_x desc limit 1'.format( ticker, time_x) rs_s...
d33d817afdf58407c9e4ecb66ed9f43e9de6128a
3,601,365
from typing import Union import json def prettify(data: Union[list, dict]) -> str: """ Return input data structure (list or dict) as a prettified JSON-formatted string. Default is set here to stringify values like datetime values. """ return json.dumps(data, indent=4, sort_keys=True, default=str)
800ef5d3f7a5765bca6fe42fc32e40da5a1cc398
3,601,366
import time def search(vector, k=10): """ vector: numpy array vector Return: predicted name of the face and search time """ db = DBObject(db=DB_NAME, user=USER, password=PASSWORD) q = 'SELECT name from images order by vector <-> %s asc limit %s' _vector = AsIs('cube(ARRAY[' + ','....
9c647fe8831f63a2397b83ac411c48abe55f3c5e
3,601,367
def filter_semesters(c, semesters): """Filters the collection by matching its date-time index with the specified semesters.""" indices = find_all_in(get_semesters(c), get_semesters(semesters)) return take_at(c, indices)
54bc88b30d856594d779b465a292c29fd850fa82
3,601,369
def download_pos_file(): """ Devuelve el fichero de posiciones. En caso de error, muestra un mensaje flash por pantalla. """ # Si el servidor está activo, mostramos la página correspondiente if active: # Se intenta enviar el fichero de posiciones try: return send_from...
e0cc2b28869794957257c3f0ce6aabbf8c1224a7
3,601,370
import unittest def getTestSuite(): """ set up composite test suite """ test_suite = unittest.TestSuite([]) test_suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestPairs)) return test_suite
ac8b40220da1cbce87ab256f249ac0aceed59cf7
3,601,372
def fetch_inactive_objects(connection): """Returns list of inactive objects""" resp = connection.execute('GET', 'activation/inactiveobjects') return Marshal.deserialize(resp.text, IOCList())
ec09bf30d9b8f75c5028f76e1f81195d4d4a86c1
3,601,373
def find_outlier(x): """ return a bool array indicating outliers or not in *x* """ l, m, h = np.percentile(x, [16.0, 50.0, 84.0]) d = (h-l) * 0.5 return (x > (m + d*3)) | (x < (m - d*3))
a3d981769f847ec114b546de2fb2b48e80594c3c
3,601,374
def create_placeholders(n_H0, n_W0, n_C0, n_y): """ Creates the placeholders for the tensorflow session. Arguments: n_H0 -- scalar, height of an input image n_W0 -- scalar, width of an input image n_C0 -- scalar, number of channels of the input n_y -- scalar, number of classes Returns:...
2619b84901f1f27a433655d5d1fbdc54e2ce0035
3,601,375
import profile import torch import time def profile_inference( model, dataloader, device, metric_fn, profiler, flow_scale=1.0, count_params=False, pad_divisor=1, ): """ Uses a model to perform inference on a dataloader and profiles model characteristics such as memory usage, in...
6759e86841cce8d0e272ebc0b110c138f8e2404b
3,601,376
def _image_pos(name): """ 查找指定图片在背景图中的位置 """ pull_screenshot() imsrc = ac.imread('bg.png') imobj = ac.imread('images/0{}.PNG'.format(name)) # find the match position pos = ac.find_template(imsrc, imobj, 0.8) circle_center_pos = None if pos != None: circle_center_pos = pos...
2eac5ff9aba651e51eaf492adcaffb2a42c8dfe7
3,601,377
import json def face_register(input_dict): """ Registers only one picture. :param input_dict: e.x. {"user_id": "10098440", "group_id": "staff", "gender": "女", "user_info": "康佳慧", "user_image": base64_image} :return: None, results will be written into database. """ try: # _json ...
61975dbd2a930ff76443b64879263ec7dcb87b77
3,601,379
def power_series(z, cs): """ returns cs[0] + cs[1] * z + cs[2] * z ** 2 + ... + cs[-1] * z ** (len(cs) - 1) """ s = cs[-1] for c in reversed(cs[:-1]): s *= z s += c return s
a9fe54d8a4bc15385f5c1da61eb1696b43a470d4
3,601,380
def database_creation(func): """ Creates the database and tables if it dose not exist Tables: username (text): password (text): salt (text): """ @wraps(func) def wrapper(*args, **kwargs)->None: database_cursor.execute(""" CREATE TABLE IF NOT EXIS...
bc45a8f4763a748d47c38152f76f6d84872c3b0e
3,601,381
def array( item_processor, # type: Processor alias=None, # type: Optional[Text] nested=None, # type: Optional[Text] omit_empty=False, # type: bool hooks=None # type: Optional[Hooks] ): # type: (...) -> RootProcessor """ Create an array processor that can be used ...
268e0046a9fe4e96d2bb6224227b9c7689d81ac5
3,601,383
def normalize(signal): """Restrict the range of a signal to the closed interval [-1.0, 1.0]. """ normalized_signal = signal / max(signal.max(), signal.min(), key=abs) return normalized_signal
d86fe058302ee133e6318f5c0a3fa24430e7e24c
3,601,384
from corpkit.constants import transobjs, transshow def to_cql(dquery, exclude=False, **kwargs): """ Turn dictionary query into cql format """ qlist = [] if exclude: operator = '!=' else: operator = '=' for k, v in dquery.items(): obj, show = transobjs.get(k[0]), tra...
e1b73abd8c2fbaaa697ff9899613c774938dbe6f
3,601,386