content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def TC_NTU(T1,T2,T3,T4,NTU): """ Outlet temperature of the cold side of the heat exchanger with given number of transfer units (for a counterflow heat exchanger only) """ C = (T1 - T2) / (T4 - T3) if C<1: E = (1 - exp((C - 1) * NTU)) / (1 - C*exp((C - 1) * NTU)) Ecold = E...
0186026757d0ac8da45821315c38e0846ad328c0
39,338
def quadraticEval(a, b, c, x): """given all params return the result of quadratic equation a*x^2 + b*x + c""" return a*(x**2) + b*x + c
cfb808435b50ec262ec14cd54cf9caf30f2bc4b8
39,339
def file_format_from_suffix(file_suffix: str) -> FileFormat: """Returns the file format associated with the file extension (`tfrecord`).""" if file_suffix not in _FILE_SUFFIX_TO_FORMAT: raise ValueError('Unrecognized file extension: Should be one of ' f'{list(_FILE_SUFFIX_TO_FORMAT.values()...
f6dc5bc65174d3154663c1dca043144a4577e42e
39,340
def upgrade_tarball_install(config, new_tarball, preserve_old_install): """Performs an upgrade for an existing Scalyr Agent 2 that was previously installed using the tarball method. @param config: The configuration for this agent. @param new_tarball: The path to file containing the new tarball to install. ...
87d91294a565881f0cf648d8b8396eff631a240f
39,341
from typing import List def grab_std_includes(headers: List[str], sources: List[str]) -> List[str]: """Grab all std includes from headers and sources""" total_std_includes: List[str] = [] for header in headers + sources: with open(header) as file: lines = file.readlines() ...
d1ad1ffc6c53134c95002c88e591349f355f5473
39,342
def get_testcase_params(): """ Returns the list of testcase parameters from the configuration file :return: dict """ testcase_parameters = dict() parameters = CONF_FILE.get_variable_list(cf.CFS_TESTCASE_PARAMETERS) for param in parameters: testcase_parameters[param] = CONF_FILE.get_...
1b4d4fd704be348def8bedbec09c2380b2a35412
39,343
def job_get_script_list(request, biz_cc_id): """ 查询业务脚本列表 :param request: :param biz_cc_id: :return: """ # 查询脚本列表 client = get_client_by_request(request) script_type = request.GET.get('type') kwargs = { 'bk_biz_id': biz_cc_id, 'is_public': True if script_type == '...
ccdf1a0d6c9b95ab229be30eab1ef67ed80a6dbf
39,344
def stringdb_escape_text(text): """Escape text for database_documents.tsv format.""" return text.replace('\\', '\\\\').replace('\t', '\\t')
5d41b0b224cb314141b669ff721896d04a2fe2e8
39,345
import torch def in_parallel(model, device_ids): """ Wraps a model in a DataParallel module such that it supports an input dictionary for multiple inputs rather than kwargs. """ return RemoveStatePrefix(DictToKwargs(torch.nn.DataParallel( KwargsToDict(model), device_ids)), 'module.modu...
acb707311ea2aff49ac33636565b69fb1643a8d2
39,349
def mean_ap(dist_mat, query_ids, gallery_ids, query_cams, gallery_cams): """Compute mean average precision (mAP)""" dist_mat = dist_mat.cpu().numpy() m, n = dist_mat.shape query_ids = np.asarray(query_ids) gallery_ids = np.asarray(gallery_ids) query_cams = np.asarray(query_cams) gallery_cams...
05e79c4b4d0c0407a823c8c8985c7a3c51a8ceaf
39,350
def check_account_age(key): """ Searches DynamoDB for stored user_id or account_id string stored by indicator creation rules for new user / account creation """ if isinstance(key, str) and key != "": return bool(get_string_set(key)) return False
e26a98eccefa32c2e5319bd550629818a68d8ccc
39,351
def _is_cluster_volume(cluster_id, ebs_volume): """ Helper function to check if given volume belongs to given cluster. :param UUID cluster_id: UUID of Flocker cluster to check for membership. :param boto.ec2.volume ebs_volume: EBS volume to check for input cluster membership. :...
331d4f2a441718dffb8c529b570b9d285ff1a162
39,352
def serialize_sqla(data): """Serialiation function to serialize any dicts or lists containing sqlalchemy objects. This is needed for conversion to JSON format.""" # If has to_dict this is asumed working and it is used. if hasattr(data, 'to_dict'): return data.to_dict() if hasattr(data, '__d...
d1f91dc42054bbe250d9145bc0c2223224b59be1
39,353
def friends(graph, user): """Returns a set of the friends of the given user, in the given graph""" return set(graph.neighbors(user))
125c3cc21be4cc29f9ff6f0ff0bb60b35a1074ba
39,354
import xml def _ValueOrPlaceHolder(value_string, description): """Embeds a string inside an XML <value>...</value> element. If the string is empty or None, an alternate string is used instead. Args: value_string: String to embed description: String to be used if the value string is empty or None. R...
c784a5adff28cb5fd9c30f5d30eee56e318c433f
39,355
from typing import List from typing import Tuple from typing import Callable def get_input_labels( io_gratings: List[ComponentReference], ordered_ports: List[Port], component_name: str, layer_label: Tuple[int, int] = (10, 0), gc_port_name: str = "o1", port_index: int = 1, get_input_label_t...
d64f916a533e351d2a5a447daf0f0f204a7350e1
39,356
def process_NNC(chrom, positions, strand, edge_IDs, vertex_IDs, transcript_dict, gene_starts, gene_ends, edge_dict, locations, vertex_2_gene, run_info): """ Novel not in catalog case """ novelty = [] start_end_info = {} gene_ID = find_gene_match_on_vertex_basis(vertex_IDs, strand, vert...
066d208aa091e51885c5adff7497af2d6003383c
39,357
def RLT(n, f): """run length transform of a function f""" return prod(f(len(d)) for d in split("0+", bin(n)[2:]) if d != "") if n > 0 else 1
e52cb3c806e2d0e8d0dd1e47082bacf090827799
39,358
def diagonal(a, offset=0, axis1=None, axis2=None, extract=True, axes=None): """ diagonal(a, offset=0, axis1=None, axis2=None) Return specified diagonals. If `a` is 2-D, returns the diagonal of `a` with the given offset, i.e., the collection of elements of the form ``a[i, i+offset]``. If `a` h...
e18a9ca2dcab7beb5891f701cdc0f26c3943f749
39,359
from pathlib import Path def build_algod_local_client(data_dir: Path) -> AlgodClient: """ Build the `algod` client to interface with the local daemon whose configuration is at `data_dir`. Args: data_dir: the path with the network data Returns: the client connected to the local al...
b1921cd3eb3468ff1b6d556da7c436dce405021f
39,363
def set_read_only(khoros_object, enable=True, msg_id=None, msg_url=None, suppress_warnings=False): """This function sets (i.e. enables or disables) the read-only flag for a given message. :param khoros_object: The core :py:class:`khoros.Khoros` object :type khoros_object: class[khoros.Khoros] :param en...
0a3849d3e589b668d465ac9d2bbd1d13fb346ed5
39,364
def reports_download(request, file_name): """Generic method for downloading files.""" try: file_path = '%s/%s' % (MEDIA_ROOT, file_name) fp = open(file_path, 'rb') response = HttpResponse(fp.read()) fp.close() mime_type, encoding = mimetypes.guess_type(file_name) ...
8ce3124304d340a3ff4892ab1c63f90f38f9ee42
39,365
def bucket_sort(array: list[int]) -> list[int]: """ Time Complexity of Solution: Worst Case: occurs when all the elements are placed in a single bucket. The overall performance would then be dominated by the algorithm used to sort each bucket. In this case, O(n log n), because of TimSort. Avera...
744165384ad1e562c0acd695e90676dcced8db79
39,366
def create_tokenizer_from_hub_module(): """Get the vocab file and casing info from the Hub module.""" with tf.Graph().as_default(): bert_module = hub.Module(BERT_MODEL_HUB) tokenization_info = bert_module(signature="tokenization_info", as_dict=True) with tf.Session() as sess: vocab_file, do_lower_...
0782b6c66253ce053ef693b3dba9006fff2ce8e1
39,367
def get(package, plugin): """Get a given plugin""" _import(package, plugin) return _PLUGINS[package][plugin].func
e47d0c655d210515f7d1dae520f32943ea67f9d0
39,368
def read_paragraph_element(element): """Returns the text in the given ParagraphElement. Args: element: a ParagraphElement from a Google Doc. """ text_run = element.get('textRun') if not text_run: return '' return text_run.get('content')
96df0dc1c2ded0bdb1105bfacc4150c27f9e21c9
39,369
def telnet_read_eager(tn: ConnectionInformation, wf: object, current_output_log: [str], enable_removeLF: bool) -> str: """ Dealing with unread material. """ if tn.eof: return False try: # current_output = tn.read_very_lazy() # Not recommended because it will be blocked. cur...
d1d1a25b2345d2b1f0fcefe10d00c07b74051070
39,370
def parse_int(integer, default=None): """提取整数,若失败则返回default值""" try: return int(integer) except Exception, e: return default
c064ab555763570515d97f403cf8a144f9598bc3
39,372
def ctd_sbe16digi_preswat(p0, t0, C1, C2, C3, D1, D2, T1, T2, T3, T4, T5): """ Description: OOI Level 1 Pressure (Depth) data product, which is calculated using data from the Sea-Bird Electronics conductivity, temperature and depth (CTD) family of instruments. This data product...
3756752c661773bd74436311a278efdaa3d3913f
39,373
import hashlib def sha256(file: str): """ Reads a file content and returns its sha256 hash. """ sha = hashlib.sha256() with open(file, "rb") as content: for line in content: sha.update(line) return sha.hexdigest()
c6babc2939e25228df25827a5a0b383d6c68dd07
39,374
import logging def make_div_share_variable(exposure_level=7, div_level=3): """Calculates the share of employment in a low diversification sector Args: exposure_level (int): min threshold for high exposure div_leve (int): min threshold for low diversification """ _DIVISION_NAME_LOOKUP ...
a6b1ab48b40a4fd861f1d52faf5a83d00c35b08c
39,375
def _user_has_perm(user, perm, obj): """ A backend can raise `PermissionDenied` to short-circuit permission checking. """ for backend in auth.get_backends(): if not hasattr(backend, 'has_perm'): continue try: if backend.has_perm(user, perm, obj): r...
bf5882e4fbef7b1d9fa1c971841565f43a6f2e93
39,376
def gcd(a, b): """ Computes the greatest common divisor between the two numbers using Euclid's algorithm. """ if b == 0: return a else: return gcd(b, a % b)
9ea816a44e1f3d117c621bf7841428d2d15e9c24
39,377
def rect_crop_2D(im, rect_spec): """following imageJ style rectangle specification""" left, top, width, height = rect_spec im_crop = im[top:top+height, left:left+width].copy() return im_crop
6af43a11eee580b537b236b57d063b3631465292
39,378
def encode_multipart_formdata(fields, files): """ @param fields: sequence of (name, value) elements for regular form fields. @param files: sequence of (name, filename, value) elements for data to be uploaded as files @return: (content_type, body) ready for httplib.HTTP instance """ boun...
70fc71f48eeb31e2dd41bb88cd060b00c5bb6e3a
39,379
def coverage_err(y_true, y_pred): """ Coverage error: For every sample, how far down the ranked list of predicted classes must we reach to get all actual class labels? The average value of this metric across samples is the coverage error. :param y_true: array of shape (n_samples, n_labels) :par...
4e28d7847714c47ab71473c1dbc0dfdef5e1653c
39,380
def login(*args, **kwargs): """ Override view to use a custom Form """ kwargs['authentication_form'] = AuthenticationFormAccounts return login_base(*args, **kwargs)
d3c7c926e7652254a927979451907a702ee1499a
39,381
def _calculate_bearings(graph, nodes): """ Calculate the compass bearings for each sequential node paid in `nodes`. Lat/lon coordinates are expected to be node attributes in `graph` named 'y' and 'x'. Args: graph (networkx graph): containing lat/lon coordinates of each node in `nodes` ...
7ed04f75b12843a2f7a31a0bf384cb0b772d9f82
39,382
def lookup_capacity(lookup, environment, ant_type, frequency, bandwidth, generation): """ Use lookup table to find the combination of spectrum bands which meets capacity by clutter environment geotype, frequency, bandwidth, technology generation and site density. """ if (environment, ant_ty...
3bd132f97022acfe33c4bc6d706265e808679eae
39,384
from typing import Any def option(parser: Parser, otherwise: Any = None) -> Parser: """Create a parser that succeeds even when the given parser does not. If nothing was parsed, then the value that was parsed is |otherwise|. """ def fn(parse_state): """Parse with parser, return value of None i...
dbc88037855b232881f0cdfe25d195d2985ef865
39,385
import json def to_json(response): """ Return a response as JSON. """ assert response.status_code == 200 return json.loads(response.get_data(as_text=True))
4fb4d62eb8b793363394b6d0759a923f90315072
39,386
def num(s): """This function is used to convert string to int or float.""" try: return int(s) except ValueError: return float(s)
a3faae6fa4f166898b281f9e114fcff8abdcd2e3
39,387
from pathlib import Path def equalize(request): """ヒストグラム平坦化関数""" # キャッシュディレクトリを作成 cache_dir = Path(__file__).parent.joinpath('cache').joinpath('equalize') cache_dir.mkdir(parents=True, exist_ok=True) # 画像データをbase64形式で取得 base64image = request.POST.get('image') # base64をバイナリデータに変換し、ヘッダーも同...
18fd0b41baec1e49427238703f5345f9097c3ad3
39,388
def mutation_frequency(H, D): """ # ======================================================================== MUTATION FREQUENCY PURPOSE ------- Calculates the mutation frequency. INPUT ----- [INT] [H] The number of haplotypes. [2D ARRAY] [D] A distance mat...
688a0540be6e67834e3bdae527191f4275bae641
39,389
from datetime import datetime def _parse_given(rtype: str, report: str, opts: [str]) -> (dict, int): """ Attepts to parse a given report supplied by the user """ try: ureport = _HANDLE_MAP[rtype]("KJFK") # We ignore the station ureport.update(report) resp = asdict(ureport.data...
f9af0fadf16c37f9884ddb0d391e79878c55b87e
39,390
def new_feature(signal): """Computes a new feature Parameters ---------- signal : nd-array Input from which new feature is computed Returns ------- float new feature """ return np.mean(signal)-np.std(signal)
e85dd3edec1f824d64d645c0d32dfda751c52c4e
39,391
def SKPD_processing(Cov_MPMB, opt_str): """SKPD_processing Kernel of the Sum of Kronecker Product Decomposition. INPUT Cov_MPMB: [N*Npol x N*Npol] covariance matrix opt_str. N: number of images Npol: number of polarization...
bfd11c067acf0a71a3f00d99c43a63895281c9cd
39,393
def get_public_keys_of_user(session, user_id): """Retrieve all public keys for user. Args: session(models.base.session.Session): database session user_id(int): id of user in question Returns: List of PublicKey model object representing the keys """ pkey = session.query(Publ...
ebb367bf8ed14f94d597bc4fc8942d6c51f3b0f2
39,395
def avgFriendDegree(v, Giant): """ Calculate the average degree of the neighbors of a node""" degSum = 0 for u in Giant.neighbors(v): degSum += Giant.degree(u) return degSum / Giant.degree(v)
667213aeb0f66887c629aef784f83549ced7bdb6
39,396
def create_snapshot_if_not_exist(volume_id, tags, time_limit): """ Create a snapshot of the volume in parameter only if any snapshot exists for this volume_id and if it was created in the time delta define by the difference between now and the time_limit value (in minutes). :param ...
4b469243f935296068ad9a81eeeca5b0ee1717e0
39,397
def calculate_sigma_v(depths, gammas): """ Calculates the vertical stress """ depth_incs = depths[1:] - depths[:-1] depth_incs = np.insert(depth_incs, 0, depth_incs[0]) sigma_v_incs = depth_incs * gammas sigma_v = np.cumsum(sigma_v_incs) return sigma_v
22ab0582bf67935d6358bbccd37db0750ddb9976
39,398
def lon_lat_to_cartesian(lon, lat, radius=1): """ calculates lon, lat coordinates of a point on a sphere with radius radius """ # Unpack xarray object into plane arrays if hasattr(lon, 'data'): lon = lon.data if hasattr(lat, 'data'): lat = lat.data if lon.ndim != lat.nd...
54fb3275b1a36a479f30feeaf50a87f0a0b25342
39,399
def get_eia860_xlsx(years, filename, data_dir): """Read in Excel files to create Excel objects. Rather than reading in the same Excel files several times, we can just read them each in once (one per year) and use the ExcelFile object to refer back to the data in memory. Args: years (list):...
a9a92e52464836fa4881591ef0d9dad78cc24816
39,400
from typing import List import statistics def SmoothArray(xx: List[float]) -> List[float]: """Runs the 353QH algorithm twice and returns smooth version of the input. For documentation see these proceedings https://cds.cern.ch/record/186223/ on page 292. The algorithm runs twice to avoid over-smoothing pe...
39e322178772cbf995a109de656898ed6c0a0696
39,403
from operator import sub def check_attack(board, bad_positions, snake): """ Determines if we have the opportunity to attack - doesn't seek out attacking but will attack given the opportunity """ possible_attacks = [] available_moves = available_next_positions(board, snake) # attack potential position...
2f8445dc816b1f88d652fcbe638bc3485942d744
39,404
def station(): """ Return a list of all stations from database. """ session = Session(engine) results = session.query(Station.name).all() session.close() station_dict = list(np.ravel(results)) return jsonify(station_dict)
a384c8fa1639ea3e76e1269907daf128f642ed3e
39,405
def dots2utf8(dots): """ braille dots to utf-8 hex codes""" code=0 for number in dots: code += 2**(int(number)-1) return hex(0x2800 + code)
0406c3cf18d5dbd66ea35b0862785371cdd68796
39,406
def set_domain_to_dns_name(session, domain_name, dns_resource, hosted_zone): """Updates or Creates a domain name with FQDN resource. Args: session (Session|None) : Boto3 session used to lookup information in AWS If session is None no lookup is performed domain_n...
bb3fc8d999039109bcd69fbe30e18458512eb1fc
39,407
import itertools from functools import reduce import operator def full_range_args_generator(**ranges): """ Cartesian production, generates all possible combinations of the arguments :param ranges: range(...) objects or lists, defines arguments' domains :return: """ res = itertools.product(*(r ...
96ccf2c576dfb06ea6e65853478e00adfc5dd1af
39,408
def _can_view_courseware_with_prerequisites(user, course): """ Checks if a user has access to a course based on its prerequisites. If the user is staff or anonymous, immediately grant access. Else, return whether or not the prerequisite courses have been passed. Arguments: user (User): the...
3d39e73b4217872776f4684201353581f525b24e
39,409
def _convert_to_coord_format(interaction_file, out_file): """make it easier to work with interaction file, produces start_id, end_id, score """ assert interaction_file.endswith(".gz") assert out_file.endswith(".gz") # reformat reformat = ( "zcat {} | " "awk -F ',' '{{ pr...
4e0626a631f23f902a2191ce8fe63e60b884f79b
39,410
def add_num_epochs_and_checkpoints(config): """Add number of epochs and checkpoints where model will be saved to config.""" problem_cls = config["problem_cls"] num_epochs = DEFAULT_TEST_PROBLEMS_SETTINGS[problem_cls.__name__]["num_epochs"] config["num_epochs"] = num_epochs if "checkpoints" not in c...
c2827aca8ce69dd74cc856d5f75f782920765ad0
39,412
import ast def doCompare(op, left, right): """Perform the given AST comparison on the values""" top = type(op) if top == ast.Eq: return left == right elif top == ast.NotEq: return left != right elif top == ast.Lt: return left < right elif top == ast.LtE: return left <= right elif top == ast.Gt: retur...
b82a1c4d101428cf9ded532d65539cfe3195d8a1
39,413
def runGdScript(godot, filepath): """Run the given GdScript file and return the results as an array of strings""" return runGodot([godot, '-s', filepath])
956a7f572349f70bce58e27f8f27c1a2aef36d63
39,416
import torch def unmold_mask(masks, bboxes, image_shape): """Converts a mask generated by the neural network into a format similar to it's original shape, using overlap-tile strategy here. masks: [detect_num, depth, height, width, num_instances] of type float. A small, typically 28x28 mask. bboxes: [d...
94cae3ebd455e228ce67f1d9675b08e11c801ef9
39,417
def create_link_atoms(mol, qmatoms): """ Create hydrogen caps for bonds between QM and MM regions. Each link atom will have ``metadata.mmatom``, ``metadata.mmpartner`` attributes to identify the atom it replaces and the atom it's bonded to in the MM system. Raises: ValueError: if any MM/QM ato...
abc9a8feb74c0a411a79b00b4d729c4a82a1a39b
39,418
import hmac import hashlib def generate_signature(secret, verb, url, nonce, data): """Generate a request signature compatible with BitMEX.""" # Parse the url so we can remove the base and extract just the path. parsedURL = urlparse(url) path = parsedURL.path if parsedURL.query: path = path...
5d173a6f8ab472e8547e3739f19cfd73d9fb9c4b
39,419
def get2(request): """一键多值""" # 获取GET属性对应的queryDict类型的对象 query_dict = request.GET a = query_dict.getlist('a') # query_dict.get('a') 只会获取最后一个值 b = query_dict.get('b') c = query_dict.get('c') # 如果key不存在,返回None str = '%s - %s -%s' % (a, b, c) return HttpResponse(str)
c43c83c560e469a76af22b98e0c448e7ad84cf2e
39,420
from __init__ import identifier def signature(class_name): """return the signature for a port using one of the module classes defined in this file""" return ':'.join((identifier, class_name))
efcffe04c716c334e7e0e7d7507647cc48e0dbd0
39,421
from . import Label from . import get_volume_labels_from_aseg def get_volume_labels_from_src(src, subject, subjects_dir): """Return a list of Label of segmented volumes included in the src space. Parameters ---------- src : instance of SourceSpaces The source space containing the volume regio...
2a893f6462640bdd08c782d87e31a20894fd136e
39,422
import platform def get_path_name(obj_name, io=None): """ Returns a path and a name for where the downloaded objects (list or excel file) will be stored. :param str obj_name: a list name or a path to an excel file in sharepoint :param str io: path to where downloaded objects (list or excel file) will be s...
602436f393a74006f10be23efad3d0c58391d24f
39,423
def Lagrange_polynomials_01(x, N): """ Compute all the Lagrange polynomials (at x) for N+1 equally spaced interpolation points on [0,1]. The polynomials and points, as two separate lists, are returned. Works for symbolic and numerical computation of the polynomials and points (if x is sympy.Symb...
9bbb7d8b789ea90108ac471db232ae16e66d2f21
39,424
def _random_integer(minval, maxval, seed): """Returns a random 0-D tensor between minval and maxval. Args: minval: minimum value of the random tensor. maxval: maximum value of the random tensor. seed: random seed. Returns: A random 0-D tensor between minval and maxval. """ return tf.random.u...
0760098d43b41c66a5609295b6334cdb0f7349f4
39,425
def list_posts(page=1, num_items=10): """List all blog posts, in sets of 10.""" url = bottle.request.urlparts page = bottle.request.query.page or 1 try: page = int(page) if int(page) > 0 else 1 except: bottle.abort(404, "Page not found") count = db.zcard("content:posts:live") ...
8c400fef15f88429e178bf4f858c2e35dd934626
39,426
def read_dataset(path, header=None, columns=None, make_binary=False, binary_th=4.0, user_key='user_id', item_key='item_id', rating_key='rating', sep=',', user_to_idx=N...
9c071af4e026c437915b96f8f4cbbf6f200397c7
39,427
def _normalize_unknown_symbols(token): """Símbolos (letras) no reconocidos los decodifica a ASCII.""" return ''.join([ s if ALPHABET.match(s) else _to_unicode(unidecode(s)) for s in _to_unicode(token)])
31c63426358b649d4e2200fa02a4e7a0891a9d46
39,428
def _customized_dumper(container, dumper=Dumper): """ Coutnerpart of :func:`_customized_loader` for dumpers. """ def container_representer(dumper, data, mapping_tag=_MAPPING_TAG): """Container representer. """ return dumper.represent_mapping(mapping_tag, data.items()) def us...
a36bbfdfffefc278586c226c2404fe4c690c5cd0
39,429
def raw_encode(data): """Special case serializer.""" content_type = 'application/data' payload = data if isinstance(payload, unicode): content_encoding = 'utf-8' payload = payload.encode(content_encoding) else: content_encoding = 'binary' return content_type, content_enco...
e4f7042f0aea627913d554b2fc63b6f79771241c
39,430
def iou(box1, box2): """Computes pairwise intersection-over-union between box collections. Args: box1: a float Tensor with [N, 4]. box2: a float Tensor with [M, 4]. Returns: a tensor with shape [N, M] representing pairwise iou scores. """ intersections = intersection(box1, box2) areas1 = area(...
021056736b7cc128d34097da2cc5096b92e52935
39,431
def bytes_realize(space, py_obj): """ Creates the string in the interpreter. The PyBytesObject buffer must not be modified after this call. """ py_str = rffi.cast(PyBytesObject, py_obj) s = rffi.charpsize2str(py_str.c_buffer, py_str.c_size) w_obj = space.wrapbytes(s) track_reference(spac...
b3c5841f307ed30354632f256417c4b574375299
39,432
def get_interface_by_name(interfaces, name): """ Return an interface by it's devname :param name: interface devname :param interfaces: interfaces dictionary provided by interface_inspector :return: interface dictionary """ for interface in interfaces: if interface['devname'] == name:...
9d63bf667a0677ba7d0c3fdde2b4b35affc3b72b
39,433
import unicodedata def trata_texto(texto): """ Trata textos convertendo para maiusulo,\n sem acentos e espaços indesejaveis. """ texto = texto.strip().upper() texto = unicodedata.normalize("NFKD", texto) texto = texto.encode("ascii", "ignore") texto = texto.decode("utf-8").upper() # ...
0cced9e55fd3fc15a9cdbaa3899519658668025c
39,434
def normalize_trans_probs(p): """ Normalize a set of transition probabilities. Parameters ---------- p : pandas.DataFrame, dtype float Unnormalized transition probabilities. Indexed by source_level_idx, destination_level_idx. Returns ------- pandas.DataFrame, dtype floa...
d484c4ac08ee785e5451b1aa92ff2b85fc945384
39,436
def vel(track, t_vel, r): """Randomly change the velocity of a note in a track""" time = 0 for msg in track: if msg.type == 'note_on' or msg.type=='note_off': time += msg.time if msg.type == 'note_on': if msg.velocity != 0: # To avoid messing with certain mid ...
dcce7b2810a5407444e4cd19cfd0eb363856d59c
39,437
def resize_with_fixed_AR(img, bboxes, h_dst, w_dst): """resize with fixed aspect ratio""" w_src = tf.cast(tf.shape(img)[1], tf.float32) h_src = tf.cast(tf.shape(img)[0], tf.float32) # resize image if h_dst > h_src * (w_dst / w_src): scale = (w_dst / w_src) else: scale = (h_d...
925105612073b1f241f533800254829ba630e6ad
39,438
def choose(): """ Get the user to choose which quiz. :returns: A HTML page with a form, then redirects them to the correct quiz's page once the form is submitted. """ # Ask user which quiz. if 'quiz' not in request.args: return render_template('new.html', quizzes=quizzes) ...
bde45765cdf5e4c7f53bc7c67f75df51c7d8e2d1
39,439
def get_number_of_ones(n): """ Deterine the number of 1s ins the binary representation of and integer n. """ return bin(n).count("1")
83fb14c29064008dd9f8e7ecea4c1d9dfae1dafa
39,440
def hierarchical_link_community(g_original: object) -> EdgeClustering: """ HLC (hierarchical link clustering) is a method to classify links into topologically related groups. The algorithm uses a similarity between links to build a dendrogram where each leaf is a link from the original network and branches ...
6558d218ffeb2f0c473c8e6bbd8a7deb1249b6ab
39,441
import math def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4): """Gets a bunch of sinusoids of different frequencies. Args: length: scalar, length of timing signal sequence. channels: scalar, size of timing emebddings to create. The number of differ...
dbf78c05540e3354a159d46f64949c90f819227d
39,442
def get(keys): """Wrapper around db.get that counts entities we attempted to get.""" DB_GET.inc(increment=_count(keys)) return db.get(keys)
7b194e2d63ff24ae0681be1cb57468c76c8b964e
39,443
import json def get_graph(request): """Function for getting graph This function allows to get the current graph from server. """ id_of_graph = request.GET.dict()["id"] graph = Graph.objects.get(id=int(id_of_graph)) with open(graph.path_to_graph) as file: data = json.load(file) ...
1a5b5bd5c55f04de5b0cae1c5103cbe665cfd856
39,444
def startswith(df_series, match:str): """ Filter pd.series with string and get index Parameters ---------- df_series : pd.Series match : str, to search the series Returns ------- idx: bool """ return np.array(df_series.str.startswith(match), dtype = bool)
9444412cfda0bf2e332c9f75f41a9d5081af8ff9
39,445
import math def angle2vecs(vec1, vec2): """angle between two vectors""" # vector a * vector b = |a|*|b|* cos(angle between vector a and vector b) dot = np.dot(vec1, vec2) vec1_modulus = np.sqrt(np.multiply(vec1, vec1).sum()) vec2_modulus = np.sqrt(np.multiply(vec2, vec2).sum()) if (vec1_modulu...
160043d91883f98978813cd58e74d26b9dd471c4
39,447
def _func_flagvalue(args, is_differentscenario, line, pos): """フラグの値を読む。""" _chk_argscount(args, 1, "FLAGVALUE", line, pos) _chk_string(args[0], "FLAGVALUE", 0) path = args[0].value event = cw.cwpy.event.get_nowrunningevent() if event and path in event.flags: flag = event.flags[path] ...
7811b641b2234850194cff57df37de0b75e13299
39,448
import json def help(): """ Форма генерации счета для дебага. Принимает POST-запрос с пейлоадом, отдает PDF """ if request.method == "GET": payload_str = json.dumps(sample_payload_obj, indent=4, ensure_ascii=False) return render_template("sample_payload.html", sample_payload_obj=payloa...
4d2ca9c6b9254b00daa2ac043d91406aee26559c
39,450
def cast(variable, dtype): """ Cast sparse variable to the desired dtype. Parameters ---------- variable Sparse matrix. dtype The dtype wanted. Returns ------- Same as `x` but having `dtype` as dtype. Notes ----- The grad implemented is regular, i.e. no...
59f0f53020736673481afae6ad12b450717e450a
39,451
def get_smiles(inp_str, species): """ Get the inchi name of the species """ # Set the geom pattern smi_pattern = ('smiles' + zero_or_more(SPACE) + '=' + zero_or_more(SPACE) + capturing(one_or_more(NONNEWLINE))) # Obtain the appropriate species string species_str = get_spec...
1e34f809567a8633fdd0ed644d6e73bc35f6b7de
39,453
def find_recipes(recipes, cur_recipes, puzzle, condition, result): """Find recipes as long as condition function is True. Returns result of result function, based on recipes and puzzle. """ while condition(recipes, puzzle): next_recipe = sum(recipes[recipe] for recipe in cur_recipes) di...
0183e55941f565c5b34789cecfa89babc269442d
39,454
def set_mosflm_beam_centre(detector, beam, mosflm_beam_centre): """detector and beam are dxtbx objects, mosflm_beam_centre is a tuple of mm coordinates in order (slow, fast). supports 2-theta offset detectors, assumes correct centre provided for 2-theta=0 """ slow_fast_beam_centre = mosflm_beam_...
fd8ed3de6904f2ab2043d057474318ab43099872
39,455
def prob1(N=10000): """Return an estimate of the volume of the unit sphere using Monte Carlo Integration. Input: N (int, optional) - The number of points to sample. Defaults to 10000. """ points = np.random.rand(3, N) points = points*2 - 1 radiusMask = la.norm(points,ax...
aaf2e669aaa8be4d851a6dc9030cf9cd91b1e5e9
39,456