content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def next(space, w_arr): """ Advance the internal array pointer of an array """ length = w_arr.arraylen() current_idx = w_arr.current_idx + 1 if current_idx >= length: w_arr.current_idx = length return space.w_False w_arr.current_idx = current_idx return w_arr._current(space)
668fec305ed6bbe05895f317e284c7d2e4f83189
8,700
def geocoordinatess_id_get(id, username=None): # noqa: E501 """Get a single GeoCoordinates by its id Gets the details of a given GeoCoordinates (more information in https://w3id.org/okn/o/sdm#GeoCoordinates) # noqa: E501 :param id: The ID of the GeoCoordinates to be retrieved :type id: str :param...
3ac772eab95915ac0030187f22da74f9965f6dfc
8,701
def check_callable(target, label=None): """Checks target is callable and then returns it.""" if not callable(target): raise TypeError('Expected {} callable, found non-callable {}.'.format( '{} to be'.format(label) if label is not None else 'a', type_string(type(target)))) return target
a22006b72e04adb47eeef0ee418301cecdbfde0b
8,702
import re def convert_dictionary_values(d, map={}): """convert string values in a dictionary to numeric types. Arguments d : dict The dictionary to convert map : dict If map contains 'default', a default conversion is enforced. For example, to force int for every column but colum...
4ecbd8ddd53324c3a83ce6b5bbe3ef0e5a86bc1e
8,703
def GetLimitPB(user, action_type): """Return the apporiate action limit PB part of the given User PB.""" if action_type == PROJECT_CREATION: if not user.project_creation_limit: user.project_creation_limit = user_pb2.ActionLimit() return user.project_creation_limit elif action_type == ISSUE_COMMENT: ...
91f9289d3be149112d08409b1cf1e2c8e68a9668
8,704
def best_int_dtype(data): """get bit depth required to best represent float data as int""" d, r = divmod(np.log2(data.ptp()), 8) d = max(d, 1) i = (2 ** (int(np.log2(d)) + bool(r))) return np.dtype('i%d' % i)
c8d54b10ba67a83250312668f7cd09b99e47bf56
8,705
def gen_decorate_name(*args): """ gen_decorate_name(name, mangle, cc, type) -> bool Generic function for 'decorate_name()' (may be used in IDP modules) @param name (C++: const char *) @param mangle (C++: bool) @param cc (C++: cm_t) @param type (C++: const tinfo_t *) """ return _ida_typeinf.g...
963f6bfc5ca30a7552f881d8c9f030c0c1653fce
8,706
def main(self, count=10): """ kosmos -p 'j.servers.myjobs.test("start")' """ self.reset() def wait_1sec(): gevent.sleep(1) return "OK" ids = [] for x in range(count): job_sch = self.schedule(wait_1sec) ids.append(job_sch.id) self._workers_gipc_nr_max =...
0634f76d33d6b32150f367d6c598f5c520991ef3
8,707
import requests def get_asc() -> pd.DataFrame: """Get Yahoo Finance small cap stocks with earnings growth rates better than 25%. [Source: Yahoo Finance] Returns ------- pd.DataFrame Most aggressive small cap stocks """ url = "https://finance.yahoo.com/screener/predefined/aggressive_sm...
7d7d9810782950434a0752c97984f20df74a3366
8,708
def getEnabled(chat_id): """Gets the status of a conversation""" status = EnableStatus.get_by_id(str(chat_id)) if status: return status.enabled return False
24d7ca4f197f6e4dc4c9c54e59824ff4fc89114e
8,709
def create_app(config=DevelopConfig): """App factory.""" app = Flask( __name__.split('.')[0], static_url_path='/static', static_folder=f'{config.PROJECT_PATH}/src/static' ) app.url_map.strict_slashes = False app.config.from_object(config) register_extensions(app) regi...
0154d3ebb00ae869c2f1bb2a2392e2bde74e36b4
8,710
def merge_inputs_for_create(task_create_func): """Merge all inputs for start operation into one dict""" # Needed to wrap the wrapper because I was seeing issues with # "RuntimeError: No context set in current execution thread" def wrapper(**kwargs): # NOTE: ctx.node.properties is an ImmutablePr...
119ab1b40ba84959b960295b35e668de7296929f
8,711
def embedding_lookup(params, ids): """Wrapper around ``tf.nn.embedding_lookup``. This converts gradients of the embedding variable to tensors which allows to use of optimizers that don't support sparse gradients (e.g. Adafactor). Args: params: The embedding tensor. ids: The ids to lookup in :obj:`para...
774595aaf119ab93928095f397bc4ff7f5ebad53
8,712
from re import T def value_as_unit(value: T | None, unit: Unit = None) -> T | Quantity[T] | None: """Return value as specified unit or sensor fault if value is none.""" if value is None: return None if unit is None: return value return value * unit
3f96d837a40894d589fbae3f40ca6adf220a9d56
8,713
import numpy def get_static_spatial_noise_image(image) : """ The first step is to sum all of the odd-numbered images (sumODD image) and separately sum all of the even-numbered images (sumEVEN image). The difference between the sum of the odd images and the sum of the even images (DIFF = su...
511275fefc2368c6d3976ea420e11fcf1a913f8c
8,714
import os def get_gallery_dir() -> str: """ Return the path to the mephisto task gallery """ return os.path.join(get_root_dir(), "gallery")
d3bf9455b48429b1709f249ca5691237821e4566
8,715
import random def get_next_action(): """ gets the next action to perform, based on get_action_odds """ action_odds = get_action_odds() #print(f"DEBUG action_odds {action_odds}") # get the sum of all the action odds values total = 0 for action in action_odds: #print(f"DEBUG get_ne...
372676573e69afe045c88742591555fcfe42766a
8,716
def get_movie_title(movie_id): """ Takes in an ID, returns a title """ movie_id = int(movie_id)-1 return items.iloc[movie_id]['TITLE']
e3e0694eb35923ce3a6f528a4b9ac622044b9159
8,717
import logging def get_logger(): """ Return a logger object """ logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = logging.StreamHandler() handler.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s - %(message)s") handler.setFormatter(form...
a23531364d947a83ace175ba02212ff57ba7e0ea
8,718
def enough_gap_since_last_obs(df, current_state, obs_log): """ Determine if a sufficient time has passed since the last observation in this subprogram (in any filter): """ now = current_state['current_time'].mjd # don't mess up with the upstream data structure df = df.copy() grp = df....
3a58a7d03074eec6458b4a10addc40953d01da8b
8,719
def find_nearest_feature_to_attribute(sentence, features, attribute): """ Parameters ---------- sentence: str, One sentence from the info text of a mushroom species features: list of strs List of possible features as in dataset_categories.features_list attribute: str, Mushroom featur...
6877ec945870cce9a0873a713830fa5f830408fc
8,720
from datetime import datetime def lists(): """ 库存列表 :return: """ template_name = 'inventory/lists.html' # 文档信息 document_info = DOCUMENT_INFO.copy() document_info['TITLE'] = _('inventory lists') # 搜索条件 form = InventorySearchForm(request.form) form.warehouse_id.choices = get...
25c561167cc34eba5bd8bf8123007961d28165e3
8,721
def open_1d_txt(filename, xaxcol=0, datacol=1, errorcol=2, text_reader='simple', format=None, **kwargs): """ Attempt to read a 1D spectrum from a text file assuming wavelength as the first column, data as the second, and (optionally) error as the third. Reading can be done either with a...
133361ba2ba75a1f13f8768c6130601db3d870ec
8,722
def clean_record(raw_string: str) -> str: """ Removes all unnecessary signs from a raw_string and returns it :param raw_string: folder or file name to manage :return: clean value """ for sign in ("'", '(', ')', '"'): raw_string = raw_string.replace(sign, '') return raw_string.replace...
ea484934dc10da879ede883287fc1d650cda74b8
8,723
import pandas as pd import numpy as np def df_of_tables_for_dd_ids(dd_ids, sqlite_tables, sql_con): """ :param list dd_ids: list of Deep Dive IDs to retrieve :param list sqlite_tables: list of SQLite tables to join :param sqlalchemy.create_engine sql_con: Connection to SQLite (can be \ omitted) ...
282d3e9bda8e38687660c21323f8bb3ea40abbd2
8,724
from typing import Union def get_group_type(group: Union[hou.EdgeGroup, hou.PointGroup, hou.PrimGroup]) -> int: """Get an HDK compatible group type value. :param group: The group to get the group type for. :return: An HDK group type value. """ try: return _GROUP_TYPE_MAP[type(group)] ...
e8b708911760c99c6e3c23d39b4fc4d205380bac
8,725
def mp2d_driver(jobrec, verbose=1): """Drive the jobrec@i (input) -> mp2drec@i -> mp2drec@io -> jobrec@io (returned) process.""" return module_driver( jobrec=jobrec, module_label='mp2d', plant=mp2d_plant, harvest=mp2d_harvest, verbose=verbose)
efa3cf31714719f87c239dbd6cdd1aad80982647
8,726
def query_user_list(): """ Retrieve list of users on user watch list. """ conn = connect.connect() cur = conn.cursor() cur.execute("SELECT * FROM watched_users") watched_users = cur.fetchall() return watched_users
2de40bc963503e4c87d7bc15409bf4803c5c87a6
8,727
def service_stop_list(service_id, direction): """ Queries all patterns for a service and creates list of stops sorted topologically. :param service_id: Service ID. :param direction: Groups journey patterns by direction - False for outbound and True for inbound. """ graph, di...
c2eaf08853469597a83647a3e1ec5fc6a7b02ced
8,728
def convert_coord(value): """将GPS值转换为度分秒形式 Args: value(str): GPS读取的经度或纬度 Returns: list: 度分秒列表 """ v1, v2 = value.split('.') v2_dec = Decimal(f'0.{v2}') * 60 # + Decimal(random.random()) return [v1[:-2], v1[-2:], v2_dec.to_eng_string()]
4269e9d9b58e3d7ce42c82cd0299abac6c740499
8,729
import torch def _interpolate_zbuf( pix_to_face: torch.Tensor, barycentric_coords: torch.Tensor, meshes ) -> torch.Tensor: """ A helper function to calculate the z buffer for each pixel in the rasterized output. Args: pix_to_face: LongTensor of shape (N, H, W, K) specifying the indices ...
b54d6c44fd23f842b13cb7ac1984f77c7a6a31a4
8,730
from typing import Sequence def pp_chain(chain: Sequence[Subtree]) -> str: """Pretty-print a chain """ return ' '.join( s.label if isinstance(s, ParentedTree) else str(s) for s in chain )
372488b64c86c2af459d67e5ddde0a77fa26fb5c
8,731
def ptr_ty(ty : 'LLVMType') -> 'LLVMPointerType': """``ty*``, i.e. a pointer to a value of type ``ty``.""" return LLVMPointerType(ty)
79c7d304c4cd20937abe982311b2ff6ff17a01f9
8,732
def series_spline(self): """Fill NaNs using a spline interpolation.""" inds, values = np.arange(len(self)), self.values invalid = isnull(values) valid = -invalid firstIndex = valid.argmax() valid = valid[firstIndex:] invalid = invalid[firstIndex:] inds = inds[firstIndex:] result ...
1fbbf66efc7e6c73bdcc3c63aab83237e434aa79
8,733
def label(job_name, p5_connection=None): """ Syntax: Job <name> label Description: Returns the (human readable) job label. The following labels are returned: Archive, Backup, Synchronize and System. A Job label can be used in conjunction with the Job describe command to better display the jo...
ec58cbb085cb06f5ad8f2c2d04ee6cd9d3638984
8,734
import math def rating(pairing, previous): """The lower the rating value is the better""" current = set(chain.from_iterable(pair[1] for pair in pairing)) overlaps = current & set(previous) if overlaps: return sum(math.pow(0.97, previous[overlap] / 86400) for overlap in overlaps) return 0.0
af86bf1c1bbe036e20e3a1e7bcff0dec09d382cf
8,735
from typing import Optional from typing import Dict def copy_multipart_passthrough(src_blob: AnyBlob, dst_blob: CloudBlob, compute_checksums: bool=False) -> Optional[Dict[str, str]]: """ Copy from `src_blob` to `dst_blob`, passing data through the ...
ba37598a55e00252f879e66c1438681f0033de34
8,736
import csv def read_manifest_from_csv(filename): """ Read the ballot manifest into a list in the format ['batch id : number of ballots'] from CSV file named filename """ manifest = [] with open(filename, newline='') as csvfile: reader = csv.reader(csvfile, delimiter = ",") for ...
b04b6a1b20512c27bb83a7631346bc6553fdc251
8,737
def siblings_list(): """ Shows child element iteration """ o = untangle.parse( """ <root> <child name="child1"/> <child name="child2"/> <child name="child3"/> </root> """ ) return ",".join([child["name"] for child in o.root.chil...
06737cb187e18c9fa8b9dc9164720e68f5fd2c36
8,738
import sys def max_distance_from_home(traj, start_night='22:00', end_night='07:00', show_progress=True): """ Compute the maximum distance from home (in kilometers) traveled by an individual. :param traj: the trajectories of the individuals :type traj: TrajDataFrame :param str start_night: th...
9226ce6ab2929d4e36c9b7eabbb6377af315e0ab
8,739
def combine_histogram(old_hist, arr): """ Collect layer histogram for arr and combine it with old histogram. """ new_max = np.max(arr) new_min = np.min(arr) new_th = max(abs(new_min), abs(new_max)) (old_hist, old_hist_edges, old_min, old_max, old_th) = old_hist if new_th <= old_th: h...
bc6e6edc9531b07ed347dc0083f86ee921d77c11
8,740
from typing import Mapping def unmunchify(x): """ Recursively converts a Munch into a dictionary. >>> b = Munch(foo=Munch(lol=True), hello=42, ponies='are pretty!') >>> sorted(unmunchify(b).items()) [('foo', {'lol': True}), ('hello', 42), ('ponies', 'are pretty!')] unmunchify wil...
90ee373099d46ca80cf78c4d8cca885f2258bce2
8,741
def split_data(mapping, encoded_sequence): """ Function to split the prepared data in train and test Args: mapping (dict): dictionary mapping of all unique input charcters to integers encoded_sequence (list): number encoded charachter sequences Returns: numpy array : train and test...
b8044b3c1686b37d4908dd28db7cbe9bff2e899a
8,742
def fsp_loss(teacher_var1_name, teacher_var2_name, student_var1_name, student_var2_name, program=None): """Combine variables from student model and teacher model by fsp-loss. Args: teacher_var1_name(str): The name of teacher_var1. teacher_var2...
b8937a64ec8f5e215128c61edee522c9b2cd83d7
8,743
def diff_numpy_array(A, B): """ Numpy Array A - B return items in A that are not in B By Divakar https://stackoverflow.com/a/52417967/1497443 """ return A[~np.in1d(A, B)]
72139ba49cf71abd5ea60772143c26f384e0e171
8,744
import sys def load_training_data(training_fns, trunc_min_scores, trunc_max_scores, debug=False): """ First parse group, read and position to find shared data points Then read in training scores, truncating as appropriate """ # Parse file twice. First time get all the loci, second time all the...
7107d0ebff84df09589db43004804c22ffa39abc
8,745
def _find_data_between_ranges(data, ranges, top_k): """Finds the rows of the data that fall between each range. Args: data (pd.Series): The predicted probability values for the postive class. ranges (list): The threshold ranges defining the bins. Should include 0 and 1 as the first and last val...
323986cba953a724f9cb3bad8b2522fc711529e5
8,746
def validar_entero_n(): """ """ try: n = int(input('n= ')) #si es un float también funciona el programa except: print ('Número no válido') return False else: return n
a1238025fd2747c597fc2adf34de441ae6b8055d
8,747
def Conv_Cifar10_32x64x64(): """A 3 hidden layer convnet designed for 32x32 cifar10.""" base_model_fn = _cross_entropy_pool_loss([32, 64, 64], jax.nn.relu, num_classes=10) datasets = image.cifar10_datasets(batch_size=128) retu...
e41e2f0da80f8822187a2ee82dcfe6f70e324213
8,748
from typing import List def rotate(angle_list: List, delta: float) -> List: """Rotates a list of angles (wraps around at 2 pi) Args: angle_list (List): list of angles in pi radians delta (float): amount to change in pi radians Returns: List: new angle list in pi radians """ ...
560c5138486bd3e67ad956fb2439236a3e3886cc
8,749
def global_average_pooling_3d(tensor: TorchTensorNCX) -> TorchTensorNCX: """ 3D Global average pooling. Calculate the average value per sample per channel of a tensor. Args: tensor: tensor with shape NCDHW Returns: a tensor of shape NC """ assert len(tensor.shape) == 5, 'm...
27a73d29fd9dd63b461f2275ed2941bf6bd83348
8,750
def get_LAB_L_SVD_s(image): """Returns s (Singular values) SVD from L of LAB Image information Args: image: PIL Image or Numpy array Returns: vector of singular values Example: >>> from PIL import Image >>> from ipfml.processing import transform >>> img = Image.open('./im...
50a4bd4e4a8b3834baa3aca1f5f1e635baa7a145
8,751
def path_inclusion_filter_fn(path, param, layer): """Returns whether or not layer name is contained in path.""" return layer in path
c93aa83e67c600cd83d053d50fbeaee4f7eebf94
8,752
from typing import Tuple def _parse_feature(line: PipelineRecord) -> Tuple[str, Coordinates, Feature]: """ Creates a Feature from a line of output from a CSVReader """ contig = line[0] coordinates = parse_coordinates(line[1]) feature = line[2] # Piler-cr and BLAST both use 1-based indices, but Op...
201f9c6ed5cd618fc63ec5e07a5b99977f4ef2b0
8,753
def average_summary_df_tasks(df, avg_columns): """ Create averages of the summary df across tasks.""" new_df = [] # Columns to have after averaging keep_cols = ["dataset", "method_name", "trial_number"] subsetted = df.groupby(keep_cols) for subset_indices, subset_df in subsetted: return...
9c506132cc406a91979777255c092db20d786d12
8,754
def ml_variance(values, mean): """ Given a list of values assumed to come from a normal distribution and their maximum likelihood estimate of the mean, compute the maximum likelihood estimate of the distribution's variance of those values. There are many libraries that do something like this, but th...
440d8d2d2f0a5ed40e01e640aadafb83f16ee14b
8,755
def add_landmarks(particle, d, angle): """ Adds a set of landmarks to the particle. Only used on first SLAM cycle when no landmarks have been added. :param particle: The particle to be updated :param d: An array of distances to the landmarks :param angle: An array of observation angles for the ...
d1d168e48f62f60d58e57a79223793108d50dac9
8,756
def walk_forward_val_multiple(model, ts_list, history_size=HISTORY_SIZE, target_size=TARGET_SIZE) -> float: """ Conduct walk-forward validation for all states, average the results. Parameters ---------- model -- The model to be validated ...
b3f73ceeddb720fdc7c7d9470a49bccc3c21f81b
8,757
import argparse def main(): """The 'real' entry point of this program""" # parse args parser = argparse.ArgumentParser( prog=hdtop.const.PROG_NAME, description=hdtop.const.DESCRIPTION ) parser.add_argument( "action", default="start", nargs="?", choices=_SUBP...
926ebb9ecb2af7b6d0a3f0ed9c2eae035531973a
8,758
def inverse_project_lambert_equal_area(pt): """ Inverse Lambert projections Parameters: pt: point, as a numpy array """ X = pt[0] Y = pt[1] f = np.sqrt(1.0-(X**2.0+Y**2.0)/4) return tensors.Vector([f*X,f*Y,-1.0+(X**2.0+Y**2.0)/2])
f8ab5fb44d2d271a8da13623273d8d687d38b772
8,759
import dataclasses def _get_field_default(field: dataclasses.Field): """ Return a marshmallow default value given a dataclass default value >>> _get_field_default(dataclasses.field()) <marshmallow.missing> """ # Remove `type: ignore` when https://github.com/python/mypy/issues/6910 is fixed ...
0c45e55a1c14cb6b47365ef90cb68e517342dbbc
8,760
from typing import Optional from typing import Dict from typing import Union import os import tempfile def download_file_from_s3( s3_path: str, local_path: str, create_dirs: bool = True, silent: bool = False, raise_on_error: bool = True, boto3_kwargs: Optional[Dict[str, Union[str, float]]] = N...
7c1cf7cfee127e7583316fe9fef67f072c0441f9
8,761
from typing import List from typing import Tuple import select def get_all_votes(poll_id: int) -> List[Tuple[str, int]]: """ Get all votes for the current poll_id that are stored in the database Args: poll_id (int): Telegram's `message_id` for the poll Returns: List[Tuple[str, int]]:...
cf0ad8ee700a0da70bf29d53d08ab71e08c941ea
8,762
def getUnitConversion(): """ Get the unit conversion from kT to kJ/mol Returns factor: The conversion factor (float) """ temp = 298.15 factor = Python_kb/1000.0 * temp * Python_Na return factor
cb7b33231a53a68358713ce65137cbf13a397923
8,763
def find_where_and_nearest(array, value): """ Returns index and array[index] where value is closest to an array element. """ array = np.asarray(array) idx = (np.abs(array - value)).argmin() return idx, array[idx]
a34ac1d59c8093989978fbca7c2409b241cedd5b
8,764
import numpy def twoexpdisk(R,phi,z,glon=False, params=[1./3.,1./0.3,1./4.,1./0.5,logit(0.1)]): """ NAME: twoexpdisk PURPOSE: density of a sum of two exponential disks INPUT: R,phi,z - Galactocentric cylindrical coordinates or (l/rad,b/rad,D/kpc) glon= (False...
bf8c5e0afa28e715846401274941e281a8731f24
8,765
def sc(X): """Silhouette Coefficient""" global best_k score_list = [] # 用来存储每个K下模型的平局轮廓系数 silhouette_int = -1 # 初始化的平均轮廓系数阀值 for n_clusters in range(3, 10): # 遍历从2到10几个有限组 model_kmeans = KMeans(n_clusters=n_clusters, random_state=0) # 建立聚类模型对象 cluster_labels_tmp = model_kmeans.f...
c2898e115db04c1f1ac4d6a7f8c583ea0a8b238e
8,766
import socket import time def is_tcp_port_open(host: str, tcp_port: int) -> bool: """Checks if the TCP host port is open.""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(2) # 2 Second Timeout try: sock.connect((host, tcp_port)) sock.shutdown(socket.SHUT_RD...
cbe4d0ae58610b863c30b4e1867b47cb1dbdfc3d
8,767
from typing import Callable from typing import Any import itertools def recursive_apply_dict(node: dict, fn: Callable) -> Any: """ Applies `fn` to the node, if `fn` changes the node, the changes should be returned. If the `fn` does not change the node, it calls `recursive_apply` on the children of the...
c40daa68caaea02d16511fcc1cd3ee1949c73633
8,768
import six def encode_image_array_as_jpg_str(image): """Encodes a numpy array into a JPEG string. Args: image: a numpy array with shape [height, width, 3]. Returns: JPEG encoded image string. """ image_pil = Image.fromarray(np.uint8(image)) output = six.BytesIO() image_pil.save(output, format=...
4c2d27c15c6979678a1c9619a347b7aea5718b2c
8,769
def minify_response(response): """Minify response to save bandwith.""" if response.mimetype == u'text/html': data = response.get_data(as_text=True) response.set_data(minify(data, remove_comments=True, remove_empty_space=True, ...
29a942d870636337eaf0d125ba6b2ca9945d1d1c
8,770
def get_shorturlhash(myurl): """Returns a FNV1a hash of the UNquoted version of the passed URL.""" x = get_hash(unquote(myurl)) return x
f61ef1cfe14fc69a523982888a7b1082244b7bd5
8,771
def filter_privacy_level(qs, clearance_level, exact=False): """ Function to exclude objects from a queryset, which got a higher clearance level than the wanted maximum clearance level. :qs: Django queryset. :clearance_level: Minimum clearance level. :exact: Boolean to check for the exact cleara...
a5fd864b3a9efd86bf40e0a3b966edb047979b2a
8,772
def get_configuration_store(name=None,resource_group_name=None,opts=None): """ Use this data source to access information about an existing App Configuration. ## Example Usage ```python import pulumi import pulumi_azure as azure example = azure.appconfiguration.get_configuration_store(n...
4c0baa2cdd089439f1a53415ff9679568a097094
8,773
def _linear(args, output_size, bias, scope=None, use_fp16=False): """Linear map: sum_i(args[i] * W[i]), where W[i] is a variable. Args: args: a 2D Tensor or a list of 2D, batch x n, Tensors. output_size: int, second dimension of W[i]. bias: boolean, whether to add a bias term or not. bi...
d8daafaf1dfab0bc6425aef704543833bfbf731a
8,774
def find_CI(method, samples, weights=None, coverage=0.683, logpost=None, logpost_sort_idx=None, return_point_estimate=False, return_coverage=False, return_extras=False, options=None): """Compute credible intervals and point estimates from samples. Arguments --------- ...
6b5ab3ac47f4f4a0251862946336948fd2ff66ed
8,775
def load_csv(filename, fields=None, y_column=None, sep=','): """ Read the csv file.""" input = pd.read_csv(filename, skipinitialspace=True, usecols=fields, sep=sep, low_memory=False) input = input.dropna(subset=fields) # dtype={"ss_list_price": float, "ss_wholesale_cost": float} ...
126b96e94f4a5ab201460b427828807cf31eb6ae
8,776
def Normalize(array): """Normalizes numpy arrays into scale 0.0 - 1.0""" array_min, array_max = array.min(), array.max() return ((array - array_min)/(array_max - array_min))
a8f3bae56f8e17aed80f8e41030d049a69ac8cae
8,777
def obtener_cantidad_anualmente(PaisDestino, AnioInicio, AnioFin): """ Obtener cantidad de vuelos entrantes anualmente dado un pais destino y un rango de años Obtiene la cantidad total de vuelos entrantes de cada año :param PaisDestino: Pais al que llegan los vuelos :type PaisDestino: str :param...
8364a08f4b42124b70a7769dc6a9649cdd9841d7
8,778
def calculate_shap_for_test(training_data, y, pipeline, n_points_to_explain): """Helper function to compute the SHAP values for n_points_to_explain for a given pipeline.""" points_to_explain = training_data[:n_points_to_explain] pipeline.fit(training_data, y) return _compute_shap_values(pipeline, pd.Dat...
d8a88b3c9af05a8274a0cca1a0e63c3a9faaa8d0
8,779
def read_num_write(input_string): """ read in the number of output files """ pattern = ('NumWrite' + one_or_more(SPACE) + capturing(INTEGER)) block = _get_training_data_section(input_string) keyword = first_capture(pattern, block) assert keyword is not None return keyword
0ee1a9ac178eb4c49a01a36208e4c59d6b9023bc
8,780
import requests import json def stock_zh_a_minute(symbol: str = 'sh600751', period: str = '5', adjust: str = "") -> pd.DataFrame: """ 股票及股票指数历史行情数据-分钟数据 http://finance.sina.com.cn/realstock/company/sh600519/nc.shtml :param symbol: sh000300 :type symbol: str :param period: 1, 5, 15, 30, 60 分钟的数...
b54f7dce68e102ebfa6c1784de5ebd49fcb405cb
8,781
import random def randomize_case(s: str) -> str: """Randomize string casing. Parameters ---------- s : str Original string Returns ------- str String with it's letters in randomized casing. """ result = "".join( [c.upper() if random.randint(0, 1) == 1 else...
5e00ce336e2886a0d3bd52bc033b02560f0fb9ae
8,782
def _get_results(): """Run speedtest with speedtest.py""" s = speedtest.Speedtest() print("Testing download..") s.download() print("Testing upload..") s.upload() return s.results.ping, s.results.download, s.results.upload
7092a5aa7200ebc93e266dbd6b7885095b0433bb
8,783
def findCursor(query, keyname, page_no, page_size): """Finds the cursor to use for fetching results from the given page. We store a mapping of page_no->cursor in memcache. If this result is missing, we look for page_no-1, if that's missing we look for page_no-2 and so on. Once we've found one (or we get back to ...
9af3368ef0011d7c6c9758f57bc2c956d540f675
8,784
def _get_seq(window,variants,ref,genotypeAware): """ Using the variation in @variants, construct two haplotypes, one which contains only homozygous variants, the other which contains both hom and het variants by placing those variants into the reference base string @param variants: A vcf_eval.ChromV...
316c19f964c6ce29d52358070d994f0fdfbcc1b8
8,785
import scipy def interp_logpsd(data, rate, window, noverlap, freqs, interpolation='linear'): """Computes linear-frequency power spectral density, then uses interpolation (linear by default) to estimate the psd at the desired frequencies.""" stft, linfreqs, times = specgram(data, window, Fs=rate, noverlap=...
0822f776063da9f0797aa898b0305fb295d8c0f1
8,786
def load_replica_camera_traj(traj_file_path): """ the format: index """ camera_traj = [] traj_file_handle = open(traj_file_path, 'r') for line in traj_file_handle: split = line.split() #if blank line, skip if not len(split): continue camera_traj.a...
1879c97ed5ce24834689b156ffdc971b023e67f2
8,787
def test_model(sess, graph, x_, y_): """ :param sess: :param graph: :param x_: :param y_: :return: """ data_len = len(x_) batch_eval = batch_iter(x_, y_, 64) total_loss = 0.0 total_acc = 0.0 input_x = graph.get_operation_by_name('input_x').outputs[0] input_y = graph...
7c310a7cf979004d9f14fbd1ec57228dbfc81cd2
8,788
def epanechnikov(h: np.ndarray, Xi: np.ndarray, x: np.ndarray) -> np.ndarray: """Epanechnikov kernel. Parameters: h : bandwidth. Xi : 1-D ndarray, shape (nobs, 1). The value of the training set. x : 1-D ndarray, shape (1, nbatch). The value at which the kernel density is being estimated...
45902e9396661a6c0f8faf9cfc2d017125f6a427
8,789
def punctuation(chars=r',.\"!@#\$%\^&*(){}\[\]?/;\'`~:<>+=-'): """Finds characters in text. Useful to preprocess text. Do not forget to escape special characters. """ return rf'[{chars}]'
b2fd23d8485c3b6d429723a02a95c981982559b5
8,790
import time import logging def log_http_request(f): """Decorator to enable logging on an HTTP request.""" level = get_log_level() def new_f(*args, **kwargs): request = args[1] # Second argument should be request. object_type = 'Request' object_id = time.time() log_name = ob...
ecb62d0501307330fc0a56d8eadfbee8e729adf6
8,791
def look_at(vertices, eye, at=[0, 0, 0], up=[0, 1, 0]): """ "Look at" transformation of vertices. """ if (vertices.ndimension() != 3): raise ValueError('vertices Tensor should have 3 dimensions') place = vertices.place # if list or tuple convert to numpy array if isinstance(at, lis...
10a6b94ecba08fecd829758f9c94765c718a5add
8,792
import types def _count(expr, pat, flags=0): """ Count occurrences of pattern in each string of the sequence or scalar :param expr: sequence or scalar :param pat: valid regular expression :param flags: re module flags, e.g. re.IGNORECASE :return: """ return _string_op(expr, Count, out...
c4c387f18ac75977a661662dae7606a066242b57
8,793
def simplex3_vertices(): """ Returns the vertices of the standard 3-simplex. Each column is a vertex. """ v = np.array([ [1, 0, 0], [-1/3, +np.sqrt(8)/3, 0], [-1/3, -np.sqrt(2)/3, +np.sqrt(2/3)], [-1/3, -np.sqrt(2)/3, -np.sqrt(2/3)], ]) return v.transpose()
b10c2c781d1f7ed7050e14f069efd3e0e9a80a2b
8,794
def get_output_msg(status, num_logs): """ Returnes the output message in accordance to the script status """ if status == EXECUTION_STATE_COMPLETED: return "Retrieved successfully {} logs that triggered the alert".format(num_logs) else: return "Failed to retrieve logs. Please check the scrip...
caec8de737251cc7c386a85a098d73d19617e71a
8,795
def kSEQK(age): """Age-dependent organ-specific absorbed dose rate per unit kerma rate, normalized against the corresponding value for an adult Parameters ---------- age: float or list Age(s) when kSEQK is evaluated. """ k=[] if (not isinstance(age,list)) and (not isinstance...
967584edc3be078eab2b8d21338bb5221f9c65ca
8,796
import re def insert_channel_links(message: str) -> str: """ Takes a message and replaces all of the channel references with links to those channels in Slack formatting. :param message: The message to modify :return: A modified copy of the message """ message_with_links = message match...
ce56e81e8eb66dc0f2754141bcfc30f42db50c5a
8,797
def check_int_uuid(uuid): """Check that the int uuid i pass is valid.""" try: converted = UUID(int=uuid, version=4) except ValueError: return False return converted.int == uuid
a0ba7447e6c8cc0c35b68024fb4ade25f0802239
8,798
def calc_E_E_C_hs_d_t_i(i, device, region, A_A, A_MR, A_OR, L_CS_d_t, L_CL_d_t): """暖冷房区画𝑖に設置された冷房設備機器の消費電力量(kWh/h)を計算する Args: i(int): 暖冷房区画の番号 device(dict): 暖冷房機器の仕様 region(int): 省エネルギー地域区分 A_A(float): 床面積の合計 (m2) A_MR(float): 主たる居室の床面積 (m2) A_OR(float): その他の居室の床面積 (m2) ...
8dbd0119ac90f3847de1f5af05891583a9bda26b
8,799