content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def gen_cookie(username, hash_password): """ Build secure cookie content as a string containing: - content length (excluding length itself) - role_name - 16 first chars of the hash password Part of hash password is there for 2 main reasons: 1/ If the cookie secret key is st...
44b0ec056bd7002aea7b63fb57901dc1180cb45c
3,623,837
def line_generic(pos, color=(1, 1, 1, 1), width=0.1, antialias=True, mode='line_strip'): """ Add a pyqtgraph.opengl.GLLinePlotItem to GPGLViewWidget, with exactly the same arguments. For detail, consult documentation of pyqtgraph.opengl.GLLinePlotItem: http://www.pyqtgraph.org/documentation/3dgraphic...
749189775a45cf78e20000e17edc734eed6b6bfa
3,623,838
def create_dict(obj, columns): """ Create a dict, given a database record and an ordered list of columns. Mind the order of column names in the columns list """ try: new_obj = {} for col in range(len(columns)): new_obj[columns[col]] = obj[col] return new_obj ...
9ac55086e8e6e584849deb93d79e148054e835f7
3,623,839
def filepath_result_format(classifier_name, task, res, filepath): """ Helper function to produce result dictionary using filepath filepath (str) : (e.g. '../../inferred_features/code_ss_w2v_multiclass_7.pkl' """ filepath = filepath.split("/")[-1] dims = filepath.split(".")[0].split("_") if d...
3b2d508f02963840ca7c467b40edfc2813fae73d
3,623,840
def get_optimisation_status(): """Get the status of an optimisation job.""" opt_job_id = request.args.get('opt-job-id') opt_job = database.opt_jobs.find_one({'_id': ObjectId(opt_job_id)}) return jsonify({'_id': opt_job_id, 'status': opt_job['status']})
c02707aedc5dea50389c0ef061b3df89f9024b95
3,623,841
def makeCorrelationMatrixFromDictionary(value_dictionary, keys=[], matrix_file_name="temporary_matrix_file.txt", key_file_name="temporary_key_file.txt"): """ Returns numpy.matrix: matrix object of correlation coefficients, symmetric matrix with a diagonal of ones Returns list: list of keys that correspond to the row...
6faa71bd32050ed5b9005de7f199e8ed05622f89
3,623,842
import itertools def pad(value, seq: Seq, size: int = None, step: int = None) -> Iter: """ Fill resulting sequence with value after the first sequence terminates. Args: value: Value used to pad sequence. seq: Input sequence. size: Optional minim...
b2ee68adf9e0bb760547fcc4c029b16df3f7dff3
3,623,843
def str_to_state(str_state): """ Reads a sequence of 9 digits and returns the corresponding state. """ assert len(str_state) == 9 and sorted(str_state) == list('012345678') return tuple(int(c) for c in str_state)
8e9e8c2b70f86aa4798f9be14d39c43404336e7a
3,623,844
def load_10x_h5(file, genome): """Load count matrix in 10x H5 format Adapted from: https://support.10xgenomics.com/single-cell-gene-expression/software/ pipelines/latest/advanced/h5_matrices Args: file (str): Path to H5 file genome (str): genome, top level h5 group Ret...
743da441f08eceb211340d1078ad95ba0be99afc
3,623,846
from typing import Optional def to_dataset_entity_id( full_name: str, platform: DataPlatform, account: Optional[str] = None ) -> EntityId: """ converts a dataset name, platform and account into a dataset entity ID """ return EntityId( EntityType.DATASET, DatasetLogicalID(name=full_...
cd93b34e43ef8f2b8cbda47ed1958430183fd57c
3,623,847
def get_collection_table_name(node, intermine_model): """ Get the table name for this collection :param node: :param intermine_model: :return: (table-name, reference-column-name). table-name will be null if there isn't a collection table for this node """ if 'reverse-reference' in ...
06aff0058450263131ad27afbe136dd63eaf4320
3,623,849
import time import gzip def parse_xml(path: str) -> Element: """Parse an XML file from a path to a GZIP file.""" t = time.time() log.info('parsing xml from %s', path) with gzip.open(path) as xml_file: tree = ET.parse(xml_file) log.info('parsed xml in %.2f seconds', time.time() - t) re...
526908cc950339c5471c53613a096b3fb615a51e
3,623,850
import string def apply_qos(): """POST QOS configuration from form data""" find_int_num = [i for i in request.form.get("interface") if i not in string.ascii_letters] find_int_type = [i for i in request.form.get("interface") if i in string.ascii_letters] build_config = BuildConfig.build_interface_qos(...
c426b0c3bcd9ec75306475c43600cfff1f5da7ad
3,623,851
def _readdir(DIR): """Implementation of perl readdir in scalar context""" try: result = (DIR[0])[DIR[1]] DIR[1] += 1 return result except IndexError: return None
0ebb237de9ea32fd11f7c6fc6e8a365420c65655
3,623,852
def compute_normalization(data): """ Write a function to take in a dataset and compute the means, and stds. Return 6 elements: mean of s_t, std of s_t, mean of (s_t+1 - s_t), std of (s_t+1 - s_t), mean of actions, std of actions """ l = [] for a in [data['observations'], (data['next_observatio...
521995f2611f66dc11bbe5cc3d3d40e04c97ff19
3,623,854
def convert_cidr_to_canonical_format(value): """CIDR is validated and converted to canonical format. :param value: The CIDR which needs to be checked. :returns: - 'value' if 'value' is CIDR with IPv4 address, - CIDR with canonical IPv6 address if 'value' is IPv6 CIDR. :raises: InvalidInpu...
a105c1eece32c0dd615fbe1e0082be95ade6666a
3,623,856
def g_xyz_eclip_planet_eqxdate(name, jde): """ Parameters ---------- name : str Name of the planet jde : float Julian Day of the ephemeris Returns ------- np.array[3] """ h_xyz_eclipt_earth = h_xyz_eclip_eqxdate("Earth",jde) h_xyz_eclipt_planet = h_...
9d8f29ca4af12cb369d89cc71e0428f571393d3d
3,623,857
def get_cannot_db(state_brief_db): """ Determine for each position register (identified by acceptance_id) the set of position registers. The condition for this is given at the entrance of this file. RETURNS: map: acceptance_id --> list of pattern_ids that it cannot be c...
c889ef602ff7caff59974cbb2aa5cf47dafa7581
3,623,858
def _unique_numpy_dtype_string(dtype): """Private function providing a standardized string used to characterize a Numpy dtype """ dt = np.dtype(dtype) try: s = dt[0].str except KeyError: s = dt.str return s[1:]
9764a029da8a947b0e04da11e822df00a6d7be21
3,623,859
from re import S def powsimp(expr, deep=False): """ Usage ===== powsimp(expr, deep) -> reduces expression by combining powers with similar bases and exponents. Notes ===== If deep is True then powsimp() will also simplify arguments of functions. By default deep...
55b3a28e7fbeca72ad07d588151a29fa3a4cc4ed
3,623,860
def dictize(aniter, mode, initial=None): """iter must contain (key,value) pairs. mode is a string, one of: replace, keep, tally, sum, append, or a custom function that takes two arguments. replace: default dict behavior. New value overwrites old if key exists. This is essentially a pass-thru. ...
c56a2ad83ec9a45e87caa7def33c6b51f63655cb
3,623,861
def flatten_composition(EXX): """Convert the ternary composition of B2 into a binary by taking out the vacancy composition degree of freedom. :EXX: ndarray (E, xa, xb) :returns: ndarray (E,x) """ E=EXX[:,0] a=EXX[:,1] b=EXX[:,2] xNi=1+a-b xAl=1-a xVa=b x=xNi/(xNi+...
3f2c2340214bfb36c97ee5e78189202fef12d921
3,623,862
def param_Valide_Algo_3(Lambda) : """Il faut que lambda soit valide""" return valide_Lambda(Lambda)
8b93ec29b1bdc0c9e6e55b6c640e7a0ed6e3e760
3,623,863
def extract_from(treatment): """Extract the data from the genus treatment. Parameters: treatment - a pdf file name of the genus treatment. data_type - "locations" or "classifiers" Returns a dict of results with the following format "locations" - a string of species names and locat...
fdae872f08757b990b3bd13cf3ab298b11caa9cf
3,623,864
from typing import Dict from typing import Any from typing import List def make_snapshots_of_each_scope_vars( *, locals_: Dict[str, Any], globals_: Dict[str, Any]) -> str: """ Make snapshots of each scope's variables. Parameters ---------- locals_ : dict Local scope's variables. ...
13747146eb30ffaf8629d30e8033adcd25ec9fe2
3,623,865
def get_registered_themes(): """Get registered themes. Gets a list of registered themes in form of tuple (plugin name, plugin description). If not yet auto-discovered, auto-discovers them. :return list: """ return get_registered_plugins(theme_registry)
582dc847c1e7a1118669ee1fe991ac2546201f23
3,623,866
def polyfit2d(pmap): """ Fit a 2nd order polynomial surface (paraboloid) to the map of Pearson's correlation coefficients (pmap) and return a list (a) containing the fit parameters. Model: C(i, j) = a0*i*i + a1*j*j + a2*i*j + a3*i + a4*j + a5 where (i, j) are the rows and columns in pmap. :pa...
dbf8416537219c8ad64b0dbb4909a07982d765db
3,623,867
def apriori_zc(data_set, data_set_dict, min_support=5): """ Apriori算法过程 :param data_set: 数据集 :param min_support: 最小支持度,默认值 0.5 :return: """ c1 = init_c1(data_set_dict, min_support) data = map(set, data_set) # 将dataSet集合化,以满足scanD的格式要求 freq_items = {} l1 = scan_data(data, c1, min...
5396c045e3e80bd3b2a5ca78b0cf4cca18c622b7
3,623,868
def find_replace_line_endings(fp_readlines): """ special find and replace function to clean up line endings in the file from end or starttag characters """ clean = [] for line in fp_readlines: if line.endswith("=<\n"): line = line.replace("<\n", "lt\n") clean.appe...
1fa3703b6d244d6b51c17c95a8cd71e48d5ebc9d
3,623,869
def process_properties(partition, vfunction, params): """ Process the properties specified in the 'properties' module parameter, and return two dictionaries (create_props, update_props) that contain the properties that can be created, and the properties that can be updated, respectively. If the reso...
0bb17cca4f742fb909987d948145ce1bfb52285e
3,623,870
def resize_and_project(features, resize_size, num_projection_layers, num_projection_channels): """Resizes input features and passes them through a projection head. Args: features: A [batch_size, height, width, num_channels] tensor resize_...
1fcd54728f4ffc582d9863fe549ce21570b5e245
3,623,871
import requests def _download_file_from_google_drive(id_file, destination, proxy=None): """ From https://stackoverflow.com/a/39225272/8195528. """ def get_confirm_token(response): for key, value in response.cookies.items(): if key.startswith('download_warning'): re...
95647eeaa58cef7367adbae9015badde0aeeb4c6
3,623,872
from typing import Optional def generate_text_consumer(filter_pattern: Optional[str]) -> ObservabilityEventConsumer: """ Creates a console event consumer, which is used to display events in the user's console Parameters ---------- filter_pattern : str Filter pattern is used to display cer...
3c5d10b95b05bd2b61ad3b7be7381a16c3a9ee1b
3,623,873
def verify_lacp_link_state(device, interface, links, state_name, expected_state, max_time=30, check_interval=10): """ Verify links of lag interface ...
900aee30781374e1ce61e38af6fb6c3393eec08a
3,623,874
def wfc3_bandpass(request): """Fixture to read in the pysynphot bandpass for a WFC3 filter""" return nebulio.Bandpass(','.join(['wfc3', 'uvis1', request.param]))
62b461a5ffc9e063b43caec9942e8c6bcb1513dd
3,623,875
def exists(profile, name): """Check if a role exists. Args: profile A profile to connect to AWS with. name The name of a role. Returns: True if it exists, False if it doesn't. """ result = fetch_by_name(profile, name) return len(result) > 0
bebf4cd514e9cbb2896b439c245c75b9b2c1f019
3,623,877
def _right_h5(value: list, fmt: str, meta: dict) -> dict: """Right-aligned header 5.""" return Plain([RawInline(fmt, '<h5 style="text-align:right !important">')] + value + [RawInline(fmt, '</h5>')])
811c89673d88cc090861e23551481a85f9f5bbd7
3,623,878
from typing import List def find_long_period(bool_array: List, min_duration:int, scale:int) -> List: """find_long_period. identify long period of motion :param bool_array: bool array with check of motion :type bool_array: List :param min_duration: minimum duration in index unit :type min_duration...
ab30167289045cc4ed7ee06acec669f933a1461f
3,623,879
import torch def nnc_compile(model: torch.nn.Module, example_inputs) -> torch.nn.Module: """ nnc_compile(model, example_inputs) returns a function with the same args as `model.forward`, with an extra argument corresponding to where the output is stored. This function takes the inputs (which must be Py...
15c686ec6a2b850ca0d2ef50e0e90a15392bb289
3,623,880
def _DeleteGridCellMetaData(zoom, x, y, uss_id): """Removes the USS entry in the metadata stored in a specific GridCell. Removes the USS entry in the metadata using optimistic locking behavior. Args: zoom: zoom level in slippy tile format x: x tile number in slippy tile format y: y tile number in sl...
c106116efe48ffdeb6e9093c04bb5fe1a5fc81b6
3,623,881
def compute_speed(pos, pos_tt): """Compute boolean of whether the speed of the animal was above a threshold for each time point Parameters ---------- pos: np.ndarray(dtype=float) in meters pos_tt: np.ndarray(dtype=float) in seconds smooth_param: float, optional Returns ...
f3176e459108127f79790bb67057cd316b3092c6
3,623,882
def unitsapi_Check(*args): """ * Checks the coherence between the quantity <aQuantity> and the unit <aUnits> in the current system and //! returns False when it's WRONG. :param aQuantity: :type aQuantity: char * :param aUnit: :type aUnit: char * :rtype: bool """ return _UnitsAPI.unit...
c5f5d7c1730ed7953cbda2f758186e3e39877c41
3,623,883
def read_txt_file(file_path, n_num=-1, code_type='utf-8'): """ read .txt files, get all text or the previous n_num lines :param file_path: string, the path of this file :param n_num: int, denote the row number decided by \n, but -1 means all text :param code_type: string, the code of this file ...
9c55d370d8e8610965e0f8c4b1bed85e6adcdc5b
3,623,884
import json import re def load_cluster(args): """ Load a single CourtListener cluster with its opinions from disk, and return metadata. This is called within a process pool; see ingest_courtlistener for how it's used. """ cluster_member, opinions_dir = args with cluster_member.open() a...
9d5335d72172ae933f9d2e94a8bb5a3f316fc5b9
3,623,885
import re import logging def ParseSuccessMsg(msg): """Attempt to parse the message for a user_op_manager SUCCESS line and extract user, device, op, class, and method. Return None otherwise. """ parsed = re.match(kSuccessMsgRe, msg) if not parsed: return None try: user, device, op, class_name, meth...
2e7edccb1a8d15e16aadfaa3fcf4465d755b46c8
3,623,887
import math def pow(x, y): """Return the logarithm of x with base y (default to e)""" if x <= 0 and not isinstance(y, int): raise ValueError(f"Exponent must be an integer if negative base. Received base {x} with exponent {y}.") return math.pow(x, y)
6ceb9957be3805c44db7c6b00e170db7ce27354f
3,623,888
def GetWavelength(): """ Get a single frequency reading """ return getwave(DZERO)
4b60655932762ae5e8157f2d7df12691e8162eed
3,623,889
def sum_while_same(xs, x): """Sum points for same date representation""" if not xs: return [x] if xs[-1][0] == x[0]: return xs[:-1] + [(xs[-1][0], xs[-1][1] + x[1])] else: return xs + [x]
646fc1873b582b3d9825cc69816e97de6f91bf3b
3,623,890
def download_artifact_from_aml_uri(uri: str, destination: str, datastore_operation: DatastoreOperations): """Downloads artifact pointed to by URI of the form `azureml://...` to destination :param str uri: AzureML uri of artifact to download :param str destination: Path to download artifact to :param Da...
5a59f74ed03b348960905c5f579ffb87a4edd076
3,623,891
import torch def l1_loss(pred_traj, pred_traj_gt): """ Input: :param pred_traj: Tensor of shape (batch, seq_len)/(batch, seq_len). Predicted trajectory along one dimension. :param pred_traj_gt: Tensor of shape (batch, seq_len)/(batch, seq_len). Groud truth predictions along on...
3fb4dd2b7fc85e8f32610065078aa3dc98d728d5
3,623,893
import calendar def calculate_summary_statistics(processed_fx_obs, categories): """ Calculate summary statistics for the processed data using the provided categories and all metrics defined in :py:mod:`.summary`. Parameters ---------- proc_fx_obs : datamodel.ProcessedForecastObservation c...
2871a0655e3a6b3a3df1ec137d536e3863299e72
3,623,894
import time def splitting_division_semi(f, group, table, sample_indices, splitting_fold): """Saving indices of each splitting group to a list that will be fed later to the deep learning model. Specific for the semi_resampling strategy, since there only training and validation need to be splitted.""" t0 = ...
5179caf3ec3205fc56f0e1c6b77687cd15842556
3,623,895
from typing import Tuple from typing import Any def extract(keys: Tuple[str, ...], state: State) -> Tuple[Any, ...]: """Extract multiple values from dictionary. Args: keys: Tuple of key whose values should be extracted from the dictionary. state: The dictionary where values need to be extract...
917ba523594d10a7c4af40d7f15af6815e0a2e1b
3,623,896
def distorted_bounding_box_crop(image, bbox, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), max_attempts=100): """Generate...
e788245b874c472368cba27389d15bfcf5ea0c88
3,623,897
def constructBoard(numCards=52): """"Create a board out of a shuffled deck of numCards numCards(default 52): number of cards in the board (even #, 8-52)""" deck = pd.Deck() ## Split the deck using the initial set of cards if numCards < 52 if numCards < 52: deck = splitDeck(deck, numCards) ...
9e8a26685ec01c1b35f269b50aa417bb1f08255e
3,623,898
def get_short_description(dict, value): """Get layout class based on value.""" return dict.get(value, {}).get('short_description')
f5885f10ce009db925d552f8a0b0f40ab1ccaa2a
3,623,900
def cdlconcealbabyswallow( client, symbol, timeframe="6m", opencol="open", highcol="high", lowcol="low", closecol="close", ): """This will return a dataframe of conceal baby swallow for the given symbol across the given timeframe Args: client (pyEX.Client): Client ...
04cea2169f0fc1dc9e173fea66d5c341aac4224c
3,623,901
def rectangular_hollow_section(b: float, d: float, t: float, r_out: float, n_r: int, material: pre.Material = pre.DEFAULT_MATERIAL) -> Geometry: """Constructs a rectangular hollow section (RHS) centered at *(b/2, d/2)*, with depth *d*, width *b*, thickness *t* and outer radius *r_out*, using *n_r* points to con...
a0639d8674485ba31e2e7c7b4df1c78e5980dcc8
3,623,902
def _is_subexpansion_optional(query_metadata, parent_location, child_location): """Return True if child_location is the root of an optional subexpansion.""" child_optional_depth = query_metadata.get_location_info(child_location).optional_scopes_depth parent_optional_depth = query_metadata.get_location_info(...
29391226258e75d434e07c291fe9590c1810d85b
3,623,903
import uuid def get_uuid(key, value, is_list=False, is_optional=False, default=None, options=None): """ Get the value corresponding to the key and converts it to `uuid`/`list(uuid)`. Args: key: the dict key. value: the value to parse. is_list: If this is one element or a list of e...
8325f288f580ed0b47fefc144cb16f71d4b1e742
3,623,904
import torch from typing import Sequence def to_tensor(data): """Convert objects of various python types to :obj:`torch.Tensor`. Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`, :class:`Sequence`, :class:`int` and :class:`float`. """ if isinstance(data, torch.Tensor): r...
3d9aa7cb8424e6ee07412449ee890ce174cbc5b8
3,623,905
def _filter_labels(text, labels, allowed_labels): """Keep examples with approved labels. :param text: list of text inputs. :param labels: list of corresponding labels. :param allowed_labels: list of approved label values. :return: (final_text, final_labels). Filtered version of text and labels ...
e17ed7659acbdadc71a6b3f5b522af1e34d40370
3,623,906
def _Itype(): """Loop iterator data type.""" return tf.int32 if use_xla() else tf.int64
484c51f53226f7ebb0cf9738c8b16ad99438289b
3,623,907
import math def Q(fastev,lagev,fastrc,lagrc): """Following Wuestefeld et al. 2010""" omega = math.fabs((fastev - fastrc + 3645)%90 - 45) / 45 delta = lagrc / lagev dnull = math.sqrt(delta**2 + (omega-1)**2) * math.sqrt(2) dgood = math.sqrt((delta-1)**2 + omega**2) * math.sqrt(2) if dnull < dgo...
fe975fb234297a6f25100bb85aa6639590a010d8
3,623,908
def w_median(a, weights): """ Compute the weighted median of a 1D numpy array. Parameters ---------- a : ndarray Input array (one dimension). weights : ndarray Array with the weights of the same size of `data`. Returns ------- median : float The output value. ...
f259dd036777380e50f9030d728c1d80c1f5ebaa
3,623,909
def from_trends_top_query_by_category(n=NUM_KEYWORDS): """ Get a set of keyword objects by querying Google Trends Each keyword obj is a dict with keys: keyword, category """ keyword_objs = [] for cid in POPULAR_CATEGORIES: yearmonth = '2016' pytrends = TrendReq(hl='en-US', t...
bf2582d60cf1f720b9f4b88838e9a22852f1f36f
3,623,911
from typing import List def list_vpc_cidrs(vpc_id: str, account_id: str, region: str) -> List[str]: """ Returns a list of vpc cidrs associated with a given vpc. Example use cases: 1. Get the CIDRs to install on other side of a peering. 2. See if there are any common CIDRs between two VPCs :pa...
bed0b41ff5d86fa87a89ee2aa1770871545e745e
3,623,913
def _multi_dot(arrays, order, i, j, precision): """Actually do the multiplication with the given order.""" if i == j: return arrays[i] else: return np.dot(_multi_dot(arrays, order, i, order[i, j], precision), _multi_dot(arrays, order, order[i, j] + 1, j, precision), ...
fa3e01e611d2897387452af6afb785087a0e46eb
3,623,915
import time def creation_date_demographics(route, label): """Return tweet creation dates.""" dataset = {'hateval': Tweet.objects.filter(hateval=True), 'offenseval': Tweet.objects.filter(offenseval=True), 'all': Tweet.objects.all()} db = dataset.get(route) if label == 'ab...
176f48ddf37b35d4acfd82e48e00e1be3b657072
3,623,916
def array_check(lst): """ Function to check whether 1,2,3 exists in given array """ for i in range(len(lst)-2): if lst[i] == 1 and lst[i+1] == 2 and lst[i+2] == 3: return True return False
ef60b52a9d7300fa458b503f49996aec0f0831ad
3,623,917
def fastmri_unet_transform_multicoil( kspace=None, mask=None, ground_truth=None, attrs=None, fname=None, slice_id=None ): """Transform to use as input to fastMRI's Unet model for multicoil data. This is an adapted version of the code found in `fastMRI <https://github.com/facebookresearch/fastMRI/blob/m...
c420979fc7b329972abf62b5a13996d98d2f1038
3,623,918
def stylize_cartoon(image, blur_ksize=3, segmentation_size=1.0, saturation=2.0, edge_prevalence=1.0, suppress_edges=True, from_colorspace=colorlib.CSPACE_RGB): """Convert the style of an image to a more cartoonish one. This function was primarily desi...
25db74f3ffb1548ccdc0f3af98c7ea0375150c94
3,623,919
def tca_model (image: Image.Image, order: int=2) -> ndarray: """ Compute a lens model which corrects transverse chromatic aberration. Parameters: image (PIL.Image): Input image. order (int): Polynomial order of lens model. Quadratic or cubic model is ideal. Returns: ndarray: Re...
2973e69d2896a918803bdaea3e2993048ecbcf2f
3,623,920
def _group_result_from_fields(json, fields): """Helper that creates a group response object from the given fields. :param json: original JSON string :param fields: the JSON fields :return: the created group response :rtype: GroupResult """ result = api.GroupResult() result.child_group...
a3ca4c71a4231b9a537d59c04a0c471db8785c83
3,623,921
def debounce(wait): """ Decorator that will postpone a function's execution until after `wait` seconds have elapsed since the last time it was invoked. """ def decorator(fn): timer = None def debounced(*args, **kwargs): nonlocal timer def call_it(): ...
270dc56653afde86c7874ad06a18e51ef195a80c
3,623,922
from typing import List from typing import Any def list_difference(list_1: List[Any], list_2: List[Any]) -> List[Any]: """ This Function that takes two lists as parameters and returns a new list with the values that are in l1, but NOT in l2""" differ_list = [values for values in list_1 if values no...
3831d799bb40080b828ee90e2929f77ff8aeb7ba
3,623,923
def rlsp( _run, mdp, s_current, p_0, horizon, temp=1, epochs=1, learning_rate=0.2, r_prior=None, r_vec=None, threshold=1e-3, check_grad_flag=False, solver="value_iter", reset_solver=False, solver_iterations=1000, ): """The RLSP algorithm.""" check_in("...
12449a66b430f3ad6d869184a9e954e520066232
3,623,925
def load_vsmi() -> pd.DataFrame: """ """ vsmi = pd.read_csv("../statistics/h_vsmi_30.csv", sep=";") vsmi.columns = vsmi.columns.str.lower() vsmi.rename(columns={"indexvalue": "VSMI"}, inplace=True) vsmi["date"] = pd.to_datetime(vsmi["date"], format="%d.%m.%Y") vsmi.set_index("date", inplace=...
ccd3ff8d0c728108b1556860e98c1723819cd778
3,623,926
def create_app(context: GhiaContext = None) -> Flask: """ Create the Flask app. Args: context (GhiaContext, optional): If no context is provided a new default one is automatically created. Defaults to None. Returns: Flask: Newly created Flask application. """ return ghia_web_logic.create_app(context=cont...
7df41acbc2babf6f25debac1a035a74b95fdd606
3,623,927
def shift_until_PSD(M, tol): """ Add the identity until a p x p matrix M has eigenvalues of at least tol""" p = M.shape[0] mineig = np.linalg.eigh(M)[0].min() if mineig < tol: M += (tol - mineig) * np.eye(p) return M
de2cf1060a32a487c5f6c3024ce294803f60b6da
3,623,928
def iris_to_df(iris): """ Make dataframe for multiclass classification from iris data""" X, y = iris.data, iris.target iris_column_data = X.T.tolist() iris_column_names = ["col" + str(idx) for idx in range(X.shape[1])] data = {} for ind, iris_data_column in enumerate(iris_column_data): d...
f158502b90a9a1afa8ac2e48b5446f42d18ca9f0
3,623,929
def format_feedback(feedback_row, study): """Updates the feedback dict with the new information.""" formatted_feedback_row = { "success": { study.get_single_field(field["field_id"]).field_name: field["field_value"] for field in feedback_row["success"] }, "failed":...
3d6d52d6a5340b13e81ca19ee28bff28b189cbc1
3,623,930
def build_geometry(self): """Compute the curve (Line) needed to plot the object. The ending point of a curve is the starting point of the next curve in the list Parameters ---------- self : SlotW11 A SlotW11 object Returns ------- curve_list: list A list of 7 Segmen...
c27bdfe1b1d80e4a1d9c664244cfc420b14c1742
3,623,931
def validcolor(c): """Takes a color and makes it valid by clamping each value between 0 and 255""" try: ret = [clamp(int(v+0.5), 0, 255) for v in c] return type(c)(ret) except TypeError: return clamp(int(v+0.5), 0, 255)
9a3b8e869c009c7c5c71ef8a4c9b1c0692abc856
3,623,932
def give_me_the_record(primary_id, swissprot_file): """ Return a single record given with the primary id :param primary_id: A primary id :param swissprot_file: A swissprot file :return: A record with accession == primary id """ with open(swissprot_file, 'r') as fh: for record in Swis...
9272ae10c3fb6faa2abec4638a8edb36a9bd7985
3,623,933
import requests def ms_graph_users(licensed=False): """Query the Microsoft Graph REST API for on-premise user accounts in our tenancy. Passing ``licensed=True`` will return only those users having >0 licenses assigned. """ token = ms_graph_client_token() headers = { "Authorization": "Beare...
976ebf632e1dd6bb7eee6acc7379617e2eac082a
3,623,935
def protect_def_name(defName): """Convert a DEF name to be supported in Webots.""" protectedDefName = clean_string(defName) if len(protectedDefName) > 0 and protectedDefName[0].isdigit(): protectedDefName = "_" + protectedDefName return protectedDefName
838d66ec3d0e88bff99d63f933f079df635777fb
3,623,936
from typing import Tuple def get_blog(id: str) -> Tuple: """ Function used to fetch particular blog or return error if it is doesn't exist. :param id: blog id :return: tuple of (blog object or any error) """ blog, error = _get_blog_obj(id) if not error: blog = [blog_schema.dum...
73bd9d679d2dd50a37ff6bd46fd31be677e3f5cc
3,623,937
def padded_cross_entropy_loss(logits, labels, smoothing, vocab_size): """Calculate cross entropy loss while ignoring padding. Args: logits: Tensor of size [batch_size, length_logits, vocab_size] labels: Tensor of size [batch_size, length_labels] smoothing: Label smoothing constant, used to det...
826a53fd6af931b33b7b7ac773310d2143db8597
3,623,938
from typing import List def get_neighboring_connectivity(cm: np.ndarray) -> List[float]: """ Get how strong neighboring classes are connected. Parameters ---------- cm : np.ndarray Returns ------- con : List[float] """ con = [] n = len(cm) for i in range(n - 1): ...
ba92b09ed1845eb5545d353df59f52f8032fab13
3,623,940
def autocov(x): """ Calculate the auto-covariance of a signal. This assumes that the signal is wide-sense stationary Parameters ---------- x: 1-d float array The signal Returns ------- nXn array (where n is x.shape[0]) with the autocovariance matrix of the signal x Not...
6f4f1855b9e0b4f237fbcaecdd911f51cf9c8707
3,623,941
def correlation(self, column_a, column_b): """ Calculate correlation for two columns of current frame. Parameters ---------- :param column_a: (str) The name of the column from which to compute the correlation. :param column_b: (str) The name of the column from which to compute the correlation....
b8f1600e0b2968ca4013418b2fbfda0b13f5911a
3,623,943
def get_ax(rows=1, cols=1, size=8): """Return a Matplotlib Axes array to be used in all visualizations in the notebook. Provide a central point to control graph sizes. Change the default size attribute to control the size of rendered images """ _, ax = plt.subplots(rows, cols, figsize=(size...
c5d16b65dc5e505143062c49847b54b1e84717e6
3,623,945
def multiply(a, b, out=None, increment=False, stream=None): """Element-wise product of `a` and `b`.""" dtype = a.dtype if out is None: out = gpuarray.zeros(a.shape, dtype=dtype) assert a.size == b.size assert a.dtype == b.dtype == out.dtype block = (min(a._block[0], a.size), 1, 1) ...
0886834e18d6c6ba7abab5e41943d752d9c8fd6c
3,623,947
import numpy as np def uv2spd_dir(u,v): """ converts u, v meteorological wind components to speed/direction where u is velocity from N and v is velocity from E (90 deg) usage spd, dir = uv2spd_dir(u, v) """ spd = np.zeros_like(u) dir = np.zeros_like(u) spd = np.sqrt(u**2 + v**2) ...
21525616f97974ba7463fe137f07ef7e7a728fe1
3,623,948
def adjacency_mat(x_all, y_all, ox, oy, rr): """ Function that creates the adjacency matrix from the edges and points with the no restriction method """ n = len(x_all) A = np.zeros((n, n)) road_map = [] for i in range(n): temp = [] for j in range(n): if i ==...
f66af74b37d8d2385720e71be31cef3446155afd
3,623,949
from typing import Counter def calcEOAutomorphisms(tree) : """ Computes the size of the automorphism group of the input :py:obj:`tree`. We think of :py:obj:`tree` as a rooted tree, whose vertices are decorated by degrees and which has additional "exterior" edges of two distinct types, corresponding to the bounda...
c10d579df582444339c0d0fe5859f37ed1bad4bd
3,623,951
def cisco_ios_simple_config(): """Creares raw cisco config of comments etc.""" with open( CISCO_IOS_SIMPLE_CONFIG_PATH, mode="r", errors="ignore", encoding="ascii" ) as config_file: raw_config = config_file.readlines() config = [] for line in raw_config: line = line.rstrip() ...
48e7177a99b5b2b2f196a9fff6f8e175f37dd389
3,623,952
def RRIMAPublicDashboard(request,id=0): """ :param request: :param id: :return: """ ## retrieve program model = Program program_id = id getProgram = Program.objects.all().filter(id=program_id) ## retrieve the coutries the user has data access for countries = getCountry(requ...
c5c9273d5017397eecdd99ee78bf318d45440f17
3,623,953
def get_workflows_requests(module): """Returns all requests for specified workflow""" return Request.objects.filter(module_ref=module)
6e634ded8f7c0b1dc147d276a8d9749205e9d991
3,623,954