content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def sort_keywords(scores): """ :param scores: A dictionary of lemmas and their corresponding scores, assigned by the pagerank algorithm :return: The same dictionary, sorted in descending order """ sorted_lemmas = [lemma for lemma in sorted(scores, key=scores.get, reverse=True)] return sorte...
ef4349976e755fb5d0d95b0ee98c5184fbf055f2
3,630,600
def DecodeControlTuples(ldapControlTuples,knownLDAPControls=None): """ Returns list of readily decoded ResponseControl objects ldapControlTuples Sequence-type of 3-tuples returned by _ldap.result4() containing the encoded ASN.1 control values of response controls. knownLDAPControls Dictionary...
d792ba07134b07d16881623123589709099a9a0c
3,630,601
def transform_geom( src_crs, dst_crs, geom, antimeridian_cutting=True, antimeridian_offset=10.0, precision=-1): """Transform geometry from source coordinate reference system into target. Parameters ------------ src_crs: CRS or dict Source coordina...
918d1018b9fcc591fa7c4761c0bfe4f3a394dddc
3,630,602
def part_one(data: str) -> int: """The best possible cookie score given the ingredient properties from data.""" total_quantity = 100 ingredients = [parse_ingredient(line) for line in data.splitlines()] # There are 4 ingredients total in the input, so nothing is lost here. quantities = [total_quantit...
3958414bffa0836c909c746cbbfa7ef9b01b35cc
3,630,603
import unittest def skip_if_quick(func): """Decorator to skip tests if quick option is used.""" @wraps(func) def wrapper(*args): # C0111: *Missing docstring* # pylint: disable=C0111 # W0212: *Access to a protected member %%s of a client class* # pylint: disable=W0212 ...
6b3bb6073b076e79d9795cf26b454783d7fcfcaf
3,630,604
def _build_edges(wave, sampling_type): """ Calculates edges of bins of given wavelength given the center value of the bin and the type of sampling. Parameters ---------- wave : numpy.ndarray Array with the wavelengths. sampling_type : string Sampling type of the array. It ca...
16c92dec058e895fa0be6cc2738ada23ba198099
3,630,605
def file_readlines(fn): """Open file with name `fn`, return open(fn).readlines().""" fd = open(fn, 'r') lst = fd.readlines() fd.close() return lst
2594e6763b566f4e83844f2f4457bcc8ea3663a5
3,630,606
import re def filter_table(table, **kwargs): """Retrieve the filtered rows Parameters ---------- table: astropy.table.Table, pandas.DataFrame The table to filter param: str The parameter to filter by, e.g. 'Teff' value: str, float, int, sequence The criteria to filter ...
50629e02c5e9ab6c17fcde1211b2a0a2c74570ca
3,630,607
def get_cached_skin_path(): """ Get the value of the #SKINSPATH# variable. This can be collected from various installation locations, since there are numerous ways to install Rainmeter. The easiest solution is, if the user tells Sublime Rainmeter, that he installed Rainmeter in a specific fold...
403e83a785620bb7291a89524646db75711f74fa
3,630,608
from typing import Callable import functools import inspect from typing import Hashable def func_dispatch(func: Callable = None, *, default: bool, clazz=None): """ Value-based dynamic-dispatch function decorator. Transforms a function into a dynamic dispatch function, which has different behaviors de...
af2dd4d389a26ba887cf4a34115a744fcff25534
3,630,609
import functools def access_controlled_app(app): """ An app where all the routes are access-controlled to the 'buyer' role, and there are some login routes if we need. """ login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def load_user(user_id): ...
638658711e02cc5d7fc51221a27a87099a264d38
3,630,610
def get_local_content_list(filename, encoding): """Return the file content with status""" textl = [] stat = False try: with open(filename, 'r', encoding=encoding) as f: textl = ''.join([f.read(), '\n']).splitlines() stat = True except Exception as e: log.excep...
c4171befc0b6107739d216b6854531956c2e2ac6
3,630,611
def check_pods_status(run_name: str, namespace: str, status: PodStatus, app_name: NAUTAAppNames = None) -> bool: """ Returns true if all pods related to a given run have given status. :param run_name: name of a run - obligatory :param namespace: namespace where run is located - obligatory :param sta...
6c8eed3a769976b4c8095bc93328c5ecc759778d
3,630,612
def retrieve_account(community, platform_type, platform_identifier, blah, community_platform_id=None): """Helper method to get a specific linked account.""" result = LinkedAccount.objects.filter(community=community, platform_type=platform_type, platform_identifier=platform_identifier) if community_p...
99ffa075668e374b84bd498008f16a79f1d294c4
3,630,613
import os def _read(obj): """ Try to read from a url, file or string. Parameters ---------- obj : str, unicode, or file-like Returns ------- raw_text : str """ if is_url(obj): with urlopen(obj) as url: text = url.read() elif hasattr(obj, "read"): ...
e6d82067203a1a7ef3a2143b30633f12dfa65fbc
3,630,614
def __leastsq_fit(tomo_data, weights=None, trace=None, beta=None): """ Reconstruct a state from unconstrained least-squares fitting. Args: tomo_data (list[dict]): state or process tomography data. weights (list or array or None): weights to use for least squares fitting. The def...
cc15c7e440ccf10f5e90c6daa27e6fb31a8f59c6
3,630,615
import http async def testpoint(mockserver: server.MockserverFixture) -> TestpointFixture: """Testpoint fixture returns testpoint session instance that works as decorator that registers testpoint handler. Original function is wrapped with :ref:`AsyncCallQueue` :param name: testpoint name :returns...
f9168902b4eb6074786062aba2a58e9cd083e4f8
3,630,616
def cfg(c=[], all=None): """returns parsed config for section <endpoint> - if not exists, builds it When interactive auth is requred we do not write - i.e. only valid for cur. session. To avoid frequent password queries, call GL.setup function. """ try: return c[0][FLG.endpoint_name] ...
6886df8163cce6b8df37e69e181d19e443770a53
3,630,617
from datetime import datetime def JIRATOSQLdatetimeformat(datetime_in): """ removes certain characters from fields returned by Jira requests, in order to facilitate insertion into SQL tables would need to be written differently for a production application, to handle escape characters etc. more intelligently par...
d75df0f925e4a3ed104ca98f8ef4ea0ae1d0557b
3,630,618
def _split_and_reshape_to_ndarrays(flat_v, sizes, shapes): """Split and reshape a single flat vector to make a list of ndarrays.""" xp = chainer.cuda.get_array_module(flat_v) sections = np.cumsum(sizes) vs = xp.split(flat_v, sections) return [v.reshape(shape) for v, shape in zip(vs, shapes)]
f388260cc9da0b2b8836248f109b12670e4aed57
3,630,619
from re import M import random def simSpikes(coef,M_k,M_h,dt): """ simSpikes- function to simulate """ print(np.exp(np.dot(M,coef))[1:10]) M = np.hstack(M_k,M_h) length = M.shape[0] print(length) tsp = [] jbin = 0 tspnext = random.expovariate(1) rprev = 0 n...
4a42e8eafe3c8a281c91d91399b411ea9761fcc1
3,630,620
import json def apply_lookup(dataframe, group_type): """ converts df[group_type] from ids to names dataframe : df group_type : string returns : df """ print("applying look up") print("working with {}".format(group_type)) df = dataframe.copy(deep=True) df[group_type] = ( ...
a41749555f106b4477414cc837f1c0cd56128acc
3,630,621
def make_url_parser(global_conf, directory, base_python_name, index_names=None, hide_extensions=None, ignore_extensions=None, **constructor_conf): """ Create a URLParser application that looks in ``directory``, which should be the directory for the...
2865a0adcdac1dd7879a9bf286ca91140c88945e
3,630,622
import os import yaml def get_user_labels_from_storage(label_storage_file: str) -> UserLabels: """ get all labels from label storage file Returns: UserLabels: all labels Raises: FileNotFoundError: if label storage file not found ValueError: if version mismatch Error: if p...
adb1024dcb6f09877c8d4f77fd502b7a716fdff6
3,630,623
def add_memo(): """ Insert a memo into the database. """ try: date = arrow.get(request.args.get('date', 0, type=str), 'YYYY/MM/DD').naive text = request.args.get('text', 0, type=str) record = {"type": "dated_memo", "date": date, ...
cc89826956d6b2e5dc9bed3276bf7e102f47b285
3,630,624
def items_JSON(): """Returns JSON object with all items""" # Get all items items = getItemAll(session) # Return JSON object return jsonify(Items=[i.serialize for i in items])
9e6d86c066054e2e567059fcc00f08c13c4fa797
3,630,625
def unescape(value, escape = "\\"): """ Unescapes the provided string value using the provided escape character as the reference for the unescape operation. This is considered to be a very expensive operation and so it should be used carefully. :type value: String :param value: The string ...
28aaebbfc5ea0022ce519a3ef91988504ea345f4
3,630,626
def __num_elems(shape): """Returns the number of elements in the given shape Args: shape: TensorShape Return: tot_elems: int """ tot_elems = 1 for s in shape: tot_elems *= int(s) return tot_elems
fd4f72394b22c98e6bedb545d7d11b8bfae11add
3,630,627
def ocrRawCaptcha(image): """ recognize a captcha from http://bkxk.xmu.edu.cn/xsxk/login.html without preprocessing :param image: image data of the captcha :return: a string with four character """ images, _ = processImg.processImg(image) result = ocrCaptchas(images) return result
672cb1fbd405cf4268971d87b17581563600fea4
3,630,628
from typing import Optional from typing import Any import json def read_JSON(path: OpenFile) -> Optional[Any]: """ Attempt to read a JSON file. Returns False if the file doesn't exist. :param path: the path of the file to read """ try: with open(path, "r") as f: return json.lo...
0403b2a3e891c82389ddbdcf1f13f58400cec0c8
3,630,629
def adoptionSearch(cursor, search): # search = data_params['search'] """Return the result based on Mo's search input""" lower_search = search.lower() query = f"SELECT DISTINCT Adopter.email, AdoptionApplication.application_num, AdoptionApplication.date, " \ f"AdoptionApplication.co_applicant...
22388799f65bef447c80c3da5c8f656705cba27e
3,630,630
def onc_datetime(date_time, timezone="Canada/Pacific"): """Return a string representation of a date/time in the particular ISO-8601 extended format required by the Ocean Networks Canada (ONC) data web services API. :arg date_time: Date/time to transform into format required by ONC d...
ac22065635dbba3eef6381eb464dee4cd8994c36
3,630,631
def req(retry=3, proxy=False, timeout=30, concurren=1): """ 通过装饰器来给出可选的配置。 """ def call(func): req = ReqParse(func, retry=retry, proxy=proxy, timeout=timeout, concurren=concurren) return req return call
dd02e6fb79e9333a07cf41c0e955ff7671fe1683
3,630,632
import sys def _read(f): """Read a file's contents, autodetecting whether the arg is a file or filename, and treating '-' as as indication to read from stdin.""" if type(f) is str: if f == "-": return sys.stdin.read() else: with open(f, "r") as ff: r...
51966b1a28d4c3d9b0bd037a8ffe037e901f58e5
3,630,633
import sys import os def find_utils(): """Find all the utilities used by this script""" utils = dict() for bin in ['xl', 'qemu-img', 'killall']: res = lookup_bin(bin) if not res: log.error('Cannot find required program: ' + str(bin)) sys.exit(1) utils[bin] ...
f62f8bf6d315808c315ce1d35a413a9bb5517588
3,630,634
def getHandValue(cards): """Returns value of cards.""" value = 0 numberOfAces = 0 for card in cards: rank = card[0] if rank == 'A': numberOfAces += 1 elif rank in ('K','Q','J'): value += 10 else: value += int(rank) value += number...
b40d45db627add8376ff9135229688114f81be83
3,630,635
from typing import Dict def zigzag(n: int = 8) -> Dict: """ ZigZag encoder & decoder Args: n: size of chunk Returns: dictionary of encoder and decoder """ idx_zigzag = [] for a in sorted((p % n + p // n, (p % n, p // n)[(p % n - p // n) % 2], p) for p in range(n * n)): ...
c3e67aa5e41030eafd09058413e40ac3bb1f3201
3,630,636
def get_lr(optimizer): """Get current learning rate Parameters ---------- optimizer : obj An optimizer object. Returns ------- lr Current learning rate. """ for param_group in optimizer.param_groups: return param_group["lr"]
d3636ab7e4c1e92c24de29aff02d95151a7f42e8
3,630,637
import requests def get_business_by_id(business_ids): """ Gets the business details for all the business_id's that are provided ( :param business_ids: This takes a single business id or a list of business ids :type business_ids: list :return: business :rtype: dict """ logger.info("Atte...
26161afc4b06da6572bcce28c82099fbf476e74e
3,630,638
import os import csv def load_target_class(input_dir): """Loads target classes.""" with tf.gfile.Open(os.path.join(input_dir, 'data.csv')) as f: return {row[0]: int(row[2]) for row in csv.reader(f)}
d23b9eeb717ab3c33efee9b42fcce7634899fa39
3,630,639
from federatedscope.core.lr import LogisticRegression from federatedscope.cross_backends import LogisticRegression from federatedscope.core.mlp import MLP from federatedscope.tabular.model import QuadraticModel from federatedscope.cv.model import get_cnn from federatedscope.nlp.model import get_rnn from federatedscope....
7740b62b23d2eb556210cccfc7b37d0db6e629d1
3,630,640
def twilio_secure(func): """Wrap a view function to ensure that every request comes from Twilio.""" @wraps(func) def wrapper(*a, **kw): if validate_twilio_request(): return func(*a, **kw) return Response("Not a valid Twilio request", status=403) return wrapper
364b5dcb34b626d207296417c719bb0d4ddc54e8
3,630,641
def get_batch_dataset(record_file, parser, config): """ 训练数据集TFRecordDataset的batch生成器。 Args: record_file: 训练数据tf_record路径 parser: 数据存储的格式 config: 超参数 """ num_threads = tf.constant(config.num_threads, dtype=tf.int32) dataset = tf.data.TFRecordDataset(record_file).map( ...
1e8ea8e8b7991d52b51d27245850a8abd7a486a6
3,630,642
from typing import Iterable from typing import Tuple from typing import List def find_bundles_rescalings( bundles: Iterable[InstanceBundle] ) -> Tuple[Tuple[List[InstanceBundle], Rescaling], ...]: """Finds a rescaling parameters for each subset of compatible instances. Args: bundles: Iterable...
44e3e5fd9ff563a3c4c906f0282e41ce1c4beba3
3,630,643
def get_ordinal_suffix(number): """Receives a number int and returns it appended with its ordinal suffix, so 1 -> 1st, 2 -> 2nd, 4 -> 4th, 11 -> 11th, etc. Rules: https://en.wikipedia.org/wiki/Ordinal_indicator#English - st is used with numbers ending in 1 (e.g. 1st, pronounced first)...
fc59e8586fa1df40b91c2922f52e4208ecc58038
3,630,644
def get_greppable(string): """Simply produces a string that -- when grepped -- will omit listing the grep process in a grep listing. """ return string.replace(string[0], '[%s]' % string[0], 1)
65be4daa5650605ca3d95720d74a7a1137b5f4d7
3,630,645
def is_convergent_pair(p, rules): """Is the critical pair convergent?""" u , v = p n1, n2 = list(normalforms(u, rules)), list(normalforms(v, rules)) return n1 == n2
e5e6790a98c5bb6fd6f3c6fb2e8b578d82d22d19
3,630,646
def is_userti(*args): """ is_userti(ea) -> bool """ return _ida_nalt.is_userti(*args)
8171b1bf071bf78306035008238d7ca96812409e
3,630,647
def players_player_id_get(player_id): # noqa: E501 """Retrieve a single player&#x27;s record Returns a player record # noqa: E501 :param player_id: ID of player to return :type player_id: str :rtype: Player """ return 'do some magic!'
d9c2c92dbba3d139b2b5188e8722a0add7668393
3,630,648
def zero_array(array): """ Method to zero an array of data with the initial values. :param array: Array of data - rows are time points, columns are signals. :return: Zero'd numpy array :rtype: np.ndarray """ init = array[:, 0] zerod = np.apply_along_axis(lambda x: x - init, 0, array) ...
79b51adb648f1fa56f6264079c8b24236c6e9714
3,630,649
from typing import Callable from typing import Sequence from typing import Hashable from typing import List def _stemmatological_costs_factory( max_del_len: int = 5, frag_start: float = 10.0, frag_end: float = 10.0 ) -> Callable: """ Define and return a function for computing candidate costs for a "stemma...
2be18ea378fb70b7efc511d3d5572ef8b7638a9c
3,630,650
def results_by_parameter(res, param, sort_by=None, sort_desc=False, crossvalid_use_measurment='validation', crossvalid_reduce=False, crossvalid_reduce_fn=None): """ Takes a list of evaluation results `res` returned by a LDA evaluation fu...
2ff2f4cc8edfb750bfa82b03e2d3f5cfea8646b5
3,630,651
def generate_case_study( sampling_method: NormalSamplingMethod, cmap: CommitMap, case_study_version: int, project_name: str, **kwargs: tp.Any ) -> CaseStudy: """ Generate a case study for a given project. This function will draw `num_samples` revisions from the history of the given project and ...
cd116a9cf1ae0b9eea55dde7f04ecc1d0fdeb47a
3,630,652
def is_checkbox(field): """ Boolean filter for form fields to determine if a field is using a checkbox widget. """ return isinstance(field.field.widget, forms.CheckboxInput)
e59b1f7692babd1d91752cf72c2fd51b6b9fac31
3,630,653
def build_info_str(username: str, name_len: int, remaining_chip: int, action: str, chip: int, is_waiting: bool, countdown: int) -> str: """Build a string to explain action of a user Args: username (str): user name name_len (int): characters to show the name remaining_...
1ecbb6c33d54a55500d51ce09cf9740ac28def96
3,630,654
from typing import Union from typing import List import sys import pathlib def main(argv: Union[List[str], None] = None) -> int: """Drive the derivation.""" argv = sys.argv[1:] if argv is None else argv if len(argv) != 0: print("Usage: indexer") return 2 alphabet = tuple('0123456789AB...
735fc90511fa0c8a734cfbac8e092e5eb29a3abc
3,630,655
def clustering_from_distance(dendrogram, distance): """ Given a dendrogram and a distance level, compute the partitions corresponding to the distance level Parameters ---------- dendrogram: numpy.array Each line of the dendrogram contains the merged nodes, the distance between merged n...
f4399e4dbe54b9cb9e9c3e786e8e11805ef0a75f
3,630,656
import torch def _loss_from_outputs_batch(loss_function, outputs_per_chunk, targets_per_chunk): """ Applies the loss function to batch of outputs (unpadded, masked) and batch of targets (padded, unmasked). :param loss_function: e.g., NLLLoss. :param outputs_per_chunk: a list of tensors, each the relev...
3f40b84c7b2a02b2b0315e338719fe6d78a6f1de
3,630,657
import os def dataInput(fileName): """Reads a line of data from a file and returns either a string for when there is only a single line of data or a list when there is more than one line. """ data = [] if os.path.isfile(fileName): file = open(fileName, "r") data = file.readline...
421f0a3661463d89d6f5edf001dcb798d78711a6
3,630,658
def equivPhkv(k,v,n): """ Checks if two values are the same and implicitly checks if id actually checks if two variables point to an object at the same memory location """ return equivValue(k,v,n) and referenceIdentity(n,v) and referenceIdentity(n.node,v.node)
87d1983123cf56d964adb6c6f0bc039d5a33b775
3,630,659
import numpy def get_spherical_bounding_box(lons, lats): """ Given a collection of points find and return the bounding box, as a pair of longitudes and a pair of latitudes. Parameters define longitudes and latitudes of a point collection respectively in a form of lists or numpy arrays. :retu...
6a66b6d42f993036258a73f6fe7783f1dcb6d701
3,630,660
def get_similarity_score(dict1, dict2, dissimilarity = False): """ The keys of dict1 and dict2 are all lowercase, you will NOT need to worry about case sensitivity. Args: dict1: frequency dictionary of words or n-grams for one text dict2: frequency dictionary of words or n-grams for ano...
31e8602d6ef098a58a8eaf497badebf2e19288eb
3,630,661
def predict_fn(input_data, model): """Predict using input and model""" return model(input_data)
00f7bf0bd71f70833f8f77b16ffa62559747e915
3,630,662
import os import pathlib import re import sys import base64 def solve_challenge(challenge): """ The parameter challenge comes in binary already """ global IA # 1) get the location of the certificates and keys SC = os.environ["SC"] if "SC" in os.environ else os.path.join(str(pathlib.Path.home()...
2a1f5944d529f4058dffb41186b6efa7bfbb94fd
3,630,663
def uniform_2_sphere(num: int = None): """Uniform sampling on a 2-sphere Source: https://gist.github.com/andrewbolster/10274979 Args: num: Number of vectors to sample (or None if single) Returns: Random Vector (np.ndarray) of size (num, 3) with norm 1. If num is None returned ...
097c65af0f24c1d20ee66c99723f413e6450b8f9
3,630,664
import torch def nce_past(z_next_trans_dist, z_next_enc): """ z_next_trans_dist: p(.|z, u) z_next_enc: samples from p(.|x') """ batch_size, z_dim = z_next_enc.size(0), z_next_enc.size(1) z_next_trans_dist_rep = repeat_dist(z_next_trans_dist, batch_size, z_dim) z_next_enc_rep = z_next_enc....
ad5c0206a1295dc32588464c519bead4d7591448
3,630,665
def plot_performance(barcode_counts, tick_label_size = 8, cbar_label_size = 5, dpi = 300, barcode_threshold = 1, absent_color = "black", present_color = "green", save = False, ...
c88f14ce7ea07473fe6b3d99d34a9823eb4580fe
3,630,666
def get_simple_countings(df, start_yr=START_YR, end_yr=END_YR): """Generates simple counting statistics for the criterias ports, authors, platforms, file extensions and types of exploits. It determines the 10 largest countings of each criteria. :param df (DataFrame): A DataFrame object. :param start...
e44ce1b7a0d9fe1e83726d52e8cd3f1eb90a50b7
3,630,667
from zine.application import get_application def get_engine(): """Return the active database engine (the database engine of the active application). If no application is enabled this has an undefined behavior. If you are not sure if the application is bound to the active thread, use :func:`~zine.appl...
2cfeb1aed8eceab4cc94db3e3619f6bcc12d59bd
3,630,668
def get_unnormalized_text(words): """ Returns the (unnormalized) text composed from the given words.""" return "".join([x.unnormalized_with_whitespaces for x in words])
162854d917ee4d49c3b2b824abc07697ac4f05ba
3,630,669
def getCurrentUsersHomePath(): """ Return the path to the users home directory. Usually C:/Users/<user> """ return (shell.SHGetFolderPath (0, shellcon.CSIDL_PROFILE, None, 0))
f6f637028bbf6b6dd6eb976e7ed81b460173b4eb
3,630,670
import re def alpha_num_order(string: str) -> str: """Returns all numbers on 5 digits to let sort the string with numeric order. Ex: alphaNumOrder("a6b12.125") ==> "a00006b00012.00125" """ return "".join( [ format(int(x), "05d") if x.isdigit() else x for x in re.split(...
01d49320c30f232163198ae8e88a11e4dfbc611f
3,630,671
import logging import os import sys def setup_logging_streams(model, log_to_file=True, log_to_stdout=False): """Utility function for setting up logging handlers for `model`.""" formatter = logging.Formatter( '[%(name)s][%(asctime)s][%(levelname)s]: %(message)s', datefmt='%m:%d:%Y:%I:%M:%S' ...
c656a59d54f903398269214e65170db59bfcc632
3,630,672
import tempfile import logging import sys def setup_logger(): """Set up the logger output. """ def get_console_handler(stream_level="INFO"): console_handler = logging.StreamHandler() console_handler.setLevel(level=getattr(logging, stream_level)) console_handler.setFormatter(FORMAT...
48c44a14b45399772c751a90b664b2f722d63b17
3,630,673
import requests def _web_services_request(endpoint, params, method='GET'): """ Perform a request on an NYC.ID Web Services endpoint. 'userName' and 'signature' are added to the specified params. :param endpoint: web services endpoint (e.g. "/account/validateEmail.htm") :param params: request para...
745a93616cc8fa1bc5a275f7abf3c000c5635af4
3,630,674
import os def write_nk_file(target_dir, target_name, data): """ Args: target_dir(str): must be in an existing directory target_name(str): name of the file without the extension data(str): Returns: str: path the file has been written to. """ target_path = os.path.j...
47b0959fa7fa81316eb10569a73f7728eccd0a12
3,630,675
def dihedral_group(n): """ Return the dihedral group S_n. >>> from qitensor import dihedral_group >>> S3 = dihedral_group(3) >>> S3.order 6 >>> S3.elements [<S3.r0>, <S3.r1>, <S3.r2>, <S3.s0>, <S3.s1>, <S3.s2>] >>> S3.e <S3.r0> >>> S3.r1 * S3.s0 <S3.s1> >>> import p...
9045d3d417f5aea2b6e118fd2ad7f054a194c308
3,630,676
def _half(X): """Returns the lower triangular part of a matrix with half of diagonal part. Args: X: tensor of shape (..., m, m). Returns: tensor of shape (..., m, m), a set of matrices with half of diagonal and without upper triangular parts.""" dim = tf.shape(X)[-1] d...
3f52e2c4a289fc9d14ba8e9c9c42c3d3a22a7b28
3,630,677
def multipart_encode_for_requests(params, boundary=None, cb=None): """streams uploads instead of loading entire file into memory""" datagen, headers = multipart_encode(params, boundary, cb) return IterableToFileAdapter(datagen), headers
859c07b9af80b4df3267900276ab1c0506d42355
3,630,678
import json def get_ability_icons(champion, input_path): """ This function takes a champion and input path strings as input and returns a dictionary of png file paths with keys corresponding to the following abilities: Passive, Q, W, E, and R """ global ability_icon_paths ability_icon_pa...
e33c01bedcd8bf20959978df2bc2b33b934e2181
3,630,679
import json def build_json_response(data, response_code='200 OK'): """ data (str | dict) : JSON encodable data response_code (str) : HTTP response code ---- Return (bytes) HTTP response of JSON-encoded data. """ if type(data) == str: data = json.loads(data) elif type(data) ==...
ca2e19fbcaea7811c45d984540f2b03d21a1ce87
3,630,680
import math def eval_biot_savart(xcp0, xnode1, xnode2, gamma, l0, delta_visc=0.025): """ This function uses the Biot-Savart law to evaluate the induced velocities at control points (xcp), due to vortex line elements defined by locations xnode1, xnode2, with strengths gamme and lengths l0. The delta_v...
01595ad9eb5977f39ebe916f733746f8789e4bd0
3,630,681
import inspect def validate_params(func): """ @note: validate decorator """ def _decorator(*args, **kwargs): def _get_param_items(func, args, kwargs): parameters = inspect.signature(func).parameters arg_keys = tuple(parameters.keys()) vparams = [k for k, v...
ae0eb32347a3916f657653b1d8fda4ddd3292e44
3,630,682
def techniques_used(technique_list, technique): """ Add technique to technique list and make distinction between techniques subtechniques """ attack_id = util.buildhelpers.get_attack_id(technique['object']) has_subtechniques = False if attack_id: # Check if technique not already in...
b1132f1bdf2abc0084a284ef891fd78b716a602b
3,630,683
def admin_view_semesters_of_a_curriculum(request, curriculum_id): """ gets all the semesters of a specfic curriculum """ curriculum = Curriculum.objects.get(id=curriculum_id) semesters = Curriculum.get_semesters_objects(curriculum) semester_slots = [] for sem in semesters: a = list(Semester...
60be9bad528d4e144bc53370719b94b0692716c2
3,630,684
import requests import os def fetch_lightcurve_dr2(gaia_id, output_dir='../data/'): """ Fetch Gaia Lightcurve for a Gaia Source ID (of a variable star) from Gaia DR2 Data Link Returns path of csv file stored for given source Args: gaia_id (string): String. Gaia Source ID of the variable ...
18fb18ccb7cfcd2bbb8f826cbdf592ca59356ef9
3,630,685
from typing import Awaitable from re import T async def _aw_to_coro(aw: Awaitable[T]) -> T: """Wrap a given awaitable so it appears as a coroutine.""" return await aw
5ac8301fa23fb9c231bfb68be43cee70cdeb8b8e
3,630,686
from typing import Union def get_text_recursive(tag: Union[Tag, NavigableString, None]) -> str: """Extract the text using the childrens.""" if tag is None: return "" if isinstance(tag, NavigableString): return str(tag).strip().replace("\n", " ") tag_name = tag.name # Special tags...
012019d845825f6cdba4d2d1883cd0b3940cd4d3
3,630,687
def _l1_regularization(l1, model): """Computes the L1 regularization for the given model Args: l1 (float): L1 parameter model (:obj:`torch.nn.Module`): Model to use Returns: float: L1 loss (i.e. l1 * l1_norm(params)) """ l1_loss = sum(param.norm(1) for param in model.parame...
32826672a7de00f8a0412e2496e6ebfea213b502
3,630,688
def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return Conv2D(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias_attr=False)
55a4e869297ed1faccdabfcddae6a61855a67efb
3,630,689
import torch def create_feature_extractor(model, device=None): """ Factory function for creating an evaluator for supervised models Args: model (`torch.nn.Module`): the model to evaluate device (str, optional): device type specification (default: None). Applies to bo...
d39bf294c7a667e6319eda27b4436c4ce6688d65
3,630,690
def callit(iteratee, *args, **kwargs): """Inspect argspec of `iteratee` function and only pass the supported arguments when calling it.""" maxargs = len(args) argcount = kwargs["argcount"] if "argcount" in kwargs else getargcount(iteratee, maxargs) argstop = min([maxargs, argcount]) return iter...
2a23ad787929e7f50e6a38447c2a6fc458fc528e
3,630,691
def get_doc_tokens(paragraph_text): """Tokenize the given paragraph and return character to word token offset for answer ranges""" doc_tokens = [] char_to_word_offset = [] prev_is_whitespace = True for c in paragraph_text: if is_whitespace(c): prev_is_whitespace = True el...
bbe0374877ee19f2d9c31298f84201e8c5261a13
3,630,692
def ispython(script_path): """ Check to see if file is a python script file by extension :param script_path: :return: """ return hasextension(script_path, ".py")
2d2c13df1eff659fb12c502b64eb5ed81b04466e
3,630,693
def num_to_name(num): """ (int) -> str Get IO pin name from its numeric identifier >> num_to_name(8) gpio_8 >> num_to_name(107) D7 >>num_to_name(115) A1 """ # Pi pin numeric identifiers are the actual GPIO number if num <= 27: pname = "gpio_" + str(num) # 100 ...
202a7be3831ad9adbca68a3ff46587775b467ca2
3,630,694
import os def load_cifar_datasets(data_dir): """Load CIFAR10 and SVHN dataset from np array.""" tr_in = load_tfdata_from_np(os.path.join(data_dir, 'cifar10_train.npy')) val_in = load_tfdata_from_np(os.path.join(data_dir, 'cifar10_val.npy')) test_in = load_tfdata_from_np(os.path.join(data_dir, 'cifar10_test.np...
6e1af6bc036dcc5cfebe6be54db0c714646948e6
3,630,695
def ConnectToDb_Return_Df_table(id,pwd,host,db_name,table_name): """ This method will Connect to Data base and return the requested table in the form of a dataframe Better to make it a singleton to ensure multiple db connections are not spawned :param id: :param pwd: :param host: :param db_n...
af1fca9a0c7cacd22bb9fbb032eee0599b7158bd
3,630,696
from typing import List from sys import path def update_model( model_artifact, parameters: dict = None, metrics: dict = None, extra_data: dict = None, inputs: List[Feature] = None, outputs: List[Feature] = None, feature_vector: str = None, feature_weights: list = None, key_prefix: ...
0d3d7fdb152614fc7269356819cb302c3cbef8e0
3,630,697
import os import sys from io import StringIO import traceback def runscript(scriptname, args, in_directory=None, fail_ok=False, sandbox=False): """Run a Python script using exec(). Run the given Python script, with the given args, in the given directory, using 'exec'. Mimic proper shell fu...
51296e78ceb41c3f30454baef0f74a1e3ee45658
3,630,698
def n_prop_vs_rec(sorted_props, gt, n=100): """ sort n proposals by their score. returns #proposals vs. recall -> [[a], [b], ..., [n]] a = recall for 1 proposal b = recall for 2 proposals . . . n = recall for (n+1) proposals :param sorted_props: [[prop_0], [prop_1], ...
558c4fcccd08329ed97b1dbbba87b8d8fca883e8
3,630,699