content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def backproject_to_plane(cam, img_pt, plane): """Back an image point to a specified world plane""" # map to normalized image coordinates npt = np.matrix(npl.solve(cam[0], np.array(list(img_pt)+[1.0]))) M = cam[1].transpose() n = np.matrix(plane[:3]).flatten() d = plane.flat[3] Mt = M * cam[2...
47ae45103460db5a5447900dda10783c8f92362e
3,640,100
from datetime import datetime def format_cell(cell, datetime_fmt=None): """Format a cell.""" if datetime_fmt and isinstance(cell, datetime): return cell.strftime(datetime_fmt) return cell
8d3fb41bb3d7d3f3b341482e2d050d32092118bf
3,640,101
def optimize(gradients, optim, global_step, summaries, global_norm=None, global_norm_clipped=None, appendix=''): """Modified from sugartensor""" # Add Summary if summaries is None: summaries = ["loss", "learning_rate"] # if "gradient_norm" in summaries: # if global_norm is None: # ...
4887d45d5b9eb5a96008daeab5d11c97afed27fd
3,640,102
def _get_desired_asg_capacity(region, stack_name): """Retrieve the desired capacity of the autoscaling group for a specific cluster.""" asg_conn = boto3.client("autoscaling", region_name=region) tags = asg_conn.describe_tags(Filters=[{"Name": "value", "Values": [stack_name]}]) asg_name = tags.get("Tags"...
cdcec8493333a001fe3883b0c815da521c571f7a
3,640,103
def _default_geo_type_precision(): """ default digits after decimal for geo types """ return 4
eef082c8a8b38f4ede7bfb5d631b2679041b650c
3,640,104
import scipy def load_movietimes(filepath_timestamps, filepath_daq): """Load daq and cam time stamps, create muxer""" df = pd.read_csv(filepath_timestamps) # DAQ time stamps with h5py.File(filepath_daq, 'r') as f: daq_stamps = f['systemtime'][:] daq_sampleinterval = f['samplenumber'][...
4d54f7378f3d189a5bea4c14f68d5556958ba4f3
3,640,105
def is_valid_hotkey(hotkey: str) -> bool: """Returns True if hotkey string is valid.""" mode_opts = ["press", "click", "wheel"] btn_opts = [b.name for b in Button] wheel_opts = ["up", "down"] hotkeylist = hotkey[2:].split("_") if len(hotkeylist) == 0 or len(hotkeylist) % 2 != 0: return ...
2fb47b3f77b4cb3da2b70340b6ed96bd03c0bd14
3,640,106
def find_range_with_sum(values : list[int], target : int) -> tuple[int, int]: """Given a list of positive integers, find a range which sums to a target value.""" i = j = acc = 0 while j < len(values): if acc == target: return i, j elif acc < target: acc += values...
d54f185c98c03f985724a29471ecb1e301c14df5
3,640,107
def output_AR1(outfile, fmri_image, clobber=False): """ Create an output file of the AR1 parameter from the OLS pass of fmristat. Parameters ---------- outfile : fmri_image : ``FmriImageList`` or 4D image object such that ``object[0]`` has attributes ``coordmap`` and ``shape`` cl...
b805e73992a51045378d5e8f86ccf780d049002b
3,640,108
def feature_bit_number(current): """Fuzz bit number field of a feature name table header extension.""" constraints = UINT8_V return selector(current, constraints)
4a2103f399765aec9d84c8152922db3801e4a718
3,640,109
def render_page(context, slot, payload): # pylint: disable=R0201,W0613 """ Base template slot """ chapter = request.args.get('chapter', '') module = request.args.get('module', '') page = request.args.get('page', '') try: if page: return render_template(f"{chapter.lower()}/{modul...
69e5a837d90084b4c215ff75fb08a47aab1cff97
3,640,110
def add_stripe_customer_if_not_existing(f): """ Decorator which creates user as a customer if not already existing before making a request to the Stripe API """ @wraps(f) def wrapper(user: DjangoUserProtocol, *args, **kwargs): user = create_customer(user) return f(user, *args, **kwar...
676e9fad5de545a2627d52942917a49af3c6539d
3,640,111
def debug(): """ Import the test utils module to be able to: - Use the trace tool and get context variables after making a request to Apigee """ return ApigeeApiTraceDebug(proxy=config.PROXY_NAME)
0639a52e1a838b0408a820dd29ae4a08f89b0adc
3,640,112
def FromModuleToDoc(importedMod,filDfltText): """ Returns the doc string of a module as a literal node. Possibly truncated so it can be displayed. """ try: docModuAll = importedMod.__doc__ if docModuAll: docModuAll = docModuAll.strip() # Take only the firs...
e79882283e232166df67a1a5333e60fcdb2a136f
3,640,113
def noisify_patternnet_asymmetric(y_train, noise, random_state=None): """ mistakes in labelling the land cover classes in PatternNet dataset cemetery -> christmas_tree_fram harbor <--> ferry terminal Den.Res --> costal home overpass <--> intersection park.space --> park.lot runway_mark --> p...
ef37d5c39081cba489076956c0cd948a93ba0387
3,640,114
def group_superset_counts(pred, label): """ Return TP if all label spans appear within pred spans :param pred, label: A group, represeted as a dict :return: A Counts namedtuple with TP, FP and FN counts """ if (pred["label"] != label["label"]): return Counts(0, 1, 1) for label_span i...
8fddd5cfdb0050e97ec60d37e4d939b40cf5d891
3,640,115
def other(): """ Queries all of the logged in user's Campaigns and plugs them into the campaigns template """ entities = db.session.query(Entity) entities = [e.to_dict() for e in entities] return render_template('other.html', entities=entities)
7c7613f919bf5eecc223cf90715e9bd2ae6eb130
3,640,116
def rel_angle(vec_set1, vec_set2): """ Calculate the relative angle between two vector sets Args: vec_set1(array[array]): an array of two vectors vec_set2(array[array]): second array of two vectors """ return vec_angle(vec_set2[0], vec_set2[1]) / vec_angle(vec_set1[0], vec_set1[1]) ...
af89a10e26968f53200294919d8b72b532aa3522
3,640,117
def check_position_axes(chgcar1: CHGCAR, chgcar2: CHGCAR) -> bool: """Check the cell vectors and atom positions are same in two CHGCAR. Parameters ----------- chgcar1, chgcar2: vaspy.CHGCAR Returns ------- bool """ cell1 = chgcar1.poscar.cell_vecs cell2 = chgcar2.poscar.cell_v...
29eabfd72a664c77d55164953b6819f3eabd72f1
3,640,118
def path_shortest(graph, start): """ Pythonic minheap implementation of dijkstra's algorithm """ # Initialize all distances to infinity but the start one. distances = {node: float('infinity') for node in graph} distances[start] = 0 paths = [(0, start)] while paths: current_distance, cu...
32fe7df3fb02c3a0c3882f5cc5135417c5193985
3,640,119
import urllib import json def request(url, *args, **kwargs): """Requests a single JSON resource from the Wynncraft API. :param url: The URL of the resource to fetch :type url: :class:`str` :param args: Positional arguments to pass to the URL :param kwargs: Keyword arguments (:class:`str`) to pass...
66f23e5a15b44b5c9bc0777c717154749d25987e
3,640,120
def destagger(var, stagger_dim, meta=False): """Return the variable on the unstaggered grid. This function destaggers the variable by taking the average of the values located on either side of the grid box. Args: var (:class:`xarray.DataArray` or :class:`numpy.ndarray`): A variable ...
89bb08618fa8890001f72a43da06ee8b15b328be
3,640,121
from typing import Optional from typing import Dict from typing import Any def predict_pipeline_acceleration( data: arr_t, sampling_rate: float, convert_to_g: Optional[bool] = True, **kwargs ) -> Dict[str, Any]: """Apply sleep processing pipeline on raw acceleration data. This function processes raw acce...
f714a29925c2733d0e8baf8d95b2884bf9d98e6e
3,640,122
def create_blueprint(request_manager: RequestManager, cache: Cache, dataset_factory: DatasetFactory): """ Creates an instance of the blueprint. """ blueprint = Blueprint('metadata', __name__, url_prefix='/metadata') @cache.memoize() def _get_method_types_per_approach(): ...
32693a6286e4ffb15e4820dbd7ad5fdbe6632e95
3,640,123
def sides(function_ast, parameters, function_callback): """ Given an ast, parses both sides of an expression. sides(b != c) => None """ left = side(function_ast['leftExpression'], parameters, function_callback) right = side(function_ast['rightExpression'], parameters, function_callback) ...
9ed00100122f821340a0db37e77bfcf786eacdf9
3,640,124
def print_url(host, port, datasets): """ Prints a list of available dataset URLs, if any. Otherwise, prints a generic URL. """ def url(path = None): return colored( "blue", "http://{host}:{port}/{path}".format( host = host, port = por...
37d58dce1672f60d72936d6e1b9644fdd5ab689f
3,640,125
def get_default_sample_path_random(data_path): """Return path to sample with default parameters as suffix""" extra_suffix = get_default_extra_suffix(related_docs=False) return get_default_sample_path(data_path, sample_suffix=extra_suffix)
54220840dc6ef1831859a60058506e7503effcb7
3,640,126
def VectorShadersAddMaterialDesc(builder, materialDesc): """This method is deprecated. Please switch to AddMaterialDesc.""" return AddMaterialDesc(builder, materialDesc)
0aaec1d3e14536a65c9cb876075d12348176096c
3,640,127
import math def phase_randomize(D, random_state=0): """Randomly shift signal phases For each timecourse (from each voxel and each subject), computes its DFT and then randomly shifts the phase of each frequency before inverting back into the time domain. This yields timecourses with the same power ...
d8f3230acdf8b3df98995adaadc92f41497a27ea
3,640,128
def monospaced(text): """ Convert all contiguous whitespace into single space and strip leading and trailing spaces. Parameters ---------- text : str Text to be re-spaced Returns ------- str Copy of input string with all contiguous white space replaced with ...
51f07908dde10ef67bd70b5eb65e03ee832c3755
3,640,129
def molecule_block(*args, **kwargs): """ Generates the TRIPOS Mol2 block for a given molecule, returned as a string """ mol = Molecule(*args, **kwargs) block = mol.molecule_block() + mol.atom_block() + mol.bond_block() + '\n' return block
79ebf821e105666fb81396197fa0f218b2cf3e48
3,640,130
def setup_test_env(settings_key='default'): """Allows easier integration testing by creating RPC and HTTP clients :param settings_key: Desired server to use :return: Tuple of RPC client, HTTP client, and thrift module """ return RpcClient(handler), HttpClient(), load_module(settings_key)
827a71692dd2eb9946db34289dcf48d5b5d4415b
3,640,131
from typing import List from typing import Tuple def calculateCentroid( pointCloud : List[Tuple[float, float, float]] ) -> Tuple[float, float, float]: """Calculate centroid of point cloud. Arguments -------------------------------------------------------------------------- pointCloud (flo...
0e8d6d578a0a983fe1e68bff22c5cc613503ee76
3,640,132
def timber_load(): """ Calculate Timber's IO load since the last call """ #io(read_count=454556, write_count=3456, read_bytes=110592, write_bytes=0) global timber_io_stat try: new_stat = p.get_io_counters() readCount = new_stat.read_count - timber_io_stat.read_count write...
eebd8c3b0cc48b01f361de0455c34daee5942ea9
3,640,133
def get_num_uniq_users(csv_file, userid_col): """ A Helper function to help get the number of unique users :param csv_file: path to CSV file :param userid_col: Column for user ID :return: """ # Read the CSV file using pandas df = pd.read_csv(csv_file) # Use the nunique() method to g...
ade25596bb308414c80e1aea87d412bd5a340288
3,640,134
def generate_graph_batch(n_examples, sample_length): """ generate all of the training data Parameters ---------- n_examples: int Num of the samples sample_length: int Length of the samples. # TODO we should implement samples of different lens as in the DeepMind example. ...
8f98b86e069070a44c84368592a023311ebcdc7d
3,640,135
from zooniverse_web.models import Survey, QuestionResponse, Response, QuestionOption from zooniverse_web.utility.survey import generate_new_survey def administration(request): """Administration actions ((re)train acton predictor for a new survey) Parameters ---------- request: POST request ...
7d5a08450c9058f6fd33a13fc4cf6b714bc7e657
3,640,136
from typing import Counter def checkout(skus): """ Calculate the total amount for the checkout based on the SKUs entered in :param skus: string, each char is an item :return: int, total amount of the cart, including special offers """ total = 0 counter = Counter(skus) # got through t...
ad00a9c3e3cd4f34cfd7b5b306d3863decc0751b
3,640,137
def func_tradeg(filename, hdulist=None, whichhdu=None): """Return the fits header value TELRA in degrees. """ hdulist2 = None if hdulist is None: hdulist2 = fits.open(filename, 'readonly') else: hdulist2 = hdulist telra = fitsutils.get_hdr_value(hdulist2, 'TELRA') if hdulis...
4e6751d2eb0ac9e6264f768e932cbd42c2fc2c4e
3,640,138
def column_indexes(column_names, row_header): """項目位置の取得 Args: column_names (str): column name row_header (dict): row header info. Returns: [type]: [description] """ column_indexes = {} for idx in column_names: column_indexes[idx] = row_header.index(column_names...
4205e31e91cd64f833abd9ad87a02d91eebc8c61
3,640,139
import logging import pickle def dmx_psrs(caplog): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ caplog.set_level(logging.CRITICAL) psrs = [] for p in psr_names: with open(datadir+'/{0}_ng9yr_dmx_DE436_epsr.pkl'.format(p), 'rb') as fin: ...
6bbb5df017374f207d7c9338a737212f5c7e5b23
3,640,140
def fit_stats(act_map, param, func=KentFunc): """Generate fitting statistics from scipy's curve fitting""" phi_grid, theta_grid = meshgrid(phi_arr, theta_arr) Xin = np.array([theta_grid.flatten(), phi_grid.flatten()]).T fval = act_map.flatten() fpred = func(Xin, *param) # KentFunc res = fval - ...
97e4223daf3e140f1a091491f18012840b8c006a
3,640,141
def conv2d_for_hpool_valid_width_wrapper(inputs,filters,strides,padding,**kwargs): """ Wraps tf.layers.conv2d to allow valid convolution across signal width and 'same' convolution across signal height when padding is set to "valid_time" Arguments: inputs (TF Tensor): Tensor input. filters (TF...
9b4438c687232245e645ea5714e7ad7899ecd98b
3,640,142
import copy def resample_cells(tree, params, current_node = 'root', inplace = False): """ Runs a new simulation of the cell evolution on a fixed tree """ if not inplace: tree = copy.deepcopy(tree) for child in tree.successors(current_node): initial_cell = tree.nodes[current_node][...
10cde9abdf3a6271aa20276c3e193b1c93ca7908
3,640,143
def get_sql_query(table_name:str) -> str: """Fetch SQL query file for generation of dim or fact table(s)""" f = open(f'./models/sql/{table_name}.sql') f_sql_query = f.read() f.close() return f_sql_query
fc3308eae51b7d10667a50a0f4ee4e295bfea8d0
3,640,144
def _map_args(call_node, function): """Maps AST call nodes to the actual function's arguments. Args: call_node: ast.Call function: Callable[..., Any], the actual function matching call_node Returns: Dict[Text, ast.AST], mapping each of the function's argument names to the respective AST node. "...
b19befded386e6081be9858c7eb31ffd45c96ef3
3,640,145
def sub_bases( motif ): """ Return all possible specifications of a motif with degenerate bases. """ subs = {"W":"[AT]", \ "S":"[CG]", \ "M":"[AC]", \ "K":"[GT]", \ "R":"[AG]", \ "Y":"[CT]", \ "B":"[CGT]", \ "D":"[AGT]", \ "H":"[ACT]", \ "V":"[ACG]", \ "N":"[ACGTN]"} for symbol,...
10ff2ea1959aba103f1956398afb5f1d8801edd7
3,640,146
import logging def parse(input_file_path): """ Parse input file :param input_file_path: input file path :return: Image list """ verticals, horizontals = 0, 0 logging.info("parsing %s", input_file_path) with open(input_file_path, 'r') as input_file: nb = int(input_file.readline(...
ecd4fd066d1128f385da59965a93e59c038052bd
3,640,147
def char(ctx, number): """ Returns the character specified by a number """ return chr(conversions.to_integer(number, ctx))
5c5254978055f690b6801479b180ff39b31e2248
3,640,148
import re import logging async def get_character_name(gear_url, message): """ It is *sometimes* the case that discord users don't update their username to be their character name (eg for alts). This method renders the gear_url in an HTML session and parses the page to attempt to find the charact...
cdd18e0123f226d2c59d41bbf39e0dfc02188d73
3,640,149
import pandas def get_treant_df(tags, path='.'): """Get treants as a Pandas DataFrame Args: tags: treant tags to identify the treants path: the path to search for treants Returns: a Pandas DataFrame with the treant name, tags and categories >>> from click.testing import CliRunner ...
a5972646e27ffd88d18f1c0d212a2ae081ebe4f1
3,640,150
def gather_keypoints(keypoints_1, keypoints_2, matches): """ Gather matched keypoints in a (n x 4) array, where each row correspond to a pair of matching keypoints' coordinates in two images. """ res = [] for m in matches: idx_1 = m.queryIdx idx_2 = m.trainIdx pt...
5abef87c570493b57e81dcddc2732ed541aa6a08
3,640,151
async def stop(): """ Stop any playing audio. """ Sound.stop() return Sound.get_state()
3c7ea7aae3e8dd7e3b33ddd9beed0ce2182800bc
3,640,152
def is_numeric(X, compress=True): """ Determine whether input is numeric array Parameters ---------- X: Numpy array compress: Boolean Returns ------- V: Numpy Boolean array if compress is False, otherwise Boolean Value """ def is_float(val): try: float(v...
ad28657f51680cd193671a6a8a8da6a91390dc15
3,640,153
def figure_ellipse_fitting(img, seg, ellipses, centers, crits, fig_size=9): """ show figure with result of the ellipse fitting :param ndarray img: :param ndarray seg: :param [(int, int, int, int, float)] ellipses: :param [(int, int)] centers: :param [float] crits: :param float fig_size: ...
de6b58a01a64c3123f5aad4dfb6935c6c19a041c
3,640,154
def fmt_bytesize(num: float, suffix: str = "B") -> str: """Change a number of bytes in a human readable format. Args: num: number to format suffix: (Default value = 'B') Returns: The value formatted in human readable format (e.g. KiB). """ for unit in ["", "Ki", "Mi", "Gi", "Ti",...
09b36d229856004b6df108ab1ce4ef0a9c1e6289
3,640,155
def get_kpoint_mesh(structure: Structure, cutoff_length: float, force_odd: bool = True): """Calculate reciprocal-space sampling with real-space cut-off.""" reciprocal_lattice = structure.lattice.reciprocal_lattice_crystallographic # Get reciprocal cell vector magnitudes abc_recip = np.array(reciprocal_...
0536b5e2c37b7ba98d240fc3099fad93d246f730
3,640,156
def resnet_v1_101(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, spatial_squeeze=True, reuse=None, scope='resnet_v1_101', **kwargs): """ResNet-101 model of...
138289084d48edd9d9c1096bd790b1479d902ec1
3,640,157
def is_package_authorized(package_name): """ get user information if it is authorized user in the package config Returns: [JSON string]: [user information session] """ authorized_users = get_package_admins(package_name) user_info = get_user_info() user_dict = j.data.serializers.json...
59b89ebb9c8579d61a18a194e7f5f4bd41d738b6
3,640,158
def submit_search_query(query_string, query_limit, query_offset, class_resource): """ Submit a search query request to the RETS API """ search_result = class_resource.search( query='%s' % query_string, limit=query_limit, offset=query_offset) return search_result
f8c30c86f7ff7c33fc96b26b1491ddaa48710fbc
3,640,159
def one_hot_encode(df): """ desc : one hot encodes categorical cols args: df (pd.DataFrame) : stroke dataframe returns: df (pd.DataFrame) : stroke dataframe with one_hot_encoded columns """ # extract categorical columns stroke_data = df.copy() cat_cols = stroke_data....
6895dfbc4bb57d5e8d9a5552e2ac7fcb94e07434
3,640,160
def assert_increasing(a): """Utility function for enforcing ascending values. This function's handle can be supplied as :py:kwarg:`post_method` to a :py:func:`processed_proprty <pyproprop>` to enforce values within a :py:type:`ndarray <numpy>` are in ascending order. This is useful for enforcing ti...
f1ded37b40686cf400da23f567880e73180a78fe
3,640,161
def copy_to_device(device, remote_path, local_path='harddisk:', server=None, protocol='http', vrf=None, timeout=300, compact=False, use_kstack=False, ...
762ef928656473458e0fee8dc47c1a581103ed0e
3,640,162
import os def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expand...
51a17757d3d764c090efc0b8b213e9e6e9abca3d
3,640,163
def decode_replay_header(contents): """Decodes and return the replay header from the contents byte string.""" decoder = VersionedDecoder(contents, protocol.typeinfos) return decoder.instance(protocol.replay_header_typeid)
1fcee7900a5c0c310e67afe31a154b8310da7089
3,640,164
def _generate_indexed(array: IndexedArray) -> str: """Generate an indexed Bash array.""" return ( "(" + " ".join( f"[{index}]={_generate_string(value)}" for index, value in enumerate(array) if value is not None ) + ")" )
2443b3c6be74684360c395995b3d16d4ebecf1d8
3,640,165
from datetime import datetime def up_date(dte, r_quant, str_unit, bln_post_colon): """ Adjust a date in the light of a (quantity, unit) tuple, taking account of any recent colon """ if str_unit == 'w': dte += timedelta(weeks=r_quant) elif str_unit == 'd': dte += timedelta(...
684b09e5d37bf0d3445262b886c73188d35425ef
3,640,166
from typing import MutableMapping def read_options() -> Options: """ read command line arguments and options Returns: option class(Options) Raises: NotInspectableError: the file or the directory does not exists. """ args: MutableMapping = docopt(__doc__) schema = Schema({...
25cd3c29f6e206fd97334f7a48d267680a9e553c
3,640,167
def test_generator_single_input_2(): """ Feature: Test single str input Description: input str Expectation: success """ def generator_str(): for i in range(64): yield chr(ord('a') + i) class RandomAccessDatasetInner: def __init__(self): self.__data =...
d251279c0740b52c9d32c2ae572f6dbdf32f36ea
3,640,168
def SLINK(Dataset, d): """function to execute SLINK algo Args: Dataset(List) :- list of data points, who are also lists d(int) :- dimension of data points Returns: res(Iterables) :- list of triples sorted by the second element, first element is index of poin...
d10a3f8cb3e6d81649bebd4a45f5be79d206f1be
3,640,169
def static_file(path='index.html'): """static_file""" return app.send_static_file(path)
5c3f2d423d029a8e7bb8db5fbe3c557f7a6aa9c3
3,640,170
def lazy_property(function): """ Decorator to make a lazily executed property """ attribute = '_' + function.__name__ @property @wraps(function) def wrapper(self): if not hasattr(self, attribute): setattr(self, attribute, function(self)) return getattr(self, attribute) ...
db1d62eb66a018bc166b67fe9c2e25d671261f77
3,640,171
from pathlib import Path def basename(fname): """ Return file name without path. Examples -------- >>> fname = '../test/data/FSI.txt.zip' >>> print('{}, {}, {}'.format(*basename(fname))) ../test/data, FSI.txt, .zip """ if not isinstance(fname, path_type): fname = Path(fna...
55cd53ec71e4e914493129e40fa216ddcdbe8083
3,640,172
def validate_lockstring(lockstring): """ Validate so lockstring is on a valid form. Args: lockstring (str): Lockstring to validate. Returns: is_valid (bool): If the lockstring is valid or not. error (str or None): A string describing the error, or None if no error w...
0feb67597e31667013ab182159c8433ae4a80346
3,640,173
from typing import Iterable def decode_geohash_collection(geohashes: Iterable[str]): """ Return collection of geohashes decoded into location coordinates. Parameters ---------- geohashes: Iterable[str] Collection of geohashes to be decoded Returns ------- Iterable[Tuple[float...
2e673c852c7ac2775fd29b32243bdc8b1aa83d77
3,640,174
def renormalize_sparse(A: sp.spmatrix) -> sp.spmatrix: """Get (D**-0.5) * A * (D ** -0.5), where D is the diagonalized row sum.""" A = sp.coo_matrix(A) A.eliminate_zeros() rowsum = np.array(A.sum(1)) assert np.all(rowsum >= 0) d_inv_sqrt = np.power(rowsum, -0.5).flatten() d_inv_sqrt[np.isinf...
33122bcf018dba842f04e044cf9e799860a56042
3,640,175
from typing import Union import torch import os def load_gloria( name: str = "gloria_resnet50", device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", ): """Load a GLoRIA model Parameters ---------- name : str A model name listed by `gloria.available_models...
5ec060dd7e430244b597891d10cb19bc176a727f
3,640,176
import subprocess import os import re def is_enabled(): """ Check if `ufw` is enabled :returns: True if ufw is enabled """ output = subprocess.check_output(['ufw', 'status'], universal_newlines=True, env={'LANG': 'en_US', ...
fa922cdb87e35e1fc7cf77c5eba6a7da651ea070
3,640,177
def _fetch( self, targets=None, jobs=None, remote=None, all_branches=False, show_checksums=False, with_deps=False, all_tags=False, recursive=False, ): """Download data items from a cloud and imported repositories Returns: int: number of successfully downloaded files ...
18238bb1c4c5bd0772757013173e26645d5cdf5a
3,640,178
def get_connected_input_geometry(blend_shape): """ Return an array of blend_shape's input plugs that have an input connection. pm.listConnections should do this, but it has bugs when the input array is sparse. """ results = [] blend_shape_plug = _get_plug_from_node('%s.input' % blend_shape) num_input_elements ...
c69421ce452a1416006db0f22d279a6ed9694ebc
3,640,179
import torch from typing import Tuple def get_median_and_stdev(arr: torch.Tensor) -> Tuple[float, float]: """Returns the median and standard deviation from a tensor.""" return torch.median(arr).item(), torch.std(arr).item()
d8fca5a97f00d14beecaa4b508442bc7a3637f86
3,640,180
def connect(user, host, port): """Create and return a new SSHClient connected to the given host.""" client = ssh.SSHClient() if not env.disable_known_hosts: client.load_system_host_keys() if not env.reject_unknown_hosts: client.set_missing_host_key_policy(ssh.AutoAddPolicy()) con...
a13a3ce5e80f603f21933c9e6ad48b073368b97e
3,640,181
import scipy def _chf_to_pdf(t, x, chf, **chf_args): """ Estimate by numerical integration, using ``scipy.integrate.quad``, of the probability distribution described by the given characteristic function. Integration errors are not reported/checked. Either ``t`` or ``x`` must be a scalar. """ ...
7022d335d39c25b73203b63b40b1ebb8c178154b
3,640,182
import re import logging def ParseTraceLocationLine(msg): """Parse the location line of a stack trace. If successfully parsed, returns (filename, line, method).""" parsed = re.match(kCodeLocationLine, msg) if not parsed: return None try: return (parsed.group(1), parsed.group(2), parsed.group(3)) exc...
15e74bb26a7c213cf24171ffdfa32b8d4e6d818a
3,640,183
import pandas import os def get_rl_params(num, similarity_name, reward_name): """ Get RL model parameters (alpha and beta) based on <num>'s data. <similarity_name> is the name of the similarity metric you want to use, see fmri.catreward.roi.data.get_similarity_data() for details. <reward_name> ...
08bc39fbc02b2fa3d459a3996a87e294e0ef1d94
3,640,184
import functools def return_arg_type(at_position): """ Wrap the return value with the result of `type(args[at_position])` """ def decorator(to_wrap): @functools.wraps(to_wrap) def wrapper(*args, **kwargs): result = to_wrap(*args, **kwargs) ReturnType = type(arg...
30bf4e4a46b0b64b6cb5752286a13c0e6f7618df
3,640,185
def extend(s, var, val): """Copy dict s and extend it by setting var to val; return copy.""" try: # Python 3.5 and later return eval('{**s, var: val}') except SyntaxError: # Python 3.4 s2 = s.copy() s2[var] = val return s2
919e7102bf7f8766d9ddb9ea61a07ddd020d1bb8
3,640,186
from typing import Optional from typing import Any def rx_reduce(observable: Observable, accumulator: AccumulatorOperator, seed: Optional[Any] = None) -> Observable: """Create an observable which reduce source with accumulator and seed value. Args: observable (Observable): source accumulator ...
600d5c47fd7b29ead5293c7a172c8ebdb026706a
3,640,187
import logging import torch def predict(image: Image.Image): """ Take an image and run it through the inference model. This returns a ModelOutput object with all of the information that the model returns. Furthermore, bounding box coordinates are normalized. """ logging.debug("Sending image to model ...
eb90a598fb573dd8f345c62408bbf921f765a1f3
3,640,188
def minimum_filter( input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0, ): """Multi-dimensional minimum filter. Args: input (cupy.ndarray): The input array. size (int or sequence of int): One of ``size`` or ``footprint`` must be ...
fbbda2abbd470b98cb03158377256c7397c17da6
3,640,189
import copy def lowpass(data, cutoff=0.25, fs=30, order=2, nyq=0.75): """ Butter low pass filter for a single or spectra or a list of them. :type data: list[float] :param data: List of vectors in line format (each line is a vector). :type cutoff: float :param cutoff: Desired cuto...
ac42a32c406b1c5a182a1af805e86bf0b0c0606f
3,640,190
from re import M def format(value, limit=LIMIT, code=True, offset=0, hard_stop=None, hard_end=0): """ Recursively dereferences an address into string representation, or convert the list representation of address dereferences into string representation. Arguments: value(int|list): Either the s...
d8eae5b2cc8dbab9a26d7248faf17fe638f5e603
3,640,191
def sogs_put(client, url, json, user): """ PUTs a test `client` request to `url` with the given `json` as body and X-SOGS-* signature headers signing the request for `user`. """ data = dumps(json).encode() return client.put( url, data=data, content_type='application/json', headers=x_sog...
7bb3f34d7aff75f422b898ba6eee2908c8bc4ca4
3,640,192
import tqdm import requests def get_results(heading): """Get all records under a given record heading from PubChem/ Update results from those records.""" page = 1 results = {} with tqdm(total=100) as pbar: while True: url = (f"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/anno...
fba50023290dfde12a54f6d7792f578ecc66e3d9
3,640,193
def create_dictionary(documents): """Creates word dictionary for given corpus. Parameters: documents (list of str): set of documents Returns: dictionary (gensim.corpora.Dictionary): gensim dicionary of words from dataset """ dictionary = Dictionary(documents) dictionary.compactif...
bba8e6af363da3fcdde983c6ebf52432323ccf96
3,640,194
def clone_bitarray(other, src=None): """ Fast clone of the bit array. The actual function used depends on the implementation :param other: :param src: :return: """ if FAST_IMPL_PH4 and src is not None: src.fast_copy(other) return src return to_bitarray(other)
9196474dff0e6c1b79f9307409c5f351f2c015d7
3,640,195
from typing import List from typing import Optional from typing import Dict def _create_graph( expressions: List[expression.Expression], options: calculate_options.Options, feed_dict: Optional[Dict[expression.Expression, prensor.Prensor]] = None ) -> "ExpressionGraph": """Create graph and calculate expr...
e7f5a9dbaf3c34a3c925c5d390d6ee44fac57062
3,640,196
import warnings def power_to_db(S, ref=1.0, amin=1e-10, top_db=80.0): """Convert a power spectrogram (amplitude squared) to decibel (dB) units This computes the scaling ``10 * log10(S / ref)`` in a numerically stable way. Parameters ---------- S : np.ndarray input power ref : sc...
bee32e8b9be49d4797a83ec940c6a29ae09e144e
3,640,197
def generate_arn(service, arn_suffix, region=None): """Returns a formatted arn for AWS. Keyword arguments: service -- the AWS service arn_suffix -- the majority of the arn after the initial common data region -- the region (can be None for region free arns) """ arn_value = "arn"...
53dcf55c3fb15784770d1c2d62375d1e750469f8
3,640,198
def prod_list(lst): """returns the product of all numbers in a list""" if lst: res = 1 for num in lst: res *= num return res else: raise ValueError("List cannot be empty.")
8179e2906fb4b517d02972fd4647095d37caf6cd
3,640,199