content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_expanse_certificate_context(data): """ provide custom context information about certificate with data from Expanse API """ return { "SearchTerm": data['search'], "CommonName": data['commonName'], "FirstObserved": data['firstObserved'], "LastObserved": data['lastOb...
cf5c1d38ae7ed3474171ccff7d437d7b622cbcec
3,614,962
def find_polygon_divisions(line_pts, polygon_pts, angle): """ Esta función primero genera una recta, con un ángulo definido por angle, en cada punto contenido dentro de line_pts. Luego, para cada recta generada, encuentra la intersección con cada mitad del polígono definido en polygon_pts. R...
41add86abc9ad47be8cec00a0029d83f067b864b
3,614,963
def factorial(x: i32) -> i32: """ Computes the factorial of `x`. """ if x < 0: return 0 result: i32 result = 1 i: i32 for i in range(1, x+1): result *= i return result
31daab3c0e27756346154c6e1d1576363b81e83d
3,614,964
from datetime import datetime def convert_time(time_str): """Convert iso string to date time object :param time_str: String time to convert """ try: dt = datetime.strptime(time_str, "%Y-%m-%dT%H:%Mz") return dt except Exception: return time_str
4ba3d5b8af4305cc44afb60d02eeb1b1d041fab9
3,614,966
def get_common_words(): """Finds all common words in Redis""" redis_connection = get_redis_connection() words = redis_connection.keys(get_word_key("*")) return set([word[2:].decode('utf-8') for word in words])
888b6f8e77954ce6ed6f45d647156da53338faf3
3,614,967
import numpy def complex_to_amp_phase(lookup_table): """ This constructs the function to convert from complex64 or 128 to AMP8I_PHS8I format data. Parameters ---------- lookup_table : numpy.ndarray Returns ------- callable """ _validate_lookup(lookup_table) def converte...
92acec01b2a166a17b36a6d32352805ae0a6c7ce
3,614,968
def suck_out_formats(reporters): """Builds a dictionary mapping edition keys to their cite_format if any. The dictionary takes the form of: { 'T.C. Summary Opinion': '{reporter} {volume}-{page}', 'T.C. Memo.': '{reporter} {volume}-{page}' ... } In other ...
a0db907839573ca53f7c96c326afe1eac5491c63
3,614,969
import time import logging def tsne_embeddings(X, include_svd=True, n_svd_components=50, tsne_params=dict()): """ Computes t-SNE embeddings of the tf-idf vectors. By default it first performs a dimensionaly reduction using truncated SVD, as recommended in the scikit-learn documentation. This i...
186d9f67e6142e51b87fdfca2d2f4a6e05a60b7a
3,614,970
def get_expected_return( rewards: tf.Tensor, gamma: float, standardize: bool = True) -> tf.Tensor: """Compute expected returns per timestep.""" n = tf.shape(rewards)[0] returns = tf.TensorArray(dtype=tf.float32, size=n) # Start from the end of `rewards` and accumulate reward sums # int...
a8b5a2dbd67eaaf000dba05340239bc0fca1a563
3,614,971
def cast_bytes(data, encoding='utf8'): """ Cast str, int, float to bytes. """ if isinstance(data, str) is True: return data.encode(encoding) elif isinstance(data, int) is True: return str(data).encode(encoding) elif isinstance(data, float) is True: return str(data).enco...
01ac5d7cd4a728e401075334900808a6a579deef
3,614,972
def deep_access_list(x, keylist, key_value_eq=None): """ >>> deep_access_list({"a":2}, ["a"]) 2 >>> deep_access_list({"a":[{"a":2, "b":5}, {"a":1, "b":6}]}, ["a", "a"]) 3.0 >>> deep_access_list({"a":[{"a":"cat1", "b":"cat2"}, {"a":"cat3", "b":"cat2"}]}, ["a", "a"], "cat1") 1.0 >>> deep_a...
cdc3491c5b99ec02a40fcf518cd9f4e40e743f8a
3,614,974
def plot_roc_curve(y_true_arr, y_pred_proba_arr, labels_arr, pos_label=None, plot_thres_for_idx=None, log_wandb=False): """Function for plotting ROC curve Args: y_true_arr (list/np.array): list of all GT arrays y_pred_proba_arr (list/np.array): list of all predicted probabili...
46f4e1b3ab25183f72d724e6c13f8e2320125158
3,614,975
def _pillow2array(img, flag='color', channel_order='bgr'): """Convert a pillow image to numpy array. Args: img (:obj:`PIL.Image.Image`): The image loaded using PIL flag (str): Flags specifying the color type of a loaded image, candidates are 'color', 'grayscale' and 'unchanged'. ...
70800bd3174a6ab33389ca51c4204d21d19e3d16
3,614,976
import torch from typing import Optional from typing import Tuple def get_eval_fn(model: torch.nn.Module): """Get the evaluation function for server side. Parameters ---------- model The model we want to evaluate. Returns ------- evaluate The evaluation function """ ...
918b4e62422f0c645ffa68da346aae1c5e588413
3,614,977
def build_rnn_dataset(dataframes, tokenizer=lambda s: s.split()): """ Given an SST reader, return the dataset as (X, y) training pairs. Parameters ---------- dataframes : pd.DataFrame or list of pd.DataFrame The dataset or datasets to process, as read in by `sentiment_reader`. ...
71feeeed3369a8e6ddc3d2d62b56161da8da336a
3,614,978
def api_user_current_bar(): """Request endpoint to change a user's current bar :param int user_id: ID of the user to modity :param int bar_id: ID of the bar to set as user's current view default If 0, will use the configured default bar :param string next: Should be the URL of the current page s...
5353640a895ab8260d8919609a1ba661cf391d48
3,614,979
def _default_line_time_factory(self: "Kymo"): """Line time in seconds""" if self.timestamps.shape[1] > 1: ns_to_sec = 1e-9 return (self.timestamps[0, 1] - self.timestamps[0, 0]) * ns_to_sec else: raise RuntimeError( "This kymograph consists of only a single line. It is no...
075242606bacac1b9963d62f5e3794a5b276412e
3,614,980
def B(i,j,k): """ Tensor B used in constructing ROMs. Parameters ---------- i : int j : int k : int Indices in the tensor. Returns ------- int Tensor output. """ if i == j + k: return -1 elif j == i + k or k == i + j: return 1 el...
b4969759fd2f07bd2bd2baed48a2adfd8669987a
3,614,981
def magic(data): """Mime-Type anhand eines Datenstroms raten.""" if data[0:2] == '\xff\xd8': # JPEG Start of Image return 'image/jpeg', '.jpg' elif data[0:4] == '\x89PNG': return 'image/png', '.png' elif data[0:4] == '%PDF': return 'application/pdf', '.pdf' else: LOG...
16043cee7c05f81973702e624344447c23fe8677
3,614,982
def logout(): """登出""" session.pop("user_id", None) session.pop("nick_name", None) session.pop("mobile", None) # session.pop('user_id', None) # session.pop('nick_name', None) # session.pop('mobile', None) session.pop('is_admin', None) return jsonify(errno=RET.OK, errmsg="退出登录成功")
7c0abc3be1c097e63cfb1ae08af13f38dd806cad
3,614,984
def boost_python_pattern_generator(asg, pattern=None, *args, **kwargs): """ """ return boost_python_generator(asg, asg.declarations(pattern=pattern), *args, **kwargs)
21c6e1f653376a155ea12104b0884e2ac3bdc0c7
3,614,985
def make_upload_chart(gfunc, yaml_path, json_path, title): """Create an upload chart Args: gfunc: the group by function yaml_path: the template path json_path: the path to write to title: the title of the chart Retuns: the chart JSON """ return pipe( gfunc, ...
db9636700faa099ffe018a9f8b60293c531cca8b
3,614,986
import torch import time from re import X def _yuzu_ism(model, X_0, precomputation, device='cpu', use_layers=use_layers, ignore_layers=ignore_layers, terminal_layers=terminal_layers, verbose=False): """Perform ISM using compressed sensing to reduce the necessary compute. This function will take a model,...
5cf32eafc131380609d6f27e4baa9f638a5c3754
3,614,987
def resmlp_24_224(): """ ResMLP-24 Paper: ResMLP: Feedforward networks for image classification... Link: https://arxiv.org/abs/2105.03404 """ cfg = MLPMixerConfig( name="resmlp_24_224", url="[timm]", patch_size=16, embed_dim=384, nb_blocks=24, mlp_...
d92f9e483ec19a950771e076ba786755ca92469e
3,614,989
import math def h2abc(h): """Returns a description of the cell in terms of the length of the lattice vectors and the angles between them in radians. Takes the representation of the system box in terms of an upper triangular matrix of column vectors, and returns the representation in terms of the ...
aaaf35381bc447398a2339180e39a488530cd313
3,614,990
def get_joint_distribution( trials, mean_prior=lambda: tfd.Uniform(0., 1.), inverse_concentration_prior=lambda: tfd.HalfNormal(5.)): """Returns a joint distribution over parameters and successes.""" param_shape = ps.shape(trials)[:1] mean = tfd.Sample(mean_prior(), param_shape) inverse_concentration...
cc1a2eacad8870048d92eb573af13244a3405a8c
3,614,991
import io def format_data(data, indent): """Format a bytestring as a C string literal. Arguments: data: Bytestring to write indent: Indentation for each line, a string Returns: A multiline string containing the code, with indentation before every line including the first. There is...
260e2b296addeb1113d657b086302197a8e365bb
3,614,992
from re import A def survey_series_rheader(r): """ The series rheader """ if r.representation == "html": db = current.db s3db = current.s3db tablename, record = s3_rheader_resource(r) if not record: series_id = current.request.vars.series t...
c4d35cec80f32e575cb505e43113dc656682b9ca
3,614,993
def sample(bn, cond=None): """ Sample every variables of a Bayesian Network :param bn: a Bayesian Network :param cond: dict, given variables :return: """ g = bn.DAG cond = cond if cond else dict() if any(nod not in cond for nod in bn.Exo): raise ValueError('Exogenous nodes do...
81606afea08f1e80b73d115ed6a6a2581c13890c
3,614,994
from typing import Any import json async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: ConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" # Currently we only support a single device device = hass.data[DOMAIN][entry.entry_id][VICARE_DEVICE_CONFIG] da...
cee924ef4bff944a53dfffd7b8aff84b369691bc
3,614,995
from typing import List def predict_single(classifier: GaussianNB, test_data:List[Text], num: int = 200): """ predicts the most probable class value for the given test tokens and model Parameters ---------- classifier: GaussianNB model that holds the bag of words model test_d...
2f0e136a1bc0c4988219e76e7145c8ba19e29a99
3,614,997
def psf_to_inhg(psf): """Convert lb/ft^2 to inches of mercury.""" return psf * 0.014139030952735
c1a482c71ad86ae31efece5f1a395fa354db8c3e
3,614,998
def post_request_with_retries(url, json_payload, verify_ssl=True): """This function performs a POST request with a total of 5 retries in case of timeouts or connection issues. .. versionchanged:: 3.2.0 The query URL is now made into an absolute URL as necessary before performing the API request. .....
b3b37e5819d82cfd1871c614db1b9715ede05fe4
3,614,999
import signal def filt(data, cutoff, fs=1., order=1, rp=10., rs=10., kind='butter', btype='low', ftype='filtfilt', axis=0, analog=False): """ Apply a digital filter. :param data: :param cutoff: :param fs: :param order: :param rp: :param rs: :param kind: :param btype: :param...
e37e03079700446c0eedbfb0b09dd8d045c87155
3,615,000
def remove_exceptions(words): """ Removes exceptions from the resulting words """ return [word for word in words if root(word) not in EXCEPTIONS]
1bdcc8bfb74f1cf3d31c80203da07580b66c40dd
3,615,001
def convert_ring_to_sub_molecule(ring): """ This function takes a ring structure (can either be monoring or polyring) to create a new submolecule with newly deep copied atoms Outputted submolecules may have incomplete valence and may cause errors with some Molecule.methods(), such as update_atomty...
2e6c7c1ef637dd2e60988e4a7bf6b4f56ad41563
3,615,002
def generate_first_goal(roi_boundaries, vehicle_pos, parking_pos): """ generate goal for forward task """ x = roi_boundaries[4].x + 4 y = (roi_boundaries[6].y + roi_boundaries[5].y) / 2 \ + (roi_boundaries[6].y - roi_boundaries[5].y) / 4 - 1.1 theta = 2...
45308e1662f7b6512ab8364d65721fc7820687eb
3,615,003
def compute_acc(Y, log_dist_a, n_se=2, return_er=False): """compute the accuracy of the prediction, over time - optionally return the standard error - assume n_action == y_dim + 1 Parameters ---------- Y : 3d tensor [n_examples, T_total, y_dim] log_dist_a : 3d tensor [n_exam...
d042c2b6c8e540035f61cc06e7b751c664a44bda
3,615,005
def get_closest_point(points, point): """ Get the closest point in an array of points to the given point. """ if len(points) == 1: return 0, points[0] min_dist = None min_pt = None min_i = None for i, pt in enumerate(points): v = [point[j] - pt[j] for j in range(0, 3)] di...
64f9c0bf949df7e18defa129105ca742bb5b6b2e
3,615,007
def get_facemesh_coords(landmark_list, img): """Extract FaceMesh landmark coordinates into 468x3 NumPy array. """ h, w = img.shape[:2] # grab width and height from image xyz = [(lm.x, lm.y, lm.z) for lm in landmark_list.landmark] return np.multiply(xyz, [w, h, w]).astype(int)
2c7f21fe65e852659aecba966b9623938e1fd33d
3,615,009
def decode_resource(name): """Load and decode sublime text resource. Arguments: name - Name of the resource file to load. returns: This function always returns a valid dict object of the decoded resource. The returned object is empty if something goes wrong. """ try: ...
98c2d590e977981175fd38539ce0b65097d07fba
3,615,010
def get_dtw(action_list, env_output_list, environment): """Dynamic Time Warping (DTW). Muller, Meinard. "Dynamic time warping." Information retrieval for music and motion (2007): 69-84. Dynamic Programming implementation, O(NM) time and memory complexity. Args: action_list: List of actions. env_out...
401def9c268195eda2b7a09cea30a220c43890aa
3,615,011
def get_version(v): """ Generate a PEP386 compliant version Stolen from django.utils.version.get_version :param v tuple: A five part tuple indicating the version :returns str: Compliant version """ assert isinstance(v, tuple) assert len(v) == 5 assert v[3] in ('alpha', 'beta', 'rc...
946c9ea382ac7da0da1c74373cf981df174737c1
3,615,012
def cpdf_shape(e, p, x): """The conditional probability distribution function of the shape parameters e and p (ellipticity and prolateness) given the curvature x, as defined by Bardeen, Bond, Kaiser & Szalay (1986) in equation (7.6), together with (A15), (C4) and (C3).""" # BBKS eqn. (C3): chi =...
c2703d2438fac1ff2ec166ac85f2c9d5b293e7dc
3,615,013
def get_nuc2prot(): """ Returns a dict of nucleotide accessions numbers as keys and protein acession numbers as values. """ nuc2prot_acc = {} with open("./data/download/nucleotide2protein", "r") as handle: line = handle.readline() while line: prot, nuc = line.split("...
8f6e0ab5ad76cfaa63d8c0bf12f84e18b759e750
3,615,014
def tadsize_chart(genome_name): """ Determine the distance threshold to build coverage tracks. Args: genome_name (string): name of the reference genome; ex: mammals, drosophila, c_elegans, s_pombe, c_crescentus Returns: dist_thresh (int): integer specifying dist...
844744424845a1d240fa93023b9786a7ed2cc12c
3,615,017
from typing import List def vertices_of_mesh(bsp, mesh_index: int) -> List[VertexReservedX]: """gets the VertexReservedX linked to bsp.MESHES[mesh_index]""" # https://raw.githubusercontent.com/Wanty5883/Titanfall2/master/tools/TitanfallMapExporter.py (McSimp) mesh = bsp.MESHES[mesh_index] material_sor...
279defde6999f29ca085d2ec81602c21de69bf80
3,615,018
def convert_results_to_table(results, aggregation="average"): """ Convert results to table Args: results (dict): results dictionary aggregation (str): aggregation method, either average or sum """ headers = [] columns = [] for target_task, source_tasks in results.items(): ...
51d38a52cb5428568c89e518df86624c5f438cf6
3,615,019
def collapse_cr_map(dq_map): """Transform a 4D array containing cosmic ray hit locations (1 for CR hit, 0 for no hit), into a 3D (integration, y, x) map that lists for each pixel the group number of the first CR hit. If that pixel has no CR hits in the integration, then it will have a value of NaN. ...
d041608ad2b3813f8f3a4bb97c51966730ccd23e
3,615,021
def pretty_league(league): """Formats a detailed league view in a PrettyTable""" fields = ["Previous rank", "Current rank", "Arrow up/down", "Team name", "Manager name", "Gameweek score", "Total score", "Team Id"] table = PrettyTable(field_names=fields) table.title = league.name for t ...
d500b5b8929a5f7b5dbebef6558cfd2b57ea0c79
3,615,022
def pix2np(pix): """ Converts a pixmap buffer into a numpy array """ # pix.samples = sequence of bytes of the image pixels like RGBA #pix.h = height in pixels #pix.w = width in pixels # pix.n = number of components per pixel (depends on the colorspace and alpha) im = np.frombuffer(pix.sa...
827cc54cbf66bed4ad980d8403c8bce96a884e52
3,615,023
def get_org_menu_extras(org): """ Check if there are any Config Attributes for extra org related menus in different pages :param org: Organization Object :return: Object with additional org menus to show. e.g. archive_buttons: { "url": "/apps/shipping/p--0000-0015/sxd/device/", ...
5de3e64538633381f8eff395ab1e57acb6d8c039
3,615,024
from typing import Dict def deep_dict_merge(source: Dict, dest: Dict): """Merge dictionaries recursively (i.e. deep merge).""" for key, value in source.items(): if isinstance(value, dict): # get node or create one node = dest.setdefault(key, {}) deep_dict_merge(valu...
98f3f7bb819e1245155280e4d31f5b07f7944cc4
3,615,025
def get_challenge(): """Calc game Q&A generation. generate two random numbers and calculate result of random operation Returns: dictionary: key QUESTION (string) : operation description; key ANSWER (string) : result of operation """ num1 = randint(_min(), _max()...
d21cc8672fd4bc3b4eae3e69d0d3a83978ed4d64
3,615,027
def _los(da, eos, sos): """ LOS = Length of season (in DOY) """ los = eos - sos # handle negative values los = xr.where( los >= 0, los, da.time.dt.dayofyear.values[-1] + (eos.where(los < 0) - sos.where(los < 0)), ) return los
fe3da95bb3328643925a7d52656e201f055809fe
3,615,028
def test_fallback_Jacobian_qnode(monkeypatch): """Test the decorator fallsback to Jacobian QNode if it can't determine the device model""" dev = qml.device('default.gaussian', wires=1) # use monkeypatch to avoid setting class attributes with monkeypatch.context() as m: m.setitem(dev._capabi...
3aa0dc3b29b01b23e05dc096e708f2992b703496
3,615,029
import textwrap def construct_pdp_query( metarels, dwpc=None, path_style="list", return_property="name", property="name", join_hint="midpoint", index_hint=False, unique_nodes=True, aggregate_columns=False, ): """ Create a Cypher query for computing the path degree product f...
79a24cc17139273356959f6b4c2b9867c9943e5a
3,615,030
from typing import List def get_sparclur_renderers(): """Helper function that returns a list of all SPARCLUR Renderers""" present_renderers: List[Renderer] = \ [renderer for renderer in _sparclur_parsers.values() if issubclass(renderer, Renderer)] return present_renderers
80883bfda55f20c5ec2e38ed1a3dfbb28a5cd69f
3,615,031
from typing import Tuple def load_component_from_url( cUrl: str, tProperties: "Tuple[PropertyValue]" ) -> "XComponent": """ Open or Create a document from it's URL. Args: cUrl (str): specifies the URL of the document to load New documents are created from URL's such as: ...
3e62ac958d1b9b98a751d153d672843faf388bfe
3,615,032
def get_fields(search_input): """ Forms the field properties for a search input based on the input type and properties stored in the database. For some types it returns a list with only one field for which the label is empty. Because it takes the label of its fieldsets while rendering. For others, it re...
ec79e36eea1f4c185873fca1cd9c3d999d2d5e8e
3,615,033
def sub_menu(context, root): """Returns the sub menu items, the children of the root page. Only live pages that have the show_in_menus setting on are returned.""" menu_pages = root.get_children().live().in_menu() return {'request': context['request'], 'root': root, 'menu_pages': menu_pages}
e8ebfacd36263bad8cfb4d0acd2aba5e02560a7f
3,615,035
def alembic_config(postgres): """Создает объект с конфигурацией для alembic, настроенный на временную БД.""" cmd_options = SimpleNamespace( config="alembic.ini", name="migrations", pg_url=postgres, raiseerr=False, x=None ) return make_alembic_config(cmd_options)
be8e438caae3846a07baf09f07636e6a2f7f3dda
3,615,037
def get_setting(name): """ Возвращает значение для настройки, или дефолт, если он задан, или None. Если настройка обязательная, но она не задана - выбрасывает исключение. """ if hasattr(settings, name): return getattr(settings, name) if name in REQUIRED_SETTINGS: _raise_required...
6fd6bfe7de233af34d6fbe03bbc57a6bebebdbcc
3,615,038
import mmap def is_word_in_file(fname, word): """ Search word in given file. This function skips empty files. """ f = open(fname) try: s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) if s.find(word) != -1: return True return False except ValueError: ...
c16b94bb450807fefdab35470535c0752a9ecbbd
3,615,039
def Difference(left, right): # pylint: disable=invalid-name """ @type: left: Iterable[Any] @rtype: set[Any] """ return to_set(left).difference(to_set(right))
d891e141f9dbb498dd0ea375de226060f5230f15
3,615,040
import opcode def getP2PKHOpCode(pkScript): """ getP2PKHOpCode returns opNonstake for non-stake transactions, or the stake op code tag for stake transactions. Args: pkScript (ByteArray): The pubkey script. Returns: int: The opcode tag for the script types parsed from the script. ...
4468bc3dcc9828005aae322d28466093b1e127e9
3,615,041
def emat(st1, yt, t, a=None): """ returns exponential moving average for a t-period EMA and incremental value where st1 is the previous average, yt is the incr value, and t is the size of the avg a can optionally be overridden with a specific coefficient, else 2/(t-1) is used """ # St = a...
484403ca5ba13bd960bcda6220846eef9ac09114
3,615,042
from datetime import datetime def generate_dates_in_year_df(year, spark): """Generate all dates and all hours between in the given year""" date = datetime.datetime.strptime(f"01/01/{year}", "%d/%m/%Y") end = datetime.datetime.strptime(f"01/01/{year+1}", "%d/%m/%Y") dates = list() while date != end...
50c489b4f169568c88cef4b7783caa88e9397863
3,615,043
def plot_kmeans(result ,names, colors, country, season, mapbox_access_token): """ Creates and interactive html output of the clusters, if the number of points is more 100K randomly sample 50K of them result: Dataframe, constaining k-means clustering results under the column 'label' names: List of clust...
c948a98b9a4a12bb1b673ab0394f349fdf20c82f
3,615,045
import time def _fitFunc(pfit, pfitKeys, x, y, err=None, func=None, pfix=None, verbose=False, follow=None): """ interface to leastsq from scipy: - x,y,err are the data to fit: f(x) = y +- err - pfit is a list of the paramters - pfitsKeys are the keys to build the dict pfit and pfi...
5b13bcd74958818d57d4e18a155fffa4b43a4262
3,615,046
def do_set_license_link(parser, token): """ Stores the license link to a context variable. Usage:: {% license_link as [varname] %} """ bits = token.contents.split() if len(bits) != 3: raise template.TemplateSyntaxError('%s tag requires two arguments' % bits[0]) if ...
8c424990daeab639475cea0cb88d692803f14c66
3,615,048
def bf_get_snapshot_inferred_node_roles(): # type: () -> NodeRolesData """Gets suggested definitions and hypothetical assignments of node roles for the active network and snapshot.""" return bf_session.get_node_roles(inferred=True)
d0be36c9ce23190487669f384f4e7d1b7b44c85d
3,615,049
import textwrap def ExtractHelpStrings(docstring): """Extracts short help and long help from a docstring. If the docstring contains a blank line (i.e., a line consisting of zero or more spaces), everything before the first blank line is taken as the short help string and everything after it is taken as the l...
c85f0008f059128c13f823a86e49eff901df3076
3,615,050
def flat_page(path): """flat pages rendering""" page = g.pages.flatpages.get_or_404(path) # Configure the img link plugin g.flat_page = page return render_template('article.html', page=page)
654badee72cbe1c0f62d8859358afa22746d3432
3,615,051
def init_smoothing_wf(fwhm=None, memcalc=MemoryCalculator(), name=None, suffix=None): """ Smooths a volume within a mask while correcting for the mask edge """ if name is None: if fwhm is not None: name = f"smoothing_{int(float(fwhm) * 1e3):d}_wf" else: name = "sm...
10cd279fe401cd23286d5f98efa49e6bf44ef3e2
3,615,052
import array def check_similarity_in_list(token_1: str, token_list: array, threshold: int) -> bool: """ :param token_1 :param token_list :param threshold :return true, if token_1 and at least one token in token_list are equal due to levenshtein distance and a given threshold, otherwise false "...
e7b88a555ed4c220b1354e711892740ca5a85038
3,615,053
def sin(val): """ Qiskit wrapper of sine function """ if isinstance(val, Qobj): return val.sinm() else: return np.sin(val)
daea123bc919f6b5686b87eff3f1b2e94766fb69
3,615,054
def toy_data_multitask(n_samples, input_dim, output_dim, random_state=None): """Generate data according to Evgeniou, C. A. Micchelli, and M. Pontil. 'Learning multiple tasks with kernel methods.' 2005. Parameters ---------- """ rs = check_random_state(random_state) X = rs.rand(n_samples, ...
7ba1e2c1644b57d83844757807b8bfd55f503027
3,615,055
def select_all(event): """Select all text event in textbox An event that is bound to the select-all key press. Selects all text within a text widget. """ event.widget.tag_add(SEL, "1.0", END) event.widget.mark_set(INSERT, "1.0") event.widget.see(INSERT) return 'break'
25cbd469df40c9e25bde52cb49fbc054c7cc978e
3,615,056
def get_service_type(f): """Retrieves service type from function.""" return getattr(f, 'service_type', None)
fb4d98a4b4db0d10ab97d94d98ccfe21cea05fe9
3,615,057
def tempcsv(): """Create a temporary CSV file""" return tempfilename(suffix='.csv')
3fe27678892dccecc852363338db74cac97ac5ac
3,615,058
def func_d2lV(isvegc, edge, saturate): """ input: isvegc : [ncol x nrow] array of vegetation field output : d2lV : [ncol x nrow] array, distance to nearest veg cell to the left = 0 for veg cells = 1 for bare cells with a veg cell immediately left """ ncol = isvegc...
89820134f31ee577a2f923fca658d65e8cac92bc
3,615,059
def generate_enum(cls_name, values, imports='') -> str: """ Helper function to create C++ enum headers :param cls_name: the name of the enum :param values: values to include :param imports: additional files to import """ code = templates.FOUNDATION_ENUM.format( name=cls_name, ...
adee41955f7ca800944c57ae470a5638a3df1e2a
3,615,060
def u(string): """ This is a unicode() wrapper since u'string' is a Python3 compiler error. """ if is_python3(): return string return unicode(string, encoding='utf-8', errors='strict')
bc37126387c04d67504de0ec981d805ea5e19c15
3,615,061
def env(ctx, name, home='~'): """Run with an anaconda environment""" return ctx.prefix('source %s/%s/bin/activate %s' % (home, ANACONDA, name))
984075f721f62d973145705b8774ef33c6e75c0e
3,615,062
def output_file(file_name): """ adds output file extension, if missing """ return _add_extension(file_name, Extension.OUTPUT_LOG)
946dcfee5a706b6cf0dc3713f75013bdc07f274f
3,615,063
def load_pnasnetlarge(scopes, return_fn=_assign): """Converted from the [TF Slim][2].""" filename = 'pnasnet_large.npz' weights_path = get_file( filename, __model_url__ + 'nasnet/' + filename, cache_subdir='models', file_hash='a1afc7679b950b643865aa7ea716c901') values = parse_wei...
9908f72795523ef4990e3f6e55ab45f3d0627772
3,615,064
def coord_max(t): """Multidimensional argmax Returns coordinates of largest element in tensors of any shape Args: t: Tensor to find location of max element within Returns: 0 or 1-D Tensor of length t.ndims containing coordinates """ # Run 1-D argmax on flattened array idx ...
5e006bae358c4ef97986abf08b9d45effbcd81d0
3,615,065
def block_dot(A, B, diagonal=False): """ Element wise dot product on block matricies +------+------+ +------+------+ +-------+-------+ | | | | | | |A11.B11|B12.B12| | A11 | A12 | | B11 | B12 | | | | +------+------+ o +------+------| = +-------...
453b4f5a300d750a9302f3309ab7f73c8d4b51c7
3,615,066
def SSIM(pred, ref): """ Compute SSIM between predicted and reference tensors in Tensorflow Params: - pred : TensorFlow tensor Predicted tensor - ref : TensorFlow tensor Reference tensor Outputs: - ssim : float SSIM value ...
fb5546ad16dab75c1bcbc63c9dabd47a100d7924
3,615,067
def CreatePackagableRoot(target, output_dir, ldpaths, root='/'): """Setup a tree from the packages for the specified target This populates a path with all the files from toolchain packages so that a tarball can easily be generated from the result. Args: target: The target to create a packagable root from ...
a86316d6928baf7cc7b66f7771d8538baea4007a
3,615,068
def tablename(dxfname): """ Translate DXF-table-name to attribute-name. ('LAYER' -> 'layers') """ name = dxfname.lower() return TABLENAMES.get(name, name+'s')
20ede17ece01f164a54d1052cfd43dc90fe0155e
3,615,069
def extra_aaindex(filename): """Return AAIndex obj list. """ index_list = ['A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V'] aaindex = [] with open(filename, 'r') as f: temp_h = "" lines = f.readlines() for i...
346898a4094612161245464dde31b46b83af197c
3,615,070
def make_block(arch_args, in_chs): """ Creates a block instance """ block_type_code = arch_args['block_type'] out_chs = arch_args.get('out_chs') if out_chs is None: out_chs = in_chs arch_args['name'] = clean_name(arch_args['name']) block_type_def = NetBuilderConfig.get_block_ty...
d587990fab9984719bd34199d113743ee201bdac
3,615,071
def aks_list_table_format(results): """"Format a list of managed clusters as summary results for display with "-o table".""" return [_aks_table_format(r) for r in results]
b105b18f8b6d613a7d216bbcba9a31d1ee94bb32
3,615,072
import requests from bs4 import BeautifulSoup import tqdm def bank_rank_banker() -> pd.DataFrame: """ 全球银行排名前 25 家 https://www.thebankerdatabase.com/index.cfm/search/ranking :return: 全球银行排名前 25 家 :rtype: pandas.DataFrame """ url = "https://www.thebankerdatabase.com/index.cfm/search/index.c...
f63c5e35e9f2b91af3d50d5c2eb23c0bad4f1dde
3,615,073
from functools import reduce def matmul(mat_list): """ Compute matrix multiplication of the matrices in mat_list Arguments: mat_list: list of numpy arrays, the target matrices Return: prod: numpy array, the result """ if len(mat_list) <= 1: prod = mat_list[0] els...
0defdd6d073f9a254e178cac6489e96818cbe4f7
3,615,074
def ByteStreamCopyToUTF16Stream(byte_stream, byte_stream_size=None): """Reads an UTF-16 formatted stream from a byte stream. The UTF-16 formatted stream should be terminated by an end-of-string character (\x00\x00). Otherwise the function reads up to the byte stream size. Args: byte_stream: The byte strea...
f994f5c88400b174eb7c435f69f7f0a0220fc371
3,615,076
def compute_error(model_data, reference_data): """Returns the summ of the squared differences between model and reference data.""" error = ((model_data - reference_data) ** 2).sum() return error
66e80326b85eed67008b517dfeff99cc8352bffd
3,615,077
def blog_comment(): """ 博客文章评论 """ the_result = do_blog_comment(db, Post, Comment, request.form, request.headers['X-Real-IP']) return the_result
802aa611be206f483dddd0762e7e20a1f6089881
3,615,078