content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def center_film(structure): """ Centers a film at z=0 Args: structure: AiiDA structure returns: AiiDA structure """ if structure.pbc != (True, True, False): raise TypeError('Only film structures having surface normal to z are supported') sorted_struc = sort_atoms_z_value(...
121a9252e5a0da2e50f4b7fdf95a7c37a1245695
34,400
def get_stop_response(): """ end the session, user wants to quit the game """ speech_output = STOP_MESSAGE return response(speech_response(speech_output, True))
4843b735859428a4d12337a7b26f42ed40900c2f
34,401
import re def __extract_clusters_from_html(html): """Parse the clusters of a balancer manager page. :param html: The raw HTML of the balancer manager page. :returns: a list of clusters. """ clusters = [] for section in re.findall('(<h3>.+?)<hr />', html.replace('\n', '')): cluster = _...
2c5077e264a7bf853886d55c2e9c64b149da40a0
34,402
from typing import Union def _value_to_int(value: Union[int, str]) -> int: """String value to int.""" try: return int(value) except ValueError as error: raise Exception("The value is not integer")
635afb6d75edec8df64b12dad8db7dd408502250
34,403
import calendar def era5_temp_anomalies(obs_directory, save_directory, start_range='1999-01-01', end_range='2019-12-31', save=False, author=None): """ Create ERA5 temperature hindcast anomalies. Args: obs_directory (str): Directory where files are located. save...
7c49cc3aad3c9b92e9520f0b709d4118f59afec3
34,404
def is_supported(browser): """ 指定したブラウザがサポート対象かチェック Attributes: browser (str): チェック対象ブラウザ Returns: bool: ブラウザのサポート有無 """ return browser in _browser_modules
d3e49446b8c333f72b5e652899491b46960fd2ae
34,405
from typing import Sequence from typing import Tuple import operator def pie_marker( ratios: Sequence[float], res: int = 50, direction: str = "+", start: float = 0.0, ) -> Tuple[list, list]: """ Create each slice of pie as a separate marker. Parameters: r...
61522394a5356f1a7c0e9e2e112c0025ae7dc9cc
34,406
def indref_dust_wolff_2009(wav): """ This function returns the index of refraction for dust. The data used are nominally taken from Wolff (2009), which extends from 236 nm to 98.5423 micron. There are only 5 points in our wavelength region of interest. For the moment, we use the compendium provided by the Ames GC...
864bc7efd908c9da47f050e82315f1ddd48ad500
34,407
from re import DEBUG import sys def copy_rules(ctx, institution, requirement_id): """ copy_rules : COPY_RULES expression SEMICOLON?; The expression is a requirement_id enclosed in parentheses (RA######). """ if DEBUG: print(f'*** copy_rules({class_name(ctx)}, {institution}, {requirement_...
4070e812485858a84b4411f8f539f4cc4a2ca7eb
34,408
def select_columns( df: pd.DataFrame, *args, invert: bool = False, ) -> pd.DataFrame: """ Method-chainable selection of columns. Not applicable to MultiIndex columns. It accepts a string, shell-like glob strings `(*string*)`, regex, slice, array-like object, or a list of the previous o...
a0881fbcf078f4c501b5dd0d706b7801ab47794d
34,409
def compute_distance(location_1, location_2): """ Euclidean distance between 3D points. Parameters ---------- location_1 : carla.Location Start point of the measurement. location_2 : carla.Location End point of the measurement. """ x = location_2.x - location_1.x y ...
8511a59cb949a355ceaaeb85035474285412ba49
34,410
def ewma_2d(x, halflife): """ Exponentially Weighted Moving Average, optimised for 2D data sets. """ assert x.ndim == 2 assert np.isfinite(halflife) and halflife > 0 decay_coefficient = np.exp(np.log(0.5) / halflife) out = np.empty_like(x, dtype=np.float64) for i in range(out.shape...
23232e3050dd6280a1a0819ad5261a8c9545cfd3
34,411
def DT2str(dt): """ convert a datetime to a string in the GNOME format. """ dt_string = "%3i, %3i, %5i, %3i, %3i"%(dt.day, dt.month, dt.year, dt.hour, dt.minute) return dt_string
7d0b26c9d4517738be448e2ab897b1ffb419179f
34,412
def get_active_lines(lines, comment_char="#"): """ Returns lines, or parts of lines, from content that are not commented out or completely empty. The resulting lines are all individually stripped. This is useful for parsing many config files such as ifcfg. Parameters: lines (list): List o...
b49c8cd034c8fa8e7dcf0b5153c8d5bcce52a1f3
34,413
def is_shutout(goalie_dict, goalies_in_game): """ Checks whether current goalie game can be considered a shutout. """ # only goalies that played and didn't concede any goals can have a shutout if (goalie_dict['games_played'] and not goalie_dict['goals_against']): # if more than two goalies (...
c9aa7adead449366e8845b562fd04b98396321cc
34,414
def phase_segmentation(image, threshold, area_bounds=[0.5, 6.0], ip_dist=0.160): """ Segement a phase image and return the mask. Parameters ---------- image : 2d-array The phase image to be segmented. This image will be converted to a float type. threshold...
a4eeb7dd8f9602c0dada2a62f3e2cabda3036950
34,415
from datetime import datetime def _fix_other_columns(df): """ Fills all other columns using reasonably similar rows. """ cols_to_fill1 = [ "season", "workingday", "weathersit", "temp", "atemp", "hum", "windspeed", "cnt", ] dhour =...
c710d6342dbcf1c340479a7dc3b8eacfeee7cfb1
34,416
def storage_get_all_by_project(context, project_id, marker, limit, sort_key, sort_dir): """Get all storages belonging to a project.""" return IMPL.storage_get_all_by_project(context, project_id, marker, limit, sort_key, sort_dir)
aa8e20ce1fda6e80a7e9033ede16aa2f457557ce
34,417
def evaluate_parentheses(token): """ Evaluates parentheses. Parameters ---------- token : ``Token`` Returns ------- new_token : ``Token`` The final evaluated token. """ new_token = evaluate_tokens(token.sub_tokens) new_token.start = token.start new_token...
7f0b3044fd25c3d0ae958abadea668ca07dec3c3
34,418
def typprice( client, symbol, timeframe="6m", opencol="open", highcol="high", lowcol="low", closecol="close", ): """This will return a dataframe of typical price for the given symbol across the given timeframe Args: client (pyEX.Client): Client symbol (string): T...
3d7e8621a9c85e48913df15d59944a480c0cda35
34,419
import json def evaluate_grants(path_to_gt_json, path_to_test_json): """ This function measures the micro recall of the grantIDs identified by a system. Input: - gt_json: Path to ground truth .json file - test_json: Path to user submitted .json file Output: - Float value of mic...
465bfb885780983ac5df05d590f0570dee52d6bd
34,420
def read_puzzle(board, input_puzzle): """ Reads unsolved puzzle If the string given is a filename with .txt of .sud suffix, the puzzle is read from the file, otherwise a string containing the puzzle is considered Expected format: 1 line, row-wise saved values where unknown cells are marked with ...
b8c44230fdccebb6122ab16f924ee10dd6e3e171
34,421
from typing import get_args import dataclasses def dataclass_from_dict(klass, d): """ Converts a dictionary based on a dataclass, into an instance of that dataclass. Recursively goes through lists, optionals, and dictionaries. """ if is_type_SpecificOptional(klass): # Type is optional, dat...
434f05ba49db17016c175155b89986f044c914e3
34,422
def depolarization_factor(wl): """Bucholtz 95 Table 1 Depolarization factor as fct of wavelength in nm""" rho = np.array([[0.200, 4.545], [0.205, 4.384], [0.210, 4.221], [0.215, 4.113], [0.220, 4.004], [0.225...
ccc2212391e1439b74f5399e82a9bc8c7825b14b
34,423
def draw_line (surface, color, a, b, width=1): """draw_line (...) -> Rect Draws a line on a surface. The 'color' argument needs to match the pygame color style. 'a' and 'b' are sequences of the x- and y-coordinate on the surface and 'width' denotes the width of the line in pixels. The return valu...
33519d943fad5979e5ccadb1ce03c4d35baea497
34,424
import io import csv import sys def rows2csv(rows): """http://stackoverflow.com/a/9157370""" if sys.version_info[0] <= 2: #python2 version of csv doesn't support unicode input #so use BytesIO instead #https://stackoverflow.com/a/13120279 #TODO: does StringIO.StringIO work? ...
e479b0a39a2bccf45235dc61dab402ac516bec4d
34,425
def judge_all_tests(judge: LocalJudge, verbose_level, score_dict, total_score): """Judge all tests for given program. If `--input` is set, there is only one input in this judgement. """ judge.build() report = Report( report_verbose=verbose_level, score_dict=score_dict, total_score=total_s...
9f442cdd9a38f17528f6802f76c6ceddabfe6022
34,426
import re def generate_per_sample_fastq_command(forward_seqs, reverse_seqs, barcode_fps, mapping_file, output_dir, params_str): """Generates the per-sample FASTQ split_libraries_fastq.py command Parameters ---------- forward_seqs : list of str The list of...
44d3cef9cca598a8ce36a46637bfa288c49a5f98
34,427
def renderInlineStyle(d): """If d is a dict of styles, return a proper style string """ if isinstance(d, (str, int, float)): result = str(d) else: style=[] for k,v in d.items(): style.append("{}:{};".format(k, v)) separator = ' ' result = separator.join(st...
f08ea415e4fa29404b7c879f2346832dc84d2e67
34,428
from typing import cast def selftest(silent: bool=False) -> bool: """Run a simple self-test of DHParser. """ if not silent: print("DHParser selftest...") print("\nSTAGE I: Trying to compile EBNF-Grammar:\n") builtin_ebnf_parser = get_ebnf_grammar() docstring = str(builtin_ebnf_par...
6353abac840ee7a66b2a40133f427ec9ae91f8f2
34,429
def bounding_box(grid, cell_kji0, points_root = None, cache_cp_array = False): """Returns the xyz box which envelopes the specified cell, as a numpy array of shape (2, 3).""" result = np.zeros((2, 3)) cp = grid.corner_points(cell_kji0, points_root = points_root, cache_cp_array = cache_cp_array) result[...
e526a4ee029a02d224bd264aee9c160a5ecdaa85
34,430
def sample_pauli_base(rho, pauli_term, epsilon, base_shots=5000, debug=False, disp=True): """ Sample using the inverse transform sampling technique :param rho: density matrix of state. :param pauli_term: operator to measure. :param epsilon: absolute precision. The standard er...
57c95e3581c4a85bb942b7eeb1820018885b3173
34,431
def test_dup_args_in_call(x): """The naive gradient update rule fails when a function's arguments contain the same variable more than once.""" return x * x
978f4f6e901b4b4aba01bbad098c107eacab59f3
34,432
def snake_to_camel_case(snake_text): """ Converts snake case text into camel case test_path --> testPath :param snake_text:str :return: str """ components = snake_text.split('_') # We capitalize the first letter of each component except the first one with # the 'title' method and j...
b42e1393cf99b88e2ebbcf4b38643c770e218ceb
34,433
def compute_accuracy(dist, labels, threshold): """ Compute the average accuracy over the given set of images. dist: computed distance between pair of images. labels: true class labels threshold: decision threshold. """ trueclass = np.sum(np.logical_and((dist <= threshold)...
d59388c89fe5da610ca51fb7198cd52aa063502b
34,434
import os def add_athena_proc_number(cmd): """ Add the ATHENA_PROC_NUMBER and ATHENA_CORE_NUMBER to the payload command if necessary. :param cmd: payload execution command (string). :return: updated payload execution command (string). """ # get the values if they exist try: value...
42d5b421bcb631f5e664230073fc05c2aa159a5b
34,435
def http_take_solver(): """Return the string of answer""" request_data = request.get_json() answers = ai.take_solver(request_data) return jsonify({"answers": answers})
c11977b0180037f4e458f526533ce604ff10859a
34,436
def create_organization( *, db_session: Session = Depends(get_db), organization_in: OrganizationCreate ): """ Create a new organization. """ organization = get_by_name(db_session=db_session, name=organization_in.name) if organization: raise HTTPException( status_code=400, det...
7511a20a1588b122f02d0c930c3a6e209907a482
34,437
import networkx def check_all(logic_forms: list, checks=None, verbose=False) -> list: """ Do all Logic Form Graph checking. Parameter: logic forms (list): logical forms verbose (bool): enable printing details Returns: lf_graphs (list): dicts of id (int) and a graph (LogicalFormGraph) ""...
21bc30647ab379e98566bf7dc1e7dd3d0e88e86b
34,438
def remove_noise(line,minsize=8): """Remove small pixels from an image.""" if minsize==0: return line bin = (line>0.5*amax(line)) labels,n = morph.label(bin) sums = measurements.sum(bin,labels,range(n+1)) sums = sums[labels] good = minimum(bin,1-(sums>0)*(sums<minsize)) return good
0ee16876ed90f84be1abcd911689dafafad7ef96
34,439
def get_wide_dword(*args): """ get_wide_dword(ea) -> uint64 Get two wide words (4 'bytes') of the program at 'ea'. Some processors may access more than 8bit quantity at an address. These processors have 32-bit byte organization from the IDA's point of view. This function takes into account order of bytes ...
4d8574128bfca6a48e595516c4e9bee6a9bbfc75
34,440
import copy def corrupt(x, mask=None): """Take an input tensor and add uniform masking. Parameters ---------- x : Tensor/Placeholder Input to corrupt. mask: none Returns ------- x_corrupted : Tensor 50 pct of values corrupted. """ cor = copy.deepcopy(x) if ...
f8b91f07012bd231570981824a0759b40f30f4b0
34,441
def bvi(model, guide, claims, learning_rate=1e-5, num_samples=1): """perform blackbox mean field variational inference on simpleLCA. This methods take a simpleLCA model as input and perform blackbox variational inference, and returns a list of posterior distributions of hidden truth and source reliabil...
bb7469efd4615156219f0f514200784a50a84ad6
34,442
from pathlib import Path import json def load_metadata(bucket: str, prefix: str) -> dict[str, dict]: """ Get general export metadata file and table status metadatas. The former contains column names / types as well as a string containig schema and table name. Export metadata contains info about t...
578b7cb312d1490a9d9ded1574b9e5a445d93d5d
34,443
from datetime import datetime def get_dbtbl(options: list): """Handles dbtbl (available lobby table) calls.""" main.terminate_incorrect_lobbies() order = None resort = None for option in options: option = option.strip("'") if option.startswith("order="): order = option[...
f0c14f2cabc7a600b1296ed012b5c2b814a90708
34,444
def compare_parsed_text(seq_list, auto_stripped_text): """ This is a stupid workaround to the fact that bs4 parsers generally suck. Tries to measure whether parsing was "successful" by looking at the automatically scraped text of the policy to the text we parse here. Note: can't match/replace entir...
c1bc7b2fd87dbd90082a434f7193cfed08d3164d
34,445
import ctypes def repmi(instr, marker, value, lenout=None): """ Replace a marker with an integer. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmi_c.html :param instr: Input string. :type instr: str :param marker: Marker to be replaced. :type marker: str :param value: Re...
c366f8a2077cc51bfff5f2d7e2f0b019e48c09f7
34,446
def _get_parameter_state(sender_owner, sender_type, param_name, component): """Return ParameterState for named parameter of a Mechanism requested by owner """ # Validate that component is a Mechanism or Projection if not isinstance(component, (Mechanism, Projection)): raise ParameterStateError(...
11c72ad6bdf4bd28f25c771d4d4283b88522e1a2
34,447
def start_volume( mdserver_name ): """ Start up an existing metadata server for a volume. Return 1 on success. """ global conf ctl_root = VOLUME_CTL_ROOT( conf, {'NAME': mdserver_name} ) config_file = VOLUME_CONF_PATH( ctl_root ) md_logfile = LOGFILE_PATH( ctl_root ) md_pidfile = PIDFIL...
1d8ed9310d9e67f3ca77f97eed935b0ff45661a6
34,448
from typing import Any def _pycall_path_dest_only( x1: int, y1: int, x2: int, y2: int, handle: Any ) -> float: """A TDL function which samples the dest coordinate only.""" return ffi.from_handle(handle)(x2, y2)
808a50335bc3c70aa49f6fe198beb4817655dc8a
34,449
from datetime import datetime def calculate_leap_seconds(year, month, day): """ get the leap seconds for the given year to convert GPS time to UTC time .. note:: GPS time started in 1980 .. note:: GPS time is leap seconds ahead of UTC time, therefore you should subtract leap seconds fr...
236d71d4827c4647999aef90e8f9f7ee49053f85
34,450
import re def convert_vpc_name_to_vpc(possible_vpc_id, error_on_exit=True): """ Convert a given VPC name into the VPC ID. If the input VPC name looks like an existing VPC ID, then return the VPC immediately. If the VPC with the given VPC name exists, then return the VPC. If there is no suc...
3b5f644001bf12a3d2b1758a9bb045ee2e8e88b1
34,451
def preprocess_person(hh_dat, person_dat): """ This function preprocesses person-level features and merge with household data. Nominal categorical variables, such as years of age are transformed into continuous values. Input: Preprocessed household-level data Original perosn-le...
5becaeb1141ad72a85128340d2c9f47e5899f0e9
34,452
from typing import Optional from typing import Dict def from_file(archive: PathOrTarFile) -> Optional[Dict]: """Load and parse CRAN package archive Args: archive (PathOrTarFile): path to archive or `tarfile.TarFile` instance Returns: (dict): Dictionary of R package metadata """ re...
b4e0c24bfc0c7489be27da23fcc5c3431273d932
34,453
from google.cloud import bigquery def to_google_cloud_bigquery(pandas_gbq_schema): """Given a schema in pandas-gbq API format, return a sequence of :class:`google.cloud.bigquery.schema.SchemaField`. """ # Need to convert from JSON representation to format used by client library. schema = add_defa...
519c6314889c1ca0bca747e2f5784ac00bf94aed
34,454
def update_exception_behavior(behavior_input, id): """ Executes a "update exception behavior" mutation with graphql-client :param behavior_input: the behavior input :param id: The id of the behavior to update :return: Server response """ behavior_variables = { "behaviorInput": behavi...
b8046c2a2a64e66e73159f2f19137bd7b8ab9097
34,455
def ps_dim(tasks): """ Dimension a Polling Server such that it fits into the provided task set. Parameters ---------- tasks : list of pSyCH.tasks.Periodic Task set whose schedulability is to be checked. Returns ------- sched : bool True if the task set is schedulable, F...
458b77bd5bb32ddd5c7002f872d0ed4e22642c4c
34,456
def signature(obj, *, follow_wrapped=True): """Get a signature object for the passed callable.""" return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
cec0e2d7bcf6cd3347bcd06ef58f33a0c65bdb94
34,457
def ingest_epv_into_graph(epv_details): """Handle implementation of API for triggering ingestion flow. :param epv_details: A dictionary object having list of packages/version as a nested object. Ex: { "ecosystem": "<ecosystem_name>", (*required) "packages": [ { ...
0de5afbfe6e9b1d79e3ee34f54475095dc05e9e3
34,458
def create_sys(Model, size, epsi, dens, init, bd_cond='periodic'): """Creates a instance of the LdftModel `Model` under the parameters `size`, `epsi`, `dens`. The `init`-parameter determines the initial density profile of the created system. Parameters ---------- Model : `class` The...
d30ae63022934e668c0ef90a72c91713caa6a228
34,459
def limit(resource, value): """ Check if this is a valid limit for the number of matching resources to be specified. :param resource: :type resource: :param value: specified limit :type value: int :return: True if valid limit, False otherwise :rtype: bool """ return value > 0
3ee75e7e41752e2bddebb94915bbf9161e02caec
34,460
import gc def sequence(values, rasts): """ Iterates through a sequence of linearly interpolated rasters. Args: values: The unknown values for which new rasters will be interpolated and returned. rasts: A dictionary of the known values and rasters between which the ...
6ff4d0f192f1bc92030693aba4e903378d06b636
34,461
def is_native_xmon_op(op: cirq.Operation) -> bool: """Check if the gate corresponding to an operation is a native xmon gate. Args: op: Input operation. Returns: True if the operation is native to the xmon, false otherwise. """ return isinstance(op, cirq.GateOperation) and is_native...
41189dc252c766669127129e4a801f13b93a33fb
34,462
def mono_extractor(b_format, azis=None, eles=None, mode='beam'): """ :param b_format: (frames, channels) IN SN3D :param mode: 'beamforming' or 'omni' :return: """ frames, channels = b_format.shape x = np.zeros(frames) if mode == 'beam': # MaxRE decoding b_format_n...
edaf426546a41dd3bb4afcb95e28dcfe93e20044
34,463
def get_ranking_order_switches(list): """list has to be list of quadruples (obs_id, sent_id, score, rank) output from get_ranks function as in Ranking-Based Evaluation of Regression Models, Rosset et al.""" ranking_order_switches=0 #itearte over list, get observation i n = len(list) for i in ran...
f87e8e07bdde631747454ddd27a79e81ed3b5c6f
34,464
def b58_to_bytes(val: str) -> bytes: """ Convert a base 58 string to bytes """ return base58.b58decode(val)
49f4634a4c44f162aca242e5ccf41239926af504
34,465
def generate_sphere(phi, theta, r): """ Generate points for structured grid for a spherical shell volume. This method is useful for generating a structured cylindrical mesh for VTK. :param phi: azimuthal angle array :param theta: polar angle array :param r: radius of sphere :return: grid poi...
3de54ecdc22c056d5ec3a3d979573b4e4cf0e893
34,466
def get_target_langs(request): """ Get Target Languages for a CI Pipeline :param request: Request object :return: HttpResponse object """ if not request.is_ajax(): return HttpResponse("Not an Ajax Call", status=400) post_params = request.POST.dict() ci_pipeline = post_params.get...
f7b663b26012505568b5d49b81903951ad4842ac
34,467
def _reciprocal_calculate(a): # pragma: no cover """ TODO: Replace this with more efficient algorithm From Fermat's Little Theorem: a^(p^m - 1) = 1 (mod p^m), for a in GF(p^m) a * a^-1 = 1 a * a^-1 = a^(p^m - 1) a^-1 = a^(p^m - 2) """ if a == 0: raise ZeroDivisionError...
0055de1d1e04e78ae78d743598deee892becaae2
34,468
def page_list_return(total, current=1): """ page 分页,返回本次分页的最小页数到最大页数列表 """ min_page = current - 4 if current - 6 > 0 else 1 max_page = min_page + 6 if min_page + 6 < total else total return range(min_page, max_page + 1)
99b099a7e90e1e150881d93129b1558eb8bc9a20
34,469
import sys def get_compatibility_tags(filename): """Get the python version and os architecture to check against. Args: filename (str): Wheel filename that ends in .whl or sdist filename that ends with .tar.gz. Returns: pyver (str)['py3']: Python version of the library py3 or cp38 ... ...
a5e058c2a82268bdaead21add485f7e65b840cb9
34,470
import sys import struct import json def recv_msg(): """Receive a message from the extension.""" # Each message is serialized using JSON, UTF-8 encoded and is preceded with # 32-bit message length in native byte order. # Read the message length (first 4 bytes). length_bytes = sys.stdin.read(4) ...
d315ebd2ad456b294a5b5dafcfa00e45e37e5ade
34,471
import time def get_deployment_dates(site, node, sensor, deploy): """ Based on the site, node and sensor names and the deployment number, determine the start and end times for a deployment. :param site: Site name to query :param node: Node name to query :param sensor: Sensor name to query ...
cbc91ea8518184a40c1e8d35bacc1deebab3e768
34,472
def delete_documents_by_filter(filters: FilterRequest): """ Can be used to delete documents from a document store. :param filters: Filters to narrow down the documents to delete. Example: '{"filters": {{"name": ["some", "more"], "category": ["only_one"]}}' To delete ...
d69f6d390544d61666a576c1a84d4721bad6ad5a
34,473
import os def jpgs_in_dir(dir): """ (provided, DO NOT MODIFY) Given the name of a directory, returns a list of the .jpg filenames within it. Input: dir (string): name of directory Returns: filenames(List[string]): names of jpg files in directory """ filenames = [] ...
36db3a07faa77a44b9644083cc1057f89e2bb4e7
34,474
def ensure_credential_server_running( foreground=False, run_once=False ): """ Instantiate our credential server and keep it running. """ # is the watchdog running? pids = syndicate_watchdog.find_by_attrs( "syndicate-credential-server-watchdog", {} ) if len(pids) > 0: # it's running ret...
2a55534f29509ad275d350db534c7ab158388278
34,475
import glob def load_dbc(folder, verbose=True): """ Load all dbc files from specified folder add to dbc database. Parameters ---------- folder : str Absolute or relative path to folder, which contains dbc files. verbose : bool, optional Set to False to have no readout. The def...
62b062d1f48021317f99cd46dad6ad697d0ec4a9
34,476
def unique_timestamps(data): """ Identify unique timestamps in a dataframe :param data: dataframe. The 'Time' column is used by default :returns: returns a sorted numpy array """ unique_timestamps = sorted(data['Time'].unique()) return unique_timestamps
4e8b86643e4c976d51e39663ffefc95ec2be0e55
34,477
def printf_format_for_type(t, types): """ Returns a format string for printing the given type (either atomic or struct). """ description = type_description(t, types) if "struct" in description: specifer = printf_format_for_struct(t, types) else: specifer = description["printf_specifi...
6647cfa80934e345f269b4d4afa69e95f0d8928d
34,478
def get_operator_artifact_type(operatorArtifactString): """get_operator_artifact_type takes a yaml string and determines if it is one of the expected bundle types. :param operatorArtifactString: Yaml string to type check """ # Default to unknown file unless identified artifact_type = UNKNOWN_F...
50e14ff39e8c4e7258c0f305cf8a05973c836d3a
34,479
def is_occ_conflict_exception(e): """ Is the exception an OccConflictException? :type e: :py:class:`botocore.exceptions.ClientError` :param e: The ClientError caught. :rtype: bool :return: True if the exception is an OccConflictException. False otherwise. """ is_occ = e.response['Error...
3df46480341b617570e1e980ade194c9bd3fb26e
34,480
def replace_list_element(l, before, after): """Helper function for get_cluster_idx """ for i, e in enumerate(l): if e == before: l[i] = after return l
b15f43332efdcec878fbd16df64d46b1e23d2630
34,481
def hit_counter_from_list(filenames, barcode): """ :param filenames: all files from a single barcode - just the same hit_counter but for a list of filenames :param barcode: the barcode associated to our experiment :return: a dict {genome:hits} """ genomes = dict() for name in filenames: ...
ed85426ed654399a10434a4d1c4d97cd603368c1
34,482
def average(v): """ :param v: a list of numerical values :return: average for a list of values expressed as a float """ return sum(v) * 1.0 / len(v)
cbc9e450ee854289c62b613c257655fcd0c3e62c
34,483
def get_all_projects_of_type(project_type: int): """Get the project ids for active and inactive projects in Firebase DB.""" project_id_list = [] fb_db = firebaseDB() # we neglect private projects here # since there are no projects set up in production yet status_list = ["active", "inactive"] ...
ed5211bcab68139de79c262d2f61c5e62e714610
34,484
import typing def set_engine(filename, *, resolve: bool = False, require: bool = False, title: typing.Optional[str] = None, title_memory_tag: str = _globals.MEMORY_TAG): """Return new sqlite3 engine and set it as default engine for treedb.""" log.inf...
eebd51176d8b4533af810d2f27cd4e48ea6bf316
34,485
def camel_split(string): # test: (str) -> str """ >>> print('(%s)' % ', '.join("'%s'" % s for s in camel_split('theBirdsAndTheBees'))) ('the', 'Birds', 'And', 'The', 'Bees') >>> print('(%s)' % ', '.join("'%s'" % s for s in camel_split('theBirdsAndTheBees123'))) ('the', 'Birds', 'And', 'The', 'Be...
d001f42b103ad911c92256bd326a3d478fc8f424
34,486
def iSP(a: Point, b: Point, c: Point) -> Turn: """iSP Determine the positional relationship of the three Points. Returns ------- Turn direction """ flg = sign((b - a).det(c - a)) if flg == 1: return Turn.CCW elif flg == -1: return Turn.CW else: if si...
80143dcb4d3b6985cae49208193ee9662b4e5edb
34,487
def generatePathsACS(ants: list, graph: np.ndarray, H: np.ndarray, P: np.ndarray, alpha: float, beta: float, decay: float, pher_init: float, Q: float, exp_heuristic: bool = True) -> list: """ Function that performs the exploration of the graph using the Ant Colony Syste...
36cdd05ab9b403203603851403b85e502c614905
34,488
import warnings def fit_a_model(args): """ Parallelizable """ model, model_args, x_train, y_train, x_test, y_test = args classifier = model(**model_args) # NOTE: Not best practice, but otherwise warnings pollute try: with warnings.catch_warnings(): classifier.fit(x...
73f115f1e13fc1f4141fda042152923185c3a8e1
34,489
def detect_hfo_cs_beta(sig, fs=5000, threshold=0.1, cycs_per_detect=4., mp=1): """ Beta version of CS detection algorithm. Which was used to develop CS detection algorithm. Parameters ---------- sig: numpy array 1D numpy array with raw data fs: int Signal sampling frequency ...
7d8a207612a066c217ee7dabaa1925c6c6fcff09
34,490
def get_comments(user): """Returns all of the user's comments""" comments = '' for comment in user.get_comments(limit=None): comments = comments + ' ' + comment.body return comments
cb095b78a2ac304c849e75a7b988c581a826aef1
34,491
def is_supported(): """Get whether Dialite is supported for the current platform.""" return not isinstance(_the_app, StubApp)
67846bf87c1b7c3ceda7bf6eb1090f55f9bd6453
34,492
def _check_axes_range(axes, ndim): """ Check axes are within the number of dimensions of tensor x and normalize the negative axes. Args: axes (Union[int, tuple(int), list(int)]): Axes of the tensor. ndim (int): The number of dimensions of the tensor. Return: Axes (Union[int, tupl...
135b7b729b5e207c5b97de14a32035d291765c2e
34,493
def compare_token_sets(qset, iset, intersector, counter, high_intersection_filter, len_legalese, unique, rule, filter_non_matching=True, high_resemblance_threshold=0.8): """ Compare a `qset` query set or multiset with a `iset` index rule set or multiset. Return a tupl...
cfcaeeec91673cb800d67ec241574ebf80c70416
34,494
def cm_LU_USGS24(): """Land use colormap. https://github.com/blaylockbk/pyBKB_v2/blob/master/BB_cmap/landuse_colormap.py # MUST SET VMAX AND VMIN LIKE THIS TO SCALE COLOR RANGE CORRECTLY cm, labels = LU_MODIS21() plt.pcolormesh(LU_INDEX, cmap=cm, vmin=1, vmax=len(labels) + 1) """ C =...
4f5eb1cce0f4fddc88712d8e2863a8b8593e3cba
34,495
import functools def lazy_value(fce): """ The decorator for only once computed value. Same a functools.cache, but there is no need to take care of arguments. """ x = [] """ Hack for staticmethod decorator, which is in fact binded by the descriptor protocol """ if isinstance(fce, staticmet...
dd983e23b036f5d2c7fbe98e048973c894378d97
34,496
def identity_by_descent(dataset, maf=None, bounded=True, min=None, max=None) -> Table: """Compute matrix of identity-by-descent estimates. .. include:: ../_templates/req_tvariant.rst .. include:: ../_templates/req_biallelic.rst Examples -------- To calculate a full IBD matrix, using minor al...
7d8a0a2015955d19046835dcbf0f2ae60e937aa4
34,497
def sanitize_cloud(cloud: str) -> str: """Fix rare cloud layer issues""" if len(cloud) < 4: return cloud if not cloud[3].isdigit() and cloud[3] not in ("/", "-"): # Bad "O": FEWO03 -> FEW003 if cloud[3] == "O": cloud = cloud[:3] + "0" + cloud[4:] # Move modifiers ...
7ec10be12ac2bc1a305688b31125af11a734c327
34,498
def list_permission(request): """显示权限名称的列表""" tpl_name = 'user/list_permission.html' perms = Permission.objects.all() info = {'perms':perms} return render(request,tpl_name,info)
1fc388516789ab594d12080b7d8beeb5afa50220
34,499