content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import platform def get_log_path(subfolder=None, filename=None, create=True): """ Returns the default log path for the platform. This will be: - macOS: '~/Library/Logs/SUBFOLDER/FILENAME' - Linux: '$XDG_CACHE_HOME/SUBFOLDER/FILENAME' - fallback: '$HOME/.cache/SUBFOLDER/FILENAME' ...
e09157cb91ef378c25dc0fe116c89cc5398b7af3
48,074
from typing import Any def frozen_after_init(cls: C) -> C: """Class decorator to freeze any modifications to the object after __init__() is done. The primary use case is for @dataclasses who cannot use frozen=True due to the need for a custom __init__(), but who still want to remain as immutable as possi...
367ee5c692c98aefcc1ea3905e352483d47c43f1
48,076
async def async_get_trigger_capabilities( hass: HomeAssistant, config: ConfigType ) -> dict[str, vol.Schema]: """List trigger capabilities.""" return { "extra_fields": vol.Schema( {vol.Optional(CONF_FOR): cv.positive_time_period_dict} ) }
bdc59bd309228f5e3df8ad7994ee8ab5c675dd60
48,077
def check_key_expired(key, node, url): """check if key expired if is return url with args so it will push status message else return url :param str key: the private link key passed in :param Node node: the node object wants to access :param str url: the url redirect to :retur...
6d7a64df855dc2dc235dca2fdce14162d71673f3
48,078
from datetime import datetime def set_entity_props(entity, args): """ 设置实体对象属性 """ for column in entity.__table__.columns: value = args[column.name] if value is None: continue if type(column.type) == db.DateTime: if value is None: value = 0 ...
62be944db6541cd3df90b45e9f1008fa535e8f0b
48,079
from typing import Type from typing import Any def adsSyncReadByNameEx( port: int, address: AmsAddr, data_name: str, data_type: Type, return_ctypes: bool = False, handle: int = None, check_length: bool = True, ) -> Any: """Read data synchronous from an ADS-device from data name. :...
92242e2102c7d8525473b723ed3b18a77d0976e6
48,080
from covid.impl.util import compute_state def regularize_occults(events, occults, init_state, stoichiometry): """Regularizes an occult matrix such that counting processes are valid :param events: a [M, T, X] events tensor :param occults: a [M, T, X] occults tensor :param init_state: a [M, S] init...
087e94d4e41b213094929f265052a01ceb29f314
48,081
from typing import Tuple from typing import Dict from typing import List def calc_hist_by_group( df: dd.DataFrame, bins: int, ngroups: int, largest: bool ) -> Tuple[pd.DataFrame, Dict[str, int]]: """ Compute a histogram over the values corresponding to the groups in another column Parameters ----...
54490fd414bd5d14e8753236fb87cc29430683bf
48,082
def _get_filename(step: base_layer.JTensorOrPartitionSpec) -> str: """Returns a filename for the given step.""" step_num = _get_step(step) return f'decoder_out_{step_num}_shard_{jax.process_index()}'
7273126af9e62138502a17b7e4cdf87e3579acb0
48,083
def add_ticket_submit(request): """ Ajax submit ticket form. """ ticketform = AddTicketForm(request, request.POST) dc_settings = request.dc.settings if ticketform.is_valid(): # Send mail to SUPPORT_EMAIL sendmail(None, 'gui/support/add_ticket_subject.txt', 'gui/support/add_ticke...
abe83eb1783636759278b1468f72e2927c4247c3
48,084
def order_genes(genes, species, genomes): """Returns a list of ordered genes for the specified species, on a given strand of a given chromosome. :param genes: list of genes for species (on a given strand of a given chromosome) :param species: KEGG organism code :param genomes: dict of dicts...
a637a14a03d876dc2bf25f01d0ca30a983906f26
48,085
import re def perform_search(query): """ The perform_serach function takes the query entered by a user and presents the list of documents that best match the search words entered sorted by their rank results Args: query (str): A string containing the query terms entered by the user ...
2e26177aec3c2d3e0cd38d60e056bb42231ca456
48,086
def xent(pred, label): """ Calculates Cross Entropy Loss Args: pred: Tensor of label predictions label: Tensor of golden labels (True values) returns: Mean Squared Error of predictions and labels """ # Note - with tf version <=0.12, this loss has incorrect 2nd deriva...
ca485fda60329afcbc8fcb0555cb9b0ae310b166
48,089
def scale_image(img: np.ndarray)->np.ndarray: """ Return a copy of the array where all non-zero values have been scaled between 0 and 1 :param img: img to be scaled """ mn = np.min(img) mx = np.max(img) return ((img-mn)/(-mn+mx))*(img != 0)
d20925baebdbc452eadf7f2dbc12afee31621919
48,090
from typing import Tuple from typing import Pattern def format_m_year_execute(input_string:str, match_pattern:Tuple[Pattern, str]) -> str: """ Core of loop for format_m_year_strings """ return_string = str(input_string) # type:str search_pattern, month_number = match_pattern # type: Pattern, str ...
7e1e5d1e897e741d6d63a87fe91b8b37cc9a84bc
48,092
from datetime import datetime import json def create_accurat_request(article, request_id, text, src, tgt): """This method creates a translation request for MT-Serverland.""" shortname = "accurat_%s_%s" % (request_id, datetime.datetime.now().isoformat()) # submit a n...
bf939239a06ab94042f625350223fd477153f22b
48,093
from typing import Dict import yaml def load_yaml_into_dict(file_path: str) -> Dict: """ This loads yaml files into a dictionary to be used in API calls. """ with open(file_path, "r") as yaml_file: loaded = yaml.safe_load(yaml_file) if isinstance(loaded, dict): return loade...
891439af7cdd0e83f360b7398c98890419e8232f
48,094
def get_by(session, model, primary_key_value, primary_key=None): """Returns the first instance of `model` whose primary key has the value `primary_key_value`, or ``None`` if no such instance exists. If `primary_key` is specified, the column specified by that string is used as the primary key column. Ot...
53b30555930e987fff4777f068bd411dfc3ef4a0
48,095
def group(name: t.Optional[str] = None, **attrs: t.Any) -> t.Callable[[F], TaskioGroup]: """Creates a new :class:`Group` with a function as callback. This works otherwise the same as :func:`command` just that the `cls` parameter is set to :class:`Group`. """ attrs.setdefault("cls", Taskio...
dcc0c948d59e617123c31f0cc9f77c3292b436db
48,096
def compute_adiabatic_tf(ds, base_var): """Compute adiabatic tendencies as in Pierre's TF version Args: ds: xarray dataset base_var: Base variable to be computed Returns: adiabatic: xarray dataarray """ adiab = (ds[base_var].diff(dim='time', n=1) / dt_sec - ds[phy_dict[base...
7c21c2faaf35ad80f89b855442fdbb97fa5e6fca
48,097
from typing import Union def _get_reception_time_from_scene_dir_second(scene_dir_second: str) -> Union[str, None]: """If there is time datum inside `scene_dir_second` string, then return it. Otherwise, return None.""" # second part of scene dir, it can be: `13_53_00`, # `13_53_00_ETC2`, `14_35_23_CB1...
89cf95ed1f110c6641de4eae6ac8230d78a7b802
48,098
import json import requests def get_arc_servicedict(url): """Returns a dict of service information for an ArcGIS REST service URL Arguments url (String): An ArcGIS REST service URL, e.g. 'http://services.slip.wa.gov.au/arcgis/rest/services/QC/MRWA_Public_Services/MapServer' """ ...
80a1775d809c63ea34729c02ddcf98b8488fd825
48,099
from typing import Annotated def fast_fitting_predicate( page_width, # Ignored. ribbon_frac, # Ignored. min_nesting_level, # Ignored. max_width, triplestack ): """ One element lookahead. Fast, but not the prettiest. """ chars_left = max_width while chars_left >= 0: ...
5ebb7847f7841236c9fc991e592f9504074f981a
48,100
def fallout_rate(y_true, y_pred, sample_weight=None): """ The fallout rate is also known as the False Positive Rate. At the present time, this routine only supports binary classifiers with labels taken from {0, 1}. By definition, this is the complement of the Specificity, and so uses :any:`speci...
aacf7c56f371e80b8196ac3ff1246c2d9338423d
48,101
from typing import Callable import operator def get_side_operator(side, invert=False) -> Callable: """ generic operator selection when comparing odds - if side is 'BACK', returns gt (greater than) - if side is 'LAY', returns lt (less than) - set invert=True to return the other operator """ ...
61c105b585cb3fa127eff51ce4651168c292a1e8
48,102
import random def search_dag(G,edge_a,edge_b): """Operador de reparo: Verfica se o grafo possui ciclo, se tiver um ciclo ele retira uma aresta do circulo que não seja a ultima que foi adicionada. Entrada: G=Grafo edge_a e edge_b= nós da ultima aresta adicionada, sendo a->b. Saída: Gráfo...
013ca6eed206ba6f26610e7516129d239c4940ef
48,103
import gzip def read_ids(filename): """ Read record IDs from a file. Parameters ---------- filename : str Filename containing record IDs. """ if filename.endswith('.gz'): f = gzip.open(filename) else: f = open(filename) ids = [line.strip() for line in f] ...
588fd86a3fd8b504cf5419924032b25c81e52004
48,105
import json def dumps(obj): """ Serialize ``obj`` to a JSON formatted ``str``. 序列化对象 """ return json.dumps(obj)
8fa77ad5615531eea0e2190abf9eaf27196a2337
48,106
def from_grid_range(x): """from [-1,1] to [0,1]""" return (x + 1) / 2.0
a36e3ccace6fe385eeef1f4b5bf64c00f7b971ba
48,107
def ddpg( # Common settings device="cuda", discount_factor=0.98, last_frame=2e6, # Adam optimizer settings lr_q=1e-3, lr_pi=1e-3, # Training settings minibatch_size=100, update_frequency=1, polyak_rate=0.005, # Replay Buffer...
c80c0b6802fb548721598eb36d6c24e16cbbb022
48,108
import re def escaped_split(inp_str, split_char): """ Split inp_str on character split_char but ignore if escaped. Since, return value is used to write back to the intermediate data file, any escape characters in the input are retained in the output. :param inp_str: String to split :param...
13eaf77ffff52fdd6cfaa83ee08fc773f241be17
48,109
import torch def dataloader_msrvtt_train(args, tokenizer): """return dataloader for training msrvtt-9k Args: args: hyper-parameters tokenizer: tokenizer Returns: dataloader: dataloader len(msrvtt_train_set): length train_sampler: sampler for distributed training ...
4519b8b00c751982c1c7b7de79bdb78b32419cea
48,110
def read_num_axm(input_string): """ """ pattern = ('NumAXM' + one_or_more(SPACE) + capturing(one_or_more(INTEGER)) + one_or_more(SPACE) + capturing(one_or_more(INTEGER)) + one_or_more(SPACE) + capturing(one_or_more(INTEGER))) block = _get_system_info_section...
161ccd1dbd4f95d01f2571669ffb52f343b574a8
48,111
def ids_filter(doc_ids): """Create a filter for documents with the given ids. Parameters ---------- doc_ids : |list| of |str| The document ids to match. Returns ------- dict A query for documents matching the given `doc_ids`. """ return {'filter': [ids_selector(doc...
1e8f7cc6e1d5afd13cca3c3f10a0c6847a2ac041
48,112
def dup_div(f, g, K): """Polynomial division with remainder in `K[x]`. """ if K.has_Field or not K.is_Exact: return dup_ff_div(f, g, K) else: return dup_rr_div(f, g, K)
e1b620ca567dc1cd7a7f5cc94d94873ccbd0bee5
48,113
import logging import json def main(req: func.HttpRequest) -> func.HttpResponse: """main function""" logging.info("Getting table data") datatype = req.route_params.get("datatype") if not datatype: logging.error("No datatype provided") return func.HttpResponse( body='{"sta...
aaeb840015b42b05b219f2d2a082e14a91eb4d04
48,116
from typing import Optional def parse_message_timestamp(date_str) -> Optional[dt.datetime]: """Parses the message timestamp string and converts to a python datetime object. If the string cannot be parsed then None is returned.""" timestamp: Optional[dt.datetime] = None try: timestamp = dt.da...
380f7042bbb76d6550f2aa2e2ad4d767e56e0f1b
48,117
def expectation_values_to_real(expectation_values: ExpectationValues) -> ExpectationValues: """Remove the imaginary parts of the expectation values Args: expectation_values (zquantum.core.measurement.ExpectationValues object) Returns: expectation_values (zquantum.core.measurement.Expectatio...
ee6b6761e61f4ad21ef0a5a7a6b847fb900a8f38
48,118
def dbpool(): """ Returns the unique database pool for this process. Most often there is only a single pool per-process, so we provide this function as a global starting point for getting connections. Use it like this: from antipool import dbpool ... conn = dbpool().connection() ...
bada157c08eeeab498b7ada625ee0a959d948ea4
48,119
import requests def view_group_email(group_name): """View for email form to members""" if request.method == "GET": # Get group information group = get_group_info(group_name, session) # Get User's Group Status unix_name = session["unix_name"] user_status = get_user_group...
7df3d98cfb06f25b489ab6b24f661e9a44883aba
48,120
import functools def vgg_net(inputs, num_classes=1000, spatial_squeeze=True, name='vgg_a', global_pool=True, pruning_method='baseline', init_method='baseline', data_format='channels_last', width=1., prune_last_...
2a5c52a5d0ac3ad048788021ab0327e6a1b1f1c3
48,121
import requests from bs4 import BeautifulSoup def get_articles(url): """Returns article links, images, and titles as a list of dictionaries""" page = requests.get(url) page_content = page.content soup = BeautifulSoup(page_content, features="html.parser") posts = soup.find_all("div", {"class": "t...
f01824204e49fff042c3f6e788cc58d64fb88067
48,122
def present_species(species): """Given a vector of species of atoms, compute the unique species present. Arguments: species (:class:`torch.Tensor`): 1D vector of shape ``(atoms,)`` Returns: :class:`torch.Tensor`: 1D vector storing present atom types sorted. """ present_species = sp...
e597cdcf75ef912c266fc92861779d550f664616
48,123
def linkcheck_status_filter(status_message): """ Due to a long status entry for a single kind of faulty link, this filter reduced the output when display in list view :param status_message: error description :type status_message: str :return: a concise message :rtype: str """ if not...
07bd5cff212dbf3c764c71dc22d46caca34df4d6
48,124
def complex_pad_simple(xfft, fft_size): """ >>> # Typical use case. >>> xfft = tensor([[[1.0, 2.0], [3.0, 4.0], [4.0, 5.0]]]) >>> expected_xfft_pad = tensor([[[1.0, 2.0], [3.0, 4.0], [4.0, 5.0], ... [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]]]) >>> half_fft_size = xfft.shape[-2] + 3 >>> fft_size = (...
30da547fe53fb4ab4926373885479ffca20986f9
48,125
def extract_result(log): """Extracts the name of each test condition run""" module_name = log['testInfo']["testName"] str="" for d in log['results']: src = d['src'] if src == 'WebRunner' or src == 'BROWSER' or src == module_name: # these are asyncronous and the order isn't pr...
4f4b5311c0dc27b7b178488bee81abeabf4e434d
48,126
def prepare_y_train(add_noise_trajectory: Traj) -> np.ndarray: """ Prepare y values for training, which are (cy, cx) of data points in noise-added trajectory. :param add_noise_trajectory: the trajectory with noise added :return: x values for training, of size n x 1 """ return prepare_y_values(a...
389a097e19560081890ad2a3966bf0ca53868361
48,127
def extract_barrier_polygons(gdb_path, target_crs): """Extract NHDArea records that are barrier types. Parameters ---------- gdb_path : str path to the NHD HUC4 Geodatabase target_crs: GeoPandas CRS object target CRS to project NHD to for analysis, like length calculations. ...
6c14d1db4c4d3a64c3d106f42e048db799ed3f8f
48,128
def p2pv(p): """ Extend a p-vector to a pv-vector by appending a zero velocity. :param p: p-vector to extend. :type p: array-like of shape (1,3) :returns: pv-vector as a numpy.matrix of shape 2x3. .. seealso:: |MANUAL| page 142 """ pv = _np.asmatrix(_np.zeros(shape=(2,3), dtype=float, ord...
d752f3598f49870977de432889fc51bea2078b76
48,129
def create_experiment( database_session: Session, experiment: schema_experiment.ExperimentBase ): """Add Experiment to DB""" db_experiment = models.Experiment(**experiment.dict()) database_session.add(db_experiment) database_session.commit() database_session.refresh(db_experiment) return db_...
fee8bf74397804c2c6a73e630584fefb26f4db1a
48,130
def apply_filter(signal, window): """Apply filter window to a signal. for now datatype should be using numpy types such as 'np.int16' the entire file is read assuming datatype so header length should be specified in words of the same bit length filter_frequency should be supplied in units of sampling rate fil...
db63db61a6d6561836676cb202feb6307df8739a
48,131
def compute_affinity_matrix(X): """Compute the affinity matrix from data. Note that the range of affinity is [0,1]. Args: X: numpy array of shape (n_samples, n_features) Returns: affinity: numpy array of shape (n_samples, n_samples) """ # Normalize the data. l2_norms = np....
daa6f0b823d8476cd9e3a757a0d0a1755c3c9f29
48,132
def trace_fn(current_state, kernel_results, summary_freq=10, callbacks=()): """ Can be passed to the HMC kernel to obtain a trace of intermediate kernel results and histograms of the network parameters in Tensorboard. """ # step = kernel_results.step # with tf.summary.record_if(tf.equal(step % s...
b129e3487304bc7dd6f36446841bfa28e5d4c699
48,134
def pyramid_settings(): """Return the default app settings.""" return {"sqlalchemy.url": TEST_DATABASE_URL}
2873301eef18a60d365b65f61229ca29b15d6144
48,135
def train(action_set, level_names): """Train.""" if is_single_machine(): local_job_device = '' shared_job_device = '' is_actor_fn = lambda i: True is_learner = True global_variable_device = '/gpu' server = tf.train.Server.create_local_server() server_target = FLAGS.master filters = ...
0a90f5258a1b9932b1b16b5d250c61fdbf8ab3bc
48,136
def get_uniqueid(scan, x_grid, y_grid): """Reads the student's ID from the form. """ uniqueid = [] for char_num in range(8): bubble_intensities = [read_bubble(scan, x_grid[UNIQUEID_X+char_num], y_grid[UNIQUEID_Y+y]) for y in range(36)]...
4f0ffa6d41178fc65c1e653a9764853b3d8f6ef9
48,137
def _init_redis(app): """Initializes Redis client from app config.""" app.config.setdefault('REDIS_HOST', 'localhost') app.config.setdefault('REDIS_PORT', 6379) app.config.setdefault('REDIS_DB', 0) app.config.setdefault('REDIS_PASSWORD', None) return redis.Redis(host=app.config['REDIS_HOST'], ...
6c947003d4e9b4845e550508f6f0c24c973c282e
48,138
def _add_cmdline_quotes(cmd_str: str) -> str: """Add extra quotes to command line string containing SQL variables. DB_PATH='C:\\temp\\crdm\\data\\BD:mdf' => DB_PATH="'C:\\temp\\crdm\\data\\BD:mdf'" Arguments --------- cmd_str Command line string containing SQL variables. Returns -...
87fc70f2450e3742481ab28b7dbcdb448c3641ed
48,139
def _log_unnormalized_prob_logits(logits, counts, total_count): """Log unnormalized probability from logits.""" logits = tf.convert_to_tensor(logits) return (-tf.math.multiply_no_nan(tf.math.softplus(-logits), counts) - tf.math.multiply_no_nan( tf.math.softplus(logits), total_count - count...
1c294d16dd905b267da0ff42dc8c234bc05692f1
48,140
def eom_spfs(nel,nmodes,nspfs,npbfs,spfstart,spfend,uopspfs,copspfs,copips, huelterms,hcelterms,spfovs,A,spfs,mfs=None,rhos=None,projs=None): """Evaluates the equation of motion for the mctdh single particle funcitons. """ # create output array spfsout = np.zeros(nel, dtype=np.ndarray) ...
4e4db33ea3e85e320ceaeb4d6cabac9306de1451
48,141
def state_view(decoy: Decoy) -> StateView: """Get a mocked out StateView.""" return decoy.mock(cls=StateView)
4d199bff45a8525044a0c41c7cd4879838e8a816
48,142
import json from datetime import datetime def _tweet_for_template(tweet, https=False): """Return the dict needed for tweets.html to render a tweet + replies.""" data = json.loads(tweet.raw_json) parsed_date = parsedate(data['created_at']) date = datetime(*parsed_date[0:6]) # Recursively fetch rep...
f87f75a66dfba5314c66aa8c96475898412353fd
48,143
from pathlib import Path def response_page(): """Fixture to response page.""" txt = read_file(str(Path(__file__).parent / "data/page.txt")) resp = Response() resp.status_code = 200 resp._content = str.encode(txt) return resp
85d31872fef77eb23afc98d2a0e1fe150ddcf6d7
48,145
def decode_text(payload, charset, default_charset): """ Try to decode text content by trying multiple charset until success. First try I{charset}, else try I{default_charset} finally try popular charsets in order : ascii, utf-8, utf-16, windows-1252, cp850 If all fail then use I{default_charset} and...
2bdb58d2b43d7a58c795d9a3c7dad3459d5f02bb
48,148
import pandas from re import T def pql_import_json(state: State, table_name: T.string, uri: T.string): """Imports a json file into a new table. Returns the newly created table. Parameters: table_name: The name of the table to create uri: A path or URI to the JSON file Note: ...
ce3e6fc95a4f3ef7f16a6692c87725521c058a16
48,149
from typing import Tuple def read_dataset(train_batch_size: int = 32, eval_batch_size: int = 128, train_mode: str = 'pretrain', strategy: tf.distribute.Strategy = None, topology=None, dataset: str = 'cifar10', train_split: str = 'train', eval_split: str = 'test', dat...
c5abf6e45a76ed0c74503675b0c5dd051991e7b5
48,150
def test_run_dry_multiple_packages(murlopen, tmpfile, capsys): """dry run should edit the requirements.txt file and print hashes and package name in the console """ def mocked_get(url, **options): if url == "https://pypi.org/pypi/hashin/json": return _Response( { ...
b19e6c8f80e8533fb530bacc0df387f01ced9d12
48,155
def get_scaled_cutout_wdhtdp_view(shp, p1, p2, new_dims): """ Like get_scaled_cutout_wdht, but returns the view/slice to extract from an image instead of the extraction itself. """ x1, y1, z1 = p1 x2, y2, z2 = p2 new_wd, new_ht, new_dp = new_dims x1, y1, x2, y2 = int(x1), int(y1), int(x...
f639a69a8e7c0e65ac968be03b62b7de8f43dc99
48,156
def get_tp(gold, guess): """ Args: gold (Iterable[T]): guess (Iterable[T]): Returns: Set[T] """ return get_correct(gold, guess)
b60a2ed086df6c29cbee0190b8d885c3ad467f13
48,158
import collections def insert(container, key_path, item): """ >>> insert({}, ['a', '1', '2', 'world'], 'hello') {'a': {'1': {'2': {'world': 'hello'}}}} """ if isinstance(container, collections.OrderedDict): gen = collections.OrderedDict update = lambda i, k, v: i.update({k: v}) ...
656c6a69f3f261d7598daca8bda37908ddf1527b
48,159
import torch def construct_edge_feature_gather(feature, knn_inds): """Construct edge feature for each point (or regarded as a node) using torch.gather Args: feature (torch.Tensor): point features, (batch_size, channels, num_nodes), knn_inds (torch.Tensor): indices of k-nearest neighbour, ...
b49d26e0e7cee13952ff85f8f1f8075658fc391a
48,161
def _prepare_data_fn(features, target='label', flatten=True, return_batch_as_tuple=True, seed=None): """ Resize image to expected dimensions, and opt. apply some random transformations. :param features: Data :param target Target/ground-truth data to be r...
da9a254f9960e680dab1b1a3134058e100af81e9
48,162
def _get_sentinel_event(): """Generate a sentinel event for terminating worker.""" return Event()
9839575558ecec19034d41346eb1cf63c22fdc8b
48,163
def _process_pip_requirements( default_pip_requirements, pip_requirements=None, extra_pip_requirements=None ): """ Processes `pip_requirements` and `extra_pip_requirements` passed to `mlflow.*.save_model` or `mlflow.*.log_model`, and returns a tuple of (conda_env, pip_requirements, pip_constraints). ...
0e040f9a19d6e35a21ce5081edecde4f1f2ade9b
48,164
def _parse_standings(d): """ Used to parse the standings of a competition. """ standings = [] for o in d.get("teams", []): info = CompetitionStanding(o) standings.append(info) return standings
061263cc8959b490a585c4babcf97b8fe20a84e1
48,165
from typing import Type from re import T from typing import Optional from typing import cast def bind_prop( prop_name: str, prop_type: Type[Variable], default: T, doc: Optional[str] = None, doc_add_type=True, objtype=False, ) -> property: """Define getters and setters for a named property ...
105b3649b2358d616d62f606eeb9cb6e8cfae4c0
48,166
def get_vpip_players(hand: Hand) -> Indications: """ Return an indication of the players that were VPIP for the hand. Voluntary Put In Pot (VPIP) means the player volunteered to put money into the pot pre-flop. """ return _get_players_making_actions(hand.preflop, (Bet, Raise, Call))
c609c1a125a4fae64c14cd2c4d07aa4fc2251428
48,167
def canonicalize_name(name: str) -> str: """ Normalize the name strings from certificates and emails so that they hopefully match. """ name = name.upper() for c in "-.,<> ": name = name.replace(c, "") return name
3cfee0a655c876c037bb915098e564376f9b8cf5
48,169
from unittest.mock import patch def test_game_play_diagonal() -> None: """RED should be able to fill the diagonal while YELLOW does nothing but help.""" moves = [0, 1, 1, 2, 2, 3, 2, 3, 3, 5, 3] def mock_input(s: str) -> int: return moves.pop(0) game = Game() with patch("connect_four.gam...
19cc21e358116b6a4552117356d1268a3ce07a00
48,170
import timeit def get_exec_time(total_execs=1, _repeat=1): """ basically here we calculate the average time it takes to run this function or block of code """ def inner_wrapper(_function, *args, **kwargs): computational_times = timeit.repeat( lambda: _function(*args, **kwargs), number=total_execs, ...
d0826d3fb047736c5d4a5baa4d440bb7d2af2373
48,171
def find_in_map(obj, *args): """ It accepts the dict object and nested keys and return the value of last key if present in nested key is present in object. Args: obj (dict): dict object Returns: Value of last nested key """ if not isinstance(obj, dict): # raise InvalidReque...
20cfc2181ebe987a97a291cfef61739e6eedbeb2
48,172
def parse_from_file_msg(fp): """ Parsing email from file Outlook msg. Args: fp (string): file path of raw Outlook email Returns: Instance of MailParser with raw email parsed """ return MailParser.from_file_msg(fp)
4de62263dfe523d63d238f78f2fc801ba51917ea
48,174
def simple_5reciprocal(x, a, b): """ reciprocal function to fit convergence data """ c = 0.5 if isinstance(x, list): y_l = [] for x_v in x: y_l.append(a + b / x_v ** c) y = np.array(y_l) else: y = a + b / x ** c return y
8c046fee748a03b7c17f2c62b0d5c713d5b95354
48,175
def get_user_group(user: User, user_group_id: int) -> UserGroup: """ Get a user group. :param user :param user_group_id: :return: """ user_group = UserGroup.query.filter_by(id=user_group_id).first() if user_group is None: raise NotFoundException(f'No user group with id {user_grou...
f27dbedb6ec6bf39be451e000709db37d566d0c4
48,176
import timeit def test_accuracy(backend, shape, ndim, axes, dtype, inplace, norm, use_lut, r2c=False, dct=False, gpu_name=None, stream=None, queue=None, return_array=False, init_array=None, verbose=False, colour_output=False, ref_long_double=True): """ Measure the :para...
57f51eec7646d6103e3b23492a0effe8c29fea53
48,177
def negate_value(func): """negate value decorator.""" def do_negation(name, value): print("decorate: we can change return values by negating value") return -value return do_negation
276981a7c668308c97ca9e54066163036cb55528
48,178
def readable_memory_size(bytes_): """Convert number of bytes into human readable form, eg '1.2 Kb'. """ return _readable_units(bytes_, memory_divs)
a9ecd31225cd57b218be9cdc26f57af6a78f8a84
48,180
import random import numpy def get_labels (num, ltype='twoclass'): """Return labels used for classification. @param num Number of labels @param ltype Type of labels, either twoclass or series. @return Tuple to contain the labels as numbers in a tuple and labels as objects digestable for Shogun. """ labels=[] ...
2e083f70c4ff936f180be7b176957f04ae86d894
48,181
def conv3x3(x,K): """3x3 convolution with padding""" return F.conv2d(x, K, stride=1, padding=1)
fcc4daee5b9b76714f561af0e2064c26c45afea9
48,183
def alert_factory(site, rule, data_point): """ Creating an alert object """ # Getting the last alert for rule point = rule.alert_point.last() alert_obj = None # If the last alert exists does not exist if point is None: alert_obj = create_alert_instance(site, rule, data_point) # i...
5ebc2fb30fc9616a9690be709022806affa95ab8
48,184
def _get_average_time(callable_name): """Returns the average_time in seconds for the passed-in callable name. :param str callable_name: The name of the callable. :returns: The average_time in seconds for the passed-in callable name. :rtype: float """ return _ProfilingStatCollection.get_stats_...
e17279ca1112f975320e8877fdc40943cc341cac
48,185
def rolling_integral(x0, periods, function=None): """ Integrate a function over a rolling window ending in the interval. :param x0: Variable or Parameter; the interval under consideration :param periods: the width of the rolling window :param function: a function from float to float to be integrate...
c7a01f9b986362cf1aab78d17c2ee9910ec3e6ba
48,186
def build_app_models_environment(): """ Build a full test model environment for vcftestmodels. Uses vcftestmodels.models.get_app_models_environment, which returns an empty base.tests.helpers.AppModelsEnvironment object. Model classes are created here but must by initialized via the object's `mi...
9a195e0665409150c5155d000e78c33920646818
48,187
import torch def create_random_direction(weights, args, ignore='biasbn', norm='filter', model=None): """ Setup a random (normalized) direction with the same dimension as the weights. Args: weights: the given trained model ignore: 'biasbn', ignore biases and BN parameters. ...
2f82feca5a81c57c9b9736502d0bc406e9ad2b3d
48,189
import functools def wait_key_pressed_logical(key_name, timeout: float = None) -> bool: """Wait for a key or mouse/joystick button logical state to be pressed.""" return _wait_for(timeout, functools.partial(is_key_pressed_logical, key_name)) or False
f0d13eeecef02864695247178d99eb30fa6c6e54
48,190
def calc_fc_from_fixed_Q_Brune(event_inv_params, Qs_curr_event, density, Vp, A_rad_point, surf_inc_angle_rad=0., verbosity_level=0): """Function to calculate fc by fitting Brune model to spectra with fixed Q.""" # Calculate f_c based on curve-fit of spectra with Brune model for fixed Q: # Setup some data ou...
68c0c02d10f5d7ba8ed2cc7af68a3a86f4c9183c
48,191
def compute_d(a, b): """Compute value d for golden section search.""" d = a + ((b - a) / 1.618) return d, f(d)
544b1c6bfc1244a4d0c5c62f340e165701579b21
48,194
def convert_2D_polar_line_to_conformal_line(rho, theta): """ Converts a 2D polar line to a conformal line """ line_val = val_convert_2D_polar_line_to_conformal_line(rho, theta) return layout.MultiVector(line_val)
170b16f522d2c97ea933e97405c3ef08746d5901
48,195
def B_m_def(tau, phi, **params): """ Implements Eq. 9.159 from Nawalka, Beliaeva, Soto (pg. 471) """ beta1 = beta1m(**params) beta2 = beta2m(beta1, **params) beta3 = beta3m(beta1, **params) beta4 = beta4m(phi, beta1, **params) exp_term = np.exp(beta1 * tau) denominator = beta2 * bet...
2adbca8682ddba7d12055e7dc59439fe4aa70f3e
48,196
def delete_crime_collection(): """ Helper function to delete crime collection in db. """ count = len(Crime.objects()) check_crime_duration() for crime in Crime.objects(): duration = check_filter(crime.incident_type_primary) if (crime.duration == None or crime.duration == 30) and ...
287830498f42f983fc4597694262e719ca62a9f7
48,199