content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def mvw_ledoit_wolf(prices, weight_bounds=(0.,1.), rf = 0., options = None): """ Calculates the mean-variance weights given a DataFrame of returns. Wraps mean_var_weights with ledoit_wolf covariance calculation method Args: * prices (...
086f6430d189fd12509d56ce4a96a351a178979b
3,651,100
def _PadLabels3d(logits, labels): """Pads or slices 3-d labels to match logits. Covers the case of 2-d softmax output, when labels is [batch, height, width] and logits is [batch, height, width, onehot] Args: logits: 4-d Pre-softmax fully-connected output. labels: 3-d, but not necessarily matching in si...
223f7dfea9ebc970e62dbe71e2f27dfb5c9f161d
3,651,101
def intx(): """Returns the default int type, as a string. (e.g. 'int16', 'int32', 'int64'). # Returns String, the current default int type. """ return _INTX
57661ef00953e07228ff81abc93ec22c216797ff
3,651,102
import json def dev_end_hardware_script() -> Response: """Designate the end of a hardware script in flask log. Can be invoked by: curl http://localhost:4567/development/end_hardware_script """ return Response(json.dumps({}), mimetype="application/json")
714b448642180753e639992f2d101841074aeefd
3,651,103
def _init_train(opt): """Common initilization stuff for all training process.""" ArgumentParser.validate_prepare_opts(opt) if opt.train_from: # Load checkpoint if we resume from a previous training. checkpoint = load_checkpoint(ckpt_path=opt.train_from) fields = load_fields(opt.save...
bb2a043d1a59f996b303aabf9db724ced3505dbf
3,651,104
import os import fnmatch def main(wf): """Run workflow script.""" opts = docopt.docopt(__doc__, argv=wf.args, version=wf.version) if opts['list']: return list_actions(opts) dry_run = opts['--nothing'] log.info('=' * 50) log.debug('opts=%r', opts) log.info('looking for workflows us...
7d62c3e498374097eaf232bc8195da908a370dbd
3,651,105
def compare(isamAppliance1, isamAppliance2): """ Compare Update Servers between two appliances """ ret_obj1 = get_all(isamAppliance1) ret_obj2 = get_all(isamAppliance2) for obj in ret_obj1['data']: del obj['uuid'] for obj in ret_obj2['data']: del obj['uuid'] return ibms...
e29025ca0af897f10b3b8498f8def86841b76c97
3,651,106
from rasterio import Affine, features from gisutils import get_authority_crs from fiona.crs import from_epsg, to_string def rasterize(feature, grid, id_column=None, include_ids=None, crs=None, epsg=None, proj4=None, dtype=np.float32, **kwargs): """Rasterize a feature onto...
474fd8dc871d6d2b64eb459f2c026be764f6a48d
3,651,107
import random def get_random(): """ Retrieves the current issue of XKCD, chooses an issue 1 - current issue #, and returns a json object. Returns null if an requests error occurs. """ return get_issue(random.randint(1, int(get_current()["num"])))
10fbf75681901722510b0b9fbb2de298eb80b45e
3,651,108
def get_fasta_readlengths(fasta_file): """ Get a sorted list of contig lengths :return: (tuple) """ lens = [] with open_fasta_reader(fasta_file) as f: for record in f: lens.append(len(record.sequence)) lens.sort() return lens
769cf5af50ba684c107a1312d2aeaab2721a29c6
3,651,109
def postprocess(p, gt, width_and_height, p_binary, false_positives=False, false_negatives=False): """ This function does matching and then postprocessing of p's and gt's :param p: the objects given from rcnn :param gt: the objects we get from the ground truth :param width_and_height: the width and h...
dd83de4547f7c1461b64fcd2dfa4c3df54aefd10
3,651,110
from csb.bio.structure import TorsionAngles import numpy def deg(x): """ Convert an array of torsion angles in radians to torsion degrees ranging from -180 to 180. @param x: array of angles @type x: numpy array @rtype: numpy array """ func = numpy.vectorize(TorsionAngles.d...
95e37a0c644df1562e417c1ad61e4788bd46c279
3,651,111
import timeit def run_median_trial(): """Generate table for Median Trial.""" tbl = DataTable([10,15,15],['N', 'median_time', 'sort_median']) trials = [2**k+1 for k in range(8,20)] for n in trials: t_med = 1000*min(timeit.repeat(stmt='assert(linear_median(a) == {}//2)'.format(n), ...
ed4c5ebe8bd6259c4adc45c4b023cc5bb96a1055
3,651,112
def regroup(X, N): """ Regroups the rows and columns of X such that rows/cols that are N apart in X, are adjeacent in Y. If N is a 2 element vector, N[0] is used for rows and N[1] is used for columns. Parameters: X: m by n matrix to be regrouped. N: Integer or two element vector...
7ad92b878cb6a55820ef9ad92c68e934184d725d
3,651,113
def return_estimators(n_components): """Returns all of the estimators that can be used to generate models. A larger selection of possible estimators have been commented out, but could be uncommented.""" estimators = [ ('PCArandom', decomposition.PCA(n_components=n_components, svd_solve...
680aa1d50c4e2db0e4d3df9e60749350df437bb8
3,651,114
def _check_type_picks(picks): """helper to guarantee type integrity of picks""" err_msg = 'picks must be None, a list or an array of integers' if picks is None: pass elif isinstance(picks, list): if not all(isinstance(i, int) for i in picks): raise ValueError(err_msg) ...
79493f75db8e57f32a6369ad18900e0632d2bc18
3,651,115
def get_test_standard_scaler_str(): """ Get a pandas projection code str """ test_code = cleandoc(""" standard_scaler = StandardScaler() encoded_data = standard_scaler.fit_transform(df) """) return test_code
fd6e1daa7e0dddb603437e5b35c283a11e68ec00
3,651,116
from typing import List from typing import Tuple import re def add_command( command_list: List[Tuple[re.Pattern, callable]], func: callable, command_str: str ) -> List[Tuple[re.Pattern, callable]]: """Add a function and the command pattern to the command list. Args: func: Function it will be call...
f8076e4a6b37722591eae04a67feb1c25e606b84
3,651,117
def get_clusters_and_critical_nodes(G, k, rho_star, phi_in): """ The implementation of the main body of the partitioning Algorithm. The main while-loop of the algorithm is executed as long as a refinement is still possible. :param phi_in: An algorithm parameter used to lower bound the inner conductance...
e7374c9cad30a87477ee5b9ce4d0a0e9cb7de041
3,651,118
def get_edges_out_for_vertex(edges: list, vertex: int) -> list: """Get a sublist of edges that have the specified vertex as first element :param edges: edges of the graph :param vertex: vertex of which we want to find the corresponding edges :return: selected edges """ return [e for e in edge...
21485073df1c754e7c8e2b7dd9cafef284e601e7
3,651,119
def pellet_plot_multi_unaligned(FEDs, shade_dark, lights_on, lights_off,**kwargs): """ FED3 Viz: Plot cumulaive pellet retrieval for multiple FEDs, keeping the x-axis to show absolute time. Parameters ---------- FEDs : list of FED3_File objects FED3 files...
3601e8ecff20a3d7978f7261ebaa5236d662a25e
3,651,120
import time def sync_via_mrmsdtw(f_chroma1: np.ndarray, f_chroma2: np.ndarray, f_DLNCO1: np.ndarray = None, f_DLNCO2: np.ndarray = None, input_feature_rate: float = 50, step_sizes: np.ndarray = np.array([[1, 0], [...
00dac7bdde14597e0daece958e65761ec01d1494
3,651,121
def simulate_beta_binomial( K, D, sigma2, theta, mu=0, invlink=logistic, seed=None): """Simulates from binomial Gaussian process with Beta latent noise. Args: K: Cell-state kernel, for example as generated by create_linear_kernel or create_rbf_kernel. D: Array of total counts. ...
de4648af70a6b35c7b7f5edc2c151a98db6d7603
3,651,122
def convert_to_floats(tsi): """ A helper function that tax all of the fields of a TaxSaveInputs model and converts them to floats, or list of floats """ def numberfy_one(x): if isinstance(x, float): return x else: return float(x) def numberfy(x): ...
a6f93f402c547435fa9fe611481084215f52f13b
3,651,123
def properties_filter(mol): """ Calculates the properties that contain logP, MW, HBA, HBD, TPSA, NRB """ #frag = Chem.rdmolops.GetMolFrags(mol) # remove '.' #if len(frag) > 1: #return False MW_s = Descriptors.MolWt(mol) # MW if MW_s < 250 or MW_s > 750: return False A...
bc124620baddb828b4c5cb82e0b0374bdb51bad7
3,651,124
def _create_certificate_chain(): """ Construct and return a chain of certificates. 1. A new self-signed certificate authority certificate (cacert) 2. A new intermediate certificate signed by cacert (icert) 3. A new server certificate signed by icert (scert) """ caext = X509Exten...
156a61e8159b1826def8fa33d5c5965add2c7f2e
3,651,125
def build_job_spec_name(file_name, version="develop"): """ :param file_name: :param version: :return: str, ex. job-hello_world:develop """ name = file_name.split('.')[-1] job_name = 'job-%s:%s' % (name, version) return job_name
55a45052852e6b24cb4370f7efe5c213da83e423
3,651,126
import torch def draw_mask(im: torch.Tensor, mask: torch.Tensor, t=0.2, color=(255, 255, 255), visualize_instances=True): """ Visualize mask where mask = 0. Supports multiple instances. mask shape: [N, C, H, W], where C is different instances in same image. """ assert len(mask.shap...
45d12dbc695755f0231ca2a8d0f8d1cdf2f423ff
3,651,127
def view_about(): """ shows the about page :return: :rtype: """ return render_template('about.html', title="About Flask AWS Template")
a364842c165864aba34605f3ffdd8c1d412015e8
3,651,128
import numpy def viterbi(observed_values, transition_probabilities, emission_probabilities, initial_distribution, file_name, log=True): """Calculates the viterbi-path for a given hidden-markov-model, heavily inspired by Abhisek Janas Blogpost "Implem...
b063e5c5bbf566afb0f16175d9d229bef7a953f1
3,651,129
def extract_psf_fitting_names(psf): """ Determine the names of the x coordinate, y coordinate, and flux from a model. Returns (xname, yname, fluxname) """ if hasattr(psf, 'xname'): xname = psf.xname elif 'x_0' in psf.param_names: xname = 'x_0' else: raise ValueError...
cee108dd1f97e506b60ba621c7f08efa7b5c33d7
3,651,130
def parseargs(p): """ Add arguments and `func` to `p`. :param p: ArgumentParser :return: ArgumentParser """ # TODO: Implement --date, --time and -t p.set_defaults(func=func) p.description = ( "Update the access and modification times of each " + "FILE to the current tim...
b6689761da04ebf3ac7e1b9682b4291c5dd4e9c1
3,651,131
def config_check_conformance(cookie, dn): """ Auto-generated UCS XML API Method. """ method = ExternalMethod("ConfigCheckConformance") method.cookie = cookie method.dn = dn xml_request = method.to_xml(option=WriteXmlOption.DIRTY) return xml_request
598fbd665dcf18a35104400bf7debfc64347c3b5
3,651,132
def get_dist_to_port(geotiff): """ Extract "truth" dist_to_port from geotiff """ with Geotiff(geotiff) as tif: dist_to_port = tif.values return dist_to_port
1a77c2ac905eea2d1796529297168dac394b4bdb
3,651,133
import inspect def build_dataset_exporter( dataset_type, strip_none=True, warn_unused=True, **kwargs ): """Builds the :class:`DatasetExporter` instance for the given parameters. Args: dataset_type: the :class:`fiftyone.types.dataset_types.Dataset` type strip_none (True): whether to exclud...
6a21c90ee2a9c297ad86515f5078221459b1fb01
3,651,134
def conditions(x): """ This function will check whether the constraints that apply to our optimization are met or not. """ if ( (10/x[0]) > 66.0 ): return False elif ( (10/x[0] + 12/x[1]) > 88.0 ): return False elif ( (10/x[0] + 12/x[1] + 7/x[2]) > 107.0 ): return ...
263fdc3fd07aa656982401f71071fcd684b8625f
3,651,135
import scipy from typing import Mapping from typing import OrderedDict import logging def load_reco_param(source): """Load reco parameterisation (energy-dependent) from file or dictionary. Parameters ---------- source : string or mapping Source of the parameterization. If string, treat as fil...
9d707f3403e0225223b6fe081158d31476b8281c
3,651,136
def get_commit_ancestors_graph(refenv, starting_commit): """returns a DAG of all commits starting at some hash pointing to the repo root. Parameters ---------- refenv : lmdb.Environment lmdb environment where the commit refs are stored starting_commit : string commit hash to start c...
078819cf0291a5e4e1e8ad4ea409f475c0df93fd
3,651,137
def is_verification_handshake(rjson): """ Determines if the request is the Slack application APIs verification handshake :rtype: bool """ # Check body contains the right keys for x in ['token', 'challenge', 'type']: if x not in rjson: return False # Check type is correct...
1ceccd9ca578bd09e9629cd59e565bc523502030
3,651,138
def template_node(scope_key): """ Create and return a new template node. Parameters ---------- scope_key : object The key for the local scope in the local storage maps. Returns ------- result : TemplateNode A new compiler template node. """ node = TemplateNode() ...
4cd9721dd9f9f91cb84326391630274b8f5764a7
3,651,139
def GetAutoResult(chroot_path, buildbucket_id): """Returns the conversion of the result of 'cros buildresult'.""" # Calls 'cros buildresult' to get the status of the tryjob. build_result = GetStatusFromCrosBuildResult(chroot_path, buildbucket_id) # The string returned by 'cros buildresult' might not be in the...
705fbc011c11fa67d0b61f130a3b6f024a6dcd44
3,651,140
def rft(x): """ Real Fourier Transform """ # XXX figure out what exactly this is doing... s = x.shape[-1] xp = np.zeros(x.shape,dtype="complex64") xp[...,1:s/2] = x[...,1:-1:2]+x[...,2::2]*1.j xp[...,0] = x[...,0]/2. xp[...,s/2] = x[...,-1]/2. return np.array(nmr_reorder(np.fft...
3a65f0a0059df4c74b223f3284e996b82d7ebf02
3,651,141
def yam_path(manifestsdir): """Bundletracker manifest.""" return join(manifestsdir, 'yam.json')
5d1b5162bd8285d8e33c822a3b5edcc996452719
3,651,142
def single_from(iterable): """Check that an iterable contains one unique value, and return it.""" unique_vals = set(iterable) if len(unique_vals) != 1: raise ValueError('multiple unique values found') return unique_vals.pop()
c8fb8864083195ad913ff1ddf0114b5a50068902
3,651,143
import requests def vthash(filehash: str): """Returns the analysis data class for a file in VirusTotal's database""" endpoint_path = f'/files/{filehash}' endpoint = f"{api_base_url}{endpoint_path}" r = requests.get(endpoint, headers=header) if r.status_code == 404 and r.json()['error']['code'] ...
bf4f334ad7a35e1141f9e00a44544fdd0709b411
3,651,144
def prod(x, axis=None, keepdims=False): """ product of all element in the array Parameters ---------- x : tensor_like input array axis : int, tuple of ints axis or axes along which a product is performed keepdims : bool keep dimensionality or not Returns ---...
8962e7b6abd16c9354f076c0c6d718b82fe44223
3,651,145
from typing import List import difflib def menu(queue: List[str] = None): """Fred Menu""" fred_controller = FredController(queue) an_input = "HELP_ME" while True: # There is a command in the queue if fred_controller.queue and len(fred_controller.queue) > 0: # If the comman...
b8133dd748f0a48099359b6503edee6c9f875fb6
3,651,146
def generic_repr(name, obj, deferred): """ Generic pretty printer for NDTable and NDArray. Output is of the form:: Array(3, int32) values := [Numpy(ptr=60597776, dtype=int64, shape=(3,))]; metadata := [contigious] layout := Identity; [1 2 3] """ ...
c9de29b792d943420b02455752f01a9c12fcf66c
3,651,147
def build_model(X, y, ann_hidden_dim, num_passes=20000): """ :param ann_hidden_dim: Number of nodes in the hidden layer :param num_passes: Number of passes through the training data for gradient descent :return: returns the parameters of artificial neural network for prediction using forward propagation...
bccdf828050af8a6ff5943eb84b574756f9f54ab
3,651,148
def g_square_dis(dm, x, y, s): """G square test for discrete data. Args: dm: the data matrix to be used (as a numpy.ndarray). x: the first node (as an integer). y: the second node (as an integer). s: the set of neibouring nodes of x and y (as a set()). levels: levels of ...
2f0f0b44a919177c0f5775a34e0493c62720a21d
3,651,149
def start(name): """ Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> """ cmd = "/usr/sbin/svcadm enable -s -t {0}".format(name) retcode = __salt__["cmd.retcode"](cmd, python_shell=False) if not retcode: return True ...
607b559281c6b13002d7237b8c4409533074d0bc
3,651,150
from typing import Dict def line_coloring(num_vertices) -> Dict: """ Creates an edge coloring of the line graph, corresponding to the optimal line swap strategy, given as a dictionary where the keys correspond to the different colors and the values are lists of edges (where edges are specified as ...
423e626ecbf4f48e0a192241375484a077fbe0b2
3,651,151
def flatten_outputs(predictions, number_of_classes): """Flatten the prediction batch except the prediction dimensions""" logits_permuted = predictions.permute(0, 2, 3, 1) logits_permuted_cont = logits_permuted.contiguous() outputs_flatten = logits_permuted_cont.view(-1, number_of_classes) return out...
c58fb965443a5402e9bec32afaebe9376c74653f
3,651,152
def get_r_vals(cell_obj): """Get radial distances for inner and outer membranes for the cell object""" r_i = cell_obj.coords.calc_rc(cell_obj.data.data_dict['storm_inner']['x'], cell_obj.data.data_dict['storm_inner']['y']) r_o = cell_obj.coords.calc_rc(cell_obj.data.data_di...
d51c926791845006dfe9a97cbd9c82c041ea701b
3,651,153
def get_all_migrations(ctxt, inactive=0): """Get all non-deleted source hypervisors. Pass true as argument if you want deleted sources returned also. """ return db.migration_get_all(ctxt, inactive)
c8e8ae084ca42d560e79412e4ff56d79059055a6
3,651,154
def extract(input_data: str) -> tuple: """take input data and return the appropriate data structure""" rules = input_data.split('\n') graph = dict() reverse_graph = dict() for rule in rules: container, contents = rule.split('contain') container = ' '.join(container.split()[:2]) ...
f71cdc23fdfaf6ef0d054c0c68e513db66289c12
3,651,155
def get_total_indemnity(date_of_joining, to_date): """To Calculate the total Indemnity of an employee based on employee's Joining date. Args: date_of_joining ([date]): Employee's Joining Date to_date ([data]): up until date Returns: total_allocation: Total Indemnity Allocation calc...
1b09d0dc7971ab4c3d63c303a93f64da924dcfa4
3,651,156
import os def run_species_phylogeny_iqtree(roary_folder, collection_dir, threads=8, overwrite=False, timing_log=None): """ Run iqtree to create phylogeny tree from core gene alignment. If the list of samples has not changed, and none of the samples has changed, the existing tree will be kept unless ov...
a5a6cd8e77cc3622264f4827753a2260e38d9f70
3,651,157
def api_2_gamma_oil(value): """ converts density in API(American Petroleum Institute gravity) to gamma_oil (oil relative density by water) :param value: density in API(American Petroleum Institute gravity) :return: oil relative density by water """ return (value + 131.5) / 141.5
20e625f22092461fcf4bc2e2361525abf8051f97
3,651,158
def compute_metrics(pred, label): """Compute metrics like True/False Positive, True/False Negative.` MUST HAVE ONLY 2 CLASSES: BACKGROUND, OBJECT. Args: pred (numpy.ndarray): Prediction, one-hot encoded. Shape: [2, H, W], dtype: uint8 label (numpy.ndarray): Ground Truth, one-hot encoded....
be8415c997197c06a5998671ffe09e70c6d3719c
3,651,159
import jinja2 def expand_template(template, variables, imports, raw_imports=None): """Expand a template.""" if raw_imports is None: raw_imports = imports env = jinja2.Environment(loader=OneFileLoader(template)) template = env.get_template(template) return template.render(imports=imports, variables=varia...
c5ebe1610a6e2fa9e0b18afa7d23652c1f7c25ba
3,651,160
from typing import Any from operator import truth def __contains__(container: Any, item: Any, /) -> bool: """Check if the first item contains the second item: `b in a`.""" container_type = type(container) try: contains_method = debuiltins._mro_getattr(container_type, "__contains__") except Att...
b58a5f400895df472f83a5e2410dff9cd112fc91
3,651,161
def generate_search_url(request_type): """Given a request type, generate a query URL for kitsu.io.""" url = BASE_URL_KITSUIO.format(request_type) return url
9508d909fb8eb018770b2191f7d62ccb3881f285
3,651,162
from typing import Callable def register_magic(func: Callable[[Expr], Expr]): """ Make a magic command more like Julia's macro system. Instead of using string, you can register a magic that uses Expr as the input and return a modified Expr. It is usually easier and safer to execute metaprogrammin...
06d93f8a48758dc39679af396c10a54927e3696e
3,651,163
import os def flowcellDirFastqToBwaBamFlow(self, taskPrefix="", dependencies=set()) : """ Takes as input 'flowcellFastqDir' pointing to the CASAVA 1.8 flowcell project/sample fastq directory structure. For each project/sample, the fastqs are aligned using BWA, sorted and merged into a single BAM f...
6f18083fc2c9e4a260e87c332d40d9322f2c7bc1
3,651,164
def ValidatePregnum(resp): """Validate pregnum in the respondent file. resp: respondent DataFrame """ # read the pregnancy frame preg = nsfg.ReadFemPreg() # make the map from caseid to list of pregnancy indices preg_map = nsfg.MakePregMap(preg) # iterate through the respondent pre...
a51f3af130cbad4a5cd3d3c9707788f783302000
3,651,165
def is_super_admin(view, view_args, view_kwargs, *args, **kwargs): """ Permission function for things allowed exclusively to super admin. Do not use this if the resource is also accessible by a normal admin, use the is_admin decorator instead. :return: """ user = current_user if not user.is_...
503550fcd52e62053d42a3059aba298009d3eb01
3,651,166
def normalize_depth(val, min_v, max_v): """ print 'nomalized depth value' nomalize values to 0-255 & close distance value has high value. (similar to stereo vision's disparity map) """ return (((max_v - val) / (max_v - min_v)) * 255).astype(np.uint8)
431cda7af30ef1127c60069b6958ef4d8234eaae
3,651,167
def parse_iori_block(block): """Turn IORI data blocks into `IoriData` objects. Convert rotation from Quaternion format to Euler angles. Parameters ---------- block: list of KVLItem A list of KVLItem corresponding to a IORI data block. Returns ------- iori_data: IoriData ...
b9ad59677e51c30b2bec51a0503fc2718cde0f7d
3,651,168
def ungap_all(align): """ Removes all gaps (``-`` symbols) from all sequences of the :class:`~data.Align` instance *align* and returns the resulting ~data.Container instance. """ result = data.Container() for n,s,g in align: result.append(n, s.translate(None, '-'), g) ...
511b6aeb7fc262b733a97b5180a23c7f044fea06
3,651,169
def expandBcv(bcv): """If the bcv is an interval, expand if. """ if len(bcv) == 6: return bcv else: return "-".join(splitBcv(bcv))
abfb1bf31acca579fecb526d571b32cefa7ecd61
3,651,170
import os def get_starting_dir_abs_path() -> str: """ Returns the absolute path to the starting directory of the project. Starting directory is used for example for turning relative paths (from Settings) into absolute paths (those paths are relative to the starting directory). """ if _starting_dir...
af91f10a2dd9af8ba010f75fe295acb2406e9372
3,651,171
def cluster_profile_platform(cluster_profile): """Translate from steps.cluster_profile to workflow.as slugs.""" if cluster_profile == 'azure4': return 'azure' if cluster_profile == 'packet': return 'metal' return cluster_profile
0a01f566562002fe43c3acbb00d5efcc09d25314
3,651,172
def get_price_lambda_star_lp_1_cvxpy(w: np.ndarray, c_plus: np.ndarray, psi_plus: np.ndarray) \ -> float: """ Computes lambda_star based on dual program of the projection of w_star. :param w: current state in workload space. :param c_plus: vector normal to the level set in the monotone region '...
0a1a658cd86a0253fe3caf8a5e162393926b351a
3,651,173
import typing import random def _get_nodes( network: typing.Union[NetworkIdentifier, Network], sample_size: typing.Optional[int], predicate: typing.Callable, ) -> typing.List[Node]: """Decaches domain objects: Node. """ nodeset = [i for i in get_nodes(network) if predicate(i)] if samp...
f3be401c2fd0adf58f10b679d254ff2075f4546b
3,651,174
def cdl_key(): """Four-class system (grain, forage, vegetable, orchard. Plus 5: non-ag/undefined""" key = {1: ('Corn', 1), 2: ('Cotton', 1), 3: ('Rice', 1), 4: ('Sorghum', 1), 5: ('Soybeans', 1), 6: ('Sunflower', 1), 7: ('', 5), 8: (''...
634a35d2962695dd0ef1b38a0c353498ca3dea89
3,651,175
def colmeta(colname, infile=None, name=None, units=None, ucd=None, desc=None, outfile=None): """ Modifies the metadata of one or more columns. Some or all of the name, units, ucd, utype and description of the column(s), identified by "colname" can be set by using some or all of the listed ...
15fc5b53e4ebd3563b00ef771a707d2ad2473ad7
3,651,176
def get_confusion_matrix_chart(cm, title): """Plot custom confusion matrix chart.""" source = pd.DataFrame([[0, 0, cm['TN']], [0, 1, cm['FP']], [1, 0, cm['FN']], [1, 1, cm['TP']], ], columns=["actual valu...
28884c46a51f3baf51dc5a6f3c0396a5c8f24e10
3,651,177
def get_ppo_plus_eco_params(scenario): """Returns the param for the 'ppo_plus_eco' method.""" assert scenario in DMLAB_SCENARIOS, ( 'Non-DMLab scenarios not supported as of today by PPO+ECO method') if scenario == 'noreward' or scenario == 'norewardnofire': return md(get_common_params(scenario), { ...
26bb3db0cf14eceea86cd659332c9bbc0195ab9b
3,651,178
def field_display(name): """ Works with Django's get_FOO_display mechanism for fields with choices set. Given the name of a field, returns a producer that calls get_<name>_display. """ return qs.include_fields(name), producers.method(f"get_{name}_display")
7fbc17dddfa398934496099f605f6cee97a802ad
3,651,179
import time def set_trace(response): """ Set a header containing the request duration and push detailed trace to the MQ :param response: :return: """ if TRACE_PERFORMANCE: req_time = int((time.time() - g.request_start) * 1000) trace = { "duration": req_time, ...
1b7067daaf9fd3b72cf9b2db9a78b33b64bf8fb9
3,651,180
from typing import Dict from typing import List def extract_attachments(payload: Dict) -> List[Image]: """ Extract images from attachments. There could be other attachments, but currently we only extract images. """ attachments = [] for item in payload.get('attachment', []): # noinspe...
afb9d959e680c51fc327d6c7e5f5e74fdc5db5e6
3,651,181
from ...model_zoo import get_model def yolo3_mobilenet1_0_custom( classes, transfer=None, pretrained_base=True, pretrained=False, norm_layer=BatchNorm, norm_kwargs=None, **kwargs): """YOLO3 multi-scale with mobilenet base network on custom dataset. Parameters ...
2da86fe66538e3cd9a21c456c00312a217ab5ca0
3,651,182
def calculate_levenshtein_distance(str_1, str_2): """ The Levenshtein distance is a string metric for measuring the difference between two sequences. It is calculated as the minimum number of single-character edits necessary to transform one string into another """ distance = 0 buffer_re...
949d54fbcbd2169aa06cedc7341e98c12412d03c
3,651,183
from datetime import datetime def make_datetime(value, *, format_=DATETIME_FORMAT): """ >>> make_datetime('2001-12-31T23:59:59') datetime.datetime(2001, 12, 31, 23, 59, 59) """ return datetime.datetime.strptime(value, format_)
5c6d79ae0ddc9f4c47592a90ed3232f556df0a49
3,651,184
import inspect def named_struct_dict(typename, field_names=None, default=None, fixed=False, *, structdict_module=__name__, base_dict=None, sorted_repr=None, verbose=False, rename=False, module=None, qualname_prefix=None, frame_depth=1): """Returns a new subclass of Stru...
465ac4783697b749c092d96fa8af498e67f15d51
3,651,185
from .pytorch.pytorch_onnxruntime_model import PytorchONNXRuntimeModel def PytorchONNXRuntimeModel(model, input_sample=None, onnxruntime_session_options=None): """ Create a ONNX Runtime model from pytorch. :param model: 1. Pytorch model to be converted to ONNXRuntime for inference ...
d925b67c3628995d75d1ea6c687e5beb022fdbd8
3,651,186
import os def get_model_python_path(): """ Returns the python path for a model """ return os.path.dirname(__file__)
5ddd66f8b0c37b8a84eab614c4e3efd6efe9d9ef
3,651,187
def intensity_variance(mask: np.ndarray, image: np.ndarray) -> float: """Returns variance of all intensity values in region of interest.""" return np.var(image[mask])
e967b4cd3c3a896fba785d8c9e5f8bf07daa620d
3,651,188
def permute_array(arr, axis=0): """Permute array along a certain axis Args: arr: numpy array axis: axis along which to permute the array """ if axis == 0: return np.random.permutation(arr) else: return np.random.permutation(arr.swapaxes(0, axis)).swapaxes(0, axis)
ce5f6d571062f36888d22836579332034f4fe924
3,651,189
import os import errno def convertGMLToGeoJSON(config, outputDir, gmlFilepath, layerName, t_srs='EPSG:4326', flip_gml_coords=False): """ Convert a GML file to a shapefile. Will silently exit if GeoJSON already exists @param config A Python ConfigParser containing the section ...
70ee0676d13a647d42a39313d5be1545042f73c7
3,651,190
def dsmatch(name, dataset, fn): """ Fuzzy search best matching object for string name in dataset. Args: name (str): String to look for dataset (list): List of objects to search for fn (function): Function to obtain a string from a element of the dataset Returns: First e...
0835c0da3773eedab95c78e1b4f7f28abde0d8fd
3,651,191
import os import re def _generate_flame_clip_name(item, publish_fields): """ Generates a name which will be displayed in the dropdown in Flame. :param item: The publish item being processed. :param publish_fields: Publish fields :returns: name string """ # this implementation generates n...
847956c6897a873145c78adbcf6530f0a47a9259
3,651,192
def f(q): """Constraint map for the origami.""" return 0.5 * (np.array([ q[0] ** 2, (q[1] - q[0]) ** 2 + q[2] ** 2 + q[3] ** 2, (q[4] - q[1]) ** 2 + (q[5] - q[2]) ** 2 + (q[6] - q[3]) ** 2, q[4] ** 2 + q[5] ** 2 + q[6] ** 2, q[7] ** 2 + q[8] ** 2 + q[9] ** 2, (q[7...
77c3617a76cb2e184b1f22404f1db8be8212a4c9
3,651,193
def resize(clip, newsize=None, height=None, width=None): """ Returns a video clip that is a resized version of the clip. Parameters ------------ newsize: Can be either - ``(height,width)`` in pixels or a float representing - A scaling factor, like 0.5 - A fu...
5a8541e1320d37bd47aa35978794d849af358cb6
3,651,194
def calc_rt_pytmm(pol, omega, kx, n, d): """API-compatible wrapper around pytmm """ vec_omega = omega.numpy() vec_lambda = C0/vec_omega*2*np.pi vec_n = n.numpy() vec_d = d.numpy() vec_d = np.append(np.inf, vec_d) vec_d = np.append(vec_d, np.inf) vec_kx = kx.numpy().reshape([-1,1])...
def2fb22d2e72a873794838601bc74a7c65cb9c3
3,651,195
def statistic_bbox(dic, dic_im): """ Statistic number of bbox of seed and image-level data for each class Parameters ---------- dic: seed roidb dictionary dic_im: image-level roidb dictionary Returns ------- num_bbox: list for number of 20 class's bbox num_bbox_im: list for numb...
782314baeab7fbec36c9ea56bcec57d5a508a918
3,651,196
def github_youtube_config_files(): """ Function that returns a list of pyGithub files with youtube config channel data Returns: A list of pyGithub contentFile objects """ if settings.GITHUB_ACCESS_TOKEN: github_client = github.Github(settings.GITHUB_ACCESS_TOKEN) else: ...
166ca3653173feee7513097c9313ebb5ab3b4d17
3,651,197
def reverse_uint(uint,num_bits=None): """ This function takes an unsigned integer and reverses all of its bits. num_bits is number of bits to assume are present in the unsigned integer. If num_bits is not specified, the minimum number of bits needed to represent the unsigned integer is assumed. If n...
a3197aa3f199a5677a15e053c0455c0216d07827
3,651,198
def min_by_tail(lhs, ctx): """Element ↓ (any) -> min(a, key=lambda x: x[-1]) """ lhs = iterable(lhs, ctx=ctx) if len(lhs) == 0: return [] else: return min_by(lhs, key=tail, cmp=less_than, ctx=ctx)
88fce303e6ff95f89e57ebd05c575810238497ea
3,651,199