content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import hashlib def create_view_ID(img): """ Generates 12-digit ID of image to make sure each image has a unique identifier. When saving and reading image features, two images with the same filename will have unique identifiers. :param img: image to create an ID for. :return viewID: a unique viewId...
2b429a5c504386e486542ac9f7a4fa663a08c996
3,620,326
import hashlib def calc_local_file_md5_sum(path): """ Calculate and return the MD5 checksum of a local file Arguments: path(str): The path to the file Returns: str: The MD5 checksum """ with open(path, "rb") as file_to_hash: file_as_bytes = file_to_hash.read() re...
78020e86a6d9a6939de6b9050d34fca0d482aab4
3,620,328
import json def news_keywords() -> str: """[Fetches the keywords used to gather news articles] Returns: str: [A string of the keywords searched for by the news API] """ with open("config.json", encoding="UTF-8") as config: config_data = json.load(config) news_kw = config_data[...
b0830625f58de9089130a3d571588ab558b2a3db
3,620,329
from typing import Any def default_weapon_type_option( description: str = "Restrict the weapon type. Default: All types", required: bool = False ) -> Any: """ Decorator that replaces @slash_option() Call with `@default_weapon_type_option()` """ def wrapper(func): return slash_option(...
5e5fe8e05e39ec7329264b4828b4047ea06b368a
3,620,330
from datetime import datetime async def get_patrol_id(request: Request): """ 获取当前order id,已经加 1 的了 """ _date_str = datetime.now().strftime('%Y%m') patrol_id = await request.app['redis'].get(f'it:patrolID:{_date_str}') if patrol_id is None: async with request.app['mysql'].acquire() as conn: ...
fcc0137e1af3ba2a22dc6d54b459af05db4c0e8b
3,620,331
from typing import Union from typing import List def parse( response_text: str, *, batch: bool, validate_against_schema: bool = True ) -> Union[JSONRPCResponse, List[JSONRPCResponse]]: """ Parses response text, returning JSONRPCResponse objects. Args: response_text: JSON-RPC response string. ...
ff0d2c5a4852255588db28068685f92dd6c4c66d
3,620,332
def compute_warped_image_multiNC( I0, phi, spacing, spline_order, zero_boundary=False, use_01_input=True ): """Warps image. :param I0: image to warp, image size BxCxXxYxZ :param phi: map for the warping, size BxdimxXxYxZ :param spacing: image spacing [dx,dy,dz] :return: returns the warped image ...
1f2fffb1ed09fe2b40061dfc5728ed5b672e8828
3,620,335
from datetime import datetime def get_day(days: int = 0): """ 返回的日期格式 %Y-%m-%d :param days: 距离今天的天数 :return: 格式 %Y-%m-%d """ return (datetime.datetime.now() + datetime.timedelta(days=days)).strftime("%Y-%m-%d")
9626098ad53489d8fa9c1d5364e7a471003c48d6
3,620,336
def emit_compare(field_name, value, session, model): """Emit a comparison operation comparing the value of ``field_name`` on ``model`` to ``value``.""" property = getattr(model, field_name) return property == value
a9ad880951f87f488b12c4ce7c38c5e0e463a798
3,620,337
def line_loglog(x, m, n): """a straight line in loglog-space""" return x ** m * np.e ** n
119c6b1d4e758279c10c4667839ea83742556492
3,620,338
def plot_statistical_uncertainty(response_matrix, filename=None, **kwargs): """Plot the maximum sqrt(statistical variance) of each truth bin. This plots will contain the minimum, maximum, and median marginalization of these maximum numbers. Parameters ---------- response_matrix : ResponseMatr...
7b86e929a4d620d3302dce67bfb546f4b05f7c42
3,620,339
import numpy as np import scipy.linalg as la def milcshake_a ( dt, bond, r_old, r, v ): """First part of velocity Verlet algorithm with constraints.""" # This subroutine iteratively adjusts the positions stored in the array r # and the velocities stored in the array v, to satisfy the bond constraints ...
9184b7861383710d84cbe6176e4cca1c206d29c0
3,620,340
def parse_LDI_ins(tokens): """Attempts to parse a LDI instruction.""" failure = None assert len(tokens) > 0 token1 = tokens[0] op = token1.text if op.upper() != 'LDI': return failure statement = Obj() statement.type = 'STATEMENT' statement.statement_type = 'INSTRUCTION' s...
92c6102ccaea4b5fda025c7e7ac10cf0549b56d3
3,620,341
def mad(a, axis=None): """ Compute *Median Absolute Deviation* of an array along given axis. """ # Median along given axis, but *keeping* the reduced axis so that result can still broadcast against a. med = np.nanmedian(a, axis=axis, keepdims=True) mad = np.nanmedian(np.absolute(a - med), axis=a...
7a439c970bab9696d4a1b50725afd6636f437843
3,620,342
import torch def torch_image_to_numpy(image: torch.Tensor): """ We've created a function `torch_image_to_numpy` to help you out. This function transforms an torch tensor with shape (batch size, num channels, height, width) to (batch size, height, width, num channels) numpy array """ ...
0ce27349d40a8063137a79351fa7a696cd8c6615
3,620,343
def unsigned32(i): """cast signed 32 bit integer to an unsigned integer""" return i & 0xFFFFFFFF
1d4e06406d3ee7ce7d8f5cefd28955f135059917
3,620,345
import json def get_snippet_edit_code(request, snippet_id): """ Returns a HTTPResponse that renders the admin of a smartsnippet. :param request: Request needed to create the rendering context :param snippet_id: id of the smartsnippet model :param request.POST.config: dictionary containing existi...
5eaf24488ef8d3ffa8f46356d840fa4b63cf99b3
3,620,346
def get_user_legs(df, user_id, use_multiprocessing=True) -> pd.DataFrame: """ Builds the legs DataFrame for the given user. Args: df (pandas.DataFrame): waypoints DataFrame user_id (str): ID of the user whose legs are to be created use_multiprocessing (bool, optional): Specifie...
6d21192236ad72578e4d9c443f9fdaab12be254a
3,620,347
from typing import List from typing import Tuple from typing import Dict import torch from typing import OrderedDict def generate_input( seq_len: int, batch_size: int, input_names: List[str], device: str = "cuda" ) -> Tuple[Dict[str, torch.Tensor], Dict[str, np.ndarray]]: """ Generate dummy inputs. :p...
d084e1a982ee2ecd60b0e986ead75bc5273ccbb1
3,620,348
def get_task_or_404(challenge_slug, task_identifier): """Return a task based on its challenge and task identifier""" t = Task.query.filter( Task.challenge_slug == challenge_slug).filter( Task.identifier == task_identifier).first() if not t: abort(404) return t
1765069d18604ba00a4efd1fd18a645ccc666fd6
3,620,349
def BuildToken(request, execution_time): """Build an ACLToken from the request.""" token = access_control.ACLToken( username=request.user, reason=request.REQ.get("reason", ""), process="GRRAdminUI", expiry=rdfvalue.RDFDatetime().Now() + execution_time) for field in ["REMOTE_ADDR", "HTTP_X...
164244ca93710c45d0eb8b19b1eb0c934ac89361
3,620,350
import re from datetime import datetime def parse_logfile_event_marker(line_str): """ Parse a logfile line as an event marker. Parameters: line_str (str): a line from the locust log for a load test with markers enabled. Returns: dict: dict object with the following keys: ...
0746e23926c3f4262d163c6e10d0ae8177e36ece
3,620,351
def compute_gad_point_indices_mp(args: tuple) -> dict: """ Computes geometric anomaly detection (GAD) Procedure 1 from [1], for data point indices, taking in args for multiprocessing purposes. Parameters ---------- args : tuple Multiprocessing argument tuple: data_points : n...
c0cc874af561f15b0b8234a5279f54d4df9afdee
3,620,354
def has_and_not_none(obj, name): """ Returns True iff obj has attribute name and obj.name is not None """ return hasattr(obj, name) and (getattr(obj, name) is not None)
0d68a9b01d56ba056768d06a88c68b4bd5bbd4d2
3,620,355
from typing import OrderedDict import attr def _dump(config_instance, dict_type=OrderedDict): """ Dumps an instance from ``instance`` to a dictionary type mapping. :param object instance: The instance to serialized to a dictionary :param object dict_type: Some dictionary type, defaults to ``OrderedDict``...
d8b1242d4ab47b518dfd4523e83c1d67f5e87537
3,620,356
def eval_jac_g(x, out): """Values of the jacobian of g""" assert len(x) == nvar out[()] = [ x[1] * x[2] * x[3], x[0] * x[2] * x[3], x[0] * x[1] * x[3], x[0] * x[1] * x[2], 2.0 * x[0], 2.0 * x[1], 2.0 * x[2], 2.0 * x[3], ] return out
a50f3e8621ad5a54f69d2d154464e6ba8e818337
3,620,357
import re def trivial_tokenize_urdu(s): """ A trivial tokenizer which just tokenizes on the punctuation boundaries. This also includes punctuations for the Urdu script. These punctuations characters were identified from the Unicode database for Arabic script by looking for punctuation symbols. return...
a631328849afb1fbee74788a85169874f1a895ef
3,620,359
def fpath_to_link(repo_id, path, is_dir=False): """Translate file path of a repo to its view link""" if is_dir: url = reverse("repo", args=[repo_id]) else: url = reverse("repo_view_file", args=[repo_id]) href = url + '?p=/%s' % urllib2.quote(path.encode('utf-8')) return '<a href="%...
bd4763c12983763480631714befbb771459a6b1e
3,620,360
def _qname_matches(tag, namespace, qname): """Logic determines if a QName matches the desired local tag and namespace. This is used in XmlElement.get_elements and XmlElement.get_attributes to find matches in the element's members (among all expected-and-unexpected elements-and-attributes). Args: ...
66aa9272fd6e4a6e281d39f03dd63acabad0bbe7
3,620,361
def NodeArrangementHexToTet(C): """Node ordering for conversion of a hexahedron into 6 tetrahedra refer to: [Julien Dompierre et.al. "How to Subdivide Pyramids, Prisms and Hexahedra into Tetrahedra", 8th International Meshing Roundtable, Lake Tahoe, California, 10-13 October 1999.] for only p=1...
919773449d323e6d7b4c632938d89cb6d25440d3
3,620,362
def datetogmt(str): """ Convert date string to gmt time. """ date_tuple = datetotuple(str) return mkgmtime(date_tuple)
5fa593d94926c787c700e5f9aff73d3b5dc5d2e2
3,620,363
def parse_color(color): """ Parses color into a vtk friendly rgb list """ if color is None: color = rcParams['color'] if isinstance(color, str): return vtki.string_to_rgb(color) elif len(color) == 3: return color else: raise Exception(""" Invalid color input M...
c06eec3de5d50e2e3902a66e469f6df96e679971
3,620,364
def skewness(iterable, sample=False): """ Returns the degree of asymmetry of the given list of values: > 0.0 => relatively few values are higher than mean(list), < 0.0 => relatively few values are lower than mean(list), = 0.0 => evenly distributed on both sides of the mean (= normal distribu...
3cee6e2eaf7095d92229d6744deb775e7d5b64a0
3,620,365
def create_plant(user_id, plant_name, plant_type, photo_url, germinate_date, directsow, transplant_date, growing_medium, location, environment, lighting, schedule): """ For example: >>> create_plant(1, "Nadine", "Aloe", "/static/img/aloe.jpg", "11/11/2020", "direct s...
517ff885f551ec898a52138a3179ca2c6830af52
3,620,366
import json def get_line_extents_from_json(json_data, font_file_name): """Find the vertical extents of a line based on HarfBuzz JSON output.""" max_height = None min_height = None for glyph_position in json.loads(json_data): glyph_id = glyph_position['g'] glyph_ymin, glyph_ymax = get_g...
241e715e1393ab2de9f592178ccc9e7f1f516b2f
3,620,368
def findSpikes( file_name, sweep_IB_concatenated, prominence_min = None, prominence_max = None, wlen_ms = 10, sampling_rate_khz = 25 ): """ `findSpikes` uses scipy's `find_peaks` on the concatenated sweeps to detect peaks in the data and obtain their prominences. It then plots the di...
52586d3e55dbc8fbf5cd2a97afb612e1ce8fd3b3
3,620,369
def promptForFlirtFiles(parent, overlay, overlayList, displayCtx, save=False): """Displays a dialog prompting the user to select a FLIRT transformation matrix file and associated reference image for the given overlay. :arg parent: The :mod:`wx` parent object. :arg overlay: The overlay to l...
b17834d762c236b4b6cabfcae779fbd4d4899b29
3,620,370
def coord_c2g(map_): """Rotate a map from celestial co-ordinates into galactic co-ordinates. This will operate on a series of maps (provided the Healpix index is last). Parameters ---------- map : np.ndarray[..., npix] Healpix map. Returns ------- rotmap : np.ndarray T...
4850fb1be975bc2acf6020aa878381f40e1c29ba
3,620,371
def tourism_per_year_by_country(country): """Returns the number of arrivals (tourism) per year of the given country.""" cur = get_db().execute('SELECT Year, Value FROM Indicators WHERE CountryCode="{}" AND IndicatorCode="ST.INT.ARVL"'.format(country)) tourism = cur.fetchall() cur.close() return json...
e8515f8d31de021b53c568ee01bb29aeda188e8e
3,620,372
def get_hst_to_jwst_coefficient_order(polynomial_degree): """Return array of indices that convert an aeeay of HST coefficients to JWST ordering. This assumes that the coefficient orders are as follows HST: 1, y, x, y^2, xy, x^2, y^3, xy^2, x^2y, x^3 ... (according to Cox's /grp/hst/OTA/alignment/Fo...
ceec3c2a7202ba1250f11e0d2ce3e01dc771de0f
3,620,374
from typing import List def get_categories(title: str) -> List[str]: """ Gets the categories of the wikipedia page `title` from https://en.wikipedia.org/w/api.php?action=query&format=json&titles={title}&prop=categories Returns empty list for invalid title with no redirects """ params = { ...
644eb7b110ff7e7684b8cc4dff5ca957c754941f
3,620,375
def get_chombo_box_extent(box, space_dim): """ Parse box extents from Chombo HDF5 files into low and high limits Parameters ---------- box : List Chombo HDF5 format box limits, e.g. [x_lo, y_lo, x_hi, y_hi] = [0,0,1,1] space_dim : int Number of spatial dimensions ...
d72b409a96c8a1936f456d87a341fba22ee9f97e
3,620,376
def _fast_rcnn_box_loss(box_outputs, box_targets, class_targets, normalizer=1.0, delta=1.): """Computes box regression loss.""" # delta is typically around the mean value of regression target. # for instances, the regression targets of 512x512 input with 6 anchors on # P2-P6 pyramid is a...
e408ab6068ee56af3a96be41ae894abea1a0e439
3,620,377
def calc_gcn_norm(edge_index, num_nodes, edge_weight=None): """ calculate GCN Normalization. Parameters ---------- edge_index: edge index num_nodes: number of nodes of graph edge_weight: edge weights of graph Returns ------- 1-dim Tensor "...
da1f74b1a0ad907320a6426354228d4da97df7aa
3,620,378
def get_raw_pdb_filename_from_interim_filename(interim_filename, raw_pdb_dir): """Get raw pdb filename from interim filename.""" pdb_name = interim_filename slash_tokens = pdb_name.split('/') slash_dot_tokens = slash_tokens[-1].split(".") raw_pdb_filename = raw_pdb_dir + '/' + slash_tokens[-2] + '/'...
084239659220ea65ae57a006c8ce28df73b2fd5e
3,620,379
def mae(y_true, y_pred): """Mean absolute error""" assert y_true.shape == y_pred.shape, f"{y_true.shape} != {y_pred.shape}" return np.mean(np.abs(y_true - y_pred), axis=0)
6c2a230b6a109af097cdc4fd44dadc87a6de9f5b
3,620,381
def class_tree_graph(bases, linker, context=None, **options): """ Return a `DotGraph` that graphically displays the class hierarchy for the given classes. Options: - exclude - dir: LR|RL|BT requests a left-to-right, right-to-left, or bottom-to- top, drawing. (corresponds to the dot op...
9782086a8928cdebc4f619d5bdf742b53bd8a502
3,620,382
def cg_optimize(th,floss,fgradloss,metric_length, substeps,damping,cg_iters=10, fmetric=None, num_diff_eps=1e-4,with_projection=False, use_scipy=False, fancy_damping=0,do_linesearch=True, min_lm = 0.0): """ Use CG to take one or more truncated newton steps, where a line search is used to enforce improv...
2320e3847ec88fa1d88859d610b902b99daa662e
3,620,384
def add_forth_coord(points): """forth coordinate is const = 1""" return np.hstack((points, np.ones((len(points), 1))))
09bfcd59bafd7764b78568d6496ec895dd923e31
3,620,386
def _read_reaction_gpr_from_sbml(reaction, mass_notes, f_replace): """Read the GPR information from SBMLDocument and return as a string. Warnings -------- This method is intended for internal use only. """ reaction_fbc = reaction.getPlugin("fbc") if reaction_fbc: # GPR rules ...
a9d1a91f93345c57ab91dd8f7b2eb70a2bb6e28b
3,620,388
def conv_block(x, nfeat, strides=1, name=None): """ Specific convolutional block followed by leakyrelu for unet. """ ndims = len(x.get_shape()) - 2 assert ndims in (1, 2, 3), 'ndims should be one of 1, 2, or 3. found: %d' % ndims Conv = getattr(KL, 'Conv%dD' % ndims) convolved = Conv(nfeat,...
90ed04ca5122158d609b0999db63665fa6d5121b
3,620,389
import torch def sample_from_discretized_mix_logistic(y, log_scale_min=None): """ https://github.com/fatchord/WaveRNN/blob/master/utils/distribution.py Sample from discretized mixture of logistic distributions Args: y (Tensor): B x C x T log_scale_min (float): Log scale minimum value ...
4d864be504bc0a08f58c5332785578c4c8cc551f
3,620,390
def min_dist_conformer_zma(dist_name, cnf_save_fs): """ locators for minimum energy conformer """ cnf_locs_lst = cnf_save_fs[-1].existing() cnf_zmas = [] for locs in cnf_locs_lst: zma_fs = autofile.fs.zmatrix(cnf_save_fs[-1].path(locs)) cnf_zmas.append(zma_fs[-1].file.zmatrix.read([0])) ...
6575a7ff9f1af4d971bb01580cbbf2af2f93cac9
3,620,391
def array_offset(x): """Get offset of array data from base data in bytes.""" if x.base is None: return 0 base_start = x.base.__array_interface__["data"][0] start = x.__array_interface__["data"][0] return start - base_start
b383a91790b06ffb1b5b976b9575efe637fa47a6
3,620,392
def get_kernelf(config, context={}): """Get a kernel function.""" return _from_config(config, classes=classes, context=context)
ff549e6e20f48bec1e9bda9721fdd9a0afc84003
3,620,393
import requests def layer_ogc_request(request, layername): """Provide one OGC server per layer, with their own GetCapabilities. :param layername: The layer name in Geonode. :type layername: basestring :return: The HTTPResponse with the response from QGIS Server. """ layer = get_object_or_404...
5707e3aed6223160260b2b6313d03cb98f612362
3,620,395
import torch def _demo_inputs_pair(img_shape=(64, 64), batch_size=1, cuda=False): """ Create a superset of inputs needed to run backbone. Args: img_shape (tuple): shape of the input image. batch_size (int): batch size of the input batch. cuda (bool): whether transfer input into gp...
fd0d68db73338f30de4d4dbe7939068b453981cd
3,620,396
def get_song(song_name): """Return information about a song. Parameters ---------- song_name : str The song name. Returns ------- dict name - The song name. files - Dictionary with downloaded files for this song. """ song = cache.get(song_name) if song ...
40a9752f077aeaf185d1bbc7a21f6be28658f926
3,620,397
def message_create(request, slug, topic_id, template_name='groups/message_form.html'): """ Returns a group message form. Templates: ``groups/message_form.html`` Context: form GroupMessageForm object """ group = get_object_or_404(Group, slug=slug) topic = get_object_or_40...
a0ff989c73fecbe681c167637fee35d86d3e1afd
3,620,398
def index(): """ Simple Home Page """ module_name = deployment_settings.modules[module].name_nice return dict(module_name=module_name)
5628a30596688917fdc19956f16cd7d0f68754e6
3,620,399
def player_team(replay_json): """ Returns a list of names of the players on the replay recorder's team """ own_team = get_own_team(replay_json) return [v['name'] for v in replay_json['first']['vehicles'].values() if v['team'] == own_team]
e1510fae3b5f68f22f70ac440fc509ed51c28994
3,620,400
def get_image_writer_set(): """Return the set of installed image writers. The set is returned as a dictionary where names of the image writers are the keys, and the image writer class objects are the values. """ return ImageWriterLoader().loader.get_object_set()
3d703fe96513d2b142efee71d68038df28011aee
3,620,401
import torch from typing import Tuple def convert_to_distributed_tensor(tensor: torch.Tensor) -> Tuple[torch.Tensor, str]: """ For some backends, such as NCCL, communication only works if the tensor is on the GPU. This helper function converts to the correct device and returns the tensor + original de...
71eb98868aa89bbfdea4019eff0b93256cb82025
3,620,404
def update_global_variable(): """ 修改全集变量(global关键字) :return: """ global count count = 10 return count
69c91bce24fc77dc731e05178849528e59bae4ba
3,620,405
def cancelReserve(request): """ 알림톡/친구톡 전송요청시 발급받은 접수번호(receiptNum)로 예약전송건을 취소합니다. - 예약취소는 예약전송시간 10분전까지만 가능합니다. - https://docs.popbill.com/kakao/python/api#CancelReserve """ try: # 팝빌회원 사업자번호 CorpNum = settings.testCorpNum # 예약 알림톡/친구톡 전송 접수번호 receiptNum = "0180...
63960abac51f2121a56e38b48de737c1c9c604b9
3,620,406
def _staircase_ecdf(p, data, complementary=False, q_axis="x", line_kwargs={}): """ Create a plot of an ECDF. Parameters ---------- p : bokeh.plotting.Figure instance, or None (default) If None, create a new figure. Otherwise, populate the existing figure `p`. data : array_like ...
19f8945698cfb6138c67ce025df3bcffb6463f46
3,620,407
def GenerateConfig(context): """Generates the route config""" resources = [ { 'name': context.env["name"], 'type': 'pubsub.v1.topic', 'properties': { 'topic': context.env["name"] }, 'accessControl': { 'gcpIamPolicy': MergeCallingServiceAccountWithAdminPermissionsIntoBindings(context.env, c...
53f7e44ae4f2514826d673572932f91767dd0efd
3,620,408
def get_programs(x_gw_ims_org_id, authorization, x_api_key): # noqa: E501 """Lists Programs Returns all programs that the requesting user has access to # noqa: E501 :param x_gw_ims_org_id: IMS organization ID that the request is being made under. :type x_gw_ims_org_id: str :param authorization: B...
b0907272c5539aec88d2e761a271cd08b61d7b75
3,620,409
def get_non_lib(functions): """ Get all non-library functions @param functions: List of db_DataTypes.dbFunction objects @return: a subset list of db_DataTypes.dbFunction objects that are not library functions. """ return [f for f in functions if not f.is_lib_func]
7f536ff98d647ba5e497b8550bc2497ef45e814b
3,620,410
def _check_duplicates(data, name): """Checks if `data` has duplicates. Parameters ---------- data : pd.core.series.Series name : str Name of the column (extracted from geopandas.GeoDataFrame) to check duplicates. Returns ------- bool : True if no duplicates in data. """ ...
429ce8d092b3a39fc44eeca91d593db22fe7364d
3,620,411
def path_surroundings(md, path, *, radius_pix=130, maxwidth_pix=1000, maxheight_pix=800, maxdist_pix=500, path_color=(255, 100, 0), shorten_by_rotating=True): """Create a generator of ...
a07a66d673f407f37e582d578196bb5053597aa1
3,620,412
def _has_textframe(obj): """ Check if placeholder has TextFrame """ return hasattr(obj, 'TextFrame') and hasattr(obj.TextFrame, 'TextRange')
087e6df38e55d99637e8e7ea998257f323d6d141
3,620,413
def get_mapping(combinable_list): """Determine the mapping from acceptance_id to the register id that can be used to index into an array. """ result = {} array_index = 0 while len(combinable_list) != 0: # Allways, try to combine the largest combinable set first. k ...
085f28c8d1263bc2e547a5671e115d86992af231
3,620,414
import gzip def read_sbs_from_vcf(vcf_file): """ Only reads the chrom, pos, ref and alts from the VCF file. Not strict about checking the headers, and will not filter any mutations. Lines with multiple alts will be split into one mutation for each alt. Non-single-base-substitutions (e.g. deletions...
3b669928e74fcf357c9586998ae908afec5f2008
3,620,415
def get_path(abs_url, **kwargs): """ """ if abs_url is None: return None return urlparse(abs_url, **kwargs).path
caf61367db8cf289251185c967cfb28212f61cbe
3,620,416
def clean_chamber_input(chamber): """ Turns ambiguous chamber information into tuple (int, str) with chamber id and chamber name """ if type(chamber) == str: if chamber == '1': chamber = 1 elif chamber == '2': chamber = 2 elif chamber == 'GA': chamber ...
0ad20c117fc90e523e85ef7061a548b20c68dc92
3,620,417
def search_for_letters(phrase: str = 'life, the universe, and everything', letters: str = 'forty two') -> set: """Display any 'letters' found in a 'phrase'.""" return set(letters).intersection(set(phrase))
36944391599abf971512d21819f88dee9af42f36
3,620,418
import yaml def loadyaml(file, default={}): """Utility function to load from yaml file""" try: with open(file, "r", encoding="utf-8") as f: t = yaml.load(f, Loader=yaml.FullLoader) except FileNotFoundError: t = default return t
a6720094340b71039d2e53ec1f48493480e4e26a
3,620,419
import getpass def secret(prompt=None, empty=False, default=None): """Prompt a string without echoing. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. default : float, optional Value to return if r...
45c0857e24421dd04909119b324fa6c942f4e640
3,620,422
def parse_station_list_to_csv(filepath_or_buffer) -> str: """ Return CSV-formatted data """ return _parse_station_list(filepath_or_buffer).to_csv()
c231daaf5bb343f05a959aa2cdbdf85d4f3984b0
3,620,424
import urllib def govuk_url(path): """ :returns: url to the GOV.UK Pay endpoint defined by `path` :param path: path without leading `/` e.g. `payments` """ return urllib.parse.urljoin(settings.GOVUK_PAY_URL, path)
0e0a179d3a6107f9a7f253b5a4d18f8ed3558dcd
3,620,426
def _any_sat(bdd, u, l): """ Recursive part of any_sat """ #Base Cases if u in [0,1]: return l var = _get_var_name(bdd, u) #Arbitrarily consider lower branch if bdd["t_table"][u][1] == 0: l.append("%s" % var) new_u = bdd["t_table"][u][2] else: l...
d8ed5287dff81bb51db711d2929e4810741e67e7
3,620,427
def map_mean_of_horizontal_active_links_to_node(grid, var_name, out=None): """Map the mean of active links in the x direction touching node to the node. map_mean_of_horizontal_active_links_to_node takes an array *at the links* and finds the average of all horizontal (x-direction) link neighbor values ...
b6ef9d12c9f458052473161cd79feb9476b169fd
3,620,428
def gmm_density_centered(x, std): """ Assumes dim=-1 is the component dimension and dim=-2 is feature dimension. Rest are sample dimension. """ if x.dim() == std.dim() - 1: x = x.unsqueeze(-1) elif not (x.dim() == std.dim() and x.shape[-1] == 1): raise ValueError('Last dimension must...
b050114b27ea9163cdaee61077b972bea744cf72
3,620,429
def process_pairs_vg(alns_tuple): """ Finds the pairs in alignments of one read :param alns_tuple: alignments of one read in as a tuple :return: read_id, AS pairs, mapq, metric scores """ read_id, alignments, mapqs, obs_max, end = alns_tuple return read_id, alignments, mapqs, calc_scores((re...
e1bb6cf24ba51e011b937f52586f52bc8d382cd5
3,620,430
from pathlib import Path import logging import yaml def params_from_yaml(args): """Extract the parameters for preparation from a yaml file and return a dict""" # Check the path exists try: config_file_path = Path(args.config) assert config_file_path.exists() except Exception: l...
36beadd8fa4f27471c514a963838aac216aad434
3,620,431
def get_task_monitor(node, uri): """Get a TaskMonitor for a node. :param node: an Ironic node object :param uri: the URI of a TaskMonitor :raises: RedfishConnectionError when it fails to connect to Redfish :raises: RedfishError when the TaskMonitor is not available in Redfish """ try: ...
ee69431e5c9f6711840b01150791296658920fc5
3,620,432
def get_user_ids_from_assigned_location_ids(domain, location_ids): """ Returns {user_id: [location_id, location_id, ...], ...} """ result = ( UserES() .domain(domain) .location(location_ids) .non_null('assigned_location_ids') .fields(['assigned_location_ids', '_id...
12e50ad5befece3c64e7d8172c7cfdb4751ec6de
3,620,433
def extract_sift(fn, extractor, detector): """提取图像特征""" im = cv2.imread(fn, cv2.IMREAD_GRAYSCALE) # SIFT检测器可以检测特征,而基于SIFT的提取器可以提取特征并返回它们 return extractor.compute(im, detector.detect(im))[1]
3d9997b5f57f1fd496dbedb6a327bdfa3a59915f
3,620,434
def is_operator_or_function(term): """ Checks if the term is a LaTeX mathematical operator or function. Source: http://web.ift.uib.no/Teori/KURS/WRK/TeX/symALL.html Args: term: string to be checked. Returns: True if the term is a mathematical operator, False otherwise. """ ...
b4992ffeb213979e9507cbc1b76ad1e861eef7f2
3,620,435
def getGasDensity(x=None, y=None, z=None, grid=None, ppar=None): """Calculates the gas density Parameters ---------- x : ndarray Coordinate of the cell centers in the first dimension y : ndarray Coordinate of the cell centers in the second dimension y ...
04b7a1f4b4441d06ce92b5f6b6fc09e2e614affb
3,620,436
def load_embeds(text_embed, img_embed, dcca_embed): """ Load image and sentence embeddings and create a concatenated version :param text_embed: pickle file containing the sentence embeddings :param img_embed: pickle file containing the image embeddings :param dcca_embed: pickle file containing the deep...
c74da889f05126d4ac2ace30463041d5cb9e22c3
3,620,437
import re def serialize(settings, exclude=None): """Return a consistent, human-readable string serialization of settings.""" if exclude is None: exclude = [] sdict = dict(_variables(settings)) sdict = { k: v for k, v in sdict.items() if k not in exclude } sstr = dumps(sdict, sort_keys=True...
535da5800141d6ef5ebdbeff23579a246480a271
3,620,438
from typing import List from typing import Union def list_or_first(x: List[str]) -> Union[List[str], str]: """ Returns a list if the number of elements is greater than 1 else returns the first element of that list """ return x if len(x) > 1 else x[0]
82e86001b35ecd6542a22fac3c5dd7f7723966d6
3,620,439
import re def parse_version(version_str): """'10.6' => [10, 6]""" return [int(s) for s in re.findall(r'(\d+)', version_str)]
16cfcfc292eb89b6231a266c687f9dfd8caa5a8d
3,620,440
def user(): """Get user details depending on friendship. If you are friends, sensitive data will be shown aswell. Returns: JSON reponse with the basic and sensitive user details. """ username = request.args.get('username') if username is None or username == '': username = auth...
842395d3206356f369db985abcc5de719848e7de
3,620,441
import requests def display_selected_patient_info(MRI): """ Get a patient's latest information and ECG trace image As a very important functionality of the server, the function sends a 'GET' request to the server, get a string that includes all patient's latest info and ECG image b64 string. Then ...
d0a47848451801517e9125bbd7de3b40023cbd60
3,620,442
def circ(x, y, d=1): """ Generation of a circular aperture. Args: | x (np.array[N,M]): x-grid, metres | y (np.array[N,M]): y-grid, metres | d (float): diameter in metres. | comment (string): the symbol used to comment out lines, default value is None. | delimiter (string...
7ff75431b25489db40c6d54710443c2bc4b105d1
3,620,443
from typing import Optional def labels( adata: AnnData, label_filepath: str = None, index_col: int = 0, sep: str = "\t", copy: bool = False, ) -> Optional[AnnData]: """Add label transfer results into AnnData object Parameters ---------- adata: AnnData The data object to a...
221ab6f4ed9d4eb8a189010c45205fbffc3878ab
3,620,444
def contains_common_item_2(arr1, arr2): """ loop through first array and create dictionary object where the keys are the items in the array loop through the second array and check if item in second array exists in the created dictionary """ array1_dict = {} for item in arr1: array1_dict[...
83b4eafe7904d47fd65db3fc3e5a4d598a51efea
3,620,445