content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def reportData_to_report(report_data: ReportData) -> Report: """Create a report object from the given thrift report data.""" main = { "check_name": report_data.checkerId, "description": report_data.checkerMsg, "issue_hash_content_of_line_in_context": report_data.bugHash, "locatio...
7b8d210e08113af405225ef7497f6531c4054185
7,000
def softmax(x): """A softmax implementation.""" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum(axis=0)
3c8e38bf30304733e957cabab35f8fec1c5fba55
7,001
import logging def get_cazy_class_fam_genbank_records(args, session, config_dict): """GenBank acc query results from the local CAZyme database for CAZyme from specific classes/fams :param args: cmd-line argument parser :param session: open SQLite db session :param config_dict: dict, defines CAZy clas...
3f2d8f65f811be1de6b839753242e51457f8e03e
7,002
def assign_bias_ID(data, bias_params=None, bias_name='bias_ID', key_name=None, bias_model=None): """ Assign a value to each data point that determines which biases are applied to it. parameters: data: pointCollection.data instance bias_parameters: a list of parameters, each unique combinati...
8f2145b5efcd7b892b3f156e1e0c4ff59dac9d43
7,003
def check(s): """ :param s:str. the input of letters :return: bool. """ if len(s) == 7 and len(s.split(' ')) == 4: for unit in s.split(' '): if unit.isalpha(): return True
86e1270af299ba83b68d0dab9f8afc3fc5b7d7c5
7,004
def pyeval(*args): """ .. function:: pyeval(expression) Evaluates with Python the expression/s given and returns the result >>> sql("pyeval '1+1'") pyeval('1+1') ------------- 2 >>> sql("select var('test')") # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ....
fa7febed8f25860eee497ce670dc9465526cbbc1
7,005
from typing import Dict def is_buggy(battery: Dict) -> bool: """ This method returns true in case an acpi bug has occurred. In this case the battery is flagged unavailable and has no capacity information. :param battery: the battery dictionary :return: bool """ return battery['design_capac...
3508b2ab6eae3f3c643f539c1ea5094e5052278b
7,006
def with_hyperparameters(uri: Text): """Constructs an ImporterNode component that imports a `standard_artifacts.HyperParameters` artifact to use for future runs. Args: uri (Text): Hyperparameter artifact's uri Returns: ImporterNode """ return ImporterNode( instance_name='with_h...
e06cc33d043e6abd4a9ee30648f72dcea2ad1814
7,007
def update_user_controller(user_repository_spy): # pylint: disable=W0621 """montagem de update_user_controller utilizando spy""" usecase = UpdateUser(user_repository_spy, PasswordHash()) controller = UpdateUserController(usecase) return controller
474c2bf42c932d71181bebbf7096cd628ba6956a
7,008
def blockList2Matrix(l): """ Converts a list of matrices into a corresponding big block-diagonal one. """ dims = [m.shape[0] for m in l] s = sum(dims) res = zeros((s, s)) index = 0 for i in range(len(l)): d = dims[i] m = l[i] res[index:index + d, index:index + d] = m ...
b13a67cd203930ca2d88ec3cd6dae367b313ae94
7,009
def log_new_fit(new_fit, log_gplus, mode='residual'): """Log the successful refits of a spectrum. Parameters ---------- new_fit : bool If 'True', the spectrum was successfully refit. log_gplus : list Log of all previous successful refits of the spectrum. mode : str ('positive_re...
16761ca135efbdb9ee40a42cb8e9e1d62a5dc05e
7,010
def prepare_hr_for_compromised_credentials(hits: list) -> str: """ Prepare human readable format for compromised credentials :param hits: List of compromised credentials :return: Human readable format of compromised credentials """ hr = [] for hit in hits: source = hit.get('_source...
846144700d3fe21628306de5aff72a77d2cc9864
7,011
def red_bg(text): """ Adds a red background to the given text. """ return colorize(text, "\033[48;5;167m")
edc2741f3246de2c90c9722c4dbd2d813708fe90
7,012
def model_utils(decoy: Decoy) -> ModelUtils: """Get mock ModelUtils.""" return decoy.mock(cls=ModelUtils)
eb5d3eaf8f280086521209f62025e42fca7aec93
7,013
def getLeftTopOfTile(tilex, tiley): """Remember from the comments in the getStartingBoard() function that we have two sets of coordinates in this program. The first set are the pixel coordinates, which on the x-axis ranges from 0 to WINDOWWIDTH - 1, and the y-axis ranges from 0 to WINDOWHEIGHT - 1. Lembrando...
fad5a9df02b05e76ba62013a49d77941b71f6f5f
7,014
def count_str(text, sub, start=None, end=None): """ Computes the number of non-overlapping occurrences of substring ``sub`` in ``text[start:end]``. Optional arguments start and end are interpreted as in slice notation. :param text: The string to search :type text: ``str`` :param ...
1578f868a4f1a193ec9907494e4af613ca2a6d4d
7,015
def tanh(x, out=None): """ Raises a ValueError if input cannot be rescaled to a dimensionless quantity. """ if not isinstance(x, Quantity): return np.tanh(x, out) return Quantity( np.tanh(x.rescale(dimensionless).magnitude, out), dimensionless, copy=False )
3d86565fb512bfe6f8034dd7436b65c1c322cde6
7,016
from typing import Optional from typing import Sequence from pathlib import Path def epacems( states: Optional[Sequence[str]] = None, years: Optional[Sequence[int]] = None, columns: Optional[Sequence[str]] = None, epacems_path: Optional[Path] = None, ) -> dd.DataFrame: """Load EPA CEMS data from P...
79213c5adb0b56a3c96335c0c7e5cb1faa734752
7,017
from typing import Optional from typing import Tuple import logging def check_termination_criteria( theta: Optional[float], num_iterations: Optional[int] ) -> Tuple[float, int]: """ Check theta and number of iterations. :param theta: Theta. :param num_iterations: Number of iterations....
536cd70b8e8b04d828f0a4af1db96809ab607ff3
7,018
import os def _get_rank_info(): """ get rank size and rank id """ rank_size = int(os.environ.get("RANK_SIZE", 1)) if rank_size > 1: rank_size = int(os.environ.get("RANK_SIZE")) rank_id = int(os.environ.get("RANK_ID")) else: rank_size = 1 rank_id = 0 return...
35ef60e41678c4e108d133d16fd59d2f43c6d3dd
7,019
def verify_password(password, hash): """Verify if a hash was generated by the password specified. :password: a string object (plaintext). :hash: a string object. :returns: True or False. """ method = get_hash_algorithm(flask.current_app.config['HASH_ALGORITHM']) return method.verify(pass...
484ad9f2debbd8856b9b7fbdd2a7588f9a279f62
7,020
import re def _conversion_sample2v_from_meta(meta_data): """ Interpret the meta data to extract an array of conversion factors for each channel so the output data is in Volts Conversion factor is: int2volt / channelGain For Lf/Ap interpret the gain string from metadata For Nidq, repmat the gai...
e8cd2ea376bdb44ee999459ffcc28c4c4db39458
7,021
def read_split_csv(input_files, delimiter='\t', names=['src', 'dst'], dtype=['int32', 'int32']): """ Read csv for large datasets which cannot be read directly by dask-cudf read_csv due to memory requirements. This function takes large input split into smaller files (number of input_fi...
cd1f2ccd487cf808af1de6a504bc0f6a3a8e34a1
7,022
def _gnurl( clientID ): """ Helper function to form URL to Gracenote_ API service. :param str clientID: the Gracenote_ client ID. :returns: the lower level URL to the Gracenote_ API. :rtype: str """ clientIDprefix = clientID.split('-')[0] return 'https://c%s.web.cddbp.net/webapi/xml...
6d1935c8b634459892e4ec03d129c791b1d8a06a
7,023
def flatatt(attrs): """ Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. js...
01d9ee3ec96b5a096758f60c2defe6c491d94817
7,024
def draw_bboxes(img,boxes,classes): """ Draw bounding boxes on top of an image Args: img : Array of image to be modified boxes: An (N,4) array of boxes to draw, where N is the number of boxes. classes: An (N,1) array of classes corresponding to each bounding box. Outputs: ...
6b60550206aaaa9e5033850c293e6c48a7b13e6d
7,025
def markdown(context, template_path): """ {% markdown 'terms-of-use.md' %} """ return mark_safe(get_markdown(context, template_path)[0])
ea6cb711c1a669ad7efdf277baab82ea2a65ba9c
7,026
def investorMasterGetSubaccAssetDetails(email, recvWindow=""): """# Query managed sub-account asset details(For Investor Master Account) #### `GET /sapi/v1/managed-subaccount/asset (HMAC SHA256)` ### Weight: 1 ### Parameters: Name |Type |Mandatory |Description --------|--------|--------|-------- email |STRING |...
7d4f4c5cbd069144319268dcb7235926e55f85d8
7,027
def ema_indicator(close, n=12, fillna=False): """EMA Exponential Moving Average via Pandas Args: close(pandas.Series): dataset 'Close' column. n_fast(int): n period short-term. fillna(bool): if True, fill nan values. Returns: pandas.Series: New feature generated. "...
9ddb20ddc6e0cc4b1f08a4e3347f719dbe84b55b
7,028
import os import uuid import tempfile def connect(addr=None, proto=None, name=None, pgrok_config=None, **options): """ Establish a new ``pgrok`` tunnel for the given protocol to the given port, returning an object representing the connected tunnel. If a `tunnel definition in pgrok's config file matc...
b71b8fd145e36b66f63f2a93a32c6bfc89ec9c13
7,029
def u_glob(U, elements, nodes, resolution_per_element=51): """ Compute (x, y) coordinates of a curve y = u(x), where u is a finite element function: u(x) = sum_i of U_i*phi_i(x). Method: Run through each element and compute cordinates over the element. """ x_patches = [] u_patches = [] ...
2c9cabf97b9904d80043a0102c0ac8cd156388ae
7,030
def keyring_rgw_create(**kwargs): """ Create rgw bootstrap keyring for cluster. Args: **kwargs: Arbitrary keyword arguments. cluster_uuid : Set the cluster UUID. Defaults to value found in ceph config file. cluster_name : Set the cluster name. Defaults to "ce...
077a3536a6e1ce2e762b14d8fb046617136fe941
7,031
import pandas from datetime import datetime def read_tm224_data(filename: str, folder: str = None) -> pandas.DataFrame: """ Read data stored by Lakeshore TM224 temperature monitor software. Args: filename: string name of ".xls" file on disk folder: string location...
430e5a64b5b572b721177c5adce7e222883e4512
7,032
import oci.mysql import mysqlsh from mds_plugin import compartment, compute, network, object_store import datetime import time def create_db_system(**kwargs): """Creates a DbSystem with the given id If no id is given, it will prompt the user for the id. Args: **kwargs: Optional parameters K...
4e801cf1752e527bc82d35f9e134f2fbb26a201b
7,033
import json import logging def load_keypoints2d_file(file_path, njoints=17): """load 2D keypoints from keypoint detection results. Only one person is extracted from the results. If there are multiple persons in the prediction results, we select the one with the highest detection score. Args: file_path...
3cf5c8f2c236b3883e983c74e1ac23c78d256b0d
7,034
def utf8_bytes(string): """ Convert 'string' to bytes using UTF-8. """ return bytes(string, 'UTF-8')
8e5423d2b53e8d5fbeb07017ccd328236ef8bea5
7,035
def line_search(f, xk, pk, old_fval=None, old_old_fval=None, gfk=None, c1=1e-4, c2=0.9, maxiter=20): """Inexact line search that satisfies strong Wolfe conditions. Algorithm 3.5 from Wright and Nocedal, 'Numerical Optimization', 1999, pg. 59-61 Args: fun: function of the form f(x) where x is...
787d5c1fa472f9cc2d59e517a3388f0538c4affd
7,036
def _get_value(session_browser, field): """Get an input field's value.""" return session_browser.evaluate_script('$("#id_%s").val()' % field)
7ed2d130b83af7e6fdb6cce99efb44846820585a
7,037
def search_2d(arr, target): """ TODO same func as in adfgvx """ for row in range(len(arr)): for col in range(len(arr)): if arr[row][col] == target: return row, col raise ValueError
8b6f9885175ddc766052aa10c9e57d8212ae385a
7,038
import logging def scale_large_images_landmarks(images, landmarks): """ scale images and landmarks up to maximal image size :param list(ndarray) images: list of images :param list(ndarray) landmarks: list of landmarks :return tuple(list(ndarray),list(ndarray)): lists of images and landmarks >>> ...
63449e9281b5dcfcafb89e8a661494f99170f19d
7,039
def home(): """Post-login page.""" if flask.request.method == 'POST': rooms = get_all_open_rooms() name = "anon" if flask.request.form['name'] != "": name = flask.request.form['name'] player_id = flask_login.current_user.id game_id = "" if flask.re...
3bac8a5adeeb3e22da9ef7f2ee840a02bc70b816
7,040
def ik(T, tf_base) -> IKResult: """ TODO add base frame correction """ Rbase = tf_base[:3, :3] Ree = T[:3, :3] Ree_rel = np.dot(Rbase.transpose(), Ree) # ignore position # n s a according to convention Siciliano n = Ree_rel[:3, 0] s = Ree_rel[:3, 1] a = Ree_rel[:3, 2] A = np...
41cf7ba841397f0d26ff597952609aa0685afe09
7,041
import functools def standarize_ms(datas, val_index, max=(2^32 - 1)): """ Standarize milliseconds lapsed from Arduino reading. Note: Only takes height for one circulation of ms from Arduino. datas: List of data readings val_index: Index of ms value in reading data entry max: ...
84bf498ff3c88b3415433fa9d5be7b6865b3216b
7,042
def corr_bias(x_data, y_data, yerr, pdz1_x, pdz1_y, pdz2_x, pdz2_y): """ Given a correlation measurement and associated PDZs, generate a model and fit as a bias to the measurement. Return: 1) the model [unbiased] (x and y float arrays) 2) best fit bias (float) 3) the bias PDF (x ...
255e1c5a67551deb19b91d247f5a913541d8f1da
7,043
def confidence_ellipse( x=None, y=None, cov=None, ax=None, n_std=3.0, facecolor="none", **kwargs ): """ Create a plot of the covariance confidence ellipse of `x` and `y` Parameters ---------- x, y : array_like, shape (n, ) Input data. cov : array_like, shape (2, 2) covarianc...
3965012ccdd1f6b71af4f169b812c384446ed76d
7,044
from pathlib import Path from typing import Iterator import itertools import os def lsR(root: Path) -> Iterator[Path]: """Recursive list a directory and return absolute path""" return filter(lambda p: ".git" not in p.parts, itertools.chain.from_iterable( map( lambda lsdir: list(map(lambda ...
67771d5e305d30ac72aeaab16b72ad5a85fe1493
7,045
from typing import List def adapted_fields(type) -> List[Attribute]: """Return the attrs format of `fields()` for attrs and dataclasses.""" if is_dataclass(type): return [ Attribute( attr.name, attr.default if attr.default is not MISSING ...
cc6a799e06715cbd4e3219ea42aaeff2e4924613
7,046
from typing import get_args def get_parms(): """ Use get_args to get the args, and return a dictionary of the args ready for use in pump software. @see get_args() :return: dict: parms """ parms = {} args = get_args() for name, val in vars(args).items(): if val is not None:...
6ebdbee656fd216e5d8c66025029aa2d58641831
7,047
import ftplib import os import re def cloud_backup(backup_info: dict): """ Send latest backup to the cloud. Parameters ---------- backup_info: dict Dictionary containing information in regards to date of backup and batch number. """ session = ftplib.FTP_TLS("u301483.your-storagebo...
47e2b6de1430b4b784dc0cd486d105b3c1653b12
7,048
def make_led_sample(n_samples=200, irrelevant=0, random_state=None): """Generate random samples from the 7-segment problem. Parameters ---------- n_samples : int, optional (default=200) The number of samples to generate. irrelevant : int, optional (default=0) The number of irreleva...
7dab2595c0118ca2f08a99ded22047be164f1648
7,049
def handle_source_authorization_exception(e): """ Error handler: the data source requires authorisation This will be triggered when opening a private HDX dataset before the user has supplied their authorisation token. @param e: the exception being handled """ if e.message: flask.flash(e....
e2c736b301e229d61874bb3cfad13b86dc93e1d1
7,050
def findcosmu(re0, rp0, sublat, latc, lon): # considers latc to be plaentocentric latitudes, but sublat to be planetographic """Takes the equitorial and polar radius of Jupiter (re0, rp0 respectively), the sub-latitude of Jupiter, latitude and longitude (both in radians) to determine the "cos(mu)" of the ...
677adffb6f00e9e1119a71a660ee81d2893d4ef1
7,051
def RMS_energy(frames): """Computes the RMS energy of frames""" f = frames.flatten() return N.sqrt(N.mean(f * f))
10d366e771f629c6efda2faf1f752363dca63b0a
7,052
import urllib def is_blacklisted_url(url): """ Return whether the URL blacklisted or not. Using BLACKLIST_URLS methods against the URLs. :param url: url string :return: True if URL is blacklisted, else False """ url = urllib.parse.urlparse(url).netloc for method in WHITELIST_URL: ...
8a987c0bbce01d18da67b047aed0e680ce5fc661
7,053
def heading(yaw): """A helper function to getnerate quaternions from yaws.""" q = euler2quat(0.0, 0.0, yaw) quat = Quaternion() quat.w = q[0] quat.x = q[1] quat.y = q[2] quat.z = q[3] return quat
fcd05575257ef6cdc084cb2fde309aa48b5a2fb5
7,054
def check_login_required(view_func): """ A decorator that checks whether login is required on this installation and, if so, checks if the user is logged in. If login is required and the user is not logged in, they're redirected to the login link. """ def _check(*args, **kwargs): siteconf...
9f0b44f630a24649d87af0bd604a41b7b5b885de
7,055
def Str(*args): """(s1, s2, ...) -> match s1 or s2 or ...""" if len(args) == 1: return Str1(args[0]) return Expression.Alt(tuple(map(Str, args)))
41aece71a6a774db58028add5d60d8c9fed42dd3
7,056
def image_noise_gaussian(image): """ Adds Gaussian noise to the provided image """ float_img = image.astype(np.float) gauss = np.random.normal(0.0, 4.0, (IMG_SIZE, IMG_SIZE, IMG_CHANNELS)) gauss = gauss.reshape(IMG_SIZE, IMG_SIZE, IMG_CHANNELS).astype(np.float) result = float_img + gauss ...
0e5f5a83f7017d48e083a35bcb22cdf50ebb1006
7,057
from re import T def argsort(x: T.FloatTensor, axis: int = None) -> T.LongTensor: """ Get the indices of a sorted tensor. If axis=None this flattens x. Args: x: A tensor: axis: The axis of interest. Returns: tensor (of ints): indices of sorted tensor """ if axis ...
57e2e4d8c5a870c4ea382a02e19d0451dbe90704
7,058
def dirPickledSize(obj,exclude=[]): """For each attribute of obj (excluding those specified and those that start with '__'), compute the size using getPickledSize(obj) and return as a pandas Series of KBs""" return pd.Series({o:getPickledSize(getattr(obj, o))/1024. for o in dir(obj) if not np.any([o[:2]=='_...
d27b404f8c637aa7dd230126d3dbe9112240112c
7,059
from typing import Any def audit_log() -> Any: """ List all events related to the connected member. """ if "member_id" not in session: abort(404) return render_template( "audit_log.html", full_audit_log=fetch_audit_log(session["member_id"]), )
a5c95ac9c7e55212f8e308a9bf141468dc3a7626
7,060
def load_comparisonXL(method, evaluate="train", dropna=True): """Load comparison table.""" if evaluate == "test": e = "['Test']" elif evaluate == "in bag": e = "['In Bag']" elif evaluate == "out of bag": e = "['Out of Bag']" else: e = "['Train']" # Import methods...
56ff4d8c74ec88fc8b2f245706b7cf039334a76f
7,061
def verify_user_password(user: User, password: str) -> bool: """Verify User's password with the one that was given on login page.""" return pwd_context.verify(password, user.password)
43b25118e5ef3b89622acd7aa3276a1b18352674
7,062
def __valid_ddb_response_q(response): """private function to validate a given DynamoDB query response.""" if 'ResponseMetadata' in response: if 'HTTPStatusCode' in response['ResponseMetadata']: if response['ResponseMetadata']['HTTPStatusCode'] == 200: return True return F...
f4e71c4f5d058ba20013b3a405ffeff637e03ae8
7,063
def GetPipelineResultsPathInGCS(artifacts_path): """Gets a full Cloud Storage path to a pipeline results YAML file. Args: artifacts_path: string, the full Cloud Storage path to the folder containing pipeline artifacts, e.g. 'gs://my-bucket/artifacts'. Returns: A string representing the full Cloud ...
83b7c15f00679ff201c9a8b155102f36bb8e685c
7,064
def Pnm_p(n, m, x): """Eq:II.77 """ return lpmn(m, n, x)[1][-1, -1]
027cb169263853ede6d29a6760da981d30ef950b
7,065
def _remove_empty_subspace(subspaces, n_clusters, m, P, centers, labels, scatter_matrices): """ Check if after rotation and rearranging the dimensionalities a empty subspaces occurs. Empty subspaces will be removed for the next iteration. Therefore all necessary lists will be updated. :param subspaces: ...
473a509860b9708ee217f4f7b0a2718d1a3a7d7e
7,066
def _get_citekeys_action(elem, doc): """ Panflute action to extract citationId from all Citations in the AST. """ if not isinstance(elem, pf.Citation): return None manuscript_citekeys = global_variables["manuscript_citekeys"] manuscript_citekeys.append(elem.id) return None
74dec7a972f38c34040dc430b0c130b2a76784c2
7,067
def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gra...
da85dee074f5bb15a13ea3d2c2fe105469c1ee90
7,068
def compute_neighbours_probability_matrix(n_matrix, src, d_matrix, sigma_neigh): """Compute neighbours' probability matrix. Parameters ----------- n_matrix : :py:class:`~numpy.ndarray` of :py:class:`~int`, shape (n_verts, n_neigh_max) The sets of neighbours. src : :py:class:`~numpy.ndarray...
2651ad650697266d7e0db5fdc55e176334fc3cb8
7,069
def ar_cosmap(inmap): """ Get the cosine map and off-limb pixel map using WCS. Generate a map of the solar disk that is 1 at disk center and goes radially outward as the cos(angle to LOS), which is = 2 at 60 degrees from LOS. Other outputs: - rrdeg: gives degrees from disk center - offlimb: ...
4365b0ef1134f117e5bc3396239cc1ba174f5009
7,070
def as_array(request: SubRequest) -> bool: """ Boolean fixture to support ExtensionDtype _from_sequence method testing. """ b = request.param assert isinstance(b, bool) return b
7a8b627769b8955ad4162a30be5ddc9b0ee76723
7,071
def gram_matrix(x): """Create the gram matrix of x.""" b, c, h, w = x.shape phi = x.view(b, c, h * w) return phi.bmm(phi.transpose(1, 2)) / (c * h * w)
11de97b67f3f8ecb7d7d009de16c1a5d153ab8ff
7,072
import os import pandas as pd from datetime import date from pptx import Presentation from pptx.util import Inches, Pt def create_presentation(path): """Creates ppt report from files in the specified folder. """ report = Presentation() #report = Presentation('test_data//templates//ppt_template.pptx') ...
3fdc2382b5e21bab54c0735314ab13aeb225cd0d
7,073
def open_file(path, mode): """ Attempts to open file at path. Tried up to max_attempts times because of intermittent permission errors on Windows """ max_attempts = 100 f = None for _ in range(max_attempts): try: f = open(path, mode) except PermissionError: ...
9217a1b66b2bb30895fe445fa4a50b5da5466391
7,074
import requests import json def get_sts_token(current_refresh_token): """ Retrieves an authentication token. :param current_refresh_token: Refresh token retrieved from a previous authentication, used to retrieve a subsequent access token. If not provided (i.e. on the initial authenticati...
b41c6658a4eb218771d6e908411ba3b54e4e13f3
7,075
async def device_climate_fan(device_climate_mock): """Test thermostat with fan device.""" return await device_climate_mock(CLIMATE_FAN)
1143adceacb610d18e1a26df4e24f715eb68917f
7,076
def make_training_config(args): """ Create training config by parsing args from command line and YAML config file, filling the rest with default values. Args args : Arguments parsed from command line. Returns config : Dictionary containing training configuration. """ # Parse the configuration file. config = {...
1902e0999336249a7feda1f0aa415f7d148a16ee
7,077
from typing import Tuple def _crown_relu_relaxer(inp: Bound) -> Tuple[LinFun, LinFun]: """Obtain the parameters of a linear ReLU relaxation as in CROWN. This relaxes the ReLU with the adaptive choice of lower bounds as described for CROWN-ada in https://arxiv.org/abs/1811.00866. Args: inp: Input to the ...
7e43e973adb65089a2eb35665c219911fc409446
7,078
import torch import time def run_single_measurement(model_name, produce_model, run_model, teardown, inp, criterion, extra_params, use_dtr, use_profiling): """ This function initializes a model and performs a single measurement of the model on the given input. While it might seem most reasonable to in...
a3765a88ccb10b3f0322f11f8205ecfdb7f98f38
7,079
def make_noise(fid, snr, decibels=True): """Given a synthetic FID, generate an array of normally distributed complex noise with zero mean and a variance that abides by the desired SNR. Parameters ---------- fid : numpy.ndarray Noiseless FID. snr : float The signal-to-noise ...
823c9fee2c1a696a38b6a27406f51a27185460c1
7,080
def viterbi(prob_matrix): """ find the most likely sequence of labels using the viterbi algorithm on prob_matrix """ TINY = 1e-6 # to avoid NaNs in logs # if prob_matrix is 1D, make it 2D if len(np.shape(prob_matrix)) == 1: prob_matrix = [prob_matrix] length = len(prob_...
50b28dcf7cedc75adb4a41cb9ccf2152af5f4b8f
7,081
def slsn_constraint(parameters): """ Place constraints on the magnetar rotational energy being larger than the total output energy, and the that nebula phase does not begin till at least a 100 days. :param parameters: dictionary of parameters :return: converted_parameters dictionary where the viola...
9fd4cc37c783aa1afdc816edbc88c45132fb4026
7,082
def grover_circuit(n,o,iter): """Grover Search Algorithm :param n: Number of qubits (not including ancilla) :param o: Oracle int to find :return qc: Qiskit circuit """ def apply_hadamard(qc, qubits,a=None) -> None: """Apply a H-gate to 'qubits' in qc""" for q in qubits: ...
fac61eda28a249e333dabd46c7d404603141c07c
7,083
def reference_cluster(envs, in_path): """ Return set of all env in_paths referencing or referenced by given in_path. >>> cluster = sorted(reference_cluster([ ... {'in_path': 'base', 'refs': []}, ... {'in_path': 'test', 'refs': ['base']}, ... {'in_path': 'local', 'refs': ['test']...
6398705dfb63c30de62b2eb900d88612e5144774
7,084
def scheme_apply(procedure, args, env): """Apply Scheme PROCEDURE to argument values ARGS in environment ENV.""" if isinstance(procedure, PrimitiveProcedure): return apply_primitive(procedure, args, env) elif isinstance(procedure, UserDefinedProcedure): new_env = make_call_frame(procedure, a...
14879f29a5e8c3c5b7d4d41be35730eb66dbdc66
7,085
def _validate_num_clusters(num_clusters, initial_centers, num_rows): """ Validate the combination of the `num_clusters` and `initial_centers` parameters in the Kmeans model create function. If the combination is valid, determine and return the correct number of clusters. Parameters ---------- ...
67d0be234a97c33eb742c70e8d6bb30be4608ab2
7,086
import mimetypes def urlinline(filename, mime=None): """ Load the file at "filename" and convert it into a data URI with the given MIME type, or a guessed MIME type if no type is provided. Base-64 encodes the data. """ infile = open(filename, 'rb') text = infile.read() infile.close() ...
4b8035944a7a25d5b3ce3bc8a8fbd0a4dd424447
7,087
import json def parse_matching_criteria(filters, filter_operator): """ build the filter criteria, if present :param filters:field opr value[;]... :param filter_operator: any|all :return dictionary of parsed filter settings, True/False for "all"/"any" setting """ LOG.debug("%s %s", filters,...
13bc51b84751671e913e43a614cda7edf9fe3734
7,088
def star_rating(new_rating=None, prev_rating=None): """ Generates the query to update the product's star ratings. Inc method is from https://docs.mongodb.com/manual/reference/operator/update/inc/ """ add_file = { 1: {"one_star": 1}, 2: {"two_stars": 1}, 3: {"three_stars": 1},...
e50f8271dbbb8c2722729cce6a8f036c851c4e95
7,089
def check_encoder(value: EncoderArg) -> EncoderFactory: """Checks value and returns EncoderFactory object. Returns: d3rlpy.encoders.EncoderFactory: encoder factory object. """ if isinstance(value, EncoderFactory): return value if isinstance(value, str): return create_encode...
5e23b483df8fbe190f1ac6ccf743bc783728adf8
7,090
import pathlib def allowed_task_name(name: str) -> bool: """Determine whether a task, which is a 'non-core-OSCAL activity/directory is allowed. args: name: the task name which is assumed may take the form of a relative path for task/subtasks. Returns: Whether the task name is allowed or ...
231d7a98f5d6b7059f5517283ec3bed35264050e
7,091
def get_ignored_classes(uppercase, lowercase, digit): """ get tuple of ignored classes based on selected classes :param uppercase: whether to keep uppercase classes :param lowercase: whether to keep lowercase classes :param digit: whether to keep digit classes :return: ...
2a2380f4f984feb42ce1de912739fd395a8422bd
7,092
import torch def unscaled_prediction_rmse(model, input_tensor, label_tensor, scalar, loading_length=0, return_loading_error=False, device=None): """ Prediction RMSE. :param model: model :param input_tensor: input tensor :param label_tensor: label tensor :param sc...
ea7b0e2c2fd022cc7bcb466057feacf5a1fbaa00
7,093
import copy def __copyList__(fromList, initialValues = None): """ Returns a copy of the provided list. Initial values must either be a single value, or a list of exactly the same size as the provided list. """ if __isListType__(fromList) is False: raise ValueError('The provided value to co...
9f126a10795132b5d2ddaeef552c6e5abd8680ba
7,094
import re def build_or_pattern(patterns, escape=False): """Build a or pattern string from a list of possible patterns """ or_pattern = [] for pattern in patterns: if not or_pattern: or_pattern.append('(?:') else: or_pattern.append('|') or_pattern.append(...
225cc20504a85342694e14ea76b9bf3ed8b6d11b
7,095
from typing import Tuple from typing import Any def concatenate_and_process_data( data_consent: pd.DataFrame, data_noconsent: pd.DataFrame, conversion_column: str = CONVERSION_COLUMN, drop_columns: Tuple[Any, ...] = DROP_COLUMNS, non_dummy_columns: Tuple[Any, ...] = NON_DUMMY_COLUMNS ) -> Tuple[pd...
57c84f0b406750b40161bb7f5ed19c5f2cd509e8
7,096
def plot(nRows=1, nCols=1, figSize=5): """ Generate a matplotlib plot and axis handle Parameters ----------------- nRows : An int, number of rows for subplotting nCols : An int, number of columns for subplotting figSize : Numeric or array (xFigSize, yFigSize). The size of each axis. """...
a0ec25fa932933f717ef9a576d0f80d531865aad
7,097
def make_rate_data(grp, valuevars, query="none == 'All'", data=ob): """Filters, Groups, and Calculates Rates Params: grp [list]: A list detailing the names of the variables to group by. valuevars [list]: A list detailing the names of the quantitative variable summarise and calculate...
8342d5b20f7020a97f283ce80b04b92b42476862
7,098
def test_compare_sir_vs_seir(sir_data_wo_policy, seir_data, monkeypatch): """Checks if SEIR and SIR return same results if the code enforces * alpha = gamma * E = 0 * dI = dE """ x_sir, pars_sir = sir_data_wo_policy x_seir, pars_seir = seir_data pars_seir["alpha"] = pars_sir["gamma"] ...
d70b841b23af6883a14bb1c97f31f3e24ae7fd4d
7,099