content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List from typing import Tuple def get_validation_data_iter(data_loader: RawParallelDatasetLoader, validation_sources: List[str], validation_target: str, buckets: List[Tuple[int, int]], ...
826b5847fb55e61ba3a0b416643fbbc356a23b07
3,646,100
def _serialize_property( target_expr: str, value_expr: str, a_property: mapry.Property, auto_id: _AutoID, cpp: mapry.Cpp) -> str: """ Generate the code to serialize the property. The value as the property is given as ``value_expr`` and serialized into the ``target_expr``. :param ta...
3a5a7d7795dd771224d1fd5de8304844cd260fad
3,646,101
def read_raw_data(pattern): """:return X""" if isinstance(pattern, basestring): fpaths = glob.glob(pattern) elif isinstance(pattern, list): fpaths = pattern X = [] for fpath in fpaths: print 'loading file {} ... ' . format(fpath) X.extend(loadtxt(fpath)) return X
ae3f503db4b7f31a043dc4b611d9bf2393d7a352
3,646,102
def warp_affine_rio(src: np.ndarray, dst: np.ndarray, A: Affine, resampling: Resampling, src_nodata: Nodata = None, dst_nodata: Nodata = None, **kwargs) -> np.ndarray: """ Perform Affine warp ...
4843ce222535a93b1fa7d0fee10161dadaba290b
3,646,103
def encode_integer_leb128(value: int) -> bytes: """Encode an integer with signed LEB128 encoding. :param int value: The value to encode. :return: ``value`` encoded as a variable-length integer in LEB128 format. :rtype: bytes """ if value == 0: return b"\0" # Calculate the number o...
b74832115a58248f4a45a880f657de6dd38b0d8d
3,646,104
def google_sen_new(text_content): """ Analyzing Entity Sentiment in a String Args: text_content The text content to analyze """ # text_content = 'Grapes are good. Bananas are bad.' Available types: PLAIN_TEXT, HTML client = language_v1.LanguageServiceClient() type_ = enums.Document.Ty...
57c4020f35a344d7f264453571e3f8825e00206f
3,646,105
import subprocess def _create_ip_config_data(): """ This loads into a map the result of IPCONFIG command. """ map_ipconfigs = dict() curr_itf = "" proc = subprocess.Popen(['ipconfig', '/all'], stdout=subprocess.PIPE) for curr_line in proc.stdout.readlines(): curr_line = curr_li...
64d613dfa8c602f47974f053351094e97e5d1246
3,646,106
def simplify_polygon_by(points, is_higher, should_stop, refresh_node): """ Simplify the given polygon by greedily removing vertices using a given priority. This is generalized from Visvalingam's algorithm, which is described well here: http://bost.ocks.org/mike/simplify/ is_higher = functio...
b9ae05b2d146e78dbed36cc48df6cbd24c33fcbc
3,646,107
def get_builder(slug): """ Get the Builder object for a given slug name. Args: slug - The slug name of the installable software """ for builder in Index().index: if builder.slug == slug: return builder return False
d6013fb55d11be7a153b7a9e9f2bdd991b2a6304
3,646,108
def preprocess_normscale(patient_data, result, index, augment=True, metadata=None, normscale_resize_and_augment_function=normscale_resize_and_augment, testaug=False): """Normalizes scale and augments the data. Args: patient_data...
ea427a554d204da9857f3dacda9d6a3a96e4c107
3,646,109
def get_contact_lookup_list(): """get contact lookup list""" try: return jsonify(Contact.get_contact_choices()) except Exception as e: return e.message
e8d3a8f813366a16e86cf2eadf5acb7e235218de
3,646,110
def argmax(X, axis=None): """ Return tuple (values, indices) of the maximum entries of matrix :param:`X` along axis :param:`axis`. Row major order. :param X: Target matrix. :type X: :class:`scipy.sparse` of format csr, csc, coo, bsr, dok, lil, dia or :class:`numpy.matrix` :param axis: Speci...
b97cb16798e0d726fc21a76a2a3c6a02d284e313
3,646,111
import hashlib from re import T from re import A def posts(): """ Function accessed by AJAX to handle a Series of Posts """ try: series_id = request.args[0] except: raise HTTP(400) try: recent = request.args[1] except: recent = 5 table = s3db.cms_...
dc5b43016c3e50c52969c91505856941c951911b
3,646,112
def resolve_game_object_y_collision(moving, static): """Resolves a collision by moving an object along the y axis. Args: moving (:obj:`engine.game_object.PhysicalGameObject`): The object to move along the y axis. static (:obj:`engine.game_object.PhysicalGameObject`): The...
24d63b4fd9e4a37d22aceee01e6accc2a74e8ee4
3,646,113
def filter_all(fn, *l): """ Runs the filter function on all items in a list of lists :param fn: Filter function :param l: list of lists to filter :return: list of filtered lists >>> filter_all(lambda x: x != "", ['a'], ['b'], [""], ["d"]) [['a'], ['b'], [], ['d']] """ return [filter...
114b7b9bf9b22d55bd891a654318d4a49e30be51
3,646,114
def get_test_runners(args): """ Get Test Runners """ res = list() qitest_jsons = args.qitest_jsons or list() # first case: qitest.json in current working directory test_runner = get_test_runner(args) if test_runner: res.append(test_runner) # second case: qitest.json specified with --...
73d9b4e73935cd2c41c24bd1376ade9ea274f23d
3,646,115
def get_preselected_facets(params, all_categories): """ Resolve all facets that have been determined by the GET parameters. Args: params: Contains the categories/facets all_categories: Returns: dict: Contains all sorted facets """ ret_arr = {} iso_cat = params.get("isoC...
878f3ef05aaaa643782c6d50c6796bc503c0f8e6
3,646,116
def has_joined(*args: list, **kwargs) -> str: """ Validates the user's joining the channel after being required to join. :param args: *[0] -> first name :param kwargs: :return: Generated validation message """ first_name = args[0] text = f"{_star_struck}{_smiling_face_with_heart} بسیار خ...
d446da88a362c3821e25d0bee0e110ec0a906423
3,646,117
def depth_residual_regresssion_subnet(x, flg, regular, subnet_num): """Build a U-Net architecture""" """ Args: x is the input, 4-D tensor (BxHxWxC) flg represent weather add the BN regular represent the regularizer number Return: output is 4-D Tensor (BxHxWxC) """ ...
2c5d2cb03f60acc92f981d108b791a0e1215f5f6
3,646,118
def dist2(x, c): """ Calculates squared distance between two sets of points. Parameters ---------- x: numpy.ndarray Data of shape `(ndata, dimx)` c: numpy.ndarray Centers of shape `(ncenters, dimc)` Returns ------- n2: numpy.ndarray Squared distances between...
24a1b9a368d2086a923cd656923dc799726ed7f0
3,646,119
def process_name(i: int, of: int) -> str: """Return e.g. '| | 2 |': an n-track name with track `i` (here i=2) marked. This makes it easy to follow each process's log messages, because you just go down the line until you encounter the same number again. Example: The interleaved log of four processes th...
bc3e0d06544b61249a583b6fa0a010ec917c0428
3,646,120
def cards_db(db): """ CardsDB object that's empty. """ db.delete_all() return db
9649b309990325eca38ed89c6e9d499b41786dab
3,646,121
def _geo_connected(geo, rxn): """ Assess if geometry is connected. Right now only works for minima """ # Determine connectivity (only for minima) if rxn is not None: gra = automol.geom.graph(geo) conns = automol.graph.connected_components(gra) lconns = len(conns) els...
d5993b7083703746214e70d6d100857da99c6c02
3,646,122
def scale_to_range(image, dest_range=(0,1)): """ Scale an image to the given range. """ return np.interp(image, xp=(image.min(), image.max()), fp=dest_range)
a225b44dc05d71d8ccc380d26fb61d96116414da
3,646,123
def files(): """Hypothesis strategy for generating objects pyswagger can use as file handles to populate `file` format parameters. Generated values take the format: `dict('data': <file object>)`""" return file_objects().map(lambda x: {"data": x})
04e787502a043ffba08912724c9e29f84a6a416c
3,646,124
from typing import Optional from typing import Generator def get_histograms( query: Optional[str] = None, delta: Optional[bool] = None ) -> Generator[dict, dict, list[Histogram]]: """Get Chrome histograms. Parameters ---------- query: Optional[str] Requested substring in name. Only hi...
059792d045bdea84ff636a27de9a1d9812ae4c24
3,646,125
def energy_decay_curve_chu_lundeby( data, sampling_rate, freq='broadband', noise_level='auto', is_energy=False, time_shift=True, channel_independent=False, normalize=True, plot=False): """ This function combines Chu's and Lundeby's methods: ...
3e9711fbc47442a27fc339b3fb18ad6f21a44c91
3,646,126
def sinkhorn( p, q, metric="euclidean", ): """ Returns the earth mover's distance between two point clouds Parameters ---------- cloud1 : 2-D array First point cloud cloud2 : 2-D array Second point cloud Returns ------- distance : float The distance betwee...
93a4eb2383cfc4a2f462daf1b984d773c339aee7
3,646,127
def generate_s3_events(cluster_name, cluster_dict, config): """Add the S3 Events module to the Terraform cluster dict. Args: cluster_name (str): The name of the currently generating cluster cluster_dict (defaultdict): The dict containing all Terraform config for a given cluster. config ...
93af74bcd9b0c16fdfd1a3495bb709d84edb10a6
3,646,128
def cluster_seg(bt, seg_list, radius): """ Fetch segments which align themself for a given tolerance. """ cluster, seen_ix = [], set() for i, seg in enumerate(seg_list): if i not in seen_ix: sim_seg_ix = list(bt.query_radius([seg], radius)[0]) seen_ix |= set(sim_se...
37308331b41cd7d1e1b8717bf4c0d5a4ced55385
3,646,129
def stage_grid( Dstg, A, dx_c, tte, min_Rins=None, recamber=None, stag=None, resolution=1. ): """Generate an H-mesh for a turbine stage.""" # Change scaling factor on grid points # Distribute the spacings between stator and rotor dx_c = np.array([[dx_c[0], dx_c[1] / 2....
e19e07e61be0079559ee597475ce017f8f0a6189
3,646,130
def get_best_trial(trial_list, metric): """Retrieve the best trial.""" return max(trial_list, key=lambda trial: trial.last_result.get(metric, 0))
c5ddbb9ad00cddaba857d0d0233f6452e6702552
3,646,131
def make_registry_metaclass(registry_store): """Return a new Registry metaclass.""" if not isinstance(registry_store, dict): raise TypeError("'registry_store' argument must be a dict") class Registry(type): """A metaclass that stores a reference to all registered classes.""" def _...
c1c0426e4d47323ccd3ab80ff3917253858f1b0c
3,646,132
def bind11(reactant, max_helix = True): """ Returns a list of reaction pathways which can be produced by 1-1 binding reactions of the argument complex. The 1-1 binding reaction is the hybridization of two complementary unpaired domains within a single complex to produce a single unpseudoknotted prod...
45c74105e2f9733092aba3b55edd4dbaa8e9e26e
3,646,133
def get_all_movie_props(movies_set: pd.DataFrame, flag: int, file_path: str): """ Function that returns the data frame of all movie properties from dbpedia :param movies_set: data set of movies with columns movie id and movie dbpedia uri :param flag: 1 to generate the data frame from scratch and 0 to re...
f3b85ce0d5b0e0fa8f28a2f3e8ee7d69c2002ee1
3,646,134
def convert_to_clocks(duration, f_sampling=200e6, rounding_period=None): """ convert a duration in seconds to an integer number of clocks f_sampling: 200e6 is the CBox sampling frequency """ if rounding_period is not None: duration = max(duration//rounding_period, 1)*rounding_period ...
602b00af689cc25374b7debd39264b438de44baa
3,646,135
def account_approved(f): """Checks whether user account has been approved, raises a 401 error otherwise . """ def decorator(*args, **kwargs): if not current_user: abort(401, {'message': 'Invalid user account.'}) elif not current_user.is_approved: abort(401, {'mess...
e9f9e7bd15bd1df22540a6a42db95501a26fcce2
3,646,136
def multiply(x): """Multiply operator. >>> multiply(2)(1) 2 """ def multiply(y): return y * x return multiply
77d983090e03820d03777f1f69cfc7b0ef6d88a2
3,646,137
def tally_transactions(address, txs): """Calculate the net value of all deposits, withdrawals and fees :param address: Address of the account :param txs: Transactions JSON for the address :returns: The total net value of all deposits, withdrawals and fees """ send_total = 0 for item in txs...
6eaca1e7be11f9af254bcc491ff661413d8745f4
3,646,138
def expose(policy): """ Annotate a method to permit access to contexts matching an authorization policy. The annotation may be specified multiple times. Methods lacking any authorization policy are not accessible. :: @mitogen.service.expose(policy=mitogen.service.AllowParents()) de...
74caed36885e5ea947a2ecdac9a2cddf2f5f51b0
3,646,139
def _bytes_feature(value): """Creates a bytes feature from the passed value. Args: value: An numpy array. Returns: A TensorFlow feature. """ return tf.train.Feature( bytes_list=tf.train.BytesList( value=[value.astype(np.float32).tostring()]))
e13ac22bef91af7847aecdb558e849de27e89623
3,646,140
from typing import Union from typing import OrderedDict def get_cell_phase( adata: anndata.AnnData, layer: str = None, gene_list: Union[OrderedDict, None] = None, refine: bool = True, threshold: Union[float, None] = 0.3, ) -> pd.DataFrame: """Compute cell cycle phase scores for cells in the po...
9b379c42cd409893d51885f5580b26b9700547bf
3,646,141
def variational_lower_bound(prediction): """ This is the variational lower bound derived in Auto-Encoding Variational Bayes, Kingma & Welling, 2014 :param [posterior_means, posterior_logvar, data_means, data_logvar, originals] posterior_means: predicted means for the posterior ...
bcbc9a660f07fe677f823ee3aeb284817e94601d
3,646,142
import base64 def didGen(vk, method="dad"): """ didGen accepts an EdDSA (Ed25519) key in the form of a byte string and returns a DID. :param vk: 32 byte verifier/public key from EdDSA (Ed25519) key :param method: W3C did method string. Defaults to "dad". :return: W3C DID string """ if vk ...
9991491ab486d8960633190e3d3baa9058f0da50
3,646,143
import pickle def load_dataset(datapath): """Extract class label info """ with open(datapath + "/experiment_dataset.dat", "rb") as f: data_dict = pickle.load(f) return data_dict
3a0d8ef9c48036879b32ab0e74e52429418297c0
3,646,144
def deleteupload(): """Deletes an upload. An uploads_id is given and that entry is then removed from the uploads table in the database. """ uploads_id = request.args.get('uploads_id') if not uploads.exists(uploads_id=uploads_id): return bad_json_response( 'BIG OOPS: Somethi...
df18801b287569f1fa1114fc7059a415b82913d0
3,646,145
def read(fn, offset, length, hdfs=None): """ Read a block of bytes from a particular file """ with hdfs.open(fn, 'r') as f: f.seek(offset) bytes = f.read(length) logger.debug("Read %d bytes from %s:%d", len(bytes), fn, offset) return bytes
219ad06d0b111a14ff3f1ba895d516d4340ed1dd
3,646,146
from typing import Dict from pathlib import Path import json def load_json(filename: str) -> Dict: """Read JSON file from metadata folder Args: filename: Name of metadata file Returns: dict: Dictionary of data """ filepath = ( Path(__file__).resolve().parent.parent.joinpat...
37d9f08344cf2a544c12fef58992d781556a9efd
3,646,147
def get_riemann_sum(x, delta_x): """ Returns the riemann `sum` given a `function` and the input `x` and `delta_x` Parameters ---------- x : list List of numbers returned by `np.linspace` given a lower and upper bound, and the number of intervals delta_x : The inter...
dd80d12581533fa4074411845050f29193a03432
3,646,148
def MPO_rand(n, bond_dim, phys_dim=2, normalize=True, cyclic=False, herm=False, dtype=float, **mpo_opts): """Generate a random matrix product state. Parameters ---------- n : int The number of sites. bond_dim : int The bond dimension. phys_dim : int, optional ...
22220095b5cfcb3625edf3cde59e03fa37cd5423
3,646,149
def get_short_size(size_bytes): """ Get a file size string in short format. This function returns: "B" size (e.g. 2) when size_bytes < 1KiB "KiB" size (e.g. 345.6K) when size_bytes >= 1KiB and size_bytes < 1MiB "MiB" size (e.g. 7.8M) when size_bytes >= 1MiB size_bytes: File siz...
ebc9ba25c01dedf0d15b9e2a21b67989763bc8c8
3,646,150
def pair_setup( auth_type: AuthenticationType, connection: HttpConnection ) -> PairSetupProcedure: """Return procedure object used for Pair-Setup.""" _LOGGER.debug("Setting up new AirPlay Pair-Setup procedure with type %s", auth_type) if auth_type == AuthenticationType.Legacy: srp = LegacySRPAu...
6fbd0eb57bd3da8c70233d07393513036548482b
3,646,151
def score_from_srl(srl_path, truth_path, freq, verbose=False): """ Given source list output by PyBDSF and training truth catalogue, calculate the official score for the sources identified in the srl. Args: srl_path (`str`): Path to source list (.srl file) truth_path (`str`): Path to tra...
87cfdd7ed7c1a42fc3a4080289e7e34be6a2a85a
3,646,152
def get_feature_read(key, max_num_bbs=None): """Choose the right feature function for the given key to parse TFRecords Args: key: the feature name max_num_bbs: Max number of bounding boxes (used for `bounding_boxes` and `classes`) max_num_groups: Number of pre-defined groups (used f...
6ec7f06e900baedec19950c0f4742da9c4df1514
3,646,153
import numpy import time def kernel(cc, eris, t1=None, t2=None, max_cycle=50, tol=1e-8, tolnormt=1e-6, verbose=logger.INFO): """Exactly the same as pyscf.cc.ccsd.kernel, which calls a *local* energy() function.""" if isinstance(verbose, logger.Logger): log = verbose else: lo...
24917c48cbdb2062914462ad3f354cdd0e4e6318
3,646,154
import argparse def get_arguments(): """parse provided command line arguments""" parser = argparse.ArgumentParser() parser.add_argument( "--server", help="Where to send the output - use https URL to POST " "to the dognews server API, or a file name to save locally as json", ...
bc7aa7fefda65ade99820e786a460e07a5037f46
3,646,155
async def getAllDestinyIDs(): """Returns a list with all discord members destiny ids""" select_sql = """ SELECT destinyID FROM "discordGuardiansToken";""" async with (await get_connection_pool()).acquire(timeout=timeout) as connection: result = await conne...
22e94165cc0f50c8458be152d77231f30f7383b8
3,646,156
def login(): """Handles login for Gello.""" form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is not None and user.verify_password(form.password.data): login_user(user, form.remember_me.data) return red...
5000c52d652c114a5b69b403fca9809dfa9e6bca
3,646,157
def create_loss_functions(interconnector_coefficients, demand_coefficients, demand): """Creates a loss function for each interconnector. Transforms the dynamic demand dependendent interconnector loss functions into functions that only depend on interconnector flow. i.e takes the function f and creates g by...
1522b4506d4dad40e2b3d16bdd8ebd92d9b46401
3,646,158
def num2proto(pnum): """Protocol number to name""" # Look for the common ones first if pnum == 6: return "tcp" elif pnum == 17: return "udp" elif pnum == 1: return "icmp" elif pnum == 58: # Use the short form of icmp-ipv6 when appropriate return "icmpv6" ...
ad68b0fe530d63de62087eb23e5cacca0d48b996
3,646,159
def get_problem_size(problem_size, params): """compute current problem size""" if callable(problem_size): problem_size = problem_size(params) if isinstance(problem_size, (str, int, np.integer)): problem_size = (problem_size, ) current_problem_size = [1, 1, 1] for i, s in enumerate(pr...
c71394f081a7f0d00fcae653dffc439bc7b1b3b1
3,646,160
import zipfile import os def zip_dir(path): """ Create a zip archive containing all files and dirs rooted in path. The archive is created in memory and a file handler is returned by the function. Args: path: directory containing the resources to archive. Return: file_out: file han...
fd60182ca3854a922d44c16e87efde0f7671ce1b
3,646,161
def interpolate(x, size=None, scale_factor=None, mode='nearest', align_corners=False, align_mode=0, data_format='NCHW', name=None): """ This op resizes a batch of images. The input must be a 3-D ...
a9e03ecc89cdb623922984d3cce9b6cb114419b9
3,646,162
from datetime import datetime def encode_auth_token(user_id): """ Generates the Auth Token :return: string """ try: payload = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=90), 'iat': datetime.datetime.utcnow(), 'sub': user_id } ...
5239b2d85e3c4c1f4c6f74297118295c0bf7d532
3,646,163
from typing import List from typing import Tuple from typing import Dict def build_docs_for_packages( current_packages: List[str], docs_only: bool, spellcheck_only: bool, for_production: bool, jobs: int, verbose: bool, ) -> Tuple[Dict[str, List[DocBuildError]], Dict[str, List[SpellingError]]]:...
c4196c139fda703c90c60507156cce8cb29da98e
3,646,164
def _inspect_output_dirs_test(ctx): """Test verifying output directories used by a test.""" env = analysistest.begin(ctx) # Assert that the output bin dir observed by the aspect added by analysistest # is the same as those observed by the rule directly, even when that's # under a config transition ...
de14b2d4514792d4b2427ff3ef4fae6e7af8e31d
3,646,165
import ray def wait(object_refs, num_returns=1, timeout=None): """Return a list of IDs that are ready and a list of IDs that are not. This method is identical to `ray.wait` except it adds support for tuples and ndarrays. Args: object_refs (List[ObjectRef], Tuple(ObjectRef), np.array(ObjectRe...
e56ffd1700715049cc899d27735bb98da47fa2b6
3,646,166
def train( data, feature_names, tagset, epochs, optimizer, score_func=perceptron_score, step_size=1, ): """ Trains the model on the data and returns the parameters :param data: Array of dictionaries representing the data. One dictionary for each data point (as created by the ...
51a0a506deecf56067ef185848d7f706c9da0d3e
3,646,167
def summed_timeseries(timeseries): """ Give sum of value series against timestamps for given timeseries containing several values per one timestamp :param timeseries: :return: """ sum_timeseries = [] for i in range(len(timeseries)): if len(timeseries[i])>1: sum_timeserie...
618505f8f0960900a993bb6d9196d17bf31d02a6
3,646,168
import pathlib def path_check(path_to_check): """ Check that the path given as a parameter is an valid absolute path. :param path_to_check: string which as to be checked :type path_to_check: str :return: True if it is a valid absolute path, False otherwise :rtype: boolean """ path = p...
41b3537b0be2c729ba993a49863df4a15119db8b
3,646,169
from typing import Union from typing import Sequence from typing import Optional from typing import Dict from typing import Any from datetime import datetime from typing import List def _path2list( path: Union[str, Sequence[str]], boto3_session: boto3.Session, s3_additional_kwargs: Optional[Dict[str, Any]...
542d41ce29f71e3209d702eab157a75fa40650c0
3,646,170
import torch def e_greedy_normal_noise(mags, e): """Epsilon-greedy noise If e>0 then with probability(adding noise) = e, multiply mags by a normally-distributed noise. :param mags: input magnitude tensor :param e: epsilon (real scalar s.t. 0 <= e <=1) :return: noise-multiplier. """ if...
e2e9f8f49e7d3e6b2319aaa6a869f24aa3047946
3,646,171
def beam_area(*args): """ Calculate the Gaussian beam area. Parameters ---------- args: float FWHM of the beam. If args is a single argument, a symmetrical beam is assumed. If args has two arguments, the two arguments are bmaj and bmin, the width of the major and min...
93c4616018a098199a47fb25038cb88707444864
3,646,172
def get_settlement_amounts( participant1, participant2 ): """ Settlement algorithm Calculates the token amounts to be transferred to the channel participants when a channel is settled. !!! Don't change this unless you really know what you are doing. """ total_available_deposit ...
e4bddfccbced0235b1d5265519208cef5167013d
3,646,173
import time def timefunc(f): """Simple timer function to identify slow spots in algorithm. Just import function and put decorator @timefunc on top of definition of any function that you want to time. """ def f_timer(*args, **kwargs): start = time.time() result = f(*args, **kwargs) ...
56d5d052fa559e1b7c797ed00ee1b82c8e2126d6
3,646,174
def rdr_geobox(rdr) -> GeoBox: """ Construct GeoBox from opened dataset reader. """ h, w = rdr.shape return GeoBox(w, h, rdr.transform, rdr.crs)
0c22ff869faa2988e63a4b13d17c8f5ba7343ffc
3,646,175
def sequence(lst: Block[Result[_TSource, _TError]]) -> Result[Block[_TSource], _TError]: """Execute a sequence of result returning commands and collect the sequence of their response.""" return traverse(identity, lst)
d228237edc95a4d2c4ef1c9591af41a639c42a6d
3,646,176
def keyword_dct_from_block(block, formatvals=True): """ Take a section with keywords defined and build a dictionary for the keywords assumes a block that is a list of key-val pairs """ key_dct = None if block is not None: block = ioformat.remove_whitespace(block) key_va...
929defe8d07fff4bf50f1167c0749a6e19d9ecb2
3,646,177
def get_geocode(args): """ Returns GPS coordinates from Google Maps for a given location. """ result = Geocoder.geocode(args.address) lat, lon = result[0].coordinates lat = round(lat, 6) lon = round(lon, 6) return (lat, lon)
1ef5d89a1157bbbe381ac1e4500e198735b71898
3,646,178
def mice(data, **kwargs): """Multivariate Imputation by Chained Equations Reference: Buuren, S. V., & Groothuis-Oudshoorn, K. (2011). Mice: Multivariate Imputation by Chained Equations in R. Journal of Statistical Software, 45(3). doi:10.18637/jss.v045.i03 Implementation follows th...
e2046350d071a1cc17bc23077c0be2d0939371b5
3,646,179
from sys import flags def SaveFlagValues(): """Returns copy of flag values as a dict. Returns: Dictionary mapping keys to values. Keys are flag names, values are corresponding __dict__ members. E.g. {'key': value_dict, ...}. """ if hasattr(flags, '_FlagValues'): # pylint:disable=protected-access ...
c49bfee49a9c2531c4315831e247b83f2086b592
3,646,180
def estimate_purity_err(dim: int, op_expect: np.ndarray, op_expect_var: np.ndarray, renorm=True): """ Propagate the observed variance in operator expectation to an error estimate on the purity. This assumes that each operator expectation is independent. :param dim: dimension of the Hilbert space :p...
da317a0f59ce2a13c6c3842a255acfd63a54046c
3,646,181
from functools import reduce def get_next_code(seen, server_ticket=0): """Find next unused assertion code. Called by: SConstruct and main() Since SConstruct calls us, codes[] must be global OR WE REPARSE EVERYTHING """ if not codes: (_, _, seen) = read_error_codes() if server_ticket:...
b2aeef05725137208e8aaef213f1bf68eb673e06
3,646,182
import asyncio def getEnergyUsage(): """Query plug for energy usage data. Runs as async task. :return: json with device energy data """ energy_data = asyncio.run(plug.get_emeter_realtime()) return energy_data
43fe5814de6776052c8c48ac65e9df8893956ef6
3,646,183
def get_sequence_from_kp(midi): """ Get the reduced chord sequence from a kp KP-corpus file. Parameters ========== midi : pretty_midi A pretty_midi object representing the piece to parse. Returns ======= chords : list The reduced chord sequence from the give...
fd11658607e44151fbd6eaec08bff4ce510e8ba5
3,646,184
def get_bw_range(features): """ Get the rule-of-thumb bandwidth and a range of bandwidths on a log scale for the Gaussian RBF kernel. :param features: Features to use to obtain the bandwidths. :return: Tuple consisting of: * rule_of_thumb_bw: Computed rule-of-thumb bandwidth. * bws: Li...
2e954badf9e529bd0c62449c34a631d5be87950b
3,646,185
def gen_endpoint(endpoint_name, endpoint_config_name): """ Generate the endpoint resource """ endpoint = { "SagemakerEndpoint": { "Type": "AWS::SageMaker::Endpoint", "DependsOn": "SagemakerEndpointConfig", "Properties": { "EndpointConfigName": ...
bc658e6aebc41cfddefe0e77b2d65748a84789c5
3,646,186
import yaml import os def load_config(): """ Load configuration and set debug flag for this environment """ # Load global configuration config = yaml.load(open(os.path.abspath('./conf/global.yaml'), 'r').read()) # Detect development or production environment and configure accordingly if os.e...
2b629de582cc527a92ad3d2a314c989ec939fbc1
3,646,187
def read_dataframe(df, smiles_column, name_column, data_columns=None): """Read molecules from a dataframe. Parameters ---------- df : pandas.DataFrame Dataframe to read molecules from. smiles_column : str Key of column containing SMILES strings or rdkit Mol objects. name_column ...
d27e01e38132818f0bb740fc0033f22949e9fa79
3,646,188
from typing import List def dummy_awsbatch_cluster_config(mocker): """Generate dummy cluster.""" image = Image(os="alinux2") head_node = dummy_head_node(mocker) compute_resources = [ AwsBatchComputeResource(name="dummy_compute_resource1", instance_types=["dummyc5.xlarge", "optimal"]) ] ...
ff9c24e90faf92758a83c3529d261c901b614b01
3,646,189
def float_or_none(val, default=None): """ Arguments: - `x`: """ if val is None: return default else: try: ret = float(val) except ValueError: ret = default return ret
00beabbd2fe4633e6738fea2220d55d096bfa91e
3,646,190
def user_get_year_rating(user_id: int): """ Get the last step user was at :param user_id: :return: str """ try: con = psconnect(db_url, sslmode='require') cursor = con.cursor() cursor.execute("SELECT year,rating FROM users WHERE uid = %s", (user_id,)) result = cur...
4911d5d0ea8f99b1d889d048aa31825452b3f3fe
3,646,191
from pymco import message def msg_with_data(config, filter_): """Creates :py:class:`pymco.message.Message` instance with some data.""" # Importing here since py-cov will ignore code imported on conftest files # imports with mock.patch('time.time') as time: with mock.patch('hashlib.sha1') as sh...
3bb50370512e58fce6c098ed2144b7406cc6eab4
3,646,192
import os def get_image_names(): """ Returns (image_names, covid_image_names, normal_image_names, virus_image_names), where each is a list of image names """ image_names = os.listdir(DEFAULT_IMG_PATH_UNEDITED) # Remove directories image_names.remove("COVID-19") image_names.remove("Nor...
42fcd4d570f90a9b22217559c1d942f399852363
3,646,193
def api_connect_wifi(): """ Connect to the specified wifi network """ res = network.wifi_connect() return jsonify(res)
1a8832bb67bb1d5b73357b9b1359f6c1835f3c85
3,646,194
from typing import List async def get_sinks_metadata(sinkId: str) -> List: # pylint: disable=unused-argument """Get metadata attached to sinks This adapter does not implement metadata. Therefore this will always result in an empty list! """ return []
458b674cc59a80572fd9676aec81d0a7c353a8f3
3,646,195
def fn_lin(x_np, *, multiplier=3.1416): """ Linear function """ return x_np * multiplier
e64f112b486ea6a0bdf877d67c98417ae90f03b3
3,646,196
def get_MACD(df, column='Close'): """Function to get the EMA of 12 and 26""" df['EMA-12'] = df[column].ewm(span=12, adjust=False).mean() df['EMA-26'] = df[column].ewm(span=26, adjust=False).mean() df['MACD'] = df['EMA-12'] - df['EMA-26'] df['Signal'] = df['MACD'].ewm(span=9, adjust=Fal...
b5eb25c9a5097fb2a0d874d62b6ab1957bbe3f11
3,646,197
def from_pyGraphviz_agraph(A, create_using=None): """Returns a EasyGraph Graph or DiGraph from a PyGraphviz graph. Parameters ---------- A : PyGraphviz AGraph A graph created with PyGraphviz create_using : EasyGraph graph constructor, optional (default=None) Graph type to create. If g...
66f57a2864f87342c84452336da647fb7489ec66
3,646,198
from typing import Collection import copy def get_textbox_rectangle_from_pane(pane_rectangle: GeometricRectangle, texts: Collection[str], direction: str) -> GeometricRectangle: """ Args: pane_rectangle: texts: direction: Returns: """ n...
9e0a3bb2f0a93312d17096fe36d1b0529b5b47e6
3,646,199