content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def gen_seq_obj_lst(file_contents): """ Takes the individual lines from a clustal .aln file Remove the first few lines. Make a sequence object list from the remaining. Sequence object will contain the sequence name (header), sequence and length """ sequence_list = [] for line in file_co...
6925b4c30d5c61aec9582a56894458ebf353eb27
3,598,900
import socket def sendethframe(src, dst, eth_type, payload, interface = "eth0"): """Send RAW Ethernet Frame.""" assert(len(src) == len(dst) == 6) # 48-bit ethernet addresses assert(len(eth_type) == 2) # 16-bit ethernet type s = socket(AF_PACKET, SOCK_RAW) s.bind((interface, 0)) return s.send(dst + src ...
fec62a08cbf3fc1ce1a18098ede63db9bfd43c12
3,598,901
from dynamix.correlator.event import EventCorrelator import time def gpu_ecorr_q(events, times, offsets, shape, nframes, dtype, qqmask, max_nnz): """ Calculation of the event correlation function using GPU :param events: 1D array of events values :param times: 1D array of times :param offsets: 1D arr...
0ac53f30f9a74e9f852620ef6025057f8f289e91
3,598,902
def label_contiguous_1d(X): """ WARNING: API for this function is not liable to change!!! By example: X = [F T T F F T F F F T T T] result = [0 1 1 0 0 2 0 0 0 3 3 3] Or: X = [0 3 3 0 0 5 5 5 1 1 0 2] result = [0 1 1 0 0 2 2 2 3 3 0 4] The ``0`` or ``Fal...
202e252e701d560cad3d4c86c15c48dd04bd0e7a
3,598,903
def merge_tables(tables_dict1: SINGLE_REPORT_TABLES, tables_dict2: SINGLE_REPORT_TABLES) -> MERGED_REPORT_TABLES: """Combine 2-column tables from single reports, to 3-column tables, with columns corresponding to each report.""" new_table_dict = defaultdict(list) for tab_name, tab_metrics1 in tables_dict1....
9b4514fd0b9266425f8bbd59a1427193e073c464
3,598,904
def pton_unpack6(address): """ Converts IPv6 address to int. Requires a string, returns a 128 bit int. """ try: pton = inet_pton(AF_INET6, address) except sockerror: return None unpacked = unpack("!QQ", pton) return (unpacked[0] << 64) | unpacked[1]
dbc0103d6a51f2cfa6b2cd4491e01280368d7a90
3,598,905
def _toledo8217StatusParse(status): """ Parse a scale's status, returning a `(weight, weight_info)` pair. """ weight, weight_info = None, None stat = status[status.index(b'?') + 1] if stat == 0: weight_info = 'ok' else: weight_info = [] if stat & 1 : weight_info.a...
83d8132398e740c71bdf3ac6f65f323f8c8ad65b
3,598,906
def pipe_map(n_caps, n_refs, differential=False): """ Creates the code->reference map for pipeline operation. Each column in this map contains the reference index to be used for the feedfoward capacitors. :param n_caps: Number of feedfoward capacitors with references, usually the number of stag...
93ae2866125cab889d4d3827b7b7b52341a984b6
3,598,907
import requests import dateutil def get_ninja_info(guid, customer_id, site_name): """ Pull the needed Student information from the dojo. This can be expanded but right now we are just getting the most current drop in program """ detail = requests.get( GENERAL_STUDENT_DETAIL.format( ...
aa21fb00628a357dd7015fc0e8f50ed8aa532094
3,598,908
import io import os def save_upload(request, upload, filename, user): """ raw_data: if True, upfile is a HttpRequest object with raw post data as the file, rather than a Django UploadedFile from request.FILES """ check_mime(request, filename) image = Image.open(upload) image.thumbnail(AVAT...
ba155ea48badc041a99288e8576ede5babcc9a56
3,598,909
def num_instances ( diff, flag=False ): """Counts the number of palindromic ages. Returns the number of times the mother and daughter have palindromic ages in their lives, given the difference in age. diff: int difference in ages flag: bool, if True, prints the details """ daughter = 0 ...
921953465596f9a9d5201cc62a2391880af4588e
3,598,910
import os def create_callbacks(logdir, hparams=None, save_best=True, reduce_on_plateau=False, max_metrics=None, schedule_step=0): """Creates keras callbacks for training Arguments: logdir: Path to directory where shall be logged hparams: Sample of hyperparameters for this run save_bes...
569c78c5d9ba6196a42f0e041d46b2b6e0765c6e
3,598,911
def del_tx_sheet(request, sheet_id): """Deletes a treatment sheet.""" tx_sheet = get_object_or_404(TxSheet, id=sheet_id) if request.user == tx_sheet.owner: tx_sheet.delete() return redirect('/tx_sheet/') else: raise PermissionDenied
ea90ec12224f2b3e8cb3b38d872b5c1e6a834f80
3,598,912
import time def remove_unnecessary_edges(modifiedEdgeListUpdated, origin, destination): """ Function to remove any node, which is only connected to one other node and thus is unncessary. This is the case, because we have only postive edge weights. And thus, visiting the node to then just go back the node ...
1817c3a9c844f8d9753c6e086632dedc2c4829fc
3,598,913
def validateTelescopeModelName(name): """ Validate a telescope model name. Raises ------ ValueError If name is not valid. Parameters ---------- name: str Returns ------- str Validated name. """ telClass, telType = splitTelescopeModelName(name) t...
f696e9cacf45e94b376fa92b19c22483c0b9fa16
3,598,914
def seasonal_test(x_old, period = 12, alpha = 0.05): """ This function checks the Seasonal Mann-Kendall (MK) test (Hirsch, R. M., Slack, J. R. 1984). Input: x: a vector of data period: seasonal cycle. For monthly data it is 12, weekly data it is 52 (12 is the default) alpha: signi...
3f2a37e0e0bc062ad0a425afb68dd2e39a576025
3,598,915
def callform(request): """Render call form""" return render(request, 'helpline/callform.html')
e45309b30704480a79f739c82aba476d40615894
3,598,916
def model_flow_node_model_flow_id_node_id_component_put(model_flow_id, node_id): # noqa: E501 """update a node&#x27;s components information in a model flow chart update a node&#x27;s information in a model flow chart # noqa: E501 :param model_flow_id: model flow chart id :type model_flow_id: str ...
584a493efb379fecc8b7bcacfab607e2320f4f58
3,598,917
def draw_all_at_index(index): """ Draw all lotteries in the specific index Args: index(int): zero-based index that indicates the time of lottery Return: winners([[User]]): The list of list of users who won """ lotteries = Lottery.query.filter_by(index=index) ...
62816ae24ab901828c22468ee36066ef86a4beaf
3,598,918
import webbrowser def CreateOauthToken(expiration="30days", scope='read,write', key=None, secret=None, name='trellodump', output=True): """ Script to obtain an OAuth token from Trello. More info on token scope here: https://trello.com/docs/gettingstarted/#getting-a-token-from-a-user """ # Ste...
c83b85b68f2fe3f85f1455557a7a96df62a2d692
3,598,919
def mscorr(X, ref='mean'): """MSC base line correction for spectral data. Args: X (np.ndarray): The data set to correct. ref (list, np.ndarray): The reference spectrum. Returns: The data set corrected via MSC. Notes: * Implementation partially taken from: By Cleiton A....
9ed502ef9e7e10f791112da8f608a14c1f9ff88a
3,598,920
def gsl_blas_sdsdot(*args, **kwargs): """gsl_blas_sdsdot(float alpha, gsl_vector_float const * X, gsl_vector_float const * Y, float * result) -> int""" return _gslwrap.gsl_blas_sdsdot(*args, **kwargs)
4f81c22174d937ba7eb9bd7073759dda38df25e9
3,598,921
import os import glob def list_all_files(src_directory): """Make a list of all the files in the given directory. Returns list.""" cwd = os.getcwd() os.chdir(src_directory) files = [] for file in glob.glob("*"): files.append(file) os.chdir(cwd) return files
1e2653dc3f7b8a0a093281004ac17d5a25ced744
3,598,922
def generate_bm(df, experiment_keys): """ Given the flatten DataFrame, containing all the experiment here we extract the experiments correspondent to the dictionary experiment_keys. :param df: pandas DataFrame containing the flatten df :param experiment_keys: dictionary with all the keys. :returns d...
43f91e734419c76157920fe486db48e1c17ebdc5
3,598,923
from typing import Optional from typing import Union from typing import Iterable from typing import Dict def discover_datasets_unchecked( uuid_prefix: str, store: StoreInput, filter_ktk_cube_dataset_ids: Optional[Union[str, Iterable[str]]] = None, ) -> Dict[str, DatasetMetadata]: """ Get all known...
cdac0f0fd08801901c67d50bfecff4122ed30b0c
3,598,924
def findNextKeyForTargetEntry(ipAddr): """ Find the next available TargetEntry key """ key = "None" index = 1 while 1: key = "targetEntry{}".format(index) index += 1 keypath = cc.Path('/restconf/data/ietf-snmp:snmp/target={name}', name=key) response=aa.get(keypath) if response.ok(): if...
4358f88ac4791bb5cf36e9a50db964752501c4c5
3,598,925
def twitter_reply(reply_id, username, text): """ Args: reply_id: the tweet id that the bot is replying to username: the username of the account the bot is replying to text: what test the bot will use in its reply Returns: """ # This is a default if no text is input if...
6159aba6ec50eab18b0ccdfce35e16ceab90d425
3,598,926
def labeledFcn(fcn, paramNames): """Wraps a function with its parameter names (in-place). :type fcn: callable Python object :param fcn: function to wrap :type paramNames: list of strings :param paramNames: parameters to attach to the function :rtype: callable Python object :return: the orig...
e8885cf0cf4db4e84069ec4f0164748b0ab52ae3
3,598,927
import os def get_geotiff_size_bytes(tif_path): """Reads file size in bytes from GeoTIFF at tif_path Args: tif_path (str): Path to local GeoTIFF file Returns: Size of the GeoTIFF file in bytes """ return os.path.getsize(tif_path)
0095eec3091cd44cae58eecd3d9a5e879d934349
3,598,928
import json def MakeRequests(requests, http, batch_url=None): """Makes batch requests. Args: requests: A list of tuples. Each tuple must be of the form (service, method, request object). http: An HTTP object. batch_url: The URL to which to send the requests. Returns: A tuple where the ...
c740bb22a5d0b366aec89ea7e624dc2533b757b2
3,598,929
def correct_spectra( df, correction ): """ Corrects a spectral DataFrame. :param df: DataFrame of spectra. :param correction: Series of correction with same index type as df. :returns: Corrected DataFrame. """ _, corr = std.common_reindex( [ df, correction ] ) # match index cdf = df.mu...
43c639d19753ba0fb51fba2f950f4024d43c5546
3,598,930
from traja.trajectory import _get_time_col def to_trajr(trj): """Convert trajectory to R `trajr` object. Default fps is 30. Args: trajectory (:class:`~traja.TrajaDataFrame`): trajectory Returns: traj (:class:`rpy2.robjects.vectors.DataFrame`): column names are ['x', 'y', 'time', 'displa...
9365605e5c48c853650a2573be7ff7583ceb13c1
3,598,931
def get_rfx_object(packetid): """Return the RFXObject with the packetid.""" try: binarypacket = bytearray.fromhex(packetid) except ValueError: return None pkt = rfxtrxmod.lowlevel.parse(binarypacket) if pkt is None: return None if isinstance(pkt, rfxtrxmod.lowlevel.Senso...
c60ffbbc7dee9423ddbec2107d5ae5951e78ae41
3,598,932
def get_mask(image, mask, class_ids): """Apply color overlay. image: RGB image [height, width, 3] mask: instance segmentation mask [height, width, instance count] Returns result image. """ overlay = image pd_mask = np.zeros([overlay.shape[0], overlay.shape[1], 5], dtype=np.uint8) #classchan...
d549e63904e95ac5a1e16a8bd766c15b9e106c8f
3,598,933
def sell_stock(stock, amount, limit_price, index): """ 卖出股票,并记录订单号,便于查询订单状态 :param stock: :param amount: :param limit_price: :param index: :return: """ try: sell_order = order(stock, amount, LimitOrderStyle(limit_price)) finally: g.__manager.work() if sell_or...
4c9415199b7a058e3234fe785708c9b3011989b6
3,598,934
import logging def FetchArrayByName(init_def, name): """fetch array by name""" for index, op in enumerate(init_def.op): if op.output[0] != name: continue if op.type != "GivenTensorFill": logging.error("The array {} is not contained" " by Given...
ef7d7a57ab5e72ae97a53675a0488f23e4d59564
3,598,935
from typing import Optional def calc_interpolation( val_0: pd.Series, val_1: pd.Series, wt_0: pd.Series, wt_1: Optional[pd.Series] = None, method: str = "linear", ) -> pd.Series: """Calculate interpolation between two values. Parameters ---------- val_0 : pd.Series zzz ...
81a00afbc1c5e60de3b8fd2f3b4dbf26fc20dd7b
3,598,936
import os def do_build(): """Returns whether we should build the node and calicoctl binaries.""" try: build = os.environ[BUILD_ENV] return build.lower() not in ["no", "n", "f", "false"] except KeyError: return True
1d14f6b665a2084eb41a9bd48d9013b29dd0e2d3
3,598,937
import sys from datetime import datetime def editUser(): """ Takes in a json of the form {'currentEmail' : email, 'newAttributes' : {...}} It can change any attribute that is not the email """ sys.stderr.write(str(request.json) + '\n') if not dbworker.validateAccess(dbworker.userTypeMap['...
1313d4ca2177bd8fdd420e17c52bf05cdc47e146
3,598,938
def get_min_max(input_list: list) -> tuple: """ Return a tuple(min, max) out of list of unsorted integers. Args: input_list(list): list of integers containing one or more integers """ print("->get_min_max: input_list= " + str(input_list)) if len(input_list) == 0: return None, No...
26db872de57ed6c94825e089607a4bb81390b423
3,598,939
def _code_and_constants(object_): """Helper function to get python code and constants""" return _code_and_constants_attr_getter(object_.__code__)
0385a73ac2ed70e30cdaf3246ec722e4fe1d97da
3,598,940
from typing import Union def threshold_events( data: np.ndarray, threshold: Union[float, int] ) -> np.ndarray: """Apply threshold to find start and end of events. Arguments --------- data : np.ndarray Input data to apply thresholding to. threshold : float | int Threshold value...
066f799af2ecd245cd278d73aa1ce534475da571
3,598,941
import torch def value_td_residuals( rewards: torch.Tensor, values: torch.Tensor, next_values: torch.Tensor, discount: float, ) -> torch.Tensor: """Compute TD residual of state value function. All tensors must be one dimensional. This is valid only for one trajectory. Parameters ----...
723ed0f0ce651cc7da5ad9c7950972d104198888
3,598,942
import traceback import sys def exception_format(): """ Convert exception info into a string suitable for display. """ return "".join(traceback.format_exception( sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2] ))
4bb7f74140bf5e6023850b2ad27809ded1c6fc09
3,598,943
from typing import List def get_dataset(organisms: List[Organism]): """ Builds a dataset with the samples associated with the given organisms """ dataset = {} filter_query = Q() for organism in organisms: filter_query = filter_query | Q(organisms=organism) experiments = Experiment.object...
af4edb3b09b8391c47efe31db83f88c2598650c5
3,598,944
async def agather(aiter): """Gather an async iterator into a list""" lst = [] async for elem in aiter: lst.append(elem) return lst
0a7f278d38237a722724572b6705deab429c8e70
3,598,945
import random def generate_Gnp_with_planted_clique(n, p, clique_size): """ Given a number of vertices n, a probability p and a clique size the method returns a networkx gnp graph with an additional planted clique i.e. from the Gnp graph we select a random subset of vertices of size clique_size and...
7ce98916c3a47e4af578474a3e83621fbf2e3c4d
3,598,946
def all_compliant(rules,task,env,name,seed=None,verbose=False): """ Return all possible compliant action given norms/rules """ import sys from actions import pickup_action,putdown_action from verify_action_4 import verify_action from copy import deepcopy import os from numpy import nan,rando...
8aed21be6116371b5ebcd36d5ac922f016ae94f6
3,598,947
def default_panels(institute_id, case_name): """Update default panels for a case.""" panel_ids = request.form.getlist('panel_ids') controllers.update_default_panels(store, current_user, institute_id, case_name, panel_ids) return redirect(request.referrer)
abfcffcf26e41be209eb35bf4230f0055b193ccf
3,598,948
def ParseImportLine(line): """Parse a line potentially containing an import. Note that this function does NOT properly handle: from foo.bar import FooClass It's too expensive to code for and against Python style anyway. Args: line: string, like "from x import y" or "import x.y" Returns: None:...
2f1d2fe3bd3744e09826bf2625e3bb2c6796494c
3,598,949
def client_inner_dirichlet_partition(targets, num_clients, num_classes, dir_alpha, client_sample_nums, verbose=True): """Non-iid Dirichlet partition. The method is from The method is from paper `Federated Learning Based on Dynamic Regularization <https://openreview.net/foru...
90828ef055f520d62aecb1ac92c6622121fba4ad
3,598,950
def filterTCPString(TCPMessage): """ Remove any unwanted characters from the TCP message string and truncate if necessary """ # sometimes a failed command will return html which end up in (e.g.) pilotErrorDiag, remove it if TCPMessage.upper().find("<HTML>") >= 0: # reset here. the error diag will b...
3f17c7ca4c7bb738e055127b1150bbbcbffd8653
3,598,951
from datetime import datetime import pytz def now(): """Returns the ISO 8601 formatted time in UTC""" return datetime.now(pytz.utc).isoformat()
e423e8555315f551f284c92f4fee5b3f92c1f41d
3,598,952
def carmichaellambda(n): """carmichaellambda(n) - Computer Carmichael's Lambda function of n - the smallest exponent e such that b**e = 1 for all b coprime to n. Otherwise defined as the exponent of the group of integers mod n.""" thefactors = factors(n) thefactors.sort() thefactors += [0] # Mark the end of the...
c076deb1a8216c2da32a2f83cc224bf3fe6b5040
3,598,953
def layout_photo_5_2(photo): """ 在5寸照片上排版2寸照片 :param photo: 待处理照片2寸 :return: 处理后的照片 """ bk = Image.new("RGB", (HEIGHT_5IN, WIDTH_5IN), (255, 255, 255)) # 竖版排版 # 创建画笔 draw = ImageDraw.Draw(bk) draw.line([(0, WIDTH_5IN / 2), (WIDTH_5IN, WIDTH_5IN / 2)], fill=128) # 横线 draw.line([...
2183babdc363620c7126df810c6d7e85fdbdebe0
3,598,954
from typing import Set def get_gt_nsrts(predicates: Set[Predicate], options: Set[ParameterizedOption]) -> Set[NSRT]: """Create ground truth NSRTs for an env.""" if CFG.env in ("cover", "cover_hierarchical_types", "cover_typed_options", "cover_regrasp", "cover_multistep_opti...
1fa376eef49e0ac09b89c0a3ccfc096edd159779
3,598,955
import zlib import struct def fragments_to_schedule(fragments: list) -> dict: """Convert a set of fragments (a blob) into a schedule. May raise a `zlib.error` exception. """ raw_schedule = zlib.decompress(bytearray.fromhex("".join(fragments))) zone_idx, schedule = None, [] old_day, switchpo...
b9d436a539675333c24d174c0d7a309438b28ee4
3,598,956
def compute_scl_mask( scl, mask_vals, gdf, verbose=False, verbose_plot=False, scene_id=None, res=None, date=None, bins=100): """Compute the Red Chlorophyll Index image from band08 and band04 values Args: scl (dict): Sentinel-2-L2A Band04 raster data mask_vals (dict): Sentinel-2-...
6c19a3d188a5bff07712b6e926ece7c02c08ad21
3,598,957
def r_value(aa1, aa2, aa_dict, matrix): """ :param aa1: :param aa2: :param aa_dict: :param matrix: :return: """ return sum([(matrix[i][aa_dict[aa1]] - matrix[i][aa_dict[aa2]]) ** 2 for i in range(len(matrix))]) / len(matrix)
034d1d7eb0baa63cd5bd4572c87f86bcc8774de4
3,598,958
def init(param_test): """ Initialize class: param_test """ # initialization default_args = ['-t mt/label/ -w mt/warp_template2mt.nii.gz -gm mt/mt1_gmseg.nii.gz -wm mt/mt1_wmseg.nii.gz -manual-gm mt/mt1_gmseg_goldstandard.nii.gz -sc mt/mt1_seg.nii.gz -param step=1,type=seg,algo=centermassrot,metric=M...
cd0b7e61cabda521c0f07e72e74316e7766ea2d2
3,598,959
def compose_all(graphs, name=None): """Return the composition of all graphs. Composition is the simple union of the node sets and edge sets. The node sets of the supplied graphs need not be disjoint. Parameters ---------- graphs : list List of NetworkX graphs name : string S...
0dd2a9f4e846cc7a7410ecc04cb1f85e2776bbe9
3,598,960
def create_Q_scipy(par,sol,ast,solmethod): """ create Q for use with scipy """ def remove_small(x): I = np.abs(x) < eps_low y = x.copy() y[I] = 0 return y for iz in range(par.Nz): #order of diagionals is important to getsorted indices ast.Qs[iz] = diags( di...
4172f8c116803d2a0f030f442f647c56f67478d6
3,598,961
import os def upload_to_s3_bucket(bucket, file, key, callback=None, md5=None, reduced_redundancy=False, content_type=None, encrypt_key=False): #TODO: Unit Test. """ Uploads the given file to the AWS S3 bucket and key specified. callback is a function of the form: def callback(complete, total) ...
2151bdf583836bf65dee46ed0143e24b0af50d24
3,598,962
import os def project_trajectory(dir_file, w, s, dataset, model_name, model_files, dir_type='weights', proj_method='cos'): """ Project the optimization trajectory onto the given two directions. Args: dir_file: the h5 file that contains the directions w: weights ...
d0a68cdf2171906b9e5e2c99e58235c59fc0087d
3,598,963
import os def get_car_images(data): """ Generate dataframe with columns: (ID, images) containing indexes of car exterior images for each car ID Args: data (pd.DataFrame): Car features dataframe Returns: (pd.DataFrame): Dataframe of ID's and images """ car_image_df = pd.DataFra...
0ac53a01549a65657b2535c0735633e0ac3bdb4b
3,598,964
def init_standard(nnet, dataset): """My standard initialization for a neural network """ # use orthogonal initialization of all W's for synapse in nnet.synapses: W_start = synapse.W shape = B.eval(W_start.shape) W_final = orthogonal(shape) B.set_value(W_start, W_final) ...
882e0b886bb17877983404b3aa8232e9c499d674
3,598,965
def calculateProgressMetrics(job): """ job has the most recent values updated for the current event being processed. Calculate status and progress metrics using the new information. :param job: JSON job data struture from dynamodb """ progressMetrics = {} # BASE TIMES FROM EVENTS # cr...
73524e53f5dd77c81cd0e9f6239588e41b9bc841
3,598,966
def _ydiff_excess_equals_expected(yint, xmin, xmax, x, model): """The ExcessEqualsExpected method to compute Y (differential). y / yint = y_model / yint_model""" yint_model = _integrate(xmin, xmax, model) y_model = model(x) return y_model * (yint / yint_model)
8476fee5e720ddb45a46a9baa61b18dc235f27bc
3,598,967
def rescale_boxes(boxes, current_dim, original_shape): """ Rescales bounding boxes to the original shape """ orig_h, orig_w = original_shape # The amount of padding that was added pad_x = max(orig_h - orig_w, 0) * (current_dim / max(original_shape)) pad_y = max(orig_w - orig_h, 0) * (current_dim / m...
769264b54e0a2dc438d78942e4c86f46c1b6470e
3,598,968
def get_summary_indices(df, on='NOSC'): """ Get the summary stats for the indices: median, mean, std, weighted mean and weighted std """ samples = get_list_samples(df) samples.append(on) t = df[samples] t = t.melt(id_vars = [on], var_name = 'SampleID', value_name = 'NormIntensity') t = t[t[...
34549141bdcd7b4092748c540275d4cea4ead9cf
3,598,969
def get_eqopp_policy_from_selection_rate(selection_rate, loan_repaid_probs, pis, scores): """Return policy with specified selection rate on Y=1 for both groups.""" # compute P(X, Y=1|A) ...
bffa9b5f3d1715b21422074b1c1b4d8c08fe6583
3,598,970
def getWell(mmdict, df, size, row, column, nchannels, channels=None): """ Get every image patch in a well Parameters ---------- mmdict : dict dictionary of memmap file df : DataFrame size : int size of image patches row : int row in the plate column: int ...
4814e8b8ab636691486dc7fd73077b9a84bc403a
3,598,971
def concat_time_series_matrices(mats, t=None): """Concatenate a list of gene x cell matrices into a single matrix. Arguments --------- mats: :class:`~numpy.ndarray` A list of gene x cell matrices. The length of the list equals the number of time points t: :class:`~numpy.ndarray` or list ...
afca744f7bbb945038efa59c36d44243ac5dbaa2
3,598,972
def get_route_config(route, ifname): """ Builds a basic route config dictionary with all of the fields required to format a basic network_route puppet resource. """ if route['prefix']: name = '%s/%s' % (route['network'], route['prefix']) else: name = 'default' netmask = IPNet...
e9400f52c2647a44e88932b2d808c6f18b4169ce
3,598,973
def concat (tensors_list, axis): """ Better version. """ if len(tensors_list) == 1: return tensors_list[0] return tf.concat(tensors_list, axis)
f0316f688ff0cc3a0d18970a9d614d48db584e89
3,598,974
def redundant(src, key=None, distinct=False, sort=True): """The complement of unique(), returns non-unique values. Pass distinct=True to get a list of the *first* redundant value for each key. Results are sorted by default. >>> redundant(range(5)) [] >>> redundant([1, 2, 3, 2, 3, 3]) [[2, 2...
3b660e5ba3833c95bba97e4546b7915d6f0343ae
3,598,975
import os import json import sqlite3 def session_db(data_dir: str, db_name='session.db', alp=None): """Writes a relational database (sqlite3) of session data that can be used for exploratory analysis. Parameters: ----------- data_dir - directory with the session.json data (and parameters.json...
ab23331e9ecc86ee3e006ecd58ee28502ab48fa1
3,598,976
from datetime import datetime def serialize(data, maximum_depth=0, level=0): """ Serializes dicts and django models to dict :param data: The data :param maximum_depth: Maximum recursion depth :param level: Current level :return: A dict """ result = None if isinstance(data, dict): ...
48cd8a5dad8d4a200be9f56e66faf0421052dd03
3,598,977
def create_embeddings_dic(all_words, embeddings_path, num_dimensions): """ :param all_words: :param embeddings_path: :param num_dimensions: :return: """ embeddings_dic = {} print("Building embeddings dic from " + embeddings_path) with open(embeddings_path, "rb") as infile: ne...
6a621df4d55ec8c7151fbe8d105b98787414b559
3,598,978
def user_can_view_data(user): """ Determine if the user is active and authenticated. :param user: The user to lookup. :type user: str :returns: True, False """ if user.is_active: if user.has_access_to(GeneralACL.WEB_INTERFACE): return user.is_authenticated() else...
34849adc4f87892711e52542e5142a6d9fd27df7
3,598,979
def most_similar_command(command: str, command_list: set) -> (list, str): """ Determine whether its possible to suggest a similar command. The similarity is determined by the levensthein distance and a factor (currently 1/3) sets a limit where a similar command is useful to be automatically used. If the...
58fe2cca6b7194745274e6e873cde0ca2e4980fa
3,598,980
import torch def precision_score(tp: torch.Tensor, fp: torch.Tensor, reduce: bool = True) -> torch.Tensor: """Computes the precision using true positives and false positives. :param tp: true positives, dims (C,) or () :type tp: torch.Tensor :param fp: false positives, dims (C,) or () :type fp: tor...
33ba13fbf4a267c43d32b440e5aaab317e671e50
3,598,981
def gen_cp(duration, h): """ generate the CP times from the trial by successively sampling from an exponential distribution :param duration: trial duration in sec :param h: hazard rate in Hz :return: numpy array of change point times strictly positive and inferior to duration """ cp_time...
4975795a9726e73987fccd0af65aa9f6430c1005
3,598,982
import socket def tcp_socket_open(host, port): """ Returns True if there is an open TCP socket at the given host/port """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) try: return sock.connect_ex((host, port)) == 0 except socket.timeout: return...
11519e5d9f2d1de39d8091af011f0458e556021c
3,598,983
import os def read_asteroid_map(map_path: str, root_path: str = 'data/raw', ) -> np.ndarray: """ Reads a file containing an asteroids map and returns a zero matrix with ones in asteroid positions. """ # Check the parameters path = os.path.join(root_...
374503d26902cfe74005e266fc453eff65777a60
3,598,984
def make_color_wheel() -> np.ndarray: """ Create colour wheel. Code adapted from https://github.com/liruoteng/FlowNet/blob/master/models/flownet/scripts/flowlib.py """ red_yellow = 15 yellow_green = 6 green_cyan = 4 cyan_blue = 11 blue_magenta = 13 magenta_red = 6 ncols = re...
71e64dd033164ce6541e67365583f7d0d5d2fd7e
3,598,985
def get_geo_node_us(dirname, points, state, county, simplify): """ This function maps a each node to a geographic region. For US only. """ # Directories shapepath = dirname + '/resources/additional_info/state_'+ state + '/cb_2015_'+state+'_tract_500k' # Read in shapefile sf = shapefile.R...
33c3fb8073d2faae5faf1b632e7a64c9afe09355
3,598,986
def gather_local_building_blocks(local_building_blocks, n_global_discretes): """Processes a nearest-neighbour acyclic_graph into `SevenDiscretedOperator`s. The acyclic_graph is defined by the list of numpy arrays `local_building_blocks`, and is laid out as ────┴┐ ┌┴─────┴┐ ┌┴─────┴┐ ┌┴───── N-1 │...
dc39baa03e693399eb9b355f9ee305e20a5b9929
3,598,987
def transparently(function): """ Wrap ``function`` so that it is called, but that the first parameter is returned. """ @wraps(function) def decorated(value, *args, **kwargs): function(value, *args, **kwargs) return value return decorated
30a0bc37093b18a36edf5b910342b229349e6582
3,598,988
import re def is_relative_import_name(import_name: str) -> bool: """Checks if an import name is relative.""" return re.fullmatch(_RELATIVE_IMPORT_NAME_REGEX, import_name) is not None
428925346bf0f710a886bc7b05174321142601a8
3,598,989
def decode_html(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS): """ Converts a `html` containing an HTML page into Unicode. Tries to guess character encoding from meta tag. """ if isinstance(html, unicode): return html if encoding: return html...
7dbb2b71a24c3a7662f2351eba516f6f0c518bb3
3,598,990
def variance(data): """ Assumes that an array of integers is passed """ mean = sum(data)/len(data) tot = 0.0 for d in data: tot += (d - mean)**2 return tot/mean
3329792cf7043ad6e68cad39d6a07bf2909d1496
3,598,991
import os def detectPhantomVolume(serverRoot=None): """ Check to see if serverRoot directory exists in a "phantom" volume, meaning it's simply a directory under /Volumes residing on the boot volume, rather that a real separate volume. """ if not serverRoot: serverRoot = getServerRoot(...
5ae08fefc9d3cb0d51e948ff3a1b52dac2509775
3,598,992
def generalized_parity_solver_with_partial(g, partial_solver): """ Generalized parity games solver. This is an implementation of the classical algorithm used to solve generalized parity games. This is the wrapper function which complements every priority and calls the actual algorithm. :param g: the gam...
142424d5f315cdb7e9fd1f6c2fbbf4f44493aacc
3,598,993
def susceptible_60(): """ Real Name: b'Susceptible 60' Original Eqn: b'INTEG ( deimmunization rate 60-infection rate 60, init Susceptible 60)' Units: b'person' Limits: (None, None) Type: component b'' """ return _integ_susceptible_60()
0d180ea1a1523e6ee748bcf8f9e283d5e2bde2f2
3,598,994
import os import requests def download_sample_cluster_events( host, token, sample_cluster_pk, filename=None, directory=None, method=METHOD['https']): """ Download sample data as CSV or Numpy (npy) Options: 'data_format': 'npy' (default) or 'csv' ...
1ba52698d894bc1a298fd569c5f8df9d579a3369
3,598,995
def encode_track_results(track_results): """Encode bitmap mask to RLE code. Args: track_results (list | tuple[list]): track results. In mask scoring rcnn, mask_results is a tuple of (segm_results, segm_cls_score). Returns: list | tuple: RLE encoded mask. """ ...
371fcc456cfa21c34a9c8dab95f90b9b4f2ec7f9
3,598,996
def linear_activation_backward_reg(dA, cache, activation_fn="relu", lambd=0): """ Arguments --------- dA : 2d-array post-activation gradient for current layer l. cache : tuple values of (linear_cache, activation_cache). activation : str activation used in this layer: "sig...
a1075628dfc62969d981c4537e5b44fd44b5f461
3,598,997
import traceback def get(key, response=None): """Returns k:str to exist in the yml file, Otherwise it returns default.""" try: global CONF_FILE if CONF_FILE: if isinstance(key, str): sb = key.strip('.').split('.') p = CONF_FILE for i...
f36c0fd787966c63ce2b2f3cf1b397ffceb8f4a5
3,598,998
from typing import Union from typing import List from typing import Optional from typing import Dict from pathlib import Path import torch def train_model_pretraining( dataset_name: Union[str, List[str]] = None, dataset_sampling: Union[float, List[float]] = None, dataset_dir: str = None, ...
dd7d445e7fc1193a9e1f77086ee06f1f31784eda
3,598,999