content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from datetime import datetime def undersc_str2dt(undersc): """Converts the format with underscores to a datetime instance Args: undersc(str): time in underscores-format Returns: `datetime`: datetime instance """ (mydate, mytime) = undersc.split("_") ymd = mydate.split("-") ...
36988c6af6a20590d781f7ec1ea1ee2e8713941e
3,615,800
def console_to_str(s: bytes) -> str: """From pypa/pip project, pip.backwardwardcompat. License MIT.""" try: return s.decode(console_encoding, "ignore") except UnicodeDecodeError: return s.decode("utf_8", "ignore")
86940f491c4d2bc9f3ac345e613f464f531b881a
3,615,801
def make_animation_all_channels(satellite: Satellite, example_index: int): """ Make animation of all channels An animation is made over time. Subplots show the different satellite channels Args: satellite: satellite data example_index: which example to use Returns: plotly figure ...
28dc3f9bf86e09e752c0c1a73d749c680b36bc35
3,615,802
import os def convert_path_extension(path, conversion = '.png'): """Converts a path extension to a different one (as provided).""" # Get the image name and create the final filepath. filename, _ = os.path.splitext(path) save_path = filename + conversion # Append the new path to the return list. ret...
6aae3c63885013a05b66e71dc9b90f5c623d2515
3,615,803
def mgmt_lock(timeout=MGMT_LOCK_TIMEOUT, key_args=(), key_kwargs=(), wait_for_release=False, bound_task=False, base_name=None): """ Decorator for runtime task locks. This means that task will run, but will wait in a loop until it acquires a lock or will fail if timeout is reached. """ ...
39d6b11d7a7e53b12cbfd8eedfa8882eb5ccc554
3,615,804
from weasyl import moderation, login def common_status_page(userid, status): """ Raise the redirect to the script returned by common_status_check() or render the appropriate site status error page. """ if status == "admin": return errorpage(0, errorcode.admin_mode) elif status == "loca...
8f887edb17a2c13cefce699a874ef551e33e0139
3,615,805
def get_value(rgb, animated=False): """ Obtains pixel value if it is enabled. Color is not supported yet here. :param rgb: :param animated: It is a WTF from SP1. If I do animation it requires me to invert the values... :return: """ if rgb[0] > 0 or rgb[1] > 0 or rgb[2] > 0: return "...
da154d07ca007c183a62ea05a9b6bb5d467b6b0c
3,615,806
def get_ldap_conn(host, username, password, reuse=None): """ Returns an LDAP connection """ if reuse: ldap_conn = reuse else: ldap_conn = initialize("ldap://"+host) try: ldap_conn.bind_s(username, password) except Exception as err_msg: return False, 'Error: {}...
9d51c34f65e2d8013a9d86a22aa935b2b26d1980
3,615,807
def make_profile_middleware( app, global_conf, log_filename='profile.log.tmp', limit=40): """ Wrap the application in a component that will profile each request. The profiling data is then appended to the output of each page. Note that this serializes all requests (i.e., removing c...
cad275e1a9448af1453ec5eeff421e12620c9387
3,615,808
def dup_children(my_task, file_info, children, copy_bfid, fcc): """ Create duplicates of package children in FC DB for copy of package file copy_bfid. It is metadata operation, no data copied. Get children of this package identified by file_info Children information is used to create children copies in...
1568f56d1b5188287e4e185fbec5fd659df60518
3,615,809
def encode_matrix_fbs(matrix, row_idx=None, col_idx=None): """ Given a 2D DataFrame, ndarray or sparse equivalent, create and return a Matrix flatbuffer. :param matrix: 2D DataFrame, ndarray or sparse equivalent :param row_idx: index for row dimension, Index or ndarray :param col_idx: index for col...
193abb2690a80c2875056f5d8ffcd2467f4a81c8
3,615,810
def get_facets(query, params, limit=10, referrer=None): """ High-level API for getting 'facet map' results. Facets are high frequency tags and attribute results that can be used to further refine user queries. When many projects are requested sampling will be enabled to help keep response times low...
e47baac1d0d8341d182a15d204b1b3bf6f5185cb
3,615,811
import torch def mAP(pred, target, cutoff=.5): """ Computes the Average Precision of the semantic segmentation Arguments: pred: predicted segmentation output by network target: binary segmentation targets cutoff: prediction cutoff for foreground vs background """ with torc...
4b2978a1dfec690aa43b6829c6c19ea88180cdca
3,615,812
import os def get_linkage_matrix(run_parameters, linkage_matrix, indicator_matrix): """ read bootstrap temp_h* and temp_p* files, compute and add the linkage_matrix. Args: run_parameters: parameter set dictionary. linkage_matrix: connectivity matrix from initialization or previous call. ...
55c8cb39035ca52a87b4d59ece2f4b13eda3d1fd
3,615,813
def create_User(name, email): """Create a new User. Args: name ([string]): The name of the User email ([string]): An email Raises: exceptions.DatabaseError: if an errors occurs during SQL execution Returns: [User]: A User model """ LOGGER.info("Create a User %...
707cdfff60fdc4ef84dc5a55bd9a3ea6f8bc78b6
3,615,814
import yaml def load_yaml_config(filepath): """Load Krake base configuration settings from YAML file Args: filepath (os.PathLike, optional): Path to YAML configuration file Raises: FileNotFoundError: If no configuration file can be found Returns: dict: Krake YAML file config...
a5970ab968a9da7c89733077834a88b05ca2d6a0
3,615,815
def insert_pms(payloads, app_name): """Summary Args: payloads (TYPE): Description Returns: TYPE: Description """ responses_list = [] for payload in payloads: print("inserting", payload) response = knackpy.record( payload, obj_k...
9247d8d7b8bcfce97794d40a6dcbd1564fba0853
3,615,816
def max_cum_build_rule(mod, g, p): """ **Constraint Name**: GenNewLin_Max_Cum_Build_Constraint **Enforced Over**: GEN_NEW_LIN_VNTS_W_MAX_CONSTRAINT Can't build more than certain amount of capacity by period p. """ return mod.GenNewLin_Capacity_MW[g, p] \ <= mod.gen_new_lin_max_cumulativ...
9122a05867ccccbe36378c36d34e98462c62f85d
3,615,817
import json def preprocess2(lowercase, break_hashtags, replacements, line): """ returns lowered line """ try: tweet = json.loads(line) text = tweet['text'] except: tweet = dict() text = line.decode('utf8') # Break hash sign: #hashtag -> # hashtag if break_hashtags:...
7e833af980e2d881d3dee61845fd507eed2b0d6e
3,615,818
def get_vrf_description(device, vrf): """Gets description of configured VRF. Args: device (Device): This is the device object of an NX-API enabled device using the Device class within device.py vrf: case-sensitive VRF (because 'show run section $VRF' is being used) Returns: ...
aedd4bcf3792a94b4b0df5fdad7bf12c8dffb87a
3,615,819
from torch import as_tensor def normalize(tensor, mean=NORMALIZE_MEAN, std=NORMALIZE_STD, inplace=False): """ Normalizes image tensor using VGG mean and std. Assumes image has [0,1] values. Accepts CxHxW or BxCxHxW images. """ if not inplace: tensor = tensor.clone() dtype = tenso...
f98d52212169437ef020d783f26a45ea54831545
3,615,820
import warnings def _scale_factory(scale, axis, *args, **kwargs): """If `scale` is a `~matplotlib.scale.ScaleBase` instance, nothing is done. If it is a registered scale name, that scale is looked up and instantiated.""" if isinstance(scale, mscale.ScaleBase): if args or kwargs: wa...
85111485ebf53f1b9902820882b19f52442de067
3,615,821
def clean_job_task(job_id, db_name=config.PG_JOB_TASK_DB_NAME): """This will directly clean job and related task from db""" deletion_command = f"""DELETE FROM "Task" WHERE "jobId"='{job_id}';DELETE FROM "Job" WHERE "id"='{job_id}';""" client = postgres.PGClass(config.PG_HOST, db_name, config.PG_USER, config...
ba42ebb024ff812e751fbde12f9f3e213bab91f9
3,615,822
from pathlib import Path import logging def call_qualimap(bamfile: Path, outdir: Path) -> Path: """ Makes a system call to Qualimap with the provided .bam file. Finds and returns the output file (genome_results.txt) :param bamfile: .bam file generated via BBmap.sh :param outdir: output directory for Q...
f05776ee6b4d20e8622ea4697744d5cb68253b51
3,615,823
def _pos_phrases(tokens, preprocess): """Extract phrases from a text using POS Tagging-derived rule-based approach. Args: tokens (list of str): A list of semantically-ordered tokens. preprocess (callable): A function that pre-processes the extracted phrases. Returns: li...
f3bf9f0acecda39281e9ba90f5bebc5248c22603
3,615,824
import json def create_controller(): """ 1. Check the token 2. Call the worker method 3. Show results """ minimum_buffer_min = 3 if views.ds_token_ok(minimum_buffer_min): # 2. Call the worker method args = { 'account_id': session['ds_account_id'], 'b...
2426c999b9d82db1c0a8403f1e874eb0e2307eb3
3,615,825
import os def writeValidUtf8(in_filename, out_filename, skipOrReplace = 'replace'): """ Read the input file bytes and write it to the output file as UTF-8. When skipOrReplace is skip, drop the invalid bytes, else replace them with U+FFFD. """ # Read the input file into memory as bytes. if not os.path.ex...
910f197d2657d03891e6d4e76161457773504a73
3,615,826
def total_seconds(td): """Since ``timedelta.total_seconds()`` is new in 2.7""" return float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
8a25267b3c61a41dee1cbe643174fd20ebb7d835
3,615,827
def review_table(queryset: QuerySet, fields_str: str) -> dict: """ This tag displays a QuerySet of reviews as a table :param queryset: The set of Reviews to display :type queryset: QuerySet :param fields_str: The fields to get for each review :type fields_str: str :r...
76632f481b459350299bf00dd6e15af1dd133bdd
3,615,828
from re import T def get_sparsity_penalty(nnet, inputs, sparsity, mode="mean", deterministic=False): """ returns the sparsity penalty on network activations combined as a sum """ assert mode in ("mean", "l1") rho = sparsity penalty = 0 eps = 0.0001 # for numeric...
4804b41446ae32d90b2c787692da014da983a964
3,615,829
def generate_config(context): """ Entry point for the deployment resources. """ properties = context.properties name = properties.get('name', context.env['name']) project_id = properties.get('project', context.env['project']) zone = properties.get('zone') # Network formatting if 'network' ...
3976f7e52f652ef0e0467cc5afec00d821fcd956
3,615,830
from dateutil import tz from datetime import datetime def tznow(time_zone="Europe/London"): """ # to get the list of time zones: #from dateutil.zoneinfo import get_zonefile_instance #print(list(get_zonefile_instance().zones)) # over 500 timezones """ my_tz = tz.gettz(time_zone) # or =tz.get...
4fe3e65fecc9adce09ba74910b82aff1ac6f5b11
3,615,831
def create_table(): """Создает пустую таблицу для тестов.""" id_ = base.create_id(ports.USD, ports.USD) return usd.USD(id_)
7aad4c5422adb4a75192c6498b4f3df2ee233412
3,615,832
def load_yaml(yaml_file_path, logger): """ Read a yaml file from the filesystem and return it as a dict Returns 'None' if the file is not found :param yaml_file_path: string - Location of the yaml file to be read :param logger: Logger - Logger for logging events """ if file_exists(yaml_file...
e9ece324a8fdfab903241957e68ff2f57206ad3a
3,615,833
from typing import List def available_years() -> List[int]: """List available years with datasets.""" return [2012, 2013, 2014, 2015, 2016, 2017, 2018]
898fd02e0cde1ac71251cd70069c52c481a66acf
3,615,834
def rotational_groups(rxn, key1, key2, dummy=False): """ Obtain the rotational groups for a given rotational axis :param rxn: a hydrogen migration Reaction object :param zma: a z-matrix; if passed in, the linear atoms will be determined from this; otherwise they will be determined heuristically fro...
a61286aeb183c62875c1f1e7f6aed12f3eee5ba5
3,615,835
from typing import Any from typing import Dict from typing import Optional import requests def main(*wtf: Any, **kwwtf: Any) -> Any: """ 入口函数。该函数用于在允许直接运行的同时,兼容 GCP Cloud Function/AWS Lambda 等云函数平台。 :return: 由检测到的平台决定 """ config: Dict[str, Optional[ConfigValue]] = initialize_config(CONFIG_SCHEMA)...
5db680d4c4d0083d5b83b1de9f9b1824826a544f
3,615,836
def plot_ecdf_all_states(df_mape): """Function for ECDF plots for all states Args: df_mape (pd.DataFrame): The dataframe with MAPE values for every model, region Returns: mpl.Figure, [mpl.Axes] : The figure and axes objects """ fig, axs = plt.subplots(figsize=(21, 6*15), nrows=15, ...
2c0ee1dee752f5c0233f1a376bbc13b7ce7f7aa9
3,615,837
def delete_products(wishlist_id, product_id): """ Delete an Product """ app.logger.info( "Request to delete product with id: %s from wishlist with id: %s", product_id, wishlist_id) product = Product.find(product_id) if product: product.delete() return make_response("", status...
01c12911c4844aced4fcf951854852c4e9b17c7f
3,615,838
import aiohttp async def http_call(url, method, data=None, headers=None): """ Performs an http request Args: url (str): The URL to send the request to method (str): The HTTP method to use data (dict): The data to send with the request headers (dict): The headers to send wi...
10d72f32312b7fe9071a8776f784a1ce7c4954d6
3,615,839
import uuid from datetime import datetime def new_flight(app, init_db, new_airplane): """Fixture to create a new flight""" new_airplane.save() flight = { "id": str(uuid.uuid4()), "airplane_id": new_airplane.id, "flight": 'FL111', "check_in": datetime.datetime(2019, 9, 10, 0...
990886f93c0571f97680cd7f7eebcf01be8d3950
3,615,840
import functools def tabulate(start, slots, time_context=None): """Takes a list of slots and converts it into a week schedule table. Args: start: The aware datetime representing the start of the schedule. May be any timezone. slots: The (filled, ordered, annotated) list of timesl...
a00045fc5c684353feef7f7b71efcf82bd79085f
3,615,841
import inspect import warnings def cached(user_function=None, max_size=None, ttl=None, algorithm=CachingAlgorithmFlag.LRU, thread_safe=True): """ @cached decorator wrapper :param user_function: The decorated function, to be cached :param max_size: The max number of items can be held in the cache :...
43dd083a9eb3bdbeee3ee277bf01b764e67073ba
3,615,842
import json def add_comment(blog_id, commenter, comment_content): """ add a comment to a blog post :param blog_id: :param commenter: :param comment_content: :return: """ target_post_key = ndb.Key('Post', blog_id) target_post = target_post_key.get() json_comments = target_post....
3a5589accc27add32099115bdeb2b9a6399bbf14
3,615,843
import asyncio def status_handler(func): """Register the status response handler.""" def register_status(instance_func, address): # This registers all messages for a device but only triggers on # status messages if they return within the TIMEOUT period address = Address(address) ...
0e7c6ccd0d9deece8ed24b3e1ea6883d0a91428b
3,615,844
from typing import Tuple from typing import List def check_all_categories(categories) -> Tuple[List, List, List]: """ Check all categories in ``categories``. Parameters ---------- categories: List A list of categories Returns ------- Tuple[List, List, List] A tuple co...
2727a89e17b90da551ae12020d8d327e49a5a28d
3,615,845
from typing import Counter import re def typographeur(text, fix_parenthesis=True, fix_colon=True, fix_exclamation=True, fix_interrogation=True, fix_semicolon=True, fix_ellipsis=True, fix_point_space=True, fix_comma_space=True, fix_do...
1dc760f87c5fcc2bd404d60ccbaa5c6e3f596189
3,615,846
def get_triggered(categories): """Returns any of the categories exceeding blocking threshold.""" triggered = [] for x in BLOCKED_CATEGORIES: for category in categories: if category.name.startswith(x) and category.confidence > BLOCKED_CATEGORIES[x]: triggered.append((categ...
baeded2cc9fc7b1d4cf8ee65c12cb6450c82f400
3,615,847
import torch from typing import Optional def find_best_peak( values: torch.Tensor, ) -> tuple[Optional[PositiveInt], Optional[float]]: """Takes a Tensor of values (with 1 dimension), and finds the index of the best peak If peak finding fails, (None, None) is returned. Parameters ---------- va...
a4c72e07a9fa2d88dc6f9b0144b84855db8769a3
3,615,848
def delete_records(request): """Deletes all records of model.""" model_id = request.matchdict['model_id'] try: records = request.db.delete_records(model_id) for record in records: request.notify('RecordDeleted', model_id, record['id']) except ModelNotFound: request.er...
7362572eef30a4d4d0bad5f9647dac40be707053
3,615,849
def coordinates_contain_point(coordinates, point): """ This function uses `Crossing number method` (http:#geomalgorithms.com/a03-_inclusion.html) to check whether a polygon contains a point or not. For each segment with the coordinates `pt1` and `pt2`, we check to see if y coordinate of `point` is b...
97176955324be459595503d204e0e13ce9983562
3,615,850
def obstruction(info_dict): """ Obstruction due to M2 """ # Multiply by 1.05 to take the arms into account info_dict["obstruction"] = ( info_dict["M2_factor"] * info_dict["D_M2"] ) ** 2.0 / info_dict["D_M1"] ** 2.0 return info_dict
b67cc8b87d68dbd386d75fdb869f999072085607
3,615,851
def readArduinoData(): """ DOCSTRING: this is the function for reading data from the arduino return : function will return a 3xn matrix containg RGB data and averaged 1D array """ # here finds the port which arduino connected to data = [] PORT = 0 while True: try: ...
5f2bfe1318f8a2548f9690bd58f5b13af28a38d6
3,615,852
def int_sin_m(x: float, m: int) -> float: # pragma: no cover """Computes the integral of sin^m(t) dt from 0 to x recursively""" cosx = cos(x) sinx = sin(x) start = m % 2 res = x if start == 0 else 1 - cosx for p in range(start + 1, m, 2): res = p / (p + 1) * res - cosx * sinx**p / (p + ...
2696b4a4412fad78efa1e06fe90858b68268bc10
3,615,853
def sendmail(subject, message, to_addr): """Web环境下发送邮件""" #: from_addr建议设置发件人邮箱,否则基本会被拦截或进入垃圾邮箱 from_addr = "picbed@{}".format(request.host) from_name = g.cfg.email_from_name or g.site_name #: 关闭通过本地服务器发送邮件 no_local = g.cfg.email_nolocal if is_true(no_local): res = dict(code=1) e...
c0ed81046c11fc760cff23062c916d30a3b04509
3,615,854
import struct def load(filename): """Load image file in .b16 format as used by PCO CamWare and return image data as numpy array. """ # read image file imgfile = open(filename, 'rb') # read binary buf = imgfile.read() imgfile.close() # read header # 32 bit values (long) h...
7bc554e001970ffb68872b09bf3bad0aaf6a3ab9
3,615,855
def stanza_factory(xmlnode, stream = None): """Creates Iq, Message or Presence object for XML stanza `xmlnode`""" if xmlnode.name=="iq": return Iq(xmlnode, stream = stream) if xmlnode.name=="message": return Message(xmlnode, stream = stream) if xmlnode.name=="presence": return Pr...
f46d7f6f1cc69f4896846192857b18d6e3cc2b0f
3,615,856
def _request_sts_credentials(billing_account_id, options): """ Request STS Credentials to get access to the billing account. With the assumed role, this script will be able to traverse over the member accounts in the AWS Organization. Args: billing_account_id (str): The Billing/Root AWS Acc...
0d4ce0c87535e1db0769897b19de6877ece66a20
3,615,857
def read_config_file(given_cfg_file=None): """Return a dict of items read from a config file. If given_cfg_file is None, uses one of the default config file locations. """ cfg_file = None if given_cfg_file: cfg_file = given_cfg_file else: if os.path.exists(DEFAULT_CONFIG_FILE): ...
21c01bc07a165286fc8c150f4df3ad143e0ee217
3,615,858
import typing import time def get_cache_response_headers( response: Response, *, max_age: int ) -> typing.Dict[str, str]: """Return caching-related headers to add to a response.""" assert max_age >= 0, "Can't have a negative cache max-age" headers = {} if "Expires" not in response.headers: ...
85aea5eeda87c34512ef596179ce9022a1f67225
3,615,859
def parse_response(response): """ :param response: output of boto3 rds client describe_db_instances :return: an array, each element is an 3-element array with DBInstanceIdentifier, Engine, and Endpoint Address Example: [ ['devdb-ldn-test1', 'mysql', 'devdb-ldn-test.cjjimtutptto.eu-we...
edaa4abbb695adb06c43dc93d70178bc10a82445
3,615,860
def is_linear(x, y): """ Returns True if molecule is linear (largest eigenvalue almost equivalent to second largest) """ x = x - np.mean(x,axis=0) y = y - np.mean(y,axis=0) N = x.shape[0] L, Q = sorted_eigh(build_F(x, y)) if L[0]/L[1] < 1.01 and L[0]/L[1] > 0.0: return True ...
d997e70960813f88f443397540eef418c7d84879
3,615,861
def instantiate_me(spectrograph, par, **kwargs): """ Instantiate the FluxSpec subclass appropriate for the provided spectrograph. The class must be subclassed from FluxSpec. See :class:`FluxSpec` for the description of the valid keyword arguments. Args: spectrograph : Spectrograph or str ...
5518a2cc36dd48cc3f6a6c2d33292ba3eb0ced9a
3,615,862
from pathlib import Path from typing import Tuple def generate_theme( corethemepath: Path, theme_options: ThemeOptions, outdirpath: Path, additional: Tuple[Theme, Path] = () ) -> Tuple[Theme, Path]: """Tema üretir ve dosyaya yazar Arguments: corethemepath {Path} -- Üretim yapılacak çe...
e40beeb02c478edb90b381fb12e54c667832f756
3,615,863
from typing import Optional from typing import cast def get_expression( string: str, inputs: CWLObjectType, self: Optional[CWLOutputType] ) -> Optional[str]: """ Find and return a normalized CWL expression, if any. CWL expressions in the $() form are converted to the ${} form. """ if not isin...
b7d71c0e6e362797dccd2b76d272f8dd4f350b7d
3,615,864
def neighbours(row_number: int, column_number: int) -> set[tuple[int, int]]: """ Returns all the neighboring cells within the grid """ output: set[tuple[int, int]] = set() for i in (-1, 0, 1): for j in (-1, 0, 1): if i == 0 and j == 0: continue new_row...
b169af2d37658fffcd14d35c2f43357a356fd705
3,615,865
def appprotect_setup( request, kube_apis, ingress_controller_endpoint, test_namespace ) -> AppProtectSetup: """ Deploy simple application and all the AppProtect(dataguard-alarm) resources under test in one namespace. :param request: pytest fixture :param kube_apis: client apis :param ingress_co...
b6e1dc49e38e8d24efc02631e848115a43f2b963
3,615,866
def _mrci_energy(output_str): """ Reads the MRCISD+Q energy from the output file string. Returns the energy in Hartrees. :param output_str: string of the program's output file :type output_str: str :rtype: float """ ene = ar.energy.read( output_str, app.LINE...
1aceadfb697ac35819626a695b56ea1071f011fd
3,615,867
def format_csv(factor_name, entry): """Format a data entry as a csv line.""" return "%s, %s, %s" % (entry[factor_name], entry['quarter'], entry['count'])
8d3f4f794f58f6aa0c6d259fcda124340df8d4da
3,615,868
from typing import Optional def create_security_group(security_group_name: str, vpc_id: str, other_group: Optional[SecurityGroup] = None): """Creates security group with proper ports open. Optionally allows all traffic from other_group""" print("Creating security group " + security_group_name) ec2 = u.get_ec2_r...
d5cc8362c42021578574f92e29d533fd76e7d5f2
3,615,869
def p_stat_val_indirect_indexed(p): """stat_val : '(' arithmetic ')' ',' REGISTER""" if p[5][0] != 'Y': raise ParseError(f"Only register Y can be used for indexed indirect addressing, found {p[5][0]} at " f"{p.lineno(5)}, column {_get_column(p, index=5)}") p[0] = Addressing(...
6de1a3cc4ad91953669e4a1486520b2680c9487d
3,615,870
def _remove_quotes(values): """Remove any quotes from quoted values.""" removed = [] for value in values: if value.startswith('"') and value.endswith('"'): value = value[1:-1] removed.append(value) return removed
a75bd25198a56a28748af059647e62c26df74232
3,615,871
def write_yaml(data, file_path): """Write plain data to a file as yaml Parameters ---------- data Data to write (should be lists, dicts and simple values) file_path : str The path of the configuration file to write """ with open(file_path, 'w+') as file_handle: yaml ...
915a11a707f60adb2696e7e8824663cbbb5f3b81
3,615,872
from typing import Dict def diff_schedule_embed_dicts(old_embed: Dict, new_embed: Dict) -> str: """Takes 2 schedule embed dicts and returns a string containing the differences""" diffs = [] # old_embed can be empty if we have reset it, new_embed will always have a title. if old_embed.get("title", "")...
3668a2dcd6273c3fc985040bad43068eb2e7b3a8
3,615,873
def bootstrapped_ecdf(variable, weights, seeds, ax, bootstraps=200, normalisation=None, x_count=10000, log_scale=(False, False), color="tab:blue", label=None, **kwargs): """Create a bootstrapped weighted ECDF plot. Parameters ---------- ...
40f638ef59558f61b207d66e262a27a7a267d705
3,615,874
def consolidate(voice, length): """ Join notes of the same pitch together, and increase their duration. No attempt is made to handle ties between bars, They are just treated as separate notes. :param voice: :param length: :return: """ out = list() try: for bars in range(0, ...
6e6a60be0a6438b6f7c5fb23a1be720d5486e693
3,615,875
def get_filename(training_datasets, testing_datasets, beta, sr_model): """Get filename for saving results.""" if sr_model == 'convolutional_embedding': model_str = '' # For past consistency. else: model_str = '_%s' % sr_model file_name = ('end_to_end%s_stim_%s_resp_%s_beta_%d_taskid_%d' ...
933b1179131a627bdf4bfbbc13b730fa90fba2c4
3,615,876
import argparse def create_args()->dict: """[summary] Returns: dict: [a dictionary contains the args and non args parameters] """ parser = argparse.ArgumentParser() parser.add_argument('-d', '--D', default=2, type=int, help='dimension of sample') parser.add_ar...
c6643efc2fa73a0e2870913bfb7cf5cb5f761d7f
3,615,877
import json def get_dimensions(cube_id): """ For this test data we will use a predefined dimension object matching cube-420 in the acceptance environment, but this could be read from the TAP service. """ dims = json.loads( '{"axes": [{"name": "RA", "numPixels": "4096", "pixelSize": "5.555...
aab639236510785649fd02ff80c795d7941007fd
3,615,878
def validateRouterDetails(result): """ Runs device validations on each Router object that is returned by getRouterDetails, if a device requires normalization return it for processing by normalizeRouters """ print "Validating router details" devicesToCorrect = [] for device, results in r...
ad23382a926d5eef06bdc8d04741a90053c97efe
3,615,879
from pathlib import Path import yaml def load_yaml_config(file_path: str | Path) -> dict: """ Parameters ---------- file_path : str or Path Yaml config file name. The file is assumed to be in the repo's config directory. Returns ------- config : dict Configuration...
88a137807d6d1caabd3b8f7f7a03a3be3f04bdfe
3,615,880
def advice(aa): """If a user asks for health advice or tips, then bot wil reply with an randomly generated advice""" for ab in aa.split(): if ab.lower() in advice_questions: return rndm.choice(advice_reply)
2d5aabb4fbfb42a176ab6782a3f6688de47ba1ac
3,615,881
from typing import Optional import socket from typing import Type import asyncio import os import sys def serve( host, port, app: Sanic, ssl: Optional[SSLContext] = None, sock: Optional[socket.socket] = None, unix: Optional[str] = None, reuse_port: bool = False, loop=None, protocol...
8f79286b8e783c2a07026bbe924feb07fb6aadf3
3,615,882
def dmp_strip(f, u): """ Remove leading zeros from ``f`` in ``K[X]``. Examples ======== >>> from sympy.polys.densebasic import dmp_strip >>> dmp_strip([[], [0, 1, 2], [1]], 1) [[0, 1, 2], [1]] """ if not u: return dup_strip(f) if dmp_zero_p(f, u): return f ...
2b77c5546121d59b06ef604c77df66e8725bfd15
3,615,883
import torch def mvdr_beamformer( noise_psd: ComplexTensor, steering_vector: ComplexTensor, eps=1e-15 ) -> ComplexTensor: """ Standard MVDR beamformer Args: noise_psd: time-averaged noise psd of shape [B, F, C, C] steering_vector: [B, F, C, 1] eps: eps ...
fb17a43343f059ad2bbdabd62e8a4f9caafdf903
3,615,884
def split_in_words(text, num_letters): """ Split a long text (without space) into words of num_letters letters. For instance if text is niijighkqj and num_letters is 4, will return ["niij", "iiji", "ijig", "jigh", "ighk", "ghkg", "hkgj"] :param text: Text to split into words :param num_letters: ...
334be65a1592b13056dede738fb5cabb67e79236
3,615,885
def _get_delivery_voucher_discount_for_cart(voucher, cart): """Calculate discount value for a voucher of delivery type.""" if not cart.is_delivery_required(): msg = pgettext( 'Voucher not applicable', 'Your task does not require delivery.') raise NotApplicable(msg) de...
9e08a3b47f0d7749081459f02d3c1038f28a02d4
3,615,886
import ast def rname(node): """ Obtains names from different types of AST nodes. """ if isinstance(node, str): return node if isinstance(node, ast.Num): return str(node.n) if isinstance(node, ast.Name): # form x return node.id if isinstance(node, ast.Constant): re...
bc600545a2b072e258a06c54fb671ed388a8cf63
3,615,887
import os def utr(diff, meta, i, ii, orbnum, rowmedian, rowmedian_absder, peaks): """ Saves a plot of up-the-ramp sample, the row by row sum and the derivate of the latter. It furthermore shows the aperture used for the analysis. """ cmin = int(meta.refpix[ orbnum, 2] + meta.POSTARG...
327a312e840790c9ebe2beec915f9a39dcd3e2e4
3,615,888
import os def test(test_loader, model, args): """Test the model. Args: test_loader (DataLoader): The data set loader. model: The network. criterion (Loss): The loss function. args: The hyperparameter arguments. Returns: The NMI score. The recall@k results....
cff62aadbc76da7b05a764b1456aa95b53f22a9d
3,615,889
import os import requests def get_file(station): """Download the file from NCEI, if necessary!""" # IPv6, use 205.167.25.102 rather than www1.ncdc.noaa.gov uri = ("http://www1.ncdc.noaa.gov/pub/data/ghcn/daily/all/%s.dly" ) % (station, ) localfn = "%s/%s.dly" % (BASEDIR, station) if not...
0488875f0a5c49f6e2f2ceb41017bdd7b83259a3
3,615,890
import re def get_specified_file(file_names, *args): """Get specified filename extension from a list of file names.""" specified_filename = [] if args is (): raise Exception('get_specified_file() missing at least 1 required specified argument') for name in file_names: for extension i...
195e6d1556afb46fd98972c6c7f5a4b897efbdc2
3,615,891
import re def has_sh_placeholders(message): """Returns true if the message has placeholders.""" return re.search(r'\$\{(\w+)\}', message) is not None
9bd5b4a22c89cfa1d45ea28bf7121cd4171828ee
3,615,892
import re def _find_char(input_char): """ find english char in input string """ result = re.findall(r'[a-zA-Z=_/0-9.]+', str(input_char)) return result
b89bc97e0b73c71ec6a1a875414b73e16c9d6036
3,615,893
import re def generate_inventory(baremetal_info, server_info): """Generate ansible inventory in json format""" hosts = defaultdict(list) hosts_meta = {} for node in baremetal_info: if node['Provisioning State'].lower() == 'active': role = re.findall('.*profile:(compute|control)',...
1447ffc9069690df225a49ad41508ce1956d59f7
3,615,894
def research_report( instrument_ids, research_study_id, acting_user_id, patch_dstu2, request_url, response_format, lock_key, celery_task): """Generates the research report Designed to be executed in a background task - all inputs and outputs are easily serialized (executing celery_task pare...
243125bd5a6fd275212513781074228692aca86e
3,615,895
def get_P_TU_aux_HWH(CG_category): """35. タンクユニットの補機消費電力 (温水暖房) Args: CG_category(str): コージェネレーション設備の種類 Returns: float: タンクユニットの補機消費電力 (温水暖房) """ return get_value(CG_category, 35)
61f385d8404cfa7b592ed02b15fd2051c8d5f34b
3,615,896
import collections def type_to_tf_structure(type_spec): """Returns nested `tf.data.experimental.Structure` for a given TFF type. Args: type_spec: Type specification, either an instance of `computation_types.Type`, or something convertible to it. Ther type specification must be composed of only na...
e54813475042d549343a25432cbeec6ec59dc60a
3,615,897
import urllib import re def _get_effective_areas(detector): """ Returns the effective detector areas for EIS, in a dictionary from floats (in Angstroms) to Quantities. """ areas_dic = eff_areas_a if detector == 'A' else eff_areas_b if len(areas_dic) > 0: return areas_dic url = dart...
c4b7955c2b2b90335ab371c837013339fc014ac3
3,615,898
import functools def verifyrun(func): """Prints whether the decorated function ran.""" @functools.wraps(func) def wrapper_verifyrun(*args, **kwargs): print(f'Ran {func.__name__!r} from {func.__module__}.') value = func(*args, **kwargs) return value return wrapper_verifyrun
5f2d1289573a9069f283e508b1ce133eccfe3529
3,615,899