content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def delete_report(repo, username=None, namespace=None): """Delete a report from a project.""" repo = flask.g.repo form = pagure.forms.ConfirmationForm() if form.validate_on_submit(): report = flask.request.form.get("report") reports = repo.reports if report not in reports: ...
d3cee0f0702b3a48559782b01b426bb0f4975de7
38,500
import sys import os import shutil import six def downloadmodel(model_label=None, targetdir=None): """ Query Zenodo and retrieve version-specific model parameter files and metadata """ global modelOptions if targetdir is not None: tempDir = targetdir else: tempDir = SCOPEMODELS_DATADIR ## By default, downlo...
61b6f2612fba0a04f9c48520c888b4d344089291
38,501
import math def fuzzifier_determ(D: int, N: int) -> float: """The function to determ the fuzzifier paramter of fuzzy c-means """ return 1 + (1418 / N + 22.05) * D**(-2) + (12.33 / N + 0.243) * D**(-0.0406 * math.log(N) - 0.1134)
3bf0f85a74400c19fae74349ea651eba8b600697
38,502
from typing import List def _is_paired(ordered_list: List[int]) -> bool: """Check whether values are paired in ordered_list.""" consecutive_comparison = [ t == s for s, t in zip(ordered_list, ordered_list[1:]) ] return (all(consecutive_comparison[0::2]) & (not any(consecutive_comparison[1::2])...
ba7052de513bcc7bf274e38005c459715e9f60b8
38,503
def rgb_to_gray(image, three_channels=False): """Converts a 3 channel RGB image to a 1 channel grayscale image. Args: image: Rank 3 float32 tensor containing 1 image -> [height, width, 3] with pixel values varying between [0, 1]. Returns: image: A single channel grayscale image -> [image, hei...
89b3bf7dab7b94ff21be046e72895e2326819abe
38,504
def get_largest_partition_size(ns, device): """ Returns size of the largest free region (in blocks), which can accommodate a partition on given device. There must be partition table present on this device. :type device: LMIInstance/CIM_StorageExtent or string :param device: Device which should...
104c1bd8626236fbd0983f6280213c0a15785f41
38,505
import os def create_stereo_point_cloud_folder(sensor_folder): """Create a folder for point clouds genereated using the stereo depth images, if it does not exist. Args: sensor_folder (str): Path to the sensor folder. Returns: stereo_point_cloud_folder (str): Path to the created point...
a820f93228da7a55876b92868de3b13d05ae08a2
38,506
def steps(number): """ Count steps needed to get to 1 from provided number. :param number int - the number provided. :return int - the number of steps taken to reach 1. """ if number < 1: raise ValueError("Provided number is less than 1.") steps = 0 while number != 1: s...
8681691946b5ba2d261a1ae753d2a04c46ac1719
38,507
def labs(**kwargs): """ Change plot title, axis labels and legend titles. Parameters ---------- kwargs : dict A list of new name-value pairs where name should be an aesthetic, e.g. title='Plot title' or aesthetic='Scale label'. Returns ------- `FeatureSpec` or `FeatureS...
45c0038e694b730a92d35c407ddb4a4cb639647b
38,508
def nested_dict_values(d): """ Extracts all values from a nested dictionary """ listvals = list(nested_dict_gen(d)) listvals_unwrapped = [] for l in listvals: if type(l) == list or type(l) == np.ndarray: for ll in l: listvals_unwrapped.append(ll) else:...
cfeb0a5fb782240e622b3dd21a47ce10143af569
38,509
import os import glob import torch def load_model(model, load_from, load_dict={}): """loads the weights of a model from a folder. :param model: torch model :type model: torch.nn.module :param load_from: either a filename or a folder where a list of weights are stored :type load_from: str :p...
f406e5c8ae902ed560de2d7ea95883d9430c2e07
38,510
import numpy def _get_sr_pod_grid(success_ratio_spacing=0.01, pod_spacing=0.01): """Creates grid in SR-POD space SR = success ratio POD = probability of detection M = number of rows (unique POD values) in grid N = number of columns (unique success ratios) in grid :param success_ratio_spacin...
6349afbecc8994c1078f2fa019a5a721862b0d15
38,511
from typing import Optional from typing import Set async def all_upcoming_broadcasts( seconds: Optional[int] = None, ) -> Set[TextChannel]: """All upcoming broadcast channels that have yet to be announced. If minutes are given, then it will only mention the events comming up in the given number of minutes...
bdb52910824a284b89676d3b2b2bc7a296353b50
38,512
def jd2iso(jd): """Convert a Julian date into an ISO 8601 date string representation""" return astropy.time.Time(jd, format='jd', scale=time_scale, precision=0).iso
6c8111d78adff702a22347c2cf1855ceddcc8d55
38,513
def MakeOnnxInputsOutputs(name, elem_type, shape, **kwargs): """Wrapper for creating onnx graph inputs or outputs name, # type: Text elem_type, # type: TensorProto.DataType shape, # type: Optional[Sequence[int]] """ if elem_type is None: elem_type = onnx_pb.TensorProto.UNDEFI...
e9fc478ff715584752e5ed69ec2c9c826ce76a9d
38,514
def geom_lst_to_gdf(lst): """Convert geometry or geometry list to gdf. Args: lst (geometry|list(geometry)): The geometry or geometries. Returns: gpd.GeoDataFrame: The geodataframe. """ if not isinstance(lst, list): lst = [lst] return gpd.GeoDataFrame( {'ge...
5189e77a5c4d1701aaee6feea5b4f1b80a86c0e4
38,515
def build_get_enum_valid_request( **kwargs # type: Any ): # type: (...) -> HttpRequest """Get enum array value ['foo1', 'foo2', 'foo3']. 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...
654c0de7e0efc219406e42f6395ed214aa92aeb5
38,516
import scipy def ks_2samp(data1, data2): """ Computes the Kolmogorov-Smirnov statistic on 2 samples. This is a two-sided test for the null hypothesis that 2 independent samples are drawn from the same continuous distribution. Parameters ---------- a, b : sequence of 1-D ndarrays tw...
58854c49fe6adbbc747579f5c38c00673430d21d
38,517
def list_shows(): """ return all the shows """ shows = ShowRun.query.all() ret = [] for show in shows: ret.append({'show_id': show.id, 'show_date': show.created_date, 'show_status': show.status.name}) return jsonify({'date': ret})
2008646c0c911de0012a5cfc4e6187c2e0406c2f
38,518
from typing import Dict import re def _replace_spec_toks(mthd: str, spec_toks: Dict[str, str]) -> str: """ Performs the replacement of special tokens by the original ones """ spec_toks = spec_toks.copy() # Add special tokenizer tokens -> deleted for code analysis spec_toks['<bos>'] = "" sp...
0c1b9ec96880c2c488952f238dd146719398cbcd
38,519
def redirect_to_user_chat(markup: ReplyKeyboardMarkup): """ Clean the bot commands from the group chat and send the message to a user. Args: markup: ReplyKeyboardMarkup Returns: None or Calls decorated function if in the user's chat. """ def decorator(func): ...
c8feae1ed2e3f3b5e44309b17f04dc54ba7c6e30
38,520
def run_intcode(memory, input_list): """Run an Intcode program from memory and return the result""" instr_ptr = 0 input_ptr = 0 output = None while instr_ptr < len(memory): instruction = memory[instr_ptr] digits = list_digits(instruction) # extract opcode opcode_pair...
0941d13400ca170714d41476d6cf72a4942e9c97
38,521
from typing import Union from typing import Optional def get_kubeflow_value( tfx_value: Union[int, float, str, Text]) -> Optional[pipeline_pb2.Value]: """Converts TFX/MLMD values into Kubeflow pipeline Value proto message.""" if tfx_value is None: return None result = pipeline_pb2.Value() if isinstan...
5f579f5b34261dad2f753d73dd5fe4c36cf34d8f
38,522
def read_parquet( path, engine: str = "auto", columns=None, storage_options: StorageOptions = None, use_nullable_dtypes: bool = False, **kwargs, ): """ Load a parquet object from the file path, returning a DataFrame. Parameters ---------- path : str, path object or file-like...
ea8264bbda6293a07059a7a0ebd85c15a844bdf1
38,523
import torch def calculate_cis_nominal(genotypes_t, phenotype_t, residualizer=None, return_af=True): """ Calculate nominal associations genotypes_t: genotypes x samples phenotype_t: single phenotype residualizer: Residualizer object (see core.py) """ p = phenotype_t.reshape(1,-1) r_no...
ad73cdcb962f7108761833a83e847e1dcaf9b249
38,524
def get_ver(): """Read out the version number of the radio""" return radio_get_ver_fn()
03b20e4c4e60807327f593f36605fa651350a1af
38,525
def get_entities_list(token, aiid): """Returns a list of all entities for an AI""" return fetch_api('/entities/{aiid}', token=token, aiid=aiid)
d660e56c9e94e1ae587b037571e9120df5acf8bd
38,526
def read_P23_from_sequence(file): """ read P2 and P3 from a sequence file calib_cam_to_cam.txt """ P2 = None P3 = None with open(file, 'r') as f: for line in f.readlines(): if line.startswith("P_rect_02"): data = line.split(" ") P2 = np.array([floa...
eb4e334a8dfac11c86d837640b47f3a48880af90
38,527
def openConnection(): """ Method that starts a connection with the database :return: the driver for the connection """ connection = nj.GraphDatabase.driver( uri=URI, auth=nj.basic_auth(USER, PASSWORD)) return connection
35db801d44e143007c0972747380e942fbbdee0f
38,528
from .views import item_methods def resource_view_attrs(raml_resource, singular=False): """ Generate view method names needed for `raml_resource` view. Collects HTTP method names from resource siblings and dynamic children if exist. Collected methods are then translated to `nefertari.view.BaseView` ...
63f2687b0e0fdde3d3749dade2a706818ac9acce
38,529
def total(inarray, axis, type='meanclip'): """ Collapse 2-D array in one dimension. .. note:: MYTOTAL routine from ACS library. Examples -------- >>> collapsed_array = total(inarray, 1, type='median') Parameters ---------- inarray : array_like Input 2-D array. axis : ...
f3083d53eea18303594d21fff53073c79a84e9dc
38,530
def check_rack_shape_match(source_shape, target_shape, row_count, col_count, translation_behaviour=None): """ Checks whether two rack shape match the given rack transfer or translation behaviour. :Note: One-to-one translations can not be discovered ...
273691fca54b93ab8725b4c5f2e89e00cec03d4b
38,531
def deny_request( request_id ): """Denies a given request for slots No request params. """ try: req = SlotRequest.get( SlotRequest.id == request_id ).select().join( User ).first() print(req) g.user.deny_request( request_id ) rs = RadioStation.get() send_mail( '{}...
022485b485172f7501ea021fec9d712c7d6862c0
38,532
def make_env(rank, seed=0): """ Utility function for multiprocessed env. :param env_id: (str) the environment ID :param num_env: (int) the number of environments you wish to have in subprocesses :param seed: (int) the inital seed for RNG :param rank: (int) index of the subprocess """ de...
00732e1373bd2ca4536f9612ba4ad268b606307b
38,533
def blur(img_array, blur_factor): """ Blur the image by Gaussian Blur, and it has effects on every channel. Recommend: int around 5. """ for i in range(3): img_array[:, :, i] = ndimage.gaussian_filter(img_array[:, :, i], blur_factor) return np.uint8(img_array)
d26184c85889b496b684ece8a3caf5bcd1f36a27
38,534
def add(a, b): """Adds two integers""" return a + b
5e91983492e1995437c2810c2d7c04cdd9180906
38,535
def usmap(scenario,mode,yyyy,save='n'): """ scenario: 'base', 'bakken_rail_cap', 'US_midwest_pipelines', 'US_export_ban_lifted' mode: 'Rail', 'Pipeline' years: 2012, 2015, 2018 save: 'y', 'n' """ m = Basemap(width=12000000,height=7000000, rsphere=(6378137.00,6356752.3142),\ resolution='l',area_thresh=1000.,p...
497a29913914639ae28bda82750b99e9cf2ef361
38,536
def get_python_packages(Debug): """ Retrieves the version of the python packages installed in the system. It retrieves the dependencies name conversion from file :file:`XICRA/config/python/module_dependencies.csv` using function :func:`XICRA.config.extern_progs.file_list` and :func:`XICRA.scripts.functions.main_fu...
c8ca5521603959e8d68391a32688d8fe4409fdb1
38,537
import re def replace_space(string): """Replace all spaces in a word with `%20`.""" return re.sub(' ', '%20', string)
9b9b400f913efb7ee1e86a87335955744c9b1a3a
38,538
import numpy def _get_sitk_pixelid(numpy_array_type): """Returns a SimpleITK PixelID given a numpy array.""" if not HAVE_NUMPY: raise ImportError('Numpy not available.') # This is a Mapping from numpy array types to sitks pixel types. _np_sitk = {numpy.character: sitkUInt8, n...
1ec0f992ebc786824e02a011f26137e7298580ff
38,539
import re def port_to_string(port): """ Returns clear number string containing port number. :param port: port in integer (1234) or string ("1234/tcp") representation. :return: port number as number string ("1234") """ port_type = type(port) if port_type is int: return str(port) ...
5d526406566c7c37af223ed8e5744ba13771f55f
38,540
from typing import OrderedDict def get_s_macd(c: analyze.CZSC, di: int = 1) -> OrderedDict: """获取倒数第i根K线的MACD相关信号""" freq: Freq = c.freq s = OrderedDict() k1 = str(freq.value) k2 = f"倒{di}K" default_signals = [ Signal(k1=k1, k2=k2, k3="DIF多空", v1="其他", v2='其他', v3='其他'), Signa...
483e9403c74993f9fec175c9adeb3e620ddf8291
38,541
from typing import Optional def code_block(text: str, language: Optional[str] = None) -> str: """Creates a code block using HTML syntax. If language is given, then the code block will be created using Markdown syntax, but it cannot be used inside a table. :param text: The text inside the code block :...
5d8b272d2a93463171e5a51beaccd8293db280dc
38,542
from typing import Counter def test_network(neural_network, input_window, input_max, test_location=None, test_class=None, submission=False): """Test the performance of the neural network classifier against known spikes classes.""" if submission: # If submission flag, define the indices of submission ...
a32ea3adfd9998d107135191aff8b95767d46cf0
38,543
def not_found(): """Page not found.""" return render_template('404.html')
6a299f514d62c3be42a1d1e351cb6f11eaf02e8b
38,544
import os def generate_aes_256_key(): """ This function generate a AES 256 bits long, using the package crypthography. @param None @return: (list[Key_of_AES,random_bytes_cbc,Obj_Cipher_AES]) return a 256 bytes AES key and object AES, or 0 """ try: key_dec_enc = os.urandom(32) mode_vec = os.urandom(16) bac...
09f19d2eb9bc65e7dfacc54e6de9c5dc6ba278ad
38,545
def _histogram_binsize_weighted(a, w, start, width, n): """histogram_even_weighted(a, start, width, n) -> histogram Return an histogram where the first bin counts the number of lower outliers and the last bin the number of upper outliers. Works only with fixed width bins. :Stochastics: a : a...
2c7e26a86bb4b9cd2f8b4b845a2cbae2086c889d
38,546
def merge(line): """ Helper function that merges a single row or column in 2048 """ result = list(line) head = 0 i = 1 while (i < len(result)): if (result[i] != 0): if (result[head] == result[i]): result[head] += result[i] result[i] = 0 ...
1a843ef4dc9c1b6cf20036f24288cb6166ae207b
38,547
def get_transcripts_from_tree(chrom, start, stop, cds_tree): """Uses cds tree to btain transcript IDs from genomic coordinates chrom: (String) Specify chrom to use for transcript search. start: (Int) Specify start position to use for transcript search. stop: (Int) Specify ending position to use for tra...
51aa6f1aa97d2f977840376ea2c4bf422ff8e7a6
38,548
def parse_flattened_result_only_intent(to_parse): """ Parse out the belief state from the raw text. Return an empty list if the belief state can't be parsed Input: - A single <str> of flattened result e.g. 'User: Show me something else => Belief State : DA:REQUEST ...' ...
05c7346197fa3f98f1c4194ea7d92622483d0f51
38,549
def update(*, db_session, user: DispatchUser, user_in: UserUpdate) -> DispatchUser: """Updates a user.""" user_data = jsonable_encoder(user) update_data = user_in.dict(exclude={"password"}, skip_defaults=True) for field in user_data: if field in update_data: setattr(user, field, upd...
786c2ec90a432a5da20b9483b38105d246165bd7
38,550
def cost_table(tea): """ Return a cost table as a pandas DataFrame object. Parameters ---------- units : iterable[Unit] Returns ------- table : DataFrame """ columns = ('Unit operation', 'Purchase cost (10^6 USD)', 'Utility cost (10^6 USD...
17489b80ab871caf9d3029b59e9e7f30cecc2905
38,551
def embed_conformer( mol, forcefield: str = "uff", num_conformer: int = 10, prune_tresh: float = 0.1 ): """Use Riniker/Landrum conformer generator: https://pubs.acs.org/doi/10.1021/acs.jcim.5b00654""" conf_generator = ConformerGenerator() mol, _ = conf_generator.generate_conformers(mol) return mol
515b78ae3e2fe131a554c0878336f26e12ef7bb7
38,552
import argparse def process_command_line(): """ returns a 1-tuple of cli args """ parser = argparse.ArgumentParser(description='usage') parser.add_argument('--config', dest='config', type=str, default='config.yaml', help='config file for this experiment') parser.add_argume...
573ec38b1b57538ebb97b082f71343a49081dfc7
38,553
def setup_august(hass, config, api, authenticator, token_refresh_lock): """Set up the August component.""" authentication = None try: authentication = authenticator.authenticate() except RequestException as ex: _LOGGER.error("Unable to connect to August service: %s", str(ex)) h...
881f35f74c33ba2ab8f606b80e277ebc626f1b4a
38,554
from pathlib import Path def get_default_prms() -> dict: """ Extract the default ampycloud parameters from the YAML configuration file. """ yaml = YAML(typ='safe') out = yaml.load(Path(__file__).parent / 'prms' / 'ampycloud_default_prms.yml') return out
e2f2a057d7584ba447a02506e3a7135f3271df28
38,555
import copy import os def GetEnvArgsForCommand(extra_vars=None, exclude_vars=None): """Return an env dict to be passed on command invocation.""" env = copy.deepcopy(os.environ) env.update(DEFAULT_ENV_ARGS) if extra_vars: env.update(extra_vars) if exclude_vars: for k in exclude_vars: env.pop(k)...
e9cf3c10e93db6e53e10b163eff685da06e5ddec
38,556
def filter_row_by_data_type_audf(col_name, data_type): """ Filter a column using a Spark data type as reference :param col_name: :param data_type: :return: """ data_type = parse_python_dtypes(data_type) return abstract_udf(col_name, is_data_type, "boolean", data_type)
3e8bdccb85532bf70063713049dc04c04344d5fc
38,557
import re def strip_outer_dollars(value): """Strip surrounding dollars signs from TeX string, ignoring leading and trailing whitespace""" if value is None: return '{}' value = value.strip() m = re.match(r'^\$(.*)\$$', value) if m is not None: value = m.groups()[0] return va...
3ad283af2835ba2bcf2c57705f2faa9495ea4e7a
38,558
def process_articles(article_results_list): """ Fuction that processes json result into a list :return: a list of news articles """ articles=[] for item in article_results_list: id = item.get('id') author = item.get('author') title = item.get('title') description ...
98fcddcf8a97eb7a30e2872844f3e81d7182f10b
38,559
def attrgetter_atom_split(tokens): """Split attrgetter_atom_tokens into (attr_or_method_name, method_args_or_none_if_attr).""" if len(tokens) == 1: # .attr return tokens[0], None elif len(tokens) >= 2 and tokens[1] == "(": # .method(... if len(tokens) == 2: # .method() return ...
4ed19a1ea087d1b92fbe9743421ef51c560bced1
38,560
def pytest_funcarg__barcamps(request): """return the barcamp collection""" config = request.getfuncargvalue("config") return config.dbs.barcamps
23c3aea374428ab1045c422f0b8efb72be33f5c8
38,561
import logging import psutil def stop_service(service_name): """Stops the given service by sending unix control signals to the process. Waits for the process to stop before returning from the function. Kills the process and any children processes if the process does not exit normally.""" servic...
1349d8b51f1934324c166ae2bf5ee1c5e61f0c31
38,562
import json def mark_as_read(request, app_key, user_id): """ mark all unread notifications for that user, as read """ app = Application.objects.get(secret_key=app_key) unreads = get_unread_logentry_list(app, user_id) for log in unreads: logentryread = LogEntryRead(app=app, log=log, user_id=user_id) logentry...
0b6934b093e3b79984237cced5b3b272017a5eed
38,563
def gauss(r, A, l): """Gaussian""" return A * np.exp(-0.5 * (r / l) ** 2)
46afc9c0130d562b66a95a64c66c7ffba614846a
38,564
import copy def variability(model_variability, variable_list=None): """Perform thermodynamic variability analysis. Determine the minimum and maximum values for the input variables (Flux, Gibbs free energies and metabolite concentrations). if min_growth constraint is applied then growth is maintained ...
6484c18f424330e15ea7b64d64d4acd4ba4a5bde
38,565
def tabuleiro_inicial(): """ tabuleiro_inicial: {} >>> tabuleiro - Um "mirror" para a funcao "str_para_tabuleiro" com um valor especifico. Devolve sempre o mesmo tabuleiro. """ return str_para_tabuleiro("((-1, -1, -1), (0, 0, -1), (0, -1))")
4ac3c124fde952d0cb94496499eff9998fb29c2f
38,566
def create_processor_names_for_branch_action(processor_name, processors_to_add, seff, mapping_cache): """ If current seff contains a BranchAction, check if copying processor is required, if true: create corresponding processor names and add to processors_to_add. If branch action does not require creation of...
5b50392abf58857742a36b45dd6ef152a4844c53
38,567
def cast_to_scalar_tensor_of_dtype(t, dtype): """If not yet a tensor, casts it to a constant scalar tensor.""" if issubclass(type(t), ops.Tensor): return t return array_ops.constant(t, shape=[], dtype=dtype)
d3c85844b636d708686ab98a7b38a672ffd45009
38,568
import os def menu_select(title='~ Untitled Menu ~', main_entries=[], action_entries=[], prompt='Please make a selection', secret_exit=False): """Display options in a menu for user selection""" # Bail early if (len(main_entries) + len(action_entries) == 0): raise Exception("MenuError: No items gi...
2495d79218e03430642eb4d099223fa2e2f3b357
38,569
def plot_stacked_bar_chart(data, series_labels, col_labels=None, x_label=None, y_label=None, log_scale=False): """ For plotting e.g. species distribution across locations. Reference: https://stackoverflow.com/questions/44309507/stacked-bar-plot-using-matplotlib Args: data: a 2-dimensional numpy ...
fd125eb1495d3264e8e9ec4bec29d2387a19d4de
38,570
def check_is_admin(roles): """Whether or not roles contains 'admin' role according to policy setting. """ init() return policy.check('context_is_admin', {}, {'roles': roles})
daecaf480916d7576c9aa0a42ea949eb2ea6e0d0
38,571
from typing import Sequence from typing import Tuple def merge_requirements( requirements: Sequence[Tuple[Feature, Requirements]] ) -> Tuple[Feature, Requirements]: """Determine the lowest common denominator in the given requirements.""" if len(requirements) == 1: return requirements[0][0], requir...
2fc98482311b374d8d2d3d222a1113fab75f74e1
38,572
def resource_data_get_all(resource, data=None): """ Looks up resource_data by resource.id. If data is encrypted, this method will decrypt the results. """ if data is None: data = (model_query(resource.context, models.ResourceData) .filter_by(resource_id=resource.id)) if...
f4370f7d7f9d8a7a338ba964c7958b26bf7bc849
38,573
def setig(): """The """ return load(_os.path.join("npc", "setig.csv"))
60f2c8849830b4af0512065c42203bdff05c06bc
38,574
import os def does_file_exist(file, proj_dir): """Determine if a file in our persistent data still exist. If file is not absolute, will check if relative from the project directory exists. Args: file (str): Relative or absolute file path to check the existence of proj_dir (str): Project pa...
e7b6c514c4d5de3acfde55b2739bb7e5a06b8da3
38,575
from typing import Optional def serialize(model, data, fields=None, exc: Optional[set] = None, rels=None, root=None, exclude=None, functions=None, **kwargs): """ This utility function dynamically converts Alchemy model classes into a dict using introspective lookups. This saves on manually m...
5a6350347ac58e12b9400137796ac701e3002447
38,576
from datetime import datetime def interval( value: int | datetime.timedelta | None = None, unit: str = 's', years: int | None = None, quarters: int | None = None, months: int | None = None, weeks: int | None = None, days: int | None = None, hours: int | None = None, minutes: int | ...
11448a6e99fd547f241721cf2d4f3ea8e7469d7a
38,577
def numpy_product(quat0, quat1): """Returns the quaternion product of q0 and q1.""" quat = np.zeros(4) x0, y0, z0, w0 = quat0[0], quat0[1], quat0[2], quat0[3] x1, y1, z1, w1 = quat1[0], quat1[1], quat1[2], quat1[3] quat[0] = w0*x1 + x0*w1 + y0*z1 - z0*y1 quat[1] = w0*y1 - x0*z1 + y0*w1 + z0*x1 ...
a76d25b372c7a565e4cc7f535ff0ff49130b9adb
38,578
def estimate_price(mileage, theta0, theta1): """ Estimate price function: """ return theta0 + theta1 * mileage
43ba05aacc3cb94f9bf3223f6ea8f74a569c2537
38,579
def init_axis(title = '', geometry = ''): """ Initializes plotting area and returns a handle for plot area :param None: :return: Axis object """ fig = plt.figure() ax = fig.add_subplot(111) plt.axis("equal") mngr = plt.get_current_fig_manager() #mngr.window.setGeometry(50,100,640, 545) mngr.window.wm_geome...
cb31c8c9a35ba5b0bfde862bb9daac37d94a5cb4
38,580
def similar_date(anon, obj, field, val): """ Returns a date that is within plus/minus two years of the original date """ return anon.faker.date(field=field, val=val)
d9a723d3c22954797895b43d57f297330272c8cb
38,581
def launch_request_handler(handler_input): """Handler for Skill Launch.""" return launch_request(handler_input)
e5df4bcfaa2b39adc1afd1ca9d5da1227441d8f1
38,582
def tweetDiv(tweet): """View text of tweet""" res = '<div class="panel"><div class="header"><img src="' res = res + tweet['user']['profile_image_url'] res = res + '" ><div class="text">' res = res + tweet['user']['name'] res = res + '</div></div><p><small><small>' res = res + tweet['created_...
c852c8bf2181636f3052dc9a94d6e435fafe216a
38,583
from typing import Union from typing import Optional def variable_like(inputs: Union[tf.Tensor, tf.Variable], initializer: initializers.Initializer = initializers.Zeros(), trainable: Optional[bool] = None, name: Optional[str] = None) -> tf.Variable: """Creates a...
a44a4d598f4d8fd625389262719e4bcbc727896e
38,584
def make_signing_service(config, entity_id): """ Given configuration initiate a SigningService instance :param config: The signing service configuration :param entity_id: The entity identifier :return: A SigningService instance """ _args = dict([(k, v) for k, v in config.items() if k in KJ...
603d47cf08779a7d36238c5a8cd8ac3c0dacba40
38,585
from functools import reduce def fsum(iterable): """fsum(iterable) Return an accurate floating point sum of values in the iterable. """ return reduce(Add, iterable)
ece802387b3e2910d45ec9a520c51702216543fb
38,586
def structure_sampling_values(graph, centrality, function): """ helper function to compute the centrality values for an edge""" cent = centrality.get_values(graph) edges = graph.get_edges() left_values =cent[edges[:,0]] right_values=cent[edges[:,1]] values = function(left_values, right_values) ...
a0608646867704dea6b1e27e4cfee8b3062ab0da
38,587
from pathlib import Path from typing import Union def riglob(path: Path, pattern: str = None, regex: Union[str, PTYPE] = None, files=True, directories=True): """same as Path.rglob method, but instead match on given pattern or regex, case-insensitively, and filtering on path type (file and / or directory I...
44579b2e243f66f80d368ef49f9b34057875b038
38,588
def get_all(isamAppliance, check_mode=False, force=False): """ Get information on all existing Transactions """ return isamAppliance.invoke_get("Retrieving a list of transactions", "{0}".format(module_uri), requires_modules=requires_modules, requires_version=requires_...
2dbc495db106e500279909cbe25d9a940272d498
38,589
def get_naive_affinities(raw, offsets): """get naive pixel affinities based on differences in pixel intensities.""" affinities = [] for i, off in enumerate(offsets): rolled = np.roll(raw, tuple(-np.array(off)), (0, 1)) dist = np.linalg.norm(raw - rolled, axis=-1) affinities.append(di...
f405b30a796539418d4f1a71bb544d502a1264dd
38,590
def generallaplacian(W, G=None): """ Compute the general laplacian of graph. Parameters: - - - - - W: float, array weight adjacency matrix Returns: - - - - L: float, sparse array surface mesh Laplacian matrix """ [D, Dinv] = degree(W) n = D.shape[0] i...
0af8e2a9ab71d7d6730689d282427cfe208e6564
38,591
def dummy_wrapper(fn): """Simple wrapper used for testing""" def _run_callable(*args, **kwargs): return fn(*args, **kwargs) return _run_callable
60d92942fd1d87b835ea05dd00baea8a71117fac
38,592
def _validate_privatekey_pem(key_pem): """Implement private key validation. Args: key_pem (str): RSA PKCS#8 PEM private key (traditional OpenSSL format) of at least 2048 bit strength. """ assert isinstance(key_pem, str) # Create the cryptography package private key object and p...
d520ba02a4dce0cc47885f252a6edda2aa138023
38,593
def integrate(func,a,b): """ Wrapper for definite integration using scipy.integrate.quad(). """ ## calculate integral and error val, abserr = spint.quad(func,a,b, limit=100) ## get relative error relerr = np.nan if val != 0: relerr = np.abs(abserr/val) ## warning parameters maxrel, maxabs = 1e-4, 1e-6 ## e...
f16d46088f7aa9d2b575a4bf63736b65642764d4
38,594
def get_backlinks(dictionary): """ Returns a reversed self-mapped dictionary @param dictionary: the forwardlinks """ o = dict() for key, values in dictionary.items(): try: for v in values: try: o[v].add(key) except KeyE...
43b28e4f177a7813ba8d8c0960d04e71ad28f83b
38,595
def shift_date(date_str, n): """ :param date_str: 日期, 'YYYYMMDD'格式的字符串 :param n: 时间跨度, int :return: 调整后的交易日,date """ tc = ts.util.dateu.trade_cal() tc = tc[tc.isOpen == 1] tc.set_index('calendarDate', inplace=True) if len(tc[:date_str]) < n: return tc.iloc[0].name else...
7a9a1cb500e9ac38b5a51a17b35e05d33760ea32
38,596
def mfcc_filter_banks(sampling_rate, num_fft, lowfreq=133.33, linc=200 / 3, logsc=1.0711703, num_lin_filt=13, num_log_filt=27): """ Computes the triangular filterbank for MFCC computation (used in the stFeatureExtraction function before the stMFCC function call) This function is t...
99f08847b24785afdacdd5769656bc0aa4a8218b
38,597
import os import pickle def train(version, n_epochs, batch_size, lr, dr, l1, l2, bn, deconvolution, n_base_filters, depth, filter_size, activation, final_activation, n_classes, optimizer, loss_function, metrics, n_train_patients, n_val_patients, checkpoint_model, models_dir, train_featur...
2ccb941b66435945f1e744a7ad9959996ecdffa9
38,598
def make_BinaryQuadraticModel_from_JSON(obj: dict): """make BinaryQuadraticModel from JSON. Returns: corresponding BinaryQuadraticModel type """ label = obj['variable_labels'][0] if isinstance(label, list): #convert to tuple label = tuple(label) mock_linear = {label:1....
e95329fedb4ca997452a38158fa3a0d1c504f26a
38,599