content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Any def build_get301_request(**kwargs: Any) -> HttpRequest: """Return 301 status code and redirect to /http/success/200. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. :return: Returns an :class:`~azure.core.res...
2ef01a4c126890fd30fd3bc656036b92d2ef0408
20,434
def error_function_latticeparameters(varying_parameters_values_array, varying_parameters_keys, Miller_indices, allparameters, absolutespotsindices, ...
e1c3242855354ed82d2dd164a7ae16aa76cd5e22
20,435
def run_forward_model(z_in): """ Run forward model and return approximate measured values """ x_dummy[:prm.nn]=z_in x_dummy[prm.nn:]=prm.compute_velocity(z_in,t0) x_meas = H_meas.dot(x_dummy) return x_meas
fd6bfbbacba59e08b2bb8c4588793b969cab4b60
20,436
def optimize(name: str, circuit: cirq.Circuit) -> cirq.Circuit: """Applies sycamore circuit decompositions/optimizations. Args: name: the name of the circuit for printing messages circuit: the circuit to optimize_for_sycamore """ print(f'optimizing: {name}', flush=True) start = time...
07027dc2ad21e33ca2038cb40c3cbb2b529941e7
20,437
def download_sbr(destination=None): """Download an example of SBR+ Array and return the def path. Examples files are downloaded to a persistent cache to avoid re-downloading the same file twice. Parameters ---------- destination : str, optional Path where files will be downloaded. Opti...
0b928977806b546325569dbf71e93e8b760868fa
20,438
from typing import Tuple from typing import Union def isvalid_sequence( level: str, time_series: Tuple[Union[HSScoring, CollegeScoring]] ) -> bool: """Checks if entire sequence is valid. Args: level: 'high school' or 'college' level for sequence analysis. time_series: Tuple of sorted ...
5e32906408540c504347c745113fc303ef0d989b
20,439
def non_linear_relationships(): """Plot logarithmic and exponential data along with correlation coefficients.""" # make subplots fig, axes = plt.subplots(1, 2, figsize=(12, 3)) # plot logarithmic log_x = np.linspace(0.01, 10) log_y = np.log(log_x) axes[0].scatter(log_x, log_y) axes[0].s...
86ce934aebc6b6f8e6b5c1826d9d26c408efc8df
20,441
import io def label_samples(annotation, atlas, atlas_info=None, tolerance=2): """ Matches all microarray samples in `annotation` to parcels in `atlas` Attempts to place each sample provided in `annotation` into a parcel in `atlas`, where the latter is a 3D niimg-like object that contains parcels ...
65a3f83b031871a14b250df48c9edef3cdcce7ac
20,442
def group_by(x, group_by_fields='Event', return_group_indices=False): """ Splits x into LIST of arrays, each array with rows that have same group_by_fields values. Gotchas: Assumes x is sorted by group_by_fields (works in either order, reversed or not) Does NOT put in empty lists...
12e8034556ca303a9ebd2ccaab83cbcc131b0bec
20,443
def unlock_file(fd): """unlock file. """ try: fcntl.flock(fd, fcntl.LOCK_UN) return (True, 0) except IOError, ex_value: return (False, ex_value[0])
2c6ce071072fa45607ce284b0881af5df44b5e6d
20,444
def DsseTrad(nodes_num, measurements, Gmatrix, Bmatrix, Yabs_matrix, Yphase_matrix): """ Traditional state estimator It performs state estimation using rectangular node voltage state variables and it is customized to work without PMU measurements @param nodes_num: number of nodes of the grid @p...
9e662255875970fc8df38c29e728637e53a30db5
20,445
def _get_specs(layout, surfs, array_name, cbar_range, nvals=256): """Get array specifications. Parameters ---------- layout : ndarray, shape = (n_rows, n_cols) Array of surface keys in `surfs`. Specifies how window is arranged. surfs : dict[str, BSPolyData] Dictionary of surfaces. ...
310208c5bd8db46d37635fa8e2fcd8422a753a1b
20,446
def upper_camel_to_lower_camel(upper_camel: str) -> str: """convert upper camel case to lower camel case Example: CamelCase -> camelCase :param upper_camel: :return: """ return upper_camel[0].lower() + upper_camel[1:]
e731bbee45f5fc3d8e3e218837ccd36c00eff734
20,448
def get(isamAppliance, cert_dbase_id, check_mode=False, force=False): """ Get details of a certificate database """ return isamAppliance.invoke_get("Retrieving all current certificate database names", "/isam/ssl_certificates/{0}/details".format(cert_dbase_id))
34ade7c42fcc1b1409b315f8748105ee99157986
20,449
def model_check(func): """Checks if the model is referenced as a valid model. If the model is valid, the API will be ready to find the correct endpoint for the given model. :param func: The function to decorate :type func: function """ def wrapper(*args, **kwargs): model = None ...
809d7659a721ad6dedf4a651dd1fdab1b1dbf51e
20,450
def content_loss_func(sess, model): """Content loss function defined in the paper.""" def _content_loss(p, x): # N is the number of filters at layer 1 N = p.shape[3] # M is the height * width of the feature map at layer 1 M = p.shape[1] * p.shape[2] return (1 / (4 * N * ...
229866eaaf6021e7a078460dc29a6f0bfaa853bd
20,451
import joblib def Extract_from_DF_kmeans(dfdir,num,mode=True): """ PlaneDFを読み込んで、client_IP毎に該当index番号の羅列をそれぞれのtxtに書き出す modeがFalseのときはシーケンスが既にあっても上書き作成 """ flag = exists("Database/KMeans/km_full_"+dfdir+"_database_name")#namelistが存在するかどうか if(flag and mode):return plane_df =...
cb086c07024716022343c7e8eb5755f2de3695db
20,452
from typing import Optional def get_workspace(workspace_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetWorkspaceResult: """ Resource schema for AWS::IoTTwinMaker::Workspace :param str workspace_id: The ID of the workspace. """ __args__ = d...
5c0970884be38923ae156511faf619fda725d004
20,453
import socket def find_open_port(): """ Use socket's built in ability to find an open port. """ sock = socket.socket() sock.bind(('', 0)) host, port = sock.getsockname() return port
516540fd23259d0fe247e02c4058c5ed7f3ee3a8
20,454
import itertools def split_list_round_robin(data: tp.Iterable, chunks_num: int) -> tp.List[list]: """Divide iterable into `chunks_num` lists""" result = [[] for _ in range(chunks_num)] chunk_indexes = itertools.cycle(i for i in range(chunks_num)) for item in data: i = next(chunk_indexes) ...
a87322b2c6a3601cda6c949354e55c38e215289a
20,455
def calc_Q_loss_FH_d_t(Q_T_H_FH_d_t, r_up): """温水床暖房の放熱損失 Args: Q_T_H_FH_d_t(ndarray): 温水暖房の処理暖房負荷 [MJ/h] r_up(ndarray): 当該住戸の温水床暖房の上面放熱率 [-] Returns: ndarray: 温水床暖房の放熱損失 """ return hwfloor.get_Q_loss_rad(Q_T_H_rad=Q_T_H_FH_d_t, r_up=r_up)
04ad561fa0090de2eb64d5514a28729da92af63c
20,456
import random def t06_ManyGetPuts(C, pks, crypto, server): """Many clients upload many files and their contents are checked.""" clients = [C("c" + str(n)) for n in range(10)] kvs = [{} for _ in range(10)] for _ in range(200): i = random.randint(0, 9) uuid1 = "%08x" % random.randint(...
384aa2b03169da613b25d2da60cdd1ec007aeed5
20,458
def multi_lightness_function_plot(functions=None, **kwargs): """ Plots given *Lightness* functions. Parameters ---------- functions : array_like, optional *Lightness* functions to plot. \*\*kwargs : \*\* Keywords arguments. Returns ------- bool Definition su...
18a4706d919c5b8822ff76a40dcd657028a6179b
20,459
def delete_notification(request): """ Creates a Notification model based on uer input. """ print request.POST # Notification's PK Notification.objects.get(pk=int(request.POST["pk"])).delete() return JsonResponse({})
c4750bfbaa8184e64293517689671dbf717e6cd4
20,460
from dateutil import tz def parse_query_value(query_str): """ Return value for the query string """ try: query_str = str(query_str).strip('"\' ') if query_str == 'now': d = Delorean(timezone=tz) elif query_str.startswith('y'): d = Delorean(Delorean(timezone=tz)....
ac9c6845871094d043eee7004214fdcecb20daec
20,461
def build_model(): """ Build the model :return: the model """ model = keras.Sequential([ layers.Dense(64, activation='relu', input_shape=[len(train_dataset.keys())]), layers.Dense(64, activation='relu'), layers.Dense(1) ]) optimizer = tf.keras.optimizers.RMSprop(0.00...
b5e4b0a64e7d39a0c7b72c0380ef98d8eaf9cc01
20,462
def detect(stream): """Returns True if given stream is a readable excel file.""" try: opendocument.load(BytesIO(stream)) return True except: pass
a9ef5361d9f6f5ae40767f40f12b89c3d53177a4
20,463
def new_default_channel(): """Create new gRPC channel from settings.""" channel_url = urlparse(format_url(settings.SERVICE_BIND)) return Channel(host=channel_url.hostname, port=channel_url.port)
4771306570213fa03cc5df08a0e8c9b216ecfd44
20,464
def iou(bbox1, bbox2): """ Calculates the intersection-over-union of two bounding boxes. Args: bbox1 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2. bbox2 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2. Returns: int: intersection-over-onion o...
7609bcc6eb39757240a22c28fc7c15f4024cd789
20,465
def get_version(): """ Obtain the version of the ITU-R P.1511 recommendation currently being used. Returns ------- version: int Version currently being used. """ return __model.__version__
4d36eacabebe74bfb18879ba64f190ceb1bbc22a
20,466
import copy def sample_filepaths(filepaths_in, filepaths_out, intensity): """ `filepaths_in` is a list of filepaths for in-set examples. `filepaths_out` is a list of lists, where `filepaths_out[i]` is a list of filepaths corresponding to the ith out-of-set class. `intensity` is the number of i...
b20c1e1a019eaebc0eb7ea46b33c286b72da7af7
20,467
def makekey(s): """ enerates a bitcoin private key from a secret s """ return CBitcoinSecret.from_secret_bytes(sha256(s).digest())
51658c6426a78ae2e20752542bc579f5bb7ebc01
20,468
def shape_broadcast(shape1: tuple, shape2: tuple) -> tuple: """ Broadcast two shapes to create a new union shape. Args: shape1 (tuple) : first shape shape2 (tuple) : second shape Returns: tuple : broadcasted shape Raises: IndexingError : if cannot broadcast """...
4737332b371e0f16df3860d5c53e46718f68f30e
20,469
import xxhash def hash_array(kmer): """Return a hash of a numpy array.""" return xxhash.xxh32_intdigest(kmer.tobytes())
9761316333fdd9f28e74c4f1975adfca1909f54a
20,470
def GenerateDiskTemplate( lu, template_name, instance_uuid, primary_node_uuid, secondary_node_uuids, disk_info, file_storage_dir, file_driver, base_index, feedback_fn, full_disk_params): """Generate the entire disk layout for a given template type. """ vgname = lu.cfg.GetVGName() disk_count = len(disk_in...
87995b08d3579fc22a8db7c8408a9c29e47a8271
20,471
def check_pc_overlap(pc1, pc2, min_point_num): """ Check if the bounding boxes of the 2 given point clouds overlap """ b1 = get_pc_bbox(pc1) b2 = get_pc_bbox(pc2) b1_c = Polygon(b1) b2_c = Polygon(b2) inter_area = b1_c.intersection(b2_c).area union_area = b1_c.area + b2_c.area - int...
8caa07a42850d9ca2a4d298e9be91a44ac15f6a5
20,472
def apply_hypercube(cube: DataCube, context: dict) -> DataCube: """Reduce the time dimension for each tile and compute min, mean, max and sum for each pixel over time. Each raster tile in the udf data object will be reduced by time. Minimum, maximum, mean and sum are computed for each pixel over time. ...
c2c3b7b90a48a37f5e172111ef13e8529a3a80c5
20,473
def dateIsBefore(year1, month1, day1, year2, month2, day2): """Returns True if year1-month1-day1 is before year2-month2-day2. Otherwise, returns False.""" if year1 < year2: return True if year1 == year2: if month1 < month2: return True if month1 == month2: if ...
3ba19b6e57c8e51a86e590561331057a44885d10
20,474
def all_stat(x, stat_func=np.mean, upper_only=False, stat_offset=3): """ Generate a matrix that contains the value returned by stat_func for all possible sub-windows of x[stat_offset:]. stat_func is any function that takes a sequence and returns a scalar. if upper_only is False, values are added t...
16ef240b33a477948ae99862bb21540a230a8a2f
20,475
def PyCallable_Check(space, w_obj): """Determine if the object o is callable. Return 1 if the object is callable and 0 otherwise. This function always succeeds.""" return int(space.is_true(space.callable(w_obj)))
e5b8ee9bbbdb0fe53d6fc7241d19f93f7ee8259a
20,476
from typing import Callable def _multiclass_metric_evaluator(metric_func: Callable[..., float], n_classes: int, y_test: np.ndarray, y_pred: np.ndarray, **kwargs) -> float: """Calculate the average metric for multiclass classifiers.""" metric = 0 for label in range(n_class...
a8a61c7a2e3629ff69a6a2aefdb4565e903b82de
20,477
def idxs_of_duplicates(lst): """ Returns the indices of duplicate values. """ idxs_of = dict({}) dup_idxs = [] for idx, value in enumerate(lst): idxs_of.setdefault(value, []).append(idx) for idxs in idxs_of.values(): if len(idxs) > 1: dup_idxs.extend(idxs) return ...
adc8a0b0223ac78f0c8a6edd3d60acfaf7ca4c04
20,479
async def store_rekey( handle: StoreHandle, wrap_method: str = None, pass_key: str = None, ) -> StoreHandle: """Replace the wrap key on a Store.""" return await do_call_async( "askar_store_rekey", handle, encode_str(wrap_method and wrap_method.lower()), encode_str(pas...
e7abb35147bd7b5be5aa37b6583571e5be8f144b
20,480
import requests def prepare_bitbucket_data(data, profile_data, team_name): """ Prepare bitbucket data by extracting information needed if the data contains next page for this team/organisation continue to fetch the next page until the last page """ next_page = False link = None profil...
a2fe54a4fd02e80b4bf4d41ff932e27b555afc5c
20,481
def add(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.add <numpy.add>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in add") # C...
7c35ea06f5bff91da283e3521185a6b9f1b55b32
20,482
def aslist(l): """Convenience function to wrap single items and lists, and return lists unchanged.""" if isinstance(l, list): return l else: return [l]
99ccef940229d806d27cb8e429da9c85c44fed07
20,483
def getKeyList(rootFile,pathSplit): """ Get the list of keys of the directory (rootFile,pathSplit), if (rootFile,pathSplit) is not a directory then get the key in a list """ if isDirectory(rootFile,pathSplit): changeDirectory(rootFile,pathSplit) return ROOT.gDirectory.GetListOfKeys()...
69d51a496ec77e00753518fee7ae8a0e5b9e7c9a
20,485
from typing import Any def query_from_json(query_json: Any, client: cl.Client = None): """ The function converts a dictionary or json string of Query to a Query object. :param query_json: A dictionary or json string that contains the keys of a Query. :type query_json:...
58d1b1f3efedf0b74a0136d1edd1da13bf16bf8c
20,487
def fetch_validation_annotations(): """ Returns the validation annotations Returns: complete_annotations: array of annotation data - [n_annotations, 4] row format is [T, X, Y, Z] """ ann_gen = _annotation_generator() data = [] for annotation in ann_gen: if annotation[0] in...
1b9a8b86bbc005c79b152e1f59e653b7711e674f
20,489
def enough_data(train_data, test_data, verbose=False): """Check if train and test sets have any elements.""" if train_data.empty: if verbose: print('Empty training data\n') return False if test_data.empty: if verbose: print('Empty testing data\n') retu...
f11014d83379a5df84a67ee3b8f1e85b23c058f7
20,490
def calculate_tidal_offset(TIDE, GM, R, refell): """ Calculates the spherical harmonic offset for a tide system to change from a tide free state where there is no permanent direct and indirect tidal potentials Arguments --------- TIDE: output tidal system R: average radius used ...
278b27b2a1378cf0ccb44055a37baf9def7d6c6a
20,492
def get_questions(set_id, default_txt=None): """Method to get set of questions list.""" try: cache_key = 'question_list_%s' % (set_id) cache_list = cache.get(cache_key) if cache_list: v_list = cache_list print('FROM Cache %s' % (cache_key)) else: ...
0153ab71caa705f7a4f2a07ce5ef210b02618dd4
20,493
def get_mms_operation(workspace, operation_id): """ Retrieve the operation payload from MMS. :return: The json encoded content of the reponse. :rtype: dict """ response = make_mms_request(workspace, 'GET', '/operations/' + operation_id, None) return response.json()
c88aca93803ab5075a217a10b7782ae791f168bc
20,495
def _check_data_nan(data): """Ensure data compatibility for the series received by the smoother. (Without checking for inf and nans). Returns ------- data : array Checked input. """ data = np.asarray(data) if np.prod(data.shape) == np.max(data.shape): data = data.ravel...
1cde49f2836405deb0c1328d5ce53c69ffbcb721
20,496
def function(row, args): """Execute a named function function(arg, arg...) @param row: the HXL data row @param args: the arguments parsed (the first one is the function name) @returns: the result of executing the function on the arguments """ f = FUNCTIONS.get(args[0]) if f: retu...
3b6e2e20c09c6cefebb4998d40376ff1b1aa63f2
20,497
def extract_rfc2822_addresses(text): """Returns a list of valid RFC2822 addresses that can be found in ``source``, ignoring malformed ones and non-ASCII ones. """ if not text: return [] candidates = address_pattern.findall(tools.ustr(text).encode('utf-8')) return filter(try_coerce_asc...
b256bd585a30900e09a63f0cc29889044da8e0e0
20,499
def set_edge_font_size_mapping(table_column, table_column_values=None, sizes=None, mapping_type='c', default_size=None, style_name=None, network=None, base_url=DEFAULT_BASE_URL): """Map table column values to sizes to set the edge size. Args: table_column (str): Name of C...
7360f57d1e4921d58eaf5af4e57a6c5f636fefdb
20,500
def compute_time_overlap(appointment1, appointment2): """ Compare two appointments on the same day """ assert appointment1.date_ == appointment2.date_ print("Checking for time overlap on \"{}\"...". format(appointment1.date_)) print("Times to check: {}, {}". format(appointmen...
c459ef52d78bc8dd094d5be9c9f4f035c4f9fcaa
20,501
def set_up_prior(data, params): """ Function to create prior distribution from data Parameters ---------- data: dict catalog dictionary containing bin endpoints, log interim prior, and log interim posteriors params: dict dictionary of parameter values for creation of pri...
eb75965b9425bbf9fe3a33b7f0c850e27e2d454a
20,502
def is_nonincreasing(arr): """ Returns true if the sequence is non-increasing. """ return all([x >= y for x, y in zip(arr, arr[1:])])
6d78ef5f68ca93767f3e204dfea2c2be8b3040af
20,503
def restore_missing_features(nonmissing_X, missing_features): """Insert columns corresponding to missing features. Parameters ---------- nonmissing_X : array-like, shape (n_samples, n_nonmissing) Array containing data with missing features removed. missing_features : array-like, shape (n_m...
733fd72d36ea86269472949eaa12a306835578f9
20,504
def get_sample_type_from_recipe(recipe): """Retrieves sample type from recipe Args: recipe: Recipe of the project Returns: sample_type_mapping, dic: Sample type of the project For Example: { TYPE: "RNA" } , { TYPE: "DNA" }, { TYPE: "WGS" } """ return find_mapping(recipe_type_mapping, recipe)
57cef2f592d530ad15aed47cc51da4441430f3d2
20,505
import yaml def _is_download_necessary(path, response): """Check whether a download is necessary. There three criteria. 1. If the file is missing, download it. 2. The following two checks depend on each other. 1. Some files have an entry in the header which specifies when the file was ...
69cd2778fb6d4706ff88bd35c1b5c1abda9a39ba
20,506
import hashlib def hash64(s): """Вычисляет хеш - 8 символов (64 бита) """ hex = hashlib.sha1(s.encode("utf-8")).hexdigest() return "{:x}".format(int(hex, 16) % (10 ** 8))
e35a367eac938fdb66584b52e1e8da59582fdb9a
20,507
def course_runs(): """Fixture for a set of CourseRuns in the database""" return CourseRunFactory.create_batch(3)
1ffd4efe008e44f9e2828c9128acfe3cdafb5160
20,508
import json def _response(data=None, status_code=None): """Build a mocked response for use with the requests library.""" response = MagicMock() if data: response.json = MagicMock(return_value=json.loads(data)) if status_code: response.status_code = status_code response.raise_for_st...
0ccd38a954d28a4f010becc68319b49896323de0
20,509
def findtailthreshold(v, figpath=None): """ function [f,mns,sds,gmfit] = findtailthreshold(v,wantfig) <v> is a vector of values <wantfig> (optional) is whether to plot a diagnostic figure. Default: 1. Fit a Gaussian Mixture Model (with n=2) to the data and find the point that is greater t...
8ef0c3267582d604621bd98fa7c81976b76b2c51
20,510
from typing import Optional from typing import Dict import asyncio async def make_request_and_envelope_response( app: web.Application, method: str, url: URL, headers: Optional[Dict[str, str]] = None, data: Optional[bytes] = None, ) -> web.Response: """ Helper to forward a request to the ca...
22d18de671cc84d3471120273a7b0599fda26210
20,511
def get_provincial_miif_sets(munis): """ collect set of indicator values for each province, MIIF category and year returns dict of the form { 'cash_coverage': { 'FS': { 'B1': { '2015': [{'result': ...}] } } } } """ prov_sets = defaultdi...
a4484a40a30f8fe9e702735f6eccf78c395ea446
20,513
def create_kernel(radius=2, invert=False): """Define a kernel""" if invert: value = 0 k = np.ones((2*radius+1, 2*radius+1)) else: value = 1 k = np.zeros((2*radius+1, 2*radius+1)) y,x = np.ogrid[-radius:radius+1, -radius:radius+1] mask = x**2 ...
33bbfa6141eb722180ffa9111555e4e00fbdac6a
20,514
def edimax_get_power(ip_addr="192.168.178.137"): """ Quelle http://sun-watch.net/index.php/eigenverbrauch/ipschalter/edimax-protokoll/ """ req = """<?xml version="1.0" encoding="UTF8"?><SMARTPLUG id="edimax"><CMD id="get"> <NOW_POWER><Device.System.Power.NowCurrent> </Device.System.Power.No...
9de1720f00ca4194b66f79048314bac1cac950ed
20,515
import torch def get_class_inst_data_params_n_optimizer(nr_classes, nr_instances, device): """Returns class and instance level data parameters and their corresponding optimizers. Args: nr_classes (int): number of classes in dataset. nr_instances (int): number of instances in dataset. ...
f97e12b99a42f32bb3629df5567ca44477d71dc0
20,516
def inc(x): """ Add one to the current value """ return x + 1
c8f9a68fee2e8c1a1d66502ae99e42d6034b6b5c
20,517
def regionError(df, C, R): """Detects if a selected region is not part of one of the selected countries Parameters: ----------- df : Pandas DataFrame the original dataset C : str list list of selected countries R : str list list of selected regions Returns ---...
53e237bba7c1696d23b5f1e3c77d4b2d2a4c9390
20,518
def lherzolite(): """ Elastic constants of lherzolite rock (GPa) from Peselnick et al. (1974), in Voigt notation - Abbreviation: ``'LHZ'`` Returns: (tuple): tuple containing: * C (np.ndarray): Elastic stiffness matrix (shape ``(6, 6)``) * rho (float): Density (3270 ...
4d7e16fcfc1732ee3a881d4b1c2d755bbd9035f3
20,519
def int_to_bit(x_int, nbits, base=2): """Turn x_int representing numbers into a bitwise (lower-endian) tensor.""" x_l = tf.expand_dims(x_int, axis=-1) x_labels = [] for i in range(nbits): x_labels.append( tf.floormod( tf.floordiv(tf.to_int32(x_l), tf.to_int32(base...
a9529c737e058da664d31055aa85cc7e6179f585
20,520
def create_ldap_external_user_directory_config_content(server=None, roles=None, role_mappings=None, **kwargs): """Create LDAP external user directory configuration file content. """ entries = { "user_directories": { "ldap": { } } } entries["user_directories"]...
baaf3d7a02f2f4e18c3ccddb7f3ff4d5b379c1d4
20,521
def intersection(lst1, lst2): """! \details Finds hashes that are common to both lists and stores their location in both documents Finds similarity that is measured by sim(A,B) = number of hashes in intersection of both hash sets divided by minimum of the number of hashes in lst1 and lst2 \param l...
7288e523e743fda89596e56f217aac8c87899b50
20,522
def allrad2(F_nm, hull, N_sph=None, jobs_count=1): """Loudspeaker signals of All-Round Ambisonic Decoder 2. Parameters ---------- F_nm : ((N_sph+1)**2, S) numpy.ndarray Matrix of spherical harmonics coefficients of spherical function(S). hull : LoudspeakerSetup N_sph : int Decod...
a34cfd7719c36dd8abf1313e3eca4aa2ce49477b
20,523
def outfeed(token, xs): """Outfeeds value `xs` to the host. Experimental. `token` is used to sequence infeed and outfeed effects. """ flat_xs, _ = pytree.flatten(xs) return outfeed_p.bind(token, *flat_xs)
1b4b8c289ebd5dbb90ddd7b565c98ea9ebaec038
20,525
def add_gaussian_noise(images: list, var: list, random_var: float=None, gauss_noise: list=None): """ Add gaussian noise to input images. If random_var and gauss_noise are given, use them to compute the final images. Otherwise, compute random_var and gauss_noise. :param images: list of images :param ...
e453f1fda24ec428eb1e33aec87db9456fa015b2
20,526
def get_sso_backend(): """ Return SingleSignOnBackend class instance. """ return get_backend_instance(cfg.CONF.auth.sso_backend)
4c2a9b857006405f804826b1c096aa8d828d6e42
20,527
def conv_relu_pool_forward(x, w, b, conv_param, pool_param): """ Convenience layer that performs a convolution, a ReLU, and a pool. Inputs: - x: Input to the convolutional layer - w, b, conv_param: Weights and parameters for the convolutional layer - pool_param: Parameters for the pooling layer Returns a tuple...
20d5f3d4b30edd91ef54b53a7b09882b3e2ab9b8
20,528
def ConnectWithReader(readerName, mode): """ ConnectWithReader """ hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER) if hresult != SCARD_S_SUCCESS: raise EstablishContextException(hresult) hresult, hcard, dwActiveProtocol = SCardConnect(hcontext, readerName, mode, SCARD_PROTOC...
af7606fb9ad669185c7a655967d0193b59404fe1
20,529
def interpolate(points: type_alias.TensorLike, weights: type_alias.TensorLike, indices: type_alias.TensorLike, normalize: bool = True, allow_negative_weights: bool = False, name: str = "weighted_interpolate") -> type_alias.TensorLike: """...
13d49a570ac482a0b2b76ab0bb49bf7994df7204
20,530
def calcADPs(atom): """Calculate anisotropic displacement parameters (ADPs) from anisotropic temperature factors (ATFs). *atom* must have ATF values set for ADP calculation. ADPs are returned as a tuple, i.e. (eigenvalues, eigenvectors).""" linalg = importLA() if not isinstance(atom, ...
0a0a0db2ca99d4a3b754acb9cd22ec4659af948f
20,531
def bitset(array, bits): """ To determine if the given bits are set in an array. Input Parameters ---------------- array : array A numpy array to search. bits : list or array A list or numpy array of bits to search. Note that the "first" bit is denoted as zero, w...
cbae61dabfbe0789ff349f12b0df43860db72df7
20,533
from typing import OrderedDict def sample_gene_matrix(request, variant_annotation_version, samples, gene_list, gene_count_type, highlight_gene_symbols=None): """ highlight_gene_symbols - put these genes 1st """ # 19/07/18 - Plotly can't display a categorical color map. See: https://gith...
70ed9387ebba73664efdf3c94fe08a67ed07acc9
20,535
import random def normal218(startt,endt,money2,first,second,third,forth,fifth,sixth,seventh,zz1,zz2,bb1,bb2,bb3,aa1,aa2): """ for source and destination id generation """ """ for type of banking work,label of fraud and type of fraud """ idvariz=random.choice(zz2)...
aec17f55306691395dc2797cf30e175e0cb5b9e8
20,537
from typing import List def find_paths(root: TreeNode, required_sum: int) -> List[List[int]]: """ Time Complexity: O(N^2) Space Complexity: O(N) Parameters ---------- root : TreeNode Input binary tree. required_sum : int Input number 'S'. Returns ------- all_p...
71cd37db1be97015173748e8d2142601e306552b
20,539
import time import requests import json def macro_bank_switzerland_interest_rate(): """ 瑞士央行利率决议报告, 数据区间从20080313-至今 https://datacenter.jin10.com/reportType/dc_switzerland_interest_rate_decision https://cdn.jin10.com/dc/reports/dc_switzerland_interest_rate_decision_all.js?v=1578582240 :return: 瑞士央...
14eb2ce7dc85e0611a8d55147172256ed8a2c71e
20,540
def create_dataframe(message): """Create Pandas DataFrame from CSV.""" dropdowns = [] df = pd.DataFrame() if message != "": df = pd.read_csv(message) df = df.sample(n = 50, random_state = 2) # reducing Data Load Running on Heroku Free !!!! if len(df) == 0: return pd.D...
c0d764ed47cba31d0129d1c61e645065ba2e99b5
20,541
def load_model(path): """ This function ... :param path: :return: """ # Get the first line of the file with open(path, 'r') as f: first_line = f.readline() # Create the appropriate model if "SersicModel" in first_line: return SersicModel.from_file(path) elif "ExponentialDiskMo...
425113abe09b1de1efa1d5cf1ca2df4d999886c2
20,542
import functools def add_metaclass(metaclass): """ Class decorator for creating a class with a metaclass. Borrowed from `six` module. """ @functools.wraps(metaclass) def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not Non...
f6ee3feef418d5bff4f0495fdbfc98c9a8f48665
20,543
import torch def max_pool_nd_inverse(layer, relevance_in : torch.Tensor, indices : torch.Tensor = None, max : bool = False) -> torch.Tensor : """ Inversion of LogSoftmax layer Arguments --------- relevance : torch.Tensor Input relavance indices : torch.Ten...
ae3ad1b2a3791063c90568f0c954d3de6f3985f8
20,544
def aroon_up(close, n=25, fillna=False): """Aroon Indicator (AI) Identify when trends are likely to change direction (uptrend). Aroon Up - ((N - Days Since N-day High) / N) x 100 https://www.investopedia.com/terms/a/aroon.asp Args: close(pandas.Series): dataset 'Close' column. n(...
2a44c15b06e9a1d2facaa800a186b780fc226717
20,545
def triangulate(points): """ triangulate the plane for operation and visualization """ num_points = len(points) indices = np.arange(num_points, dtype=np.int) segments = np.vstack((indices, np.roll(indices, -1))).T tri = pymesh.triangle() tri.points = np.array(points) tri.segments = seg...
d18a7d171715217b59056337c86bf5b49609b664
20,548
def immutable(): """ Get group 1. """ allowed_values = {'NumberOfPenguins', 'NumberOfSharks'} return ImmutableDict(allowed_values)
851853b54b106cbc3ee621119a863a7b2862e8d5
20,549
def test_plot_colors_sizes_proj(data, region): """ Plot the data using z as sizes and colors with a projection. """ fig = Figure() fig.coast(region=region, projection="M15c", frame="af", water="skyblue") fig.plot( x=data[:, 0], y=data[:, 1], color=data[:, 2], size...
4a9f2727d046d91445504d8f147fcef95a261cb5
20,550
def predict_to_score(predicts, num_class): """ Checked: the last is for 0 === Example: score=1.2, num_class=3 (for 0-2) (0.8, 0.2, 0.0) * (1, 2, 0) :param predicts: :param num_class: :return: """ scores = 0. i = 0 while i < num_class: scores += i * ...
ee4038583404f31bed42bed4eaf6d0c25684c0de
20,551