content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def combine(connected_events): """ Combine connected events into a graph. :param connected_events: see polychronous.filter :return: graph_of_connected_events """ graph_of_connected_events = nx.Graph() graph_of_connected_events.add_edges_from(connected_events) return (graph_of_connected_e...
99471930f70bea0583d36d3c0c13fc62b23d6fe8
3,659,000
import hashlib def calculate_hash(filepath, hash_name): """Calculate the hash of a file. The available hashes are given by the hashlib module. The available hashes can be listed with hashlib.algorithms_available.""" hash_name = hash_name.lower() if not hasattr(hashlib, hash_name): raise Exception...
975fe0a2a4443ca3abc67ed950fb7200409f2497
3,659,001
from pathlib import Path from typing import Type from typing import Tuple from typing import List from typing import Dict import logging import yaml import sys def specify_run_step( args: RunConfig, aml_resources: AMLResources, run_script_path: Path, loop_config_class: Type[OptimizerConfig], check...
30aa58f599559d9be2c29524befe710cc26fac1d
3,659,002
def default_mp_value_parameters(): """Set the different default parameters used for mp-values. Returns ------- dict A default parameter set with keys: rescale_pca (whether the PCA should be scaled by variance explained) and nb_permutations (how many permutations to calculate emp...
0dcac3981154fbf0cc1fa0eeed6e83a1e1b63294
3,659,003
import os def change_auth_keys(server, user, auth_keys): """ update authorize keys. ath_keys is list of keys. will get current auth_keys, remove keys with auth_tag, and add new auth_keys with auth_tag. return: if success, none. else, a dict: { stdout: xxx, stderr: yyy } """ auth_tag = os...
b1b67d168ca5b863ce6ddc62b9ecc988d70aace8
3,659,004
def svn_wc_diff(*args): """ svn_wc_diff(svn_wc_adm_access_t anchor, char target, svn_wc_diff_callbacks_t callbacks, void callback_baton, svn_boolean_t recurse, apr_pool_t pool) -> svn_error_t """ return _wc.svn_wc_diff(*args)
c4fbc11d26b6da2d595cb79314b0d901b084eb52
3,659,005
import re def _FindResourceIds(header, resource_names): """Returns the numerical resource IDs that correspond to the given resource names, as #defined in the given header file." """ pattern = re.compile( r'^#define (%s) _Pragma\S+ (\d+)$' % '|'.join(resource_names)) with open(header, 'r') as f: ...
24847b1d4374a2022ae12f5161bd9df4becd110d
3,659,006
import re def resolve_request_path(requested_uri): """ Check for any aliases and alter the path accordingly. Returns resolved_uri """ for key, val in PATH_ALIASES.items(): if re.match(key, requested_uri): return re.sub(key, val, requested_uri) return requested_uri
5405a795a95279a354d455f3702dbf2c3dc6f1e0
3,659,007
def apim_api_delete( client, resource_group_name, service_name, api_id, delete_revisions=None, if_match=None, no_wait=False): """Deletes an existing API. """ cms = client.api return sdk_no_wait( no_wait, cms.delete, resource_group_name=resource_group_name, service_n...
4be4f895ae576ee1ffd08af31abcdad193b84b2c
3,659,008
def deep_copy(obj): """Make deep copy of VTK object.""" copy = obj.NewInstance() copy.DeepCopy(obj) return copy
c00c4ff44dad5c0c018152f489955f08e633f5ed
3,659,009
def get_dunn_index(fdist, *clusters): """ Returns the Dunn index for the given selection of nodes. J.C. Dunn. Well separated clusters and optimal fuzzy partitions. 1974. J.Cybern. 4. 95-104. """ if len(clusters)<2: raise ValueError, "At least 2 clusters are required" intra_dist =...
c78c5302d78b5d5969a5edf9e19b81ee6f68bfbf
3,659,010
import random def sample(words, n=10) -> str: """Sample n random words from a list of words.""" return [random.choice(words) for _ in range(n)]
cad435238c776b5fcda84d50295ac50298bf3ab2
3,659,011
def extract_peaks( imzml_path, db, tol_ppm=DEFAULT_TOL_PPM, tol_mode=DEFAULT_TOL_MODE, base_mz=DEFAULT_BASE_MZ, ): """ Extract all peaks from the given imzML file for the supplied database of molecules. :param imzml_path: :param db: A pandas DataFrame containing an 'mz' column. Addit...
b388fc8cd4e7e1be7a2179caddf8f07cf044173e
3,659,012
def cov_dense(n_features=100, scale=0.5, edges='ones', pos=True, force_psd=True, random_state=None): """ Returns a covariance matrix with a constant diagonal and whose off diagnale elements are obtained from adj_mats.complete_graph() Parameters ---------- n_features: int scale: f...
48b8f5fec91ea11acaf9ce026d8b1742b5185604
3,659,013
def measure_fwhm(array): """Fit a Gaussian2D model to a PSF and return the FWHM Parameters ---------- array : numpy.ndarray Array containing PSF Returns ------- x_fwhm : float FWHM in x direction in units of pixels y_fwhm : float FWHM in y direction in units of...
e3ee047b453b979387505a19bdfebb75950a3916
3,659,014
def exists(profile, bucket, name): """Check if a file exists in an S3 bucket. Args: profile A profile to connect to AWS with. bucket The name of the bucket you want to find the file in. name The name of a file. Returns: True if it exis...
5269cca9198a1d100b76b13f6e2fbf7314d948fd
3,659,015
def fetchquota(adr): """Retrieves the account quota information and passes the interesting part of the json object along to the request source. Arguments: adr (str): The email account address of interest. Returns: The quota part of the json object for the response. """ debuginf...
56b5c283ae38bc56c315cd6140d2fd910baeaf98
3,659,016
def project_login(driver): """ 針對多綫程執行設定不同樣本編號,若修改問卷,也許提供該問卷樣本編號的第一順位號碼。 """ SAMPLE_NUMBER = 20200101+sample_add try: WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.XPATH, '//*[@name="{}"][1]' .format(str(SAMPLE_NUMBER))))).click() # 選擇樣本編號作答 sleep(1) ...
db3ef26e1769cb991c887509427f9d809047398d
3,659,017
def convert_convolutionfunction_to_image(cf): """ Convert ConvolutionFunction to an image :param cf: :return: """ return create_image_from_array(cf.data, cf.grid_wcs, cf.polarisation_frame)
6f5819abce6a987665ff49af9e5fca70f586a478
3,659,018
def macro(libname): """Decorator for macros (Moya callables).""" def deco(f): exposed_elements[libname] = f return f return deco
c4d06d2b9e3fa7913445554794027e68328ab918
3,659,019
import logging import torch def get_dataloaders(dataset, mode='train', root=None, shuffle=True, pin_memory=True, batch_size=8, logger=logging.getLogger(__name__), normalize=False, **kwargs): """A generic data loader Parameters ---------- dataset : {"openimages", "jetimages", "eva...
6bb40b3eb1bc004418dd8910dab1432cd3984ca5
3,659,020
def stats_file(filename, shape, dtype=None, file_format='raw', out_of_core=True, buffer_size=None, max_memory=None, progress_frequency=None): """stats_file(filename, shape, dtype=None, file_format='raw', out_of_core=True, buffer_size=None, max_memory=None, ...
750b4d334aa25a2423e5278eab7cd5ee43385303
3,659,021
def get_info(args): """ Loads todo.txt, sets up file paths, loads in any available star information, saves the relevant parameters for each of the two main routines and sets the plotting parameters. Parameters ---------- args : argparse.Namespace command-line arguments parallel : b...
919ae745424c16c6307db460ec2054b250ba72a6
3,659,022
def _weight_func(dist): """Weight function to replace lambda d: d ** -2. The lambda function is not valid because: if d==0 then 0^-2 is not valid.""" # Dist could be multidimensional, flatten it so all values # can be looped with np.errstate(divide="ignore"): retval = 1.0 / dist ret...
9052b68592f2f6cf4c59c623a3561f77d3d2b933
3,659,023
def two_poles(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns the Cartpole Balance task with two poles.""" physics = Physics.from_xml_string(*get_model_and_assets(num_poles=2)) task = Balance(swing_up=True, sparse=False, random=random) environment_kwargs = environ...
b5236731d61464067073c3275cdd03d493f17821
3,659,024
def process_topic_entity(entity: dict, language: str) -> bool: """ Given a topic entity, gather its metadata :param entity :param language: :type entity dict :type language str :returns bool """ try: # Get ID remote_id = entity["title"] print("%s\t%s" % ("ID"...
2f03c0d24f35e49cd05ac11389b91345cc43de6e
3,659,025
import math import torch def _no_grad_trunc_normal_(tensor: Tensor, mean: float, std: float, a: float, b: float) -> Tensor: """Cut & paste from PyTorch official master until it's in a few official releases - RW Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf Ar...
064fce46591c490999c6495999554700f478878b
3,659,026
def inverse_update(C, m, return_drop=False): """ Compute the inverse of a matrix with the m-th row and column dropped given knowledge of the inverse of the original matrix. C = inv(A) B = drop_col(drop_row(A, m),m) computes inv(B) given only C Args: C: inverse of full m...
0f368d30d0459fe3d07d6fc1fa19dedc449e23e9
3,659,027
def loss_calc(settings, all_batch, market_batch): """ Calculates nn's NEGATIVE loss. Args: settings: contains the neural net all_batch: the inputs to neural net market_batch: [open close high low] used to calculate loss Returns: cost: loss - l1 penalty """ loss = set...
fdca1bb0fa86d1972c2a0f8b1fab10183e98fb4e
3,659,028
def fits_downloaded_correctly(fits_loc): """ Is there a readable fits image at fits_loc? Does NOT check for bad pixels Args: fits_loc (str): location of fits file to open Returns: (bool) True if file at fits_loc is readable, else False """ try: img, _ = fits.getdat...
8df470b4b2895fb7d77cbccefbd2eae7f22c649b
3,659,029
def union_of_rects(rects): """ Calculates union of two rectangular boxes Assumes both rects of form N x [xmin, ymin, xmax, ymax] """ xA = np.min(rects[:, 0]) yA = np.min(rects[:, 1]) xB = np.max(rects[:, 2]) yB = np.max(rects[:, 3]) return np.array([xA, yA, xB, yB], dtype=np.int32)
904cb58f593bedfbf0e28136a446b4f877955e49
3,659,030
from typing import List from typing import Dict def configure_services(config: List[Dict]) -> Dict[str, GcpServiceQuery]: """ Generate GcpServiceQuery list from config :param config: list with GcpServieQuery's configuration :return: mapping of service name to GcpServiceQuery objects """ if not...
3c9b9472de4d319446ec4da1d990ecc1750bd248
3,659,031
def tags_get(): """ Get endpoint /api/tag args: optional company_filter(int) - id of a company, will only return tag relation to said company optional crowd(int) - 0 - 2 specifing crowd sourcing option. Key: 0 - all tags 1 - Only crowd sourced tags 2 - Only non crowd...
c009c0b84bbc825383dffb1141361dd1732b7b19
3,659,032
import os import re import gzip import shutil def gunzip(filename, targetdir): """Decompress a gzip-compressed file into a target directory. Args: filename: Full path to gzip file. targetdir: Directory to decompress file into. Returns: The output file name. Raises: Fi...
39f3eec7018fcfc95f3a825ee33cec5387b006ed
3,659,033
def get_accept_languages(accept): """Returns a list of languages, by order of preference, based on an HTTP Accept-Language string.See W3C RFC 2616 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) for specification. """ langs = parse_http_accept_header(accept) for index, lang in enumerate...
ad329605cd0101e61c2c21aa42f2c81a84db771b
3,659,034
def get_princ_axes_xyz(tensor): """ Gets the principal stress axes from a stress tensor. Modified from beachball.py from ObsPy, written by Robert Barsch. That code is modified from Generic Mapping Tools (gmt.soest.hawaii.edu) Returns 'PrincipalAxis' classes, which have attributes val, trend, p...
e9285464e17eb987ebfd21c8e066ff745a856dc1
3,659,035
def extractYoushoku(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if 'The Other World Dining Hall' in item['tags'] and (chp or vol): return buildReleaseMessageWithType(item, 'The Other World Dining Hall', vol, chp, frag=frag, postfix=postfix) return False
686daef4d594e0e53779be48d7c49a525cabe4ee
3,659,036
def _perform_Miecalculations(diam, wavelength, n, noOfAngles=100.): """ Performs Mie calculations Parameters ---------- diam: NumPy array of floats Array of diameters over which to perform Mie calculations; units are um wavelength: float Wavelength of light...
4ce8fa518477c3eb38816d8f441207716b3a90df
3,659,037
from typing import Tuple def load_config_dict(pipette_id: str) -> Tuple[ 'PipetteFusedSpec', 'PipetteModel']: """ Give updated config with overrides for a pipette. This will add the default value for a mutable config before returning the modified config value. """ override = load_overrides...
485db2aad493eda30e6dad07b3d6c9413bc5c3c8
3,659,038
def ErrorAddEncKey(builder, encKey): """This method is deprecated. Please switch to AddEncKey.""" return AddEncKey(builder, encKey)
c39bb36b3923ca1a0e508b23ef84a6de130700a3
3,659,039
def _read_txs_from_file(f): """ Validate headers and read buy/sell transactions from the open file-like object 'f'. Note: we use the seek method on f. """ ans = [] f.seek(0) workbook = openpyxl.load_workbook(f) sheet = workbook.active all_contents = list(sheet.rows) _validate_he...
0c62c647a2ff1a797fb5e8593279bbf64bc0d495
3,659,040
from typing import Union def get_generator_regulation_lower_term_4(data, trader_id, intervention) -> Union[float, None]: """Get L5RE term 4 in FCAS availability calculation""" # Term parameters enablement_min = get_effective_enablement_min(data, trader_id, 'L5RE') energy_target = lookup.get_trader_so...
626ab26f92feefea25777046c1fc37c4115f7be8
3,659,041
def count_parameters(model): """count model parameters""" return sum(p.numel() for p in model.parameters() if p.requires_grad)
5edcb3ee03794cb66f5986670c4825efab93a1d8
3,659,042
def string_rule_variable(label=None, params=None, options=None, public=True): """ Decorator to make a function into a string rule variable. NOTE: add **kwargs argument to receive Rule as parameters :param label: Label for Variable :param params: Parameters expected by the Variable function :pa...
3bd35ac2e27c58ee35f7e13bb359cb8240f8efda
3,659,043
def detect_horizon_lines(image_thre, row, busbar, cell_size, thre=0.6, split=50, peak_interval=None, margin=None): """ Detect horizontal edges by segmenting image into vertical splits Parameters --------- image_thre: array Adaptive threshold of raw images row: int Number of rows of solar m...
e8365b29829d6e1a71c4c9caefff221d9357b0a3
3,659,044
def countRoem(cards, trumpSuit=None): """Counts the amount of roem (additional points) in a list of cards Args: Returns: Integer value how many points of roem are in the cards in total """ roem = 0 # Stuk # Without a trumpSuit, stuk is impossible if trumpSuit is not None: ...
31e2dbf346801fa81e5a5905a480f6d5b8e9ce1a
3,659,045
from typing import Optional def batch_to_space( data: NodeInput, block_shape: NodeInput, crops_begin: NodeInput, crops_end: NodeInput, name: Optional[str] = None, ) -> Node: """Perform BatchToSpace operation on the input tensor. BatchToSpace permutes data from the batch dimension of the d...
fe7004243e7c4a6dfd78b1f39df22ba7290c9244
3,659,046
def url_in(url): """ Send a URL and I'll post it to Hive """ custom_json = {'url': url} trx_id , success = send_notification(custom_json) return trx_id, success
ecfcb02cdbd9050a5a305f38d9673d64b9b1d307
3,659,047
def login(): """ Display a basic login form in order to log in a user """ if request.method == 'GET': return render_template('login.html') else: try: usr = User.query.get(request.form['user_id']) if bcrypt.checkpw(request.form['user_password'].encode('utf-...
37702dc290d627544d5714ed21d8804eaa00f354
3,659,048
def hflip(stream): """Flip the input video horizontally. Official documentation: `hflip <https://ffmpeg.org/ffmpeg-filters.html#hflip>`__ """ return FilterNode(stream, hflip.__name__).stream()
140f7d4ceecee09e5f0ba7db9a68cee15e536ffa
3,659,049
def get_diagonal_ripple_rainbows_2(): """ Returns 11 diagonal ripple rainbows Programs that use this function: - Diagonal Ripple 3 - Diagonal Ripple 4 """ rainbow01 = [ [C1, C2, C3, C4, C5, C6, C7, C8], [C1, C2, C3, C4, C5, C6, C7, C8], [C1, C2, C3, C4, C5, ...
ce917a063de580b2fcacfe2b59991585aefe30a4
3,659,050
def matrix_prod(A, B, display = False): """ Computes the matrix product of two matrices using array slicing and vector operations. """ if A.shape[1] != B.shape[0]: raise ValueError("Dimensions not compatible.") # Not allowed!? #matrix = A.dot(B) # Dotproduct of each A.row*B.clm ...
c38c3c3c9b1d2cc3edf6efb1997fe94a15c870ec
3,659,051
def remove_quat_discontinuities(rotations): """ Removing quat discontinuities on the time dimension (removing flips) :param rotations: Array of quaternions of shape (T, J, 4) :return: The processed array without quaternion inversion. """ rots_inv = -rotations for i in range(1, rotations.sha...
7d3874f5c56f82f3a8951daef48ac115f7f8943a
3,659,052
import glob def compute_profile_from_frames(frames_str, ax, bt, box, N_bins=100, \ shift=None, verbose=False): """ Compute a density profile from a batch of xyz frames. Input ===== - frames_str: a regex containing frames in xyz format - ax: axis along which to compute the profile ...
70702dbcf73f2a7e9894899ca20f81eadc3046fe
3,659,053
import urllib import requests import json def wikipedia_search(query, lang="en", max_result=1): """ https://www.mediawiki.org/wiki/API:Opensearch """ query = any2unicode(query) params = { "action":"opensearch", "search": query, "format":"json", #"formatversion":...
e88b50c11d78989e086417d15e91515d24151586
3,659,054
def group_result(result, func): """ :param result: A list of rows from the database: e.g. [(key, data1), (key, data2)] :param func: the function to reduce the data e.g. func=median :return: the data that is reduced. e.g. [(key, (data1+data2)/2)] """ data = {} for key, value in result: ...
7687521c216210badcda5ee54bd59a3bc6a234bd
3,659,055
import torch def prep_image(img, inp_dim): """ Prepare image for inputting to the neural network. Returns a Variable """ orig_im = img dim = orig_im.shape[1], orig_im.shape[0] img = cv2.resize(orig_im, (inp_dim, inp_dim)) # img_ = img[:,:,::-1].transpose((2,0,1)).copy() img_...
65159c8ce3a2df3cb09a6f1f318bb3374943e314
3,659,056
import uuid def extractLogData(context): """ helper function to extract all important data from the web context. :param context: the web.py context object :return: a dictionary with all information for the logging. """ logData = {} logData['ip'] = context.ip logData['account'] = cont...
5fb68d4f19dae0b7175a089dd1366cab0407152b
3,659,057
def Backbone(backbone_type='ResNet50', use_pretrain=True): """Backbone Model""" weights = None if use_pretrain: weights = 'imagenet' def backbone(x_in): if backbone_type == 'ResNet50': return ResNet50(input_shape=x_in.shape[1:], include_top=False, ...
23bc493e8306d5dc5dba33cd2f67de231cbb3e02
3,659,058
def start(ctx, vca_client, **kwargs): """ power on server and wait network connection availability for host """ # combine properties obj = combine_properties( ctx, kwargs=kwargs, names=['server'], properties=[VCLOUD_VAPP_NAME, 'management_network']) # get external if obj.get(...
6e3e3a94095ef200e586f7dfdc7e117ae3ee375f
3,659,059
def softplus(z): """Numerically stable version of log(1 + exp(z)).""" # see stabilizing softplus: http://sachinashanbhag.blogspot.com/2014/05/numerically-approximation-of-log-1-expy.html # noqa mu = z.copy() mu[z > 35] = z[z > 35] mu[z < -10] = np.exp(z[z < -10]) mu[(z >= -10) & (z <= 35)] = log...
f683c1f2240d053c4ee2c24f64ff5576c0d9d32d
3,659,060
from typing import Mapping from typing import Hashable from typing import Union from typing import Sequence from typing import Set from typing import Tuple from typing import OrderedDict from typing import Any def merge_indexes( indexes: Mapping[Hashable, Union[Hashable, Sequence[Hashable]]], variables: Mappi...
b893d118312697d1995a0a42bbff8354b73ca642
3,659,061
def least_squares(m, n): """ Create a least squares problem with m datapoints and n dimensions """ A = np.random.randn(m, n) _x = np.random.randn(n) b = A.dot(_x) x = cp.Variable(n) return (x, cp.Problem(cp.Minimize(cp.sum_squares(A * x - b) + cp.norm(x, 2))))
21b3b4577ec232f6e74d1f096946d0923f867cf7
3,659,062
import sys def getRef(refFile): """Returns a genome reference.""" refDict={} hdList=[] ref='' num=0 try: f=open(refFile) except IOError: errlog.error('Cannot find reference file ' +refFile+'. Please check pathname.') sys.exit('Cannot find reference file '+refFile+'....
bd6f149662077acff88f42029c87deab08e92331
3,659,063
import os def cleanup_path(paths, removedir=True): """ remove unreable files and directories from the input path collection, skipped include two type of elements: unwanted directories if removedir is True or unaccessible files/directories """ checked = [] skipped = [] for ele in paths: ...
36105a4617ea0cfffc870dd083540f81aaf56079
3,659,064
def expand_amn(a, kpoints, idx, Rvectors, nproj_atom=None): """ Expand the projections matrix by translations of the orbitals Parameters ---------- a : ndarray, shape (nkpts, nbnds, nproj) kpoints : ndarray, shape (nkpts, 3) idx : ndarray indices of translated orbitals Rvectors:...
d68a7cd4cb019b2d516305d0b6a2b45f6a422ba8
3,659,065
def combine_basis_vectors(weights, vectors, default_value=None, node_num=None): """ Combine basis vectors using ``weights`` as the Manning's n value for each basis vector. If a ``default_value`` is set then all nodes with out data are set to the ``default_value``. :type weights: :class:`numpy....
50a0cc5ba8ad88a480fc589f6fbe184548700485
3,659,066
from typing import List from typing import Tuple from typing import Any def _prepare_data_for_node_classification( graph: nx.Graph, seed_node: int ) -> List[Tuple[Any, Any]]: """ Position seed node as the first node in the data. TensorFlow GNN has a convention whereby the node to be classified, the "...
3ed718e583d9e96b2c5bd28e5640c36e5e009065
3,659,067
import logging def init(): """ Init the application and add routes """ logging.basicConfig(format='%(asctime)s: [%(levelname)s]: %(message)s', level=logging.DEBUG) global theconfig theconfig = get_config() global rc rc = init_redis(theconfig) app = default_app()...
c9c8694bf389fb52572ccd43a83d7c410a3538a2
3,659,068
def norm_potential(latitude, longitude, h, refell, lmax): """ Calculates the normal potential at a given latitude and height Arguments --------- latitude: latitude in degrees longitude: longitude in degrees height: height above reference ellipsoid in meters refell: reference ellipsoid n...
5fc9f26a206c4fced5ebd434c84dda26621c08dc
3,659,069
import os import glob def _findPlugInfo(rootDir): """ Find every pluginInfo.json files below the root directory. :param str rootDir: the search start from here :return: a list of files path :rtype: [str] """ files = [] for root, dirnames, filenames in os.walk(rootDir): files.extend...
d3367d8f71598d1fa1303baec0d4f6803b1293b2
3,659,070
def get_pp_gene_chains(chain_class_file, v=False): """Get gene: pp chains dict.""" gene_to_pp_chains = defaultdict(list) # init the dict f = open(chain_class_file, "r") # open file with classifications f.__next__() # skip header for line in f: line_data = line.rstrip().split("\t") ...
d09fe5f7e8aaed0b8aa46593931b3cda655f56e3
3,659,071
import os import fnmatch def rec_search(wildcard): """ Traverse all subfolders and match files against the wildcard. Returns: A list of all matching files absolute paths. """ matched = [] for dirpath, _, files in os.walk(os.getcwd()): fn_files = [os.path.join(dirpath, fn_file)...
47e8bd48956de87a72c996795f94b69979bf992f
3,659,072
def skip_object(change_mode, change): """ If `Mode` is `change`: we do not care about the `Conditions` Else: If `cfn` objects: - We can omit the `Conditions`, objects will be involed when `Mode` is `provision` or `destroy`. (Original design. Backward compatibility.) - In case...
a80365acc6f3390818f4c56a44ad4923f771fcee
3,659,073
def rootfinder(*args): """ rootfinder(str name, str solver, dict:SX rfp, dict opts) -> Function Create a solver for rootfinding problems Takes a function where one of the rootfinder(str name, str solver, dict:MX rfp, dict opts) -> Function rootfinder(str name, str solver, Function f, dic...
13ac40736849b6b4240dc5d22ad36aa472583bcb
3,659,074
def f18(x, rotation=None, shift=None, shuffle=None): """ Hybrid Function 8 (N=5) Args: x (array): Input vector of dimension 2, 10, 20, 30, 50 or 100. rotation (matrix): Optional rotation matrix. If None (default), the official matrix from the benchmark suite will be used. ...
d76b4aef256bdc72bc077adefda5e7a93f8ea500
3,659,075
def shake_256_len(data: bytes, length: int) -> hashes.MessageDigest: """ Convenience function to hash a message. """ return HashlibHash.hash(hashes.shake_256_len(length), data)
c59f1a224264649573d53b67f170c7238b5a9840
3,659,076
def rgb_to_cmyk(color_values: tp.List[float]) -> tp.List[float]: """Converts list of RGB values to CMYK. :param color_values: (list) 3-member RGB color value list :return: (list) 4-member CMYK color value list """ if color_values == [0.0, 0.0, 0.0]: return [0.0, 0.0, 0.0, 1.0] r, g, b =...
f0054c92e862c5f0a8b09f94c115c03150b3363b
3,659,077
def check_family(matrix): """Check the validity of a family matrix for the vine copula. Parameters: ---------- matrix : array The pair-copula families. Returns ------- matrix : array The corrected matrix. """ # TODO: check if the families are in the list of copulas ...
49ef0a621c8c7f4063ff6e886ed5455bfa760213
3,659,078
import re def parse_pgt_programmearray(url): """ Parse filter.js programmearray for pgt information :param url: base url for timetabling system :return: pgt programme name to id dict """ # get filter.js file source = get_filterjs(url) name_to_id = {} # e.g. programmearray[340] [...
b7901c37cdb931dce75a77422394f98b5e3898d1
3,659,079
def distance_calc(x1, y1, x2, y2): """Calculates distance between two points""" return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
4c0001d90d38371a5336e8163fbf63b3d6e95834
3,659,080
import requests def LoadNasaData(lat, lon, show= False, selectparms= None): """ Execute a request from NASA API for 10 years of atmospheric data required to prepare daily statistical data used in Solar Insolation calculations """ cmd = formulateRequest(-0.2739, 36.3765, selectparms) jdi ...
a2f61d20f46feee5d86bad2525c3bc20c3e00e14
3,659,081
from datetime import datetime def mmyy_date_slicer(date_str): """Return start and end point for given date in mm-yy format. :param date_str: date in mmyy format, i.e. "1222" or "0108". :return: start and end date string for a given mmyy formatted date string """ # Initialize output start...
f1c7f74f1824d5b4c410f3d8cc6ade15571fe3ca
3,659,082
import typing def constant_arg(name: str): """ Promises that the given arg will not be modified Only affects mutable data types Removes the need to copy the data during inlining """ def annotation(target: typing.Callable): optimiser = _schedule_optimisation(target) optimiser.c...
fdd132d3beea900b81bfe645616b0c20933e22e3
3,659,083
def place_connection(body): # noqa: E501 """Place an connection request from the SDX-Controller # noqa: E501 :param body: order placed for creating a connection :type body: dict | bytes :rtype: Connection """ if connexion.request.is_json: body = Connection.from_dict(connexion.re...
c69520f428f257a9eb3df97e060ad2e5cde45c94
3,659,084
def tag_list(request): """展示所有标签""" return render(request, 'admin/tags_list.html')
44b33197b3f8cb3467c8e7d32d4538f4dc2833b1
3,659,085
import requests def scan_url(urls): """ Scan the url using the API Args: urls: the list of urls Returns: A tuple of a bool indicating if all the urls are safe and a list indicating the safeness of individual urls """ is_safe = True safe_list = [True] * l...
9d3217a4c69a6a521d372b5692f93387ae7d61ad
3,659,086
def head_to_tree(head, len_, prune, subj_pos, obj_pos): """ Convert a sequence of head indexes into a tree object. """ head = head[:len_].tolist() root = None if prune < 0: nodes = [Tree() for _ in head] for i in range(len(nodes)): h = head[i] nodes[i].i...
0459e6ebb0c64a8170970d44e5c6bcde5bb6221c
3,659,087
def capped_subtraction(x, y): """Saturated arithmetics. Returns x - y truncated to the int64_t range.""" assert_is_int64(x) assert_is_int64(y) if y == 0: return x if x == y: if x == INT_MAX or x == INT_MIN: raise OverflowError( 'Integer NaN: subtracting IN...
c4a171497ff351c22df3fc831a1e840366a90c5b
3,659,088
def evaluate_points(func, begin, total_samps, var_list, attr): """ Inputs: func- the lambda function used to generate the data from the evaluation vector begin- the index to start at in the `attr` array total_samps- the total number of samples to generate var_lis...
68ba7eb95e8d26becbef58f14e3073f7ed184a5b
3,659,089
import os def get_username(): """Return username Return a useful username even if we are running under HT-Condor. Returns ------- str : username """ batch_system = os.environ.get('BATCH_SYSTEM') if batch_system == 'HTCondor': return os.environ.get('USER', '*Unknown user*') ...
1e199e7e38ed6532253ee1f7f229bb1baffc5538
3,659,090
def corresponding_chromaticities_prediction_CIE1994(experiment=1): """ Returns the corresponding chromaticities prediction for *CIE 1994* chromatic adaptation model. Parameters ---------- experiment : integer or CorrespondingColourDataset, optional {1, 2, 3, 4, 6, 8, 9, 11, 12} ...
f138ec844b2712d0d09be630f912f156aa50acbd
3,659,091
def interpExtrap(x, xp, yp): """numpy.interp interpolation function extended by linear extrapolation.""" y = np.interp(x, xp, yp) y = np.where(x < xp[0], yp[0]+(x-xp[0])*(yp[0]-yp[1])/(xp[0]-xp[1]), y) return np.where(x > xp[-1], yp[-1]+(x-xp[-1])*(yp[-1]-yp[-2]) / (xp[-1]-xp[-2]), y...
8a0acc55e146a29171ef6648897cd5eba7e23c12
3,659,092
import logging import subprocess def get_operating(): """Get latest operating budgets from shared drive.""" logging.info('Retrieving latest operating budget') command = "smbclient //ad.sannet.gov/dfs " \ + "--user={adname}%{adpass} -W ad -c " \ + "'prompt OFF;"\ + " cd \"FMGT-Share...
21add01cda622abd366dfb7f5d5af54f5b9de6b0
3,659,093
import json def get_nome_socio(id): """pega o nome de um livro pelo id.""" if request.method == 'GET': try: socio = db.query_bd('select * from socio where id = "%s"' % id) if socio: print(socio) socio = socio[0] print(soc...
8945ef5bbc46cd8b6c79903f1dd0d3d226860792
3,659,094
def processDeps(element: etree.Element, params: dict = {}) -> None: """Function to NAF deps layer to RDF Args: element: element containing the deps layer params: dict of params to store results Returns: None """ output = params["out"] for dep in element: if dep...
a096e42a3a036048daf97079f9e5bb78f5f068d9
3,659,095
def fit_solution_matrix(weights, design_matrix, cache=None, hash_decimal=10, fit_mat_key=None): """ Calculate the linear least squares solution matrix from a design matrix, A and a weights matrix W S = [A^T W A]^{-1} A^T W Parameters ---------- weights: array-like ndata x ndata matr...
3b237600ab2ae266cec1cdc3f1fc650cc02b82d8
3,659,096
def version_from(schema_path, document_path): """HACK A DID ACK derives non-default 1.1 version from path.""" LOG.debug("xml version derivation flat inspection schema_path=%s", schema_path) if CRVF_PRE_OASIS_SEMANTIC_VERSION in str(schema_path): return CRVF_PRE_OASIS_SEMANTIC_VERSION if CRVF_DEF...
f63c34e5467c098d0461b25699fe2d7a406508d9
3,659,097
def nessus_vuln_check(request): """ Get the detailed vulnerability information. :param request: :return: """ if request.method == 'GET': id_vul = request.GET['vuln_id'] else: id_vul = '' vul_dat = nessus_report_db.objects.filter(vul_id=id_vul) return render(request, ...
b1b9e2cce8b00f4a837f2712abd2dc4e2f5edb3d
3,659,098
def wait_for_job_completion(namespace, timeout, error_msg): """ This is a WORKAROUND of particular ocsci design choices: I just wait for one pod in the namespace, and then ask for the pod again to get it's name (but it would be much better to just wait for the job to finish instead, then ask for a n...
652834a4d28232895fc6da9c74f7e08cdbee4798
3,659,099