content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import logging def level_from_verbosity(verbosity=3, maxlevel=logging.CRITICAL): """Return the logging level corresponding to the given verbosity.""" return max(1, # 0 disables it, so we use the next lowest. min(maxlevel, maxlevel - verbosity * 10))
45064e04e27fa170257f37faa56de02ea544f811
3,598,592
from typing import Type def prepare_datasets(configs: ConfigLoader, dataset_class: Type[AbsDatasetReader]): """ The Dataset provider method for train, test and dev datasets :param configs: an instance of ConfigLoader which has been loaded with a yaml config file :param dataset_class: the classname of ...
ebc558bc5ee8366b0aedbad14ebe00955c755596
3,598,594
def screenshot(window_title): """ Take a screenshot of the window if it exists. Returns: Image: Image data for the screenshot taken. bool: False if no window exists. """ hwnd = get_hwnd(window_title) return ImageGrab.grab(win32gui.GetWindowRect(hwnd)) if hwnd else False
6e56ef96767c3327dc3c349e34bb4fe38a3ce24f
3,598,595
def procrustes_analysis(shape, example_shape, is_scaling_allowed=True): """ Ordinary Procrustes Analysis of a pair of shapes. Calculate a linear transformation which makes the points of one shape conform to the points in another shape in the best way. Return (rotation, scale, translation) tuple. ...
d9bd024e2fbc5b09407730a44d6ee3a894d5d4b0
3,598,596
def _get_rd_rate(a, b, s): """Gives a random comparison score a (float): local score of video a b (float): local score of video b s (float): scaling parameter of user Returns: (float): random comparison score """ class my_pdf(st.rv_continuous): def _pdf(self, r): ...
71202963b65e0406dbe1c8ae98d3b9664a9328c0
3,598,597
def irregular( subdivisions=2, radius=0.0625, factor=0.1, seed=None, ): """Generates a mesh from an icosphere, by applying some randomly parametrized transformations. Args: subdivisions: subdivisions parameter of the icosphere radius: the mesh always fits within a sphere of this radius. fac...
ee65044aaddb7be67c4300a83b1d206675fd351b
3,598,599
def get_app_by_id(app_id): """ 查询业务信息 :param app_id :return dict: {host_info} """ if app_id: cc_result = bk.cc.get_app_by_id(app_id=app_id) if cc_result: return cc_result[0] return {}
5c4303110b62b5606d13ea5aeb4a835eb7865bef
3,598,600
def add_tag(row, tag_key, capitalize=False): """ Looks up the correct tag based on the row, and appends it to the list of tags :param row: :param tag_key: the tag key (string of tag) to add :param capitalize: True to initial cap the tag key :return: the updated row """ if not tag_key: ...
f8a84d4eeb82f516a301553528c3f66741879a7a
3,598,601
def get_host_fsids(node_metadata): """ Return all the cluster FSIDs found for each socket in a host """ all_fsids = [] for socket_metadata in node_metadata['ceph']['sockets'].values(): config = socket_metadata.get('config', {}) if not config: continue fsid = confi...
543cf63d563fe5993dae343cc662084f51147162
3,598,602
def form_hall_insert(request, cinema_id): """ Returns Hall's insert form :param request: :param cinema_id: linked Hall's ID :return: web-page for creating new entity """ if request.user.is_staff is True: if request.method == "POST": form = HallForm(request.POST) ...
f20aaa64e1e5ae2848caa8eef06a1d617253dece
3,598,603
from typing import Any from typing import Optional def plot_psd( df: pd.DataFrame, y_col: str = None, time_col: str = None, nfft: int = None, fs: int = 1, min_period: int = 0, max_period: int = np.inf, plot_time: bool = False, title: str = None, show: bool = True, **kwargs:...
5d59ad17a9e2ba461cda1291acf2de8088c8b105
3,598,605
import typing def _aggregate_config_values(config_values: typing.List[ConfigValue]) -> dict: """ Returns a (sorted) :param config_values: :type config_values: :return: :rtype: """ _keys: defaultdict = _nested_default_dict() _sorted_values = sorted(config_values, key=lambda x: x.na...
e44793653bd8e294aa006d1772541907bb4ea12d
3,598,606
def full_fft(): """FFT of waveform where independent axis is evenly spaced and a power of 2.""" wobj, fsample, finc = fft_wave() # Compute reference solution npoints = len(wobj.indep_vector) ret_indep_vector = barange(-fsample / 2.0, +fsample / 2.0, finc) ret_dep_vector = fft(wobj.dep_vector, np...
925c2f4a8d29248069b0e60a8f5a7d7416d9f31e
3,598,609
def piecewise_linear_mapping(x, knots): """ A piecewise linear mapping function, defined by the boundary points of each segment. For example, a function consisting of 3 segments is defined by 4 points. The x-coordinate of each point need to be greater that the x-coordinate of the previous point, the y-c...
0da3164fd13be15626e1b1d3a9b81d1bb5fc0a85
3,598,610
def specific_heat_capacity_moist_air(spec_hum): """ Calculate the specific heat capacity of moist air. Parameters ---------- spec_hum : numeric Specific humidity (kg kg-1). Returns ------- spec_heat_cap_moist_air : numeric Specific heat capacity of moist air (J kg-1 K-1...
c464c572cfd483c22934f8934f81f8524ae924ee
3,598,612
import warnings def resample(image, voxel_spacing, new_spacing=None, new_shape=None, order=1): """ Resamples the scan according to the either new spacing or new shape When new_spacing and new_shape are provided, new_shape has the priority use order = 1 for nearest neighbor and order = 3 for cubic ...
a9b3585874626cbc8bcc34d76e41f03efc7f5eb5
3,598,614
def parse_kde(args, hough_transform: HoughTransform): """Get vanishing points using the KDE method""" vps, kdes = hough_transform.find_vps_kdes( weight_threshold=args.weight_threshold, filter_threshold=args.filter_threshold, kde_width=args.kde_width, kde_height=args.kde_height, ...
81f5050c733b6a4d695b95dfa8fc0fedb8eafdd0
3,598,615
def read_formatted_file(file, listmat=None, listmf=None, listmt=None): """Read formatted file and return either Errorr, Gendf or Endf6 instance according to file format. Returns ------- `Errorr` or `Gendf` or `Endf6` """ ftype = get_file_format(file) if ftype is "errorr": re...
d5b0ad84ef7bf3490b3bacbf8225548eecbf8922
3,598,616
def get_strains(known_origin=False, issues=False): """ Returns a list of strains; Represents all strains Args: known_origin: Returns only strains with a known origin issues: Return only strains without issues """ ref_strain_list = Strain.query.filter(Strain.isotype_ref_strain == True...
4c4e2f699f68726da574861c9fb5db1ecb3503e4
3,598,617
def nested_dict_traverse(path, d): """Uses path to traverse a nested dictionary and returns the value at the end of the path. Assumes path is valid, will return KeyError if it is not. Warning: if key is in multiple nest levels, this will only return one of those values.""" val = d for p in path: val...
1f7e4744585ae134ab1f2eface9284756526ed65
3,598,618
def compute_recommendation_cdf(table_offers): """Approach 1: compute the salary recommendation based on the CDF, it was designed to be called in a groupby. Args: table_offers: pandas Dataframe containing every offers of a single job group. Returns: a list of namedtuple containi...
af700938006fbde18a0acda687dcb231addd9afc
3,598,620
import torch def box_planar_dir(box: torch.Tensor, eps: float = 1e-4) -> torch.Tensor: """ Finds the unit vector n which is perpendicular to each plane in the box and points towards the inside of the box. The planes are defined by `_box_planes`. Since the shape is convex, we define the interior to...
5cdb68dbf93f1b0bf91e0467a101198f86e1fcdf
3,598,621
from qharv.reel import ascii_out def get_jk_kvecs(fout, header = 'kSpace coefficient groups', trailer = 'QMCHamiltonian::addOperator'): """ parse QMCPACK output for kSpace Jastrow kvecs """ mm = ascii_out.read(fout) text = ascii_out.block_text(mm, header, trailer) data = [] for line in text.split('\...
c0bbaff7e31754bab904d509d4c51ee1a3eb7a46
3,598,622
import torch def squeeze(x, axis=None): """ Remove single-dimensional entries from the shape of a tensor. Parameters: ----------- x : ht.DNDarray Input data. axis : None or int or tuple of ints, optional Selects a subset of the single-dimensional entries in the shape. ...
a80c56b95e12f0cc43e3a27df509b4059f4da14d
3,598,624
import importlib def possible_words( words=None, include=None, only=False, require=None, match_count=False, exclude=None, length=None, at_least=False, mask=None, ): """Return words from that meet the filter criteria. Parameters ---------- words : [str], optional ...
1f2f6fbcfc67464d4f194d43a2f39957075ea4d7
3,598,629
def is_file_download_finish(file_name): """ 判断文件是否下载完 判断文件后缀为xltd即未下载完 :param file_name: :return: """ return not file_name.endswith('.xltd')
b782d358359c03f50efb6d791bd4403a4190aac0
3,598,630
def delete_vip_request(vip_request_ids, keep_ip='0'): """Delete vip request.""" for vip_request_id in vip_request_ids: try: vip = get_vip_request_by_id(vip_request_id) bypass_ip = True if keep_ip == '1' else False vip.delete_v3(bypass_ipv4=bypass_ip, bypass_ipv6=bypa...
2b5d1b699b1631ed664f605c74c041d8e7145633
3,598,631
def survey(survey_name): """Render the survey page with the requested survey name to the client""" return render_template('survey.html', survey_name=survey_name)
b827350bb7d78087589ebdcab0af532171fc9fbe
3,598,633
def normalize2(numbers): """Normalize list of numbers, caching names""" thr = Config.threshold fact = Config.factor norm = [] for num in numbers: if num > thr: num /= fact norm.append(num) return norm
fb0c8c8843e760196dcfde1ea5e6dfcd4fe1ab53
3,598,634
def check_antonym_suffix_wrapper(row): """Wrapper for check_antonym_is_token_suffix function""" return check_antonym_is_token_suffix(str(row.token), str(row.pos))
90d311da4c480301590ec6fc9612501d8c9d3758
3,598,635
def sample_par_from_list(probs, size=1, replace=False): """ Take a parameter or multiple parameters, with or without replacement, at random from a list of possible options """ idx = np.arange(len(probs)) # Ensure probabilities add up to 1 probs = np.array(probs) probs /= probs.s...
0facee157a52edf4ca416a416790224d09f96a10
3,598,636
def fix_zip5(zip5): """add leading zeros if they have been stripped by the scorecard db""" if len(zip5) == 4: return "0{0}".format(zip5) if len(zip5) == 3: return "00{0}".format(zip5) else: return zip5[:5]
ff781562c97c297dde7a05740436b5d668d7fbb8
3,598,637
from typing import Any import scipy def problem(request: Any) -> Problem: """Simulate a fixed effect problem against which algorithms can be compared.""" covariates, scales, levels, singletons = request.param # simulate the data state = np.random.RandomState(hash(tuple(request.param)) % 2**32) id...
8b0466ffe5e6e96b5c4e5d11addcc24a29a1eb28
3,598,638
def create_qdisc_root(interface): """ Creates a root htb qdisc in traffic control for a given interface """ return shell.execute_suppressed('{} qdisc add dev {} root handle 1:0 htb'.format(BIN_TC, interface)) == 0
02dadebb82d2806151f58778bb377c6471582d58
3,598,639
def constant_case(s: str): """ Transform into upper case string with an underscore between words. Parameters ---------- s : str Original string to transform. Returns ------- Transformed string. """ return _change_case(s, '_', str.upper)
3ea3f4c5e9570da9cdd1359b9dfaf80cef266b5b
3,598,640
def eigenvectors_from_displacements(disp, masses): """ Calculate the eigenvectors from the atomic displacements """ nphonons, natoms, ndirections = disp.shape sqrt_masses = np.sqrt(masses) return np.einsum("nax,a->nax", disp, sqrt_masses)
15bf112d22e705de8b8064ca297cb1cad612b6f9
3,598,641
def count_bit_differences(s1, s2): """number of positions at which the corresponding bits are different""" assert len(s1) == len(s2), 'len(s1) ({}) != len(s2) ({})'.format(len(s1), len(s2)) return (~(~s1 ^ s2)).count(True)
618a469cf6be2386b13950813102a18ed73ba68d
3,598,642
def round_preserving_sum(iterable): """Rounds an iterable of floats while retaining the original summed value. Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and description of each parameter is optional, but should be included if not o...
5da1dd917ce7b69938e255d44ae729b1d3755ede
3,598,643
def train_and_gen_result(clf, X, y, X_test, use_proba=False, save_url=None, n_splits=1, random_state=None): """ train and generate result with specific clf Args: clf: classifier X: vectorized data y: target X_test: test data use_proba: predict probabilities of labels ins...
8c07355caf76f02e4d2e0cb268c391f7cb1faa5e
3,598,644
import tqdm def calc_accessibility_load(tracts, pois, G, weight='length', func=acc_cumulative_gaussian, k=5, random_seed=None,func_kws={}, pois_weight_column=None, tracts_weight_column=None, ...
6b5ef37858296eac85161f80c0020a0b5c9d3af2
3,598,646
def flag_callback(): """JS callback for the flagging button Returns ------- code : :obj:`str` """ code = """ //f_sources: Flagged data source //n_ax: number of figures available //uf_sources: unflagged data source for (let n=1; n<=n_ax; n++){ for (l...
6fdc9abbfe103bdd40ce02e009f9c59be7b32c9f
3,598,647
def export_cropobject_graph(cropobjects, validate=True): """Collects the inlink/outlink CropObject graph and returns it as a list of ``(from, to)`` edges. :param cropobjects: A list of CropObject objects. :param validate: If set, will raise a ValueError if the graph defined by the CropObjects ...
2caf2d70352c275d503a06c3e57c0cb10c9ac9db
3,598,649
import itertools def list_flatten(_l): """Flatten a complex nested list of nested lists into a flat list """ return itertools.chain(*[list_flatten(j) if isinstance(j, list) else [j] for j in _l])
05d1e4018accfe850c07504f123d85949a2ced60
3,598,651
def get_create_indexes_queries(graph_name, backend): """Format all SQlite CREATE INDEXES statements with the name of the RDF graph to insert.""" if backend == "sqlite" or backend == "sqlite-catalog": return [ f"CREATE UNIQUE INDEX IF NOT EXISTS {graph_name}_spo_index ON {graph_name} (subject...
445a13ee13f7ae7dc3bd8d260ebf7deed6f0709c
3,598,653
def generateChatbotNameSentences(): """Returns generated lines with chatbot's name.""" contexts = [] answers = [] for length in range(1, MAX_TOKENS + 1): context = "" for _ in range(length): context += "{} ".format(CHATBOT_NAME) contexts.append(context) an...
c4d212779d67654a883943d16062673b25eb1c10
3,598,655
def handle_2_columns(datalist, return_list = False): """This function has the intent of changing: ('A8', '2') => ('A8', '', '2') ('A8', '', '2') => ('A8', '', '2') [('E2', '5')] => [('E2', '', '5')] [('G1', '', '5')] => [('G1', '', '5')] with the purpose of handling 2 column csv part file inputs...
57a9c1dbad9484a3513cebab68069983d3ae9f35
3,598,656
def singledispatch_on(idx): """Helper to dispatch on any argument, not only the first one.""" # It works by wrapping the function to include the relevant # argument as first argument as well. def decorator(func): @ft.wraps(func) def wrapper(*args, **kwargs): dispatch_obj = a...
7f7a149458c71c81a001a4e0b0c0ec6e8703b6ef
3,598,657
def get_auc(fprs, tprs): """Computes AUC under a ROC curve""" sorted_fprs, sorted_tprs = zip(*sorted(zip(*(fprs, tprs)))) sorted_fprs = list(sorted_fprs) sorted_tprs = list(sorted_tprs) if sorted_fprs[-1] != 1.0: sorted_fprs.append(1.0) sorted_tprs.append(sorted_tprs[-1]) return ...
6953047b35b3205bbc237d6f67e34f0b7650fbac
3,598,658
import time def so_special(treatment_feature, extra_filter): """helper""" if extra_filter: qs1 = SampledStackOverflowPost.objects.filter( has_wiki_link=True, sample_num__in=[0,1,2], has_c_wiki_link=True).order_by('uid') qs2 = SampledStackOverflowPost.objects.filter( has...
689f843c1941528e5ec6c5297fed8d9b69924ce8
3,598,659
def stellarmass_from_halomass(log_Mhalo,z=0): """ Stellar mass from Halo Mass from Moster+2013 https://doi.org/10.1093/mnras/sts261 Args: log_Mhalo (float): log_10 halo mass in solar mass units. z (float, optional): halo redshift. Assumed to be 0 by default. Ret...
f7b7e5f6cba5fe452b84274e10f77ea6a7788c84
3,598,660
from typing import List from typing import Dict from typing import Tuple import tqdm def add_data_edges( base_graph: nx.Graph, distributions: List[Dict[str, np.ndarray]], alpha: int, image: np.ndarray, partition: Dict[int, set], params: dict, verbose: float = True, ) -> Tuple[nx.Graph, Lis...
d9ca4e643dfee29b2a426fad74053b73d894bb84
3,598,662
def format_button(recipient_id, button_text, buttons): """ Ref: https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template """ return { "recipient": {"id": recipient_id}, "message": { "attachment": { "type": "template", ...
a05f6d08b87d0897a65b291c539b3cbd883c0799
3,598,663
def calibration_gravity_parameters(signals:NDArray) -> NDArray: """calibration_gravity_parameters. :param signals: :type signals: NDArray :rtype: NDArray """ n = signals.shape[0] # row number of 2D array A = np.zeros((n, 6)) row_unit = np.ones((1, n)) for i in range(n): ...
575d9c78ac68e117ef0f5555985c60eb3c146899
3,598,664
def vis_gauss(u, v, sigma_lm, A=1., i=0., pa=0., l0=0., m0=0.): """ The visibility model of a Gaussian profile, which is inclined to the line of sight with the inclination angle i and position angle pa. The coordinates transformation is consistent with 2017ApJ...839...99P. Parameters ---------...
d8ab15159852ec14f0788405e538f8de5aec096b
3,598,665
import random def meme_rand(): """Generate a random meme.""" img = random.choice(imgs) quote = random.choice(quotes) path = meme.make_meme(img, quote.body, quote.author) return render_template('meme.html', path=path)
06d6ad5f1d61fed82338c04408f1fe7b050bbb9b
3,598,666
def GPA_from_letter_grades(letterGrades): """ Computes a floating point GPA for a student given a list of their letter grades. """ letter2number = {'A':4.0, 'B':3.0, 'C':2.0, 'D':1.0, 'F':0.0} return np.mean([letter2number[letter] for letter in letterGrades if letter != '0'])
bf688457930fe0753bb4f3aefa6ca02497f1ba14
3,598,668
def distribute_first_fillers(places_available, num, num_places): """ Chooses places for a first batch of fillers For a first batch of fillers, places in the second half of the sequence are chosen. This is done to limit the predominance of repeat trials late in the sequence. :param places_available...
c23816e89c9fdf34cdaa5cf6de78fb7485ad6fec
3,598,669
def scenario_to_age_distribution(s): """ scenarios see above, every dict provides the name of the scenario and age mass distribution. here we convert it to the initial values for the ODE solver """ ages = s[1] a = np.zeros((n_days)) for ag in ages: a[ag[0]] = ag[1] return a
6c6253c22722cd92f817227c8e5ee0f050207296
3,598,670
def get_quotation_items_rows(*args, **kwargs): """ 获取列表 :param args: :param kwargs: :return: """ return db_instance.get_rows(QuotationItems, *args, **kwargs)
7719567882a8bd478d227d1490c0f8be624b388c
3,598,671
import requests import json def submit(url, job, headers, inputs=[]): """ Submits a job to the given URL, which can be the ".../jobs" URL or a ".../sites/site_name/" URL If inputs is not empty, the listed input data files are uploaded to the job's working directory, and a "start" command is sent ...
cd4642a86b1dadf48b5a32ff777e0e0e4af17ab7
3,598,672
def conv(in_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=True, batch_norm=True): """Creates a 2D convolutional layer (for downscaling width and height of the input tensor) with an attached optional batch normalization layer. Arguments: in_channels: input ch...
50b0dcc7dde113ab1cce2b7d51d8de9ed82e4354
3,598,674
def prof(d, pres=5e2, desc=False): """Calculate profile (prof) from points (pts). d - Points (pts) dataset (dict). pres - Pressure resolution (float). desc - Descending profile (bool). """ pmin, pmax = np.nanmin(d['p']), np.nanmax(d['p']) phalf_min = pmin - (pmin % pres) phalf_max = pmax + pres - (pmax % pres)...
4427883d325cb9d70504047b7bb951c7e9f9d5dc
3,598,675
import re def remove_line_comment(old_str: str, comment_mode: str): """ 去除行内注释 :param old_str: 原字符串 :param comment_mode: 注释符号 :return: """ temp_str = new_str = old_str if comment_mode not in old_str: return new_str for regex in ["\".+\"", "\'.+\'"]: for s in re.fin...
b5b53f909bf04da8688b7ef54d56815dfadbf993
3,598,676
def CalculateSLOGPVSA(mol, bins=None): """ ################################################################# MOE-type descriptors using LogP contributions and surface area contributions. logpBins=[-0.4,-0.2,0,0.1,0.15,0.2,0.25,0.3,0.4,0.5,0.6] You can specify your own bins to compute some des...
27533151c58cd9aeaed498589226c36b7c5384c5
3,598,678
def identity_partition_selector(context, partition_set_def): """Utility function for supplying a partition selector when creating a schedule from a partition set made of ``datetime``s that assumes the schedule always executes at the partition time. It's important that the cron string passed into ``crea...
ebc59c2a54b20256a8bd2a779fd2036df6346081
3,598,679
import numpy def ComputeGeodesicSphereMesh(radius=1.0,level=2): """Computes a geodesic sphere to a specified level. Returns the vertices and triangle indices""" GTS_M_ICOSAHEDRON_X = numpy.sqrt(numpy.sqrt(5)+1)/numpy.sqrt(2*numpy.sqrt(5)) GTS_M_ICOSAHEDRON_Y = numpy.sqrt(2)/numpy.sqrt(5+numpy.sqrt(5)) ...
d823f621b23d04c1f195968337649d03468366e0
3,598,680
def get_position_key(atom): """ Get atom position as tuple of integers to be used as lookup key. Rounds the coordinates to 4 decimal places before multiplying by 50 to get unique integer-space coordinates, and avoid floating point errors. :param atom: Atom to get key for :type atom: :class:`nan...
b367fd851a0afa903c2d73548849cc8864233f56
3,598,681
def get_unity(): """ Returns the unity global object of the current connection. If no connection is present, automatically launch a localserver connection. """ if not is_connected(): launch() assert is_connected(), ENGINE_START_ERROR_MESSAGE return __UNITY_GLOBAL_PROXY__
e7653b1a28cc61aedee1723cac979c6ba772f4a9
3,598,682
from typing import List def syncall_from_blobs(dry_run: bool = False, *, session: Session) -> List[Exception]: """ Sync all trials from the JSON blobs in TrialMetadata to the new relational tables. Handles ClinicalTrial, CollectionEvent, Cohort, Shipment, Participant, and Sample. Return a list of all ...
8ecf342830e1b241b7fe3a864fb025b89fbd8172
3,598,683
def sample_uint32(random_key: PRNGKey) -> int: """Returns an integer uniformly distributed in 0..2^32-1.""" iinfo = jnp.iinfo(jnp.int32) # randint only accepts int32 values as min and max. jax_random = jax.random.randint( random_key, shape=(), minval=iinfo.min, maxval=iinfo.max, dtype=jnp.int32) return ...
6098738a052ca56e8e81adee78ae1cdebae63da2
3,598,684
def create_item(user,cmd_args): """ cmd_args: url """ item = Item.objects.create( owner = user, image_url =cmd_args['img_url'][0]['payload']['url'], description = cmd_args.get("description",DEFAULT_DESCRIPTION), date_created = timezone.now() ) user.last_state = S...
6949c9ba9cf5226f916acc59823407fb21612ac6
3,598,685
def get_all_geom_set(): """ Returns a set of all component classes used in the assembly. """ return set(instances_by_class.keys())
6706d1822b34c15f79ceef214d82ccfb3a0d6e51
3,598,687
def AtrousResBlock(x, n_filters, ksize, scope='arb'): """ DAVANet: Stereo Deblurring with View Aggregation https://arxiv.org/pdf/1904.05065.pdf """ with tf.variable_scope(scope): net = slim.conv2d(x, n_filters, [ksize, ksize], scope='conv1') net = slim.conv2d(net, n_filters, [ksize, ...
e2d223d8d6b067e1e55b046729195f69250f383a
3,598,688
def check_horizontal_visibility(board: list): """ Check row-wise visibility (left-right and vice versa) Return True if all horizontal hints are satisfiable, i.e., for line 412453* , hint is 4, and 1245 are the four buildings that could be observed from the hint looking to the right. >>> che...
c32ad3a5a31636b48f73d884d4c6af90dec91e3d
3,598,689
def _str_eval_break(eval, act, ctxt) : """Passes through [break] so that the writer can handle the formatting code.""" return ["[break]"]
2da4059adb4305a3d7e2183c29d89c9539f3c63b
3,598,690
from typing import Tuple def parse_entry_point_string(entry_point_string: str) -> Tuple[str, str]: """ Validate the entry point string and attempt to parse the entry point group and name :param entry_point_string: the entry point string :return: the entry point group and name if the string is valid ...
c2ec3eda2fca341580ff5a8d2d952e7c66fa1a0b
3,598,691
from typing import Sequence import glob async def pool_remove(p: 'Player', c: Messageable, msg: Sequence[str]) -> str: """Remove a map from a mappool in the database.""" if len(msg) != 2: return 'Invalid syntax: !pool remove <name> <pick>' name, mods_slot = msg # separate mods & slot if ...
7d74bfa42af8a84c932f022592af13c393411648
3,598,692
def int32(v) -> Int32: """Shorthand for `Int32(v)`.""" return Int32(v)
335f9f181a89bec5433cc3497f8098c7df2ee8be
3,598,693
import math def tuning_score_size(performance_space, peak): """ Computes TS_s, the tuning score based on the size of the performance space compared to the achievable performance. """ return math.sqrt(performance_space.top() / peak)
9e5386932fa164f0d33e65dd41d57d7a22ebe4d6
3,598,694
import logging def get_user(): """generateba single user :return: str:user """ logging.info("Generating user ") return f"{fake.first_name()} {fake.last_name()}"
3a8e535e185864ceff652f4048c75378d3c7fa33
3,598,695
def delete_record(tableName, query): """ Function to delete a DynamoDB table Params: tableName::str The table name to get the record query::dict The query to fetch the record Returns: bool If the record was deleted or not """ if not ta...
d819a99a1955dcafec5947bdd5eaae76cc55ae69
3,598,696
def transform_pixels_to_meters(body, pixels): """Transforms pixels to meters using scale of the given body. Note this does NOT take into account the warping at the edges. So really must take a weight... Radii from Stern, S.A. et al. (2015) "The Pluto System: Initial results from its exploration by...
374e4d766d42382d43a8f21889ff90c0f5ff8151
3,598,697
def bin_to_revstr(x, digits=16): """ >>> bin_to_revstr(10, 6) '010100' """ return "".join(reversed(bin_to_str(x, digits)))
5640237a15014bc780f06d67e75b284ac86e64d7
3,598,699
def peo(graph): """ Returns a perfect elimination order of graph. Args: graph (NetworkX graph): a decomposable graph. Returns: a perfect elimination order of graph. Example: >>> from trilearn.graph import decomposable as dlib >>> g = dlib.naive_decomposable_graph(5) ...
af5d07c68cfbf181d86b7a4ba822db36fbf353d2
3,598,701
def _switch_to_raid_mode(node, controller_fqdd): """Convert the controller mode from Enhanced HBA to RAID mode :param node: an ironic node object :param controller_fqdd: the ID of the RAID controller. :returns: a dictionary containing - The raid_controller key with a ID of the ...
5df59ccacf5216043b8dc8f5225166d238063f21
3,598,702
def demo_parameters(): """Four plots showing the effects on the sample size of various parameters.""" plt.figure(figsize=(12, 10)) plt.suptitle("Effects on sample size from different parameters") def compute_res(u_size, f, N, k, d): res = k * ( f * N + N / u_size...
944c8393924630a5a3495fe0fec50303d5e104db
3,598,703
def normdist(mpa1, mpa2): """More efficient version of norm(mpa1 - mpa2) :param mpa1: MPArray :param mpa2: MPArray :returns: l2-norm of mpa1 - mpa2 """ return norm(mpa1 - mpa2) # This implementation doesn't produce an MPA with double rank: # # return np.sqrt(norm(mpa1)**2 + norm(mp...
58181fd1b38e5d88a82cd953e76b08b8294801a1
3,598,704
def project_name(request, *args, **kwargs): """ Custom context processor to provide the name of the project in the context for some templates """ return { 'PROJECT_NAME': settings.PROJECT_NAME }
7317f3ca6f12e5b303aba27ce9b1eb9dfb7133c5
3,598,705
def std_loss(simplex, values, value_scale): """ Computes the loss of the simplex based on the standard deviation. Parameters ---------- simplex : list of tuples Each entry is one point of the simplex. values : list of values The scaled function values of each of the simplex poin...
cbf739b75a0d936876b345ad070095e032c66c48
3,598,707
def jwt_auth(view_func): """Wraps a view with required JWT authentication and tries to get auth header from a request.""" @wraps(view_func) def wrapped_view(*args, **kwargs): request = args[0] auth_token = request.headers.get('Authorization', '').split(' ')[-1] valid_token = dec...
e6415ba449c33ae15d39ad4cf518eb9a36932078
3,598,709
def get_or_create_contact( from_header: str, mail_from: str, alias: Alias, msg: Message ) -> Contact: """ contact_from_header is the RFC 2047 format FROM header """ try: contact_name, contact_email = parse_full_address(from_header) except ValueError: contact_name, contact_email =...
fa44638ddfe70140e750eae82c5e019b2e22cd65
3,598,710
def available(func): """A decorator to indicate that a method on the adapter will be exposed to the database wrapper, and will be available at parse and run time. """ func._is_available_ = True return func
a0c886bccb9bbbdacfe23c5659929b8be68c004e
3,598,711
def test_idempotent_lambda_first_execution_with_validation( config_with_validation: IdempotencyConfig, persistence_store: DynamoDBPersistenceLayer, lambda_apigw_event, expected_params_update_item_with_validation, expected_params_put_item_with_validation, lambda_response, hashed_idempotency_k...
900f54cbe0d82981bfe665ca6afb910b2b9d3bb3
3,598,712
def get_current_token() -> str: """Returns the current OAuth access token stored in ~/.kube/config Returns ------- str current OAuth access token stored in ~/.kube/config """ oc_whoami_args = [ "whoami", "--show-token", ] oc_whoami_command_result = execute_oc_c...
5ee30889fc5b90ce799cf4c4fc1099031ccbc38a
3,598,713
def get_all_k_combinations(k: int, n_items: int) -> np.ndarray: """ Generates all k-combinations from n_features Parameters ---------- k: int Number of items per combination n_items Total number of items Returns ------- np.ndarray 2D array containing all k-combi...
01a1be64b4f588bbcd9c294386a8614e3ebb54a1
3,598,714
def spaces_and_caps_to_snake(spaced_str: str) -> str: """Convert caps and spaces to snake.""" underscored = spaced_str.strip().replace(' ', '_') return underscored.lower()
31796e696c2d4efa7821a0cdff09e04b3e7e8232
3,598,715
from typing import Sequence from typing import Optional def bst_make_balanced_recur(values: Sequence[int]) -> Optional[BTNode]: """Make a balanced binary search tree from a sorted sequence of values.""" if not values: return None mid = len(values) // 2 root = BTNode(values[mid]) root.left ...
5bf12ef85bed7d0e764e95f03ec0f101e01e97fe
3,598,716
from typing import OrderedDict from typing import Type import collections def kwtypes(**kwargs) -> OrderedDict[str, Type]: """ This is a small helper function to convert the keyword arguments to an OrderedDict of types. .. code-block:: python kwtypes(a=int, b=str) """ d = collections.Ord...
8024e6940f84f2eab8d4c44924889624d75ca3bd
3,598,717
def index(): """ serve index.html """ return send_from_directory(PUBLIC_PATH, 'index.html')
f0b9075667f0073b2b81fb72222c9e4b71040265
3,598,718
def dimensionless_variables(h_l): """ Function for determining dimensionless variables which depending on dimensionless liquid level in stratified flow :param h_l: dimensionless liquid level in stratified flow :return: a_l, a_g, s_l, s_g, s_i, v_l, v_g, d_l, d_g """ a_l = 0.25 * (uc.pi - np.arc...
2e3027951e4287cdd702e79a3a0b693455b8a514
3,598,719