content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def performance_metric(y_true, y_predict): """ Calculates and returns the coefficient of determination R2. R2 captures the percentage of squared correlation between the predicted and actual values of the targets. Parameters: y_true - Array, the actual target values y_predict - Array, the...
e5bc397e25e5e3c0a97742dbc85250bed092c74a
58,000
def formatstr(text): """Extract all letters from a string and make them uppercase""" return "".join([t.upper() for t in text if t.isalpha()])
749aeec962e3e39760c028bfb3e3a27ad8c10188
58,001
from datetime import datetime import json def update_local_db_based_on_record(eox_record, create_missing=False): """ update a database entry based on an EoX record provided by the Cisco EoX API :param eox_record: JSON data from the Cisco EoX API :param create_missing: set to True, if the product shou...
0790c82966ca8ad2444fdffeecda2db131c24db4
58,002
def move_in(library, session, space, offset, length, width, extended=False): """Moves a block of data to local memory from the specified address space and offset. Corresponds to viMoveIn* functions of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical ...
4e5b6b7231a786659d54482a70ca091e9f44b3f3
58,003
import os from datetime import datetime def evaluate(args, mode, appcfg): """prepare the report configuration like paths, report names etc. and calls the report generation function """ log.debug("evaluate---------------------------->") subset = args.eval_on iou_threshold = args.iou log.debug("subset: {}"...
80e4db931a9675e121466732f296b024b5bee35a
58,004
def reflexive_missing_elements(relation, set): """Returns missing elements to a reflexive relation""" missingElements = [] for element in set: if [element, element] not in relation: missingElements.append((element,element)) return missingElements
c31ce237c9156f17cc87a12ac80e595f81b08889
58,005
def cosine_groups(structure='fine'): """ Returns cosine group bounds in increasing order. Parameters ---------- structure : str Named structure. Options currently include fine. """ if structure == 'fine': """ A fine cosine group structure I created """ cb = np....
2a9497597650f96c11b9cf658e3d61f5422d7454
58,006
def form2_list_comprehension(items): """ Remove duplicates using list comprehension. :return: list with unique items. """ return [i for n, i in enumerate(items) if i not in items[n + 1:]]
02d095c86de1b7d52d53cdb4bfe77db08523ea3a
58,007
from verticapy.plot import range_curve from tqdm.auto import tqdm from typing import Union def learning_curve( estimator, input_relation: Union[str, vDataFrame], X: list, y: str, sizes: list = [0.1, 0.33, 0.55, 0.78, 1.0], method="efficiency", metric: str = "auto", cv: int = 3, pos...
1f1bbf7c307a134ef512cd0cb0d597bbe3ce2199
58,008
import os import glob def _DetectVisualStudioVersions(versions_to_check, force_express): """Collect the list of installed visual studio versions. Returns: A list of visual studio versions installed in descending order of usage preference. Base this on the registry and a quick check if devenv.exe exis...
b69e7d32035f5a589275f317d0930b9cc1fb2974
58,009
def route_image_next(): """ Shows the next image. """ result = image_viewer.next() return jsonify({'next' : result})
81f8ce34287a80dfc6e505a296fbdd4f3f70ee7a
58,010
from prophet import Prophet from typing import Union import logging def _prophet_fit_and_predict( # pylint: disable=too-many-arguments df: DataFrame, confidence_interval: float, yearly_seasonality: Union[bool, str, int], weekly_seasonality: Union[bool, str, int], daily_seasonality: Union[bool, st...
cf2d0e640fe4be67a913a82b94d1177477b3122a
58,011
def _beta_cont_frac(x, a, b, tol=1e-6, max_iter=200): """ Calculates continued fraction of the incomplete beta function. NOTE: Inspired by: https://malishoaib.wordpress.com/2014/04/15/the-beautiful-beta-functions-in-raw-python/ Parameters ---------- x : array_like, shape (n,) Varia...
f7cf6dfc7b4f2e235b6f8557f63902a66f7cbec4
58,012
def calcMass(volume, density): """ Calculates the mass of a given volume from its density Args: volume (float): in m^3 density (float): in kg/m^3 Returns: :class:`float` mass in kg """ mass = volume * density return mass
38f0ef780704c634e572c092eab5b92347edccd3
58,013
def update_Lambda(Lambda, L, Lx, X, G, Sigma, track_fval=False): """ Update function for dual variables Lambda. ! Needs to be checked. """ n = len(Lx) temp = [L-G[i] for i in range(n)] Lambda[0], val_lam_change = up_Lam(Lambda[0], temp) temp = [L-Lx[i] for i in range(n)] Lambda[1], tem...
44cffb5d198ca54618979f6f7e9ff4cf7b4e2759
58,014
def train_NB1(train_matrix, train_category): """ train_NB0函数的改进 :param train_matrix: 训练文档矩阵(准确来说只是python原生二维数组) :param train_category: 训练文档矩阵对应的分类(一维向量) :return: (在非侮辱性文档类别下词汇表中单词的出现概率向量, 在侮辱性文档类别下词汇表中单词的出现概率向量, 任意文档属于侮辱性文档的概率) """ # 训练文档的数目 num_train_docs = len(train_matrix) num...
a936a91b21239bfc0a2150519764b5f169f19c2b
58,015
def index(): """renders the html form and listens for user trying to delete an object.""" json_handler.get_user_input() # deleting alarm/notification if "alarm_item" in str(request.url) or "notif" in str(request.url): delete_an_object() return fill_out_the_form()
dc2c84b76555462d05452b77d235f305e2f4a91c
58,016
from io import StringIO def make_summary_tables( res ): """ takes a summary from statsmodel fitting results and turn it into 2 dataFrame. - result_general_df : contains general info and fit quality metrics - result_fit_df : coefficient values and confidence intervals """ # transfo...
cbb18ae56c2bf8cbe48486a4f047287a9b0c0681
58,017
def novelty_vector(convo): """ Returns the novelty vector measured from the convo text. Parameters ---------- convo : Conversation Returns ------- np.array """ freq = type_frequency_distribution(convo) if len(freq) == 0: return [] return novelty(freq)
67558a6129ce5e4c882ad1dc26af7baa6b1ad45c
58,018
def rescale(arr, vmin, vmax): """ Rescale uniform values Rescale the sampled values between 0 and 1 towards the real boundaries of the parameter. Parameters ----------- arr : array array of the sampled values vmin : float minimal value to rescale to vmax : float ...
d6debc0eeccd9fe19ed72d869d0de270559c9ce8
58,019
def get_write_in_model(): """ Retrieves the model class (specified in ``settings.NOTORHOT_SETTINGS['WRITE_IN_MODEL']``) to be used to store write-in submissions. See :func:`get_write_in_model_name` for details :returns: write-in storage model class (**not** an instance) :rtype: :class:`d...
9dbeaa0c892ec46864acd98a3a4da4c5d91913c1
58,020
def get_extreme(extreme, range_minimum, range_maximum): """ extreme : should be min or max range_minimum::int : minimum value you want your extreme to be range_maximum::int : maximum value you want your extreme to be """ if isinstance(extreme, str): if extreme == "": e...
d44d15310c83b1e2fcf03939cd1e7625f68f0b11
58,021
import os import getpass def synapse_login(): """ This function logs into synapse for you if credentials are saved. If not saved, then user is prompted username and password. :returns: Synapseclient object """ try: syn = synapseclient.login(silent=True) except Exception as e...
16b32f562898e7d54dff7f6eafdbc834b3171b81
58,022
import torch def predict(image_path, model, limit=5, gpu=False): """ Predict the class (or classes) of an image using a trained deep learning model. :param image_path: string :param model: model :param limit: int Top K results that should be returned :param gpu: bool :returns: np.array, li...
e1da70ce9868139270dbf7772bbda0df0b402330
58,023
import tqdm def morph_stc(stcs, subject_ids, subject_dir): """Morph stc inplace onto generic brain""" morphed_stcs = [] for i, (stc, subject_id) in tqdm(enumerate(zip(stcs, subject_ids)), total=len(stcs)): try: morph = mne.compute_source_morph(stc, ...
b26b0b73ebd214b6896bba132c8b43baae350230
58,024
def py2_strencode(s): """Encode a unicode string to a byte string by using the default fs encoding + "replace" error handler. """ if PY3: return s else: if isinstance(s, str): return s else: return s.encode(ENCODING, ENCODING_ERRS)
9aa76af9e96e69cb1cd7765ad22cb9ccd5a46d79
58,025
import shutil def rename(path: str, target: str): """Copy path to target.""" return shutil.move(path, target)
00f46f2557f4e0e7bd07610889a8c2deb028f24a
58,026
def compute_moments(log_both, logit_rho, log_scale, phi, pi, theta, psi): """Compute the means and variances implied by the paramters.""" rho = special.expit(logit_rho) vol_mean = np.exp(log_both) / (1 - rho) vol_var = ((2 * np.exp(log_scale) * rho * vol_mean + np.exp(log_scale)**2 * np...
0eea3c59c6d6d4be21ac0860c987760f40cd98af
58,027
def render_latex(root_node, width=0, **options): """Render a node tree as a LaTeX document. """ options = make_options(**options) return _cmark.render_latex(root_node, options, width)
a4f18f9474cd0d0aa56f51d3525c51d26c7fc9be
58,028
import socket def check_port_occupied(port, address="127.0.0.1"): """ Check if a port is occupied by attempting to bind the socket :return: socket.error if the port is in use, otherwise False """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((address, port)) ex...
5919e228c835ceb96e62507b9891c6a1ce5948fa
58,029
import timeit def heap_remove(N, num): """Run a single trial of num heap remove requests. Make sure that num < N.""" return 1000*min(timeit.repeat(stmt=''' for _ in range({}): heapq.heappop(h)'''.format(num), setup = ''' import heapq h = [] for i in range(0,2*{},2): heapq.heappush(h, i)'''.for...
19101cd920904a2384aaec62b23dc169bdfe6dae
58,030
def commit(msg=None): """ Commit your changes to git :msg: @todo :returns: @todo """ print '---Commiting---' print msg = msg or prompt('Commit message: ') commit = False commit = prompt('Confirm commit? [y/n]') == 'y' if commit: with settings(warn_only=True)...
c0d111c2354f8db5348c1750eb4c8456b689741f
58,031
def inverseExtend(boundMethod, *args, **kargs): """Iterate downward through a hierarchy calling a method at each step. boundMethod -- This is the bound method of the object you're interested in. args, kargs -- The arguments and keyword arguments to pass to the top-level method. You can call t...
a511470f6cd3d86de19cc95e489498e649bea7a5
58,032
import gettext def p_sign_up( username, password, password2, code, email=None, mobile_phone_number=None): """ 普通用户注册函数 :return: """ data = {} if current_user.is_authenticated: data['msg'] = gettext("Is logged in") data["msg_type"]...
5b8ccd13ebb483c9198e7576816d89b4d6898b1a
58,033
def is_intent_completed( s_i: int, option_id: option_utils.Options, s_f: int, intent_id: Intents, ) -> IntentStatus: """Determines if a (state, option, state) transition completes an intent. Args: s_i: (Unused) The integer representing the taxi state. option_id: (Unused) The integer rep...
96ab19f7527b8cadfdbaf148c2871a80d984c418
58,034
def inv_monitor_nonlinearity(x, x_gamma_function): """Monitor colour displaying is not linear but follows x^gamma function. Convert monitor scale back to linear image float values. parameters: - x: image as numpy.ndarray (floats in [0,1])""" # clip values that are too small or too large x[...
4969a49da207abaa0e17847f9bc5381608416a03
58,035
def jpg_image_to_array(image_path): """ Loads JPEG image into 3D Numpy array of shape (width, height, channels) """ with Image.open(image_path) as image: im_arr = np.fromstring(image.tobytes(), dtype=np.uint8) im_arr = im_arr.reshape((image.size[1], image.size[0], 1)) return im_...
8c188c2199dd1a074d1c1eb9ac032280ab6cd713
58,036
def dict2func(d): """Converts all strings in a dictionary to their corresponding functions (if applicable)""" res = dict() for k, v in d.items(): if isinstance(v, dict): res[k] = dict2func(v) else: res[k] = str2func(v) return res
ddb74e6d6e877a85d6881354e0064596efd2f27d
58,037
def _midpoints_1d(arr, frac=0.5, axis=-1): """Return the midpoints between values in the given array. If the given array is N-dimensional, midpoints are calculated from the last dimension. Arguments --------- arr : ndarray of scalars, Input array. frac : float, Fraction of the ...
b95d376a98dbfa5fc98a5892686f39df557cc65b
58,038
def _run_once_sucessfully(f): """ Decorator that uses a cache to flag an action as already executed, and check to ensure that it hasn't been executed before running (in the event of retries, multiple failures). :param f: a function/method to run only once. """ def inner(self, *args, **kwarg...
bf1cc23ca7dd7f8aac994acdc15778dd520d02cc
58,039
def get_source_tag (aligned_dict, src_word_tag_dict): """Get the aligned (source) tag for each word in each sentence of target language from a source language""" tar_tag_dict = {} # create a dict to store predicted tag for tar language print("get source tag") for sentence_cnt in aligned_dict.keys(): ...
ccd4fe0a2a0d1a13c553c7392f7876979729de1c
58,040
import torch import math def cal_GauProb(mu, sigma, x): """ Arguments: mu (BxMxC) - The means of the Gaussians. sigma (BxMxC) - The standard deviation of the Gaussians. x (BxC) - A batch of data points (coordinates of position). Return: probabilities (BxM): proba...
6625878d6dd199b106bbb48336fc52f52e8c1f4f
58,041
from typing import Dict def determine_postAST_from_filename(filenamesplit) -> Dict: """determine postAST from filenamesplit""" basepf_split, postAST = filenamesplit, "" if all([i in basepf_split for i in ("post", "AST")]): if any(s in basepf_split for s in ["LC"]): if "postAST_LC" in ...
3787dcef3ae65538f2fe66f98be60cc0f71f7790
58,042
def getPrivacyList(disp, listname): """ Requests specific privacy list listname. Returns list of XML nodes (rules) taken from the server responce. """ try: resp = disp.SendAndWaitForResponse(Iq("get", NS_PRIVACY, payload=[Node("list", {"name": listname})])) if isResultNode(resp): return resp.getQueryPayload...
3c8dc760df11907793b768459b16f62499c0709a
58,043
def modified_fisher_transform(r: float, n: int) -> float: """Returns a Fisher's z modified by dividing it by the standard error.""" z = atanh(r) inverse_standard_error = sqrt(n - 3) return z * inverse_standard_error
8b4b652c87be85536459f9aa4a93f9e8f89880a5
58,044
import html def indicator(color, text, id_value): """ Builds a new Dash div styled as a container, with borders and background. :param str color: background color of the container (RGB or Hex colors). :param str text: name to be plotted inside the container. :param str id_value: identifier of the...
7cbb68cbe09b07eb8a549825f80129c3b6720fc6
58,045
def pack(fmt, *args): """ Return string containing values v1, v2, ... packed according to fmt. See struct.__doc__ for more on format strings. """ try: o = _cache[fmt] except KeyError: o = _compile(fmt) return o.pack(*args)
61d8bbfe5c210045bfc3fb2196b5a5291f47aa6a
58,046
def require_context(f): """Decorator to require *any* user or admin context. This does no authorization for user or project access matching, see :py:func:`authorize_project_context` and :py:func:`authorize_user_context`. The first argument to the wrapped function must be the context. """ ...
83fac830883968bf62b4e04ea3dad3ef4c619caf
58,047
def get_reg_info(*args): """get_reg_info(char regname, ulonglong mask) -> char""" return _idaapi.get_reg_info(*args)
77790803e8b21b1a6b063f9f496579b64757b5a3
58,048
def pretty(data, corner = '+', separator='|', joins='-'): """ Parameters : ~ data : Accepts a dataframe object. ~ corner : Accepts character to be shown on corner points (default value is "+"). ~ separator : Accepts character to be shown in place to the line separating two values (default value...
812fb5d255c5e44c1d026d307e2a39c7b3c31f14
58,049
import torch def double_observation(f: torch.Tensor) -> torch.Tensor: """Double observation vector as (A, B, C, D) --> (A, A, B, B, C, C, D, D) Args: f: Observation vectors (n_batch, ...) Returns: Observation vectors (2*n_batch, ...) """ return torch.repeat_interleave(f, 2, dim=0...
06f8e9acf3f62cd0d75a0a69451625fe4bdc8659
58,050
import csv def write_rows(rows, filename, sep="\t"): """Given a list of lists, write to a tab separated file""" with open(filename, "w", newline="") as csvfile: writer = csv.writer( csvfile, delimiter=sep, quotechar="|", quoting=csv.QUOTE_MINIMAL ) for row in rows: ...
41e04ee6203baf7db2d08722aed76dfacbc9e838
58,051
import collections def context(): """A mock for the lambda_handler context parameter.""" Context = collections.namedtuple('Context', 'function_name function_version') return Context('TestFunction', '1')
b7d65ca7ff87aea1bd22e87dba4cb2d0e5ec411d
58,052
def get_pa_type_factory(pa_type): """return type factory""" if pt.is_int8(pa_type): return pa.int8 elif pt.is_int16(pa_type): return pa.int16 elif pt.is_int32(pa_type): return pa.int32 elif pt.is_int64(pa_type): return pa.int64 elif pt.is_uint8(pa_type): ...
01063af85f556fdd2e67d1935c75b54532d25b84
58,053
def iscircular(linked_list): """ Determine wether the Linked List is circular or not Args: linked_list(obj): Linked List to be checked Returns: bool: Return True if the linked list is circular, return False otherwise """ if linked_list.head is None: return False ...
874073d433f1a3069ca250379b4855303f5a6510
58,054
def controller_encryption_exists(handle, controller_type, controller_slot, server_id=1): """ Checks if encryption is enabled on the controller Args: handle (ImcHandle) controller_type (str): Controller type 'SAS' contro...
02d17aebbf7508a94308f37c524bd056b96d531f
58,055
import torch def make_one_mask_target(cfg, mode, input, sampled_proposal, sampled_assign, truth_box, truth_mask): """ Deprecated. Was used for generating mask for MaskRcnn """ sampled_mask = [] mask_crop_size = cfg['mask_crop_size'] for i in range(len(sampled_proposal)): _, D, H, ...
0e9ddf14b5fe8c4d0b453b6c64b9859ae5e8dcc8
58,056
import tqdm def chamfer_hausdorff_dists_block_wise(X0, X1, sub_batch_size=10000): """ Compute one-sided Chamfer and Hausedorf distances and Chamfer and Hausedorf distances in the block-wise manner. """ def chamfer_hausdorff_oneside_dists(X0, X1): b0 = X0.shape[0] b1 = X1.shape[0] ...
ce047cf3e61965d5e5c9a08cf5fe64b5b3c7a2a5
58,057
def sample_with_replacement(population, k, n=None): """ Return a sample of size k with replacements chosen from the population. If n is set, an array of size n containing samples of size k is returned. :param population: :param k: size of the sample :param n: number of samples :return: n (o...
00a2f17276812c4e775e13d8e3391aece9c65047
58,058
def cartesian_regions_to_slices(regions): """ Convert a sample region(s) string, consisting of a comma-separated list of (colon-or-hyphen-separated) pixel ranges into Python slice objects. These ranges may describe either multiple 1D regions or a single higher- dimensional region (with one range pe...
b1ec8ec783f5ea380fd665888131733d0b4b1833
58,059
import typing def build_charge_table(charges: typing.List[Charge], page_number: int)\ -> FlexibleColumnWidthTable: """ This function builds a Table containing itemized billing information :param typing.List[Charge] charges: the rows on the invoice :param int page_number: Current page number...
79039651de64081662350b2cc27e0bbe77958c1d
58,060
def view_processing( request ): """ If shib headers ok, logs user in & redirects to admin view. """ log.debug( 'starting view_processing()' ) user = user_grabber.get_user( request.META ) if user: log.debug( 'logging in user' ) django_login(request, user ) url = reverse('admin:iip_pro...
a1af48233d3e993539f25b02e01ef632fa4eacac
58,061
def count_occurence_of_character_in_neighbour_squares(x, y, board, character): """ returns the number of neighbours of (x,y) that are bombs. Max is 8, min is 0. """ num_rows = len(board[0]) num_cols = len(board) squares = neighbour_squares(x, y, num_rows, num_cols) character_found ...
1d9e2ef22e1f61c51845417e9c036943e66283a5
58,062
from typing import Sequence from typing import List from typing import Set def remove_overlapping_lane_seq(lane_seqs: Sequence[Sequence[int]]) -> List[Sequence[int]]: """ Remove lane sequences which are overlapping to some extent Args: lane_seqs (list of list of integers): List of sequence of lan...
b9489dfd7c592c1a41a323627bb974b92f3257ab
58,063
import tqdm import torch def evaluate_encoder(model, tokenizer, eval_dataset, device="cpu", batch_size=16, output_predictions=True, output_topk=0, progress_bar=True): """ Evaluates any HuggingFace Encoder model. A model's prediction is determined by the probabilities assigned to the ...
a6bfb2e9be190a2003a42aa9052b052d8fdf9037
58,064
def _generate(n, pi, mu, random_state=None): """ Generate samples from an EMM. Parameters ---------- n : int Sample size. pi : array Mixing weight of the individual exponential distribution in the EMM. mu : array Mean of the individual exponential distribution in the...
e8a78b16d1b84669189a986fa51c1d2b71fca6c4
58,065
def _auth_handler(): """ Requrired JWT method """ return None
9ec5301d6e32c7b3016a92ba9ae89d22fed3bad5
58,066
def validate_experimental(context, param, value): """Load and validate an experimental data configuration.""" if value is None: return config = ExperimentConfiguration(value) config.validate() return config
a486f76a5c9006fbdd765c7c682bea237a445d90
58,067
def todatadict(data): """Reorganize tuple of dicts into single dict where keys are defined by ID and NAME, values are numerical data corresponding to RPKM values :param data: tuple of dicts from loaded cleaned data :returns: dict containing reorganized data """ full = nest(get(0), dict.keys, tu...
5b95ac1030cccf405a38bd8e00114c53598ca317
58,068
def HKL2string(hkl): """ convert hkl into string [-10.0,-0.0,5.0] -> '-10,0,5' """ res = "" for elem in hkl: ind = int(elem) strind = str(ind) if strind == "-0": # removing sign before 0 strind = "0" res += strind + "," return res[:-1]
325ddfcb2243ce9a30328c5b21626a4c93a219de
58,069
def evaluate_models(dataset, p_values, d_values, q_values, training_portion=0.66): """ Fucntion to tune hyperparameters of arima model Parameters ---------- dataset : array or list All dataset. p_values : in...
931129f351fcd749b2e9c80c61a4ec5632285e14
58,070
import plan2scene.texture_prop.graph_generators as graph_generators def get_graph_generator(conf: ConfigManager, graph_generator_def: Config, include_target: bool): """ Creates graph generator given the graph generator configuration. :param conf: Config manager. :param graph_generator_def: Graph gener...
4b60d7e00fd16a447a956db8e77c7847cde65966
58,071
import logging import sys def getLogger(nm): """Get a basic-configured trace-enabled logger.""" logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(levelname).1s: %(message)s') log = logging.getLogger(nm) return log
a6fc4f0fe6d2104c0e2487d6038401306ad3e3ba
58,072
import json def returnBook(): """returnBook sara' attivato dopo una richiesta HTTP asincrona (AJAX); l'utente informera' il db che il libro sia stato restituito mediante il metodo managedb.returnBookDB(). La risposta sara' in formato JSON """ # Flask salvera' un item logged_in se l'utente ...
7aa6959aa2ea468a096ff1062a6034e93705a14b
58,073
import base64 import six import requests import json from datetime import datetime def fetch_refreshed_token(refresh_token): """ Fetches a new access token using refresh token """ payload = {'grant_type': 'refresh_token', 'refresh_token': refresh_token} auth_headers = base64.b64encode(six.text_type(CLIENT...
c3a42504c345b630728cab253e6de2ee0e4d3937
58,074
import re def splitAtUppercase(a_string): """assumes a_string is a string returns a list of strings, a_string split at each uppercase letter""" pattern = "([A-Z])" string_list = re.split(pattern, a_string) return string_list
5cbf4673ee46db81b8acfb30bfe64a44d10d0d9a
58,075
def send_sms(destination, message): """ Sends an sms message using AWS SNS. Args: destination (str): Required. The sms number to send to. message (str): Required. The message to be sent. Returns: The AWS response. """ client = boto3.client('sns', region_name='eu-west-1...
50bbfa763c11e57de378a819a107c3b7a4720706
58,076
from typing import List def should_expand_range(numbers: List[int], street_is_even_odd: bool) -> bool: """Decides if an x-y range should be expanded.""" if len(numbers) != 2: return False if numbers[1] < numbers[0]: # E.g. 42-1, -1 is just a suffix to be ignored. numbers[1] = 0 ...
fcd5a8e027120ef5cc52d23f67de4ab149b19a2c
58,077
def get_all_bababooeys() -> list: """ Returns all permutations of "bababooey" with acceptable character substitutions. :return: list of all bababooeys """ substitutions = { 'b': '🅱️', 'o': '0', 'e': '3', } char_possibilities = [] for c in 'bababooey': su...
a6275d64cf3c498a5472d594941615575b86b25f
58,078
def from_inches(unit, val): """Convert val in inches to unit.""" return _FROM_INCHES[unit](val)
1ac86745f83e333fc6eff27c2fcc980521ad1727
58,079
def zyx_to_yxz_dimension_only(data, z=0, y=0, x=0): """ Creates a tuple containing the shape of a conversion if it were to happen. :param data: :param z: :param y: :param x: :return: """ z = data[0] if z == 0 else z y = data[1] if y == 0 else y x = data[2] if x == 0 else x ...
2477976f795f5650e45214c24aaf73e40d9fa4eb
58,080
def _get_params(deep: bool) -> str: """ Get parameters for this estimator. :param deep: If True, will return the parameters for this estimator and contained subobjects that are estimators. :type deep: bool :param return: Parameter names mapped to their values. :type return...
f8904a8db8f791b97f485a5cd98285aee9eed6b9
58,081
def mse_l1_sparsity(x, x_hat, concepts, sparsity_reg): """Sum of Mean Squared Error and L1 norm weighted by sparsity regularization parameter Parameters ---------- x : torch.tensor Input data to the encoder. x_hat : torch.tensor Reconstructed input by the decoder. concepts : tor...
cabb269caf826348909ccf42f3d26582ae02777b
58,082
def CalculateChi10p(mol): """ ################################################################# Calculation of molecular connectivity chi index for path order 10 ---->Chi10 Usage: result=CalculateChi10p(mol) Input: mol is a molecule object. ...
340227613b9e561802c0fbc40bfe8e4c6d49af31
58,083
def binary_log_loss(Y, P): """ Compute negative log loss """ N = len(Y) # Clip values very close to 1 or 0 P = np.clip(P, EPS, 1 - EPS) # Negative log likelihood function mask0 = (Y == 0) # label = 0 observations mask1 = (Y == 1) # label = 1 observations nll = -(np.log(P[mask1]...
1f2a5d6b714d32851e8388e1162f9c37e9169ac4
58,084
def run_policy( policy_and_value_net_apply, observations, lengths, params, state, rng, vocab_size, observation_space, action_space, rewards_to_actions, ): """Runs the policy network.""" policy_input = _prepare_policy_input( observations, vocab_size, observation_space, a...
be76524d40758f0083657e62b7a9230b81cddd41
58,085
def make_vagrant_unit_factory(branch): """ This returns the factory that runs the Vagrant unit tests. """ f = BuildFactory() f.addStep(Git(repourl="git://github.com/mitchellh/vagrant.git", branch=branch, mode="full", method="fresh", ...
74b058410fcecafeabee3589d96730849a522a79
58,086
def _find_non_suppressed_predicates(predicates, validity_intervals): """Returns the predicates that are left after suppression operations. :param predicates: A sequence of predicates in the form of TimedPropertyGraph objects. :param validity_intervals: The intervals during which corresponding predicates ho...
69aa7b419624e911ca9dc05bc071989f78ee6cfb
58,087
def handle_market_cap(request): """ Generate response to intent type MarketCapIntent with the current market cap of the ticker. :type request AlexaRequest :return: JSON response including market cap of the ticker """ ticker = request.get_slot_value(slot_name="stockTicker").upper() # Query D...
a46d9aee35581abd8766fd59c7cc207ac0376687
58,088
from datetime import datetime import math def prepare_fetch_hourlies_query(raw_station: dict, start_timestamp: datetime, end_timestamp: datetime): """ Prepare url and params to fetch hourly readings from the WFWX Fireweather API. """ base_url = config.get('WFWX_BASE_URL') logger.debug('requesting his...
7430fd07cdeb1dd760272d904fffe72d4b7910a8
58,089
import six import json def _safe_match_string(value): """Sanitize and represent a string argument in MATCH.""" if not isinstance(value, six.string_types): if isinstance(value, bytes): # should only happen in py3 value = value.decode('utf-8') else: raise GraphQLInvalidA...
7e6c06af244379b274fcf71ce97d1291808ace84
58,090
def first_supported_filter(test, runner): """Get the first filter supported by the server Arguments: test (Node): reference to Node object runner (Runner): reference to Runner object Returns: (dict): single (first) request filter """ return single_supported_filter(test...
a5b00124ad48f429ba9ef435661fcb2f63ad9d52
58,091
import functools def remotable_classmethod(fn): """Decorator for remotable classmethods.""" @functools.wraps(fn) def wrapper(cls, context, *args, **kwargs): if NovaObject.indirection_api: result = NovaObject.indirection_api.object_class_action( context, cls.obj_name(), ...
5f5e25b294df7e755c8ed6b921150552474be7dd
58,092
def gen_anonymous_varname(column_number: int) -> str: """Generate a Stata varname based on the column number. Stata columns are 1-indexed. """ return f'v{column_number}'
f0e150300f7d767112d2d9e9a1b139f3e0e07878
58,093
from typing import Optional import os from datetime import datetime import asyncio async def make_rzd_request(url) -> Optional[str]: """Get response from rzd with Selenium. Args: url: Search url. Returns: response: Page data. """ # ChromeBrowser (heroku offical supports it) easy ...
2f8b9dff66d7f75afcc992a1ba8b152fe5f2ac73
58,094
def min_version(the_module, min_version_str: str = "") -> bool: """ Convert version strings into tuples of int and compare them. Returns True if the module's version is greater or equal to the 'min_version'. When min_version_str is not provided, it always returns True. """ if min_version_str: ...
2ab3d5c3a9b2fd1c938ddd3f7967d8df7c5b6c77
58,095
def graph_from_place(query, network_type='all_private', simplify=True, retain_all=False, truncate_by_edge=False, name='unnamed', which_result=1, buffer_dist=None, timeout=180, memory=None, max_query_area_size=50*1000*50*1000, clean_periphery=True, ...
c4a981aa0f7c68e183593e4c985f899ceb038aca
58,096
def inspect_file_attrs(f_path_or_f_obj): """ List out the attributes of some HDF5 file object. If a path is provided, then it will open the file in read mode. Examples: .. code-block:: python import h5py from support.hdf5_util import inspect_file_attrs file_path = "e...
a7ede3aac50c93a048bc188e2e6795586ec3eac2
58,097
def strip_name(s): """ Strips the name per RE_STRIP_NAME regex. >>> strip_name('Login') 'Login' >>> strip_name('LoginHandler') 'Login' >>> strip_name('LoginController') 'Login' >>> strip_name('LoginPage') 'Login' >>> strip_name('LoginView') ...
6cc3956bcb9e4696a1a434ccb654ac519d24b443
58,098
def api_queuelist(): """ Api Method that return the number of remaining itens in queue """ return str(len(link_queue)) + '\n'
48d21f6420dd8065f796f0697cad26dd416592a1
58,099