content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import typing from pydantic import BaseModel # noqa: E0611 from re import T def describe_response( status: typing.Union[int, HTTPStatus], description: str = "", *, content: typing.Union[typing.Type[BaseModel], type, dict] = None, headers: dict = None, links: dict = None, ) -> typing.Callable[...
8cbe3b5c519ea2383a2d20a1f46abd967084866d
40,049
def report_exception(f): """ Minimal decorator for reporting exceptions that occur within a function. Does not support generators.""" @wraps(f) def wrapped_f(*args, **kwargs): try: return f(*args, **kwargs) except: sentry_sdk.capture_exception() raise ...
5af0ace66d157ed84b03e0b5256d2a75f56eec07
40,050
def uncorr_noise_deprojection_bias(f1, map_var): """ Computes the bias associated to contaminant removal in the presence of uncorrelated inhomogeneous noise to the auto-pseudo-Cl of a given field f1. :param NmtField f1: fields to correlate :param map_cls_guess: array containing a HEALPix map correspond...
588379d9011fec22be3d9f1f4888ff4569e59499
40,053
def convert_expression(lst_tkn:list): """ Parameters: ----------- * lst_tkn [list]: list containing the raw tokens. Return: ------- * lst_res [list]: NPI tokens list obtained by shunting-yeard algorithm. """ lst_tkn = natural_conversion(lst_tkn) lst_res = shunting_yard_al...
2b8954b092f1d4de9c46b2ab608e363ec5aa71f2
40,054
def value(colors: list): """ Each resistor has a resistance value. Manufacturers print color-coded bands onto the resistors to denote their resistance values. Each band acts as a digit of a number. The program will take two colors as input, and output the correct number. :param colors: ...
14a52f12bfcfccd921ade8fa7708d3563c9c2508
40,055
import array def intersect_curve_surface(curve, surface, itol=None): """ Find the intersection points of a curve and a surface. :param curve: Curve to intersect. :type curve: :class:`.BezierCurve` or :class:`.NurbsCurve` :param surface: Surface to intersect. :type surface: :class:`.BezierSurf...
4c75b0f41b2345060f63032a0466bc0ed07cce69
40,056
def get_test_batch(data, batch_size=100, stim_history=30, min_window=10): """Get a batch of training data.""" stim = data['stimulus'] resp = data['responses'] ei_mag = data['ei_magnitude'] stim_batch = np.zeros((batch_size, stim.shape[1], stim.shape[2], stim_history)) resp_batch =...
c07642e213414fa192b5fd7c50822ed03ecf8afb
40,057
def rgb_to_hex(r, g, b): """ Generate a html hex color string from r,g,b values :params r,g,b: (0,1) range floats :return: a html compatible hex color string """ assert is_valid_rgb(r, g, b), "Error, r,g,b must be (0,1) range floats" R,G,B = rgb_to_RGB(r,g,b) return "#{:02x}{:02x}{:...
a71b30a96231940a019b9e16c7a2b06afe622073
40,058
def load_transforms(name): """Load data transformations. Note: - Gaussian Blur is defined at the bottom of this file. """ _name = name.lower() if _name == "cifar_sup": normalize = transforms.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010]) aug_transform...
e925adebd7c414f53f20a902622734509922138c
40,059
def set_axes(ax: Axes, x_scale: str = 'linear', y_scale: str = 'linear', xlim: tuple = (), ylim: tuple = (), fontsize: int = 20, show_grid: bool = True, hide_xticklabels: bool = False, hide_yticklabels: bool = False) -> Axes: """ Sets axes to an existing ax. The explanation of the argu...
78f793f76af961c6785dcc8ee1d8f12dd0d71e8f
40,060
def parallel_run(tasks): """ Tasks is an iterable of bound functions. The wrapper makes it easy for us to run a list of different functions, rather than one function over a list of inputs. """ workers = max(1, len(tasks)) with Pool(processes=workers) as pool: # As soon as any one ta...
067d437c5fe6269d8df8fbbe11dc797e0e94a41a
40,062
def bgr_to_hex(b, g, r): """Converts (blue, green, red) to a "#rrbbgg" string. Args: b, g, r: the BGR values Returns: a hex string """ return rgb_to_hex(r, g, b)
97d91cfd544a0dc3bae97fb81e0f626c40dc0ebe
40,063
from typing import List def get_all_csv_files_in_folder(folder: str) -> List[str]: """Returns list of strings including path to folder for CSV files""" return get_all_files_in_folder_ending_with(folder=folder, ending=OUTPUT_FILE_ENDING)
b025404edd4a23cbb96c67ae9e02dfdc59562767
40,064
import numpy def linear_correct_byte(image: numpy.ndarray, gamma: float = 2.2) -> numpy.ndarray: """ :param image: :type image: :param gamma: :type gamma: :return: :rtype:""" return gamma_correct_float_to_byte(image / 255, gamma)
a307a28724ae0dfd4470a163b489b18397f36a5e
40,065
import base64 def is_authenticated(request, username, password): """Authenticate the request using HTTP Basic authorization""" authenticated = False if 'HTTP_AUTHORIZATION' in request.META: auth = request.META['HTTP_AUTHORIZATION'].split() if len(auth) == 2: if auth[0].lower() ...
9ea596245283d34146058e7c79964646661c2151
40,066
def inspect_object(object_: object): """Find all members of Python object. Example: def say_hi(name: str) -> str: print(f"hi {name}") print(inspect_object(say_hi)) >>> say_hi=> type=<class 'function'> parameters=> name=> annotation=<class 'str'> default=None kind=POSITIONAL_OR_KEYWORD ...
06dc3558861dd2488e7e88c379a9c6d103812b3b
40,067
def recall(prediction, ground_truth, average="macro"): """ Return the recall score evaluated between PREDICTION and GROUND_TRUTH average - (default: "macro") mode of averaging for multi-class prediction """ return metrics.recall_score( prediction, ground_truth, ...
f526752e1187b4eaef8c44169442faca8e04e6cf
40,068
def tf_lipschitz_constant(M, G, phi, phiT, tol=1e-3, verbose=None): """Compute lipschitz constant for FISTA It uses a power iteration method. """ n_times = M.shape[1] n_points = G.shape[1] iv = np.ones((n_points, n_times), dtype=np.float) v = phi(iv) L = 1e100 for it in range(100): ...
75c66a3909debc23c06894e2040737be6e2081f0
40,069
def fourCornersSort(pts): """ Sort corners: top-left, bot-left, bot-right, top-right """ # Difference and sum of x and y value # Inspired by http://www.pyimagesearch.com diff = np.diff(pts, axis=1) summ = pts.sum(axis=1) # Top-left point has smallest sum... # np.argmin() returns INDEX o...
05fa8b611b4f42853282f0d55d301be74f78e873
40,070
import abc import copy def populate_user_output_from_schema_and_outputs(output_schema, output_names, outputs): """Follows the schema to generate an output that is expected by the user""" def _replace_stub_with_tensor_value(user_output, outputs, output_idx): # Recursively traverse across user_output a...
600d72ae8d886b35cc62bb1250163fb82f309727
40,071
def get_current_mapset(): """Return the current mapset This is the fastest way to receive the current mapset. The current mapset is set by init() and stored in a global variable. This function provides access to this global variable. """ global current_mapset return current_mapset
90c183d91cdf8c8db2a56c49a3e0d843087a9436
40,072
def compress_image_to_file(path, terms, annotate, iterations=None, path_out=None): """ Compresses the image from `path` using singular value expansion. The image is saved to an output file which name is chosen automatically, unless `path_out` is specified. Parameters ---------- path : path ...
20385189911c25ebe0c4ede335091542fd7fb7a4
40,073
from typing import Counter def merge_vocabs(vocabs, vocab_size=None): """ Merge individual vocabularies (assumed to be generated from disjoint documents) into a larger vocabulary. Args: vocabs: `torchtext.vocab.Vocab` vocabularies to be merged vocab_size: `int` the final vocabulary si...
f7237ad4342acabf444c9facf6dc4eb841140082
40,074
import torch def nan_mode(input): """Mode value for tensor (ignoring NaNs).""" return torch.mode(input[~torch.isnan(input)])[0]
cf2ef4fb23a0dfbc251dd385a38ed8e01142ac08
40,075
import pandas from re import T import numpy def event_values_block( da: xarray.DataArray, events: pandas.DataFrame, offset: T.Union[T.Iterable[int], T.Dict[T.Hashable, int]], load: bool = True, ): """ Gets the values from da where an event is active """ if load: da = da.load()...
419b10f9ef9384cf60a4277e6fdaa518cd43d2f7
40,076
def get_signing_pubkey(client, secret_url): """ Gets a PEM file from the vault, and returns one of RSAPublicKey, DSAPublicKey, or EllipticCurvePublicKey depending on the contents of the secret. """ try: raw_pubkey = client.get_secret(secret_url).value return load_ssh_public_key( ...
3b23e7c3d95b07a1460fd1e136ce42e5782b0990
40,077
def validate_dandiset_yaml(filepath): """Validate dandiset.yaml""" with open(filepath) as f: meta = yaml_load(f, typ="safe") return _check_required_fields(meta, _required_dandiset_metadata_fields)
86d199a89b72c8df361af7be163ee7ca57cb9600
40,079
def get_grads(spike_stats, targets_frs, update_rule=0.0005): """Calculate gradients for updating the synaptic weights""" mean_frs = spike_stats['firing_rate']['mean'] fr_diffs = {pop_name: (trg_fr - mean_frs.loc[pop_name]) for pop_name, trg_fr in targets_frs.items()} mse = np.sum(np.power(list(fr_diffs....
6fd845f811bee0abc0f512bd9e8d5a0b91064f1a
40,080
def _im_to_blocks(im, width, roi=None, roi_method="all"): """ Converts image to list of square subimages called "blocks." Parameters ---------- im: array_like Image to convert to a list of blocks. width: int Width of square blocks in units of pixels. roi: array_like, dtype b...
029751c9b2c0052e9718f44c231066dc37b569d6
40,081
from typing import Dict import re import string def preprocess(docs: Dict[str,str], **kwargs): """ Takes as input a dictionary of the documents for clustering and transforms them into the compact data structures of corpus and Vocabulary in preperation for clustering. This process turns each document from...
7e2adfeed7f7738763829bfed8784f7f993933c0
40,082
def activation(func_a): """Activation function wrapper """ return eval(func_a)
ad7f668aec546de452ef4968b22c338c2ca873b6
40,083
def gravity(z, g0, r0): """Relates Earth gravity field magnitude with the geometric height. Parameters ---------- z: float Geometric height. g0: float Gravity value at sea level. r0: float Planet/Natural satellite radius. Returns ------- g: float Gra...
28b0fdacbadf63755870024acec99b4a38057e24
40,084
def tfunc(t, rdd): """ Transforming function. Converts our blank RDD to something usable :param t: datetime :param rdd: rdd Current rdd we're mapping to """ return rdd.flatMap(lambda x: stream_twitter_data())
d60a9731e3134e04c38f855aedb202ec895a15e1
40,085
def quote_columns_data(data: str) -> str: """When projecting Queries using dot notation (f.e. inventory [ facts.osfamily ]) we need to quote the dot in such column name for the DataTables library or it will interpret the dot a way to get into a nested results object. See https://datatables.net/referenc...
db5e82e5d3641bebcac069ac4d5a7bb42baafcbb
40,086
def svn_client_checkout2(*args): """svn_client_checkout2(char const * URL, char const * path, svn_opt_revision_t peg_revision, svn_opt_revision_t revision, svn_boolean_t recurse, svn_boolean_t ignore_externals, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t""" return _client.svn_client_checkout2(*args)
f0891b04e0eac9675e6912f105e8499ede218ef9
40,087
def sort_kv_pairs_by_value(d): """Turn a dict into a list of key-value pairs, sorted by value.""" return [ (k, v) for v, k in sorted([(v, k) for k, v in d.items()], reverse=True) ]
58f3e40c4993a64f71212157fdd73ad82712fa44
40,088
import csv def parsaCollettivi(file_collettivi): """ Dato il csv genera lista di collettivi """ collettivi = [] with open(file_collettivi, 'r') as aulefile: parsedCollettivi = csv.reader(aulefile, delimiter=';') for row in parsedCollettivi: flags = [] turni = [] ...
88c0e972232baae19862df3c3a6bc9324d94a501
40,089
def rk4(derivs, y0, t, *args, **kwargs): """ Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta. This is a toy implementation which may be useful if you find yourself stranded on a system w/o scipy. Otherwise use :func:`scipy.integrate`. Args: derivs: the derivative of the sys...
3db3e7131525ff7b9decb554c99b67f9dc8a40dc
40,090
def hexEncode(value): """Some replaces.""" if isinstance(value, unicode): value = value.encode('ascii', 'backslashreplace') return value
06b4a4d1e6c8b3fff74fa6b2c0240b428f54eef6
40,091
import logging def get_logger(name=None, level=None, stream=DEFAULT_STREAM, clobber_root_handler=True, logger_factory=None, wrapper_class=None): """Configure and return a logger with structlog and stdlib.""" _configure_logger( logger_factory=logger_factory, wrappe...
4ed97ccb18096ae67dc37d957f6607a6de9ee3fc
40,092
def log_likelihood(model,data) : """Return log10 (normalized) likelihood: P(3D astrometry | 3D phase space, Covariance)""" functions = [] for s in data : functions.append(imageLikelyhood(s)) images = getImages(model) if(len(images)==len(functions)): # probably a very bad idea re...
5b74b3e6e503cb6f4a29a4db6a5574dd883bf806
40,093
def yices_division(t1, t2): """Returns the term (t1 / t2) from the given terms, or NULL_TERM if there's an error. division(t1, t2): t1 and t2 must be arithmetic terms NOTE: Until Yices 2.5.0, t2 was required to be a non-zero constant. This is no longer the case: t2 can be any arithmetic term. ...
32daac08ea6b9004e68505a8db1843dd18027949
40,095
import string def is_string_formatted(s, return_parsed_list=False): """ check if a string has formatted characters (with curly braces) """ l = list(string.Formatter().parse(s)) if len(l) == 1 and l[0][0] == s: is_formatted = False else: is_formatted = True if return_parsed_list: ...
a47a698d1c53bbf4bfb88ec7aca9e1ed3b0958d5
40,096
def extract_number(img): """Get the image number only""" img=img.split('.fits') nimg=int(img[0][-4:]) return nimg
693648b7ea11fe311da1c30485e69ed0a6aea774
40,097
def cv_score_table(res_sprm_cv): """ Internal function reorganizing sklearn GridSearchCV results to pandas table. The function adds the cv score table to the object as cv_score_table_ """ n_settings = len(res_sprm_cv.cv_results_['params']) etas = [res_sprm_cv.cv_results_['para...
8d139a8cfb5c2bfd625409fa319d3ff189f3afec
40,098
def calc_aridity(prec, pet, water_year): """Calculates the aridity as described in Knoben et al (2018)""" prec = prepare_data(prec, water_year=water_year) pet = prepare_data(pet, water_year=water_year) prec_pet = pd.concat([prec[0],pet.iloc[:,0:2]],axis=1) prec_pet.columns = ["prec", "pet", "water_...
661c5b76941abf14e2befa834d9e7d2fce8eb908
40,099
def group_reads_by_allele(allele_reads): """ Returns dictionary mapping each allele's nucleotide sequence to a list of supporting AlleleRead objects. """ return groupby(allele_reads, lambda read: read.allele)
b7a18b40b45d0eeb5234b1f79f6b114bc109b64a
40,101
from typing import Optional from typing import MutableMapping from typing import Any def create_handler( session: Optional[SessionProxy], request: ResourceHandlerRequest, callback_context: MutableMapping[str, Any], # pylint: disable=unused-argument ) -> ProgressEvent: """This function is triggered by...
850f5c600fea75ac56ec4643888235a1ce5db836
40,102
import sqlite3 def get_buoy_metadata(db): """ Extracts the meta data from the buoy database. Parameters ---------- db : str Full path to the buoy data SQLite database. Returns ------- meta_info : list List of dicts with keys based on the field names from the Stations ...
0a985b57093661d768d09f90ff5b2e66d1ad24ca
40,103
def get_dist_args(dist): """Probe a scipy.stats distribution (or JMCtools distribution) for its required arguments""" has_args = False try: fargs = dist.args has_args = True except AttributeError: has_args = False if not has_args: try: func_args = g...
af274ebfc4d1667bead06203c48111907f1f8d0f
40,104
def MobileNetV2( input_shape, alpha=0.35, include_top=True, pooling=None, classes=1000, classifier_activation='softmax', last_block_filters=None, **kwargs ): """Instantiates the MobileNetV2 architecture. .. seealso:: * `MobileNetV2: Inverted Residuals and Linear Bottlenecks <https://arxiv.org/...
4eac36750d536cd4e98247c85271abf3dcf22e6f
40,105
from typing import Collection def update_menu_item_linked_object(menu_item, linked_object): """Assign new linked object to a menu item. Clear other links.""" menu_item.category = None menu_item.collection = None menu_item.page = None if isinstance(linked_object, Category): menu_item.categ...
708c8af16a565d5093bf36a0b9ad65a12f6e57ac
40,106
from datetime import datetime def _get_creation_date(): """作成時刻を返す""" return datetime.utcnow().strftime('%Y-%m-%d-T%H:%M:%SZ')
a6725716361b0b37c35c62fe1f9600224d8d04f2
40,107
def _param_with_axes_sow_reduce_fn(x, y): """Reduction function for sow() calls. Args: x: Existing value, or () if there was none. y: New axis names sown. Returns: New axis names. Raises: TypeError: If the newly sown value is not an AxisMetadata. ValueError: If the newly sown axis names d...
7f5ba0199c7ee8743c3bb6d6a4d9a0d2c7654221
40,108
def combine_similar_titles(extracted_strings): """Take a dictionary with titles and nested dicts with scores and combine scores for titles which we decide are the same.""" # Iterate through each possible pair of title keys, including both # permutations of each pair for title_pair in permutation...
4eaf64cbff8e6000ba41d8e6b8abcde737e06543
40,109
import operator def rkLeavesByK(hmat): """Sort the Rk leaves by descending compression ratio. Args: hmat: an instance of HMatrixStructure Returns: [(compression_ratio1, leaf1), ...] """ leaves = hmat.listRkLeaves() ratio_leaves = [(x.k, x) for x in leaves] ratio_leaves.sort(k...
228eef2af7c422471744b1c92572d5e66f69166b
40,110
def check_length(min_length: int, max_length: int, mode: str = 'and', *args) -> bool: """ check items length is between min_length and max_length :param min_length: minimum length :param max_length: maximum length :param mode: check mode, 'and': all...
f959619a466f62bf6ecfaf10e0fbb316652891e7
40,111
def _fix_estrs(estrs): """Add fitzpatrick colors, and remove emoji variation selectors. 1) The emoji ordering html page omits the skin color variants. Since we want to display them, we have to add them. However, we don't add them for sequences with multiple people, since we don't support multiracial groups ...
2e7ac8ac84d7a3afad796b607efb075e3ef8d087
40,112
from typing import Type from re import T from typing import Dict def dict_to_df(desired_type: Type[T], dict_obj: Dict, logger: Logger, orient: str = None, **kwargs) -> pd.DataFrame: """ Helper method to convert a dictionary into a dataframe. It supports both simple key-value dicts as well as true table di...
dad9f8f0630404641bc8316ab06c817d8df51c3a
40,113
import html def architecture_summary(): """ Returns the text and image of architecture summary of the project. """ return html.Div(children=[ dcc.Markdown(''' # Project Architecture This project uses MongoDB as the database. All data acquired are stored in raw form to t...
6e5221c5cf3179760180242c583c4c0c1c3f1a8c
40,114
def chunk_str(msg, sep=(" ", ".", ",", "(")): """ chunk_str will take a string and a tuple of separators and recursively split the string into Chunk objects that record which separator was used to split it. :param msg: The string that we want to break apart. :type msg: str :param sep...
f1735fc8fda1a86eb3a3722c60764c3e40fc5041
40,115
def build_shared_head(cfg): """Build shared head of detector.""" return build(cfg, SHARED_HEADS)
ed82b32b8fab10120ac9a611d18ac0ebae43aa18
40,117
def check_csrf(func): """Checks/removes a csrf_token from request.session's list of valid tokens.""" def _wrapper(request, *args, **kw): valid_csrf_tokens = request.session.get('csrf_tokens') request_csrf_token = request.REQUEST.get('csrf_token') # Special easter-egg to get around the csrf token. #...
ee3d9b78528318750b08c191bfe0375c6dca95a9
40,118
from typing import Optional def get_connection_monitor(connection_monitor_name: Optional[str] = None, network_watcher_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> ...
65829ab0b59914cc4dc71b7575641fab9e09959c
40,119
def ssh(host, user, passwd, log=LOG): """SSH to any host. """ ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=passwd) return ssh
99b4a474c66e2fd9c9206698f47d8044e675ce5b
40,120
def _filter_deps(filter, deps): """Filters dep targets based on tags.""" if not filter: return deps kept_deps = [] for dep in deps: info = None if TulsiSourcesAspectInfo in dep: info = dep[TulsiSourcesAspectInfo].filtering_info # Only attempt to filter targe...
a673c92c93bd43279e355da904ae495075a9027c
40,121
import tokenize def prepare_text_for_lda(text): """ :param text: :return: list of filetered tokens """ tokens = tokenize(text) tokens = [token for token in tokens if len(token) > 4] tokens = [token for token in tokens if token not in stop_words_es] tokens = [get_lemma(token) for token...
819769632c1d96ade4ddfd6cde6c2b5ea51bb83d
40,122
def make_grammar(description, whitespace=r'\s*'): """Convert a description to a grammar. Each line is a rule for a non-terminal symbol; it looks like this: Symbol => A1 A2 ... | B1 B2 ... | C1 C2 ... where the right-hand side is one or more alternatives, separated by the '|' sign. Each altern...
b390f8a75aa228490a9d4ddc6a0d24b6cf8b5633
40,123
from pathlib import Path def repo_root() -> Path: """Repository root, 3 levels up from the resources root.""" return builtin_resources_root().parent.parent.parent
5d156b90d9c60accc5ab55ba13495ac178a168c5
40,124
from typing import Optional from typing import Sequence def get_acl_token(accessor_id: Optional[str] = None, description: Optional[str] = None, local: Optional[bool] = None, namespace: Optional[str] = None, policies: Optional[Sequence[pulumi.Inpu...
db8255cebea93eb4ce02ef347e38785b41db471f
40,125
def calc_code_churn( repo: pygit2.Repository, commit_a: pygit2.Commit, commit_b: pygit2.Commit, churn_config: tp.Optional[ChurnConfig] = None ) -> tp.Tuple[int, int, int]: """ Calculates churn between two commits. Args: repo: git repository commit_a: base commit for diff cal...
5297797d567c0b04283e7d68fa0070ba2cf7f8d8
40,126
def utf8_to_vyxal(code: str) -> str: """Turn UTF-8 characters into bytes according to the codepage""" return "".join(chr(codepage.index(char)) for char in code)
13590b17a821561e1baabfc01df0a2ba6997b505
40,127
def apply_chunk_id_maps(continuation_arr, chunk_id_maps): """ Applies id maps to each set of continuations """ for (c_dict, id_map) in zip(continuation_arr.flat, chunk_id_maps.flat): apply_id_map(c_dict, id_map) return continuation_arr
d738e36a264a0b7a707203c01bbf13b952f1b8c8
40,128
def find_system_symbol(img, instruction_addr, sdk_info=None, cpu_name=None): """Finds a system symbol.""" img_cpu_name = get_cpu_name(img['cpu_type'], img['cpu_subtype']) cpu_name = img_cpu_name or cpu_name return DSymSymbol.objects.lookup_symbol( instruction_addr=instruction_addr, image...
219e9fe30b5b15e3943ec56bec735395d5fd6a41
40,129
def check_processed_data(df,col_list,na_action): """ Checks if provided dataframe consists of required columns and no missing values """ check_passed = True # Check columns df_cols = df.columns if set(df_cols) != set(col_list): check_passed = False print('Column names mismatched...
fd26d00eabd9eb1dfd1f8bce01a3fb86582a740f
40,130
def bezier_terms(n, t): """ Bezier curve. Return n+1 terms in list () """ m_terms = list() m_C = binomial_term for i in range(n): m_terms.append( m_C(n, i) * (1 - t)**(n - i) * t**i ) m_terms.append(t ** n) return m_terms
b0891cb6fc848f971134367988f2cd85f3a624a5
40,131
def feed_conversation(samples, limit=5, threshold=.85): """helper function to feed result of classifier to Conversation module.""" try: iter(samples) assert not any(not isinstance(sub, tuple) for sub in samples) except (AssertionError, TypeError) as e: raise TypeError('samples must b...
4c3d9b7c63e71790bb1a8445662754d48e31524f
40,133
def _mount_config_map_op(config_map_name: str) -> OpFunc: """Mounts all key-value pairs found in the named Kubernetes ConfigMap. All key-value pairs in the ConfigMap are mounted as environment variables. Args: config_map_name: The name of the ConfigMap resource. Returns: An OpFunc for mounti...
6c8193465f70ca34619a8a7c9f3debc534208f6e
40,134
def make_tree(file_name): """Loads reStructuredText, outputs an lxml tree""" rst = resource_string(__name__, file_name) xml = rst2xml(rst) return etree.fromstring(xml)
be71c99472ecf9fb8994390c090da4d21e26c144
40,135
import csv def save_comments(name, token, nfrom = 0, toappend=[]): """ Args: Takes a pagename, an API token, (optionally: an integer specifying which # post to begin from, and a list to append comments to) Out: a list containing: a list of of the comments it has i...
210995010d6ee61dec45aaa3db17d1e43aad6c37
40,136
def point_inside_volume(p, ab1, ab2, eps = 0.01): """ Check if point p is inside the aabb volume """ ab1 = ab1.copy() - eps ab2 = ab2.copy() + eps if ab1[0] <= p[0] <= ab2[0] and \ ab1[1] <= p[1] <= ab2[1] and \ ab1[2] <= p[2] <= ab2[2]: return True else: retu...
9cdb6323343fdc23dae4b2c899927450c92cb7a2
40,137
def vgg_input_preprocess(image, max_dim=512, **kvargs): """ apply appropriate VGG preprocessing to image, shape=(?,h,w,c) should be same as `tf.keras.applications.vgg19.preprocess_input(rgb_data)/255.0` NOTE: - x_train from dataset will be dtype=tf.float32, domain=(0,1.) AFTER tf.image.convert_image_dtype(...
dec82416a3f91842280db82c0c62780ae628dde8
40,138
def ldns_rr_set_type(*args): """LDNS buffer.""" return _ldns.ldns_rr_set_type(*args)
a8223db4323693a46676292fd0d6065341254d05
40,139
def spline_jacobian(coordinates, force_coordinates, fudge=1e-5): """ Make the Jacobian matrix for the 2D biharmonic spline. Follows [Sandwell1987]_. Each column of the Jacobian is the Green's function for a single force evaluated on all observation points. Parameters ---------- coordi...
a997105a9b7d8ac025bde4d8b77e05199d21b0d7
40,140
def whip(innings_pitched: float, bb: int, h: int) -> float: """Calculate a baseball pitcher's WHIP. WHIP = (BB + H) / IP bb = Walks / Base on balls h = hits """ WHIP = (bb + h) / innings(str(innings_pitched)) return round(float(WHIP), 2)
a28809aae63bab2b68f61bde2c84919e34b2998d
40,141
def _determine_levels(index): """Determine the correct levels argument to groupby.""" if isinstance(index, (tuple, list)) and len(index) > 1: return list(range(len(index))) else: return 0
2eaed820eb45ff17eb4911fe48670d2e3412fb41
40,142
def integerise(series): """ This duplicates functionality that exists in humanleague, rather than intorducing a package dependency solely for this function """ sumf = sum(series) sumi = round(sumf) # rescale series to nearest-integer sum series = series * sumi / sumf # get integer and fr...
a498c3fda42c7c02a3552ece93ea3d6c1996eacc
40,143
def update_cluster_host_deployed_config( cluster_id, host_id, user=None, session=None, **kwargs ): """Update clusterhost deployed config by cluster id and host id.""" clusterhost = _get_cluster_host( cluster_id, host_id, session=session ) return _update_clusterhost_deployed_config( c...
97ccffbded81262f42bab2349636f28db5416760
40,144
def make_ppo_runner(env, policy, num_runner_steps, gamma=0.99, lambda_=0.95, num_epochs=3, num_minibatches=4): """ Returns env runner for PPO """ transforms = [GAE(policy, gamma=gamma, lambda_=lambda_, normalize=False)] if not policy.is_recurrent() and getattr(env.unwrapped, "nenvs", Non...
9443dabb606457f8984900c35941dbf068dd9b2d
40,145
def left_window_coords(win_size, original_left_bound): """ Returns a `tuple` `(new_start, new_end)` left of original bound describing a window of length `win_size` (see note). Note: Converts any new value less than `1` to `1`. :param win_size: size of window to the left. :param original_left_b...
80d1c96ab2f9de650b50dbde04acfdb455824f78
40,146
def _get_forms_to_modify(domain, modified_forms, modified_cases, is_deletion): """Used on user.retire() and user.unretire() Returns a list of IDs of forms which only modify the cases passed in and which aren't already listed in `modified_forms`. """ form_ids_to_modify = set() for case_id in mod...
4c907c12a79a7eedb29b4b52461dcdc0c2d8602a
40,147
def build_post_required_integer_header_request( **kwargs # type: Any ): # type: (...) -> HttpRequest """Test explicitly required integer. Please put a header 'headerParameter' => null and the client library should throw before the request is sent. See https://aka.ms/azsdk/python/protocol/quickstar...
ba9fe7629c798311fb9670db3092f5a72d9a9717
40,148
def mask2rle(img: np.ndarray): """ img: numpy array, 1 - mask, 0 - background Returns run length as string formated """ pixels = img.copy().flatten() pixels = np.concatenate([[0], pixels, [0]]) runs = np.where(pixels[1:] != pixels[:-1])[0] + 1 runs[1::2] -= runs[::2] return ' '.join(...
be053cd777f30a610121cae80cf97b15014504a3
40,149
def make_mask(df: pd.DataFrame, image_name: str="img.jpg", shape: tuple=(256, 1600)): """ Create mask based on df, image name and shape. """ encoded_masks = df.loc[df["im_id"] == image_name, "EncodedPixels"] masks = np.zeros((shape[0], shape[1], 4), dtype=np.float32) for idx, label in enumerate...
7902d5bc5a7a3c5e7d124f698b94548742e37fdf
40,150
from typing import List from typing import Dict def parse_filters(tokens: List[str]) -> Dict[str, str]: """Parses a filter description, like 'filter-for', 'refcounty', '42'.""" ret: Dict[str, str] = {} filter_for = False for index, value in enumerate(tokens): if value == "filter-for": ...
6b659342761e11311bfa3aa1962067e3e83a809d
40,151
def format_val(v): """Takes in float and formats as str with 1 decimal place :v: float :returns: str """ return '{:.1f}%'.format(v)
932ca312a573a7e69aa12e032d7b062ac22f3709
40,152
def _can_cast(type1, type2): """NOT_RPYTHON: operates on BaseType subclasses""" return casting_table[type1.num][type2.num]
03e8602528b26c2c5a61fc56af0ef79c82a9ecf2
40,153
def concat(layers): """ Args: layers (list(layer)): a list of layers """ return ( np.concatenate([l[0] for l in layers]), np.concatenate([l[1] for l in layers]) )
b07eda38b6974a208f2756b04fc7f92ca5853da4
40,154
import struct def array_to_bytes(arr: np.ndarray): """ Dumps a numpy array into a raw byte string. :param arr: A numpy array. :return: A `bytes` string. """ shape = arr.shape ndim = arr.ndim ret = struct.pack('i', ndim) + struct.pack('i' * ndim, *shape) + arr.tobytes(order='C') ret...
fa623658aa73d0f5486771f497c9ce159ea89ca6
40,155
def count_parameters(model): """ number of model parameters to update """ return sum(p.numel() for p in model.parameters() if p.requires_grad)
3f739da845f483fdd489afabd9da12340b0f44a9
40,156