content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _uid_or_str(node_or_entity): """ Helper function to support the transition from `Entitie`s to `Node`s. """ return ( node_or_entity.uid if hasattr(node_or_entity, "uid") else str(node_or_entity) )
82f5747e8c73e1c167d351e1926239f17ea37b98
3,645,800
def power(maf=0.5,beta=0.1, N=100, cutoff=5e-8): """ estimate power for a given allele frequency, effect size beta and sample size N Assumption: z-score = beta_ML distributed as p(0) = N(0,1.0(maf*(1-maf)*N))) under the null hypothesis the actual beta_ML is distributed as p(alt) = N( beta , 1.0/(maf*(1-maf)N) )...
1806718cd0af5deb38a25a90864bb14f40e2c57a
3,645,801
def get_rotation_matrix(angle: float, direction: np.ndarray, point: np.ndarray = None) -> np.ndarray: """Compute rotation matrix relative to point and direction Args: angle (float): angle of rotation in radian direction (np.ndarray): axis of rotation point (np.ndarray, optional): center...
fd7c8d22368b51310a85453f6a9732f56a443803
3,645,802
import logging import sys import traceback import inspect def assert_check(args: dict = None, log_level: str = LOG_LEVEL) -> bool: """ assert caller function args """ if args is None: logger.critical("Arguments dict is empty or does not exist!") return False else: logging.debug("A...
a61d33f78f99cf91bcde7d5920ba20d6ac3e6816
3,645,803
from typing import Any import os def establish_github_connection(store: dict[str, Any]) -> ValidationStepResult: """ Establishes the connection to GitHub. If the name of the environment variable storing the GitHub PAT is not given, then it will default to searching for one named "GH_TOKEN". If provid...
8aab64c1d042639096b307f11dc469525095cfcf
3,645,804
def answer(panel_array): """ Returns the maximum product of positive and (odd) negative numbers.""" print("panel_array=", panel_array) # Edge case I: no panels :] if (len(panel_array) == 0): return str(0) # Get zero panels. zero_panels = list(filter(lambda x: x == 0 , panel_arra...
7169fba8dcf6c0932722dcbc606d6d60fdaf3ed1
3,645,805
def load_fromh5(filepath, dir_structure, slice_num, strt_frm=0): """ load_fromh5 will extract the sinogram from the h5 file Output: the sinogram filepath: where the file is located in the system dir_structure: the h5 file directory structure slice_num: the slice where the singoram will be ext...
90aa278a7429cc832071a374df9de2d8dd2abb88
3,645,806
def lqr_6_2(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): """Returns an LQR environment with 6 bodies of which first 2 are actuated.""" return _make_lqr( n_bodies=6, n_actuators=2, control_cost_coef=_CONTROL_COST_COEF, time_limit=time_limit, rando...
b27a4fd55d67cfcbb9a651b7915fd2e3b4460af9
3,645,807
def machine_stop(request, tenant, machine): """ Stop (power off) the specified machine. """ with request.auth.scoped_session(tenant) as session: serializer = serializers.MachineSerializer( session.stop_machine(machine), context = { "request": request, "tenant": tenant } ...
b91a375c1aa8b62a6ed665d0045ff4b9eeae6a18
3,645,808
import subprocess def exec_command_rc(*cmdargs, **kwargs): """ Return the exit code of the command specified by the passed positional arguments, optionally configured by the passed keyword arguments. Parameters ---------- cmdargs : list Variadic list whose: 1. Mandatory first ...
bfe4f5bbdcbed6cfc3c8f52abffe2be7107fd091
3,645,809
from typing import Tuple from typing import Dict from typing import Any def _get_input_value(arg: Tuple[str, GraphQLArgument]) -> Dict[str, Any]: """Compute data for the InputValue fragment of the introspection query for a particular arg.""" return { "name": __InputValue.fields["name"].resolve(arg, No...
7e82936b07b01531b0716c6904709c37e807d868
3,645,810
def wrapper(X_mixture,X_component): """ Takes in 2 arrays containing the mixture and component data as numpy arrays, and prints the estimate of kappastars using the two gradient thresholds as detailed in the paper as KM1 and KM2""" N=X_mixture.shape[0] ...
f5e093590897c363bbab2360a14d7c3a82fd6bcd
3,645,811
import torch def iou( outputs: torch.Tensor, targets: torch.Tensor, eps: float = 1e-7, threshold: float = 0.5, activation: str = "sigmoid" ): """ Args: outputs (torch.Tensor): A list of predicted elements targets (torch.Tensor): A list of elements that are to be predicted ...
4c43832560126c19b8b9ebc01daf3920603b5f17
3,645,812
def readCoords(f): """Read XYZ file and return as MRChem JSON friendly string.""" with open(f) as file: return '\n'.join([line.strip() for line in file.readlines()[2:]])
0cf1a9d07b4b3fe1836ce5c8a308ff67b5fe4c70
3,645,813
import os def fetch_hillstrom(target_col='visit', data_home=None, dest_subdir=None, download_if_missing=True, return_X_y_t=False, as_frame=True): """Load and return Kevin Hillstrom Dataset MineThatData (classification or regression). This dataset contains 64,000 customers who last purchas...
a400779d477f413e88c252d2f47b6318385f8ab1
3,645,814
def api_update_note(note_id: int): """Update a note""" db = get_db() title = request.form["title"] if "title" in request.form.keys() else None content = request.form["content"] if "content" in request.form.keys() else None note = db.update_note(note_id, title, content) return jsonify(note.__dict...
d6668b89854e4aa6c248041a97a55c95cd568e9e
3,645,815
def padding_oracle(decrypt, cipher, *, bs, unknown=b"\x00", iv=None): """Padding Oracle Attack Given a ciphersystem such that: - The padding follows the format of PKCS7 - The mode of the block cipher is CBC - We can check if the padding of a given cipher is correct - We can try to decrypt ciphe...
077eeed2f8f0f2e91aa482c93f36825bdbcef17a
3,645,816
def pixels(): """ Raspberry Pi pixels """ return render_template("pixels.html")
d3af0be80b09096e05a29ef3e9209cef2dba8431
3,645,817
async def get_song_info(id: str): """ 获取歌曲详情 """ params = {'ids': id} return get_json(base_url + '/song/detail', params=params)
2185c62db03bba3019d9d010fc5603c432a0048f
3,645,818
def _find_odf_idx(map, position): """Find odf_idx in the map from the position (col or row). """ odf_idx = bisect_left(map, position) if odf_idx < len(map): return odf_idx return None
642398d72abe89aa63b7537372499655af5a5ded
3,645,819
def get_or_create(session, model, **kwargs): """ Creates and returns an instance of the model with given kwargs, if it does not yet exist. Otherwise, get instance and return. Parameters: session: Current database session model: The Class of the database model **kw...
4d3e4f0da5ca61789171db5d8d16a5fa06e975cc
3,645,820
def pack_asn1(tag_class, constructed, tag_number, b_data): """Pack the value into an ASN.1 data structure. The structure for an ASN.1 element is | Identifier Octet(s) | Length Octet(s) | Data Octet(s) | """ b_asn1_data = bytearray() if tag_class < 0 or tag_class > 3: raise ValueError(...
14aad1709b5efa46edc5d7ac8659fe1de0615a57
3,645,821
from typing import Dict def choose(text: str, prompt: str, options: Dict[str, str], suggestion: str, none_allowed: bool): """ Helper function to ask user to select from a list of options (with optional description). Suggestion can be given. 'None' can be allowed as a valid input value. """ p = Col...
0b43452f00378ddc1345b85ca72b37ff1edfae05
3,645,822
import os def get_environ_list(name, default=None): """Return the split colon-delimited list from an environment variable. Returns an empty list if the variable didn't exist. """ packed = os.environ.get(name) if packed is not None: return packed.split(':') elif default is not None: ...
3e59962558b127790e456a79edf6175d1c3f7bbe
3,645,823
def util_color( graph: list[list[int]], max_color: int, colored_vertices: list[int], index: int ) -> bool: """ alur : 1. Periksa apakah pewarnaan selesai 1.1 Jika pengembalian lengkap True (artinya kita berhasil mewarnai grafik) Langkah Rekursif: 2. Iterasi atas setiap warna: ...
081bf9e8b1e0dcc847fdd0bc78167819506e3f1c
3,645,824
def reverse_complement(sequence): """ Return reverse complement of a sequence. """ complement_bases = { 'g':'c', 'c':'g', 'a':'t', 't':'a', 'n':'n', 'G':'C', 'C':'G', 'A':'T', 'T':'A', 'N':'N', "-":"-", "R":"Y", "Y":"R", "S":"W", "W":"S", "K":"M", "M":"K", "B":"V", "V":"B", "D": ...
d28e520a9159cb4812079b4a7a5f2f6eb5723403
3,645,825
def get_variable_ddi( name, shape, value, init, initializer=None, dtype=tf.float32, regularizer=None, trainable=True): """Wrapper for data-dependent initialization.""" kwargs = {"trainable": trainable} if initializer: kwargs["initializer"] = initializer if regularizer: kwargs["regularizer"] = re...
b941f110ee8efbdfb9e4d2a6b5ba0a5b3e5881ed
3,645,826
def convert_to_mp3(path, start=None, end=None, cleanup_after_done=True): """Covert to mp3 using the python ffmpeg module.""" new_name = path + '_new.mp3' params = { "loglevel": "panic", "ar": 44100, "ac": 2, "ab": '{}k'.format(defaults.DEFAULT.SONG_QUALITY), "f": "mp3...
9d30c593e761103e6b434b530290637e8a4c345c
3,645,827
def conv3x3(in_planes, out_planes, Conv=nn.Conv2d, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return Conv(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
7741248a5af70e33abe803469c8a20eb2f4bcdb1
3,645,828
async def async_setup(hass, config): """Set up the AirVisual component.""" hass.data[DOMAIN] = {} hass.data[DOMAIN][DATA_CLIENT] = {} hass.data[DOMAIN][DATA_LISTENER] = {} if DOMAIN not in config: return True conf = config[DOMAIN] hass.async_create_task( hass.config_entrie...
e44beaaf7657848fa377700021671d6c27317696
3,645,829
def hasConnection(document): """ Check whether document has a child of :class:`Sea.adapter.connection.Connection`. :param document: a :class:`FreeCAD.Document` instance """ return _hasObject(document, 'Connection')
d0999c488ea1af1d0117eb53a6e67d5ce876a142
3,645,830
from typing import List def trsfrm_aggregeate_mulindex(df:pd.DataFrame, grouped_cols:List[str], agg_col:str, operation:str, k:int=5): """transform aggregate statistics for multiindex ...
f84ac88bb3f3474fe5611486031e746e4dc9954d
3,645,831
from typing import Optional def get_hub_virtual_network_connection(connection_name: Optional[str] = None, resource_group_name: Optional[str] = None, virtual_hub_name: Optional[str] = None, opts: Option...
3275fdf70d088df2f00bfe9e0148026caca16fcc
3,645,832
def newcombe_binomial_ratio_err(k1,n1, k2,n2, z=1.0): """ Newcombe-Brice-Bonnett ratio confidence interval of two binomial proportions. """ RR = (k1/n1) / (k2/n2) # mean logRR = np.log(RR) seLogRR = np.sqrt(1/k1 + 1/k2 - 1/n1 - 1/n2) ash = 2 * np.arcsinh(z/2 * seLogRR) lower ...
8ea31bcbbc1d6393e2d60d9ef6a1052b3b5347c5
3,645,833
from typing import Any from typing import Optional import json def parse_metrics(rpcs: Any, detokenizer: Optional[detokenize.Detokenizer], timeout_s: Optional[float]): """Detokenizes metric names and retrieves their values.""" # Creates a defaultdict that can infinitely have other defaultdic...
d169e9e247d8b969f6adf5161f0f7399a7b69da6
3,645,834
def cigarlist_to_cigarstring(cigar_list): """ Convert a list of tuples into a cigar string. Example:: [ (0, 10), (1, 1), (0, 75), (2, 2), (0, 20) ] => 10M 1I 75M 2D 20M => 10M1I75M2D20M :param cigar_list: a list of tuples (code, l...
4d3a039f60f8976893e5ad3775f61fbfa2656acc
3,645,835
def add(x, y): """Add two numbers""" return x+y
7f18ee62d6cd75e44a9401d000d9bcada63f2c24
3,645,836
import os def generateCSR(host_id, key): """Generate a Certificate Signing Request""" pod_name = os.environ['MY_POD_NAME'] namespace = os.environ['TEST_APP_NAMESPACE'] SANURI = f'spiffe://cluster.local/namespace/{namespace}/podname/{pod_name}' req = crypto.X509Req() req.get_subject().CN = ho...
761cfe7b2627c38dcddce68be99f7ead4965369c
3,645,837
import logging def sdecorator(decoratorHandleDelete: bool = False, expectedProperties: list = None, genUUID: bool = True, enforceUseOfClass: bool = False, hideResourceDeleteFailure: bool = False, redactConfig: RedactionConfig = None, timeoutFunction: bool = True): """Decorate a funct...
f06647b034c2c5fa10a84afed83673f3a8be15f7
3,645,838
def clean_acl(name, value): """ Returns a cleaned ACL header value, validating that it meets the formatting requirements for standard Swift ACL strings. The ACL format is:: [item[,item...]] Each item can be a group name to give access to or a referrer designation to grant or deny base...
1cceb2af22d2f5bbf223a0eb381b4c6643d76f0e
3,645,839
def test(X, Y, perms=10000, method="pearson", tail="two-tail", ignore_nans=False): """ Takes two distance matrices (either redundant matrices or condensed vectors) and performs a Mantel test. The Mantel test is a significance test of the correlation between two distance matrices. Parameters ---...
7f0d7447ed475292f221e1dc6e4944f5cb2e8bd4
3,645,840
def get_format_datestr(date_str, to_format='%Y-%m-%d'): """ Args: date_str (str): '' to_format (str): '%Y-%m-%d' Returns: date string (str) """ date_obj = parser.parse(date_str).date() return date_obj.strftime(to_format)
bf443aad3ca38eb35b647d26b38b1404cf82f387
3,645,841
def lor(*goalconsts): """ Logical or for goal constructors >>> from logpy.arith import lor, eq, gt >>> gte = lor(eq, gt) # greater than or equal to is `eq or gt` """ def goal(*args): return lany(*[gc(*args) for gc in goalconsts]) return goal
9726cc24f6d79214e652d42ff1b872f60b5a4594
3,645,842
import time def kalman_smoother(Z, M_inv, plotting=False): """ X: state U: control Z: observation (position and forces) F: state transition model B: control input model Q: process variance R: observation variance """ t_steps = Z.shape[0] x0 = np.r_[Z[0,0:6], ...
927062585686897462ca866819ecdff22aed245c
3,645,843
def get_convex_hull(coords, dim = 2, needs_at_least_n_points = 6): #FIXME restrict only for 2D? """ For fitting an ellipse, at least 6 points are needed Parameters ---------- coords : 2D np.array of points dim : dimensions to keep when calculating convex hull Returns --------- coo...
6939db4475b9e11c8d0e53a5d820773bb899f15a
3,645,844
import logging from operator import gt def score(input, index, output=None, scoring="+U,+u,-s,-t,+1,-i,-a", filter=None, # "1,2,25" quality=None, compress=False, threads=1, raw=False, remove_existing=False): """Score the in...
c4b0fee2df964e65ee0aec12c84b0b1d7985a254
3,645,845
def keyword_search(queryset: QuerySet, keywords: str) -> QuerySet: """ Performs a keyword search over a QuerySet Uses PostgreSQL's full text search features Args: queryset (QuerySet): A QuerySet to be searched keywords (str): A string of keywords to search the QuerySet Returns: ...
1fb38af2c3aa3bdf092196e8e12539e0a2cf9e58
3,645,846
def classification_loss(hidden, labels, n_class, initializer, name, reuse=None, return_logits=False): """ Different classification tasks should use different scope names to ensure different dense layers (parameters) are used to produce the logits. An exception will be in tr...
c89fd14fae7099b43f639bf0825600e26b60e417
3,645,847
def do_pdfimages(pdf_file, state, page_number=None, use_tmp_identifier=True): """Convert a PDF file to images in the TIFF format. :param pdf_file: The input file. :type pdf_file: jfscripts._utils.FilePath :param state: The state object. :type state: jfscripts.pdf_compress.State :param int page_...
e5a48cdf2c93b037c4f983a56467e839920fa06c
3,645,848
from pathlib import Path import subprocess def git_patch_tracked(path: Path) -> str: """ Generate a patchfile of the diff for all tracked files in the repo This function catches all exceptions to make it safe to call at the end of dataset creation or model training Args: path (Path): pat...
374d80f8d1f74de76ab1dc1305f0772fde85d4f5
3,645,849
def connect(transport=None, host='localhost', username='admin', password='', port=None, key_file=None, cert_file=None, ca_file=None, timeout=60, return_node=False, **kwargs): """ Creates a connection using the supplied settings This function will create a connection to an Arista EOS nod...
09407d39e624f9a863a7633627d042b17b7a6158
3,645,850
def cov_hc2(results): """ See statsmodels.RegressionResults """ # probably could be optimized h = np.diag(np.dot(results.model.exog, np.dot(results.normalized_cov_params, results.model.exog.T))) het_scale = results.resid**2/(1-h) cov_hc2_ ...
328eeb88e37a2d78a6c0f0f9b3b81459230d87d5
3,645,851
def add_people(): """ Show add form """ if request.method == 'POST': #save data to database db_conn = get_connection() cur = db_conn.cursor() print ('>'*10, request.form) firstname = request.form['first-name'] lastname = request.form['last-name'] address = request.form['address'] country = request....
db2fcd7a2d9ed0073741d02a0bcafef37f714299
3,645,852
import inspect def api_to_schema(api: "lightbus.Api") -> dict: """Produce a lightbus schema for the given API""" schema = {"rpcs": {}, "events": {}} if isinstance(api, type): raise InvalidApiForSchemaCreation( "An attempt was made to derive an API schema from a type/class, rather than...
d07f6c6915967a1e61bc8f9bd1b72adb24207684
3,645,853
def sum2(u : SignalUserTemplate, initial_state=0): """Accumulative sum Parameters ---------- u : SignalUserTemplate the input signal initial_state : float, SignalUserTemplate the initial state Returns ------- SignalUserTemplate the output signal of the filter ...
3649942de13f698a92703747d8ea73be7ece4ddb
3,645,854
def approve_report(id): """ Function to approve a report """ # Approve the vulnerability_document record resource = s3db.resource("vulnerability_document", id=id, unapproved=True) resource.approve() # Read the record details vdoc_table = db.vulnerability_document record = db(vdo...
ce1bdb00a5fb6958c51422543e62f289de5e96cb
3,645,855
def sparse_column_multiply(E, a): """ Multiply each columns of the sparse matrix E by a scalar a Parameters ---------- E: `np.array` or `sp.spmatrix` a: `np.array` A scalar vector. Returns ------- Rescaled sparse matrix """ ncol = E.shape[1] if ncol != a.shape[...
a215440e630aeb79758e8b0d324ae52ea87eba52
3,645,856
def soup_extract_enzymelinks(tabletag): """Extract all URLs for enzyme families from first table.""" return {link.string: link['href'] for link in tabletag.find_all("a", href=True)}
7baabd98042ab59feb5d8527c18fe9fa4b6a50af
3,645,857
def choose(db_issue: Issue, db_user: User, pgroup_ids: [int], history: str, path: str) -> dict: """ Initialize the choose step for more than one premise in a discussion. Creates helper and returns a dictionary containing several feedback options regarding this argument. :param db_issue: :param db_u...
0404e955a7872086d45ccf4018bc8a9977c2df21
3,645,858
def loops_NumbaJit_parallelFast(csm, r0, rm, kj): """ This method implements the prange over the Gridpoints, which is a direct implementation of the currently used c++ methods created with scipy.wave. Very strange: Just like with Cython, this implementation (prange over Gridpoints) produces wrong r...
82201310483b72c525d1488b5229e628d44a65ca
3,645,859
import numpy import scipy def sobel_vertical_gradient(image: numpy.ndarray) -> numpy.ndarray: """ Computes the Sobel gradient in the vertical direction. Args: image: A two dimensional array, representing the image from which the vertical gradient will be calculated. Returns: A two di...
f8f9bf6fadbae962206255ab3de57edbab9d935e
3,645,860
def custom_field_sum(issues, custom_field): """Sums custom field values together. Args: issues: List The issue list from the JQL query custom_field: String The custom field to sum. Returns: Integer of the sum of all the found values of the custom_field. """ ...
32c1cce310c06f81036ee79d70a8d4bbe28c8417
3,645,861
def routingAreaUpdateReject(): """ROUTING AREA UPDATE REJECT Section 9.4.17""" a = TpPd(pd=0x3) b = MessageType(mesType=0xb) # 00001011 c = GmmCause() d = ForceToStandbyAndSpareHalfOctets() packet = a / b / c / d return packet
b9bb0e498a768eb6b7875018c78ca23e54353620
3,645,862
def doRipsFiltration(X, maxHomDim, thresh = -1, coeff = 2, getCocycles = False): """ Run ripser assuming Euclidean distance of a point cloud X :param X: An N x d dimensional point cloud :param maxHomDim: The dimension up to which to compute persistent homology :param thresh: Threshold up to which to...
a0e4cabb613ac77659fda2d31867a7e9df32f288
3,645,863
def build_target_areas(entry): """Cleanup the raw target areas description string""" target_areas = [] areas = str(entry['cap:areaDesc']).split(';') for area in areas: target_areas.append(area.strip()) return target_areas
48e76a5c1ed42aed696d441c71799b47f9193b29
3,645,864
def convert_to_celcius(scale, temp): """Convert the specified temperature to Celcius scale. :param int scale: The scale to convert to Celcius. :param float temp: The temperature value to convert. :returns: The temperature in degrees Celcius. :rtype: float """ if scale == temp_scale.FARENHEI...
a7c2f0f7405eea96c1ebb4a7e103cf28a95b6f5a
3,645,865
def config_file_settings(request): """ Update file metadata settings """ if request.user.username != 'admin': return redirect('project-admin:home') if request.method == 'POST': update_file_metadata(request.POST) return redirect('project-admin:home') files = FileMetaData...
c8e91ac49305e3aa7aa33961939c3add23fc5327
3,645,866
def roundtrip(sender, receiver): """ Send datagrams from `sender` to `receiver` and back. """ return transfer(sender, receiver), transfer(receiver, sender)
939d9fd861b89037322fcc7c851d291ab073b520
3,645,867
import json def loadHashDictionaries(): """ Load dictionaries containing id -> hash and hash -> id mappings These dictionaries are essential due to some restrictive properties of the anserini repository Return both dictionaries """ with open(PATH + PATH_ID_TO_HASH, "r") as f: ...
de8af6d5e5562869c992e08343aadb77c48933b0
3,645,868
def preprocess(tensor_dict, preprocess_options, func_arg_map=None): """Preprocess images and bounding boxes. Various types of preprocessing (to be implemented) based on the preprocess_options dictionary e.g. "crop image" (affects image and possibly boxes), "white balance image" (affects only image), etc. If se...
141b170e0d4c6447750e2ece967afec7a92a37ea
3,645,869
def update_comment(id): """修改单条评论""" comment = Comment.query.get_or_404(id) if g.current_user != comment.author and not g.current_user.can(Permission.COMMENT): return error_response(403) data = request.get_json() if not data: return bad_request('You must put JSON data.') comment....
59db7122f9139f7fda744284e83045533d6361fb
3,645,870
def resnet18(num_classes, pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ encoder = ResNetEncoder(BasicBlock, [2, 2, 2, 2]) if pretrained: encoder.load_state_dict(model_zoo.load_url(model_urls...
b342fa322cb26571b5df7e5e8f117ce016a7febf
3,645,871
import html def display_page(pathname): """displays dash page""" if pathname == '/': return main.layout elif pathname == '/explore': return explore.layout elif pathname == '/eval': return eval.layout elif pathname == '/train': return train.layout else: r...
3aeb44ca1974b63f63b9ef97526aef20d2d92ddb
3,645,872
def getFilterDict(args): """ Function: An entire function just to notify the user of the arguments they've passed to the script? Seems reasonable. Called from: main """ ## Set variables for organization; this can be probably be removed later outText = {} outAction = "" userString = ""...
ea175812465fa30866fe90c6461f416c4af1d6b2
3,645,873
def pointwise_multiply(A, B): """Pointwise multiply Args: ----------------------------- A: tvm.te.tensor.Tensor shape [...] B: tvm.te.tensor.Tensor shape same as A ----------------------------- Returns: ----------------------------- tvm.te.tensor.Tensor shap...
37c27cced9cc77f3a3aefef32d56f92f0ceb292f
3,645,874
import traceback def create_website(self): """ :param self: :return: """ try: query = {} show = {"_id": 0} website_list = yield self.mongodb.website.find(query, show) return website_list except: logger.error(traceback.format_exc()) return ""
b7b8faf55095288e5c2d693aeed85f6412449c08
3,645,875
def _get_sparsity(A, tolerance=0.01): """Returns ~% of zeros.""" positives = np.abs(A) > tolerance non_zeros = np.count_nonzero(positives) return (A.size - non_zeros) / float(A.size)
44b7fb501a10551167ad37ffdafaef42c6c849b9
3,645,876
def findPeaks(hist): """ Take in histogram Go through each bin in the histogram and: Find local maximum and: Fit a parabola around the two neighbor bins and local max bin Calculate the critical point that produces the max of the parabola (critical point represents orientation...
99b89d4fd9f35deab141e178aaa107dabf35ccfe
3,645,877
def tph_chart_view(request, template_name="monitor/chart.html", **kwargs): """Create example view. that inserts content into the dash context passed to the dash application. """ logger.debug('start') context = { 'site_title': 'TPH monitor', 'title': 'TPH chart via Plotly Dash for D...
135adb437fb3c27327ea8c6a83e33dfadec1f3ce
3,645,878
def gradient_descent(x_0, a, eta, alpha, beta, it_max, *args, **kwargs): """Perform simple gradient descent with back-tracking line search. """ # Get a copy of x_0 so we don't modify it for other project parts. x = x_0.copy() # Get an initial gradient. g = gradient(x, a) # Compute the norm...
701097aaebbe15306818593daf501b0f7d622f49
3,645,879
import re def ExtractCalledByNatives(contents): """Parses all methods annotated with @CalledByNative. Args: contents: the contents of the java file. Returns: A list of dict with information about the annotated methods. TODO(bulach): return a CalledByNative object. Raises: ParseError: if una...
bbf8c80cc7ac323469de7bf8a2fdf0da84b834e1
3,645,880
from typing import Counter def knn_python(input_x, dataset, labels, k): """ :param input_x: 待分类的输入向量 :param dataset: 作为参考计算距离的训练样本集 :param labels: 数据样本对应的分类标签 :param k: 选择最近邻样本的数目 """ # 1. 计算待测样本与参考样本之间的欧式距离 dist = np.sum((input_x - dataset) ** 2, axis=1) ** 0.5 # 2. 选取 k 个最近邻样本的标...
8deaec88369d2d0cb42ebdd3961caf891357335b
3,645,881
from datetime import datetime import re def charReplace(contentData, modificationFlag): """ Attempts to convert PowerShell char data types using Hex and Int values into ASCII. Args: contentData: [char]101 modificationFlag: Boolean Returns: contentData: "e" modificatio...
ca321869608e7524c260a8feeea6f2cf8bd6fd49
3,645,882
import six import os def _prepare_config(separate, resources, flavor_ref, git_command, zip_patch, directory, image_ref, architecture, use_arestor): """Prepare the Argus config file.""" conf = six.moves.configparser.SafeConfigParser() conf.add_section("argus") c...
b2f1528ea0d8426316b7b5a1f6b40f5cc723f5d5
3,645,883
def all_logit_coverage_function(coverage_batches): """Computes coverage based on the sum of the absolute values of the logits. Args: coverage_batches: Numpy arrays containing coverage information pulled from a call to sess.run. In this case, we assume that these correspond to a batc...
32674a4528b69b756b3fc5f161dcbfd3ceaba01f
3,645,884
import asyncio async def create_audio(request): """Process the request from the 'asterisk_ws_monitor' and creates the audio file""" try: message = request.rel_url.query["message"] except KeyError: message = None LOGGER.error(f"No 'message' parameter passed on: '{request.rel_url}'"...
6aa90764c167be9a1d980dea0e54243a9467c276
3,645,885
def reinterpret_axis(block, axis, label, scale=None, units=None): """ Manually reinterpret the scale and/or units on an axis """ def header_transform(hdr, axis=axis, label=label, scale=scale, units=units): tensor = hdr['_tensor'] if isinstance(axis, basestring): axis = tensor['labels...
e19d1a5cf567f72ae261cc0fef69b03e2d8a9696
3,645,886
def duel(board_size, player_map): """ :param board_size: the board size (i.e. a 2-tuple) :param player_map: a dict, where the key is an int, 0 or 1, representing the player, and the value is the policy :return: the resulting game outcomes """ board_state = init_board_state(board_size) result...
3fbcd1477fc90553cdc5371440083c9737b4bf5b
3,645,887
def set_processor_type(*args): """ set_processor_type(procname, level) -> bool Set target processor type. Once a processor module is loaded, it cannot be replaced until we close the idb. @param procname: name of processor type (one of names present in \ph{psnames}) (C++: const char *) ...
32d827fe0c0d152af98e6bed5baa7a24d372c4f8
3,645,888
from onnx.helper import make_node from onnx import TensorProto def convert_repeat(node, **kwargs): """Map MXNet's repeat operator attributes to onnx's Tile operator. """ name, input_nodes, attrs = get_inputs(node, kwargs) opset_version = kwargs['opset_version'] if opset_version < 11: rais...
120e1ee364bf64b00b504fcdc8d0769a6d02db7b
3,645,889
def my_quote(s, safe = '/'): """quote('abc def') -> 'abc%20def' Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted. RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists the following reserved characters. reserve...
c5c28b7779e9cab2488696435832f9f7cbd03e57
3,645,890
def GetExperimentStatus(experiment, knobs, exp_data, track='stable'): """Determine the status and source of a given experiment. Take into account all ways that a given experiment may be enabled and allow the client to determine why a given experiment has a particular status. Experiments at 100% are always on....
9deef37c2e517987bd49cf91892149f202b43993
3,645,891
from masci_tools.tools.cf_calculation import CFCalculation, plot_crystal_field_calculation def test_plot_crystal_field_calculation(): """ Test of the plot illustrating the potential and charge density going into the calculation """ cf = CFCalculation() cf.readPot('files/cf_calculation/CFdata.hdf'...
90488103d929929615dc1e5de1531102a9f7b96a
3,645,892
import re import tempfile from pathlib import Path async def submit_changesheet( uploaded_file: UploadFile = File(...), mdb: MongoDatabase = Depends(get_mongo_db), user: User = Depends(get_current_active_user), ): """ Example changesheet [here](https://github.com/microbiomedata/nmdc-runtime/blob/...
ebe9306aba0fef88c906c3c584f87e7c783fe9d8
3,645,893
import json def get_notes(request, course, page=DEFAULT_PAGE, page_size=DEFAULT_PAGE_SIZE, text=None): """ Returns paginated list of notes for the user. Arguments: request: HTTP request object course: Course descriptor page: requested or default page number page_size: requ...
3256cacd845cf2fd07027cf6b3f2547a59cefd0f
3,645,894
import numpy def convert_hdf_to_gaintable(f): """ Convert HDF root to a GainTable :param f: :return: """ assert f.attrs['ARL_data_model'] == "GainTable", "Not a GainTable" receptor_frame = ReceptorFrame(f.attrs['receptor_frame']) frequency = numpy.array(f.attrs['frequency']) data = nu...
dd816eb0730b0f9993efe07c2b28db692ac6a06e
3,645,895
import pathlib def list_files(directory): """Returns all files in a given directory """ return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]
a8c5fea794198c17c2aff41a1a07009984a8e61f
3,645,896
def condition_conjunction(conditions): """Do conjuction of conditions if there are more than one, otherwise just return the single condition.""" if not conditions: return None elif len(conditions) == 1: return conditions[0] else: return sql.expression.and_(*conditions)
acf26bd9b8e47d27ad83815be70216db0e4ad091
3,645,897
def get_claimed_referrals(char): """ Return how many claimed referrals this character has. """ return db((db.referral.referrer==char) & (db.referral.claimed==True)).count()
5820cdd21cbb77f6a43537ae18dc227ad4fec1b8
3,645,898
def groupsplit(X, y, valsplit): """ Used to split the dataset by datapoint_id into train and test sets. The data is split to ensure all datapoints for each datapoint_id occurs completely in the respective dataset split. Note that where there is validation set, data is split with 80% for training and 2...
e8ba393270a32e2464c30409a13b2c5e9528afdd
3,645,899