content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def shift_time(x, dt): """Shift time axis to the left by dt. Used to account for pump & lamp delay""" x -= dt return x
c93fdddea8e41221583139dcc7a2d81177ba7c17
8,800
from datetime import datetime import json def eps_xfer(request,client_slug=None,show_slug=None): """ Returns all the episodes for a show as json. Used to synk public url's with the main conference site. """ client=get_object_or_404(Client,slug=client_slug) show=get_object_or_404(Show,client=...
9a6691e0ac750919b5915e45ace0c347aa83cbe3
8,801
def register(class_, option=None, get_funcs={}): """A decorator to register a function as the way to display an object of class_ """ if option: key = (class_, option) else: key = class_ def decorator(func): class_function_mapping[key] = (func, get_funcs) return func return decorator
c060691dd9e2760905e29a2c643dfa63d4ed029c
8,802
def startup(target: machine.Machine, workload: str, count: int = 5, port: int = 0, **kwargs): """Time the startup of some workload. Args: target: A machine object. workload: The workload to run. count: Number of containers to start. port: The port to ...
c53b627d95270aa074f9178e1ebcd6ea49b8eeaa
8,803
def schema_handler(request): """ Handle schema request from UI. """ logger.debug("schema_handler: enter") req = request.GET.get('payload', '') action = request.GET.get('action', '') logger.debug('Received schema Request (%s)' % action) if not request.user.is_authenticated(): log...
0a7997e5ad946aebfbf915b1dd2dddcf46d5fe2e
8,804
def log2_fold_change(df, samp_grps): """ calculate fold change - fixed as samp_grps.mean_names[0] over samp_grps.mean_names[1], where the mean names are sorted alphabetically. The log has already been taken, so the L2FC is calculated as mean0 - mean1 :param df: expanded and/or filtered dataframe ...
07fcef6f5143095f4f8f77d0251bbd7ecd486fd9
8,805
def infer_wheel_units(pos): """ Given an array of wheel positions, infer the rotary encoder resolution, encoding type and units The encoding type varies across hardware (Bpod uses X1 while FPGA usually extracted as X4), and older data were extracted in linear cm rather than radians. :param pos: a ...
82d1a63c11c31d4de83ba5360def223b85194ef9
8,806
def extract_tform(landmarks, plane_name): """Compute the transformation that maps the reference xy-plane at origin to the GT standard plane. Args: landmarks: [landmark_count, 3] where landmark_count=16 plane_name: 'tv' or 'tc' Returns: trans_vec: translation vector [3] quat: quaterni...
d9d4ed43c9572cdd76b34235e380f22a6eb27d03
8,807
from typing import TextIO import csv def load_events(fhandle: TextIO) -> annotations.Events: """Load an URBAN-SED sound events annotation file Args: fhandle (str or file-like): File-like object or path to the sound events annotation file Raises: IOError: if txt_path doesn't exist Retur...
2c2017d754fe12ebd37349b359ba6a92ec115421
8,808
import os def loadandcleanRAPIDexport(rapidsubproductsexport): """ :param rapidsubproductsexport: an Excel file name with ".xlsx" extention :return: """ exportfile = os.path.realpath("gannt_data/"+ rapidsubproductsexport) df = pd.read_excel(exportfile,na_values=["-"]) df = convertFYQfields...
0ff955267ec0baa3e67d0e65e945317b2ea57128
8,809
def set_nan(df, chrom_bed_file): """This function will take in a dataframe and chromosome length bed file and will replace 0's with np.nan according to each chromosome length. This will fix any issues when calculating Z-scores""" # Build dictionary of key=chromosome and value=chromosome_length chrom...
e90008c42db5a94c8676c941da5832438301a724
8,810
def configure_smoothing(new_d,smoothing_scans): """ # <batchstep method="net.sf.mzmine.modules.peaklistmethods.peakpicking.smoothing.SmoothingModule"> # <parameter name="Peak lists" type="BATCH_LAST_PEAKLISTS"/> # <parameter name="Filename suffix">smoothed</parameter> # <parameter nam...
031586cf5dbb9fdf1fb6762a89a988367d172942
8,811
def contact_us(): """ Contact Us Route Route to lead to the contact page Args: None Returns: rendered template for contact_us.html """ return render_template('contact_us.html', title='CONP | Contact Us', user=current_user)
2597038074e8f60e14066f10390a161b15cf7071
8,812
def costFunc1(x, module, output, col, row, bbox, img, prfObj): """Debugging function. Does the same as costFunc, but col and row are constants, and only the brightness of the prf can be changed. """ model = prfObj.getPrfForBbox(module, output, col, row, bbox) model *= x[0] cost = img-mode...
1af21d844482d773e0bf279a49f12520ffb27aa8
8,813
import pandas def query_field(boresight, r1=None, r2=None, observatory='apo', mag_range=None, mag_column=None, database_params=None): """Selects Gaia DR2 stars for a field, from the database. Parameters ---------- boresight : tuple A tuple with the right ascension and declinat...
c05276ecfac3b33dcc5382cf54e220b416614656
8,814
def get_throttling_equilibria(simulation_config, input_params, priority_queue=True, dev_team_factor=1.0): """ Returns the equilibrium profiles for throttling configuration under analysis. :param simulation_config: :param input_params: :return: """ desc_inf003 = "THROTTLING_INF003" proce...
4e0f6dd8fa3b0b36b713b33ab1a5aaf8394d4942
8,815
def signature(part): """ return the signature of a partial object """ return (part.func, part.args, part.keywords, part.__dict__)
522ae88538d6dd880492292c6f2ef169f3bbd06d
8,816
def clean_key(func): """Provides a clean, readable key from the funct name and module path. """ module = func.__module__.replace("formfactoryapp.", "") return "%s.%s" % (module, func.__name__)
946288cd231148eb39af5d1e7e0b957d9f2131e8
8,817
def rotY(M, alpha): """Rotates polygon M around Y axis by alpha degrees. M needs to be a Numpy Array with shape (4,N) with N>=1""" T = np.eye(4) alpha_radians = np.radians(alpha) sin = np.sin(alpha_radians) cos = np.cos(alpha_radians) T[0,0] = cos T[2,2] = cos T[0,2] = sin T[2,0]...
49e850ff66b3c7877e6d8b4a450baaa6707d4f15
8,818
def is_image_file(filename): """ :param filename: :return: """ return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
40125478c6440efc9a740d2df57ba2f7bb15a5d1
8,819
def invert_comp_specifier(comp_specifier): """ return the opposite (logical negation) of @p comp_specifier """ inverse_map = { Comparison.Equal: Comparison.NotEqual, Comparison.Less: Comparison.GreaterOrEqual, Comparison.LessOrEqual: Comparison.Greater, Comparison.NotEqual: Compa...
187392dd1dc7f52c744536e8e372cab752ff8c85
8,820
import utm def latlong2utm(point): """ This function converts a point from lat long to utm Input : point : (lat,long) Output : utm point : (x,y,z, n) """ return utm.from_latlon(point[0],point[1])
3ee82f9df84b02aa35fa0f2a35ec0916edf30e42
8,821
def multiply(a,b): """ multiply values Args: a ([float/int]): any value b ([float/int]): any value """ return a*b
67a85b1675da48684e9de7e9834d3daa4357699b
8,822
from typing import Tuple from typing import Dict from typing import List import regex def merge_vocab(pair: Tuple[str, str], input_vocab: Dict[str, int]) -> Tuple[Dict[str, int], List]: """ >>> pair = ('w', 'o') >>> input_vocab = {'b i r d @': 3, 'w o r d @': 7, 'w o g @': 13} >>> new_vocab, new_pairs...
15226aa9ebd9cae73e5bd00b60cb1b3bbb5d8e07
8,823
def visualize_bbox_act(img, bboxes,labels, act_preds, classes=None,thickness=1, font_scale=0.4,show=False, wait_time=0,out_file=None): """Show the tracks with opencv.""" assert bboxes.ndim == 2 assert labels.ndim == 1 assert bboxes.shape[0] == labels.shape[0] ...
de67d5acba2b2994ec2b66ae4e7e0c58498ecebe
8,824
def calculate_similarity(subgraph_degrees): """ Given a list of subgraph degrees, this function calls the guidance function and calculates the similarity of a particular node with all it's non-connected nodes. :param subgraph_degrees: A list of lists containing the non connected node and degree...
cd4be7c405b2974f35db24dbd7d7db7bdf9a867e
8,825
def balance_thetas(theta_sets_types, theta_sets_values): """Repeats theta values such that all thetas lists have the same length """ n_sets = max([len(thetas) for thetas in theta_sets_types]) for i, (types, values) in enumerate(zip(theta_sets_types, theta_sets_values)): assert len(types) == len(va...
3ca7316a18d57c95adbfbdfec5f5be36f33dc0ea
8,826
def _format_weights(df, col, targets, regs): """ Reformat the edge table (target -> regulator) that's output by amusr into a pivoted table that the rest of the inferelator workflow can handle :param df: pd.DataFrame An edge table (regulator -> target) with columns containing model values :pa...
b683846d9d059a39280077a714455718bd710670
8,827
def put_thread(req_thread: ReqThreadPut): """Put thread for video to DynamoDB""" try: input = thread_input.update_item(req_thread) res = table.update_item(**input) return res except ClientError as err: err_message = err.response["Error"]["Message"] raise HTTPExcepti...
dba9fe080451a3cb68365824faf8dbccad03b1b6
8,828
def _get_or_create_campaign_team(name, owner, tasks, redudancy): """ Creates CampaignTeam instance, if it does not exist yet. Returns reference to CampaignTeam instance. """ # pylint: disable-msg=no-member _cteam = CampaignTeam.objects.get_or_create( teamName=name, owner=owner, ...
4bb7980c621e48aa1eea3471004c627a8ea18e21
8,829
def check_method(adata): """Check that method output fits expected API.""" assert "labels_pred" in adata.obs return True
78c1a5181395f1675854333c30bf617c578cc1d4
8,830
def build_index_block(in_channels, out_channels, kernel_size, stride=2, padding=0, groups=1, norm_cfg=dict(type='BN'), use_nonlinear=False, expa...
03e15760146ce75f06de64ffd6886fe627afcf9b
8,831
def nodes(*paths, type=None): """Call node() on each given path and return the list of results. nodes('foo', 'bar', ...) is equivalent to [node('foo'), node('bar'), ...] """ return list(map(lambda p: node(p, type=type), paths))
d1ae50237a275c70b9b9e85684e898494fc6c954
8,832
def GetCodeBucket(app, project): """Gets a bucket reference for a Cloud Build. Args: app: App resource for this project project: str, The name of the current project. Returns: storage_util.BucketReference, The bucket to use. """ # Attempt to retrieve the default appspot bucket, if one can be cre...
603126fc33dedb941407a66618748b1d58b91570
8,833
def parse_rule(parameter_string): """Parse a parameter string into its constituent name, type, and pattern For example: `parse_parameter_string('<param_one:[A-z]>')` -> ('param_one', str, '[A-z]') :param parameter_string: String to parse :return: tuple containing (parameter_nam...
881e219ab59c801da078e91cf82ccb15caa7798d
8,834
def plan(): """ 改进方案 :return: """ return render_template('plan.htm')
135d8b003adbe8f6311f781f0d4ff7ed206a81d6
8,835
def extract_traceback(notebook): """ Extracts information about an error from the notebook. Parameters ---------- notebook: :class:`nbformat.notebooknode.NotebookNode` Executed notebook to find an error traceback. Returns ------- bool Whether the executed notebook has an er...
9af26f973e6810936eaa68058efcdb7bc145803b
8,836
def get_log() -> str: """get_log() -> str (internal) """ return str()
3e2d7bf82128afc664eded15e6c11f1ed9da45e7
8,837
def start_server(self, parameters): # pragma: no cover """adds the server start to celery's queue Args: parameters(dict): The POST JSON parameters """ self.update_state(state=CeleryStates.started) session = ServerSession(parameters) return session()
c20e2233ee7c1e6b1718b0c4bfbb2b9b5f52e0e1
8,838
def generate_config(context): """ Entry point for the deployment resources. """ properties = context.properties name = properties.get('name', context.env['name']) project_id = properties.get('project', context.env['project']) bgp = properties.get('bgp', {'asn': properties.get('asn')}) router ...
506c7ded703b8c00fb9a2a6d7645e9e5d0da6905
8,839
import time def cachedmethod(timeout): """ Function decorator to enable caching for instance methods. """ def _cached(func): if not(hasattr(func, 'expires')): func.expires = {} func.cache = {} def __cached(self, *args, **kwargs): if(timeout and func.expires.get(repr(self), 0) < time.time()): if(r...
dd8999a60aa6d92e6b442c7c0661d88cd0e8590e
8,840
def __build_pyramid(models, features): """Applies all submodels to each FPN level. Args: models (list): List of submodels to run on each pyramid level (by default only regression, classifcation). features (list): The FPN features. Returns: list: A list of tensors, one f...
269be978f9aafbdc36b1c9d726171785a85f54a4
8,841
def get_ap_list(): """ Method to return list of aps present in the network """ return jsonify_params( CELLULAR_NETWORK.ap_list )
da0777219025499603425f3147b2897d2bce2da6
8,842
def _merge_url_rule(rule_before, rule_after): """ Merges two url rule parts. Parameters ---------- rule_before : `None` or `tuple` of `tuple` (`int`, `str`) First url part if any to join `rule_after` to. rule_after : `None` or `tuple` of `tuple` (`int`, `str`) Second url part wh...
0682734a82b227f746325363652d1c3f378f2e51
8,843
import argparse def parse_options(args): """ Parse commandline arguments into options for Monitor :param args: :return: """ parser = argparse.ArgumentParser() parser.add_argument( "--tcp", required=True, action="append", help="TCP/IP address to monitor, e.g...
adda9497c230b885887b8c21f8e1adfd8bdd2376
8,844
def create_graphic_model(nodes, edges, gtype): """ Create a graphic model given nodes and edges Parameters ---------- nodes : dict for each node {key, text, math} edges : dict for each edge {key, text, math} gtype : str [default="text"] "text" for a verbose version, ...
028c740cc7fa003642815a8ec0f27154fc6e0dab
8,845
def zero_cross_bounds(arr, dim, num_cross): """Find the values bounding an array's zero crossing.""" sign_switch = np.sign(arr).diff(dim) switch_val = arr[dim].where(sign_switch, drop=True)[num_cross] lower_bound = max(0.999*switch_val, np.min(arr[dim])) upper_bound = min(1.001*switch_val, np.max(ar...
52d3431c32f61f47223fdccf4c5a85a92589534f
8,846
def remove_tseqs(t: ST_Type) -> ST_Type: """ Get just the sseqs and the non-nested types, removing the tseqs """ if type(t) == ST_SSeq or type(t) == ST_SSeq_Tuple: inner_tseqs_removed = remove_tseqs(t.t) return replace(t, t=inner_tseqs_removed) elif is_nested(t): return remov...
323f9cd3c007c1decf11653091f641dc453d32cb
8,847
def prod_cart(in_list_1: list, in_list_2: list) -> list: """ Compute the cartesian product of two list :param in_list_1: the first list to be evaluated :param in_list_2: the second list to be evaluated :return: the prodotto cartesiano result as [[x,y],..] """ _list = [] for element_1 in ...
9fdbfc558f5ec3b11c78535b9125e0a1c293035e
8,848
from .esri_basemap import esrimap def classFactory(iface): # pylint: disable=invalid-name """Load esrimap class from file esrimap. :param iface: A QGIS interface instance. :type iface: QgsInterface """ # return esrimap(iface)
3e067a97cba21a07c818077e4207cd8e337143d9
8,849
def gpib_open(name): """ Start a device session. Returns a unique integer for the instrument at the specified GPIB address. For example:: >>> gpib_open(lan[158.154.1.110]:19) 4 @param name : LAN/GPIB address of the device @type name : str @return: int """ (devtype,devID) = name.split() add...
fa9e87a3873248866586758c0b0f370a3ad29e6e
8,850
def myjobs_view(request): """ Renderbox view :param request: :return: """ return render(request, 'renderbox/myjobs.html')
ac0ffbc92a33657a165beb5e12905e3dc495c943
8,851
import functools import sys def set_task_payload(func): """Set TASK_PAYLOAD and unset TASK_PAYLOAD.""" @functools.wraps(func) def wrapper(task): """Wrapper.""" environment.set_value('TASK_PAYLOAD', task.payload()) try: return func(task) except: # Truly catch *all* exceptions. e = s...
a1ba88a6bf5df872eab712c6ffe52be2c2fd3283
8,852
def _match_contact(filter_criteria): """ This default matching strategy function will attempt to get a single result for the specified criteria. It will fail with an `unmatched` result if there are no matching contacts. It will fail with a `multiple_matches` result if there are multiple matches ...
088199ac26dc226e1412b43ed0c9b380c669c64e
8,853
from typing import Generator def get_objects_dictionary(): """ creates a dictionary with the types and the circuit objects :return: Dictionary instance """ object_types = {'bus': Bus(), 'load': Load(), 'static_generator': StaticGenerator(), ...
bd82c2dc30877f841e4275aafbe054849b6f6ba2
8,854
def create_stripe_onboarding_link(request, stripe_id=None,): """Creates stripe connect onboarding link by calling Stripe API.""" account_links = stripe.AccountLink.create( account=stripe_id, return_url=request.build_absolute_uri( reverse("users:stripe_callback") ), re...
1dd1e7c50645fb5eaa36d7426abd5cff198e1610
8,855
def add_scheme_if_missing(url): """ >>> add_scheme_if_missing("example.org") 'http://example.org' >>> add_scheme_if_missing("https://example.org") 'https://example.org' """ if "//" not in url: url = "http://%s" % url return url
97a33ce1f60ab67e6a807ef1bd1d95250b5d18c6
8,856
from typing import Dict def _extract_assembly_information(job_context: Dict) -> Dict: """Determine the Ensembl assembly version and name used for this index. Ensembl will periodically release updated versions of the assemblies which are where the input files for this processor comes from. All divisi...
b78513b826c0a12bf87563095e33320aee328b76
8,857
def fixture_circle_2() -> Circle: """Return an example circle.""" return Circle(Point(0.0, 0.0), 1.0)
4040cb356a1e09cfe83280711d93a43b9352ff66
8,858
from warnings import warn import logging from fparser import api from loopy.frontend.fortran.translator import F2LoopyTranslator from loopy.transform.callable import merge from loopy.frontend.fortran.translator import specialize_fortran_division def parse_fortran(source, filename="<floopy code>", free_form=None, stri...
69d85ba20fd429598d3441297a89a12933f69925
8,859
def compute_sources(radius, evolved_vars): """ Computes source terms for the symmetry. """ mass_density = evolved_vars[0] momentum_density = evolved_vars[1] energy_density = evolved_vars[2] factor = -_symmetry_alpha / radius pressure = compute_pressure(mass_density, momentum_density, ene...
f2c7c68f3d00a063f9a29b220f98f71c6bb02aef
8,860
def average_pq(ps, qs): """ average the multiple position and quaternion array Args: ps (np.array): multiple position array of shape Nx3 qs (np.array): multiple quaternion array of shape Nx4 Returns: p_mean (np.array): averaged position array q_mean (np.array): averaged qua...
b7064d75f07361d60375de1dad91e0139533b042
8,861
def logobase(**kwargs): """Create a PyGraphviz graph for a logo.""" ag = pygraphviz.AGraph(bgcolor='#D0D0D0', strict=False, directed=True, ranksep=0.3, **kwargs) ag.edge_attr['penwidth'] = 1.4 ag.edge_attr['arrowsize'] = 0.8 return ag
60772de3f3b33f58559ecfd3293cffc26cfe8e70
8,862
import torch def integral_raycasting( pixels: Tensor, mu: Tensor, rho: Tensor, lambd: Tensor, appearance: Tensor, background_appearance: Tensor, K: Tensor, dist_coef: Tensor = None, alpha: float = 2.5e-2, beta: float = 2e0, eps: float = 1e-8, ) -> Tensor: """ :para...
fc5165c04732ea021d105df5d5f997524b037abd
8,863
async def cors_handler(request, handler): """Middleware to add CORS response headers """ response = await handler(request) response.headers['Access-Control-Allow-Origin'] = '*' return response
c9f33261b1fb2e6dc3ab3139e657106a94c5bfd1
8,864
def validate_image(task: ExternalTask): """ To simulate BPMN/Failure/Success, this handler uses image name variable (to be passed when launching the process) """ log_context = {"WORKER_ID": task.get_worker_id(), "TASK_ID": task.get_task_id(), "TOPIC": task.get_topic...
97413656181bfc4480dc7b2a195713e8124d44f2
8,865
def simulate_patch(app, path, **kwargs): """Simulates a PATCH request to a WSGI application. Equivalent to:: simulate_request(app, 'PATCH', path, **kwargs) Args: app (callable): The WSGI application to call path (str): The URL path to request Keyword Args: params (di...
48fda74dc2765e3a281a71c7ba6f4144e9a258cd
8,866
def minimum_image_box(sizes): """Creates a distance wrapper using the minimum image convention Arguments: sizes (array-like of float): box sizes """ def _box(sizes, distance_vectors): """A minimum image wrapper for distances""" shift = sizes[None, None, :] * np.round(distance_ve...
5d26092a988a011e9fb1967a74c3ceec935f5b1b
8,867
def mlrPredict(W, data): """ mlrObjFunction predicts the label of data given the data and parameter W of Logistic Regression Input: W: the matrix of weight of size (D + 1) x 10. Each column is the weight vector of a Logistic Regression classifier. X: the data matrix of siz...
57542e5b54ddd223f4cbcae7adf932e85c4ffeeb
8,868
def calc_mean_score(movies): """Helper method to calculate mean of list of Movie namedtuples, round the mean to 1 decimal place""" return round(sum([movie.score for movie in movies]) / len(movies), 1)
ccf52f813091d1c907470996c62dafa61303e245
8,869
import hmac import hashlib def get_proxy_signature(query_dict, secret): """ Calculate the signature of the given query dict as per Shopify's documentation for proxy requests. See: http://docs.shopify.com/api/tutorials/application-proxies#security """ # Sort and combine query parameters into a sin...
c234f18c1d44a936c4844ae2fe1b912a624eef61
8,870
def candlestick_echarts(data_frame: pd.DataFrame, time_field: str = 'time', open_field: str = "open", high_field: str = 'high', low_field: str = 'low', close_field: str = 'close', volume_field: str = 'volume', mas: list = [5...
f8bc3d1ef876a5df0f2fdbdf7dbf97b039a54cc4
8,871
def select_sounder_hac(path_sounder, sounder): """ Donne les indices pour un sondeur (sounder) dans un hac (path sounder), et retourne les index de sondeur et de transducer correspondant inputs: path_sounder: path du hac à analyser sounder: nom du transducer outputs: index du son...
2f054ef6a8e3a64f0910e5eb4bce9407befc4b33
8,872
def upvote_checklist(request, checklist_id): # for "messages", refer https://stackoverflow.com/a/61603003/6543250 """if user cannot retract upvote, then this code be uncommented if Upvote.objects.filter(user=User.objects.filter(username=username).first(), checklist=Checklist.objects.get(id=checklist_id)): ...
559f9e0341652391b824b215448f87fa3250baae
8,873
def index(request): """查询页面""" ctx = {} Advert_1 = Advert.objects.get(advert_num=1) # 广告1 Advert_2 = Advert.objects.get(advert_num=2) # 广告2 ctx['Adverturl1'] = Advert_1.advert_url ctx['Adverturl2'] = Advert_2.advert_url ctx['Advertimg1'] = '/advert/'+ str(Advert_1.img) ctx['Advertimg2...
91e7a771273ed262e7025bc289defe7f6a52047e
8,874
def load_amazon(): """ """ df = pd.read_csv('data/amazon.txt', header=None, delimiter='\t') X_data = df[0].tolist() y_data = df[1].tolist() print 'Preprocessing...' vectorizer = TfidfVectorizer(strip_accents='unicode', lowercase=True, stop_words='english', ngram_range=(1, 2), max_df=0.5, min_df=5...
8e11cf91d616f7dfe17e26da2fcf43d82ea26f80
8,875
def get_switch_filters( switch_id, exception_when_missing=True, user=None, session=None, **kwargs ): """get filters of a switch.""" return _get_switch( switch_id, session=session, exception_when_missing=exception_when_missing )
db270f761fcdfb40a9d2970923b4643ebecf7cc3
8,876
def generalized_zielonka_with_psolC(g): """ Zielonka's algorithm with psolC partial solver. :param g: the game to solve. :return: the solution in the following format : (W_0, W_1). """ return generalized_parity_solver_with_partial(g, psolC_gen.psolC_generalized)
1ac4a81df393970c16a5f303155c89cf74db34ab
8,877
import seaborn as sns import matplotlib.pyplot as plt def plot_matrix(mat, figsize=(7, 4), draw_cbar=True, vmin=0, vmax=1, cmap=None): """ wrapper for plotting a matrix of probabilities. attribues (optional) are used as xlabels """ if np.any(mat < 0): print('rescaling matrix to probabilit...
a84948730816e5c59654fa6d0eeab773218fba61
8,878
from datetime import datetime def read_properties_core(xml_source): """Read assorted file properties.""" properties = DocumentProperties() root = fromstring(xml_source) creator_node = root.find(QName(NAMESPACES['dc'], 'creator').text) if creator_node is not None: properties.creator = creat...
357411103a52bbbfc6e621c47b734b9d11f04284
8,879
import torch def batch_decode(loc, priors, variances): """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes ...
7963b771e2c7bc560e5f9e5051abea43de2f46e3
8,880
def _step2_macs_seq (configs): """Step2 MACS if the raw data type is seq. So it will use the output from step1. """ # check the input t_rep_files = configs["samtools.treat_output_replicates"] t_comb_file = configs["samtools.treat_output"] c_comb_file = configs["samtools.control_output"] ...
69deb8fafeb3f7054901d431d6e32c647504258f
8,881
def menu_entry_to_db(entry): """ Converts a MenuEntry into Meal, Menu, and MenuItem objects which are stored in the database. """ menu, _ = Menu.objects.get_or_create(date=entry.date) meal = Meal.objects.create(meal_type=entry.meal_type, vendor=entry.vendor) for item_name in entry.items: ...
f35ddb4bb715a3a8bcee073fd863a5f4d8240651
8,882
import torch def get_device_of(tensor: torch.Tensor) -> int: """ Returns the device of the tensor. """ if not tensor.is_cuda: return -1 else: return tensor.get_device()
5532712bd812842fc462951e7c763b9753370174
8,883
def test_script_task(scheduler: Scheduler) -> None: """ Tasks should be definable as shell scripts. """ @task(script=True) def task1(message): return """echo Hello, {message}!""".format(message=message) assert scheduler.run(task1("World")) == b"Hello, World!\n"
c5f764b06f1245feb9ab0c1af5a13fd368fde362
8,884
import copy def __yaml_tag_test(*args, **kwargs): """YAML tag constructor for testing only""" return copy.deepcopy(args), copy.deepcopy(kwargs)
0abeb68caf32912c7b5a78dacbc89e537061a144
8,885
import os import json def _create_fake_bids_dataset(base_dir='', n_sub=10, n_ses=2, tasks=['localizer', 'main'], n_runs=[1, 3], with_derivatives=True, with_confounds=True, no_session=False): """Creates a fake bids dataset di...
9e9c33d9d51dbcd67eda66c4a14799219982601b
8,886
def format_data_for_training(data): """ Create numpy array with planet features ready to feed to the neural net. :param data: parsed features :return: numpy array of shape (number of frames, PLANET_MAX_NUM, PER_PLANET_FEATURES) """ training_input = [] training_output = [] for d in data: ...
b241a932f7a5321ed28dccd8a583fbcf7529e482
8,887
import urllib import json def idcardcert(appcode, card_no): """ 身份证实名认证身份证二要素一致性验证 """ host = 'http://idquery.market.alicloudapi.com' path = '/idcard/query' # method = 'GET' appcode = appcode querys = 'number=%s' % card_no # bodys = {} url = host + path + '?' + querys try: ...
a359edf15e7b8795fc80ceda1008f1809d9c52a0
8,888
def custom_error_exception(error=None, exception=None): """Define custom exceptions for MySQL server errors This function defines custom exceptions for MySQL server errors and returns the current set customizations. If error is a MySQL Server error number, then you have to pass also the exception ...
eb24301d2511199e1ee1407152f27d00b72adba5
8,889
import hashlib def cal_md5(content): """ 计算content字符串的md5 :param content: :return: """ # 使用encode result = hashlib.md5(content.encode()) # 打印hash md5 = result.hexdigest() return md5
0cd26654c364e34ecc27b0a0b4d410a539e286c3
8,890
import os def get_arkouda_server_info_file(): """ Returns the name of a file to store connection information for the server. Defaults to ARKOUDA_HOME + ak-server-info, but can be overridden with ARKOUDA_SERVER_CONNECTION_INFO :return: server connection info file name as a string :rtype: s...
c2ab568a02d6799f456bc0d96477353f3515c9fb
8,891
import re import os def _GenerateElementInfo(impl_path, names): """Generates the data a group needs to load sub elements. Args: impl_path: The file path to the command implementation for this group. names: [str], The names of the sub groups or commands found in the group. Raises: LayoutException: ...
cbecd4d5ad9ab235d1597ee272db0d244314d0a9
8,892
import os def locate_dir(instrument, mode=None): """Locate the instrument specific directory for a reference file. The mode=None test case is disabled because it mysteriously causes these tests to fail when running the runtests script: ERROR: test_throughput_lookup_generation (crds.tests.test_syn...
3d52a7b5cd70590c2edb78af5886ee0291476771
8,893
def pas(al, ap, bl,bp): """ Postion-angle from spherical coordinates. :param al: longitude of point A in radians. :type al: float :param ap: latitude of point A in radians. :type ap: float :param bl: longitude of point B in radians. :type bl: float :param bp: latitude of point B in r...
9d8321c908c793df84e5ff28c51e4a79f6db99c6
8,894
def get_messy_items_for_training(mod_factor=5): """ Fetch a subset of `FacilityListItem` objects that have been parsed and are not in an error state. Arguments: mod_factor -- Used to partition a subset of `FacilityListItem` records. The larger the value, the fewer records will be ...
d04f5471266c33cfea122adac72835043ed6c34a
8,895
def tanh_squared(x: np.ndarray, margin: float, loss_at_margin: float = 0.95): """Returns a sigmoidal shaping loss based on Hafner & Reidmiller (2011). Args: x: A numpy array representing the error. margin: Margin parameter, a positive `float`. loss_at_margin: The loss when `l2_norm(x) == margin`. A `fl...
4c8dbb826dad5b047682fe030362f4fe71021f06
8,896
def _inv_Jacobian_2D(J, detJ): """ manually invert 2x2 jacobians J in place """ tmp = J[:, 1, 1, :] / detJ J[:, 0, 1, :] = -J[:, 0, 1, :] / detJ J[:, 1, 0, :] = -J[:, 1, 0, :] / detJ J[:, 1, 1, :] = J[:, 0, 0, :] / detJ J[:, 0, 0, :] = tmp return J
23b1ff231e32f09f09dbae781f7e97354f3ca811
8,897
def ratio_error_acc(y_true, y_pred, epsilon, threshold): """ Calculate the ratio error accuracy with the threshold. :param y_true: :param y_pred: :param epsilon: :param threshold: :return: """ ratio_1 = keras.layers.Lambda(lambda x: (x[0] + x[2]) / (x[1] + x[2]))([y_true, y_pred, eps...
9ae487e056800ac9fb5cc6e92301b74c00d65c21
8,898
def error_embed(ctx: context.ApplicationContext, title: str, description: str, author: bool = True) -> discord.Embed: """Make a basic error message embed.""" return make_embed( ctx=ctx, title=title if title else "Error:", description=description, color=discord.Color.red(), ...
aca18ec2d25c4f0a2dec7f4c083716ab9bf4dbae
8,899