content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def test_knowledge_graph_init(graph_mutation_client, graph_mutation_responses): """Test knowldge graph client initialization.""" return graph_mutation_client.named_types
932a425e4bbdc301ef223e0f91936ecacf3bd5aa
3,642,605
def read_camera_matrix(filename): """ Read camera matrix from text file exported by PhotoScan """ with open(filename, 'r') as f: s = f.read() s = s.split(',') s = [x.strip('\Matrix([[') for x in s] s = [x.strip(']])') for x in s] s = [x.strip('[') for x in s] s = [x.strip(']...
be01c60d3c8940250c578a67de2c06110fb403e4
3,642,606
import pathlib def stem(path: str) -> str: """returns the stem of a path (path without parent directory and without extension) e.g j.sals.fs.stem("/tmp/tmp-5383p1GOmMOOwvfi.tpl") -> 'tmp-5383p1GOmMOOwvfi' Args: path (str): path we want to get its stem Returns: str: path with...
ec7507becb31bda7662122668b490148ca15d347
3,642,608
import json import re def fluent_text(field, schema): """ Accept multilingual text input in the following forms and convert to a json string for storage: 1. a multilingual dict, eg. {"en": "Text", "fr": "texte"} 2. a JSON encoded version of a multilingual dict, for compatibility w...
e07b8f7d83500bd79662f36df5ff2a4cf42af092
3,642,609
def palette_color_brewer_q_Set3(reverse=False): """Generate set3 Brewer palette of a given size ... interpolate as needed ... best for discrete mapping Args: reverse: order the colors backward as compared to standard Brewer palette Returns: lambda: generates a list of colors See Also:...
38355f8b9f7a69ad7c7f4951d324e9b8bbd233bb
3,642,610
def get_loss_function(identifier): """ Gets the loss function from `identifier`. :param identifier: the identifier :type identifier: str or dict[str, str or dict] :raise ValueError: if the function is not found :return: the function :rtype: function """ return _get(identifier, loss_...
060a14f21332ad47273febeb7d4a8347a2fd3957
3,642,612
def find_defender(ships, side): """Crude method to find something approximating the best target when attacking""" enemies = [x for x in ships if x['side'] != side and x['hp'] > 0] if not enemies: return None # shoot already wounded enemies first wounded = [x for x in enemies if x['hp'] < x[...
4c58ec01abae1f59ced47e61e257abe7f8923aea
3,642,613
import csv def Create_clump_summaries(feature_file,simplify_threshold): """ Employs Panda Shapely library to simplify polygons by eliminating almost colinear vertices. Generates two data structures: First - sort_clump_df: Panda Dataframe containing the longest line in the simplified and unsimplifie...
3b846760d78ad44630de0005e70e26f00b44b7d4
3,642,615
from re import S def norm(point): """Returns the Euclidean norm of a point from origin. Parameters ========== point: This denotes a point in the dimensional space. Examples ======== >>> from sympy.integrals.intpoly import norm >>> from sympy.geometry.point import Point >>> norm(P...
8e341bb7e623d2ef7a998b91a15e8a6735403860
3,642,616
def read_reducing(): """Return gas resistance for reducing gases. Eg hydrogen, carbon monoxide """ setup() return read_all().reducing
3e0d78fc999909d29c469f3399e845df542e1e68
3,642,617
def access_rights_to_metax(data): """ Cherry pick access right data from the frontend form data and make it comply with Metax schema. Arguments: data {object} -- The whole object sent from the frontend. Returns: object -- Object containing access right object that comply to Metax schem...
f66167028d86b5af4f15149bd21ab52fab9c3ba4
3,642,618
def read_toml_file(input_file, config_name = None, confpaths = [".", TCFHOME + "/" + "config"]): """ Function to read toml file and returns the toml content as a list Parameters: - input_file is any toml file which need to be read - config_name is particular configuration to pull - d...
9f0e05dfd556f06ed0323e6484e804f7813c626c
3,642,619
def and_sum (phrase): """Returns TRUE iff every element in <phrase> is TRUE""" for x in phrase: if not x: return False return True
d65953c5811aedef0a7c76cd3191aba8236f02fa
3,642,620
def load_data(filename: str): """ Load house prices dataset and preprocess data.g Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (prices) - either as a single DataFrame or a Tuple[DataFrame, Series] """ ...
a01179d470262bdc77e9d5417c1bd00415e4ccbd
3,642,621
def eccanom(M, e): """Finds eccentric anomaly from mean anomaly and eccentricity This method uses algorithm 2 from Vallado to find the eccentric anomaly from mean anomaly and eccentricity. Args: M (float or ndarray): mean anomaly e (float or ndarray): eccentrici...
433ee8d5f6c247626316d953ecf35a9805b70390
3,642,622
def transform_frame(frame: np.array, transform: AffineTransformation, rotate: bool = False, center_crop: bool = False) -> np.array: """ Perform affine transformation of a single image-frame. Parameters ---------- frame : array Image fr...
7e29b2a0abf62e1388c6715cfb30958046f1ff18
3,642,623
def TEMA(equity, start=None, end=None, timeperiod=30): """Triple Exponential Moving Average :param timeperiod: :return: """ close = np.array(equity.hp.loc[start:end, 'close'], dtype='f8') real = talib.TEMA(close, timeperiod=timeperiod) return real
0494e2cd6fedfc6b8ea8880808090f481c1128bc
3,642,624
def get_miner_pool_by_owner_id(): """ 存储提供者详情 :return: """ owner_id = request.form.get("owner_id") data = MinerService.get_miner_pool_by_no(owner_id) return response_json(data)
aa9fb36843d8999ac428d492463432de096628fe
3,642,625
def notFound(e): """View for 404 page.""" return render_template('content/notfound.jinja.html'), 404
d1bb53d22351ecbceda60ea28bdf8e7b688ad77d
3,642,626
from datetime import datetime def get_stay(admission_date, exit_date): """Method to get exit date.""" try: if not exit_date: exit_date = datetime.now().date() no_days = exit_date - admission_date # Get More years = ((no_days.total_seconds()) / (365.242 * 24 * 3600))...
bba3aa63884608500793c9f97c0c6e0e5d9e69ef
3,642,627
def compress(X, halve, g = 0, indices = None): """Returns Compress coreset of size 2^g sqrt(n) or, if indices is not None, of size 2^g sqrt(len(indices)) as row indices into X Args: X: Input sequence of sample points with shape (n, d) halve: Algorithm that takes an input a set of points an...
34503bf6602ef4577811c6fe449ae6109fa25007
3,642,628
def filter_objects(objs, labels, none_val=0): """Keep objects specified by label list""" out = objs.copy() all_labels = set(nonzero_unique(out)) labels = set(labels) remove_labels = all_labels - labels for l in remove_labels: remove_object(out, l) return out
8fccf936a5e74e274a2df5c182764e346e39dafb
3,642,629
def get_index_freq(freqs, fmin, fmax): """Get the indices of the freq between fmin and fmax in freqs """ f_index_min, f_index_max = -1, 0 for freq in freqs: if freq <= fmin: f_index_min += 1 if freq <= fmax: f_index_max += 1 # Just check if f_index_max is not...
f3e014626d763f18ce6b661cabeb244bfabe9782
3,642,630
def get_gene_mod(gene_id, marker_id): """Retrieves a GeneMod model if the gene / marker pair already exists, or creates a new one """ if gene_id in ("None", None): gene_id = 0 if marker_id in ("None", None): marker_id = 0 gene_mod = GeneMod.query.filter_by(gene_id=gene_id, mar...
26f29cbaa33c6fb7d40626152977c583fa5bcf57
3,642,631
def triangulate_polylines(polylines, holePts, lowQuality = False, maxArea = 0.01): """ Convenience function for triangulating a polygonal region using the `triangle` library. Parameters ---------- polylines List of point lists, each defining a closed polygon (with coinciding first a...
e2ae0eb5339d51d02eb1d26302fc18229ff85f83
3,642,633
def inclination(x, y, z, u, v, w): """Compute value of inclination, I. Args: x (float): x-component of position y (float): y-component of position z (float): z-component of position u (float): x-component of velocity v (float): y-component of velocity ...
bf85358fc6f002cdb4e0d47e6af0a93b8f9e4024
3,642,634
def OctahedralGraph(): """ Return an Octahedral graph (with 6 nodes). The regular octahedron is an 8-sided polyhedron with triangular faces. The octahedral graph corresponds to the connectivity of the vertices of the octahedron. It is the line graph of the tetrahedral graph. The octahedral is s...
d2abce73e747890f992301bb4814cfa52e55bce4
3,642,635
def peak_detect(y, delta, x=None): """ Find local maxima in y. Args: y (array): intensity data in which to look for peaks delta (float): a point is considered a maximum peak if it has the maximal value, and was preceded (to the left) by a value lower by DELTA. x (array, optional): corre...
def69cfcea7ccaed931fd764eab88de9fbb8773a
3,642,636
def quadruplet_fixated_egomotion( filename ): """ Given a filename that contains 4 different point-view combos, parse the filename and return the pair-wise camera pose. Parameters: ----------- filename: a filename in the specific format. Returns: ----------- egomotion: a nu...
5b40e8cfac7362c361ebe9119e5e4753c8e03978
3,642,637
def moshinsky(state1,state2,stater,statec,state,type): """ calculates the moshinsky coefficients used to transform between the two-particle and relative-center of mass frames. w1 x w2->w wr x wc->w type can be either "SU3" or "SO3" if type=="SU3": state1,state2,stater,statec,state are simply SU3State class ...
ee53cc25f2723b95179e1e190d94536de18f6321
3,642,638
def test_lie_algebra_nqubits_check(): """Test that we warn if the system is too big.""" @qml.qnode(qml.device("default.qubit", wires=5)) def circuit(): qml.RY(0.5, wires=0) return qml.expval(qml.Hamiltonian(coeffs=[-1.0], observables=[qml.PauliX(0)])) with pytest.warns(UserWarning, mat...
b4e296eabab9dc1fd250d391e8c12d2b2f12c59c
3,642,639
def get_elastic_apartments_not_for_sale(): """ Get apartments not for sale but with published flags """ s_obj = ( ApartmentDocument.search() .filter("term", publish_on_oikotie=True) .filter("term", publish_on_etuovi=True) .filter("term", apartment_state_of_sale__keyword=A...
080afdfa61f40f966ad498b3e292224bbfac262d
3,642,640
def promptYesNoCancel(prompt, prefix=''): """Simple Yes/No/Cancel prompt :param prompt: string, message to the user for selecting a menu entry :param prefix: string, text to print before the menu entry to format the display :returns: string, menu entry text """ menu = [ {'index': 1, 'te...
bf71ac635ef83ce370350bd352a7e0d619a956c7
3,642,641
def gradcheck_naive(f, x): """ Implements a manual gradient check: this functions is used as a helper function in many places - f should be a function that takes a single argument and outputs the cost and its gradients - x is the point (numpy array) to check the gradient at """ rndstate = ran...
c99f687ae8fad8ea890119e014294879f97fce33
3,642,642
def cal_mae_loss(logits, gts, reduction): """ :param preds: (N,C,H,W) logits predicted by the model. :param gts: (N,1,H,W) ground truths. :param reduction: specifies how all element-level loss is handled. :return: mae loss """ probs = logits.sigmoid() loss = (probs - gts).abs() retur...
6cc813552c46c4c6ea92fb1295478e8770cb255c
3,642,643
def divideByFirstColumn(matrix): """This function devide a matrix by its first column to resolve wrong intemsity problems""" result = (matrix.T / matrix.sum(axis=1)).T return result
348bbaa1a3c16a42be90978a0fcc65b1a7daf557
3,642,644
def get_archive_by_path(db, vault_name, path, retrieve_subpath_archs=False): """ Will attempt to find the most recent version of an archive representing a given path. If retrieve_subpath_archs is True, then will also retrieve latest versions of archives representing subdirs of the path. :param path:...
af30d33e90ef1b509a75f1c96a85b0457d454b71
3,642,646
import random def superpixel_colors( num_pix:int = 1536, schema:str = 'rgb', interleave:int = 1, stroke:str = '', ) -> list: """ Generate color (attribute) list for superpixel SVG paths Parameters ---------- num_pix : int Number of super pixels to account for (default ...
7a574b48dff30126052c2acd5d06e01a9f4a9af0
3,642,647
from typing import List def build_module_op_list(m: tq.QuantumModule, x=None) -> List: """ serialize all operations in the module and generate a list with [{'name': RX, 'has_params': True, 'trainable': True, 'wires': [0], n_wires: 1, 'params': [array([[0.01]])]}] so that an identity module can be ...
e14bbfe8122e05d0b65e93246494fa1414bcdf1b
3,642,648
import json def file_to_dict(filename, data): """Converts JSON file to dict :param filename: filename :param data: string :return: dict object """ try: try: json_data = to_json(data) return json.loads(json_data) except Exception as _: return...
3d6ff02246081dce83097545b5290dbbeedddab7
3,642,650
def reorganizeArray(id_A, id_B, gids_tuple, unordered_coordinates ): """ From a tuple of genome ID's representing a coordinate array's structure (gidI, gidJ). and the corresponding coordinate np-array (n x 4) of design [[locI1, locJ1, fidI1, fidJ2, Kn, Ks], ...
c4ac1add615f21e4238ad3cd65e1fb9797c02b27
3,642,651
def compile_model_output(i,j,files,model): """ compiles the model variables over severl files into a single array at a j,i grid point. Model can be "Operational", "Operational_old", "GEM". returns wind speed, wind direction, time,pressure, temperature, solar radiation, thermal radiation and humidity. "...
d42b3b8b4222b1ac15d1f8d7643c994efec0bb5e
3,642,652
def read_audio(path, Fs=None, mono=False): """Read an audio file into a np.ndarray. Args: path (str): Path to audio file Fs (scalar): Resample audio to given sampling rate. Use native sampling rate if None. (Default value = None) mono (bool): Convert multi-channel file to mono. (Default...
6b3f88ae00b1d9dab8016b33cc5a2d7c58d5b87e
3,642,653
from numpy import array def build_varied_y_node_mesh(osi, xs, ys, zs=None, active=None): """ Creates an array of nodes that in vertical lines, but vary in height The mesh has len(xs)=ln(ys) nodes in the x-direction and len(ys[0]) in the y-direction. If zs is not None then has len(zs) in the z-directi...
878386f1b815840d198de106f57e11883aec3d1c
3,642,655
def self_quarantine_end_10(): """ Real Name: b'self quarantine end 10' Original Eqn: b'50' Units: b'Day' Limits: (None, None) Type: constant b'' """ return 50
bb5fa131866d337460a37237b711d8c21588250d
3,642,656
import analysis as an import phasecurves as pc from astropy.io import fits as pyfits import pyfits def spexsxd_scatter_model(dat, halfwid=48, xlims=[470, 1024], ylims=[800, 1024], full_output=False, itime=None): """Model the scattered light seen in SpeX/SXD K-band frames. :INPUTS: dat : str or numpy a...
e4653a62f7d98a253034fd2908d4231ca23cff8b
3,642,657
def newff(minmax, size, transf=None): """ Create multilayer perceptron :Parameters: minmax: list of list, the outer list is the number of input neurons, inner lists must contain 2 elements: min and max Range of input value size: the length of list equal to the number of laye...
b488298fea98877cd7097374576722ea4b24e9c3
3,642,658
import importlib def write(*args, package="gw", file_format="dat", **kwargs): """Read in a results file. Parameters ---------- args: tuple all args are passed to write function package: str the package you wish to use file_format: str the file format you wish to use. D...
b7246e035f13b60fc8047abd768fae4bb1937600
3,642,659
def photo(el, dict_class, img_with_alt, base_url=''): """Find an implied photo property Args: el (bs4.element.Tag): a DOM element dict_class: a python class used as a dictionary (set by the Parser object) img_with_alt: a flag to enable experimental parsing of alt attribute with img (set by th...
304fea5700a8fcc2b95636265dbbc9c5c6dd1635
3,642,660
def calc_TOF(t_pulse, t_signal): """Calculate TOF from pulse and signal time arrays.""" tof = [] idxs = [-1] dbls = [] for t in t_signal: idx = bisect_left(t_pulse, t) if idx == len(t_pulse): t_0 = t_pulse[-1] else: t_0 = t_pulse[idx - 1] if id...
b58b14396c85f297e6454195fba597635b5fb54d
3,642,661
def get_nodes_ips(node_subnets): """Get the IPs of the trunk ports associated to the deployment.""" trunk_ips = [] os_net = clients.get_network_client() tags = CONF.neutron_defaults.resource_tags if tags: ports = os_net.ports(status='ACTIVE', tags=tags) else: # NOTE(ltomasbo: if ...
5472d184a4483355c81679ec6df41bc16ca7b32e
3,642,662
def get_visualizations_info(exp_id, state_name, interaction_id): """Returns a list of visualization info. Each item in the list is a dict with keys 'data' and 'options'. Args: exp_id: str. The ID of the exploration. state_name: str. Name of the state. interaction_id: str. The intera...
6ce3875be2244bcb3564d1ca006db62f56883a7f
3,642,663
def push(array, *items): """Push items onto the end of `array` and return modified `array`. Args: array (list): List to push to. items (mixed): Items to append. Returns: list: Modified `array`. Warning: `array` is modified in place. Example: >>> array = [...
2c43c6b4c5691d7f40601cdb7747ecf6e063f778
3,642,664
import csv def compute_list(commandline_argument): """ Returns a list of booking or revenue data opening booking data file with first parameter """ # utf-8_sig # Open booking CSV and read everything into memory with open(commandline_argument, "r", encoding="shift_jis") as database: ...
115725f5ab35c04412a2fe4f982a72c6b2e4c297
3,642,665
import re def calculate_saving(deal, item_prices): """ Parse the deal string and calculate how much money is saved when this deal gets applied. Also returns deal requirement. Args: deal (str): deal information item_prices (dict): {item: price} Returns: requirements (collect...
b67e5c53551866a8b390eb49fa4bc29ff9d3261a
3,642,666
def fetchone_from_table(database, table, values_dict, returning): """ Constructs a generic fetchone database command from a generic table with provided table_column:value_dictionary mapping. Mostly used for other helper functions. :param database: Current active database connection. :param table: ...
8b757bb5e9e7ba50a335a4917630543ef6989714
3,642,667
def ParseMultiCpuMask(cpu_mask): """Parse a multiple CPU mask definition and return the list of CPU IDs. CPU mask format: colon-separated list of comma-separated list of CPU IDs or dash-separated ID ranges, with optional "all" as CPU value Example: "0-2,5:all:1,5,6:2" -> [ [ 0,1,2,5 ], [ -1 ], [ 1, 5, 6 ], [ 2...
c114d931567ba3fdfc50b3eb7cd6cc7764bdd1d6
3,642,669
def _call(arg): """Shortcut for comparing call objects """ return _Call(((arg, ), ))
d7ec1e0c29b52f7d77daec3d2fa7c5f8ba6ea1f8
3,642,670
from typing import List def gather_directives( type_object: GraphQLNamedType, ) -> List[DirectiveNode]: """Get all directive attached to a type.""" directives: List[DirectiveNode] = [] if hasattr(type_object, "extension_ast_nodes"): if type_object.extension_ast_nodes: for ast_node...
211108bd35940e412e68e0b092ada050ce745c8e
3,642,671
def get_request(language=None): """ Returns a Request instance populated with cms specific attributes. """ request_factory = RequestFactory() request = request_factory.get("/") request.session = {} request.LANGUAGE_CODE = language or settings.LANGUAGE_CODE request.current_page = None ...
1ef86666693118ccd36f8d9818e70566e895cb13
3,642,672
from typing import cast def validate_hash(value: str) -> bool: """ Validates a hash value. """ return cast(bool, HASH_RE.match(value))
c273e5287e2e0448c2e58173813d725f61f3210a
3,642,673
def string_to_digit(string, output): """Convert string to float/int if possible (designed to extract number from a price sting, e.g. 250 EUR -> 250) :argument string: string to convert :type string: str :argument output: output type :type output: type :returns float/int or None """ ...
dc83485e7ffa4548aee019b67f23ba6db385421d
3,642,674
def calc_B_phasors(current, xp, yp, cable_array): """It calculates the phasors of the x and y components of the magnetic induction field B in a given point for a given cable. Given the input, the function rectifies the current phase extracting respectively the real and imaginary part of it. Then, ...
66f696121f3a26a99e4d662b3680d21199bedcc1
3,642,675
def get_shortest_text_value(entry): """Given a JSON-LD entry, returns the text attribute that has the shortest length. Parameters ---------- entry: dict A JSON-LD entry parsed into a nested python directionary via the json module Returns ------- short_text: str ...
c63511a830f56c610230e0c7e208a926b0304b3c
3,642,676
from datetime import datetime def generate_token(user_id, expires_in=3600): """Generate a JWT token. :param user_id the user that will own the token :param expires_on expiration time in seconds """ secret_key = current_app.config['JWT_SECRET_KEY'] return jwt.encode( {'user_id': user_i...
62a92d7903e941446dbef3097b12ba2adf9a1fd5
3,642,677
import codecs def debom(s): """ 此函数是去除字符串中bom字符, 由于此字符出现再文件的头位置 所以对csv 的header造成的影响, 甚至乱码 通过此函数可以避免这种情况 """ boms = [ k for k in dir(codecs) if k.startswith('BOM') ] for bom in boms: s = s.replace(getattr(codecs, bom), '') return s
4ac056a8ba93f00a0a31e3a447e62810c5b68687
3,642,678
def rolling_window(array, window): """ apply a rolling window to a np.ndarray :param array: (np.ndarray) the input Array :param window: (int) length of the rolling window :return: (np.ndarray) rolling window on the input array """ shape = array.shape[:-1] + (array.shape[-1] - window + 1, wi...
cde677c20c6a4d5f096d2f36bae2fc1087b73ccf
3,642,679
def calculate_timezone_distance_matrix(df): """ Calculate timezone distance matrix from a given dataframe """ n_users = len(df) timezone_df = df[['idx', 'timezone', 'second_timezone']] timezone_df.loc[:, 'timezone'] = timezone_df.timezone.map( lambda t: remove_text_parentheses(t).split('...
d788ab8758d0300516ecde2749cd438597775440
3,642,680
import platform def pyxstyle_path(x, venv_dir="venv"): """Calculate the path to py{x}style in the venv directory relative to project root.""" extension = ".exe" if platform.system() == "Windows" else "" bin_dir = "Scripts" if platform.system() == "Windows" else "bin" return [str(path_here / f"{venv_di...
2eaf3686f20db6ca26b55dc5cf065e926d6fd5ef
3,642,681
def update_tc_junit_resultfile(tc_junit_obj, kw_junit_list, tc_timestamp): """loop through kw_junit object and attach keyword result to testcase Arguments: 1. tc_junit_obj = target testcase 2. kw_junit_list = list of keyword junit objects 3. tc_timestamp = target testcase timestamp """ for m...
97c85b6b197a5e325c51bcb70d0f7e173f1feb1d
3,642,682
from OpenGL.error import GLError def checkFramebufferStatus(): """Utility method to check status and raise errors""" status = glCheckFramebufferStatus( GL_FRAMEBUFFER ) if status == GL_FRAMEBUFFER_COMPLETE: return True description = None for error_constant in [ GL_FRAMEBUFFER_INCO...
9a603cde0b4f9cda340f969eb8b8137cbf34fede
3,642,683
def load_sentences(filename): """give us a list of sentences where each sentence is a list of tokens. Assumes the input file is one sentence per line, pre-tokenized.""" out = [] with open(filename) as infile: for line in infile: line = line.strip() tokens = line.split() out.a...
6a4c458f9a0d9b17eaa38c38570dacc4c40e86c0
3,642,684
def imageSequenceRepr(files, strFormat='{pre}[{firstNum}:{lastNum}]{post}', forceRepr=False): """ Takes a list of files and creates a string that represents the sequence. Args: files (list): A list of files in the image sequence. format (str): Used to format the output. Uses str.format() command and requires the ...
9f8b63594eb86f54bf8d264b12bd006c2c50da20
3,642,685
def farthest_point_sampling(D, k, random_init=True): """ Samples points using farthest point sampling Parameters ------------------------- D : (n,n) distance matrix between points k : int - number of points to sample random_init : Whether to sample the first point random...
d5ab5c3f30048cd16bf38bc73bf48f58f88ef383
3,642,686
def part2(lines): """ >>> part2(load_example(__file__, '9')) 982 """ return run(lines, max)
c243792fc4b3e32a5bc41f5185cbbe1ef2d6b840
3,642,687
def get_utility_function(args): """ Select the utility function. :param args: the arguments for the program. :return: the utility function (handler). """ if args.mode == 'entropy': utility_function = compute_utility_scores_entropy elif args.mode == 'entropyrev': # Reverse entropy m...
fc49a9f3456a187b6015c9fbbdaa4faba0dfc778
3,642,689
def convertRequestToStringWhichMayBeEmpty(paramName, source): """ Handle strings which may be empty or contain "None". Empty strings should be treated as "None". The "None" strings are from the timeSlicesValues div on the runPage. Args: paramName (str): Name of the parameter in which we ar...
d620197e60e15d48d450a9406cbe3f4ea61a64d8
3,642,690
import re def find_am(list_tokens:list): """[summary] Parameters ---------- list_tokens : list list of tokens Returns ------- tuple(list,list) matches tokens, token indexes """ string = "START"+" ".join(list_tokens).lower() match = re.findall(am_p...
91663e71882764045d679b24c5cb793f1c192410
3,642,691
def calculate_min_cost_path(source_node: int, target_node: int, graph: nx.Graph) -> (list, int): """ Calculates the minimal cost path with respect to node-weights from terminal1 to terminal2 on the given graph by converting the graph into a line graph (converting nodes to edges) and solving the respective s...
ad48d0930f010ffa04f142710bd7f3aafd932e76
3,642,693
def promote(name): """ Promotes a clone file system to no longer be dependent on its "origin" snapshot. .. note:: This makes it possible to destroy the file system that the clone was created from. The clone parent-child dependency relationship is reversed, so that the origin fi...
7d6ddd76525096c13f7ff4b1a07121d52e688b24
3,642,694
def otp_verification(request): """Api view for verifying OTPs """ if request.method == 'POST': serializer = OTPVerifySerializer(data = request.data) if serializer.is_valid(): data = serializer.verify_otp(request) return Response(data, status=status.HT...
513dff831deca69a8087fe99d27f1f54108d4ae2
3,642,695
def hpd_grid(sample, alpha=0.05, roundto=2): """Calculate highest posterior density (HPD) of array for given alpha. The HPD is the minimum width Bayesian credible interval (BCI). The function works for multimodal distributions, returning more than one mode Parameters ---------- sample : ...
ee3a24f056a038b5e9ec08875d37f39e0a8180f1
3,642,697
import re def emph_rule(phrase: str) -> Rule: """ Check if the phrase only ever appears with or without a surrounding \\emph{...}. For example, "et al." can be spelled like "\\emph{et al.}" or "et al.", but it should be consistent. """ regex = r"(?:\\emph\{)?" regex += r"(?:" + re.escape(...
a6eb0eb716a265876efd857dd51dc6106a24f35b
3,642,699
import pathlib from datetime import datetime import traceback def parse_amwg_obs(file): """Atmospheric observational data stored in""" file = pathlib.Path(file) info = {} try: stem = file.stem split = stem.split('_') source = split[0] temporal = split[-2] if le...
60e00a6d2c9ac426d20e1d02f6baab05e0619988
3,642,700
def taylor(x,f,i,n): """taylor(x,f,i,n): This function approximates the function f over the domain x, using a taylor expansion centered at x[i] with n+1 terms (starts counting from 0). Args: x: The domain of the function f: The function that will be expanded/approximated i: ...
c6d5ed8b583dba8959554bb761e7a961c84624e8
3,642,701
def precision_and_recall_at_k(ground_truth, prediction, k=-1): """ :param ground_truth: :param prediction: :param k: how far down the ranked list we look, set to -1 (default) for all of the predictions :return: """ if k == -1: k = len(prediction) prediction = prediction[0:k] ...
cf8543279c6d7874f99c5badeb3064b621fa36a4
3,642,702
def bubble_sort(array: list, key_func=lambda x: x) -> list: """ best:O(N) avg:O(N^2) worst:O(N^2) """ if key_func is not None: assert isfunction(key_func) for pos in range(0, len(array)): for idx in range(0, len(array) - pos - 1): if key_func(array[idx]) > key_func(a...
40e0baa0f9a36e73b2020db8c07c332dc973b919
3,642,703
from qiskit.aqua.operators import MatrixOperator from qiskit.aqua.operators.legacy.op_converter import to_weighted_pauli_operator import scipy def limit_paulis(mat, n=5, sparsity=None): """ Limits the number of Pauli basis matrices of a hermitian matrix to the n highest magnitude ones. Args: ...
cd0b88316eb9cebda2a58ce30384f22fed17cb54
3,642,704
def tar_cat(tar, path): """ Reads file and returns content as bytes """ mem = tar.getmember(path) with tar.extractfile(mem) as f: return f.read()
f07f00156c34bd60eea7fcae5d923ea9f1650f6f
3,642,706
def __get_base_name(input_path): """ /foo/bar/test/folder/image_label.ext --> test/folder/image_label.ext """ return '/'.join(input_path.split('/')[-3:])
5df2ef909f4b570cf6b6224031ad705d16ffff42
3,642,707
def or_ipf28(xpath): """change xpath to match ipf <2.8 or >2.9 (for noise range)""" xpath28 = xpath.replace('noiseRange', 'noise').replace('noiseAzimuth', 'noise') if xpath28 != xpath: xpath += " | %s" % xpath28 return xpath
7bf508c48d5a6fc09edba340e2bfc9ec13513fc8
3,642,708
def make_form(x, current_dict, publication_dict): """Create or update a Taxon of rank Form. Some forms have no known names between species and form. These keep the form name in the ``infra_name`` field. e.g. Caulerpa brachypus forma parvifolia Others have a known subspecies/variety/subv...
43ce623d67db4142f804b0c01f8e6690831387cd
3,642,709
def render_view(func): """ Render this view endpoint's specified template with the provided context, with additional context parameters as specified by context_config(). @app.route('/', methods=['GET']) @render_view def view_function(): return 'template_name.html', {'con...
07e2f4394af5c774d3aad421cacd8f89448525b6
3,642,710
def extract_and_resize_frames(path, resize_to=None): """ Iterate the GIF, extracting each frame and resizing them Returns: An array of all frames """ mode = analyseImage(path)["mode"] im = PImage.open(path) if not resize_to: resize_to = (im.size[0] // 2, im.size[1] // 2) ...
27632e7485f98697b4bfe1fbb6aeaee18a29b5db
3,642,711
def voter_star_off_save_doc_view(request): """ Show documentation about voterStarOffSave """ url_root = WE_VOTE_SERVER_ROOT_URL template_values = voter_star_off_save_doc.voter_star_off_save_doc_template_values(url_root) template_values['voter_api_device_id'] = get_voter_api_device_id(request) ...
2f00fc92c43e7ebb6541f0e9e5bd773d3e3168a2
3,642,712
import colorsys def lighten_color(color, amount=0.5): """ Lightens the given color by multiplying (1-luminosity) by the given amount. Input can be matplotlib color string, hex string, or RGB tuple. Examples: >> lighten_color("g", 0.3) >> lighten_color("#F034A3", 0.6) >> lighten_co...
4ef801fff6cb145a687a62dd18725258f1534abd
3,642,714
def unf_gas_density_kgm3(t_K, p_MPaa, gamma_gas, z): """ Equation for gas density :param t_K: temperature :param p_MPaa: pressure :param gamma_gas: specific gas density by air :param z: z-factor :return: gas density """ m = gamma_gas * 0.029 p_Pa = 10 ** 6 * p_MPaa rho_gas =...
6e41802367bbe70ab505ae5db89ee3e9a32e7d7c
3,642,715
def poll(): """Get Modbus agent data. Performance data from Modbus enabled targets. Args: None Returns: agentdata: AgentPolledData object for all data gathered by the agent """ # Initialize key variables. config = Config() _pi = config.polling_interval() # Initia...
b922b59c659e40ddc2b341a4605465d53e8cdaa8
3,642,716
import time def dot_product_timer(x_shape=(5000, 5000), y_shape=(5000, 5000), mean=0, std=10, seed=8053): """ A timer for the formula array1.dot(array2). Inputs: x_shape: Tuple of 2 Int Shape of array1; ...
91d03070ea6efbe8d29e7bb5323aad0f20cead90
3,642,717
def npareatotal(values, areaclass): """ numpy area total procedure :param values: :param areaclass: :return: """ return np.take(np.bincount(areaclass,weights=values),areaclass)
b5e79c7648569b84a9fad77dd9ee555392a676ab
3,642,720