content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_tworay_path_loss(range_m, freq_hz, tx_ht_m, rx_ht_m, include_atm_loss=True, atmosphere=None): """ Computes the two-ray path loss according to L = 10*log10(R^4/(h_t^2*h_r^2)) This model is generally deemed appropriate for low altitude transmitters and receivers, with a flat Earth model....
343d3b3e2df86f209d2b175e06f36ff695178818
36,100
def check_bots_database(): """Check for elements in bot's database. Returns: int: Size of list if there is any elements None: If table is empty """ db_status = database.get_data("confDB", False, "SELECT bot_name FROM tokens") return None if not db_s...
7f7302d9f6edb4bfd42cc053f81875de728d11f6
36,101
from datetime import datetime def get_features_for_commit_people(git_commit): """Retrieves the people associated with a git commit Arg: git_commit(dict): a commit message parsed into a dictionary Return: (tuple): relevant people and type extracted from the commit """ curr_time = datetime.datetime....
2f1ba38bb1f190ead2c1f4974f023feaeb55bca2
36,102
from bs4 import BeautifulSoup def get_url_source(url_name): """ If you already know the url_name or if you have run through the get_noaa_forecast_url(), then you can send in the url here. Get the source information for the url and place the information into a BeautifulSoup object, so that we can do an...
f7ab186d2d9f68020286317f28a169ad296d39fd
36,103
import torch def norm(x): """ Normalize (z-norm) from [0,1] range to [-1,1] """ out = (x - 0.5) * 2.0 if isinstance(x, torch.Tensor): return out.clamp(-1, 1) elif isinstance(x, np.ndarray): return np.clip(out, -1, 1) else: raise TypeError( "Got unexpected objec...
43dba4ec5c7e44daccef4231db5667319d73cc88
36,104
def gen_gp_loss(gp): """Generate an internal objective, `dlik_dh * H`, for a given GP layer. """ def loss(_, H): dlik_dh_times_H = H * K.gather(gp.dlik_dh, gp.batch_ids[:gp.batch_sz]) return K.sum(dlik_dh_times_H, axis=1, keepdims=True) return loss
e3fe0f3634c1309acce9cc65978e028da2fa05ff
36,105
from typing import Tuple from typing import Optional def set_market(asset_form: NewAssetForm) -> Tuple[Optional[Market], Optional[str]]: """Set a market for the to-be-created asset. Return the market (if available) and an error message.""" market = None market_error = None if int(asset_form.marke...
9d597acc1b12cbc95fea929939292a0f7641f550
36,106
def _evaluateMockedResponse(table, cmd_dict, success=True, is_save=True): """ Evaluates if the response from a mock is as expected. :param Table table: :param dict cmd_dict: :param bool success: value of success :param bool is_save: value of is_save """ response, returned_is_save = \ table.p...
20b5a3ff800e012cffc65fd0876656ced9e45f89
36,107
def plot_resource_utilization(filename, subplt, ylim=None, pattern=None): """ :param filename: resource_log file :param subplt: pyplot axes object :param ylim: y-axes range, defaults to [0,1.05] :param pattern: only plot resources whose name matches the pattern (in regular expression), ...
e82b902fccc77d3d7850ade72adcbdd9fb9910df
36,108
import sys def projection_simplex_sort(v, z=1): """ Bounds control field to agent's magnetic field budget. ... Parameters ---------- v : numpy.array Control field allocation of the agent. z : float Magnetic field budget (default 1.0) """ n_features = v.shape[...
042d3ce5851c31c8d5483e25d5ca2343809cebea
36,109
import collections def _get_synthetic_digits_data(): """Returns a dictionary suitable for `tf.data.Dataset.from_tensor_slices`. Returns: A dictionary that matches the structure of the data produced by `tff.simulation.datasets.emnist.load_data`, with keys (in lexicographic order) `label` and `pixels`....
c770d08c9a92c7aa958037a45baf2fde306c2bc2
36,110
def all_subclasses(cls): """Returns recursively-generated list of all children classes inheriting from given `cls`.""" return set(cls.__subclasses__()).union([s for c in cls.__subclasses__() for s in all_subclasses(c)])
fa9c08bd37d9bee504a404d20f5e94e8e3b2bab1
36,111
from typing import Tuple def get_sample_input01() -> Tuple[int, np.ndarray]: """ A single input vector sample of the "Necessary" category. """ label = 0 feature_vector = np.array([[0., 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ...
2bab4949027b015d645a5a965867227453d29448
36,112
def calc_pose_instances( pose_heatmaps, pose_localmax, pose_embed_maps, min_embed_sep_between, max_embed_sep_within, max_inst_dist): """ Given the input parameters for a single image/frame, return a list of PoseInstance objects Parameters: pose_h...
2bd30e997e4cfe55153954bfeadbae263e24ca9a
36,113
def cap_rating(flight_phase, short_period_cap, short_period_damping): """ Give a rating of the short period mode flight quality level: Level1 Level2 or Level3 and 4 according to MIL-STD-1797A Args: flight_phase (string) : 'A', 'B' or 'C' short_period_cap (float): Control Anticipation ...
2ecebb417f32320213a916ca1366f36dd473fc62
36,114
def set_immd(*args): """ set_immd(ea) -> bool Set 'has immediate operand' flag. Returns true if the 'FF_IMMD' bit was not set and now is set @param ea (C++: ea_t) """ return _ida_bytes.set_immd(*args)
9521a509cfed727a0e48b6ac72704bbbc5218087
36,115
from slycot import sb01bd def place_varga(A, B, p, dtime=False, alpha=None): """Place closed loop eigenvalues K = place_varga(A, B, p, dtime=False, alpha=None) Required Parameters ---------- A : 2D array_like Dynamics matrix B : 2D array_like Input matrix p : 1D array_like...
fcfcbca4e7320e39143deb6462fd98c335566b26
36,116
def kToc(k, nu = 5.0, xF = 0.2, xS = 0.8, xG = 0.0 ): """ kToc will convert a k-eigenvalue to a c-eigenvalue given the cross sections for the problem. """ xA = xG + xF xT = xA + xS return (nu*xF/k + xS)/xT
a3e310884f3a260b0bc5069f3799784d81b2c93f
36,117
import os import json def _build_parameters(statistics, gcs_data_dir): """Generate model params based on the stats generated from the data-set.""" # Do binning on sequence lengths bins = np.arange(0, 1700, 100) # Choose maximum seq length based on number which covers 50% of seq lengths threshold ...
4ea79d35203f55e89bd10b9c6ef1b2bb26e52edc
36,118
def analysis(sliceno, prepare_res, params): """ reading complete file, writing to this slice only""" separator, filename, _, labels, dw = prepare_res if options.hashlabel: hash_ix = labels.index(options.hashlabel) else: hash_ix = -1 copied_lines = 0 n_labels = len(labels) res_num = ffi.new('uint64_t [2]'...
e14d3440a24404f8487d9ecf7ac50a7aa5291f3c
36,119
def construct_generic_B(n_states, n_control): """ Generates a fully controllable transition likelihood array, where each action (control state) corresponds to a move to the n-th state from any other state, for each control factor """ num_factors = len(n_states) if num_factors == 1: ...
e09b6abd0b72637b914e0c94b57b04aed42c3554
36,120
from typing import Union from typing import TextIO from typing import Optional import click def parse( in_data: Union[str, PathLike, TextIO], input_linesep: Optional[str] = None, max_size: int = _MAX_SIZE, ) -> dict: """Parse a VEP plain text statistics file into a dictionary. :param in_data: Inp...
171914b54aadd2cddef672951351c4a987110a9e
36,121
def analysis_to_subword_dicts(ana): """ Returns a list of list of dicts. Each list element is an analysis. For each analysis, there is a list of subwords. Each dict contains an Omorfi analysis """ return map(pairs_to_dict, chunk_subwords(analysis_to_pairs(ana)))
933a73c0c4787bf63cecefbedfd230a3d99906f9
36,122
from datetime import datetime def create_directory_content_output(share_name: str, raw_response: dict, directory_path: str = "") -> dict: """ Create XSOAR context output for list directory command. Args: share_name (str): Share name. raw_response (dict): Request raw response. direc...
a23b3ce74f4274c2ee59823a3f9a976943b94a5a
36,123
def circle_area(r): """Calculates the area of a trapezium using the formula: area = \u03C0(radius squared) Parameters ---------- r: int or float The radius in the equation. Returns ------- Float \u03C0 * (r**2) Raises ------ ValueError If r:: ...
e8d3c8fd556a90851757a4edf6091d44452f59cc
36,124
def split_to_batches(graphs, labels, size): """ split the same size graphs array to batches of specified size last batch is in size num_of_graphs_this_size % size :param graphs: array of arrays of same size graphs :param labels: the corresponding labels of the graphs :param size: batch size ...
7e93c7eec3f4d5c94e41e44356c496148b78162c
36,125
from matplotlib import ticker from matplotlib.pyplot import gca def showLines(*args, **kwargs): """ Show 1-D data using :func:`~matplotlib.axes.Axes.plot`. :arg x: (optional) x coordinates. *x* can be an 1-D array or a 2-D matrix of column vectors. :type x: :class:`~numpy.ndarray` ...
e21bcc8fd563c632ecc2da76ebdd7af3a0cefc3c
36,126
import json def build_response(status, message): # type: (DownloadStatus, str) -> str """ function to build a response as json string """ return json.dumps({'status': status, 'message': message})
078db81165a43e2bf68ddde13b4ca566507ef3ab
36,127
import json def loads_json(fid, **kwargs): """ Loads a JSON file and returns it as a dict. :param path: String or another object that is accepted by json.loads :param kwargs: See ``json.dump()``. :return: Content of the JSON file. """ assert isinstance(fid, str), fid return json.loads(fi...
ccdb62568982f6a0862dd5c8167b2e1d177137ea
36,128
import argparse def cli_parse_args(args=None, namespace=None): """ CLI (Command Line Interface) parsing based on ``ArgumentParser.parse_args`` from the ``argparse`` module. """ # CLI interface description parser = argparse.ArgumentParser( description=__doc__, epilog="by Danilo J. S. Bellini", ...
8c76ec6cb3a398048c9878a3d996eed329f67ac3
36,129
def get_rad_list(H_MR, H_OR): """主たる居室、その他の居室という単位で設定された放熱機器を暖房区画ごとの配列に変換 Args: H_MR(dict): 暖房機器の仕様 H_OR(dict): 暖房機器の仕様 Returns: list: 放熱機器の暖房区画ごとの配列 """ # 暖房区画i=1-5に対応した放熱器のリストを作成 rad_list = [None, None, None, None, None] # 放熱系の種類 rad_types = get_rad_type_list() ...
0645c6f5af6cbbd2568e664272cea3a0576fa3bf
36,130
def GetArrayElement(tag, array_id, idx): """ Get value of array element. @param tag: Tag of array, specifies one of two array types: AR_LONG, AR_STR @param array_id: The array ID. @param idx: Index of an element. @return: Value of the specified array element. Note that this functi...
5d2c957a0f2c64d25325db55d748b0f041d34eaa
36,131
import subprocess def shutdown_pi(): """ Shuts down the Pi system """ subprocess.Popen(["sudo", "shutdown", "-h", "now"]) return True
b0f80afecd4682529daed2a14497c07c36598c64
36,132
def init_lars_optimizer(current_epoch, params): """Initialize the LARS Optimizer.""" learning_rate = poly_rate_schedule(current_epoch, params) optimizer = tf.contrib.opt.LARSOptimizer( learning_rate, momentum=params['momentum'], weight_decay=params['weight_decay'], skip_list=['batch_norma...
6eba9c650c1a14b3df9a1e46d52014cb62898124
36,133
import time import random def suffix(): """Generate a random string of length 4""" alph = "abcdefghijklmnopqrstuvwxyz" return "-".join([time.strftime("%Y-%m-%d-%H%M%S"), "".join(random.sample(alph, 4))])
f0e6c053ffb38e09d5ed4516f07fb1533b5dd80d
36,134
def augment_data(spectrogram: np.ndarray) -> list: """ Augment the given data. :param spectrogram: Data to augment :return: Augmented data """ result = [ mask_spectrogram(spectrogram, n_freq_masks=1, n_time_masks=0), # mask_spectrogram(spectrogram, n_freq_masks=3, n_time_masks=0)...
a56bd5e7baaa45f6ccb53b27b73e50baecf6e3ee
36,135
import datasets import torch def load_train(root_path, dir, batch_size, phase): """ Load data for train set """ transform_dict = { 'src': transforms.Compose( [transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ...
372571a5cf75c878782fa96c73860bfe04631972
36,136
def reduceModel(model, atoms, select): """Return reduced NMA model. Reduces a :class:`.NMA` model to a subset of *atoms* matching *select*. This function behaves differently depending on the type of the *model* argument. For :class:`.ANM` and :class:`.GNM` or other :class:`.NMA` models, force constan...
6bb5ed82638f50e311879ec623fbe027a6297258
36,137
def executable(s): """Attempts to use the "ex" entry in LS_COLORS, falling back to green""" return __ls_color(s, 'ex', term.green)
0a6ae7f999a7fa23391db68eddfc4cd67f89df2c
36,138
def put_target_state(): """SDP target State. Sets the target state """ sdp_state = SDPState() errval, errdict = _check_status(sdp_state) if errval == "error": LOG.debug(errdict['reason']) rdict = dict( current_state="unknown", last_updated="unknown", ...
b810987edad9f0cb644fdb69974ca91d6a8cc01b
36,139
def _skew_circulant_multiply(c, x, f_method='std'): """Multiply a skew-circulant matrix by a vector. Runs in O(n log n) time. See algorithm S7 in Sukhoy & Stoytchev 2019 (full reference in README). Args: c (np.ndarray): first column of skew-circulant matrix G x (np.ndarray...
de20516ce427385d7462cd031cfb2001f0f3b640
36,140
def _apply_temp_conv(var, var_unit, dest_unit): """Return the variable converted to different units using a temperature conversion algorithm. Args: var (:class:`xarray.DataArray` or :class:`numpy.ndarray`): A variable. var_unit (:obj:`str`): The variable's current units. ...
6df9d02b1d74cd8554d4ad8b135986636f3e2c95
36,141
from typing import List import os def read_all_labels(fp_folder: str = "./rs19_val/jsons/rs19_val") -> List[dict]: """Loads the data of all JSON files from a provided folder and returns the contents in a list. :param fp_folder: Filepath to the folder containing JSON files. :dtype fp_folder: str """ ...
aa8b0267afa66696b9ff10f2a19f4ea505ecacf9
36,142
import requests def epidemic_history() -> pd.DataFrame: """ 该接口最好用代理速度比较快 https://github.com/canghailan/Wuhan-2019-nCoV 2019-12-01开始 :return: :rtype: pandas.DataFrame """ url = "https://raw.githubusercontent.com/canghailan/Wuhan-2019-nCoV/master/Wuhan-2019-nCoV.json" r = requests.g...
c16e375c0e3e288667afebcbc8fa3f54dc486dcc
36,143
def main(*, data, d): """entrypoint function for this component Usage example: >>> main( ... data = pd.Series( ... [1.2, 7.2, 2.8, 4.8, 10.8], ... index = [2, 3, 5, 6, 9] ... ), ... d = 2 ... )["interpolation"] 2 1.2 4 5.0 6 4.8 8...
e026badb020177538c34689300cb9df7783df0aa
36,144
def derivative ( fun , x , h = 0 , I = 2 , err = False , args = () , kwargs = {} ) : """Calculate the first derivative for the function # @code # >>> fun = lambda x : x*x # >>> print derivative ( fun , x = 1 ) - see R. De Levie, ``An improved numerical approximation for the first derivative'...
f6dc64f483e9512775b078e8cd602dc9dc66cc53
36,145
def get_statevector(result) -> np.ndarray: """ Creates a statevector out of a simulation result. Used when the simulator does not give a statevector. Parameters ---------- result: the result from the simulation. Returns ------- ndarray: the statevector correspondin...
6dab1bb772e54f084dcf0b9ce141f8dea08812e0
36,146
def weighting(distance): """Weighting function for pyresample.""" weight = 1 / distance**2 return weight
2af699d6daef7a3d375fe80ee79f7414047921c8
36,147
import os def absolute_path(path): """ Returns the absolute path for the given path and normalizes the path. :param path: Path for which the absolute normalized path will be found. :returns: Absolute normalized path. """ return os.path.abspath(os.path.normpath(path))
39a8af97f223828ae521b3570116e43990e15e66
36,148
import math def weighted(*values): """ Calculates the uncertainty weighted average of the provided values, where each value is a ValueUncertainty instance. For mathematical formulation of the weighted average see "An Introduction to Error Analysis, 2nd Edition" by John R. Taylor, Chapter 7.2. ...
b51158e5f34d010902bbdcb6a98e94971c549c15
36,149
def average_precision_at_k(targets, ranked_predictions, k=None): """Computes AP@k given targets and ranked predictions.""" if k: ranked_predictions = ranked_predictions[:k] score = 0.0 hits = 0.0 for i, pred in enumerate(ranked_predictions): if pred in targets and pred not in ranked_...
57e21a1ca8b8f7fccc0b5c59dbfc799d8618fc93
36,150
def on_intent(intent_request, session): """ Called when the user specifies an intent for this skill. Main logic point to determine what action to take based on users request. """ print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) #...
23ed09f7c6f26a155e9a550b31fe538a33075107
36,151
import time def check_index_by_doc(es_alias, db, doc_id, interval=10): """ Given a doc, update it in couch (meaningless save that updates rev) and check to make sure that ES will eventually see it after some arbitrary delay """ target_rev = None try: couch_doc = db.open_doc(doc_id if d...
3df71f7795859f8ca30f79858c659ce692cf7523
36,152
def formatEpisodeNumbers(episodenumbers): """Format episode number(s) into string, using configured values """ if len(episodenumbers) == 1: epno = Config['episode_single'] % episodenumbers[0] else: epno = Config['episode_separator'].join( Config['episode_single'] % x for x in...
d33da0c2da5213dfc7214f4c11d18b5c3bdd814c
36,153
def _PureShape(shape): """Make sure shape does not contain int tensors by calling int().""" return [int(x) for x in shape]
1cebacd516cbf223833342ecffb6f8d9fe22ff2d
36,154
from typing import cast def sum(pda: pdarray) -> np.float64: """ Return the sum of all elements in the array. Parameters ---------- pda : pdarray Values for which to calculate the sum Returns ------- np.float64 The sum of all elements in the array Raises ----...
9a28da173746280b6fd28ad0a6c942ee5e7a7463
36,155
import textwrap def add_ui_containerized_action(sub_parser: ArgumentParser) -> ArgumentParser: """Populates the sub parser with the container launch kernel arguments.""" sub_parser.add_argument( '-d', '--directory', dest='notebooks_directory', default='.', help=textwrap.dedent(...
ba21b9a990bf290db86a330faed7433a0bd4da4b
36,156
from typing import Sequence def _tf_cleanup_all( triples_groups: Sequence[MappedTriples], *, random_state: TorchRandomHint = None, ) -> Sequence[MappedTriples]: """Cleanup a list of triples array with respect to the first array.""" reference, *others = triples_groups rv = [] for other in o...
7b76533b8860d17f072b54645fc11f02d1bc3ffd
36,157
import copy def apply_pdbfixer(input_file_path, output_file_path, directives): """ Apply PDBFixer to make changes to the specified molecule. Single mutants are supported in the form "T315I" Double mutants are supported in the form "L858R/T790M" The string "WT" still pushes the molecule through P...
3ef9a13e9d9842e8837651f197fb20b86bf86ceb
36,158
def char_to_number(value: str, required_type: str) -> str: """Converts the string representation of a number (int or float) to a number Args: value (str): String representation of a number required_type (str): Output type desired (bigint or double) Raises: Exception: The conversion...
cb58f24100f961d4f260473cee4fa82621eb5887
36,159
def get_PHM08Data(save=False): """ Function is to load PHM 2008 challenge dataset """ if save == False: return np.load("./PHM08/processed_data/phm_training_data.npy"), np.load("./PHM08/processed_data/phm_testing_data.npy"), np.load( "./PHM08/processed_data/phm_original_testing_data...
0f963eb988ac8e9d8ead2b47f9ff13dd82449389
36,160
def _validate_index_string(index_string: str) -> bool: """ Handle validation of index string from the argument. a string should be in format 't{%d}' or 'r{%d}' or 'd{%d}' Parameters: index_string: the string we want to validate Returns: a boolean indicating whether the index st...
aa6d7d0aba2a0378d2e1c836b78b0ec943cc1bdb
36,161
import subprocess import socket import time def _restart_debugging(interactive=True): """ Args: interactive: Returns: """ global tb_pid #Kill existing TB proc = subprocess.Popen(["kill", str(tb_pid)]) proc.wait() debugger_socket = socket.socket(socket.AF_INET, socket.S...
0b1accc7eece03d4d5e3f3157ba849bcbbb74b5f
36,162
def get_r_GU(r_HPU): """1時間平均のガスユニットの暖房出力分担率 (15) Args: r_HPU(ndarray): 1時間平均のヒートポンプユニット暖房出力分担率 (-) Returns: ndarray: 1時間平均のガスユニットの暖房出力分担率 """ return 1 - r_HPU
dc4c7a913ff7402a10d9aad08bab4f3646cff904
36,163
def onset_by_rain(date, df, window=5, rain_threshold=5): """ Finds true storm onset by finding the first date around the landfall that rain exceeds a threshold Args: date: the date to look around df: df with a date and rain column window: number of days around date to find max (tota...
87e4d1f35114974a004c5b923aea05ed835cf9a7
36,164
def get_most_read(key): """ Gets the most read news from a given page (national or international) :param key: the key of the source page (e.g: g1, localDF, WP, etc.) :return: a list with the most read news from the page """ # Check if the News Source is national or internacional if key in n...
89998185adaeb4e129440ab5dd90b89f823dab6b
36,165
import math def trapezoid_list(area, rotate_and_mirror=True): """Returns a list of possible trapezoids (various height/width ratios, various orientations) with approximately the requested area. We support two kinds of trapezoids: w1 w2 |----\ /--\ h | \ ...
44a4d678e8f1850d74e2a2087461ea68129de755
36,166
import os from datetime import datetime import asyncio async def generate_tarot_card( id_: int, resources: BaseTarotResource, direction: int = 1, *, need_desc: bool = True, need_upright: bool = True, need_reversed: bool = True, width: int = 1024) -> Resu...
0c699388b161e557a3b93df59d47832360ede612
36,167
import os def work_in(dir_ext): """Execute a function in a different directory""" def func_decorator(func): @wraps(func) def wrapped_function(*args, **kwargs): here = os.getcwd() dir_path = os.path.join(here, dir_ext) if not os.path.isdir(dir_path): ...
fda5ecdea5dc0a75869c2bc65f726abb00904d9a
36,168
import os def login(request): """ Log user in using Github OAuth""" # Create keys if not yet there! if not request.session.get('github_token'): request.session['github_token'] = None # To keep API token request.session['github_info'] = None # To keep user infor (e.g. name, avatar url) ...
30a5acbaf6bdb3c746cbc49ca4ea03f1a75eefb7
36,169
def counter(iterable): """ Return a dict of counts for items in iterable. """ counts = defaultdict(int) for item in iterable: counts[item] += 1 return counts
ace03795b5204fdad77860d99965889c1dec4435
36,170
def meets_criteria(num): """boolean test for meeting the password criteria. + Two adjacent digits are the same (like 22 in 122345). + Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679) Arg: num: number to be tested ...
9001f2012cb3572c52967307924bdf4f0e37e614
36,171
def return_loop( onset_loc, envelope, function_time_thresh, hist_threshold, hist_time_samples, nperseg=512, ): """ This function is used by the calculate_onsets method. This looks backwards in time from the attack time and attempts to find the exact onset point by identifying the p...
50c2a3afbc4b1b2a753a7f43ae30c7601ad49c1e
36,172
from numpy import matrix def hostAppMat2numpy(hostmat): """ This will return a matrice in a numpy.array format This function can also be used when theire is LeftHand / RightHand conflict. ie a numpy matrice is a regular 4x4 matrice (3x3rot+trans) @type hostmat: hostObject Matrice @p...
f28ff26826edbac6f41e1882d6aa250c639d613b
36,173
def integrate_entropy(data, scaling): """Integrates entropy data with scaling factor along last axis Args: data (np.ndarray): Entropy data scaling (float): scaling factor from dT, amplitude, dx Returns: np.ndarray: Integrated entropy units of Kb with same shape as original array ...
0a92f4c1da3966cc12a581f943c96bb79a1c8e4e
36,174
import os def parse_old_arhive_file_name(file_name): """Retrieves information from the given old archive file name and returns it in the following form: function, dimension, instance :param file_name: old archive file name in form f[f1]-[f2]_i[i1]-[i2]_[d]D.txt """ split = os.path.basename(f...
7ffe05e80ff7f5b60b648056bb7a37fa5de5e38e
36,175
import urllib def removelink(inp, nick='', db=None): """.removelink <search terms> -- Remove a bad link from the database. e.g., .removelink shaq""" if nick in administrators: result = remove_link(db, urllib.quote_plus(inp)) if result is True: return "Removed " + inp + " successfu...
1b2581651373fb16f6f8c24daebd4e832dc87307
36,176
def embed(sagas): """ The data is embedded into numerical data (vectors to represent characters) that we can use to train our RNN. :param sagas: Training data :return: Tensor containing the input data in embeded form, array of unique character in the input. """ # All unique characters in our sa...
a85fa1bc5b3ff09640a832d8ba13cd03590cec92
36,177
def create_data(step: 'projects.ProjectStep') -> STEP_DATA: """ Creates the data object that stores the step information in the notebook results JavaScript file. :param step: Project step for which to create the data :return: Step data tuple containing scaffold data structure for th...
56a55bf01ce52b69973f1054eee9b32427aed826
36,178
def byte_string_dtypes(endianness="?", min_len=0, max_len=16): # type: (str, int, int) -> st.SearchStrategy[np.dtype] """Return a strategy for generating bytestring dtypes, of various lengths and byteorder.""" order_check("len", 0, min_len, max_len) return dtype_factory("S", list(range(min_len, max_...
4a8de45377b2c15671049762b5f1f4de10bc8692
36,179
def get_company(): """ Gets company for contact entered """ company = input("Please input a company\n") while True: if company == "": print("Please input a company please") else: break return company
324d49384ab80aad3c8c09a3707ad9fd01929166
36,180
def set(request): """Set new CTL value to a encoder/decoder""" def inner(func, obj, value): result_code = func(obj, request, value) if result_code is not opuslib.api.constants.OK: raise opuslib.exceptions.OpusError(result_code) return inner
695caab9b6ac1b63b1cd22c4ad534dd60e768c5d
36,181
import subprocess import os def getInstalledPackageVersion(pkgid): """ Checks a package id against the receipts to determine if a package is already installed. Returns the version string of the installed pkg if it exists, or an empty string if it does not """ # First check (Leopard and la...
8517615ee865feb1e7b48ce3d1a0cb6c418bd0ad
36,182
def read_mapping(mapf, verbose=False): """ Read the mapping from metagenomes to nodes in the tree :param mapf: the mapping file :param verbose: more output :return: """ mapping = {} with open(mapf, 'r') as f: for l in f: p = l.strip().split("\t") if p[1] ...
d6852efb1a3514e1ef4bdf545624e5ee38b07a69
36,183
def tfr_gen(func, op_defs): """Parse a function and emit the TFR functions.""" mlir_code, _ = TfrGen(op_defs).transform(func, None) assert tfr.verify(mlir_code), 'mlir code not verified: {}'.format(mlir_code) return mlir_code
7bb43e936aa4f9dd4ed0527a7d2a533b4172b7b3
36,184
from typing import Tuple import torch def preprocess_image(image:'np.ndarray', input_shape:Tuple=(79,95,79), normalized=True) -> 'torch.Tensor': """Resize, normalize between 0-1 and convert to uint8 Args: image('np.ndarray'): input_shape(Tuple, optional): (Default value = (79,95,79)) norma...
c8d9f7c0d504f28fd45a1fa6fe6d43ff176f2d59
36,185
import inspect import textwrap def convert_to_static(dyfunc): """ Converts dygraph function into static function. """ # Get AST from dygraph function raw_code = inspect.getsource(dyfunc) code = textwrap.dedent(raw_code) root = gast.parse(code) # Transform AST dygraph_to_static = D...
00c2e2126832ab36a43d7537fa147cb2a91a6592
36,186
from datetime import datetime def add_minutes(sourcedate, min_, debug=False): """ Incremental increase of datetime by given minutes """ sourcedate += datetime.timedelta(minutes=float(min_)) return sourcedate
f146837b640327f20c81f5ca95531fc684cf817f
36,187
def poly_kernel(X, Y=None, gamma=1.0, coef0=0.0, degree=3): """ Compute the poly kernel between X and Y: K(x, y) = (scale*dot(x, y^T) + shift)**degree for each pair of rows x in X and y in Y. Parameters ---------- X : ndarray of shape (n_samples_X, n_features) Y : ndarray of shap...
c47ebba04bf50e474c0eff94b777110ead0a4f61
36,188
def filter_process(session, file, action, wkt, **kwargs): """Wrapper function for the filtering process. Arguments: session (dict): Dictionary with session information. file (str): The full path of the source file. action (str): The filtering operation. wkt (str): Well-Known Tex...
68a2e8be4df13996d9a45ee5138076faa2378539
36,189
def help_text(): """ Retreive human-readable description of all added craftable items :return: description of all added craftable items :rtype: str """ ret = [] for name in craftables: items, item = craftables[name] item_names = utils.list_to_english([str(x) for x in items])...
ce8ffb7ed681ad875242317b8ae426ca13ffb9dc
36,190
def _load_image(path): """ Reads image image from the given path and returns an numpy array. """ image = np.load(path) assert image.dtype == np.uint8 assert image.shape == (64, 64, 3) return image
0950925b484dbe75bb578df781c6ee09c1e80634
36,191
def nb(model, ref): """ Normalzied bias. model = nuemrical solution of shape M by N ref = analytical solution or observation of shape M by N returns nb """ e = model - ref mean_e = nanmean(e) mean_abs_ref = nanmean(abs(ref)) nb = mean_e / mean_abs_ref return nb
d021af55091f161e6621222d3be9ed5f85541cc7
36,192
def annotate_heatmap(im, data=None, valfmt="{x:.2f}", textcolors=["black", "white"], threshold=None, **textkw): """ A function to annotate a heatmap. Parameters ---------- im The AxesImage to be labeled. data Data used to annotate. If None, the image's data is used. Optional. ...
9b75485cf6b9f33b1feccbdd552fe7c68378fb40
36,193
def sigmoid(x): """ Sigmoid activation function @param x: input array @return: out: output array """ return 1 / (1 + np.exp(-x))
a1b23861287b50c7f78537e026b2da9bd2b664bd
36,194
def _flagword(obj): """Internal use only""" #create the flags word for an objective _f = B_DISC #everything's discoverable if obj.neg: _f |= B_NEG if obj.synch: _f |= B_SYNCH if obj.dry: _f |= B_DRY return _f
eb34deececffdbd8a69c600d437d4cd0965b49dd
36,195
def create_model(conditioning_dim, flags): """Define model, and initialize classifiers.""" model = VAEBasic(flags.height, flags.width, latent_dim=flags.latent_dim, conditioning_dim=conditioning_dim, start_filters=flags.start_filters, name='VAE') return model
8903edadfafbb60183d740855fb6f1733ff4d0f3
36,196
def palette(name): """Palette decorator""" def wrapper(cls): palette_providers[name] = cls return cls return wrapper
27e8dffd4eb9eeb7df2e31812f5c2f6e64c98ea0
36,197
import copy def remove_one_path(path_graph, dest=None, preserv_cov=False): """ Removes one path from the path set in a way that the vertices covered by the set of paths does not decrease. """ complete = False ix = 0 if dest is None: dest = max(list(path_graph.keys())) + 1 w...
e8bf21429937e36190c530a1fd69a2a83007ca9b
36,198
import types import inspect def spec_builtin(obj): """ Describe a builtin function """ # Built-in functions cannot be inspected by # inspect.getargspec. We have to try and parse # the __doc__ attribute of the function. docstr = obj.__doc__ args = '' if not docstr: if isinstance(obj,types....
b892bc8268e7394e87de63e00154698084fba302
36,199