content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _filename_pattern(ext): """Returns an re matching native or tfrecord files of format `ext`.""" return r".*\.{}(\.tfrecord)?(\.gz)?".format(ext)
6ec5a86dbba2432293451ca7dff0a0d1d5091bf0
8,600
def assemble_remote_url(): """ 组装目标服务器URL, 即生成 parse.remote_url 的值 :rtype: str """ if parse.is_external_domain: # 请求的是外部域名 (external domains) scheme = 'https://' if parse.is_https else 'http://' return urljoin(scheme + parse.remote_domain, parse.remote_path_query) else: ...
f0e14ddb42636f12f4fafa31af4a87b3f91a4e05
8,601
def register_blueprints(app): """Register Flask blueprints.""" app.register_blueprint(public.views.blueprint) app.register_blueprint(drawbot.views.blueprint) app.register_blueprint(user.views.blueprint) return None
936c17a95ddc013ec9f0c6c232a689245fc313d0
8,602
def write_attribute(xml_elem, elem: str=None, attrib: str=None, txt: str=None): """ Write new text to a xml attribute. Elem can be used to refer to a subelement of the current xml_elem Args: xml_elem: The current xml element elem (str): The requested element tag name attrib (str): ...
d2ee296b6926a71ef2ffaf9fd9d47128f66e8806
8,603
def _ndarray_feature(x: np.ndarray) -> tf.train.Feature: """Create an ndarray feature stored as bytes.""" x_bytes = x.tostring() feature = tf.train.Feature(bytes_list=tf.train.BytesList(value=[x_bytes])) return feature
03ad22f7d943d24574c92a494c915c28611a8d12
8,604
import re def get_img_compliance_level(profile): """ Try to figure out the IIIF Image API compliance level given the `profile` value from a info.json. """ patt_iiif = re.compile('level([0-2])\.json$') patt_stan = re.compile('#level([0-2])$') def get_from_str(s): m = None ...
7970a795ea1b79bfea3df0e5a306e2d0286a61de
8,605
def _extract_protocol_layers(deserialized_data): """ Removes unnecessary values from packets dictionaries. :param deserialized_data: Deserialized data from tshark. :return: List of filtered packets in dictionary format. """ packets_filtered = [] for packet in deserialized_data: packe...
3c3a899909c5278b29ffb402ccb4d8dde24fce3a
8,606
from typing import Optional from operator import gt def calculate_affinity( adata: AnnData, level: int = 1, block_key: Optional[str] = 'nsbm', group_by: Optional[str] = None, state: Optional = None, neighbors_key: Optional[str] = 'neighbors', adjacency: Optional[sparse.spmatrix] = None, ...
e2eec0e9f45199d6cc1559d71dfbf629dba61621
8,607
import asyncio async def scrape_website(client): """ :param client: client bot is connected to :return: only if there's an issue Type '!scrape' to restart the scraping process. Note: this function is executed on bot_ready, so I have to work around not having a convenient guild object. r ...
0a27b9fafd607e0a1816c5a4575209051e32929a
8,608
def numpy_dtypes_for_minmax(request): """ Fixture of numpy dtypes with min and max values used for testing cummin and cummax """ dtype = request.param min_val = ( np.iinfo(dtype).min if np.dtype(dtype).kind == "i" else np.finfo(dtype).min ) max_val = ( np.iinfo(dtype).max...
d2ad3676549f427c134b38106a93145c54114052
8,609
def solve(topics): """Solve.""" a_words, b_words = get_dicts(topics) candidates = [] original = [] duplicates = [] for a, b in topics: # print(a, b) # print(a_words[a], b_words[b]) if not (a_words[a] == 1 or b_words[b] == 1): candidates.append((a, b)) ...
bb78da10ff6bb939bc0de9e0cc51a036c2a0e8b9
8,610
def get_package_plugin(package_type): """ Get a plugin for a specific package Parameters ---------- package_type: str The package type to fetch Returns ------- InvirtualEnvPlugin: The invirtualenv plugin for the specific package_type """ for plugin in installed_...
a1d97a6d1c4248f7a1bfeade8e734bcc0af3aceb
8,611
import ast from typing import Tuple from typing import Optional import sys def _type_annotation( node: ast.AST, atok: asttokens.ASTTokens ) -> Tuple[Optional[TypeAnnotation], Optional[Error]]: """Parse the type annotation.""" if isinstance(node, ast.Name): return AtomicTypeAnnotation(identifier=Id...
cc8955f094da748855985b277f5cb0876c1ac2a3
8,612
def validate_basic_message(msg): """Validate basic messages. This example just uses basic assertions but you could easily use a schema library to get more sophisticated validators. """ assert msg.type == TYPE assert "~l10n" in msg assert "sent_time" in msg assert "content" in msg re...
df6b1541adf86a295e6592f26d72ab2109617f6b
8,613
def _filter_event_queryset(queryset, params, srs=None): """ Filter events queryset by params (e.g. self.request.query_params in EventViewSet) """ # Filter by string (case insensitive). This searches from all fields # which are marked translatable in translation.py val = params.get('text', No...
35103268d301239d4c884d50ab5321ebb22ed235
8,614
import re def process_user(enrollment, section): """Handle getting assignments for a single user Args: enrollment (canvasapi.enrollment.Enrollment): Canvas <Enrollment> object section (canvasapi.section.Section): Canvas <Section> object Returns: [list]: formatted list for writing...
88b471433d99c659eabac82a797530def3baf8f2
8,615
def op(name, data, bucket_count=None, display_name=None, description=None, collections=None): """Create a histogram summary op. Arguments: name: A unique name for the generated summary node. data: A `Tensor` of any shape. Must be castable to `float64`. bucket_count: O...
368b5f0af59352e5f283566d9008c413d38692c9
8,616
def read_as_str(file): """ 读取文件,并返回读取到的内容 """ try: with open(file, 'r') as f: return f.read() except IOError: return ""
934bec1e47e0f9af09be7f4d695a8ddf09004f3f
8,617
def has_xml_header(filepath): """ Return True if the first line of the file is <?xml :param filepath: :return: """ return True
21fdbdf36cf08ca18d8a0f0d7f7d2201b243c558
8,618
def shikaku(givens): """Solver for Shikaku minipuzzles.""" sym = grilops.make_number_range_symbol_set(0, SIZE * SIZE - 1) sg = grilops.SymbolGrid(LATTICE, sym) rc = grilops.regions.RegionConstrainer( LATTICE, solver=sg.solver, rectangular=True ) shifter = Shifter(sg.solver) for p in LAT...
e380ce634b342a19ecd466576e8e5d3ff28ccc25
8,619
import argparse def parse_arguments(args_to_parse): """Parse the command line arguments. Parameters ---------- args_to_parse: list of str Arguments to parse (split on whitespaces). """ description = "PyTorch implementation of CNN's for Human Activity Recognition" de...
17266dedd3a8086c7382652363a55b5c1067cdc7
8,620
def invert_qgniw(qh,phi,phih,k,l,f0): """ Calculate the streamfunction given the potential vorticity. The algorithm is: 1) Calculate wave potential vorticity 2) Invert for wave, pw, and vortex stremfunctions, pv. 3) Calculate the geostrophic stremfunction...
b90c5f76c2be93d0a45b8c260e7a7228094ff4c0
8,621
def package_ref_key(package_name, ref): """Returns ndb.Key corresponding to particular PackageRef.""" assert is_valid_package_ref(ref), ref return ndb.Key(PackageRef, ref, parent=package_key(package_name))
270b69baa1309bf29a054736ca6f898f23839ee3
8,622
def conv2d_backprop_input(dout, x_size, weight, stride=1, pad=0): """Backpropagation input for conv2d.""" filter_num, _, filter_h, filter_w = weight.shape dout = dout.transpose(0, 2, 3, 1).reshape(-1, filter_num) col_w = weight.reshape(filter_num, -1).T dcol = np.dot(dout, col_w.T) dx = col2im(d...
3749398101de25ec4f7b83c8a52754d18d0e8872
8,623
def get_feeds_from_url(url: str) -> list: """ Try to parse the URL and find any RSS feeds in the webpage Adapted from: https://gist.github.com/alexmill/9bc634240531d81c3abe """ logger.info(f"Attempting to find RSS feeds from {url}...") # If the URL itself is a proper RSS feed, just return it ...
0a8b10af257b2acfc4dbf4da886e96118cc5c32f
8,624
def fine_license_ratio(license_data, fine_data, column_name1=None, column_name2=None,year=None): """Get ratio of fines to licenses issued in a given year Parameters: ----------- license_data: DataFrame Any subset of the Professional and Occupational Licensing dataframe fine_data: DataFrame Any subset of...
97dad8c4f5c78b1291016e1cd9fa9c5f8ef20beb
8,625
def import_obj(obj_path, hard=False): """ import_obj imports an object by uri, example:: >>> import_obj("module:main") <function main at x> :param obj_path: a string represents the object uri. :param hard: a boolean value indicates whether to raise an exception on impor...
fe6bc0cd8fff5c0d5b1ba9fc0e153b2004b09755
8,626
def Get_Histogram_key(qubitOperator): """ Function to obtain histogram key string for Cirq Simulator. e.g. PauliWord = QubitOperator('X0 Z2 Y3', 0.5j) returning: histogram_string = '0,2,3' Args: qubitOperator (openfermion.ops._qubit_operator.QubitOperator): QubitOper...
f574f7b3f6c43de7b3121d4e49240a84a4bcfdfc
8,627
def get_organizations(): """ Queries API for a list of all basketball organizations registered with Basketbal Vlaanderen. :return: list of basketball organizations :rtype: [Organization] """ organizations = [] for organization_data in get_list(): organizations.append(Organizatio...
bcf29925465cde99399214cbe44648bbfd136e1b
8,628
def logout(): """Logout.""" logout_user() flash('您已成功登出', 'info') return redirect(url_for('public.home'))
e816d67e4084bad0549d0b932ec806de55cfc41d
8,629
def get_column_labels(): """ This function generates a list of column names for the extracted features that are returned by the get_features function. """ # list the names of the extracted features feature_labels = ["amplitude_envelope", "root_mean_square_energy", ...
c140ced9c4344bd7a4029d331d50ebe0750fac0a
8,630
def corr_finder(X, threshold): """ For each variable, find the independent variables that are equal to or more highly correlated than the threshold with the curraent variable Parameters ---------- X : pandas Dataframe Contains only independent variables and desired index threshold:...
3b32a3eacb721ff09f6b5614c0ada82df814d5fa
8,631
def magic_file(filename): """ Returns tuple of (num_of_matches, array_of_matches) arranged highest confidence match first. :param filename: path to file :return: list of possible matches, highest confidence first """ head, foot = _file_details(filename) if not head: raise ValueError...
3fc625006c5589b14c73fff501d48a523d1bce5b
8,632
def plot_sentiment( df: pd.DataFrame, title: str = None, height: int = 300, label_col: str = "label" ) -> Figure: """ Plot the predicted sentiment of the sentences. Args: df (pd.DataFrame): Dataframe with the outputs of a sentiment analysis model. title (str): Ti...
bf5f7f65fa4cbee6b0abfc77d1f47b6f175ed8f9
8,633
def subf(pattern, format, string, count=0, flags=0): # noqa A002 """Apply `sub` with format style replace.""" is_replace = _is_replace(format) is_string = isinstance(format, (_util.string_type, _util.binary_type)) if is_replace and not format.use_format: raise ValueError("Compiled replace is n...
7ef105eeafb5ab4e6c3405206d850520d3489314
8,634
def independent_connections(fn): """Target must support simultaneous, independent database connections.""" # This is also true of some configurations of UnixODBC and probably win32 # ODBC as well. return _chain_decorators_on( fn, no_support('sqlite', 'Independent connections disabled wh...
cf11838e5b32cc2a6c165fda38baf4d680beda4a
8,635
def Route(template, handler): """Make a Route whose placeholders accept only allowable map IDs or labels.""" return webapp2.Route(template.replace('>', r':[\w-]+>'), handler)
2ec563ed4db815ee98d050e8e9a672a7a53ca010
8,636
def values_iterator(dictionary): """Add support for python2 or 3 dictionary iterators.""" try: v = dictionary.itervalues() # python 2 except: v = dictionary.values() # python 3 return v
e4fef48fd1b2a9189d81465fec259efe102c5b75
8,637
def _standardize_bicluster(bicluster): """Standardize a bicluster by subtracting the mean and dividing by standard deviation. Ref.: Pontes, B., Girldez, R., & Aguilar-Ruiz, J. S. (2015). Quality measures for gene expression biclusters. PloS one, 10(3), e0115497. Note that UniBic synthetic data ...
371adc72f64bec4039e0fab65e8acb77e37063d8
8,638
def get_deployment_polarion_id(): """ Determine the polarion_id of the deployment or upgrade Returns: str: polarion_id of the deployment or upgrade """ polarion_config = config.REPORTING.get('polarion') if polarion_config: if config.UPGRADE.get('upgrade'): if config...
475689b0adac68fdaf60d77af88f5b6c3e229003
8,639
import shlex def parse_command(message) -> ParsedStatusCommand: """Parsing command arguments to arguments list""" LOGGER.debug('Got message: %s', message) try: _, target, *args = shlex.split(message) return ParsedStatusCommand(target, *args) except ValueError as ex: raise Comma...
868841d0b218a02f7b59b9e4302d22bd5d6ed57e
8,640
import io import traceback def mail_on_fail(func: callable): """Send an email when something fails. Use this as a decorator.""" @wraps(func) def _wrap(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: # Handle recursive error handling. ...
6672ec78551f26e875002b24ef21f331ab171540
8,641
def base_conv(num, base): """Write a Python program to converting an Integer to a string in any base""" _list = [] if num//base == 0: return str(num%base) else: return (base_conv(num//base, base) + str(num%base))
9fcc28ccfe8ba80d974cc4012aad456bfb8c9544
8,642
def handle_log(request): """ Handle streaming logs to a client """ params = request.match_info log_dir = py.path.local('data').join( params['project_slug'], params['job_slug'], ) # Handle .log ext for DockCI legacy data log_path_bare = log_dir.join(params['stage_slug']) log...
4d5b4bd14ff759cd62b72224c0a2d1c99b7dc786
8,643
def get_scheme(patterns, config): """Returns the encoding scheme specified by the given config object Args: patterns (list(list)): List of input patterns config (dict): The config object """ assert(type(patterns) == list and len(patterns) > 0) assert(type(config) == dict) min_ma...
de9cc88bed0446854903832fb7bc64c24cc37144
8,644
def open_signatures_window(*args): """ open_signatures_window() -> TWidget * Open the signatures window ( 'ui_open_builtin' ). @return: pointer to resulting window """ return _ida_kernwin.open_signatures_window(*args)
e699df0192755b28d3c1c324c485ca4486cab98e
8,645
def get_subscription_id(_ctx=ctx): """ Gets the subscription ID from either the node or the provider context """ return get_credentials(_ctx=_ctx).subscription_id
23af53f6f807e14ad629e60ea79e21e8ed3eeef5
8,646
def origin_trial_function_call(feature_name, execution_context=None): """Returns a function call to determine if an origin trial is enabled.""" return 'RuntimeEnabledFeatures::{feature_name}Enabled({context})'.format( feature_name=feature_name, context=execution_context if execution_cont...
201dbe8449373dbad0144633350d3e6adbb58b80
8,647
def get_bit(byteval, index) -> bool: """retrieve bit value from byte at provided index""" return (byteval & (1 << index)) != 0
1fe020449ae2ae2513073835db6f75b24e558fdb
8,648
def upsert_target(data, analyst): """ Add/update target information. :param data: The target information. :type data: dict :param analyst: The user adding the target. :type analyst: str :returns: dict with keys "success" (boolean) and "message" (str) """ if 'email_address' not in d...
4baa064c52bbeacdc18323196c1762cabd9607aa
8,649
import torch def batch_data(data, batch_size): """ data is a dict := {'x': [numpy array], 'y': [numpy array]} (on one client) returns x, y, which are both numpy array of length: batch_size """ data_x = data["x"] data_y = data["y"] # randomly shuffle data np.random.seed(100) rng_st...
58cfde03668dd61e23bdb8b96527ae17176c4872
8,650
import ast import sys def ast_parse_node(node): """ :param ast.Node node: an ast node representing an expression of variable :return ast.Node: an ast node for: _watchpoints_obj = var if <var is a local variable>: # watch(a) _watchpoints_localvar = "a" elif ...
22b3b6fed61e18ed6dc742040a365ebca8847fd5
8,651
def simplify_board_name(board_name: str) -> str: """Removes the following from board names: - `x86-`, e.g. `x86-mario` - `_he`, e.g. `x86-alex_he` - `&` - e.g. `falco & falco_II` - ',' - e.g. `hoho, but substitute a dp to vga chip` (why) Args: board_name: the board name to simplify ...
bd6a9756aa6e6725b9727825f52ba544e2e4a97d
8,652
import argparse def parse_args(): """ Parse CLI arguments. Returns ------- argparse.Namespace Parsed arguments """ parser = argparse.ArgumentParser( description="Optimize model for inference") parser.add_argument("-m", "--model", dest="model_typ...
71eb3b1a567cdc7705fd6a2120c1ed23c9e8afd8
8,653
def delete_news_site(user_id, news_name): """ Delete subscription to user list Params: - user_id: The user email - news_name: The name of news provider Return: void """ user_info = get_user_by_email(user_id) user_info = user_info.to_dict() list_news = user_info['news_sites'] ...
02f4ea485b2822c1a614e39dae3ef3aa924596b0
8,654
from datetime import datetime def get_time_str(dt: datetime.datetime = None, tz_default=LocalTimeZone): """ @param dt 为None时,返回当前时间 @param tz_default dt无时区信息时的默认时区 """ if not dt: dt = datetime.datetime.now() dt = convert_zone(dt, tz_default=tz_default) time_str = dt.isoformat().spl...
41f9f1465fe88e35450569995a14dfce6ebc9bc5
8,655
def plotLikesTablePair( likesTableFNs, plotFile, nonNormedStats = (), includeSpecialBins = True, getio = None ): """Visually plot a likes table. """ if getio: return dict( depends_on = likesTableFNs, creates ...
6671877a21749747ce45a020d7a87eec86280d8c
8,656
import os import math def get_res_details(f): """ extracts bmaj, bmin, bpa and coordinate increment""" cmd = "prthd in=%s 2>/dev/null"%(f) pcmd = os.popen(cmd) output = pcmd.read() output = output.split('\n') #print(output) for lin in output: if 'Beam Size' in lin: prin...
5a95c08f494beffb85b2942e90561837bc82fbd0
8,657
def del_api_msg(): """ @api {post} /v1/interfaceapimsg/del InterfaceApiImsg_删除接口信息 @apiName interfaceApiImsgDel @apiGroup Interface @apiDescription 删除接口信息 @apiParam {int} apiMsgId 接口信息id @apiParamExample {json} Request-Example: { "apiMsgId": 1, } @apiSuccessExample {json}...
fabd5a2fc257219e2568991f9520587d4053c909
8,658
def find_nearest(array, value): """ Find nearest value of interest in array (used for frequencies, no double value issues) Parameters ---------- array: array Give the array in which you want to find index of value nearest-by value: int or float The value of interest Return ...
e96a87b5b857a8cafbc0c6371b395040dde48e8d
8,659
import math def tube_light_generation_by_func(k, b, alpha, beta, wavelength, w = 400, h = 400): """Description: This functio generates a tube light (light beam) with given paratmers, in which, k and b represent the function y = k*x + b # TODO: Test k, b range Args: k (int): y = k*x + ...
c4fe0e817233f7e983e2bc513377e63379e23f93
8,660
def get_book(isbn): """ Retrieve a specific book record by it's ISBN --------------------------------------------- Endpoints: GET /books/isbn GET /books/isbn?act=(borrow|handback) @QueryParams: act: (optional) specific action on book Possible values: borrow, handback ...
fd1471234f6c73062569fea0ae489da3dc9af8ac
8,661
def toint16(i): """ Convert a number to a hexadecimal string of length 2 """ return f'{i:02x}'
3effd2b3f011a962beac19682ad29e930eb0f057
8,662
def is_phone(text): """ 验证字符串是否是固定电话 :param text: 需要检查的字符串 :return: 符合返回True,不符合返回False """ return check_string(text, '\(?0\d{2,3}[) -]?\d{7,8}$')
a90e8d28737b94f02381ed6e959e0a155628eaae
8,663
def get_loc(frameInfo, bbox_type): """Return GeoJSON bbox.""" bbox = np.array(frameInfo.getBBox()).astype(np.float) print("get_loc bbox: %s" %bbox) if bbox_type == "refbbox": bbox = np.array(frameInfo.getReferenceBBox()).astype(np.float) coords = [ [ bbox[0,1], bbox[0,0] ], ...
a95a9eb6ae9e33b5d69451fb1b34e19c7b0be8d3
8,664
def load_df(input_path, fname, ext): """Read chain as Pandas DataFrame""" fname = os.path.join(input_path, fname + ext) print 'loading %s' % fname assert(os.path.isabs(fname)) X = pd.DataFrame.from_csv(fname) return X
be4c0d82bdb8881d3ad555b215469df7e8daaefe
8,665
from typing import Set def _load_order_component(comp_name: str, load_order: OrderedSet, loading: Set) -> OrderedSet: """Recursive function to get load order of components. Async friendly. """ component = get_component(comp_name) # If None it does not exist, error alrea...
c9d2adc8dbcf392e3d904b1e5f9d47f623e5646e
8,666
def clean_english_str_tf(input_str): """Clean English string with tensorflow oprations.""" # pylint: disable=anomalous-backslash-in-string string = tf.regex_replace(input_str, r"[^A-Za-z0-9(),!?\'\`<>/]", " ") string = tf.regex_replace(string, "\'s", " \'s") string = tf.regex_replace(string, "\'ve", " \'ve") ...
6439f708dea8566d5706968811aed7478b1c107c
8,667
def _square_eqt(x, y, x0, y0, angle): """simple equation for a square. this returns: max(np.dstack([abs(x0 - x), abs(y0 -y)]), 2). this should then be compared to the "radius" of the square (half the width) the equation comes from this post: http://polymathprogrammer.com/2010/03/01/answered-can-yo...
4000bf329399dfc8b842c2a496cdea193dd47fc6
8,668
def multinomial(x, num_samples=1, replacement=False, name=None): """ This OP returns a Tensor filled with random values sampled from a Multinomical distribution. The input ``x`` is a tensor with probabilities for generating the random number. Each element in ``x`` should be larger or equal to 0, but not...
6412cf815aaf8b9175946c501beacb716deb0c5c
8,669
def run_experiment( max_epochs, log=None, evaluate=True, projection=True, save_directory=".", save_file=None, save_interval=1, **configuration, ): """Runs the Proof of Constraint experiment with the given configuration :param max_epochs: number of epochs to run the experiment ...
7ebfc72dc3ebe7047e708ffa0903f24de67d8134
8,670
from typing import List from typing import Callable def compose_decorators(decorators: List[Callable]) -> Callable: """Compose multiple decorators into one. Helper function for combining multiple instrumentation decorators into one. :param list(Callable) decorators: A list of instrumentation decorators ...
14d8ecbf5af598419906ba9776bb40be6271279f
8,671
import torch def xyz_to_polar(sphere_points): """ (B,3,N) -> theta, phi (B,2,N), r (B) x = r*cos(theta)*sin(phi) y = r*sin(theta)*sin(phi) z = r*cos(phi) """ r = torch.sqrt(torch.sum(sphere_points*sphere_points, dim=1)) theta = torch.atan2(sphere_points[:,1,:], sphere_points[:,0,:]) ...
3332240df5230d801800ab3601873d26872326fc
8,672
def get_cpu_cores(): """获取每个cpu核的信息 Returns: 统计成功返回是一个元组: 第一个元素是一个列表存放每个cpu核的信息 第二个元素是列表长度, 也就是计算机中cpu核心的总个数 若统计出来为空, 则返回None """ cpu_cores = [] with open('/proc/cpuinfo') as f: for line in f: info = line.strip() if info.starts...
ad66faac3a956b1922173263415890bc543e0bba
8,673
from typing import Union from typing import Tuple def itk_resample(image: sitk.Image, spacing: Union[float, Tuple[float, float, float]], *, interpolation: str = "nearest", pad_value: int) -> sitk.Image: """ resample sitk image given spacing, pad value and interpolation. Args: ima...
37636c42e3f28c09dc0d3ef511c483eec0d3b3e2
8,674
def gen_anchor_targets( anchors, image, bboxes, labels, num_classes, negative_overlap=0.4, positive_overlap=0.5 ): """ Generate anchor targets for bbox detection. @author: Eli This is a version of anchor_targets_bbox that takes tensors for images, bboxes, and labels to play...
6ac0b5602a6d3aa2d1905da09f457ca44193b02c
8,675
def parameters_to_weights(parameters: Parameters) -> Weights: """Convert parameters object to NumPy weights.""" return [bytes_to_ndarray(tensor) for tensor in parameters.tensors]
e235fee46ad9ffcc31eea86f2491a9ac305d3ac5
8,676
from multiprocessing import Pool def get_iou(data_list, class_num, save_path=None): """ Args: data_list: a list, its elements [gt, output] class_num: the number of label """ ConfM = ConfusionMatrix(class_num) f = ConfM.generateM pool = Pool() m_list = pool.map(f, data_list) ...
cce5b270a34700eed592e9a47d0c56a8b43027ff
8,677
import torch def hook_modules(module): """ Temporarily adds the hooks to a `nn.Module` for tracing """ hooks = [] def register_submodule_tracer(module): def _submodule_pre_tracer(module, input): log.debug(f'pre tracer in _submodule_pre_tracer in {type(module).__name__}') l...
1a165b4a49f3179485811eced8b114e0b0a6da8b
8,678
def bridge_forward_delay(brname): """Read a bridge device's forward delay timer. :returns ``int``: Bridge forward delay timer. :raises: OSError, IOError (ENOENT) if the device doesn't exist. """ return int(_get_dev_attr(brname, 'bridge/forward_delay'))
ba164ba85f1e1e3c5f82e28f38413cb8ca9e5090
8,679
def RF(X, y, X_ind, y_ind, is_reg=False): """Cross Validation and independent set test for Random Forest model Arguments: X (ndarray): Feature data of training and validation set for cross-validation. m X n matrix, m is the No. of samples, n is the No. of fetures y (ndarray...
c8ab9aa7cf6bbe159be172cdea82bc970b896914
8,680
import struct def keystring2list(s): """convert a string of keys to a list of keys.""" if len(s) == 0: return [] keys = [] i = 0 while i < len(s): keylength = struct.unpack(data.MESSAGE_KEY_LENGTH_FORMAT, s[i:i + data.MESSAGE_KEY_LENGTH_SIZE])[0] i += data.MESSAGE_KEY_LENGT...
b580d4062be1f5e99f5264aeb5c0a7e4cb70bbd2
8,681
def binary_fmt(num, suffix='B'): """A binary pretty-printer.""" if num == 0.0: return '0 %s' % suffix for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return '%.3g %s%s' % (num, unit, suffix) num /= 1024.0 return '%.3g %s%s' % (num, 'Yi', suffix)
70ae3ee429dd80e8d9cb3a1a3c6eeba09f7ea77a
8,682
def transformMatrices( translation = (0,0,0), center = (0,0,0), rotation = (0,1,0,0), scale = (1,1,1), scaleOrientation = (0,1,0,0), parentMatrix = None, ): """Calculate both forward and backward matrices for these parameters""" T,T1 = transMatrix( translatio...
0d1ae564b0e27000ce1c8d0a3e5aa04ec02fa19f
8,683
async def get_region(country=None, id=None): """ `linode_region` provides details about a specific Linode region. """ __args__ = dict() __args__['country'] = country __args__['id'] = id __ret__ = await pulumi.runtime.invoke('linode:index/getRegion:getRegion', __args__) return GetRegion...
09bd2e83496b6a38d477a24e3bc70a72a8bea8a7
8,684
def entry_type(entry, default): """Return the type of and entry""" if entry.attribute is None: return default return entry.attribute.get('entry_type', default)
04825e225e86bbb98808d0d18633032c022e4870
8,685
def build_expression(backend, arrays, expr): """Build an expression, based on ``expr`` and initial arrays ``arrays``, that evaluates using backend ``backend``. """ return CONVERT_BACKENDS[backend](arrays, expr)
da10481741b2dae18e47a7b203dc548cc6d78a0e
8,686
import argparse def build_parser(args): """ A method to handle argparse. """ parser = argparse.ArgumentParser(usage='$ python verdict.py', description='''Downloads, filters and re-publishes the Google ...
e28ee8a0e9ebbb614802f4cb59b7064138a87fa7
8,687
from mlalchemy.parser import parse_query as mlalchemy_parse_query from typing import OrderedDict def parse_query(qd, session, config): """Parses the given query dictionary to produce a BaseQuery object.""" defaults = { "limit": config["default_limit"], "backref_limit": config["default_backref...
17001d60365451375939fd902a6720b4d5889a7c
8,688
from typing import Dict def get_covid19_us_bears( url_root=CSV_URL_ROOT, file_prefix=CSV_FILE_PREFIX, file_suffix=CSV_FILE_SUFFIX, encoding=CSV_ENCODING) -> Dict[Dict[Bears]]: """Converts USAFACTS confirmed and deaths CSV files to state and county `Bears` to a dictionary of dictionaries. Args: ...
2cdc1b3112cde9d589388666484cf17a0f6055af
8,689
from typing import Optional from typing import Union from typing import Tuple import json def jsonify_promise( future_obj: Input[Jsonable], indent: Input[Optional[Union[int, str]]]=None, separators: Input[Optional[Tuple[str, str]]]=None ) -> Output[str]: """Convert a Promise object to a Promis...
bc0769d6897c771c4a04b76ace11b90c13bde844
8,690
def randnums(start, stop, n_samples): """ Helper function to select real samples and generate fake samples """ ix = [] for i in range(n_samples): ix.append(randint(start, stop)) ix = np.array(ix) return ix
da2e06527e56e9a971a904fee176428bef2b536a
8,691
def shift_1_spectra(spectra, shift): """ This method find the relative position of the FFT of the two spectras \ in order to later k-linearize. Args: :param spectra1: OCT spectra of first mirror. :type spectra1: list Return: :rname: Zspace: - pi to pi linear vector space ...
b76616a064da9eefb9199088ffba50950c9f160a
8,692
import pandas import types def hpat_pandas_series_div(self, other, level=None, fill_value=None, axis=0): """ Pandas Series method :meth:`pandas.Series.div` and :meth:`pandas.Series.truediv` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_serie...
25fdfed169738ee0a7d1faabba7b52217736cbe9
8,693
def alias(self, arg): """ set the new alias to magic *alias alias1 string* alias1 is added into magic command """ if arg == '' or arg.lower() == 'help': return dbhelp(self, 'alias') name, fstring = arg.split(" ", 1) print "new alias: %s <%s>" % (DBPRINT.msg_green(name), fstring) ...
aaf4c3d72b740888b2282258b6138c80827e8665
8,694
def _transform_cat_options(metadata: dict) -> pd.DataFrame: """Transform category options metadata into a formatted DataFrame.""" df = pd.DataFrame.from_dict(metadata.get("categoryOptions")) df = df[["id", "code", "shortName", "name"]] df.columns = ["co_uid", "co_code", "co_shortname", "co_name"] re...
b1e9ac9ac578c8c0253ee7a0ece58a090d134385
8,695
def idaview(request, idadb, idadf): """ IdaDataFrame fixture to be used for the whole testing session. Open a view based on idadf fixture. """ def fin(): try: idadb.drop_view("TEST_VIEW_ibmdbpy") idadb.commit() except: pass request.addfinalizer...
6540f4e844b8709b4b8338b15aa913e3ed67d4da
8,696
import sys import os def get_openmp_flag(compiler): """Returns list of flags for using OpenMP depending on compiler and platform. Parameters ---------- compiler : numpy.distutils.compiler Compiler used when invoking setup.py build """ if hasattr(compiler, 'compiler'): com...
f8dd4ad0cda24f517746828a6d879abd6d6ced4d
8,697
def heuristical_lengths(items): """ heuristical_lengths tries to deriver the lengths of the content of items. It always returns a list. a) If typeof(items) is a string, it'll return [len(items)] b) If typeof(items) is a dict, it'll return [len(items)] c) If typeof(items) is either list or tuple,...
94a0759bcdc2e57431e8524f164a51f2091b6e61
8,698
import subprocess def tifpages(file_id, filename, db_cursor): """ Check if TIF has multiple pages """ p = subprocess.Popen(['identify', '-format', '%n\\n', filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = p.communicate() try: if int(len(out.split())) == 1: ...
f126370866b421b120b56e8b6e84087d617e31c8
8,699