content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def lux(samples=None, resolution=10): """Converts raw LUX value into original unit (%). BITalino Sensor: Light (LUX) See sensor datasheet for more information: http://bitalino.com/datasheets/REVOLUTION_ECG_Sensor_Datasheet.pdf [TRANSFER FUNCTION] LUX(%) = ADC / 2**n * 100 - ADC Value sampled from the chan...
1466a37a01d44863b95ef7aaaac26019bc2614c0
3,609,400
import os def import_original_module(): """ Imports original user's handler using the `EPSAGON_HANDLER` env. :return: Module or Exception """ original_handler = os.getenv(EPSAGON_HANDLER) if not original_handler: raise ValueError( 'EPSAGON_HANDLER value not specified in env...
bb4b891dcbb7d1e372855d6a7df1e15f82c25322
3,609,401
def GetDefaultAirflowConfigKeys(): """Return a list of the keys of configuration for the Pipeline.""" dc = GetDefaultAirflowConfig(branch="", gcs_path="", mfest_commit="", pipeline_type="", verify_consistency="", version="", commit="") return list(dc.keys())
ca290dfb401f2ac56568c8a17f4fd218fcd166c2
3,609,402
def encrypt_password(password: str) -> str: """ Encryption on a password :param password: the password to encrypt :return: the hashed password """ return bcrypt.hashpw(password.encode("utf8"), bcrypt.gensalt()).decode("utf8")
cd37c9556188ab41cf52b9ee18f861d904453554
3,609,403
def _update_user_inputs(kwargs, default_parameters, check_parameters): """Update keyword parameters with user inputs if applicable.""" parameters = default_parameters.copy() # update the parameter with user input not_needed = [] for key in check_parameters: value = kwargs.pop(key, None) # g...
9e67e30cddf8529bf492cd7243bdbada40ef97fa
3,609,404
def joann(joann_url: str) -> dict: """Scrape product information from joann.com Keyword arguments: joann_url -- a product url from joann.com """ joann_product = _joann._joann(joann_url) return joann_product
8c0cd1c0383e591354d3984b049250ca0bd347bb
3,609,405
def sample_one_q_clifford_layer_as_compiled_circuit(pspec, absolute_compilation, qubit_labels=None, rand_state=None): """ Samples a uniformly random layer of 1-qubit Cliffords. Create a uniformly random layer of 1-qubit Cliffords on all the qubits, and then converts it to the native gate-set of `pspec`...
49d31cc182f3f77f44dec61611aa8b06b2c098a7
3,609,406
from typing import Iterable def CHANNEL(ch_id_names): """ Decorator for bot commands. Invoking msg must be sent in the channel/s provided Channel Limitations are overwritten if author is Staff | Admin | Guild Owner | Bot Owner Args: (str) Channel name (int) Channel ID ...
51d71245405f821f7b44e4b1ad4356824979c6fb
3,609,407
import json def save_service(service_name, service): """Persist a service in the monitor cluster""" service['groups'] = {} return monitor_key_set(service='admin', key="cephx.services.{}".format(service_name), value=json.dumps(service, sort_keys=True))
62a539ec50d663599c32a74a4a19f9ad3a0b3296
3,609,408
from typing import List from typing import Dict from operator import concat def render_adverbio_de_adjetivo( tpl: str, parts: List[str], data: Dict[str, str] ) -> str: """ >>> render_adverbio_de_adjetivo("adverbio_de_adjetivo", ["accidental"], defaultdict(str)) 'De un modo accidental' >>> render_a...
4ffd565fc8707eb34590884657561427183b0bc8
3,609,409
def EventType() -> str: """{ref}`nonebot.adapters.Event` 类型参数""" return Depends(_event_type)
e8da20934427961b5dbe414683f7a4942e728565
3,609,410
from typing import Optional def decode( reference: LR, reader: MapReader, observer: Optional[DecoderObserver] = None, config: Config = DEFAULT_CONFIG ) -> MapObjects: """Translates an openLocationReference into a real location on your map. Args: reference: ...
7e80957fb891586cabccb7b8807cd6a3121262f5
3,609,411
import re def tri_lexique_relation(conllu,lexique,relation): """ entrée : un conllu issu de read_file(), un lexique, une relation de dépendance sortie : - un dico {phrase du conllu : les suites de mots présentes dans le lexique, pour cette phrase} - un dico {phrase du conllu : les suites de mots absentes du lexi...
8bf910dcbd16ee62644646eec32a31e4abac08df
3,609,412
def geomap_rscale(xyin,xyref,center=None): """ Set up the products used for computing the fit derived using the code from lib/geofit.x for the function 'geo_fmagnify()'. Comparisons with results from geomap (no additional clipping) were made and produced the same results out to 5 decimal places. ...
e001fd9cbb74497088136186479418e95860b68b
3,609,413
import os def configure(base_url=None, api_key=None, verify_ssl=True, proxy=None, username=None, password=None, debug=False): """ This wrapper provides an easier to use method of configuring the API client. The base Configuration method is still exposed if you wish to further configure the A...
04ed3af1c8050d85bdb368298fc3e87b9ad5a838
3,609,414
def _resegment_wrongly_merged_cells(im_next, im_labels_curr, merged_labels, mask): """ Correct an error in tracking for a single cell at one time point. If two cells appear to merge when they shouldn't, this takes their positions in the previous timepoint and uses them to generate new seeds for a w...
b3b844d42a62f782e338880a7e94968f0fe0ba7b
3,609,415
def get_events_by_location(location): """ Gets events using a given members id. """ response = client.get( f"/events/search/?q=technology&location.address={location}&sort_by=-date" ) events = response["events"] return events
b7bfe7039182820bacbd6963227cae64a3319a27
3,609,416
from functools import reduce def wrap_onspace(text, width): """ A word-wrap function that preserves existing line breaks and most spaces in the text. Expects that existing line breaks are posix newlines (\n). """ return reduce(lambda line, word, width=width: '%s%s%s' % (line,...
57203550d4e3c02b6282ad8d62e14a562dc9c6a9
3,609,417
def symmetrical_relevance(x, y, z): """Calculate the symmetrical relevance (SR(X;Y;Z) = I(X;Y;Z) / H(X;Y|Z)) between three arrays. Parameters ---------- x : array-like, shape (n,) The first array. y : array-like, shape (n,) The second array. z : array-like, shape (n,) ...
134b408f37773fd43500897f3b4e0c6ab5fa5fda
3,609,418
import re def _get_numbers_from_string(string): """ Return a list of numbers (strings) that appear in parameter string. Match integers, decimals and numbers such as +1, 2e9, +2E+09, -2.0e-9. """ numbers = re.findall(r"[-+]?(?:(?:\d+\.\d+)|(?:\d+))(?:[Ee][+-]?\d+)?", string) return numbers
970d57aaec18bdc6ab4a9c55f6445fbbc74998d7
3,609,419
def filter_by_response(words, guess, response): """ Parses the Wordle guess response and filters out invalid words """ for idx,chr in enumerate(guess): if response[idx] == ".": words = [word for word in words if not chr in word] elif response[idx] == chr.upper(): words = ...
77a678f6603fb16e34a5b74a3350e560efa4f82d
3,609,420
def GetVersion(vm): """Returns the version of the memcached server installed.""" results, _ = vm.RemoteCommand('memcached -help |grep -m 1 "memcached"' '| tr -d "\n"') return results
ba0a16d7e9f8f7702d6f5f41595a6a47a39e0f6b
3,609,421
import os def get_version(): """ Get the version of the version as determined by :py:`_zkapauthorizer._version`. Note: This only works when run from an tree generated by git-archive (such as a tarball from github). """ version_path = os.path.join( os.path.dirname(__file__), "src/_...
301e0890aff57915c2228f7bb027fa48b3db0ba5
3,609,422
def do_mixup(x, mixup_lambda): """Mixup x of even indexes (0, 2, 4, ...) with x of odd indexes (1, 3, 5, ...). Args: x: (batch_size * 2, ...) mixup_lambda: (batch_size * 2,) Returns: out: (batch_size, ...) """ out = (x[0 :: 2].transpose(0, -1) * mixup_lambda[0 :: 2] + \ ...
93794ae5249afd49d0a88bb8c31066de51bbebf7
3,609,423
def grid_create_from_coordinates_periodic_3d(longitudes, latitudes, heights, lon_corners=False, lat_corners=False, z_corners=False, corners=False, domask=False): """ Create a 3 dimensional periodic Grid using longitudes, l...
7206d59f804dee8270759e9aec75e2968bebb692
3,609,424
import collections import logging def overwrite_state_dict(loaded_param_name: str, model_param_name: str, loaded_state_dict: collections.OrderedDict, model_state_dict: collections.OrderedDict, logger: logging.Logger = None...
4f2c19b4aa45f90d09bd1ade75d545ec219c535d
3,609,425
from typing import Optional from typing import Dict def read_labels_yaml( csvpath: PathType, prefix: Optional[str] = None ) -> Dict[str, DictConfig]: """Read labels from csvfile in YAML format.""" labels = pd.read_csv(csvpath) cells = OmegaConf.create() for label in labels.iterrows(): lab...
36b840e3c6e616009d4f2180846c1100183473ce
3,609,426
def exec_container(c, d, t, n, s='http://portainer:9000/api', e='1'): """Execute command within container. Execute a command within a running container. Args: c: Container id d: List containing command t: Authorization token n: Container swarm node s: Portainer serv...
86dd7c638051dcb905d3f1538e357f09243f33b6
3,609,427
from typing import Dict from typing import Tuple from typing import Optional def _map_rest_error(json_data: Dict[str, str]) -> Tuple[StatusCode, Optional[str]]: """ Map a Databricks REST API error (from the returned JSON) into a status code and a message. :param json_data: the JSON returned from the ...
b7bdc7af56f4263365d5347816bf3a799104011d
3,609,428
def abs_energy(x): """ Returns the absolute energy of the time series which is the sum over the squared values .. math:: E = \\sum_{i=1,\ldots, n} x_i^2 :param x: the time series to calculate the feature of :type x: pandas.Series :return: the value of this feature :return type: fl...
a7ac52ec68192990358ed9a5ebacf0d59f34a7dc
3,609,429
def write_bytes(path: str, content: bytes) -> Effect[HasFiles, OSError, None]: """ Get an `Effect` that writes to a file Example: >>> class Env: ... files = Files() >>> write_bytes('foo.txt')(b'content of foo.txt')\\ ... .discard_and_then(read('foo.txt'))\\ ....
f156cdac9553817e4212c97be785e5bbad30141c
3,609,430
def get_sentiment_compound(value): """ function get value and return whether it's Positive, Negative or Neutral :param value: floating number :return: whether value is Positive, Negative or Neutral """ # decide sentiment as positive, negative and neutral if value > 0: sentiment_compo...
7feae8fd085efb9a2e684844a25ab1a1d9b3dad0
3,609,431
def get_value_mappings(src_table, dest_table, src_field, dest_field): """ This function translates values between src_field and dest_field. E.g. the value primary_condition for condition_type_concept_id needs to be translated to the value primary_procedure for procedure_type_concept_id :param src_ta...
a63de53d893fbe55453964288dec7c1f754a73cb
3,609,432
from functools import reduce def run_map(generator, mapper) -> list: """ Map function caller for each line in each file :param generator: file and line generator :param mapper: map function to be called for each line in the files :return: generator of key value pairs returned by the map function ...
468467f9274572d82b8843449ffe9691b68331cc
3,609,433
from typing import Iterable from typing import Set def get_all_nodes(edges: Iterable[Edge]) -> Set[BaseNode]: """Return the set of nodes connected to edges.""" nodes = set() for edge in edges: if edge.node1 is not None: nodes |= {edge.node1} if edge.node2 is not None: nodes |= {edge.node2} ...
38393c91c284ae01ddf3a2f1654a5aee0fb094d2
3,609,434
def get_collection_latest(parser, token): """ {% get_latest_from_collection collection_url num as latest_forecast %} Returns the most recent 'num' items from the specified collection. """ bits = token.split_contents() if len(bits) == 5: return CollectionLatestNode(bits[1], bits[2],...
d6a76221b1fa87560bfd0e604701bc5d4c1ec655
3,609,435
import base64 import requests def docker_registry_authenticate(www_authenticate): """ returns a dictionary of headers to add as part of original request including access_token takes the Www-Authenticate header from the 401 response of a registry request like 'Bearer realm="https://192.168.204....
536453b743f41223030a7d07778d1dceb09c6ab5
3,609,436
def apply(request, pk): """ Let a user apply to a proposal. Called after confirmapply. :param request: :param pk: id of a proposal. """ prop = get_cached_project(pk) if prop.Status < 4: raise PermissionDenied('This proposal is not public, application is not possible.') if get_a...
8b02b219f988162c88078605dc8ec22ab319892e
3,609,437
def heatmap(data, row_labels, col_labels, ax=None, cbar_kw={}, cbarlabel="", **kwargs): """ Create a heatmap from a numpy array and two lists of labels. Parameters ---------- data A 2D numpy array of shape (N, M). row_labels A list or array of length N with the label...
c24ecca19da3855c008c55c90fc2bb5d4ebbb737
3,609,438
def svn_client_propset3(*args): """svn_client_propset3(char const * propname, svn_string_t const * propval, char const * target, svn_depth_t depth, svn_boolean_t skip_checks, svn_revnum_t base_revision_for_url, apr_array_header_t changelists, apr_hash_t revprop_table, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_e...
b05cf35f5ad3edd7592df0a693570e539301bd68
3,609,439
from typing import List import traceback def logger(func): """ logger """ def wrapper(*args, **kwargs): try: print(f'start {func.__name__}, args: {args}, kwargs: {kwargs}') result = func(*args, **kwargs) print(f'finish {func.__name__}, result: {result}') ...
99b566c50585bf4514c43b76405fcf1dd43ff948
3,609,440
def chebfit(x, y, deg, rcond=None, full=False, w=None): """ Least squares fit of Chebyshev series to data. Fit a Chebyshev series ``p(x) = p[0] * T_{0}(x) + ... + p[deg] * T_{deg}(x)`` of degree `deg` to points `(x, y)`. Returns a vector of coefficients `p` that minimises the squared error. Pa...
81c20a14055893a3139e222d60e932f7f52d11fb
3,609,441
def load_numpy(file_name): """Loads numpy binary file as array""" file_name = replace_ext(file_name, 'npy') try: array = np.load(file_name) except IOError as e: raise IOError( f"Cannot read file {file_name}" ) from e return array
bec0a8dfd8547df88418476f0ea02d95e5bd5c9a
3,609,442
def _predict(df, model_dict): """We break this function out separately to take advantage of memoization, if that's something we'd like to add (see Flask-Cache docs for more). """ df = df[model_dict['model_features']] general_logger.debug('Input covariate df: %s', df) preds = getattr(model_dict[...
c37ba1f96ed6257c933f8070b8afabfab6f94840
3,609,443
def draw_on_road(img_undistorted, Minv, left_line, right_line, binary, pers_image): """ Draw both the drivable lane area and the detected lane-lines onto the original (undistorted) frame. Args: img_undistorted: original undistorted color frame Minv: (inverse) perspective transform matrix us...
96c20fc9fa751759b93baca3b21604c61eb309bb
3,609,444
def gram_schmidt_columns(X): """ Apply Gram-Schmidt orthogonalization to obtain basis vectors. """ B = np.zeros(X.shape) B[:, 0] = (1/np.linalg.norm(X[:, 0]))*X[:, 0] for i in range(1, 3): v = X[:, i] U = B[:, 0:i] # subspace basis which has already been orthonormalized p...
cefec14e3709b2c3bf606fe07d0fcc142ed29782
3,609,445
import os def create_segment_mfcc_export_dirs(export_path: str, segment_parent_dirs: list) -> list: """ Creates export directories for mfccs for song segments and returns them as a list of file paths :param export_path: str :param segment_parent_dirs: list :return: list """ if not os.path....
501828589070a941904f71ccc6ac897e240ccd37
3,609,446
def put_pm_to_pandas_data(data: dict) -> dict: """ Change the +- to \pm for latex display. Note: to have the pandas frame display the table string correctly use the escapte=False as in: latex_table: str = df.to_latex(index=False, escape=False, caption='caption goes here', label='label_goes_here') ...
50193af607b8321601f35350283386021509b1bd
3,609,447
def bd_gcj(lon, lat): """Convert BD09 coordinates to GCJ02 (fast estimation).""" result = lib.prcoords_bd_gcj({'lon': lon, 'lat': lat}, 0) return (result.lon, result.lat)
711a8018949075361c04b3626ae75567117b98c3
3,609,448
def export_saved_form_data_entries(request, form_entry_id=None, theme=None): """Export saved form data entries. :param django.http.HttpRequest request: :param int form_entry_id: Form ID. :param fobi.base.BaseTheme theme: Subclass of ``fobi.base.BaseTheme``. :return django.http.HttpResponse: """...
86bd61d807008578329ab1fdd7308798d90ff58a
3,609,449
from typing import Dict from typing import Any import json def set_blob_tags_command(client: Client, args: Dict[str, Any]) -> CommandResults: """ Sets the tags for the specified Blob. Args: client (Client): Azure Blob Storage API client. args (dict): Command arguments from XSOAR. Ret...
e414c6b53b36dca2b47fc1689455fde92bf5c5cd
3,609,450
import functools import operator def get_multipliers(*params): """ Determines the overall multiplier for a pokemon of specified type(s) attacking another pokemon of specified type(s) Accepts the types as any one of the following: A string with an attacker move/type, followed by '->', followed by a...
c75a66456477426dadc28ce84f952c14bc6622d2
3,609,451
def calculate_roi(): """ Calculate returning on investment for 4 years. """ request_parameters = request.get_json() arguments, errors = CalculateRoiForm().load({ 'months': request_parameters.get('months'), 'money_per_month': request_parameters.get('economy').get('money_per_month'), ...
1ba5e929ad71aa42e811b597ff9b251bbeafdbe0
3,609,452
def safe_filename(filename, replace=' '): """文件名过滤非法字符串 """ replace_illegal_str = str.maketrans( ILLEGAL_STR, replace * len(ILLEGAL_STR)) new_filename = filename.translate(replace_illegal_str).strip() if new_filename: return new_filename raise Exception('文件名不合法. new_filename={}'....
1df9a49f1288ab0533ae49a0e041875fafc72a94
3,609,453
import copy def prepare_chart_data(val_list, factors): """ combine value and sample info together, grouping, collapse by order_index """ factors = copy.deepcopy(factors) # combine values and samples, just by position in the array for idx, e in enumerate(factors): e['value']...
950839ab6ee30e7a278de66527b1db3d4c5b5441
3,609,454
def black_on_red(string, *funcs, **additional): """Text color - black on background color - red. (see sgr_combiner()).""" return sgr_combiner(string, ansi.BLACK, *funcs, attributes=(ansi.BG_RED,))
2e2e035baac1fb9c2d070b9c93f04db9cd2875f3
3,609,455
import typing from pydantic_factories import ModelFactory def create(input_block: LinearBackboneModel, output_dim: int, rnn_layers: typing.List[int], rnn_dropout: float=0.0, bidirectional: bool=False, linear_layers: typing.List[int]=None, linear_dropout: float=0.0): """ Vel creation function...
87f67f2a671abe61f2c8f068037bfd59d674f9af
3,609,456
def index_key(fact): """ A new total indexing of the fact. Just build the whole damn thing, assuming it doesn't explode the memory usage. >>> index_key('cell') 'cell' >>> index_key(('cell',)) ('cell',) >>> index_key(('cell', '5')) ('cell', '5') >>> index_key((('value', '?x'),...
d4a98283dce65a34b2b6f91573b0081080a2f777
3,609,457
def nrvocale(text): """Scrieti o functie care calculeaza cate vocale sunt intr-un string""" count = 0 for c in text: if c in ['a', 'e', 'i', 'o', 'u']: count = count + 1 return count
083d0bd8e8954a795fe36abaf567472561a9e13f
3,609,458
def GetATMValueSummary(atm_value): """ Summarizes the atm_value params: atm_value = value object of type atm_value_t returns: string with the summary of the type. """ format_str = "{0: <#020x} {1: <16d} {2: <#020x} {3: <16d}" out_string = format_str.format(atm_value, unsigned(atm_value.a...
70b0c2c303beead4e31c1286b75712057d04c904
3,609,459
import argparse def ParseArgs(): """Parse commandline arguments. Returns: options: Namespace from argparse.parse_args(). """ parser = argparse.ArgumentParser(description="EC firmware stack analyzer.") parser.add_argument('elf_path', help="the path of EC firmware ELF") parser.add_argument('--export_ta...
c4a818b8e880c2de9fb2ea797764c7cd0ed70181
3,609,460
import pathlib def abst_path(path): """Returns a PurePath for a string representation, after checking a path string is from the root.""" p = pathlib.PurePath(path) assert p.is_absolute() return p
b86ecd8585575e3642ddd1ff54de91eb1cd5d6d9
3,609,461
def fpga_read(addr): """ read and return FPGA register content (one byte) input: addr : address of the register relatively to the beginning FPGA memory address output: v : register content """ check_running_onjog() if jogio_utils.robotPlatform == "JOG": ...
f172bcae5f53aff775802f727fe2f351dc2618f6
3,609,462
def visualize_reconstruction_and_att(img, img_size, vertices_full, vertices, vertices_2d, camera, renderer, ref_points, attention, focal_length=1000): """Overlays gt_kp and pred_kp on img. Draws vert with text. Renderer is an instance of SMPLRenderer. """ # Fix a flength so i can render this with pe...
4e5e5b556d4e6eb2a693f4d371fa5b404aa23728
3,609,463
from typing import Concatenate def yolo_body(input_shape, anchors_mask, num_classes): """ YoloV4 FPN and head network building :param input_shape: image input shape :param anchors_mask: anchor masks :param num_classes: number of category classes :return: Model """ inputs = Input(input_...
4a0b8d3f2d9578f338ff6e144b6a77fbf2b230f9
3,609,464
def find_matrix_min(matrix): """ find matrix minimal values :param ndarray matrix: :return float, [(int, int)]: >>> np.random.seed(0) >>> mx = np.round(np.random.random((3, 4)), 3) >>> mx array([[0.549, 0.715, 0.603, 0.545], [0.424, 0.646, 0.438, 0.892], [0.964, 0.383...
d26a2737a6da014f4dd720daeb674a9effb09f6c
3,609,465
def new_cluster(number_of_stars=1000, radius=None): """ Return a new cluster of stars with the given radii and a salpeter mass distribution. """ if radius is None: radius = (0.5 / number_of_stars) | nbody_system.length particles = new_plummer_model(number_of_stars) particles.mass = ...
a57664806c0750ca8084520011ced224921130b8
3,609,466
def compute_centerlines(params): """ Compute the centerlines for a surface model. """ ## Check input parameters. # if not params.surface_model: logger.error("No surface model has been specified.") return if not params.centerlines_output_file: logger.error("No centerline...
b5587edc32e9f360fa5d22078dcb0eaa3f71dd86
3,609,467
def type_user(update: Update, context: CallbackContext) -> int: """Prompts user to type username""" # user has entered the function through the main menu language = context.user_data["bot_lang"] msg = context.bot_data["texts"][language]["type_user"] if update.callback_query: update.callback...
30ffdb749f6a2a4cb81b6c5267545a148503c63a
3,609,468
import mpmath import typing def default_val(utype): """ Returns a generic default value for a given type""" if utype is int: return 0 elif utype is float: return 0. elif utype is mpmath.mpf: return mpmath.mpf("0.0") elif utype is str: return "" elif utype is boo...
aa2fc3cbba5db3ddee6ff20fa86a53f28d9381bc
3,609,469
def nvl(value, default): """ Evaluates if value es empty or None, if so returns default Parameters: value: the evalue to evaluate default: the default value Returns: value or default """ if value: return value return default
67df45a6e63c107dcef99fc7bdbaa7064b695f66
3,609,470
def get_data_lazy(image: ImageWrapper, c_index: int = 0) -> da.Array: """Get n-dimensional dask array, with delayed reading from OMERO image.""" size_z = image.getSizeZ() size_t = image.getSizeT() size_x = image.getSizeX() size_y = image.getSizeY() pixels = image.getPrimaryPixels() @delayed...
12b990bc1f7fb2a355463c2c1543605c3169a0b2
3,609,471
def verify_crm_thresholds(dut, family, thresholdtype=None, highthreshold=None, lowthreshold=None, cli_type=""): """ To verify the CRM Threshold parameters Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com) :param dut: :param family: :param thresholdtype: :param highthreshold: :param l...
3e29cc301aae1ded583be28c07ead508dbb1c59f
3,609,472
from typing import Union from pathlib import Path from typing import Dict from typing import List from typing import Counter def load_crowdsourced_xlsx_to_predictions( data_path: Union[Path, str], questions_to_ids: Dict[str, str] ) -> Dict[str, List[str]]: """ Load in the crowdsourced "fixed spelling" dat...
e7756ec0de63df3b8e2630280e0def27aaf20fe3
3,609,473
from datetime import datetime def get_group_by_date_query_set(query_set, start_date=None, end_date=None, specific_year=True): """ :param query_set: Query before annotation :param start_date: <Date> :param end_date: <Date> :param specific_year: To filter query_set with date__range else filter with ...
b080bdd710d5390ce934368cf51ab20c59eb6ffc
3,609,474
def index(request, template_name='appname/example_list.html'): """Index view.""" qs = Example.objects.all() try: page = int(request.GET.get('page', 0)) except ValueError: raise Http404 return object_list( request, queryset=qs, template_object_name='example',...
20d14742cc94a861aa8274e00174c817b7a4db08
3,609,475
def UseExceptions(*args): """UseExceptions()""" return _gdal.UseExceptions(*args)
43f07f56a0fdc866f6495116ad68f4f32d9c68a5
3,609,476
from .models import DepartmentUser from datetime import datetime def alesco_data_import(fileobj): """Import task expects to be passed a file object (an uploaded .xlsx). """ LOGGER.info('Alesco data for DepartmentUsers is being updated') wb = load_workbook(fileobj, read_only=True) ws = wb.worksheet...
05de3fc8a4851e028fdb82a6de24843c4120dbed
3,609,477
def derive_aggregation(dim_cols, agg_col, agg): """Produces consistent aggregation spec from optional column specification. This utility provides some consistency to the flexible inputs that can be provided to charts, such as not specifying dimensions to aggregate on, not specifying an aggregation, and...
402c92a14b81d0e07ab4d36ccfd0854d0059d666
3,609,478
def redefine_strides(f): """Redefine attribute strides in dparray returned by specified function""" def wrapper(*args, **kwargs): res = f(*args, **kwargs) if not isinstance(res, dparray): return res strides = dpnp.asnumpy(res).strides res._dparray_strides = strides ...
7986c27f98b6728931e3b562aaf9754a427333f6
3,609,479
import click def no_prompt_option(fn): """ No prompt """ append_params(fn, [ click.Option( ("-y", "--yes"), help="Do not prompt before running operation.", is_flag=True), ]) return fn
01ea7a1a75db5c3d904cdd621a8a8f36cc57171b
3,609,480
def c10data_to_bas(c10data): """Given a C10Data Object, returns a bstring containing the equivalent BASIC program""" if c10data.filetype != 0: raise Exception(f'{c10data.filename} has a filetype of' f'{c10data.filetype}, expected 0') if c10data.binary_mode != 0: r...
e4f55a7781b4e13f15d72390a8bfdf296f7dfeed
3,609,481
def Keywords(lang_id=0): """Returns Specified Keywords List @param lang_id: used to select specific subset of keywords """ if lang_id == synglob.ID_LANG_DJANGO: return [(1, KEYWORDS)]
acaa9ef4cc85da81b544edeb746fee99ae880843
3,609,482
def create_list_from_file(input_file): """Read a file into a list of lists where the nested list is split on whitespace.""" file_list = [] with open(input_file) as inputfile: for line in inputfile: file_list.append(line.strip().split(' ', 1)) # the check sum and file name are sepa...
44008af32ead4ceff3597e8c479c100a12c7de15
3,609,483
def llik_gamma(x, s=None, pool=None, max_iters=10000, tol=1e-7, extrapolate=True, **kwargs): """Return marginal log likelihood of Gamma expression model for each column of x x - Anndata (n, p) s - size factor (n,) (default: total molecules per sample) """ return _map_llik(_llik_gamma, x, s, p...
b7e5925832b283a99c2a274010fb33743329eb4f
3,609,484
import torch def predict_sliding_(net, image, tile_size, classes, scale=1): """ Parameters ---------- net : nn.Module image : torch.Tensor shape [batch_size, c, h, w] tile_size: tuple or list max size of image inputted to the net scale : scalar Return -----...
b878876687dad25583a989a0556f5c91928504ff
3,609,485
import time def wait_until_reachable(ip, timeout=None): """等待直到节点可达 Args: ip: 主机IP timeout: (Default value = None) Returns: Bool: 状态 """ if not timeout: while True: if ping(ip): print("{}已ping通".format(ip)) break ...
c9175b8c054f9e90741f08858a27e8633a25b7da
3,609,486
import tqdm def pool_worker(target, inputs, num_worker=None, verbose=True): """Run target function in multi-process Parameters ---------- target : func function to excute multi process inputs: list list of argument of target function num_worker: int number of worker ve...
4e6807bedb744858d5f6ed01855d43e0278c4761
3,609,487
def _qnwtrap1(n, a, b): """ Compute univariate trapezoid rule quadrature nodes and weights Parameters ---------- n : int The number of nodes a : int The lower endpoint b : int The upper endpoint Returns ------- nodes : np.ndarray(dtype=float) A...
f12d6963dbde7a0c2a8b16f5772cd11c47796f90
3,609,488
def process_header(cols): """ Splits the proposed header from the command line on commas, and checks for the appropriate number of columns (passed as cols). If this number is incorrect, a warning is given. If the number of columns in the header is too few, the cells are padded. ...
56f6d7ae9601a41b070a660f50db003c7fd00f54
3,609,489
import pywt from scipy import signal def dominant_wavenumber(field, grid, n_scales=120, smoothing=(21, 7)): """Dominant zonal wavenumber at every gridpoint of field. Implements the procedure of Ghinassi et al. (2018) based on a wavelet analysis of the input field. - `n_scales` determines the number ...
e90e311d63a9e274d8aac3e35993e8519d65ff3f
3,609,490
import hashlib def hash_password(password): """ Normal MD5, except add c if a byte of the digest is less than 10. """ password_md5 = hashlib.md5(password.encode("utf-8")).hexdigest() for i in range(0, len(password_md5), 2): if password_md5[i] == "0": password_md5 = password_md5...
c806cbe22b99cd861ef4c9d19f971e6d61216c72
3,609,491
from typing import Optional def get_org_name_from_installation_event(body: dict) -> Optional[str]: """ Attempts to extract the organization name from the GitHub installation event. :param body: the github installation created event body :return: returns either the organization name or None """ ...
6525010483825548dd28926b74f2b8b172b52e0d
3,609,492
import torch import subprocess import logging def pytorch2onnx(model, input_shape): """Convert the pytorch model to onnx model. :param model: pytorch model class :type model: class :param input_shape: the shape of input :type input_shape: list :param onnx_save_path: the path and filename to s...
50fc9323ad13c6c42c7fb93ee5c9c783b5847426
3,609,493
def to_latlon(easting, northing, zone_number, northern=None): """ Main function to convert UTM to latitude-longitude. Takes XY and returns latlon basically. Arguments: easting (float or array): list of easting (X) coordinates northing (float or array): list of northing (Y) coordinates zo...
3c008d2f298a9d940b8869633cd2e67af27d4605
3,609,494
def _suitable_minimum_unit(minimum_unit: Unit, suppress: list[Unit]) -> Unit: """Return a minimum unit suitable that is not suppressed. If not suppressed, return the same unit: >>> from human_readable.times import _suitable_minimum_unit, Unit >>> _suitable_minimum_unit(Unit.HOURS, []) <Unit.HOURS: ...
b84e1f58a040f1c8c606c89c55a1e34c4322088b
3,609,495
def test_inside_lambda(): """ >>> obj = test_inside_lambda()() >>> next(obj) 1 >>> next(obj) 2 >>> next(obj) Traceback (most recent call last): StopIteration """ return lambda:((yield 1), (yield 2))
f737fce5c04b1bb7a9b7b8a15edc60571732c2d8
3,609,496
from datetime import datetime def check_version_format(version): """ Checks if a version number is well formed, eg: YYYY-MM-DDTHH:mm:ss """ try: datetime.datetime.strptime(version, "%Y-%m-%dT%H:%M:%S") return True except Exception: raise HTTPError(406, ...
37430e75eab841a68fa9ecced659049492f0dc7a
3,609,497
from datetime import datetime def buy(): """Buy shares of stock""" transaction = "BUY" # if requested via post if request.method == "POST": # saving the user input values name = request.form.get("symbol") if not name: return apology("Please enter a 4 letter ticker...
66f1e74d858404437ca6644b7a5eb2f0bd3a36bf
3,609,498
def get_properties_node(character_node): """ Returns HIKProperty2State node of the given HumanIk Character node :param character_node: str :return: str """ if not is_character_definition(character_node): raise Exception( 'Invalid character definition node! Object "{}" does n...
20949be3fb93ab994affddcad8cf87c8806cf4f4
3,609,499