content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def fper(input, precision=3, mixed_fraction=False): """ Format PERcentage Multiply input by 100 and round it to the number of decimal points specified by precision (default 3) """ value = iiw(around(input * 100, precision)) if mixed_fraction: value = ffrac(value) return rf"{value}%...
f8dc15735482a15569b6925d69f2904b9c9a69c0
59,537
def hpo_mapping() -> pd.DataFrame: """Return dataframe containing phenotype HPO mapping.""" df = pd.read_csv( "http://compbio.charite.de/jenkins/job/hpo.annotations.monthly/lastSuccessfulBuild/artifact/annotation/ALL_SOURCES_ALL_FREQUENCIES_phenotype_to_genes.txt", sep="\t" ) columns = d...
0093c437639853c6f8726c6d5b0a545cd4ea146a
59,538
import time import re def get_uniqueID(idPrefix): """Generates a unique id """ t = time.ctime() uid = '_'.join([idPrefix, t]) return re.sub(r'[: ]', '_', uid)
b36bdd7548343f69cd2c093f66c74314d37b9665
59,539
def prev_next_submission(submission): """Return adjacent sumbission objects for the given submission.""" return (Submission.earlier_submission_for_group(submission), Submission.later_submission_for_group(submission))
b23328e6cbe809c42e2be575447ae584e83720b2
59,540
import json def test_mechanisms(): """Checks factsheet mechanisms. Checks that there is no empty list or dict. Checks that 'type' is either exponential or decay or uniform. Checks that if type is exponential, there is an according ['dist']='exp' field in parameter file. Idem if type is de...
2ecbc7cfc0bca7fc57c6ef748487a12cc0d21d22
59,541
def _path_create(self, graph): """ Construct a path within the specified `graph` from the nodes and relationships within this :py:class:`Path` instance. This makes use of Cypher's ``CREATE`` clause. """ return _path__create(self, graph, unique=False)
a7bc4dd458fc5856b3412705d3727e038499888f
59,542
from typing import Union import copy def headline(text, **kwargs) -> str: """ex. header('your text here', halign='^', width=100, pad=True, header=True, char='#', clip=True) :param text: :type text: :param kwargs: :type kwargs: :return: :rtype: str """ hdict = {'left': '<...
35b51c169263e444cd4b7d5fd00196f3dedc8952
59,543
def layer_norm(x, filters=None, epsilon=1e-6, scope=None, reuse=None): """Layer normalize the tensor x, averaging over the last dimension.""" if filters is None: filters = x.get_shape()[-1] with tf.variable_scope(scope, default_name="layer_norm", values=[x], reuse=reuse): scale = tf.get_vari...
d3e4caa3834a69be372b0c3c78e50eac8b2ea4d9
59,544
def solve(A, b): """ Solve a system of equations Ax = b by Gaussian elimination Parameters ---------- A : 2d-array The LHS of the system of equations. The number of rows must not be less than the number of columns, but can be more. b : array-like The RHS of the syste...
8a5a5f374f92fae7e4a495a334666dcc62dd212d
59,545
def get_event_subscriptions(ip, login_account, login_password): """Get event subscriptions :params ip: BMC IP address :type ip: string :params login_account: BMC user name :type login_account: string :params login_password: BMC user password :type login_password: stri...
4b9b2cf3f2c83505a77d18ba663e90a5aeb780fb
59,546
async def system_health_info(hass): """Get info for the info page.""" info = await system_info.async_get_system_info(hass) return { "version": f"core-{info.get('version')}", "installation_type": info.get("installation_type"), "dev": info.get("dev"), "hassio": info.get("hassi...
d29af8a006ab187123f3b70c0bfbb88807f1a276
59,547
def _generate_image_and_label_batch(image, label, min_queue_examples, batch_size, shuffle): """Construct a queued batch of images and labels. Args: image: 3-D Tensor of [height, width, 3] of type.float32. label: 1-D Tensor of type.int32 min_queue_examples: int32, min...
c4499cc46769f622a821657cec1b552ca132211f
59,548
def count_helices(d): """Return the helix count from structure freq data.""" return d.get('H', 0) + d.get('G', 0) + d.get('I', 0)
8469adabac42937009a1f8257f15668d630a7ca8
59,549
def get_dataframe(subset, data_home): """ This method retrieves the dataframe and creates IDs for the dataframe """ data = fetch_20newsgroups(data_home=data_home, subset=subset, categories=None,\ shuffle=True, random_state=42, remove=('headers', 'footers', 'quotes'),\ download_if_missing=True, r...
04f1f25d61a5d6cd0016e805d1dd9f1cbf8c6f87
59,550
def find_all_gauges(imagePath,blurs,imgss,LURD): """ 通过点击鼠标得到面积 """ LURD = np.array(LURD) mianji = abs((LURD[0]-LURD[1])[0]*(LURD[0]-LURD[1])[1]) # 应变片面积 #mianji = 400 blur = blurs.copy() imgs = imgss.copy() row,col = blurs.shape[:2] blurs = cv2.convertScaleAbs(blur,alpha=1.5,bet...
dcf42b76f89da724e4f838be3a1ceafd9acf8cb4
59,551
def stop_words_remover(df): """ This function removes stopwords from a list containing list of tweets which matches with stopwords from a dictionary than returns a modified dataframe """ list_of_tweets = [] final_list_of_tweets = [] for row in df['Tweets']: list_of_tweets.appen...
3e68e35c2e36e86200364ff3a2c42865bef50403
59,552
def solve(lines: Lines, steps: int) -> int: """Solve the problem.""" bodies = parse_input(lines) system = OrbitalSystem(bodies) # system.print_state() for step in range(steps): system.step() # system.print_state() return system.total_energy()
ec8f48c70da04a0a6c8058f92911dda89e62edf9
59,553
def get_market_gainers(**kwargs): """ Top-level function for obtaining top 10 market gainers from the Stocks list endpoint """ return MoversReader(mover='gainers', **kwargs).fetch()
a39fa1cf2f87fc11bedf6d052727d5d76bbf6d34
59,555
import ipaddress def parse_listen_addr(listen_addr): """ Parse an address of the form [ipaddress]:port into a tcp or tcp6 Twisted endpoint description string for use with ``twisted.internet.endpoints.serverFromString``. """ if ':' not in listen_addr: raise ValueError( "'%s'...
70a1278bf49a41868d85c56bdbcb5d01ae49a6d1
59,556
def is_style(style): """Check if a style is included in the BJCP guidelines. Keyword arguments: style-- string naming a suspected style """ styles = all_styles() if style in styles: return True else: return False
94da84cc200a89ac09c4b7e63400af285ee19083
59,558
from typing import Any def to_number(s: str, default: Any = float("NAN")) -> Any: """文字列を数値化 Example: >>> to_number('△12,345') -12345 >>> to_number('12,345') 12345 >>> to_number('12円34銭') 12.34 >>> to_number('98%') 98 >>> to_number('abc')...
b7083eff9d73fc7e6cc2f31a8a7000f8dbef4d87
59,560
def import_from_file(request): """Import pages from a CSV file. The CSV format is compatible with the one that the CSV exporter generates. This means it's possible to export pages to CSV, make changes and then import the file to bulk update them. Import is all-or-nothing. If there is at least one ...
dcdc370df5022711e7efde4f6e020e0330b46ac1
59,561
def make_data_island(density, bulk_modulus, firing_temperature, binders, powders, tag=None): """Helper function to create a relatively involved data island.""" binder_specs = keymap(lambda x: MaterialSpec(name=x), binders) powder_specs = keymap(lambda x: MaterialSpec(name=x), powders) binder_runs = key...
70506855b72516e227bc3c4fe821bb1b5a9d7763
59,562
def merge_segmentations(segmentations, xy_offsets, extend=True, f_accept=0.2, post_merge_dilate=1): """ Parameters ---------- segmentations xy_offsets extend f_accept post_merge_dilate Returns ------- """ # merge detections masks by align, summa...
6ffb92410ac903c30860087b8dce6e62fa6471cf
59,563
def home(): """ Root/Home Page - Shows the ReST API Paths """ return jsonify(routch.getall())
2808444f0cd7c82f3438dca2ae6fa3942fd2b614
59,564
from datetime import datetime import itertools def satisfies(query, **kwargs): """Check whether a given datetime object satisfies day and time predicates Keyword Args: month: The month predicate (January, February, ...) day: The day of month predicate [1 31) weekday: The day of week p...
e36ff908a31e71eab242b9ff6cf4df6721a1fbf7
59,565
def register_model(model_type): """Registers a model by name.""" def _decorator(model_cls): if model_type in MODEL_REGISTRY: raise ValueError('model type %s already registered' % model_type) MODEL_REGISTRY[model_type] = model_cls model_cls.model_type = model_type ret...
573fc50c86e8faa724b05b55d17b03e63b8edbcf
59,566
def open_dataset(fname): """Open a single dataset from fv3chem outputs (nemsio or grib2 currently) Parameters ---------- fname : string Filename to be opened Returns ------- xarray.Dataset Description of returned object. """ names, nemsio, grib = _ensure_mfdataset_...
121a88820fc328ae83f28529d03c9b01c2d559ce
59,567
def load_reward(reward_type: str, reward_path: str, venv: VecEnv) -> common.RewardFn: """Load serialized reward. Args: reward_type: A key in `reward_registry`. Valid types include {reward_types}. reward_path: A path specifying the reward. venv: An environment that the policy...
6acad5fb4c25b42bb2619df637153390c6741783
59,568
def mod_sigmoid(z, scope='', reuse=None): """ ModSigmoid implementation, using a coupled alpha and beta. """ with tf.variable_scope('mod_sigmoid_' + scope, reuse=reuse): alpha = tf.get_variable('alpha', [], dtype=tf.float32, initializer=tf.constant_initializer(0.0...
88589612442a73ceab165ae93035c1c0d711b55d
59,569
def javascript(filename, type='text/javascript'): """A simple shortcut to render a ``script`` tag to a static javascript file""" if '?' in filename and len(filename.split('?')) is 2: filename, params = filename.split('?') return '<script type="%s" src="%s?%s"></script>' % ( type, sta...
dbb8eef4adfeca91afe328dfe414d894bed68b39
59,570
def get_hip_file_path(filepath, is_caffe2 = False): """ this function should be in sync with the hipified script in third-party/hipify_torch/hipify/hipify_python.py unfortunately because it's a normal python (instead of Starlark) we cannot simply import from there The general rule of converting...
13dd969dab7762285acf00b6ac2bc1a3463b5288
59,571
from .query_parser import parse_query from . import extra_functions import inspect def run_query(query, data, additionals={}, from_file=False, processes=1, listen=False): """ Run query. This function will utilize global imports if used as a library: >>> import hashlib >>> list(run_query('.a', [{"a": ...
e849daf18ca28eed7d1702cc0a5549b8244cd332
59,572
def likelihood(mprofile, oprofile, ostd, log=True): """ Compute the (log)likelihood function given a measured concentration profile (with known measurement error) and predicted profile(s). Parameters ---------- mprofile : 1-d or n-d array_like the modelled concentration prof...
d085548f942795bbbb6ab284edcfe764e47e07ac
59,574
def renumber(): """ Renumber units and options throughout the current document. Units must be numbered consecutively and options must be numbered starting at 0 within each unit. """ print 'edit::renumber:' filename = session.filename return BookManager.renumber_units(filename)
0e8a0c01cbc4e650882629d9ffba4e63f992779c
59,575
def to_py_type(val): """Convert numpy val to python primitive equivalent. Ex: Given: val = np.array([True, False]) Returns: [True, False] Given: val = np.array(32, dtype=np.int) Returns 32 """ if not isinstance(val, (_np.ndarray, _np.generic)): return val # val is np.ndarray o...
9e3fbfde3b63e036d31e179ca65b9627c115f9be
59,576
def get_consultants(): """Get all users who are consultants""" return (User.query.filter_by(is_consultant=True) .order_by(User.username))
e2e294b644fddcf60fac7069971b016b5c4d19a1
59,577
def regulon_weight_assignment(regulator, expr, filtered_regulon): """ Assigns probability and weights for regulator - target interactions Args: regulator (str): Regulator to expand interaction network expr (:obj: `pandas DataFrame`) : pandas DataFrame containing scaled expression data of ...
188a0653ca6dcacc42c11541e172c311d2f0128a
59,578
import requests def update_blacklist(): """Check for Blacklist update and load them into db.""" blacklist_url = config.postprocess.get('blacklist_url') if blacklist_url: response = requests.get(blacklist_url) lines = response.text.splitlines() blacklists = [] for line in l...
621fa727d9372bbe9c6d001ffc32174081853572
59,579
import fromage.utils.mol as mol_init def per_select(self, labels, old_pos=False): """ Select a molecule out of a Mol in a periodic system. Parameters ---------- labels : int or list of ints The number of the atoms from which the molecules are generated old_pos : bool Option to...
d818e803b41a85fc501aac1fa0f5e0fea8596e5f
59,580
def readThermoEntry(entry, Tmin=0, Tint=0, Tmax=0): """ Read a thermodynamics `entry` for one species in a Chemkin file. Returns the label of the species and the thermodynamics model as a :class:`NASA` object. Format specification at http://www2.galcit.caltech.edu/EDL/public/formats/chemkin.htm...
ca6caa7e39e62d18c6543bb5bf7f539bdd43bcae
59,581
from typing import Optional from typing import List def preview_card( box: str, name: str, image: str, title: Optional[str] = None, items: Optional[List[Component]] = None, caption: Optional[str] = None, label: Optional[str] = None, commands: Optional[Li...
04fe247074f4d46ebe2d97fea17cd6855a64a9c6
59,582
from typing import Iterable def iterable_to_cursor(iterable: Iterable) -> CursorFunc: """Get a cursor function from an iterable. """ iterator = iterable_to_iterator(iterable) return iterator_to_cursor(iterator)
24f3f2361c4e1a3371d4b87289fbfb3a88dfb356
59,584
def range(*args): """ range([start], end [,step]) nd version of range, where each arg can be a vector of the same length Parameters: [start] (vector): the start """ # if passed in scalars call the built-in range if not isinstance(args[0], (list, tuple, np.ndarray)): return...
0c4172a243acf75e8ac3e0421b142ce9ff9bf4c5
59,585
def max_key(d, fn=identity): """Find the maximum value in a dictionary and return the associated key. If we want to compare values using something other than their numeric values, we can specify a function. For example, with a dict mapping strings to strings, fn=len would return the key with the longest...
42e017fc3e58acb659dec8f0c854ca7c9860f94f
59,586
def rectangle2(c, w, h, angle=0, center=True): """ create rotated rectangle for input into PIL ImageDraw.polygon to make a rectangle polygon mask Rectagle is created and rotated with center at zero, and then translated to center position accepts centers Default : center options for...
268726fbce3b0c70190e8f962927cb9444c9689d
59,587
import requests import json def duckduckgo(search, appName=""): """Gives instant answers from DuckDuckGo (https://duckduckgo.com/). Keyword arguments: search -- <str>; what you are searching for (case sensitive) appName -- <str>; the name of your app Return value: { "...
7bb2958986b0e1b0219e7d1a63e475ff840f0136
59,588
def init_dataset(cfg): """ Use path in cfg to init a dataset the dataset should be the following format - Each Image should be named in (pid)_c(camid)_(iid).jpg where pid is the person id, camid is camera id, iid is image id(u...
d12eb0e566eb3294c54189cba7bf2a6c56d551a5
59,589
def set_workflow_for_object(obj, workflow): """Sets the passed workflow to the passed object. If the object has already the given workflow nothing happens. Otherwise the object gets the passed workflow and the state is set to the workflow's initial state. **Parameters:** workflow The ...
3a1fce7a2cb203a6b07e9d15b1f242deddd7be25
59,590
def Max(*args): """Maximum over a set of real or integer terms""" return get_env().formula_manager.Max(*args)
74df4b162aff7ffdda17cecd579c283fa803d164
59,592
def set_bmask_name(*args): """set_bmask_name(enum_t id, bmask_t bmask, char name) -> bool""" return _idaapi.set_bmask_name(*args)
61870c3de5cb47993a6ec00b1f50587b429f3940
59,594
def install_chrome_driver(context): """ Method to install webdriver for chrome """ options = webdriver.ChromeOptions() options.add_argument("--no-sandbox") options.add_argument("--disable-setuid-sandbox") options.add_argument("--disable-dev-shm-usage") options.add_argument("--disable-ext...
1d5b3f794ead6807c45497f98cfbfce9f2ce4341
59,595
def split(y, top_db=60, ref=np.max, frame_length=2048, hop_length=512): """ codes from https://github.com/librosa/librosa use this code fragments instead of importing librosa package, because of our server has a problem with importing librosa. """ non_silent = _signal_to_frame_nonsilent(y, ...
0b367e16c09219c014fa9d997056fceb03347986
59,596
def to_wordlist_linguaview_xml(sentence): """ Get wordlist in LinguaView XML representation. :return: """ word_list = etree.Element("wordlist") word_list.attrib["length"] = str(len(sentence)) for i in sentence: tok = etree.Element("tok") tok.attrib["id"] = str(i.id) t...
082c5d366e08579ef8c362c0a72cf0d88df51896
59,597
def binary_to_decimal(number): """ Calculates the decimal of the given binary number. :param number: decimal number in string or integer format :return integer of the equivalent decimal number """ decimal = [] number = list(str(number)[::-1]) for i in range(len(number)): ...
6d615b9bc5a50cc9d2a970fa77c989fa95d0d77e
59,599
def get_model_names(model='all'): """ Returns all available model names as a list of strings. Parameters ---------- models: str OPTIONAL. Default value is 'all' in which case all keys in default_models are returned. If 'mixed' is passed, only the MixedFluid model names are return...
9ebf63306e298877c64fc80ce82e54381e005764
59,600
from operator import add from typing import Concatenate def compile_bigrus_attention(shape, n_hidden_layers, hidden_units_size, dropout_rate, word_dropout_rate, lr, mode): """ Compiles a BiGRU based on the given parameters :param mode: Depending on your choice : ['Single Task', 'Multi Task-1', 'Multi Task...
e3e8b1ca514e1dbb6c93e5f933aa19d8c9f48953
59,601
def get_dom_attr_value(dom, tag_name, attr_name): """ Return value of a tag's attribute from dom (XML file). Arguments: tag_name -- name of dom tag in which the attribute is found. attr_name -- name of dom attribute for which the value should be returned. """ tag=dom.getElementsByTag...
26f31fd7db526bb5503b7ce156b19a99705041d1
59,602
def render_xml(request, template, context=None, **kwargs): """Safely renders xml, stripping out nasty control characters.""" if context is None: context = {} rendered = render_xml_to_string(request, template, context) if 'content_type' not in kwargs: kwargs['content_type'] = 'text/xml' ...
5212ce2a41bb5a968d85f1e70d4b200866d46897
59,603
from pathlib import Path def read_camera_intrinsics(settings_path: Path) -> CameraIntrinsics: """ Read the camera intrinsics from file :param settings_path: The path to the camera settings file, output by the NDDS exporter :return: """ camera_settings = read_json(settings_path) return Came...
3a4745818c71357e6fe2d1f207f40a2ad42b0321
59,604
def share_server_get(context, id, session=None): """Get share server DB record by ID.""" return IMPL.share_server_get(context, id, session=session)
e7ba5854d72687c1c791bc2ddcd1edd1ca8086a4
59,605
def get_profile_for_plotting(equilibrium_list): """ List of symmetric equilibrium :param equilibrium_list: :return: Representative profile. """ selected_profile = None sample_team = 0 strategy_of_interest = simmodel.SIMPLE_INFLATE_STRATEGY for profile in equilibrium_list: ...
f07547821c5e92e7596d5474da6b736b29b3c306
59,606
def _hermite_moment_nonlinear(u,mu,sigma,mu3,mu4,fisher=True): """ Hermite moment models for nonlinear responses """ if fisher: mu4 = mu4 + 3 if mu4 > 3 : h3 = mu3/6 h4 = (mu4-3)/24 c4 = (np.sqrt(1+36*h4)-1)/18 c3 = h3/(1+6*c4) k = 1/(np.sqrt(1+2*c3...
c93b116c23066a21f68ac47ac051410540259dd4
59,607
def fmeasure(confusion_matrix): """Compute the f-measure of the linkage. The f-measure is calculated as: 2 * (precision * recall) / (precision + recall). Parameter Description: confusion_matrix : The matrix with TP, FP, FN, TN values. The method returns a float value. """ ...
c148f52952d5d5a71c6880dc5777e83eaac1f5f8
59,608
def probability_of_category_A(stimulus_i, category_a_exemplars, category_b_exemplars, w, c, r, alpha, b): """ Function that calculates the probability of stimulus_i belonging to category A. Note that this assumes there are only two categories in total, which is typical of categorization experiments (equatio...
33eb4c7b105f310e43d2b55ae0221e01e56b9390
59,609
def role_list(auth=None, **kwargs): """ List roles CLI Example: .. code-block:: bash salt '*' keystoneng.role_list salt '*' keystoneng.role_list domain_id=b62e76fbeeff4e8fb77073f591cf211e """ cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return clou...
90bfa586af63155eb298138eb9007df38aaefd77
59,610
def Inv_UpSample(name, x, scale=False, reverse=False): """ Upsample the given inputs by factor 2x2, but will decrease the channel num by factor of 4, such that the overall number of units remains unchanged :param name: name scope :param x: given inputs, [NHWC] :param scale: if true, scale the sp...
472267e1be3c596f5c4dffb49b3ed66f21f19ad5
59,611
def collide(Aleft, Aright, Bleft, Bright): """ optimised for speed. """ # quickest rejections first; if Aright < Bleft: return(False) if Aleft > Bright: return(False) if Aleft == Bleft: return(1) # I have to cheat here otherwise it returns 0 which will evaluate as False; ...
d66afddce5f7a464446d598d948cc74c0d97a70a
59,612
def wendlingModel_2(y, P, h = 1./512, u = np.zeros(1), couplIntra = 0, couplInter = 0 ): """ Modified Wendling's neural mass model ODEs y: last state P: model parameters h: step (1/Fs) u: stimulation input - 2 elements u[0] voltage deflection to all cells. u[1] sums the stimulus to the model input ...
79c409da2692f21c3ccb0e081d25926d0de30b7b
59,613
def construct_graphql_query(dict_object, queryDict=None, key="query"): """ {"name": "wallet", "key": "username", "fields": ["owner", "upcoming_earnings", {'name': "transactions", 'key': None, "fields": ["display", "type"] }]} :returns query{ wallet(username:""){ ...
27af54cc6f10e57cc9e6d98dc0816f51d82dd103
59,614
import shutil def delete_directory(path): """ Deletes a ticket attachments directory from disk """ path = '{}/{}'.format(settings.MEDIA_ROOT, path) try: shutil.rmtree(path) return path except: return False
42b06b7eb563cfea86409afd85df2964c69dad15
59,615
def sort_SMILES_list_by_MW(SMILES_list): """ sort smiles by molecular weight """ if len(SMILES_list) == 0: return [-1] mw_list = [calc_MW_from_SMILES_list(i) for i in SMILES_list] dataset = (list(zip(mw_list, SMILES_list))) dataset.sort(key=lambda x: x[0]) mw_list, SMILES_list =...
bc21a370c767b849978882882bdd0641b0f702e2
59,616
from typing import Tuple def fetch_dbt_data(dbt: DbtCloud) -> Tuple[dict, dict]: """call dbt api for all latest runs and jobs Args: dbt (DbtCloud): dbt cloud api instance Returns: Tuple[dict, dict]: dict of both runs and jobs """ all_runs = get_all_runs(dbt) all_jobs = get_al...
a832fdcc7083e106da6f92dbabb71906cb64968d
59,617
from typing import List import ray import random def run_wrk_on_all_nodes(trial_length: str, num_connections: int, http_host: str, http_port: str, all_endpoints: List[str] = None): """ Use ray task to run one w...
48c95de8ec87d789b984925a81914db28167fe98
59,618
def plaintext(): """Test 6: Plaintext""" return b"Hello, World!", {"Content-Type": "text/plain"}
8005ee608a45956d5aa9fc4edf34c9ee3c8605d6
59,619
def get_simbad_names(name, verbose=False): """ Get list of alternate names from Simbad Parameters ---------- name : str Name to resolve verbose : bool Verbosity flag Returns ------- List of names """ t = Simbad.query_objectids(name) if t is not None and...
6d0518f75d21891792b9820f9654e73261d3b384
59,620
def logout_view(request): """Logging off the user :param request: Django's HTTP Request object :return: Redirect to homepage """ logout(request) return redirect("homepage")
ad11a78c918f89b199f62f371fa40be2b5c9d153
59,621
import re def generate_stencil(pcb_footprints, config): # type: (list, Config) -> dict """ Generate BOM from pcb layout. :param pcb_footprints: list of footprints on the pcb :param config: Config object :param extra_data: Extra fields data :return: dict of BOM tables (qty, value, footprint...
493386d3a4bcb8b4184bd027d9e43da01b4954e3
59,623
def inspect_calibration_surface(df, param_zf, microns_per_pixel): """ To run: dict_fit_plane, fig_xy, fig_xyz, fig_plane = correct.inspect_calibration_surface(df, param_zf, microns_per_pixel) :param df: :param param_zf: :param microns_per_pixel: :return: """ if 'x' not in df.column...
90aec909eb00aa06d879e34fbf72bb2e19c38fa8
59,624
def check_inside_points(points, cur_boxes): """ points: [num, n] cur_boxes: [m 7] return: [num, m] """ # first cast points to second format points = points.copy() cur_boxes = cur_boxes.copy() points_xyz = points[:, :3] points_xyz = points_xyz[:, [0, 2, 1]] cur_boxes = cur_bo...
d458c067bbf87e8b5f2a53e7284f548db093ee60
59,626
def data_route(): """`/data/` endpoint handler""" filename = get_filename(request) path = request.args.get("path") selection = request.args.get("selection") format_arg = request.args.get("format") flatten = parse_bool_arg(request.args.get("flatten"), fallback=False) with h5py.File(filename,...
8f9304d0efc045660dead59ef983e2b2ab6ca801
59,627
def drop_voxels_with_mean_negative_amplitudes(df): """drop all voxels that have an average negative amplitude (across stimuli) """ groupby_col = ['voxel'] if 'indicator' in df.columns: groupby_col += ['indicator'] try: # in this case, we have the full dataframe (with each bootstrap ...
2799c866b411ff0e63cdcc4b28adf3bde9595f4e
59,628
def categorical_focal_ignoring_last_label(alpha=0.25,gamma=2): """ Focal loss implementation Variables: weights: numpy array of shape (C,) where C is the number of classes Usage: weights = np.array([0.5,2,10]) # Class one at 0.5, class 2 twice the normal weights, class 3 10x. ...
bf93ffb8dbadee85756c8e9204e809917b409f94
59,629
def split_peaks(prot_arr, pr, skp=0): """ split peaks in n samples giving skp fractions of window returns 'right_bases': array([32]), 'left_bases': array([7]) """ peaks = list(st.peak_picking(prot_arr)) left_bases = peaks[1]["left_bases"] right_bases = peaks[1]["right_bases"] fr_peak...
47dc06e53d46e146e42116274473f46e0c2f0dac
59,630
from typing import List def download_media( client: pyrogram.client.client.Client, chat_id: str, last_read_message_id: int, media_types: List[str], ) -> int: """Download media from Telegram. Parameters ---------- client: pyrogram.client.client.Client Client to interact with Te...
1171043981ac8fb4e25dfbaa5c74c1f72d728d1f
59,631
import re def follow_directions(starting_point, starting_orientation, *directions): """Given a starting point, starting orientation and a list of directions of the form DN, where D is R (right) or L (left) and N is an integer, return the ending point and orientation.""" point = starting_point ...
5d276bd25a317e1051c56596df7e165a6dc39593
59,632
from . import routes def create_app(): """ create and return the flask application """ app = Flask(__name__) # pylint: disable=import-outside-toplevel app.register_blueprint(routes.bp) return app
d751ba54c1ad4f60abb0a452aad7e428ac2a7bb6
59,633
from .pb import test_pb2 from .pb import test_pb2_grpc import random import string def test_mock_stream_stream_call(import_path): """Test Bidirectional Streaming gRpc Call""" class TestServicer(test_pb2_grpc.GRPCTestServicer): _server_id = random.randint(2, 2 ** 10) def BidirectionalStreami...
ab10c22a2b186a9defd551550933ef17923640d0
59,634
def flip_y(prob=0.8): """ Construct a transformation randomly containing X/Y flips (or not). Args flip_x_chance: The chance that the result will contain a flip along the X axis. flip_y_chance: The chance that the result will contain a flip along the Y axis. Returns a homogeneous...
381ed2efde5e7e8e6d44adeea3a2006daa539222
59,635
def column_stats(collection, column, stats_type): """Aggregates over a given property of the objects in a collection, calculating the sum, min, max, mean, sample standard deviation, sample variance, total standard deviation and total variance of the selected property. Args: collection (FeatureColl...
c4792043d44b0f6d23c843d0df6dde9603c1d426
59,636
def EGCD(a, b): """ Extended Euclidean algorithm computes common divisor of integers a and b. a * x + b * y = gcd(a, b) returns gcd, x, y or gcd, y, x. Sorry, I can't remember """ if a == 0: return (b, 0, 1) else: b_div_a, b_mod_a = divmod(b, a) ...
81a9365bfe2b82f0856489710afb7186d1fcf803
59,638
def _get_module(module: Module, name: str) -> Module: """Recursively get a sub-module from a module. Args: module: A `torch.nn.Module`. name: The name of the submodule to return, in the form of a period-delinated string: `sub_module.subsub_module.[...].leaf_module`. Returns: ...
913f9920c9079aa2d746d8e61469611181664f9f
59,639
import html def description_card(): """ :return: A Div containing dashboard title & descriptions for tab 1. """ return html.Div( id="description-card", children = [ html.H3("Welcome to CZviz"), dcc.Markdown('''This app allows you to explore the full dataset and ...
5a2a2d0c042fa408c10bc0e0f86f0ec63a06828e
59,641
import csv def np_float_array_from_file(data_file, delimiter=" ", header=False, gather_hist=False): """ Adds to the basic np.loadtxt by performing data checks. @param data_file: file expected to have space-separated values, with the same number of entries per row @param delimiter: default is a space-s...
0a48de03974f425677425d61e89433011387b5c0
59,642
def _evaluate(p_eval_step, params, eval_batch): """Computes evaluation metrics. Args: p_eval_step: Parallelized evaluation step computation. params: Model state. eval_batch: Batch of evaluation examples. Returns: Raw model predictions and metrics. """ n_devices_per_host = jax.l...
11d17ec8bedcd3cbfacf7e6cc12fef5a4f95221c
59,643
def _assemble_frequencies(animal_obj, start_time, end_time): """ Converts the coordinates of the animal trajectory into frequency data over the grid. Gathers the frequency data for approximating the heatmap representing the amount of time an animal spent in each location over a specified time interval. ...
1e4fe463e49bafb91f7e95088c12c3580313d66d
59,644
def view_profile(request, username=None): """ Display profile info, such as snippets, tags, and followed users """ #Set current user and check if it's my profile if username is None or username == request.user.username: user = request.user my_profile = True else: user = get_obje...
ec2e4b296dc01bf46e59983af84d658b6e058536
59,647
def filter_attr(the_dict, attr_names): """ Only return the item that in the attr_names list :param the_dict: :param attr_names: comma separated names :return: dict """ if isinstance(the_dict, dict): attrs = attr_names.split(',') return dict((k, v) for k, v in the_dict.items...
1ca5ad38af808c6a533c3abb22ce7cc26d5f82f2
59,648
def _GetFlagMetavar(flag, metavar=None, name=None, markdown=False): """Returns a usage-separator + metavar for flag.""" if metavar is None: metavar = flag.metavar or flag.dest.upper() separator = '=' if name and name.startswith('--') else ' ' if isinstance(flag.type, arg_parsers.ArgList): metavar = flag...
e8fef13fa12ea47b41ec5328dba7efb56991e9e9
59,649
def getTempDirectory(rootDir=None): """ returns a temporary directory that must be manually deleted """ if rootDir is None: return tempfile.mkdtemp() else: while True: rootDir = os.path.join(rootDir, "tmp_" + getRandomAlphaNumericString()) if not os.path.exist...
d29ff7d01fd24e5281f33d9d94b5d413c52cf47b
59,650