content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def parseAreas(area): """Parse the strings into address. This function is highly customized and demonstrates the general steps for transforming raw covid cases data to a list of address searchable in Google Map. Arguments: area: raw data downloaded from a news app Return: l: a list of human-readabl...
f205fca1d0b76aa63839a7c00552a790110998e4
17,500
def is_valid_instruction(instr: int, cpu: Cpu = Cpu.M68000) -> bool: """Check if an instruction is valid for the specified CPU type""" return bool(lib.m68k_is_valid_instruction(instr, cpu.value))
ae528e503e24698507971334d33dc6abf0f4c39c
17,501
import textwrap import sys def wrap_text(translations, linewrap=0): """Pretty print translations. If linewrap is set to 0 disble line wrapping. Parameters ---------- translations : list List of word translations. linewrap : int Maximum line length before wrapping. """ ...
adecfba77f017d4888fffda43c0466e9125b43ea
17,502
def docker_available(): """Check if Docker can be run.""" returncode = run.run(["docker", "images"], return_code=True) return returncode == 0
43ce2c7f5cb16657b4607faa5eac61b20e539e53
17,503
from datetime import datetime def is_bc(symbol): """ 判断是否背驰 :param symbol: :return: """ bars = get_kline(symbol, freq="30min", end_date=datetime.now(), count=1000) c = CZSC(bars, get_signals=get_selector_signals) factor_ = Factor( name="背驰选股", signals_any=[ ...
07dc2f01374f95544898375b8bc02b6128d70090
17,504
import time import calendar def IEEE2030_5Time(dt_obj, local=False): """ Return a proper IEEE2030_5 TimeType object for the dt_obj passed in. From IEEE 2030.5 spec: TimeType Object (Int64) Time is a signed 64 bit value representing the number of seconds since 0...
fbb9466e927f1162226760efbe609bf3e779e163
17,505
def learning_rate_schedule(params, global_step): """Handles learning rate scaling, linear warmup, and learning rate decay. Args: params: A dictionary that defines hyperparameters of model. global_step: A tensor representing current global step. Returns: A tensor representing current learning rate. ...
b88d67dd0d241d26bf183e90e3d3c215e0abd957
17,506
import logging import os import subprocess def run( command, cwd=None, capture_output=False, input=None, check=True, **subprocess_run_kwargs ): """ Wrapper for subprocess.run() that sets some sane defaults """ logging.info("Running {} in {}".format(" ".join(command), cwd or os.getcwd()...
5595721fc28da8a87230a1d367cbc5c3bacdc779
17,507
def profile(step): """ Profiles a Pipeline step and save the results as HTML file in the project output directory. Usage: @profile def step(self): pass """ @wraps(step) def wrapper(*arg, **kwargs): pipeline_instance = arg[0] project = pipeline_in...
f300000a0471a2439ae951a2d33b8a03aa61b333
17,508
from modin.pandas.series import Series def make_dataframe_wrapper(DataFrame): """ Prepares a "delivering wrapper" proxy class for DataFrame. It makes DF.loc, DF.groupby() and other methods listed below deliver their arguments to remote end by value. """ conn = get_connection() class Obt...
a2d523f6e9cb9d23ae722195a091d8e2b68139cc
17,509
def download_cmems_ts(lats, lons, t0, tf, variables, fn=None): """Subset CMEMS output using OpenDAP :params: lats = [south, north] limits of bbox lons = [west, east] limits of bbox t0 = datetime for start of time series tf = datetime for end of time series variables = li...
b97de3a7428d6e2b50ab36b28e47afe479c24042
17,510
def construct_gpu_info(statuses): """ util for unit test case """ m = {} for status in statuses: m[status.minor] = status m[status.uuid] = status return m
b8b2f41799b863d2e22066005b901f17a610d858
17,511
def load_data_time_machine(batch_size, num_steps, use_random_iter=False, max_tokens=10000): """Return the iterator and the vocabulary of the time machine dataset.""" data_iter = SeqDataLoader(batch_size, num_steps, use_random_iter, max_tokens) return ...
ed9d6b63c34cf9d1a750daabbdb81e03e467e939
17,512
def scan_paths(paths, only_detect, recursive, module_filter): """ Scans paths for known bots and dumps information from them @rtype : dict @param paths: list of paths to check for files @param only_detect: only detect known bots, don't process configuration information @param recursive: recursi...
f58216f1ed5955828738689fa67522a8cc0e497a
17,513
def generate_masks(input_size, output_size=1, observed=None): """ Generates some basic input and output masks. If C{input_size} is an integer, the number of columns of the mask will be that integer. If C{input_size} is a list or tuple, a mask with multiple channels is created, which can be used with RGB images, f...
dee12176f72a158e9f39036981fa1dbd6be81817
17,514
import yaml import logging import sys def parse_config_file(config): """ Load config file (primarily for endpoints) """ fail = False with open(config, 'r') as fp: content = yaml.load(fp.read()) if 'endpoints' not in content.keys(): return for title, items in content['endpoi...
2a9d4a47d5c5b8eea9fda0b33284a1c91bfc19b6
17,515
def average(time_array,height_array,data_array,height_bin_size=100,time_bin_size=3600): """ average: function that averages the radar signal by height and time Args: time_array: numpy 1d array with timestamps height_array: numpy 1d array with height range data_array: numpy 2d arra...
710f4c8821cffe110511bda0dd3d4fd3052f33a9
17,516
def daily_report(api, space_name, charts, num_days=1, end_time=None): """Get a report of SLO Compliance for the previous day(s) Returns: list of dicts of threshold breaches. Example Dict format: {u'measure_time': 1478462400, u'value': 115.58158333333334} :param api: An instance of sloc_report.LibratoA...
86d25f5f2dd93a827f5f7b8cd44287f549921438
17,517
def new_pitch(): """ route to new pitch form :return: """ form = PitchForm() if form.validate_on_submit(): title = form.title.data pitch = form.pitch.data category = form.category.data fresh_pitch = Pitch(title=title, pitch_actual=pitch, category=category, user_...
a7724149a7e6b9d545559fef643dcc8fd2f5c731
17,518
def get_entity_bios(seq,id2label): """Gets entities from sequence. note: BIOS Args: seq (list): sequence of labels. Returns: list: list of (chunk_type, chunk_start, chunk_end). Example: # >>> seq = ['B-PER', 'I-PER', 'O', 'S-LOC'] # >>> get_entity_bios(seq) [[...
25219d29ba8ecb2d44ca5a8245059432f3220d8d
17,519
import torch import copy def early_stopping_train(model, X, Y_, x_test, y_test, param_niter=20001, param_delta=0.1): """Arguments: - X: model inputs [NxD], type: torch.Tensor - Y_: ground truth [Nx1], type: torch.Tensor - param_niter: number of training iterations - param_delta: learning rate ...
83a8acdd24a4fde3db77184c3b4a99a1c1783349
17,520
def my_vtk_grid_props(vtk_reader): """ Get grid properties from vtk_reader instance. Parameters ---------- vtk_reader: vtk Reader instance vtk Reader containing information about a vtk-file. Returns ---------- step_x : float For regular grid, stepsize in x-direction. ...
26ef8a51648ea487372ae06b54c8ccf953aeb414
17,521
def make_env(stack=True, scale_rew=True): """ Create an environment with some standard wrappers. """ env = grc.RemoteEnv('tmp/sock') env = SonicDiscretizer(env) if scale_rew: env = RewardScaler(env) env = WarpFrame(env) if stack: env = FrameStack(env, 4) return env
347376103fa00d4d43714f30097b0d129ef45f43
17,522
def plot_distr_cumsum(result, measure="degree", scale=['log', 'log'], figures=[], prefix="", show_std=True, show_figs=True, mode="safe", colors=('r', 'b')): """ plots the cummulative distribution functions special care has to be taken because averaging these is not trivial in comparison to e.g. degree """ ...
6b0a526cf8f09dd66ac7b0988c9445d57416be21
17,523
import socket import sys def recvall(sock, n, silent=False): """Helper function for recv_msg().""" data = b'' while len(data) < n: try: packet = sock.recv(n - len(data)) if not packet: return None data += packet except (socket.error, OSEr...
0e5800929dfd2829fb922bbc0904a1ed893e79bf
17,524
import sys import os def install_jenkins(dest_folder=".", fLOG=print, install=True, version=None): """ install `Jenkins <http://jenkins-ci.org/>`_ (only on Windows) @param dest_folder where to download the setup @param fLOG logging function @param install ...
7c67cc69f2fe3add7a97abbd8bb19451ee36fddd
17,525
def state_space_model(A, z_t_minus_1, B, u_t_minus_1): """ Calculates the state at time t given the state at time t-1 and the control inputs applied at time t-1 """ state_estimate_t = (A @ z_t_minus_1) + (B @ u_t_minus_1) return state_estimate_t
0e04207028df8d4162c88aad6606e792ef618f5a
17,526
def get_post(id , check_author=True): """Get a post and its author by id. Checks that the id exists and optionally that the current user is the author. :param id: id of post to get :param check_author: require the current user to be the author :return: the post with author information :rai...
a15ac3816d134f1dd89bf690c2f800e412d7219b
17,527
def get_pixel(x, y): """Get the RGB value of a single pixel. :param x: Horizontal position from 0 to 7 :param y: Veritcal position from 0 to 7 """ global _pixel_map return _pixel_map[y][x]
47a77090683a5b8e7178b3c7d83ae5b1a090342f
17,528
from typing import Callable import re def check_for_NAs(func: Callable) -> Callable: """ This decorator function checks whether the input string qualifies as an NA. If it does it will return True immediately. Otherwise it will run the function it decorates. """ def inner(string: str, *args, *...
e9336cca2e6cd69f81f6aef1d11dc259492774f8
17,529
from typing import Union from typing import Callable def integrateEP_w0_ode( w_init: np.ndarray, w0: Union[ Callable, np.ndarray ], w0prime: Union[ Callable, np.ndarray ], B: np.ndarray, s: np.ndarray, s0: float = 0, ds: float = None, R_init: np.ndarray = np.eye( 3 ), B...
75a042b94ac46b7ecbb86e23abacde0d4034b9fe
17,530
def change_coordinate_frame(keypoints, window, scope=None): """Changes coordinate frame of the keypoints to be relative to window's frame. Given a window of the form [y_min, x_min, y_max, x_max], changes keypoint coordinates from keypoints of shape [num_instances, num_keypoints, 2] to be relative to this windo...
2aa69a55d7f8177784afb41f50cd7ccfbffdbde3
17,531
import os def eval_log_type(env_var_name): """get the log type from environment variable""" ls_log = os.environ.get(env_var_name, '').lower().strip() return ls_log if ls_log in LOG_LEVELS else False
7d2711075b830fc5861961ed52714b58fd01b96b
17,532
import random def _get_name(filename: str) -> str: """ Function returns a random name (first or last) from the filename given as the argument. Internal function. Not to be imported. """ LINE_WIDTH: int = 20 + 1 # 1 for \n with open(filename) as names: try: total_n...
1b4cd75488c6bd1814340aee5669d1631318e77f
17,533
def map_to_udm_section_associations(enrollments_df: DataFrame) -> DataFrame: """ Maps a DataFrame containing Canvas enrollments into the Ed-Fi LMS Unified Data Model (UDM) format. Parameters ---------- enrollments_df: DataFrame Pandas DataFrame containing all Canvas enrollments Ret...
303223302e326854f7a19b2f3c9d0b626a2807bc
17,534
def plot_electrodes(mris, grid, values=None, ref_label=None, functional=None): """ """ surf = mris.get('pial', None) if surf is None: surf = mris.get('dura', None) pos = grid['pos'].reshape(-1, 3) norm = grid['norm'].reshape(-1, 3) labels = grid['label'].reshape(-1) right_or_le...
0bcc5545c625675be080e6b70bf7a74d247ba1c9
17,535
from typing import Tuple def _get_laplace_matrix(bcs: Boundaries) -> Tuple[np.ndarray, np.ndarray]: """get sparse matrix for laplace operator on a 1d Cartesian grid Args: bcs (:class:`~pde.grids.boundaries.axes.Boundaries`): {ARG_BOUNDARIES_INSTANCE} Returns: tuple: A sparse ...
80880c7fb1d54a7d4502e1096c2f2ade4d30ce21
17,536
import warnings def column_or_1d(y, warn=False): """ Ravel column or 1d numpy array, else raises an error Parameters ---------- y : array-like warn : boolean, default False To control display of warnings. Returns ------- y : array """ shape = np.shape(y) if len(s...
ef3a5bfe7a1ae07b925c1d9b897bce0eff29b275
17,537
def conv_tower( inputs, filters_init, filters_end=None, filters_mult=None, divisible_by=1, repeat=1, **kwargs ): """Construct a reducing convolution block. Args: inputs: [batch_size, seq_length, features] input sequence filters_init: Initial Conv1D filters ...
82ff878423309e2963090a9569f14090a85d30e5
17,538
def edit_coach(request, coach_id): """ Edit a coach's information """ if not request.user.is_superuser: messages.error(request, 'Sorry, only the owners can do that.') return redirect(reverse('home')) coach = get_object_or_404(Coach, pk=coach_id) if request.method == 'POST': for...
ecaf07df3249d3349928b4e9da9c0524b27e603e
17,539
import torch def estimate_translation(S, joints_2d, focal_length=5000., img_size=224., use_all_joints=False, rotation=None): """Find camera translation that brings 3D joints S closest to 2D...
70b5cc75dc28919b6bb6cea70b49eae8ca593452
17,540
import random def create_midterm_data(all_students): """ Create the midterm data set Ten questions, two from each topic, a percentage of students did not show up, use it as an example of merge Rules: - International students have a 10% drop out rate - Performance changes by PROGRAM! ...
b1f946ebab616362113ada54a17cc3e857b33f98
17,541
def identify_outliers(x_vals, y_vals, obj_func, outlier_fraction=0.1): """Finds the indices of outliers in the provided data to prune for subsequent curve fitting Args: x_vals (np.array): the x values of the data being analyzed y_vals (np.array): the y values of the data being analyzed ...
e1742747ac63b34c39d1e57cbc896b9df5af85e0
17,542
def GetTypeMapperFlag(messages): """Helper to get a choice flag from the commitment type enum.""" return arg_utils.ChoiceEnumMapper( '--type', messages.Commitment.TypeValueValuesEnum, help_str=( 'Type of commitment. `memory-optimized` indicates that the ' 'commitment is for mem...
f00e645a2dbfcae94a33fc5b016809f72e87c0a9
17,543
from typing import List def gaussian_2Dclusters(n_clusters: int, n_points: int, means: List[float], cov_matrices: List[float]): """ Creates a set of clustered data points, where the distribution within each cluster is Gaussian. P...
9c950f9c5541c343a3a9a27dc3bff34be2006f8b
17,544
def prepare_concepts_index(create=False): """ Creates the settings and mappings in Elasticsearch to support term search """ index_settings = { "settings": {"analysis": {"analyzer": {"folding": {"tokenizer": "standard", "filter": ["lowercase", "asciifolding"]}}}}, "mappings": { ...
a33e7e6172c7a7c8577abab77cb467125e629e39
17,545
def pack_wrapper(module, att_feats, att_masks): """ for batch computation, pack sequences with different lenghth with explicit setting the batch size at each time step """ if att_masks is not None: packed, inv_ix = sort_pack_padded_sequence(att_feats, att_masks.data.long().sum(1)) return...
ff5e02ac5977cf525a0e2f2a96714ff8a6cf1fe3
17,546
from sys import exc_info def processor(preprocessed_data_id, param_id, param_constructor): """Dispatch the processor work""" preprocessed_data = PreprocessedData(preprocessed_data_id) params = param_constructor(param_id) sp = StudyProcessor() try: process_out = sp(preprocessed_data, param...
25c2771c1f627d8eb24b4e214e419ebab779352e
17,547
def recommendation_inspiredby(film: str, limit: int=20) -> list: """Movie recommandations from the same inspiration with selected movie Args: film (str): URI of the selected movie limit (int, optional): Maximum number of results to return. Defaults to 20. Returns: list: matching mo...
d70d6a30eabc5d1a5b5a7c3b0cebc28a9dcb0fa9
17,548
import string def str2twixt(move): """ Converts one move string to a twixt backend class move. Handles both T1-style coordinates (e.g.: 'd5', 'f18'') as well as tsgf- style coordinates (e.g.: 'fg', 'bi') as well as special strings ('swap' and 'resign'). It can handle letter in upper as well as lowerc...
fe1e644519f7d6fe7df2be8a38754ba230981a91
17,549
from datetime import datetime import re def celery_health_view(request): """Admin view that displays the celery configuration and health.""" if request.method == 'POST': celery_health_task.delay(datetime.now()) messages.success(request, 'Health task created.') return HttpResponseRedire...
52f7fb76af5dc5557e22976b1930c19e6249f1cc
17,550
def get_n_runs(slurm_array_file): """Reads the run.sh file to figure out how many conformers or rotors were meant to run """ with open(slurm_array_file, 'r') as f: for line in f: if 'SBATCH --array=' in line: token = line.split('-')[-1] n_runs = 1 + int(to...
5574ef40ef87c9ec5d9bbf2abd7d80b62cead2ab
17,551
def consume(pipeline, data, cleanup=None, **node_contexts): """Handles node contexts before/after calling pipeline.consume() Note ---- It would have been better to subclass Pipeline and implement this logic right before/after the core consume() call, but there is a bug in pickle that prevents t...
b4d3df619600892fe02d418a19993af1f0715d84
17,552
def get_field_attribute(field): """ Format and return a whole attribute string consists of attribute name in snake case and field type """ field_name = get_field_name(field.name.value) field_type = get_field_type(field) strawberry_type = get_strawberry_type( field_name, field.descrip...
fbbe2dbdf6c5f0427365fbbb0d5f43df8bb74678
17,553
def shuffle_data(data): """ Shuffle the data """ rng_state = np.random.get_state() for c, d in data.items(): np.random.set_state(rng_state) np.random.shuffle(d) data[c] = d return data
5a1fa1f81fbec54092c8d7b50ebf75f8edb526c7
17,554
def index(current_user=None): """ Display home page """ return render_template('homepage.html', username=current_user['name'], \ logged_in=current_user['is_authenticated'], \ display_error=request.cookies.get('last_attempt_error') == 'True', \ login_banner=APP.config['LOGIN_BANNER'])
287d8101ef318cb7ca308340e0d11ab157538450
17,555
import os import pandas def _read_data_file(data_path): """ Reads a data file into a :class:`pandas:pandas.DataFrame` object. Parameters ---------- data_path : str Path of the data file with extension. Supports ``.csv``, ``.xlsx``/``.xls``, ``.json``, and ``.xml``. Returns ------...
9ddfed58134a564ed63f712e305090ad6d9b6d41
17,556
def disable_admin_access(session, return_type=None, **kwargs): """ Disable Admin acccess :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type return_type: str :param return_type: If this is set to the string 'json', this function ...
5ac6c09ed3098f5b99baa2d5749d7b42a465e9f4
17,557
def _get_bbox_indices(x, y, bbox): """ Convert bbox values to array indices :param x, y: arrays with the X, Y coordinates :param bbox: minx, miny, maxx, maxy values :return: bbox converted to array indices """ minx, miny, maxx, maxy = bbox xindices, = np.where((x >= minx) & (x <= maxx))...
dd71f1852971dbd2d3026c1720f9f477b3093fc8
17,558
def skill_competencies(): """ Called by S3OptionsFilter to provide the competency options for a particular Skill Type """ table = s3db.hrm_skill ttable = s3db.hrm_skill_type rtable = s3db.hrm_competency_rating query = (table.id == request.args[0]) & \ (table.skil...
7edc87d20d36d25b05337365ed903126ef02742f
17,559
def calc_field_changes(element, np_id): """ Walk up the tree of geo-locations, finding the new parents These will be set onto all the museumobjects. """ fieldname = element._meta.concrete_model.museumobject_set.\ related.field.name field_changes = {} field_changes[fieldname] = e...
cba816488dcf10a774bc18b1b3f6498e1d8dc3d8
17,560
def index(request, _): """ 路由请求 `` request `` 请求对象 """ if request.method == 'GET' or request.method == 'get': return index_page(request) elif request.method == 'POST' or request.method == 'post': return send_wxmsg(request) else: rsp = JsonResponse({'code': -1, 'erro...
5006cf1e5cb23e49b17e9083fca66c7731f5559b
17,561
def get_daisy_client(): """Get Daisy client instance.""" endpoint = conf.get('discoverd', 'daisy_url') return daisy_client.Client(version=1, endpoint=endpoint)
6ed0df1259672becfca3197f2d115a1c789306a1
17,562
from pathlib import Path import multiprocessing def intermediate_statistics( scores, ground_truth, audio_durations, *, segment_length=1., time_decimals=6, num_jobs=1, ): """ Args: scores (dict, str, pathlib.Path): dict of SED score DataFrames (cf. sed_scores_eval.utils.sco...
5039bec8ceafed7952833aa2f39c5d44d0909790
17,563
def vnorm(v1): """vnorm(ConstSpiceDouble [3] v1) -> SpiceDouble""" return _cspyce0.vnorm(v1)
00016eaa6a765f564ce247c4126c4a360aa2b60d
17,564
def mean_iou(y_true, y_pred): """F2 loss""" prec = [] for t in np.arange(0.5, 1.0, 0.05): y_pred_ = tf.to_int32(y_pred > t) score, up_opt = tf.metrics.mean_iou(y_true, y_pred_, 2) K.get_session().run(tf.local_variables_initializer()) with tf.control_dependencies([up_opt]): ...
a2503703bae7c8c83b42ac93406178bc4c52a675
17,565
def _encode_string_parts(value, encodings): """Convert a unicode string into a byte string using the given list of encodings. This is invoked if `encode_string` failed to encode `value` with a single encoding. We try instead to use different encodings for different parts of the string, using the enc...
58f514ed7cbd9a6e2c10e6d8b22f32a32d71d6a7
17,566
import re import os def get_files(path, pattern): """ Recursively find all files rooted in <path> that match the regexp <pattern> """ L = [] if not path.endswith('/'): path += '/' # base case: path is just a file if (re.match(pattern, os.path.basename(path)) != None) and os.path.isfile(path):...
0e71a8290b6d011eeebd75fc1b07ba5fb945521a
17,567
def SocketHandler(qt): """ `SocketHandler` wraps a websocket connection. HTTP GET /ws """ class _handler(websocket.WebSocketHandler): def check_origin(self, origin): return True def open(self): qt.log("new socket open ...") qt.register_socket(self...
001f9dbee77560d4d5970fce731084b5a9cca7af
17,568
from typing import Optional def var_swap(asset: Asset, tenor: str, forward_start_date: Optional[str] = None, *, source: str = None, real_time: bool = False) -> Series: """ Strike such that the price of an uncapped variance swap on the underlying index is zero at inception. If forward start da...
0991ff1fb889b14b6a3d3e850caa2364a4f4d044
17,569
def extract_flow_global_roi(flow_x, flow_y, box): """ create global roi cropped flow image (for numpy image) image: numpy array image box: list of [xmin, ymin, xmax, ymax] """ flow_x_roi = extract_global_roi(flow_x, box) flow_y_roi = extract_global_roi(flow_y, box) if flo...
1b6d22d413693e978dc31cfbf1708c93d9256cf1
17,570
from unittest.mock import patch def patch_shell(response=None, error=False): """Mock the `AdbDeviceTcpFake.shell` and `DeviceFake.shell` methods.""" def shell_success(self, cmd): """Mock the `AdbDeviceTcpFake.shell` and `DeviceFake.shell` methods when they are successful.""" self.shell_cmd = ...
cdf4df2bb383c4c8b49b59442550e2c73ca828aa
17,571
def __setAdjacent_square__(self, pos): """ Sets all adjacencies in the map for a map with square tiles. """ self.__checkIndices__(pos) i, j = pos; adjacent = [] # Function to filter out nonexistent cells. def filterfn(p): do_not_filter = 0 <= p[0] < self.__numrows__ and 0 <= p[1] < s...
ebdd3ee3d0104b5bd26cc48e07760de027615263
17,572
def model_definition_nested_events(): """Test model for state- and parameter-dependent heavisides. ODEs ---- d/dt x_1: inflow_1 - decay_1 * x1 d/dt x_2: - decay_2 * x_2 Events: ------- event_1: trigger: x_1 > inflow_1 / decay_2 bolus: [[ 0], ...
f42a5c7c01fd6f966ecec11b28c9620022dd7aaf
17,573
async def address_balance_history( request: Request, address: Address, token_id: TokenID = Query(None, description="Optional token id"), timestamps: bool = Query( False, description="Include timestamps in addition to block heights" ), flat: bool | None = Query(True, description="Return d...
2fcae2ab775611e51fd056e98928afbcb6bf1278
17,574
def load(as_pandas=None): """ Loads the Grunfeld data and returns a Dataset class. Parameters ---------- as_pandas : bool Flag indicating whether to return pandas DataFrames and Series or numpy recarrays and arrays. If True, returns pandas. Returns ------- Dataset ...
183c37228619b835a36dc4a1cc1e1a7649fca6ec
17,575
def rule_if_system(system_rule, non_system_rule, context): """Helper function to pick a rule based on system-ness of context. This can be used (with functools.partial) to choose between two rule names, based on whether or not the context has system scope. Specifically if we will fail the parent of a ne...
2149c2ffdd6afdd64f7d33a2de4c6a23b3143dee
17,576
def find_inactive_ranges(note_sequence): """Returns ranges where no notes are active in the note_sequence.""" start_sequence = sorted( note_sequence.notes, key=lambda note: note.start_time, reverse=True) end_sequence = sorted( note_sequence.notes, key=lambda note: note.end_time, reverse=True) notes...
8db86584908283385958c5f710fb36d95795f7b1
17,577
def is_connected(G): """Returns True if the graph is connected, False otherwise. Parameters ---------- G : NetworkX Graph An undirected graph. Returns ------- connected : bool True if the graph is connected, false otherwise. Raises ------ NetworkXNotImplemented: ...
03a2602629db60565702bee044a1d70ba026a8aa
17,578
import math def show_result(img, result, skeleton=None, kpt_score_thr=0.3, bbox_color=None, pose_kpt_color=None, pose_limb_color=None, radius=4, thickness=1, font_scale=0.5, ...
af90da2b30ff9891613654d70724162ce7b4d702
17,579
def D2(X, Y, Y2=None, YT=None): """ Calculate the pointwise (squared) distance. Arguments: X: of shape (n_sample, n_feature). Y: of shape (n_center, n_feature). Y2: of shape (1, n_center). YT: of shape (n_feature, n_center). Returns: pointwise distances (n_sample, n...
daa8940e939eb2806e043f9b4521bf8cd1aefd2e
17,580
def read_table(path): """Lee un archivo tabular (CSV o XLSX) a una lista de diccionarios. La extensión del archivo debe ser ".csv" o ".xlsx". En función de ella se decidirá el método a usar para leerlo. Si recibe una lista, comprueba que todos sus diccionarios tengan las mismas claves y de ser así...
e2de4230f64cd45f3ff4caaa068c7df85c0c30df
17,581
from typing import Dict from typing import Any from typing import cast def spec_from_json_dict( json_dict: Dict[str, Any] ) -> FieldSpec: """ Turns a dictionary into the appropriate FieldSpec object. :param dict json_dict: A dictionary with properties. :raises InvalidSchemaError: ...
9bf557364a7a17cea0c84c65ece5b1d0e3983b2f
17,582
import scipy def hyp_pfq(A, B, x, out=None, n=0): """ This function is decorated weirdly because its extra params are lists. """ out = np_hyp_pfq([a+n for a in A], [b+n for b in B], x, out) with np.errstate(invalid='ignore'): out *= np.prod([scipy.special.poch(a, n) for a in A]) ou...
f1d9e0454fa63d24b1a8a403bbae12e00b818bb2
17,583
from typing import Optional from datetime import datetime def create_new_token( data: dict, expires_delta: Optional[timedelta] = None, page_only: bool = False): """Creates a token with the given permission and expiry""" to_encode = data.copy() if page_only: expires = dateti...
3a0a2aebc6b814850333a5d4f5db72b1396cf208
17,584
from pathlib import Path from typing import Union import re def parse_json_year_date(year: Number, fullpath: Path) -> Union[Path, None]: """ Filtra os arquivos json por ano. """ if not isinstance(fullpath, Path): raise TypeError("O parâmetro path deve do tipo Path.") pattern_finder = re.se...
1d482bf916c3574225fdc31e700fb570c47555b1
17,585
from malaya_speech.utils import describe_availability def available_fastspeech2(): """ List available FastSpeech2, Text to Mel models. """ return describe_availability( _fastspeech2_availability, text = '`husein` and `haqkiem` combined loss from training set', )
b7fa7f6132eb478cf27068a4377688f8b3ec5c7b
17,586
def solve(A, b, method='gauss', verbose=0, eps=1e-6, max_itration_times=100000, omega=1.9375): """ Solve equations in specified method. :param A: coefficient matrix of the equations :param b: vector :param method: the way to solve equations :param verbose: whether show the running information ...
50c7cdc5a2c8b146a062c028c4cb684c0b7efc2f
17,587
def returns_unknown(): """Tuples are a not-supported type.""" return 1, 2, 3
9fc003c890b4e053362c684b1a5f0dfca59bbe42
17,588
def get_user( cmd, app_id: str, token: str, assignee: str, api_version: str, central_dns_suffix=CENTRAL_ENDPOINT, ) -> User: """ Get information for the specified user. Args: cmd: command passed into az app_id: name of app (used for forming request URL) token...
cc387259c97ebfecadd5d82dc6acf8f970d19478
17,589
import subprocess def run_test( bess_addr, ptfdir, trex_server_addr=None, extra_args=(), ): """ Runs PTF tests included in provided directory. """ # create a dummy interface for PTF if not create_dummy_interface() or not set_up_interfaces([DUMMY_IFACE_NAME]): return False ...
c1a41561a0d6f37b8f5693dbaa8a1fc2799e0786
17,590
def get(fg, bg=None, attribute = 0): """ Return string with ANSI escape code for set text colors fg: html code or color index for text color attribute: use Attribute class variables """ if type(fg) is str: bg = bg if bg else "#000000" return by_hex(fg, bg, attribute=attribute) ...
16ee7ea3bd5c66c415a6466632cee1c5b337696b
17,591
def get_Qi(Q,i,const_ij,m): """ Aim: ---- Equalising two polynomials where one is obtained by a SOS decomposition in the canonical basis and the other one is expressed in the Laguerre basis. Parameters ---------- Q : matrix for the SOS decomposition i : integer ...
a54313c8763777840c4a018dedb2fe6363e09d55
17,592
import os def run_openlego(analyze_mdao_definitions, cmdows_dir=None, initial_file_path=None, data_folder=None, run_type='test', approx_totals=False, driver_debug_print=False): # type: (Union[int, list, str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[bool], Optional[boo...
b198f9dfbbf051a3b119a1c4fa8002f3c2e8183a
17,593
def strToBool(s): """ Converts string s to a boolean """ assert type(s) == str or type(s) == unicode b_dict = {'true': True, 'false': False, 'yes': True, 'no': False} return b_dict[s.lower()]
84e59429523e6e59a90739b0f1b160fa9e84bdc8
17,594
import json def publish_to_sns(topic_name, message, region=None): """ Post a message to an SNS topic """ AWS = AWSCachedClient(region) # cached client object partition = None if region: partition = partition_from_region(region) else: partition = 'aws' region = 'us...
5a3c35c0367873e2c0b3c79a176b7c384d2b74ed
17,595
import os def bandpass_voxels(realigned_file, bandpass_freqs, sample_period=None): """ Performs ideal bandpass filtering on each voxel time-series. Parameters ---------- realigned_file : string Path of a realigned nifti file. bandpass_freqs : tuple Tuple containing the ban...
0792647b7faa1beaa517d99f448d554168401446
17,596
from typing import List from typing import Tuple def get_subset( classes: List, train_data, train_labels, val_data, val_labels, test_data, test_labels, ) -> Tuple: """ creates a binary subset of training, validation, and testing set using the specified list of classes to select ...
8857b7f5c4563692b3236b68889201bd3a28507e
17,597
def to_xyzw(matrix): """Convenience/readibility function to bring spatial (trailing) axis to start. Args: matrix (...x4 array): Input matrix. Returns: 4x... array """ return np.rollaxis(matrix, -1)
7c74b9bd6dc271db4a5dd925bbcfec4eef7ca791
17,598
import numpy def do_3d_pooling(feature_matrix, stride_length_px=2, pooling_type_string=MAX_POOLING_TYPE_STRING): """Pools 3-D feature maps. :param feature_matrix: Input feature maps (numpy array). Dimensions must be M x N x H x C or 1 x M x N x H x C. :param stride_length_px: S...
180ceae7364dcd1dd55d23a00389d0c3bb43cc38
17,599