content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Union import torch from typing import Sequence from typing import Mapping def collect_tensors(collection: Union[torch.Tensor, Sequence, Mapping]): """ Collect all the tensors in the sequence/mapping """ if isinstance(collection, torch.Tensor): return [collection] if isi...
162a28d40f1aaa9b742877bd19ca769dbbf3c7c5
66,600
from unittest.mock import call import os import re def compress_js(directory, source, css_variables, advanced_cc): """ Compress Javascript content :param directory: The root directory :param source: The source Javascript string :param css_variables: A CSS variables object to shorten css variable name...
61e066144d7426a21b789f9bcffe5bbfbe2208af
66,601
def separate_cell_nmt(src_input, tgt_input, unroll=True, **kwargs): """Returns a NMT network.""" hparams = create_nmt_hparams(**kwargs) assert unroll return SeparateCellNMT(hparams).build_graph(src_input, tgt_input)
1a9611bd23c52ccf7a49f30836df8c36ec793ac0
66,602
def random_xffffffff(shape=(40,60), dtype=np.uint32, add=0xff000000) : """Returns numpy array of requested shape and type filled with random numbers in the range [0,0xffffff] with bits 0xff000000 for alpha mask. """ a = 0xffffff*np.random.random(shape) + add return np.require(a, dtype)
40709c00e862adc255ac4f245c0c94af43e5085f
66,603
def printSeq(startChar, endChar, seq, maxdepth): """ >>> printSeq('(', ')', (1, 2, 3), 4) ['(', '1', '2', '3', ')'] >>> printSeq('(', ')', (), 4) ['(', ')'] """ if maxdepth < 1: return '&' maxdepth -= 1 return [startChar] + [cprint2(x, maxdepth) for x in seq] + [endCh...
9a5d1fa447928cb5769b238516d41a96c5c0ffef
66,604
import configparser import os import getpass import socket def load_params(args): """ reads the parameter file and creates as list of test objects as well as the suite object """ test_list = [] cp = configparser.ConfigParser() # note, need strict=False for Python3 cp.optionxform = str...
c636ac5665f67e327c026850654c78c549a711e0
66,605
import six def across_data_formats(func): """Function wrapper to run tests on multiple keras data_format and clean up after TensorFlow tests. Args: func: test function to clean up after. Returns: A function wrapping the input function. """ @six.wraps(func) def wrapper(*args, ...
224d5ede2a32518569513ce7dfb27bf2a8ab0f0f
66,606
def process_data_arguments(data=None, single_plot=False, use_column_source=False, flatten_np=False, forbid_split_up=None, same_length=False, copy_data=False, ...
98c2de34510632d2de17515c63c1ed1b81bc1c47
66,607
def create_stack(nodes): """helper function to create a stack""" test_stack = Stack() for el in nodes: test_stack.push(el) return test_stack
5a902b693366346cbfd379b0b9d5ebf22feb0396
66,608
def mae(data: DatapointList) -> float: """ Computes the mean squared error. :param data: :param targets: A list of targets. :param preds: A list of predictions. :return: The computed mse. """ targets = [d.targets for d in data.get_data()] preds = [d.predictions for d in data.get_dat...
d442ab67cdcf0439844f8a71dc576098c7a14128
66,609
def expand_on_basis_of_basic_representation(mappings): """ Expansion using Basic Representation :param response: Response obtained after hitting the base_url of collection :param mappings: Mappings of variables and values provided by the user to expand template :return: Expanded URL on the basis of Bas...
fae0ec69922f3be5f25a561c5bba9f602dc3bba6
66,610
def compile(mod, target=None, target_host=None, params=None): """Compile the module to VM executable. A helper function for VMCompiler. Parameters ---------- mod : tvm.IRModule The Relay module to build. target : any multi-target like object, see Target.canon_multi_target For homog...
9f0bfb05339c4f122f36582ab7f922aa4e00ae08
66,611
import sqlite3 def get_multiple_data(table_name): """ get document data by document ID :return: """ conn = sqlite3.connect(DATBASE_LOCATION) cur = conn.cursor() sql = '''SELECT rowid,* FROM {0}'''.format(table_name) cur.execute(sql) data = cur.fetchall() conn.commit() conn....
7c12261e016abdb779d2f997674cbad7d54d3126
66,612
def posterior(kalman, problem): """Kalman smoothing posterior.""" *_, obs, times, states = problem return kalman.filtsmooth(obs, times)
724a80cd69efa499cbc62f79ab611de30c10ac26
66,613
def get_cache_key_counter(bound_method, *args, **kwargs): """ Return the cache, key and stat counter for the given call. """ model = bound_method.__self__ ormcache = bound_method.clear_cache.__self__ cache, key0, counter = ormcache.lru(model) key = key0 + ormcache.key(model, *args, **kwargs) ret...
241b13b29b3dce0888f2eeb40361dfa03d5f8389
66,614
from typing import Callable def fixed_step(f:Callable)->Callable: """ Decorator which fills in the missing time step parameters :param t0: Initial time :param t1: Final time :param n_step: Number of time steps to take :param dt: Time between steps :param fps: Number of steps per time unit...
ed72b3fe50bbe70b8a539bcee93fde44be738a0c
66,615
def get_HI_surface_density( h1_intensity: np.array, major: float, minor: float, inclination: int ) -> np.array: """Calculate the HI surface density from the THINGS maps Args: h1_intensity (np.array): intensity of the HI emission in [Jy/beam km/s] major (float): FWHM of the major axis of the...
d336eb66015e70788abc4956016280ec21ac7ac0
66,616
def shufflenet_block(scope, base_depth, num_units, stride, groups, groups_in=None): """Helper function for creating a shufflenet bottleneck block. Args: scope: The scope of the block. base_depth: The depth of the bottleneck layer for each unit. num_units: The number of units in the block. ...
97a70194db1b30a7956cf058212ec2f33d7ad5fb
66,617
import os async def convert_body(request: Request): """ It's just _way_ easier to deal with files rather than STDIN. Take the body of the request, write it to a temporary file, then use wkhtmltopdf to convert it. """ data = await request.body() if not data: return Response("ERROR...
7260847659e1cc67bbc12f828b4317a077913e8f
66,618
import array def read_feature(filename): """Read feature dump by C3D Parameters ---------- filename : str Fullpath of file to read Outputs ------- x : ndarray numpy array of features Note: It accomplishes the same purpose of this code: C3D/examples/c3d_featur...
5f79e850b629dac1bc1ced22d85d1be9e0131254
66,619
from datetime import datetime def set_qos(s_url, s_qos): """ Sets a new QoS to the site if existing :param s_url: str - URL/name of the site :param s_qos: float - QoS value :return: Site - The updated site or None if not existing. """ assert isinstance(s_qos, float), 'QoS value must be f...
4a5cfda19b4e34dabba79a2adab41219e35c1c2a
66,620
def extract(mod, models): """ Returns models with mod removed. """ if mod == {}: # No mod to delete, return models as it is. return models return [model for model in models if model != mod]
5aa24ccaa238fe85f4f037c8af318e95a77b7b55
66,621
def extract_labels(all_samples): """ this function extracts the labels and speaker from the dataset """ labels = [] speakers = [] print("Extracting Labels") for i in range(len(all_samples)): temp = all_samples[i] temp = (temp[0:-3].split("_")) labels.append(float(temp[0])) speakers.append(temp[1]) if i...
65b2a07a709881f5d3c72931949673ee797ba1f3
66,622
import requests def bond_spot_deal() -> pd.DataFrame: """ 中国外汇交易中心暨全国银行间同业拆借中心-市场数据-债券市场行情-现券市场成交行情 http://www.chinamoney.com.cn/chinese/mkdatabond/ """ url = "http://www.chinamoney.com.cn/ags/ms/cm-u-md-bond/CbtPri" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...
5f4355d54b476d47d86ae4d69e8aceef82ecf83f
66,623
import os def _replace_desdata(pth, desdata): """Replace the NERSC DESDATA path if needed. Parameters ---------- pth : str The path string on which to do replacement. desdata : str The desired DESDATA. If None, then the path is simply returned as is. Returns ------- p...
082681d1366b7409d11fba13c7d41fa43e4d9d9e
66,624
def get_mega_info_dict(samples): """Read mega info of all samples, return a dict {(o_prefix, pbid) --> MergeGroupOperation(pbid, group1, group2)} ex: {('tmp_1009', 'PB.1.1'): MergeGroupOperation('PB.1.1', 'PB.2.1', None)} """ mega_info = {} # ex: (tmp_1009, PB.1.1) --> MergeGroupOperation(...)...
9f9c3283633cdcc65dca4751fe65baa5b988d201
66,625
def write_xyz(tgt_geo, bath_geo): """ Write the geom strings """ tgt_str = automol.geom.string(tgt_geo) bath_str = automol.geom.string(bath_geo) return tgt_str, bath_str
9503e97dbad2621c5841ce6ad53ed86b8a1aa9e5
66,626
def get_prop(prop, default=None): """First order function which can be used to extract property of nodes""" def get(n: Node): return default if prop not in n else n[prop] return get
509602b279e6ee47128acaa84e788cab18024289
66,627
def _is_no_cache(request): """Returns True if the request should skip the cache.""" cache_control = request.headers.get('Cache-Control') or '' return 'no-cache' in cache_control or 'max-age=0' in cache_control
bf8421a3f9a654a877cdf518aa9a4de532098f89
66,628
def scanner_config(): """ 读取配置文件 :return: dict """ with open("config.inf", "r") as f: lines = f.readlines() lines = [line for line in lines if cmp(line.strip(), "") != 0] lines = [line for line in lines if not line.startswith("#")] kv_dict = {} for line in lines: kv =...
219003bac6d7b4dd7efa498ef58ba003f2f6a01d
66,629
def get_missing(array, first=True): """ returns the ids of similar looking images that we haven't collected yet array is | ID | row | col | filename | lat | lon | X_1 | ... | X_n | where ID is the image id row is the row pixel index of top left corner of subimage col is the ...
323a2b88a02fafe6f06f2e65be1be625a0ace29b
66,630
def generate_voronoi_polygons(points, scale, aoi): """ Generates Voronoi polygons :param points: :param scale: :param aoi: :return: """ error = ee.ErrorMargin(1, 'projected') # proj = ee.Projection('EPSG:3857').atScale(scale) proj = ee.Projection('EPSG:4326').atScale(scale) ...
bb450a3566db6ecdb3b9342209666f380e3c0fc8
66,631
def open_text(fname, **kwargs): """On Python 3 opens a file in text mode by using fs encoding and a proper en/decoding errors handler. On Python 2 this is just an alias for open(name, 'rt'). """ if PY3: # See: # https://github.com/giampaolo/psutil/issues/675 # https://github....
56e4c364fa915a3b75eccfbd69fa91180612585b
66,632
def plot_timeseries(server, e, dataset_id): """This defines the initial bqplot time series plot""" dt_x = bq.DateScale() sc_y = bq.LinearScale() constraints = {"time>=": server.get("min_time"), "time<=": server.get("max_time")} df, var = get_timeseries( e=e, dataset=dataset_id, ...
e6f12533716a33e2ef84a547d1ed471cd9b9ff31
66,633
def tf_idf(text): """ Compute the TF-IDF scores for each word in each document. The collection of documents must be in bag-of-words format. .. math:: \mbox{TF-IDF}(w, d) = tf(w, d) * log(N / f(w)) where :math:`tf(w, d)` is the number of times word :math:`w` appeared in document :math:`...
e008b666b58206ceb195ef84960eccadcef0b854
66,634
def get_chassis_serial(self): """ Returns the serial number of the chassis """ output = self._vchannel.cmd('show inventory rack | inc "^ 0"') line = output.split('\n')[0] # first line tmp = line.split() if len(tmp) > 2: result = tmp[2] else: result = '' BuiltIn().log...
ccbc69baaa0d093f50c6d49c3f68eb7a5a9c82c0
66,635
def create_resnet_encoder( backbone_options: config_pb2.ModelOptions.BackboneOptions, bn_layer: tf.keras.layers.Layer, conv_kernel_weight_decay: float = 0.0) -> tf.keras.Model: """Creates a ResNet encoder specified by name. Args: backbone_options: A proto config of type config_pb2.ModelOption...
f98c1bda75614c284fc8d7255b8e693aa6253a47
66,636
def group_function(table_columns, table_row, tree): """True if resultset should be grouped :return: Grouping function or None and its position. :rtype: tuple(EtcdbFunction, int)""" try: group_position = 0 for select_item in tree.expressions: expr = select_item[0] ...
68d6d27bb61499f191ed74b6e6e586e227aaff48
66,637
import numpy import itertools def stratify_irregular_dimension(storage_units, dimension): """ Creates a new series of storage units for every index along an irregular dimension that must be merged together :param storage_units: :param dimension: :return: storage_units: list of storage_unit-like ob...
331a0acbe670ce71341cc6fa3dd3ac4ae51e29b5
66,638
def _var_get_id(self, vname): """ Lookup var value by name or ID returns ISY Id or None """ if not self._vardict: self.load_vars() if isinstance(vname, IsyVar): return vname["id"] else: v = str(vname) if (v).upper() in self._vardict: # print("_get_var_id : " ...
17b3a47524cba6ff338ee830a820173ab942c34a
66,639
from re import T def sgd(cost, params, lr=1.0, alpha=0.1): """SGD with Momentum (and Langevin Dynamics)""" grads = T.grad(cost=cost, wrt=params) updates = [] for p, g in zip(params, grads): v = shared(p.get_value() * 0.) v_new = v * (1.0 - alpha) - alpha * lr * g updates.append...
a4eae61be3ca192553adda9ea829bd5997d4e900
66,640
def get_or_else(data, key, default_value = None): """ Tries to get a value from data with key. Returns default_value in case of key not found. """ if not data: return default_value try: return data[key] except: return default_value
53bc769a3331684c46127b08976fd62ca1ab47df
66,641
def update_rl_veh(env, rl_queue, rl_veh, removed_veh, control_range, num_rl, rl_ids): """Update the RL lists of controllable, entering, and exiting vehicles. Used by the open environments. Parameter...
616be730420795755d5b628284517572b0c2248f
66,642
def tree_BFS(root_node): """ My Python implementation of BFS for a tree Traverses a binary tree from its root and returns an array of the nodes in traversal order Time complexity: O(n), n = Number of nodes Space complexity: O(n) """ # Track BFS traversal bfs_traversal = [] # Queue for next nodes to explore...
349f4df805dee0c13bc3c58865b2fc3543528a53
66,643
import numpy import os def combine_habitat_contraints(args): """Build maps that will be used to constrain where habitats can be placed: Every constraint can be expressed as a mask that follows the same pattern: 1- Compute masks with limits dictated by the threshold's sign ...
094b35ed2d4b0b28f31ac6a4353e4e7abb539957
66,644
import functools def DeletionTest(f): """This indicates a test that uses deletion.""" @functools.wraps(f) def Decorator(testinstance): if testinstance.TEST_DELETION: return f(testinstance) else: return testinstance.skipTest("Tests that use deletion are disabled " ...
2f27803408a4a92e3f29def203845f27dfd0a113
66,645
def get_hyponyms(synset): """ Get the WordNet hyponyms that are in the model Params synset: nltk WordNet synset """ hyponyms = synset.hyponyms() # hyponym_terms = [hyponym.lemmas()[0].name() for hyponym in hyponyms] # hyponym_terms = [term for term in hyponym_terms if term in diction...
a0e28825869240868e0d48a02481d93b57aeee6a
66,646
def calc_frac(x, func, total=None): """ calculate the fraction of entries in *x* that satisfy *func* """ total = total or len(x) return np.count_nonzero(func(x)) / total
fba8c6b2eba855740adb8ebb2d5585af5ea644a9
66,647
from datetime import datetime def get_monthly_file_content_by_date(date: datetime) -> str: """ Get the content of the monthly trajectory summary file for a given date. :param date: The date to get the monthly file for. :return: The content of the monthly file. :raises: requests.HTTPError if the ...
35a1f57f952e94285ddea50bb623db2d25e71136
66,648
def get_frame(df, t, fps=20): """Gets the player data from the right frame Arguments: df: pd.DataFrame with player tracking data t: timestamp of the play fps: frame per second Returns: dfFrame: pd.DataFrame with player tracking data from timestamp t Raises: """ dfFrame = ...
51bad21aa17978bcfee37fe31edb79ddb45e9191
66,649
def MOE_batch_means(samples, log=False): """Assumes unkown mean, unknown variance, unknown distribution. Assumes 50 samples. Batches into 5 groups of 10 samples. Computes the 95 percent margin of error.""" if len(samples) == 0: return float('nan') batchSize = 10 batches = [samples[i:i+batchSize] for i in range(...
d7e9fc2cc2396e3072cc947bede43b0b8cde751c
66,650
import math def pformat_bar( value, width=40, prefix="", vmin=0., vmax=1., border=True, fill=' ', reverse=False): """Return a progressbar-like str representation of value. Parameters ========== value : float Value to be represented. width: int Bar width (in charac...
6b12a5bb2bd4d051224b2f5960a0378b0593b2f7
66,651
import functools def Elrn_chan(state, chan, data): """ External learning along a channel with data, as mulitset of predicates """ def lshift(a, b): return a << b freqs = [data(*data.sp.get(*a)) for a in np.ndindex(*data.sp.shape)] freq = sum(freqs) stats = [(data(*a) / freq) *...
62846791f085ccf2d03a11a7f6a1bdc69a3a3605
66,652
import select async def get_all_tenants(): """ Return all tenants """ query = select(Tenant) results = await DBSession.execute(query) return {"action": "get", "tenants": results.scalars().all()}
03de24fa79c8565d8409fa664f52e4b65ae84a78
66,653
import cmath import math def exp(x): """ Return the exponential value of x """ if isinstance(x,ADF): ad_funcs = list(map(to_auto_diff,[x])) x = ad_funcs[0].x ######################################## # Nominal value of the constructed ADF: f = exp(x) ...
3bbb7a29ae187f9450366e730cb13aec6da04bbc
66,654
def lab2xyz(lab_arr): """ Convert colur from CIE 1976 L*a*b* to CIE 1931 XYZ Parameters ---------- lab_arr: ndarray Color in CIE 1976 L*a*b* Returns ------ xyz_arr: ndarray Color in CIE 1931 XYZ """ L, a, b = lab_arr[:, 0], lab_arr[:, 1], lab_arr[:, 2] ...
08edc4ce78837369a87135e3cf4b35e2965f356d
66,655
def test_generator(func_graph, stack_roots): """Return the function that will start the fault-tolerance testing for a graph""" def test(self): """Test fault-tolerance of the topology""" self.set_up(func_graph, stack_roots) self.network_function() return test
1a607086ef68833894f8d031589c61dd8557f090
66,656
def gaussian2D(omega1, cent1, delta1, omega2, cent2, delta2, corr=0.0): """Two-dimensional complex Gaussian lineshape """ gamma1 = 0.0 gamma2 = 0.0 return voigt2D(omega1, cent1, delta1, gamma1, omega2, cent2, delta2, gamma2, corr=corr)
104e692401e87608cf235b21c8e79d5b8cb35f2c
66,657
from typing import List def create_msk_from_classes( mc_msk: np.ndarray, classes_to_use: List[int], out_msk_pix_value: int = 255, out_msk_dtype: np.dtype = np.uint16, ) -> np.ndarray: """ Create a mask of type out_msk_dtype set to the out_msk_pix_value for pixels belonging to the required ...
d1818935a9948090882431454dc04dc0d34b076f
66,658
def kmeans( s: pd.Series, n_clusters=5, init="k-means++", n_init=10, max_iter=300, tol=0.0001, precompute_distances="auto", verbose=0, random_state=None, copy_x=True, n_jobs=-1, algorithm="auto", ): """ Perform K-means clustering algorithm. """ vectors = l...
c28dcca61c637923a69dece2cc9b1b61d66526f0
66,659
def tile_read_utm(source, bounds, tilesize, indexes=[1], nodata=None, alpha=None, dst_crs='EPSG:3857', verbose=False, boundless=False): """Read data and mask. Arguments --------- source : str or :py:class:`rasterio.io.DatasetReader` input file path or :py:cla...
c16c89cc2d4c62c530f8f9ecafe73fb858a7f664
66,660
def __float2pcm(npy_array, _type='int16'): """Convert <npy_array> from float to pcm. Default conversion type is 'int16'. """ info = np.iinfo(_type) amp = 2**(info.bits - 1) offset = info.min + amp npy_array = npy_array * amp + offset return npy_array.clip(info.min, info.max).astype...
1d7e125740e77cce01ea15081d17bea0e397c82e
66,661
def force_str(s, encoding="ascii", errors="strict"): """Converts s to str (which is bytes on Python 2, and unicode on Python 3), using the provided encoding if necessary. If s is already str, it is returned as is. If errors="strict", str is bytes, and s is str, its encoding is verified by decoding it; ...
0b8b78f715923680bd56e025bded36fba98ee332
66,662
import csv def process_csv(csv_file): """Turn the contents of the CSV file into a list of lists""" print("Processing {}".format(csv_file)) with open(csv_file, "r") as datafile: data = list(csv.reader(datafile)) return data
87603c21d09332cc1e1d25a3de6074f984f95426
66,663
def _change_vname(match) -> str: """Change variable name using the match object from re. :param match: :return: String with the variable name translated """ return ( match.group('mup_pre') + _translate(match.group('vname')) + match.group('mup_post') )
e1c8a5c250a5bf0d67906e54d12a97067403fdb8
66,664
def weighted_average(values, weights=None): """Calculate the weighted mean average between two iterables of `values` and matching `weights`. If weights is ``None`` they will be autogenerated Args: values(iterable): Values to average, either `int` or `float` weights(iterable): Matching weigh...
465b63f02e3a7cf92737938e4352c154abbae911
66,665
import math def random_cartesian_from_polar(r_low, r_high): """ function that returns a random cartesian coordinates gives within the radius limits from polar coordinates """ # generate the polar angle between 0 <= x < 360 degree polar_angle = np.random.uniform(0, 360, 1)[0] # generate the radius...
0dc136ab0e56902625cba8a70ba76b782b7bab04
66,666
def unwrap_f(arg): """Multiprocessing pool.map requires a top-level function.""" return Corex.calculate_p_xi_given_y(*arg)
f3440ca4927eff696b95ed00bbf92b0e1a58f8a3
66,667
from typing import Union def precision_rate(true: np.ndarray, predicted: np.ndarray, condition: Union[bool, int, str, list, tuple, set]) -> float: """ compute precision rate, refer module description for calculation; :param true: numpy.ndarray(shape=(m), ), an array o...
671c00b4a3c5886a22d34a822564f7fd4e5bde17
66,668
def u3(self, theta, phi, lam, q): """Apply u3 to q.""" return self.append(U3Gate(theta, phi, lam), [q], [])
85f9da6a911e7ef8fbfb47771331843511d1b8fb
66,669
import re def new_exposures(out): """Scan rsync output for exposures to be transferred. Parameters ---------- out : :class:`str` Output from :command:`rsync`. Returns ------- :class:`set` The unique exposure numbers detected in `out`. """ e = set() e_re = re.c...
8fc8817fe0ad79c177473ec676853569d733ec65
66,670
def conv2d_reduce_sum(x, input_height, input_width, padding, strides): """Sums along the output dimensions in line with a convolution. For example, with a kernel size of 3, padding=`VALID`, and stride of 1, then with respect to each spatial dimension of the convolution (and disregarding class, batch and channe...
d7d345cf0b0c03144b173404d258a5d745793dd7
66,671
from typing import OrderedDict import os import logging import glob def getInputTasks(input_dir, stranded=False, has_control=False, require_peaks=True, mode='train'): """Dictionary specifying the various tasks for the profile model Args: input_dir (str): the path to dire...
7dfd1eacb7c959b12af94bd5446d58df59ea0534
66,672
def _find_relevant_examples(dataset, rule): """Find examples in `dataset` where `rule` could be used in a derivation.""" # TODO(petershaw): This could potentially be more effecient by pre-indexing # the dataset sources in a data structure such as a Trie. examples = [] for source_str, target_str in dataset: ...
6f0a1a00753e63295779e40f6515e8210c1b65f4
66,673
def violin_plot(df, class_masks, class_names, column_name, class_colors=None, alpha=1.0, transformation_function=None, pseudocount=0, y_label=None, figname=None, vert=True, yticks=None, figax=None, **kwargs): """Make a violin plot with len(class_masks) violins for the specified column from a DataFra...
76445f7d7bed5e503c5978c1aba602893ad389bd
66,674
from datetime import datetime def now(): """Current UTC datetime string suitable for use as a Solr dt field.""" return datetime.utcnow().isoformat(timespec='seconds') + 'Z'
390877fc1b7592df54300cb70b9b62590f1bd4c9
66,675
def get_classification(X, theta, temp_parameter): """ Makes predictions by classifying a given dataset Args: X - (n, d - 1) NumPy array (n data points, each with d - 1 features) theta - (k, d) NumPy array where row j represents the parameters of our model for label j ...
cce812d6511a197767c7c1c7cf6ad26f09c306c1
66,676
import base64 def create_message(sender, to, subject, message_text): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. Returns: An object ...
89f9ddde8d5a1161461078ab614c718d8ef6dd12
66,677
def get_int(buffer: bytes, offset: int) -> int: """ Returns an int at the specified offset. :param buffer: The buffer to get from. :param offset: The offset to use. :return: The int """ return _int_serialiser.deserialise_from_bytes(buffer[offset:offset + 4])
2f4830cf4693178e3992a861edc1bc234f3b85d4
66,678
def load_source_table(): """ Load table of arcline sources Returns ------- sources : Table """ src_file = arclines.__path__[0]+'/data/sources/arcline_sources.ascii' # Load sources = Table.read(src_file, format='ascii.fixed_width', comment='#') # Return return sources
ec1ccbeee783f3a47d76d1546d77772d38cc385f
66,679
def extract_batches_per_worker(federated_train_loader: sy.FederatedDataLoader): """Extracts the batches from the federated_train_loader and stores them in a dictionary (keys = data.location). Args: federated_train_loader: the connection object we use to send responses. back to th...
1a727d80c355d0cb5215c2c1b35416a36226984d
66,680
def clang_layer_packages(): """Packages for the clang layer.""" clang_tools = [ tool_names.binutils, tool_names.lib_cpp, ] packages = [] for tool in clang_tools: packages.extend(get_jessie_packages(jessie_tools()[tool])) return depset(packages).to_list()
4473a3038b52327d252cae4723c08d2b997b0b57
66,681
from typing import Generator def read_until( data: bytes, *, return_tail: bool = True ) -> Generator[tuple, bytes, bytes]: """ read until some bytes appear """ return (yield (Traps._read_until, data, return_tail))
277108459577218fd679b4ef44ae10ec9b009293
66,682
import re import subprocess def wait_for_operators(oc: str, kubeconfig_path: str) -> bool: """ Waits for enough Cluster Operators to report back healthy. The number of reporting Operators must be greater than the constant `MINIMUM_HEALTHY_OPERATORS` :param oc: The OpenShift Client binary :param k...
322dbc5ecf3c0587cf0152723f1c9c30ad893e0e
66,683
def clean_data(df): """Cleans the passed dataframe. Actions done while cleaning: - dropping all rows with missing location ids - dropping all rows where dropoff time is before pickup time - consider all location ids that map to the same zone as equivalent and replace them with a single value ...
f29a1d3784914c2dfcae1611c8860dbaa7f2a93c
66,684
def sort_by_scores(scores, features_list, topn=None): #实际在输入的时候scores=labels,features_list=[labels,logits],所以是按照labels进行排序 """Sorts example features according to per-example scores. Args: scores: A `Tensor` of shape [batch_size, list_size] representing the per-example scores. features_list: A list of...
3483225e319f083b23262aead39c76e6f15103fd
66,685
def _distance_sequence_from_scores(scores_1, scores_2): """ We want to compute the distance between two -local perturbation- models. To do this, we simply take the usual distance between two hmm models; the pretrained predictive model stays constant. The desired distance is the limiting value of t...
9a4488f157e8beaa9ad594467585063884800594
66,686
def polygon_clip(subjectPolygon, clipPolygon): """ Clip a polygon with another polygon. Args: subjectPolygon: a list of (x,y) 2d points, any polygon. clipPolygon: a list of (x,y) 2d points, has to be *convex* Note: **points have to be counter-clockwise ordered** Return: a list of (x,y) ...
1064e3f20c4145ac42484c8b4fc772e396032be2
66,687
import re import os def handle_spectrum( flmfile, fitsfile, objname, objid=None, runid=None, just_ask=False ): """ flmfile and fitsfile should be absolute paths, objname should be the name of the object. can be in folder format instead of DB format. Can optionally include objid or runid (for objects...
c702af733ffc3c3165b4b2dc9a52391c4d6291c3
66,688
def is_openbabel_molecule(obj): """Check whether an object is an `oddt.toolkits.ob.Molecule` instance. .. versionadded:: 0.6 """ return (hasattr(oddt.toolkits, 'ob') and isinstance(obj, oddt.toolkits.ob.Molecule))
1bf1cd6da46aab746f7d63d8f962c97cd5911ee0
66,689
def confirm(prompt=None, resp=False): """prompts for yes or no response from the user. Returns True for yes and False for no. 'resp' should be set to the default value assumed by the caller when user simply types ENTER. >>> confirm(prompt='Create Directory?', resp=True) Create Directory? [y]|n...
a5a6dcb89434aa7dbeac85ae1164b3912100bd4a
66,690
def streamline(mesh, field, startCoord, dLengthSteps, dataMesh=None, maxSteps=1000, verbose=False, coords=(0, 1)): """ Create a streamline from startCoord and following a vector field in up and down direction. """ xd, yd, vd = streamlineDir(mesh, field, startCoord, dLengthStep...
d01339b965c2e99c5fecd3f8df93e6025904b769
66,691
def wall_filter(gray): """ Filter walls Filter out walls from a grayscale image @Param image @Return image of walls """ ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) # noise removal kernel = np.ones((3,3),np.uint8) opening = cv2.morphologyEx(thres...
31d71c640aa229efc4384140b1bd6d502544827e
66,692
from typing import Tuple def FloatRangeTupleDataclassField(N=2, default: Tuple = (0.9, 0.999), min=0, max=1): """Returns a dataclass field with marshmallow metadata enforcing a `N`-dim. tuple with all values in given range. In particular, inputs must be N-dimensional tuples of purely numeric values withi...
2166b6aad243df5e9bc9d4b1ceb071cf00e7e5e0
66,693
import htmlentitydefs import re def xss_strip_all_tags(s): """ Strips out all HTML. """ return s def fixup(m): text = m.group(0) if text[:1] == "<": return "" # ignore tags if text[:2] == "&#": try: if text[:3] == "&#x": ...
f78dc85368c63e4ed0484add6755bb9645186d02
66,694
def safe_divide(numerator, denominator, eps=1e-7): """Avoid dividing by zero by adding a small epsilon.""" safe_denominator = tf.where(denominator == 0.0, eps, denominator) return numerator / safe_denominator
551b74f9c9404882585831c316980d36e3bb3359
66,695
def sentinel2_sr_cloud_mask(input_img): """Extract cloud mask from the Sentinel 2 SR QA60 band Parameters ---------- input_img : ee.Image Image from the COPERNICUS/S2_SR collection with a QA60 band. Returns ------- ee.Image Notes ----- Output image is structured to be ...
9b456f9b130d057cb7b2a811458e1cf426365037
66,696
def get_spacegroup(cell, positions, numbers, symprec=None): """Returns Pearson symbol and intl number corresponding to the given structure""" cell = (cell, positions, numbers) sg = spglib.get_spacegroup(cell, symprec=symprec or SYMPREC).split() return sg[0], int(sg[1][1:-1])
19d6e98cfe9fe2119bbd053a81622971f018ba90
66,697
def preprocess_idl_type_and_value(idl_type, cpp_value, extended_attributes): """Returns IDL type and value, with preliminary type conversions applied.""" idl_type = idl_type.preprocessed_type if idl_type.name == 'Promise': idl_type = IdlType('ScriptValue') if idl_type.base_type in ['long long', ...
cc270ba1b811fef6992c582cdd3e28ee04554434
66,698
def start_heterogeneous_tile( tile_name, pin_assignments, sites, equivalent_sites, ): """ Returns a new tile xml definition. Input parameters are: - tile_name: name to assign to the tile - pin_assignments: location of the pins to correctly build pin locations ...
f670e3deedd396b09a2f6a497f2f223e909413fb
66,699