content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def genargs() -> ArgumentParser: """ Generate an input string parser :return: parser """ parser = ArgumentParser() parser.add_argument("indir", help="Location of input shexj files") parser.add_argument("outdir", help="Location of output shexc files") parser.add_argument("-s", "--save", h...
1958d772e316212f90d6e3b84c5452e4fc02f2da
3,658,100
def get_model_name(factory_class): """Get model fixture name by factory.""" return ( inflection.underscore(factory_class._meta.model.__name__) if not isinstance(factory_class._meta.model, str) else factory_class._meta.model)
1021f287803b5e6dd9231503d8ddab15c355a800
3,658,101
def GetSpatialFeatures(img, size=(32, 32), isFeatureVector=True): """ Extracts spatial features of the image. param: img: Source image param: size: Target image size param: isFeatureVector: Indication if the result needs to be unrolled into a feature vector returns: Spatial features """ res...
36d864bddb125f7cb13c4bd800076733ab939d58
3,658,102
import html import logging import re def html_to_text(content): """Filter out HTML from the text.""" text = content['text'] try: text = html.document_fromstring(text).text_content() except etree.Error as e: logging.error( 'Syntax error while processing {}: {}\n\n' ...
43fc18400ef121bf12f683da03763dff229d45ae
3,658,103
async def get_robot_positions() -> control.RobotPositionsResponse: """ Positions determined experimentally by issuing move commands. Change pipette position offsets the mount to the left or right such that a user can easily access the pipette mount screws with a screwdriver. Attach tip position plac...
816f1794231aa2690665caa8eae26c301d55b198
3,658,104
def compute_basis(normal): """ Compute an orthonormal basis for a vector. """ u = [0.0, 0.0, 0.0] v = [0.0, 0.0, 0.0] u[0] = -normal[1] u[1] = normal[0] u[2] = 0.0 if ((u[0] == 0.0) and (u[1] == 0.0)): u[0] = 1.0 mag = vector_mag(u) if (mag == 0.0): return for ...
3623a80fcb86d506e5f9e2f94d98a69a2831b2a5
3,658,105
def do_LEE_correction(max_local_sig, u1, u2, exp_phi_1, exp_phi_2): """ Return the global p-value for an observed local significance after correcting for the look-elsewhere effect given expected Euler characteristic exp_phi_1 above level u1 and exp_phi_2 above level u2 """ n1, n2 = get_coefficient...
53ee295261d58c59aa1a0a667ec7ded2e986c256
3,658,106
def _check_password(request, mail_pass, uid): """ [メソッド概要] パスワードチェック """ error_msg = {} if len(mail_pass) <= 0: error_msg['mailPw'] = get_message('MOSJA10004', request.user.get_lang_mode()) logger.user_log('LOSI10012', request=request) logger.logic_log('LOSM17015', re...
8753d0ed32db0c501f2f18af9ea88253b7a1add7
3,658,107
def _read_wb_indicator(indicator: str, start: int, end: int) -> pd.DataFrame: """Read an indicator from WB""" return pd.read_feather(config.paths.data + rf"/{indicator}_{start}_{end}.feather")
87a52d5f683fc9795a7baf9ff81f2961567c3a13
3,658,108
import subprocess def pr_branches() -> list[str]: """List of branches that start with 'pr-'""" out = subprocess.run( [ "git", "for-each-ref", "--shell", '--format="%(refname:strip=3)"', "refs/remotes/origin/pr-*", ], capture_o...
f144d2546ef59cb392f4ad1226c2246384bdfd99
3,658,109
def scatter_raster_plot(spike_amps, spike_depths, spike_times, n_amp_bins=10, cmap='BuPu', subsample_factor=100, display=False): """ Prepare data for 2D raster plot of spikes with colour and size indicative of spike amplitude :param spike_amps: :param spike_depths: :param sp...
a72da0b1faacb5e13da51a2dc192778d956eb7e5
3,658,110
def is_pack_real(*args): """ is_pack_real(F) -> bool 'FF_PACKREAL' @param F (C++: flags_t) """ return _ida_bytes.is_pack_real(*args)
64e3ecf58607cf7c363e84a7e5a69ce0c76e8acc
3,658,111
import ast from typing import List from typing import Tuple def _get_sim205(node: ast.UnaryOp) -> List[Tuple[int, int, str]]: """Get a list of all calls of the type "not (a <= b)".""" errors: List[Tuple[int, int, str]] = [] if ( not isinstance(node.op, ast.Not) or not isinstance(node.opera...
f0efdf0b10a0d4ec8a4a75772277169aa708e005
3,658,112
from typing import Union def parse_boolean(val: str) -> Union[str, bool]: """Try to parse a string into boolean. The string is returned as-is if it does not look like a boolean value. """ val = val.lower() if val in ('y', 'yes', 't', 'true', 'on', '1'): return True if val in ('n', 'no...
e2cbda5a849e1166e0f2a3953220c93d1f3ba119
3,658,113
import csv from datetime import datetime def load_users(usertable): """ `usertable` is the path to a CSV with the following fields: user.* account.organisation SELECT user.*, account.organisation FROM user LEFT JOIN account ON user.account_id = account.id; """ users = [] wit...
44c1dad255e2d8152fadbb53523a53002af95001
3,658,114
def get_progress_status_view(request): """Get progress status of a given task Each submitted task is identified by an ID defined when the task is created """ if 'progress_id' not in request.params: raise HTTPBadRequest("Missing argument") return get_progress_status(request.params['progress_...
4e68fc45443443187032ce06552e97895316be41
3,658,115
def pretty_param_string(param_ids: "collection") -> str: """Creates a nice string showing the parameters in the given collection""" return ' '.join(sorted(param_ids, key=utilize_params_util.order_param_id))
10f955480fcf760317f78d478c837c93df598e08
3,658,116
def _center_crop(image, size): """Crops to center of image with specified `size`.""" # Reference: https://github.com/mlperf/inference/blob/master/v0.5/classification_and_detection/python/dataset.py#L144 # pylint: disable=line-too-long height = tf.shape(image)[0] width = tf.shape(image)[1] out_height = size...
2409d06945e77633f70de3e76f7152f61a9eaacf
3,658,117
def resample(ts, values, num_samples): """Convert a list of times and a list of values to evenly spaced samples with linear interpolation""" assert np.all(np.diff(ts) > 0) ts = normalize(ts) return np.interp(np.linspace(0.0, 1.0, num_samples), ts, values)
9453bba67add0307276ff71e85605812af337379
3,658,118
import os def merge_align_moa(data_dir, cp_moa_link): """ This function aligns L1000 MOAs with the cell painting MOAs and further fill null MOAs in one of the them (cell painting or L1000) with another, so far they are of the same broad sample ID. The function outputs aligned L1000 MOA metad...
898f4c49c839900d3f0f44eae589c1227e7adbd0
3,658,119
def supports_color(stream) -> bool: # type: ignore """Determine whether an output stream (e.g. stdout/stderr) supports displaying colored text. A stream that is redirected to a file does not support color. """ return stream.isatty() and hasattr(stream, "isatty")
4a427d6725206ef33b3f4da0ace6f2d6c3db78a9
3,658,120
from typing import Union from typing import Optional from typing import Tuple from typing import Dict from typing import List from bs4 import BeautifulSoup def parse_repo_links( html: Union[str, bytes], base_url: Optional[str] = None, from_encoding: Optional[str] = None, ) -> Tuple[Dict[str, str], List[Li...
556ba2bb728c26668548d4f714dc12b1cf2b48bd
3,658,121
def calc_kappa4Franci(T_K, a_H, a_H2CO3s): """ Calculates kappa4 in the PWP equation using approach from Franci's code. Parameters ---------- T_K : float temperature Kelvin a_H : float activity of hydrogen (mol/L) a_H2CO3s : float activity of carbonic acid (mol/L) ...
a5dcab9d871c7e78031ec74fef5f172e2a37f51b
3,658,122
def get_candidates_from_single_line(single_line_address, out_spatial_reference, max_locations): """ parses the single line address and passes it to the AGRC geocoding service and then returns the results as an array of candidates """ try: parsed_address = Address(single_line_address) except...
a2e4c68dc5a27dea98951bfe61c5e10ff887091a
3,658,123
def create_store(): """Gathers all the necessary info to create a new store""" print("What is the name of the store?") store_name = raw_input('> ') return receipt.Store(store_name)
a9b78c73712b9ec3ed39f5851b970aa97e5d3575
3,658,124
def vgg11_bn_vib(cutting_layer, logger, num_client = 1, num_class = 10, initialize_different = False, adds_bottleneck = False, bottleneck_option = "C8S1"): """VGG 11-layer model (configuration "A") with batch normalization""" return VGG_vib(make_layers(cutting_layer,cfg['A'], batch_norm=True, adds_bottleneck = ...
bf893f1e720aae92275abc961675a83c507425ee
3,658,125
from pathlib import Path def get_conf_paths(project_metadata): """ Get conf paths using the default kedro patterns, and the CONF_ROOT directory set in the projects settings.py """ configure_project(project_metadata.package_name) session = KedroSession.create(project_metadata.package_name) ...
f001dc7d6991c57f32afb3d8d6e607d24bfd61cd
3,658,126
import numpy import ctypes def _mat_ptrs(a): """Creates an array of pointers to matrices Args: a: A batch of matrices on GPU Returns: GPU array of pointers to matrices """ return cuda.to_gpu(numpy.arange( a.ptr, a.ptr + a.shape[0] * a.strides[0], a.strides[0], dtyp...
1b56c7b9cbc368612fb0f0f7ecd647b5045773a2
3,658,127
def file_upload_quota_broken(request): """ You can't change handlers after reading FILES; this view shouldn't work. """ response = file_upload_echo(request) request.upload_handlers.insert(0, QuotaUploadHandler()) return response
ed9dab36b4f67a58e90542411474da733887f4b4
3,658,128
def create_LED_indicator_rect(**kwargs) -> QPushButton: """ Useful kwargs: text: str, icon: QIcon, checked: bool, parent checked=False -> LED red checked=True -> LED green """ button = QPushButton(checkable=True, enabled=False, **kwargs) button.setStyleSheet(SS_LED_INDICATOR_RECT) ...
3323a225b3f9ac6e687bb3a3d1c5f9d6a4459384
3,658,129
import os def get_current_version_name(): """Returns the version of the current instance. If this is version "v1" of module "module5" for app "my-app", this function will return "v1". """ return os.environ['CURRENT_VERSION_ID'].split('.')[0]
cbd7fdbb9af4990e32130f2aa3af0cfe8bf59816
3,658,130
def getAlignments(infile): """ read a PSL file and return a list of PslRow objects """ psls = [] with open(infile, 'r') as f: for psl in readPsls(f): psls.append(psl) return psls
00d6c0c4e44dd3de46c3bc7f38d40fd169311164
3,658,131
import numpy def get_ring_kernel(zs,Rs): """Represents the potential influence due to a line charge density a distance *delta_z* away, at which the azimuthally symmetric charge distribution has a radius *R*.""" Logger.write('Computing ring kernels over %i x %i points...'%((len(zs),)*2)) ...
5cdbeb80c8658334245e4fa93f3acf9ac0f9dbc9
3,658,132
def dsdh_h(P, h, region = 0): """ Derivative of specific entropy [kJ kg / kg K kJ] w.r.t specific enthalpy at constant pressure""" if region is 0: region = idRegion_h(P, h) if region is 1: return region1.dsdh_h(P, h) elif region is 2: return region2.dsdh_h(P, h) elif reg...
0ecc9d783524873c2d8537e105c7d5e8814ec80c
3,658,133
from datetime import datetime def floor_datetime(dt, unit, n_units=1): """Floor a datetime to nearest n units. For example, if we want to floor to nearest three months, starting with 2016-05-06-yadda, it will go to 2016-04-01. Or, if starting with 2016-05-06-11:45:06 and rounding to nearest fifteen mi...
8c4b61b29bf9f254e2da46097e498834b54e960f
3,658,134
def get_dataset_descriptor(project_id, dataset_id): """Get the descriptor for the dataset with given identifier.""" try: dataset = api.datasets.get_dataset_descriptor( project_id=project_id, dataset_id=dataset_id ) if not dataset is None: return jsonif...
776c7f72730f52e07cf33a6f6b4c7a949810323d
3,658,135
def pe41(): """ >>> pe41() 7652413 """ primes = Primes(1000000) for perm in permutations(range(7, 0, -1)): n = list_num(perm) if primes.is_prime(n): return n return -1
bec7969b96f617848f8771dc6d85faf4b01ea648
3,658,136
def transit_flag(body, time, nsigma=2.0): """Return a flag that indicates if times occured near transit of a celestial body. Parameters ---------- body : skyfield.starlib.Star Skyfield representation of a celestial body. time : np.ndarray[ntime,] Unix timestamps. nsigma : float ...
271378e0a6558491f73968200fcb24ec694f8cbe
3,658,137
def _parse_port_ranges(pool_str): """Given a 'N-P,X-Y' description of port ranges, return a set of ints.""" ports = set() for range_str in pool_str.split(','): try: a, b = range_str.split('-', 1) start, end = int(a), int(b) except ValueError: log.error('Ig...
6926b326ea301f21e2282edda3bc16169ebe90b4
3,658,138
def get_flavors(): """ Get Nectar vm flavors in a dict with openstack_id as key """ fls = Flavor.query.all() results = [] for fl in fls: results.append(repack(fl.json(), {"name": "flavor_name"}, ["id"])) return array_to_dict(results)
005ce92fa46689ea639594fd5341f327dc04704d
3,658,139
def _HasTrafficChanges(args): """True iff any of the traffic flags are set.""" traffic_flags = ['to_revision', 'to_latest'] return _HasChanges(args, traffic_flags)
3d638195f86dc9f383c01c92d475ca90dc4fa60b
3,658,140
def find_credentials(account): """ fumction that check if a credentials exists with that username and return true or false """ return Credentials.find_credentialls(account)
dc59eec797d606854fa8a668b234a5eb61f8a0f8
3,658,141
import tokenize def enumerate_imports(tokens): """ Iterates over *tokens* and returns a list of all imported modules. .. note:: This ignores imports using the 'as' and 'from' keywords. """ imported_modules = [] import_line = False from_import = False for index, tok in enumerate(tokens...
0ee4921455899b036eb808262e183a6bc9017ccc
3,658,142
def solved(maze): """Checks if the maze was solved. The maze is solved, if there is no 3 to be found. Returns: True if the maze has no 3. """ # TODO: Extend this function to properly check for 3s inside the maze. return True
15b75435167c87f7e41480fee266416c084e7eb4
3,658,143
import re def safe_htcondor_attribute(attribute: str) -> str: """Convert input attribute name into a valid HTCondor attribute name HTCondor ClassAd attribute names consist only of alphanumeric characters or underscores. It is not clearly documented, but the alphanumeric characters are probably restr...
7a4dda539b2379120e68737d72a80226c45f5602
3,658,144
def focal_length_to_fov(focal_length, length): """Convert focal length to field-of-view (given length of screen)""" fov = 2 * np.arctan(length / (2 * focal_length)) return fov
2803de559943ce84620ac1130c099438ec1b4b12
3,658,145
def create_generic_connection(connection, verbose: bool = False): """ Generic Engine creation from connection object :param connection: JSON Schema connection model :param verbose: debugger or not :return: SQAlchemy Engine """ options = connection.connectionOptions if not options: ...
d0e0ebd9e3b7ffb38ec8add13619ac6224d6760e
3,658,146
def make_csv(headers, data): """ Creates a CSV given a set of headers and a list of database query results :param headers: A list containg the first row of the CSV :param data: The list of query results from the Database :returns: A str containing a csv of the query results """ # Create a list where each entr...
5101d53de8dd09d8ebe743d77d71bff9aeb26334
3,658,147
def draw_color_rect(buf,ix,iy,size,wrect,color): """ draw a square centerd on x,y filled with color """ code = """ int nd = %d; int x, y, i, j; int ny = 1 + 2 * nd; int nx = ny; y = iy - nd; if (y < 0) { ny += y; y = 0; } else if ((y + ny) > dimy) ny -= y + ny - dimy; x = ix - nd; if (x < 0) { ...
822bc77d1e6ccb4c802a4a3335c1bba55ba14f04
3,658,148
def _compute_focus_2d(image_2d, kernel_size): """Compute a pixel-wise focus metric for a 2-d image. Parameters ---------- image_2d : np.ndarray, np.float A 2-d image with shape (y, x). kernel_size : int The size of the square used to define the neighborhood of each pixel. An...
67b139fdef8b6501a64699344d80b19012876f86
3,658,149
from typing import Tuple def extract_value_from_config( config: dict, keys: Tuple[str, ...], ): """ Traverse a config dictionary to get some hyper-parameter's value. Parameters ---------- config A config dictionary. keys The possible names of a hyper-parameter....
d545d4c9298c74776ec52fb6b2c8d54d0e653489
3,658,150
import numpy def boundaryStats(a): """ Returns the minimum and maximum values of a only on the boundaries of the array. """ amin = numpy.amin(a[0,:]) amin = min(amin, numpy.amin(a[1:,-1])) amin = min(amin, numpy.amin(a[-1,:-1])) amin = min(amin, numpy.amin(a[1:-1,0])) amax = numpy.amax(a[0,:]) amax ...
6c007c6cf2c7c5774ca74365be8f63094864d962
3,658,151
from operator import add def offset_func(func, offset, *args): """ Offsets inputs by offset >>> double = lambda x: x * 2 >>> f = offset_func(double, (10,)) >>> f(1) 22 >>> f(300) 620 """ def _offset(*args): args2 = list(map(add, args, offset)) return func(*args2) ...
16526bc8302444a97ea27eb6088fe15604d3cf9e
3,658,152
def get_redshift_schemas(cursor, user): """ Get all the Amazon Redshift schemas on which the user has create permissions """ get_schemas_sql = "SELECT s.schemaname " \ "FROM pg_user u " \ "CROSS JOIN " \ "(SELECT DISTINCT schemaname FROM ...
2833205f3e1b863fe8e5a18da723cf1676a65485
3,658,153
def window_features(idx, window_size=100, overlap=10): """ Generate indexes for a sliding window with overlap :param array idx: The indexes that need to be windowed. :param int window_size: The size of the window. :param int overlap: How much should each window overlap. :return arr...
e10caae55424134a95c2085e5f54f73d81697e92
3,658,154
import os import json import subprocess def DetectVisualStudioPath(version_as_year): """Return path to the version_as_year of Visual Studio. """ year_to_version = { '2013': '12.0', '2015': '14.0', '2017': '15.0', '2019': '16.0', } if version_as_year not in year_to_version: raise Except...
034b2650909fde750e29765fd61704248079c418
3,658,155
from datetime import datetime def create_suburbans_answer(from_code, to_code, for_date, limit=3): """ Creates yandex suburbans answer for date by stations codes :param from_code: `from` yandex station code :type from_code: str :param to_code: `to` yandex station code :type to_code: str :p...
47b34617fdcd9fe83d1c0973c420363c05b9f70c
3,658,156
def update_user(usr): """ Update user and return new data :param usr: :return object: """ user = session.query(User).filter_by(id=usr['uid']).first() user.username = usr['username'] user.first_name = usr['first_name'] user.last_name = usr['last_name'] user.email = usr['email'] ...
d6c078c966443c609c29bb4ee046612c748bb192
3,658,157
from datetime import datetime def get_data(date_from=None, date_to=None, location=None): """Get covid data Retrieve covid data in pandas dataframe format with the time periods and countries provided. Parameters ---------- date_from : str, optional Start date of the data range with for...
14067432e5b6d51b60312707cc817acbe904ef0b
3,658,158
from typing import List from typing import Dict from typing import Any def group_by_lambda(array: List[dict], func: GroupFunc) -> Dict[Any, List[dict]]: """ Convert list of objects to dict of list of object when key of dict is generated by func. Example:: grouped = group_by_lambda(detections, lamb...
a92733a21b5e6e932be6d95ff79939ca26e3d429
3,658,159
def update(isamAppliance, is_primary, interface, remote, port, health_check_interval, health_check_timeout, check_mode=False, force=False): """ Updating HA configuration """ # Call to check function to see if configuration already exist update_required = _check_enable(isamAppliance, is_pr...
b4da64648a46e30e7220d308266e4c4cc68e25ff
3,658,160
import scipy import numpy def compare_images(image_file_name1, image_file_name2, no_print=True): """ Compare two images by calculating Manhattan and Zero norms """ # Source: http://stackoverflow.com/questions/189943/ # how-can-i-quantify-difference-between-two-images img1 = imread(image_file_name1).as...
c554750ae94b5925d283e0a9d8ff198e51abe29b
3,658,161
def prepare_update_mutation_classes(): """ Here it's preparing actual mutation classes for each model. :return: A tuple of all mutation classes """ _models = get_enabled_app_models() _classes = [] for m in _models: _attrs = prepare_update_mutation_class_attributes(model=m) # ...
27e450ea81000e81ebbf33db5d860c9a6b0adb23
3,658,162
from operator import le def makePacket(ID, instr, reg=None, params=None): """ This makes a generic packet. TODO: look a struct ... does that add value using it? 0xFF, 0xFF, 0xFD, 0x00, ID, LEN_L, LEN_H, INST, PARAM 1, PARAM 2, ..., PARAM N, CRC_L, CRC_H] in: ID - servo id instr - instruction reg - reg...
6553e5a62e22c9ad434b69e7f1e38060bd79e7e1
3,658,163
def vision_matched_template_get_pose(template_match): """ Get the pose of a previously detected template match. Use list operations to get specific entries, otherwise returns value of first entry. Parameters: template_match (List[MatchedTemplate3D] or MatchedTemplate3D): The template match(s) ...
b854da7a085934f4f3aba510e76852fb8c0a440a
3,658,164
def create_rotor(model, ring_setting=0): """Factory function to create and return a rotor of the given model name.""" if model in ROTORS: data = ROTORS[model] return Rotor(model, data['wiring'], ring_setting, data['stepping']) raise RotorError("Unknown rotor type: %s" % model)
193ab444c8b5527360498cb1c8911194f04742a3
3,658,165
def get_description(sequence, xrefs, taxid=None): """ Compute a description for the given sequence and optional taxon id. This function will use the rule scoring if possible, otherwise it will fall back to the previous scoring method. In addition, if the rule method cannot produce a name it also fal...
7885b3b7b2678f2ed3c80244ae07d106df9712f1
3,658,166
def compute_ess(samples): """Compute an estimate of the effective sample size (ESS). See the [Stan manual](https://mc-stan.org/docs/2_18/reference-manual/effective-sample-size-section.html) for a definition of the effective sample size in the context of MCMC. Args: samples: Tensor, vector (n,), float32 ...
8330c4f6efb4b23c5a25be18d29c07e946731716
3,658,167
import time def uptime(): """Returns uptime in milliseconds, starting at first call""" if not hasattr(uptime, "t0") is None: uptime.t0 = time.time() return int((time.time() - uptime.t0)*1000)
ff8dbe459cf7f349741cc8ac85b12e4d1dd88135
3,658,168
def load_plot(axis, plot, x_vals, y1=None, y2=None, y3=None, y4=None, title="", xlab="", ylab="", ltype=[1, 1, 1, 1], marker=['g-', 'r-', 'b-', 'k--']): """ Function to load the matplotlib plots. :param matplotlib.Axis axis: the matplotlib axis object. :param matplotlib.Figu...
ad7499f357349fde12537c6ceeb061bf6163709d
3,658,169
def _optimize_loop_axis(dim): """ Chooses kernel parameters including CUDA block size, grid size, and number of elements to compute per thread for the loop axis. The loop axis is the axis of the tensor for which a thread can compute multiple outputs. Uses a simple heuristic which tries to get at lea...
8f3e77cc772dcf848de76328832c0546a68c1f09
3,658,170
def no_zero(t): """ This function replaces all zeros in a tensor with ones. This allows us to take the logarithm and then sum over all values in the matrix. Args: t: tensor to be replaced returns: t: tensor with ones instead of zeros. """ t[t==0] = 1. return t
8119d1859dc8b248f5bb09b7cc0fc3b492d9b7bd
3,658,171
def php_implode(*args): """ >>> array = Array('lastname', 'email', 'phone') >>> php_implode(",", array) 'lastname,email,phone' >>> php_implode('hello', Array()) '' """ if len(args) == 1: assert isinstance(args, list) return "".join(args) assert len(args) == 2 as...
6f7c49ed340610c290d534a0c0edccd920a1e46e
3,658,172
import math def make_incompressible(velocity: Grid, domain: Domain, obstacles: tuple or list = (), solve_params: math.LinearSolve = math.LinearSolve(None, 1e-3), pressure_guess: CenteredGrid = None): """ Projects t...
73904675b5d0c5b74bd13c029b52f7a6592eddac
3,658,173
from datetime import datetime import os import shutil def create_and_empty_dir(tdir, label, suffix=datetime.now().strftime("%Y%m%d%H%M%S"), sep='__', simulation=False): """ Tests if directory exists, if not creates it. If yes, tests if readable/writable. Returns True if new directory created, False if alr...
4639c88fbd571c839288e527e229ed122e7f159f
3,658,174
from datetime import datetime import subprocess def no_source( time: datetime, glat: float, glon: float, Nbins: int, Talt: float, Thot: float ) -> xarray.Dataset: """testing only, may give non-physical results""" idate, utsec = glowdate(time) ip = gi.get_indices([time - timedelta(days=1), time], 81) ...
074ce675dac3c31fb2d750de053dd509dc928a6d
3,658,175
def reduce_to_1D(ds, latitude_range, latitude_name='Latitude', time_mean=True, time_name='Time'): """ TODO """ if isinstance(latitude_range, (int, float)): latitude_range = [latitude_range, latitude_range] elif len(latitude_range) == 1: latitude_range = [latitude_ran...
26d1bee437bffe66017fa8f9e3c03856b87d8b16
3,658,176
def get_y_generator_method(x_axis, y_axis): """Return the y-value generator method for the given x-axis. Arguments: x_axis -- an instance of an XAxis class y_axis -- an instance of a YAxis class Returns: A reference to the y-value generator if it was found, and otherwise None. """ try: method_name = AXIS_...
ab0f43743c91cfe9f51e8da3fe976f8c554af5c8
3,658,177
def generate_filename(table_type, table_format): """Generate the table's filename given its type and file format.""" ext = TABLE_FORMATS[table_format] return f'EIA_MER_{table_type}.{ext}'
076ef1e77cf4ec3c1be4fb602e5a1972eb75e826
3,658,178
def rescale_coords(df,session_epochs,maze_size_cm): """ rescale xy coordinates of each epoch into cm note: automatically detects linear track by x to y ratio input: df: [ts,x,y] pandas data frame session_epochs: nelpy epoch class with epoch times mazesize: list with size of ...
49da12dca1e3b7e30bf909a73505a129941bd3db
3,658,179
def newsreader_debug(): """Given an query, return that news debug mode.""" query = request.args.get('query') if query is None: return 'No provided.', 400 result = SL.news_check(query, debug=True) if result is None: return 'not found : %s' % query, 400 return result, 200
e5f16ed2d4253d734ce23e4b6eaf7fce3c5dbcbb
3,658,180
def get_vocabulary(query_tree): """Extracts the normalized search terms from the leaf nodes of a parsed query to construct the vocabulary for the text vectorization. Arguments --------- query_tree: pythonds.trees.BinaryTree The binary tree object representing a parsed search query. Each lea...
bd03f4894cd3f9a7964196bfb163335f84a048d7
3,658,181
def pubkey_to_address(pubkey): """Convert a public key (in hex) to a Bitcoin address""" return bin_to_b58check(hash_160(changebase(pubkey, 16, 256)))
bbfbe40346681a12d8b71ce8df6ef8670eb3e424
3,658,182
def transpose(A): """ Matrix transposition :rtype m: list :param m: a list of lists representing a matrix A :rtype: list :return: a list of lists representing the transpose of matrix A Example: -------- >>> A = [[0, -4, 4], [-3, -2, 0]] >>> print(transpose(A)) [[0.0, -3.0]...
0887166ac0f34d338bec1d95972667100403f26a
3,658,183
def find_point_in_section_list(point, section_list): """Returns the start of the section the given point belongs to. The given list is assumed to contain start points of consecutive sections, except for the final point, assumed to be the end point of the last section. For example, the list [5, 8, 30, 3...
47d5cda15b140ba8505ee658fd46ab090b2fda8a
3,658,184
import os import io import json import functools def mk_metrics_api(tm_env): """Factory to create metrics api. """ class _MetricsAPI(object): """Acess to the locally gathered metrics. """ def __init__(self): def _get(rsrc_id, timeframe, as_json=False): ...
1f122f5c71ba7abc4a5a341e240f8d76814210de
3,658,185
import os import types def generate_module(file_allocator, name): """ Generate an in-memory module from a generated Python implementation. """ assert name in file_allocator.allocated_files f = file_allocator.allocated_files[name] f.seek(0) data = f.read() modname, _ = os.path.splitex...
beab4cdf12fcdfeacef9f8a8607e995b771d6012
3,658,186
def all_reduce_sum(t, dim): """Like reduce_sum, but broadcasts sum out to every entry in reduced dim.""" t_shape = t.get_shape() rank = t.get_shape().ndims return tf.tile( tf.expand_dims(tf.reduce_sum(t, dim), dim), [1] * dim + [t_shape[dim].value] + [1] * (rank - dim - 1))
c4048c308ccf2b7550e125b63911183d097959f5
3,658,187
def get_deltas_from_bboxes_and_landmarks(prior_boxes, bboxes_and_landmarks): """Calculating bounding box and landmark deltas for given ground truth boxes and landmarks. inputs: prior_boxes = (total_bboxes, [center_x, center_y, width, height]) bboxes_and_landmarks = (batch_size, total_bboxes, [y1...
4945723b431657b643ef8799eeabacf0a745b8d2
3,658,188
def choose(population, sample): """ Returns ``population`` choose ``sample``, given by: n! / k!(n-k)!, where n == ``population`` and k == ``sample``. """ if sample > population: return 0 s = max(sample, population - sample) assert s <= population assert population > -1 i...
659eac683cae737888df74c0db21aa3ece746b33
3,658,189
def _where_cross(data,threshold): """return a list of Is where the data first crosses above threshold.""" Is=np.where(data>threshold)[0] Is=np.concatenate(([0],Is)) Ds=Is[:-1]-Is[1:]+1 return Is[np.where(Ds)[0]+1]
85fe8da97210e2eb7e3c9bca7074f0b0b88c425a
3,658,190
import csv def TVD_to_MD(well,TVD): """It returns the measure depth position for a well based on a true vertical depth Parameters ---------- well : str Selected well TVD : float Desire true vertical depth Returns ------- float MD : measure depth Attention --------- The input information comes ...
eadca9f9e5ae22fc7a6d9d31f7f0ee7ba4c26be4
3,658,191
def get_table_b_2_b(): """表 B.2 居住人数 2 人における照明設備の使用時間率 (b) 休日在宅 Args: Returns: list: 表 B.2 居住人数 2 人における照明設備の使用時間率 (b) 休日在宅 """ table_b_2_b = [ (0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00), (0.00, 0.00, 0.0...
06d29050c0bc61170eeddc75be76fe8bb8422edd
3,658,192
def eea(m, n): """ Compute numbers a, b such that a*m + b*n = gcd(m, n) using the Extended Euclidean algorithm. """ p, q, r, s = 1, 0, 0, 1 while n != 0: k = m // n m, n, p, q, r, s = n, m - k*n, q, p - k*q, s, r - k*s return (p, r)
56e1c59ac3a51e26d416fe5c65cf6612dbe56b8c
3,658,193
def string_quote(s): """ TODO(ssx): quick way to quote string """ return '"' + s + '"'
6d54e7661b9b0e17c45cb30cb6efff2c8fd913ae
3,658,194
def arcball_constrain_to_axis(point, axis): """Return sphere point perpendicular to axis.""" v = np.array(point, dtype=np.float64, copy=True) a = np.array(axis, dtype=np.float64, copy=True) v -= a * np.dot(a, v) # on plane n = vector_norm(v) if n > _EPS: if v[2] < 0.0: v *= ...
a58a80dd29ba785bd829b33ccb283e7c42993218
3,658,195
from typing import Mapping from typing import Any from typing import MutableMapping def text( node: "RenderTreeNode", renderer_funcs: Mapping[str, RendererFunc], options: Mapping[str, Any], env: MutableMapping, ) -> str: """Process a text token. Text should always be a child of an inline toke...
21b39fcdd21cba692a185e4de2c6f648c210e54b
3,658,196
def patch_importlib_util_find_spec(name,package=None): """ function used to temporarily redirect search for loaders to hickle_loader directory in test directory for testing loading of new loaders """ return find_spec("hickle.tests." + name.replace('.','_',1),package)
7a0082c0af92b4d79a93ae6bbd6d1be6ec0ec357
3,658,197
def format_msg_controller(data): """Prints a formatted message from a controller :param data: The bytes from the controller message :type data: bytes """ return format_message(data, 13, "Controller")
4d1f262fd673eb3948fbc46866931ab6bd7205ee
3,658,198
def initialize_window(icon, title, width, height, graphical): # pragma: no cover """ Initialise l'environnement graphique et la fenêtre. Parameters ---------- icon : Surface Icone de la fenêtre title : str Nom de la fenêtre width : int Largeur ...
dbc15729b0cb9548ff229ac69dd5d1f2e76c85e5
3,658,199