content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Tuple def do_ed_lines_mod_job(port_input_name: str, min_line_length: int, operator: str, gradient_thr: int = 36, anchor_thr: int = 8, scan_interval: int = 1, line_fit_err_thr: int = 1, max_edges: int = 5000, max_points_edge: int = 500, max_lines: int ...
bd674664170636d09d3db845d54c190fe696ac87
43,800
def hess_smith(x_coord,y_coord,alpha,Re,npanel,batch_analyis): """Computes the incompressible, inviscid flow over an airfoil of arbitrary shape using the Hess-Smith panel method. Assumptions: None Source: "An introduction to theoretical and computational aerodynamics", ...
b7ea2e94366002fb1a772f9f86a9b04d57d0e8fa
43,801
def filter_folders_by_predicate(walk: OsWalk, predicate: WalkPredicate, abs_path: bool = False, prune: bool = False) -> OsWalk: """ Filters a walk's folder collection using the given predicate. :param walk: The walk 'object' to filter :param predicate: The condition to check; should take in the folder ...
10e4a35bc6a9e1101a610a0fb8133aa14396a7ac
43,802
import os def extendScalarField(tetraMeshPath, meshVTK = None, threshold = None, meshNameType = '_withScalarField', recompute = False): """ Given two meshes, one superficial and another tetrahedral, extends all the scalar fields in the superficial mesh to the superficial using Laplace equation (Heat equation...
dca4938b2c63935798971deeb1dea85cdf5933bc
43,803
def get_default_baseconf_settings_filenames(): """Returns the filename string where the basic configuration will be read from. :return: filename string """ return (_baseconf_settings_filename,_baseconf_settings_filename_comments)
0f026dd4f3f330cc2cd92311818819de37baaab2
43,804
def sample_tag(user, name='main course'): """ create and return a sample tag""" return Tag.objects.create(user=user, name=name)
106fe0b97b2a311d62ec6c14099bec2d6ef4a110
43,805
def markUnexpectedSigmaPeaks(x, y, x_sigma, y_sigma, status, max_sigma, min_sigma, r_neighbors): """ For each peak, check if it has an unexpected sigma. If it does not mark the peak for removal (by setting the status to ERROR) and the neighbors as running. """ assert (x.flags['C_CONTIGUOUS']),...
db93e5a210df9db5852285fbcfbe3cd8c330424a
43,806
def cron_clean_view(): """Clean-ups every outdated article or bias pair.""" return {"cleaned": clean_articles()}
74a9f5bb69643380faa3ac288bc7028024940f4a
43,807
def calculate_plane_histogram(plane, doseplane, dosegridpoints, maxdose, dd, id, structure, hist): """Calculate the DVH for the given plane in the structure.""" contours = [[x[0:2] for x in c['data']] for c in plane] # Create a zero valued bool grid grid = np.zeros((dd['ro...
9866588a25c90fbe7fdd0db69cef413074081764
43,808
def log_model(spark_model, artifact_path, conda_env=None, jars=None, dfs_tmpdir=None, sample_input=None): """ Log a Spark MLlib model as an MLflow artifact for the current run. This uses the MLlib persistence format, and the logged model will have the Spark flavor. :param spark_model: Pip...
fccd98f6ff2a52491d850b5eba4d1ecba3065df7
43,809
def acorr(x, axis=-1, onesided=False, scale='none'): """Compute autocorrelation of x along given axis. Parameters ---------- x : array-like signal to correlate. axis : int axis along which autocorrelation is computed. onesided: bool, optional if True, only returns the ri...
11b2c4495b7f3b73d63000c7ccd694f0cfdd4c65
43,810
def jsonp(func): """ Decorator for the following JSON API functions for the connection test. """ def dec(request, *args, **kw): resp = func(request, *args, **kw) cb = request.GET.get('callback') if not cb: cb = '' resp['Content-Type'] = 'application/javascrip...
ccf8bfbffdd1ac865eb2d001f212925c332f1f82
43,811
def vtkmatrix_to_numpy(matrix): """ Copies the elements of a vtkMatrix4x4 into a numpy array. :param matrix: The matrix to be copied into an array. :type matrix: vtk.vtkMatrix4x4 :rtype: numpy.ndarray """ m = np.ones((4, 4)) for i in range(4): for j in range(4): m[i,...
779e0cad713953ddab1edb4b09b6a3d9d8006413
43,812
def PnCPjInvDyn(robot, q, qdot, qddot, s_jp, s_jd): """ q: np.array, qdot: np.array, qddot: np.array, s_jp: np.array, s_jd: np.array """ # print(qddot[0]) # print(qddot[1]) assert IsClose(qddot[0], qddot[1]) mass, mass_inv, b, g, lambda_i, jac_i_bar, null_i = UpdateRobotSystem( rob...
3c8dda501f64e77c8cbf019d46e0ea7ca3c8dd71
43,813
import torch import copy def load_model(str_filename, which_iteration=-1): """Load a previously saved model and its history from a file """ print("Loading model from %s" % str_filename) data = torch.load(str_filename) # Set the type for floats from the save set_dtype(data['cfg']['dtype']) # Reconstruct Geo...
59fe20b8eca8cce81b3af722cb0c0a219152d89d
43,814
from typing import Dict def Tbeam( depth: RealNumber, web_thickness: RealNumber, flange_width: RealNumber, flange_thickness: RealNumber, ) -> Dict[str, float]: """ Calculates the Centroid, Area, Moment of Inetia, and Section Modulus of a T beam. The assumed orientation is with the dep...
299df21bbd0ee6bd0bb92f717ee511eb5ee8a7e5
43,815
def get_base_required_field_types(): """ Get field types for UI asset required fields. 2016-08-24: removed 'coordinates': 'floatlist', 2016-08-26" remove 'augmented': 'bool', 'Ref Des': 'string','hasDeploymentEvent': 'bool','remoteDocuments': 'list', added 'editPhase' can have values: EDIT, STAGED, OPER...
0cb8b6041aeaf25efe8ad29e3986237efe5e382f
43,816
def _index_p(es_client: elasticsearch.Elasticsearch, index_name: str) -> bool: """ Checks if the given index exists. """ indices = IndicesClient(es_client) return indices.exists(index_name)
93946793a51ac6a19ddf93d3bc99c84a13403fc0
43,817
def histogram(arg, nbins=None, binwidth=None, base=None, closed='left', aux_hash=None): """ Compute a histogram with fixed width bins Parameters ---------- arg : numeric array expression nbins : int, default None If supplied, will be used to compute the binwidth binwidth...
f835099297f3c4062e29478cd4289b8fe8a6adcc
43,818
def load_cam_params(path): """Loads camera parameters from a JSON file. :param path: Path to the JSON file. :return: Dictionary with the following items: - 'im_size': (width, height). - 'K': 3x3 intrinsic camera matrix. - 'depth_scale': Scale factor to convert the depth images to mm (optional). """ ...
7564e81de1c3451bff47d61dfd81b07d5684298d
43,819
from typing import Set def _create_new_wells(field_id: int, well_names: Set[str]) -> None: """Create new wells if not exists""" return Well.objects.bulk_create( [Well(name=well_name, field_id=field_id) for well_name in well_names], ignore_conflicts=True )
5c085afa0be5e01c0d57e2a177060dda202659ca
43,820
import _io def _shell_lookup(args): """This function is called when the script is used from command line: [jakni@nissen scripts]$ python unifetch.py -a A6XGL2 -ncis Name: A6XGL2_HUMAN Data class: Unreviewed TaxID: 9606 Sequence: MALWMRLLPLLALLALWGPDPAAAFVNQHLCGSHLVEALYLVCGERGFFYTPKTRRE [ ... ...
64a12b15f9188bbc0b3a6608f1dbfeb824c1fed3
43,821
def get_feature_symbolic_learning(df, gp_config): """ Parameters ---------- df: pd.DataFrame,the input dataFrame. gp_config: GPConfig object, the config object of gplearn.SymbolicTransformer. Returns ------- df_t: pd.DataFrame, df with the features of SymbolicTransformer trans. ...
abda49c0c16934f631a50a39c3debc6a2a439dae
43,822
import torch def top_k_top_p_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')): """ Filter a distribution of logits using top-k and/or nucleus (top-p) filtering Args: logits: logits distribution shape (vocabulary size) top_k > 0: keep only top k tokens with highest ...
621d9622e87063edc9918655061550e5cbdd5bb8
43,823
def compute_angular_error(input_: np.array, target_: np.array) -> float: """ Args: input_: N*2 numpy array containing the predicted yaw and pitch angle target_: N*2 numpy array containing the corresponding target_ yaw and pitch angle. Returns: Average angular error (in degree) ""...
05feac332b52885c39c463c7c030fa65e8afc4e9
43,824
import json from datetime import datetime def messages(request): """ need to check user login or not""" if request.POST.get("mode") == "get_messages": data = get_messages(request) return HttpResponse(json.dumps(data)) if request.POST.get("post_message"): data = { "messa...
cc87f8b4d28d68451d2ae94b483859f429585476
43,825
from typing import Dict def from_strings_to_dict(data: Dict[str, str]): """ Makes a model for a given list of string like : "mission.document.name": "test" => { mission: { document: { name: "test" } } } This way we will merge the model with ...
78f8295f84b294827a7279887587cd9ccbf8a2ec
43,826
def to_rgb(img): """ Converts the given array into a RGB image. If the number of channels is not 3 the array is tiled such that it has 3 channels. Finally, the values are rescaled to [0,255) :param img: the array to convert [nx, ny, channels] :returns img: the rgb image [nx, ny, 3] ...
b5e4a2dc8d0bc6c8590f4e09db8b2d6b26c2e120
43,827
from datetime import datetime def stopwatch(): """Track the running time.""" if not hasattr(stopwatch, "start"): stopwatch.start = datetime.now() return str(datetime.now() - stopwatch.start)[:-7]
bfd8ff043661dfad1c81f84ac3b86eb10b61f14d
43,828
from typing import List from typing import Tuple def get_list_probs( mutation_list: List[Tuple[Mutation]], mutate_probs: SequenceProbsList, length_mutations: List[int], ) -> Tuple[List[List[float]], List[List[float]]]: """This function build a list of mutate and native probabilities to compute the...
b5642dbcb912237a58e1feb34f7c07e7d946e37e
43,829
def centerOfRect(rect): """ Returns the center of NSRect rect as an NSPoint. """ x = rect.origin.x + rect.size.width * 0.5 y = rect.origin.y + rect.size.height * 0.5 return NSPoint(x,y)
5bc670d3f4bfd888d51e65039d3aa9eae37a56ca
43,830
import math def gcj02towgs84(coor): """ GCJ02(火星坐标系)转GPS84 :param lng:火星坐标系的经度 :param lat:火星坐标系纬度 :return: """ lng = coor[0] lat = coor[1] if out_of_china(lng, lat): return lng, lat dlat = transformlat(lng - 105.0, lat - 35.0) dlng = transformlng(lng - 105.0, lat - ...
b79280228ee3fb2351edd44e1aa44037c4e7235c
43,831
import numpy def encode_data(labeldata,hot_vector = 1): """ Takes array of label data, and transforms it into array of one-hot encoded vectors. Args: labeldata (iterable): Array or list of data labels hot_vector: value assingned for hot, default 1 Returns: ...
92f4bb37428fa2023047abf9d368876bb6d529e5
43,832
from typing import Union def get_delay(delay_str: Union[str, int]) -> float: """Get the delay from an api call Args: json (List[str]): The delay from the json body Returns: int: The delay in seconds, 0 if no delay was found """ delay = 0 # Already in seconds if isinstanc...
41b5cbbad4d153509d7ce30a251a161dfe643218
43,833
def is_polymorphic(v, on_types=None): """ Tests if a function is polymorphic. If `on_types` is provided, checks to see if a function is generic on the set of provided types. """ if isinstance(v, Function) and v.polymorphic: if on_types is not None: gens = set(on_types) ...
4376c475b779e2d54c51077103effe96b9fb5f90
43,834
import random def get_random_word(min_word_length): """Get a random word from the wordlist using no extra memory.""" num_words_processed = 0 curr_word = None with open(WORDLIST, 'r') as f: for word in f: if '(' in word or ')' in word: continue word = wor...
5060073041076a4989c32fce1a7c267a88e028b5
43,835
def get_copysetup(copytools, copytool_name): """ Return the copysetup for the given copytool. :param copytools: copytools list from infosys. :param copytool name: name of copytool (string). :return: copysetup (string). """ copysetup = "" for ct in copytools.keys(): if copytool_...
1181352a178f954d17cf7d7b8fc6c798b441d4a6
43,836
def last_occurence_of_tag_chain(sequence, tag_type): """ Takes a sequence of tags. Assuming the first N tags of the sequence are all of the type tag_type, it will return the index of the last such tag in that chain, i.e. N-1 If the first element of the sequence is not of type tag_type, it will return -...
0edcf25e18ff4b3701f92c13bab2b634b738c158
43,837
from itertools import islice from collections import deque def tail(count): """Print the last COUNT lines. Roughly equivalent to: tail -n COUNT """ def tail(lines): if count <= 0: # TODO: don't read in memory, use a temporary file return iter(deque(lines, maxlen=-cou...
6e2187af0dd4450dc2f038a2950c8463613a9ed7
43,838
def supports_parenting(): """Does this Engine support parenting of objects, aka nesting of transforms or attaching objects. This is important when sending transformation values. """ return False
0dd8fc9e5c1917f10cf9d09a1fb75b470abc6eec
43,839
def dec_to_deg(degree: float, minute: float, second: float) -> float: """ Convert Dec from (deg, arcmin, arcsec) -> degree """ deg_sign = 1. if (degree + np.absolute(degree)) > 0 else - 1. return deg_sign * (np.absolute(degree) + minute / 60. + second / 3600.)
5ca7c3b36a16c7d603c8aae1100431b15f3323de
43,840
def sigmoidDerivative(X): """ input : array of features output : Sigmoid derivative of the input """ return stable_sigmoid(X) * (1.0 - stable_sigmoid(X))
21f4ac50d04da07e7525ded5954f890131cee6d4
43,841
def extract_sub_type(vfm_array): """ Extracts the subtype for each element of the array. Its interpretation depends on whether the feature is an aerosol, cloud, or Polar Stratospheric Cloud. Aerosol: 0 = not determined 1 = clean marine 2 = dust 3 = polluted co...
446f3ebc8a46e35bde092c9ec22e4748d422d0ec
43,842
def set_enabled_equivalencies(equivalencies): """ Sets the equivalencies enabled in the unit registry. These equivalencies are used if no explicit equivalencies are given, both in unit conversion and in finding equivalent units. This is meant in particular for allowing angles to be dimensionless. ...
aa338c62b16764a2b7b4f7116a51867238480445
43,843
from typing import List from typing import Tuple import os def get_links(source: str, subdir: str) -> List[Tuple[str, str]]: """Returns a list of all symlinks (and the directories they point to) between *source* and *subdir*. """ if not source: return [(subdir, realpath(subdir))] if islink(sub...
8b4f7abc333ead8ffef50d29066b2dc1674a0ee7
43,844
import sys def validate_query(query_str, verbose=True): """ Given a query, ensure it has a year and a denomination and extract them :param query_str: (str), query input from user :return query_params: (tuple) year(str), denomination(str), mint mark(str), str if included, None ...
710992ed38698d144ab2799ad0a449ffa594859a
43,845
def tune_clf_binary_grid(X, y_true, clf_name, n_splits_cv=5, refit_score='precision'): """ Tune a classifier using grid search cross validation """ scorers = { 'precision': metrics.make_scorer(metrics.precision_score), 'recall': metrics.make_scorer(metrics.recall_sco...
b7c3ec61d04accd342c33c901a9056c9e76d426e
43,846
def ESMP_GridGetCoordBounds(grid, staggerloc=constants.StaggerLoc.CENTER, localde=0): """ Preconditions: An ESMP_Grid has been created and coordinates have been added via ESMP_GridAddCoord().\n Postconditions: Two numpy arrays containing the grid coordinate ...
46362dd13a37ed0f9b9ec88c6c96dae508aab20c
43,847
def set_user_stared(oauth_id, uindex): """ 设置用户收藏,保存一年时间 """ key = settings.REDIS_USER_STAR_KEY % (oauth_id, uindex) return R.set(key, '1', 365 * 24 * 3600)
761bae38a3f1fa052ff337e6d7d71d64efebd601
43,848
def isChar(ch): """This function is DEPRECATED. Use xmlIsChar_ch or xmlIsCharQ instead """ ret = libxml2mod.xmlIsChar(ch) return ret
3d044a38070e753107a940883790d262a6006871
43,849
def scipy_graduate_walk(*args, **kwargs): """Scipy-compatible graduate_walk function wrapper. parameters: args[0]: target, function to be minimized args[1]: x0, starting point for minimization dx=1e-8: step in change of the point dx_start=0.1: starting value for dx step. Must be...
d1339eb0c879aa58e508fe0744edb9d12f1be515
43,850
import os import io def extract_sequences(infile, identifiers=None): """Extract sequence(s) from a multi-sequence FASTA file. Parameters ---------- infile : str file path to input multi-sequence FASTA file identifiers : int sequence index (n-th sequence in the file) ...
77802749705a74e26acfce9694e055e02553a9e2
43,851
from pathlib import Path def extract_doc(pdf_path, window_len): """Create a Document with features extracted from a pdf.""" pdf_path = Path(pdf_path) tokens = tokenize_pdf(pdf_path) # Remove tokens shorter than three characters. df = tokens[tokens["token"].str.len() >= 3] df = add_base_feature...
4ccdc178f467490eadbd61f9d484867732b4f4a0
43,852
def get_version(rel_path): """Fetch the version of package by parsing the __init__ file """ for line in read(rel_path).splitlines(): if line.startswith('__version__'): delim = '"' if '"' in line else "'" return line.split(delim)[1] else: raise RuntimeError("Unable...
d034e637301c2cbfd9a7f8ab7f94d091789a8648
43,853
def get_job_class_from_module(user_bp_module): """Returns Job class given a module""" UserJob = None for item in dir(user_bp_module): obj = getattr(user_bp_module, item) if isinstance(obj, (type(Job))): if obj.__bases__[0] == Job: UserJob = obj return UserJo...
27e8b672b969c3f0a36ccb5c7711b80f314392c3
43,854
def welford_simulatenous_update(prev_avg, prev_M2, new_value, count): """Perform Welford's simulatenous update on mean and variance M2 = n*sigma_n^2 Parameters ---------- prev_avg: array_like Vector of (count-1)th step averages prev_M2: array_like Vector of (count-1)...
b7b02af85e03d0b0fce8b035d24fb0872134ee39
43,855
import os async def download_file(post_id: int = None, contribuition_id: int = None, database: Session = Depends(get_db)) -> FileResponse: """ Description ----------- Função que permite fazer o download do arquivo de audio da publicação o...
2c4b9c7eb0665ffee8c89e513d0970d8a74ea6ea
43,856
import os def run(output_dir, data_dict, transform_func): """ Transform mapped data tables into merged dataframes, one df for each target entity type. transform_func must return a dict where keys are names of OMOP SQLAlchemy models: df_out = { 'Person': person_df, 'Spe...
e96d5e072b3b9e5480b96f3c1f8b1519bca0223a
43,857
import os from sfepy import data_dir import subprocess, shutil, tempfile def gen_misc_mesh(mesh_dir, force_create, kind, args, suffix='.mesh', verbose=False): """ Create sphere or cube mesh according to `kind` in the given directory if it does not exist and return path to it. """ ...
ebc03114456b4bfdcd2a0dc8bb36d4c16dd08b1e
43,858
import inspect def parse(source: str, eval_: bool = True, globals_=None, locals_=None, ast_module=typed_ast.ast3, *args, **kwargs): """Act like ast_module.parse() but also put static type info into AST.""" if globals_ is None or locals_ is None: frame_info = inspect.getouterframes(inspect.c...
d38cf042930fa717b4baea183e5b621fae6368eb
43,859
def gitCommitId(path, ref): """Return the commit id of *ref* in the git repository at *path*. """ cmd = gitCmdBase(path) + ['show', ref] try: output = runSubprocess(cmd, stderr=None, universal_newlines=True) except sp.CalledProcessError: print(cmd) raise NameError("Unknown gi...
9fe5ab16bfa0da97146bd2b2c5b647482dcf56ef
43,860
def cvFree(*args): """cvFree(void ptr)""" return _cv.cvFree(*args)
e518b9e502f7620d81a3c311d3e4200676de4621
43,861
def make_constant_schedule(step, cutoff_idx=np.inf): """ step - - - ▖▖▖▖▖▖▖▖▖▖▖▖ 0.0 - - - - - - - - - -▖▖▖▖▖▖ | | 0 cutoff_idx """ def schedule(n): if n >= cutoff_idx: return 0. return step return schedule
737e9e6995c252ac2b242cb756770a92856f659a
43,862
def delete_custom_data(request_ctx, user_id, scope, ns, **request_kwargs): """ Delete custom user data. Arbitrary JSON data can be stored for a User. This API call deletes that data for a given scope. Without a scope, all custom_data is deleted. See `UsersController#set_custom_data <https://g...
3aa7256294cf4ce64503c70931d4fbbbe3852b6e
43,863
import pickle as _pickle def _pipespawn(argv, env): """ Pipe spawn """ # pylint: disable = R0912 fd, name = mkstemp('.py') try: _os.write(fd, ((r""" import os import pickle import subprocess import sys argv = pickle.loads(%(argv)s) env = pickle.loads(%(env)s) if 'X_JYTHON_WA_PATH' in env: ...
3d26cdd77a6dbf9a4f32ab67552a0313f168b0b1
43,864
from datetime import datetime def clean_date(date): """ Ensure a date has the correct English format. :param (str) date: date to clean. """ try: dt = datetime.datetime.fromisoformat(date) except ValueError: return '' else: return datetime.datetime.strftime(dt, "%m/...
3251b7620446ed689115631e85984f7479066ab6
43,865
def returnCAM(feature_conv, weight_softmax, class_idx): """create cam image""" # generate the class activation maps upsample to 256x256 size_upsample = (256, 256) nc, h, w = feature_conv.shape output_cam = [] for _ in class_idx: cam = weight_softmax[class_idx].dot(feature_conv.reshape((n...
e0039bfd3c3b47716b78db685e6191dab99bdfa4
43,866
import ast import collections import six def to_str(tree, astlib=ast): """Convenient function to get the python source for an AST.""" class Printer(annotate.get_base_visitor(astlib)): """Traverses an AST and generates formatted python source code. This uses the same base visitor as annotating the AST, b...
e2998c263ffed4a8dc3d0745d99f558b4b93d308
43,867
from pathlib import Path import errno import json def _load_config(path: str) -> dict: """Load the JSON formatted config file. Parameters ---------- path : str The path of the JSON file we should load. Return ------ dict The parsed data from the JSON file. """ pat...
f1b9a0f8b902c5bfe1b282f589f5bb337cf6bcd9
43,868
def _add_dummy_encoder(circ): """add a dummy parameterized gate""" para_name = circ.para_name index = 0 while True: name = f'_d_{index}' if name not in para_name: dummy_circ = Circuit().rx(name, 0).no_grad() return dummy_circ + circ, name index += 1
041074ff48dea4318165328e6a1e1973bcee7741
43,869
def get_target_group_with_type_color_and_workspace(tg_type, color, workspace): """ Récupère un target group ayant un type et une couleur précise :param tg_type: Type recherché :type tg_type: str :param color: Couleur recherché :type color: str :param workspace: Workspace :type work...
74baf63ee309201f4b15462380f8fb3f8024ce23
43,870
def resource_path(level = 2): """Return a resource path calculated from the caller's stack. """ return get_resource_path(level + 1)
be93c9e3202bdd447d5305534e479d01997f7f0f
43,871
def split_residue_id(atom): """Takes an atom and splits its het ID into components. :param Atom atom: the atom to read. :rtype: ``tuple``""" if atom.het: id = atom.het.id.split(".")[-1] num = "".join([c for c in id if c.isdigit()]) insert = "".join([c for c in id if c.isalpha()...
7340c24dc1ef982fd0a3772764a02d7c8fd30126
43,872
from typing import Union def get_latest_education(education_history: list[Education]) -> Union[Education, HigherEducation, None]: """ Currently we presume that the education history passed in is ordered, we can add in sorting here by attendance date if we need to in the future """ if len(educa...
f89688a8f0a846326fb48877f964fe35d20d53a0
43,873
import argparse import sys def main(argc, argv): """ ============================================================================ Name: main Description: The main program function. Parameter(s): argc: The number of arguments passed on invocation. argv: A list (tup...
675ae763f3648c6d90bf9bb591b06f8d6e0fa712
43,874
def get_model(controller, name): """ List information for model Arguments: name: model name controller: name of controller to work in Returns: Dictionary of model information """ models = get_models(controller)['models'] for m in models: if m['short-name'] == name: ...
c4af45535cc1470ce0c25397af98eaea8e6ae574
43,875
def transform_coord(y_coordMat, x_coordMat, rotationCenter, transformVect): """ Transform x-y coordinate (y_mat & x_mat) by transformVect | round to int | return rotated y & x coord as vector""" """ y_mat and x_mat are the coord to be rotated | rotationCenter [y;x] or [y;x;phi] are the centre of rotation by the...
89c28fd7f5f60b20f99952538eedda89546c5b14
43,876
import numpy as np def pvs(t): """ Saturation vapor pressure as a function of tempetature t [°C] """ T = t + 273.15 # [K] Temperature # pws(T) [Pa] saturation pressure over liquid water # for temp range [0 200] °C eq. (6) C8 = -5.800_220_6e3 C9 = 1.391_499_3e0 C10 = -4.864...
8ba1aced4669753cca0ff2332bc2bd7ad5ad7814
43,877
from typing import Callable from typing import IO from typing import Optional def createPresenter(opener: Callable[[], IO[bytes]], fileName: str ) -> Optional[ReportPresenter]: """Attempt to create a custom presenter for the given artifact. Return a resource that handle...
8a3452cd2a99c0b934850205f7a95193817349b5
43,878
def enumerate_bonds(mol): """ A helper function for calling Molecule.enumerate_bonds First, get the Kekulized molecule (get the Kekule version with alternating single and double bonds if the molecule is aromatic), since we don't have implementation for aromatic bond additivity corrections """ mo...
5b2e1aad49fa9eebd7b67a442c59e8edcb295bf4
43,879
def _build_link_str(frame_info: Traceback) -> str: """ Build the clickable link string for a frame info object. """ return f'{INDENT}File "{frame_info.filename}", line {frame_info.lineno}, in {frame_info.function}'
e6781b17fbf19c82b05282c33935a7fd1849d843
43,880
def save_output_node(out): """ This calcfunction saves the out dict in the db """ out_wc = out.clone() return out_wc
7f89752332c023558dfb2ea7774231e1c1eeab99
43,881
def inject_spectrum(model, snr=100, dt=1, res=50, planet_params={}): """ Inject the synthetic model into chromatic Rainbow Parameters ---------- model : synthetic_planet Synthetic planet object with wavelength-varying limb-darkening coefficients, as defined in generate_spectrum_ld r_sta...
6f910a85c85ea7dc59bfd3ac1b27692e29a4a88f
43,882
import numbers def l2_regularizer(scale, name='l2_regularizer'): """Returns a function that can be used to apply L2 regularization to weights. Small values of L2 can help prevent overfitting the training data. Args: scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer. name: An optional na...
58f5e48b9af5a5d7ddf3217a68262e441677cd24
43,883
def cal_fdp_power(selected, non_zero_index, r_index=False): """ Calculate power and False Discovery Proportion Parameters ---------- selected: list index (in R format) of selected non-null variables non_zero_index: true index of non-null variables r_index : True if the index is taken from rpy2 ...
5e14b19c95ec0bc465c6ea6c98606768f00ee49e
43,884
def _serialize_dictionary_value(value, charset) : """ Serialize dictionary value """ error_code = Error(errOk) if value is None : return error_code, NULL_STRING result = "{" comma = "" for key, child_value in sorted( value.value.items(), key = lambda value: (value[1].order_number, value[0])...
888f344dc12afa42f2f7054bc62958a7915c82a3
43,885
def _create_types_map(sqltypes): """Take a types module and utilising the `dir` function create a mapping from the string value of that attribute to the SQLAlchemy type instance. """ sql_types_map = { item.lower(): getattr(sqltypes, item) for item in dir(sqltypes) if item[0]....
69a3902663eadc70050acc0c1869fcb86a2a6384
43,886
def discuss(topic) : """Discuss a topic with the user and return their response. Ask if the user likes the topic and why. Parameters: topic (str): The topic under discussion. Return: str: Response to the question of why they like the topic. """ like = input("Do you like " + to...
854dcb744440b98fbbeb763e9ae0a866afb5d7d0
43,887
def sigmoid(x): """ sigmoid function :param x: :return: """ return 1.0/(1.0+np.exp(-x))
6e147229a6b527bff1e0976abde0f472ea60ab84
43,888
def numba_update_portability_matrix( portability_matrix, r_ct_g, c_ct_g, c_f_g, c_cf_g, c_dt_g ): """ updating the probability matrix """ for a, b, c, d, e in zip(r_ct_g, c_ct_g, c_f_g, c_cf_g, c_dt_g): portability_matrix[a, b, c, d, e] = 1 return portability_matrix
138a55af650ab98d1ff4d991b5f81e6f709148c8
43,889
def _sin(t: 'Tensor') -> 'Tensor': """ Also see: --------- :param t: :return: """ data = np.sin(t.data) requires_grad = t.requires_grad if requires_grad: def grad_fn(grad: np.ndarray) -> np.ndarray: return grad * np.cos(t.data) depends_on = [Dependency(...
968f95788758d56414206859e48daa3ef5b4b080
43,890
def confirm(prompt, default=False): """Give a yes/no prompt with the default letter (y or n) presented as uppercase""" if default: prompt += " [Y/n] " else: prompt += " [y/N] " response = None while response is None: raw_input = input(prompt) if raw_input == "": ...
5d33b6f1116b7c7cf134afcd4c6749f183abb5d7
43,891
from . import genshistream from . import lxmletree from . import etree import sys def getTreeWalker(treeType, implementation=None, **kwargs): """Get a TreeWalker class for various types of tree with built-in support treeType - the name of the tree type required (case-insensitive). Supported va...
864eb72b48db45931908163a3e87237641022544
43,892
def get_ssa(net, blob_versions=None): """ Given a net, return a structure containing the version of each input and output blob used by each operator. Args: net: either a Net or a NetDef blob_versions: (optional) map with current version number for given ...
e800cd02d46302790dd1c96aebc7170f590f56de
43,893
def band_dos_element_spd_spin_polarized( band_folder, dos_folder, element_spd_dict, output='band_dos_element_spd_sp.png', scale_factor=5, color_list=None, legend=True, linewidth=0.75, band_color='black', unprojected_band_color='gray', unprojected_linewidth=0.6, figsize=(8...
a07b4efe8f4cb297abe618217dbc8785f3fc5428
43,894
def get_redirect_target(): """ Returns the redirect target. """ for target in request.args.get('next'), request.referrer: if not target: continue elif is_safe_url(target): return target
9c715bb77a670f15a8c10acaf29efbe99ab245af
43,895
from typing import Callable import functools def construct_schedule( name: str, **kwargs, ) -> Callable[[chex.Numeric], chex.Array]: """Constructs the actual schedule from its name and extra kwargs.""" if name == "fixed": return functools.partial(fixed_schedule, **kwargs) elif name == "imagenet_sgd"...
c1bb57b08af3aa47078d58f831118d76cce455f6
43,896
from typing import IO from datetime import datetime def set_month_year(io: IO, user_selected_moth_year: str) -> tuple[int, int]: """ Produce Month/Year combination to filter calendar by :param io: instance of IO object :param user_selected_moth_year: string containing user-selected combination of Mont...
f3dc4cb2b043e0eacadd54d43b771f0571176195
43,897
def dump_to_writer(writer, resources, resource_type=None, fields=None): """ Dump resources to a CSV writer interface. The interface should expose the :py:class:`csv.writer` interface. :type writer: :py:class:`csv.writer` :param writer: Writer object :param fields: List of fields to write :...
6824ca0ddbb893c41be335237d4d88e9de4c0c9f
43,898
def find_author(name, authors): """ Find the author with the provided name, in the list of authors""" for author in authors: if author.name == name: return author raise ValueError('Author', name, 'not found.')
dd47f0ecf8574d68a0ce9b5e94dff19b58f5887a
43,899