content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_patron_pid(record): """Get patron_pid from existing users.""" user = get_user_by_legacy_id(record["id_crcBORROWER"]) if not user: # user was deleted, fallback to the AnonymousUser anonym = current_app.config["ILS_PATRON_ANONYMOUS_CLASS"]() patron_pid = str(anonym.id) else...
e2ba9102052c0ce84f7fc04fdc5be97a6050634c
28,200
import PySide.QtGui as QtGui import PyQt5.QtWidgets as QtWidgets def get_QGroupBox(): """QGroupBox getter.""" try: return QtGui.QGroupBox except ImportError: return QtWidgets.QGroupBox
9c0333c9c8a4fafd1c4f4f5739546aaa19a6e321
28,201
import collections def update_dict(orig_dict: dict, new_dict: collections.abc.Mapping) -> dict: """Updates exisitng dictionary with values from a new dictionory. This function mimics the dict.update() function. However, it works for nested dictionories as well. Ref: https://stackoverflow.com/questio...
e176f4cf293be67aece6e9811fe75de679bb1e94
28,202
from typing import Sequence from typing import Tuple import itertools def simulate_data( covariates: int, scales: Sequence[int], levels: Sequence[int], singletons: float, state: np.random.RandomState) -> Tuple[Array, Array, Array]: """Simulate IDs and data matrices.""" # simulate fixed effect...
c5fbddde4045b2367975b28bcfc4ded032427505
28,203
def create_strike_ingest_job_message(ingest_id, strike_id): """Creates a message to create the ingest job for a strike :param ingest_id: ID of the ingest :type ingest_id: int :param strike_id: The ID of the strike :type strike_id: int """ message = CreateIngest() message.create_inge...
47e96f6fa53cc934572852cfcaf8ed9455408dec
28,204
def create_data(nfac0, # [Number of facet 0 elements -- rows/persons] nfac1, # [Number of facet 1 elements -- columns/items] ndim, # [Number of dimensions to create] seed = None, # [<None,int,{'Fac0':<None,int,array>,'Fac1':<None,int,array>}> => generates coordinate...
d21b3a9c3172087021ba92caa74b4be95cac993c
28,205
def load_database() -> pd.DataFrame: """ Loads data from hplib_database. Returns ------- df : pd.DataFrame Content of the database """ df = pd.read_csv(cwd()+r'/hplib_database.csv') return df
5bc5ec4e8376493a9d7da9a8782c2e0f4fb8223d
28,206
import re def ensure_windows_file_path_format_encoding_as_url(path: str) -> str: """Relevant for Windows where a file path name should be "file://path/to/file.html" instead of "file://path\\to\\file.html" .""" output = path.replace("\\", "/") # Raw replace backslash with slash. # Handle exception for "f...
84e429c5d8e4b0fc2fd8976b140694f0f7c1c04e
28,207
import logging def init_logger(log_level=logging.WARNING): """Initialize logger. Args: log_level (int): logging level May be (in order of increasing verboseness): logging.CRITICAL or 50 logging.ERROR or 40 logging.WARNING or 30 logging....
7a00817378c39a6a2d13becb7ccec111d9252b45
28,208
def index(): """ index page for WebUI Returns: rendered HTML page """ data = load_messages().message_contents return render_template("index.html", data=data, encoded_data=data)
c92515fc49aacded4e9242955f6b2d5ea125897a
28,209
def psnr(x, pred_x, max_val=255): """ PSNR """ val = tf.reduce_mean(tf.image.psnr(x, pred_x, max_val=max_val)) return val
7b5d44917c88d7644e5c1694a6e6d5873c0db952
28,210
def across_series_nearest_neighbors(Ts, Ts_idx, subseq_idx, m): """ For multiple time series find, per individual time series, the subsequences closest to a query. Parameters ---------- Ts : list A list of time series for which to find the nearest neighbor subsequences that are ...
4cf3f8162b33f3b313f07160bab7e8042ce08f2b
28,211
def get_boundary_from_response(response): """ Parses the response header and returns the boundary. :param response: response containing the header that contains the boundary :return: a binary string of the boundary """ # Read only the first value with key 'content-type' (duplicate keys are allowed)...
66a0112598b2210cca1a2210f6af963dfee641f7
28,212
import logging import json def get_message(message): """{ 'pattern': None, 'type': 'subscribe', 'channel': 'my-second-channel', 'data': 1L, }""" if not message: return logging.info('MSG: %s', message) data = message.get('data', {}) return json.loads(dat...
2e79ed94fbfc3fba122e8bd8663e33b124d4d2b6
28,213
def parent_node(selector): """ Finds the parent_node of the given selector. """ if not get_instance(): raise Exception("You need to start a browser first with open_browser()") return parent_node_g(get_instance(), selector)
0d6136aa5262a4b4482166108715b3323328983b
28,214
def getPairCategory(rollSorted): """ Converts a roll's ordered list of frequencies to the pairwise hand category. """ if rollSorted[0] == 6: return "six-of-a-kind" elif rollSorted[0] == 5: return "five-of-a-kind" elif rollSorted[0] == 4 and rollSorted[1] == 2: retur...
1c48abd8d0c1a27a50ce587857852a95e8949e74
28,215
def allocz(size): """Alloc zeros with range""" return [0 for _ in range(size)]
21670a20ea045ee7f2cf0780a011f89f917b7180
28,216
def uint_to_little_endian_bytearray(number, size): """Converts an unsigned interger to a little endian bytearray. Arguments: number -- the number to convert size -- the length of the target bytearray """ if number > (2 ** (8 * size) - 1): raise ValueError("Integer overflow") nle = [...
bd3314fedf0accbc0d15b1bb146f54f52cb3bce1
28,217
import re def to_alu_hlu_map(input_str): """Converter for alu hlu map Convert following input into a alu -> hlu map: Sample input: ``` HLU Number ALU Number ---------- ---------- 0 12 1 23 ``` ALU stands for array LUN number ...
8e211b7efa3f8dd23c042f046d881daf987062bc
28,218
def debug(func): """Decorator to debug a function's inputs and outputs. Uses the built-in 'logging' module.\n Inputs are logged via `decorate.debug.debug_input`, and follow the format: \n `'Datetime' | ['action'] 'function' | args=(args,) | kwargs={kwargs:values}` Logged input example: `2021...
c6d7b84f401a469afafaeda64c4be2a34542da67
28,219
import copy def randomize(jet): """build a random tree""" jet = copy.deepcopy(jet) leaves = np.where(jet["tree"][:, 0] == -1)[0] nodes = [n for n in leaves] content = [jet["content"][n] for n in nodes] nodes = range(len(nodes)) tree = [[-1, -1] for n in nodes] pool = [n for n in node...
d4e8d12f8701d140e965e773e9a2542b133d8535
28,220
import subprocess def run_command(command): """ Run command """ try: res = subprocess.run( command, capture_output=True, text=True, check=True, shell=True, ) out = res.stdout except subprocess.CalledProcessError as exc: out = exc.output, exc.stderr, exc.returncode ...
1807e42893c7f6ba6bdc52849bb69221a9d4be89
28,221
from typing import Optional def get_vt_retrohunt_files(vt_key: str, r_id: str, limit: Optional[int] = 100): """Retrieve file objects related to a retrohunt from VT.""" url = f"https://www.virustotal.com/api/v3/intelligence/retrohunt_jobs/{r_id}/matching_files?limit={limit}" data = vt_request(api_key=vt_k...
f29cdd1db8fc1b0559a49422df24a16e4708b493
28,222
import math def proj_make_3dinput_v2(project, angle = 15, start_slice = [0,0,0], crop_slice = [0.75, 0.625, 0.625]): """ This function unprojects 2d data into 3d voxel at different angles/views and do crop. :param project: 2d image input :param angle: the angle of different view. set max(1) as 0. ...
3867cd03cc9c7833a29c9f5d4d078b5caabe2b73
28,223
from ch07.digraph_search import topological_sort as ts def topological_sort(digraph): """Link in with Topological sort.""" return ts(digraph)
bb16ca7c44adf37893d47cfacd7d81ae0d646af6
28,224
def merge_scores(scores_test, scores_val): """ Aggregate scores """ scores_valtest = {} for key in scores_test: key_valtest = "final/" + key.split("/")[1] if key.startswith("test/"): keyval = "val/" + key.split("/")[1] value = 0.5 * (scores_test[key]["value"] ...
be0dded69367e7554c0cc2632946d46954a3cc15
28,225
import os def extract_data_frame_from_file(data_path, filename): """ :param data_path: path of source file directory :param filename: source file name :return: pandas dataframe with file content """ file_path = os.path.join(data_path, filename) return pd.read_csv(file_path, skiprows=1, sep...
68ab293638b40488181c908822ca50eda55731c6
28,226
def validateDate(data, name, published): """ Verify that a date string is valid. """ # Verify that if published exists it's a valid date date = parse_datetime(published) if not date: raise InvalidField(name, published) return published
d8a46a491f54cc571f2560a816d76c93a8af79cf
28,227
def debug_error_message(msg): """Returns the error message `msg` if config.DEBUG is True otherwise returns `None` which will cause Werkzeug to provide a generic error message :param msg: The error message to return if config.DEBUG is True .. versionadded: 0.0.9 """ if getattr(config, "DEBU...
7f58f62d5891f7eacc1a6326b2c64ea1ce5862fe
28,228
def join( group_id: int, db: Session = Depends(get_db), user: UserModel = Depends(get_active_user), ): """Join the group.""" return service.join(db, group_id=group_id, user_id=user.id)
cc3d329b36d04047030e8af4e2c0d0511605aa49
28,229
def calc_correlation(cs, lab): """ calc the spearman's correlation :param cs: :param lab: :return: """ rho, pval = spearmanr(cs, lab) return rho
a1768394ab94d8833cbbbd6eb32d927285bac4b8
28,230
def normalize(df): """Pandas df normalisation Parameters: df (pd df) : input df Returns: result (pd df) : output df """ result = df.copy() for feature_name in df.columns: max_value = df[feature_name].max() min_value = df[feature_name].min() result[feat...
2fc05fc9ef7642ac4b84cb6ed567ec64c1da0836
28,231
def cbv_decorator(decorator): """ Turns a normal view decorator into a class-based-view decorator. Usage: @cbv_decorator(login_required) class MyClassBasedView(View): pass """ def _decorator(cls): cls.dispatch = method_decorator(decorator)(cls.dispatch) retu...
9811cc05bcf31cb5145cc0a4f089e40433446023
28,232
def _shift_anchors(anchors, direction): """Shift anchors to the specified direction """ new_anchors = deepcopy(anchors) if direction == 'center': pass elif direction == 'top': heights = new_anchors[:,3] - new_anchors[:,1] + 1 heights = heights[:,np.newaxis] new_ancho...
fbf48649c846bbb7275cb2a773f637f9bc7023f3
28,233
import itertools def enumerate_all_features(dim: int, num_values: int) -> chex.Array: """Helper function to create all categorical features.""" features = jnp.array(list(itertools.product(range(num_values), repeat=dim))) chex.assert_shape(features, [num_values ** dim, dim]) return features.astype(jnp.int32)
049178afae402a3c73fa3a547afc8be1640efd62
28,234
def convert_pad_shape(pad_shape): """ Used to get arguments for F.pad """ l = pad_shape[::-1] pad_shape = [item for sublist in l for item in sublist] return pad_shape
39e77b3931f29f3ab95a75662187e09df545364f
28,235
def PotentialWalk(pos, tree, softening=0, no=-1, theta=0.7): """Returns the gravitational potential at position x by performing the Barnes-Hut treewalk using the provided octree instance Arguments: pos - (3,) array containing position of interest tree - octree object storing the tree structure ...
6b03d5075df752bd5c7986da76ce8fc7c28ce10c
28,236
import re def GetProjectUserEmail(git_repo): """Get the email configured for the project.""" output = RunGit(git_repo, ['var', 'GIT_COMMITTER_IDENT']).output m = re.search(r'<([^>]*)>', output.strip()) return m.group(1) if m else None
2749a7797b4ef9c2d7532f31e8b8594f0cc9c174
28,237
from typing import Tuple def decode_features(features_ext, resource_attr_range: Tuple[int, int]): """ Given matrix of features from extended configs, corresponding to `ExtendedConfiguration`, split into feature matrix from normal configs and resource values. :param features_ext: Matrix of feature...
ffb709a8ef7f7da91a7b4b99c80b2f32ff66b66e
28,238
def get_event(): """ Get the event information of the group :param room_id: the room_id of the group """ incoming = request.get_json() event = Event.get_event_with_room_id(incoming['room_id']) if event: results = {'event_name': event.name, 'location': event.location, 'start_time'...
d6f9c581b563d3231ef9d40de557eee323025e4b
28,239
import os def copy_decompress(source_fn): """Generate bash code to copy/decompress file to $TMPDIR. """ new_fn = os.path.basename(source_fn) if source_fn.lower().endswith(".gz"): new_fn = new_fn.strip(".gz") cmd = "gunzip -C {source_fn} > $TMPDIR/{new_fn}" elif source_fn.lower().en...
7b65e66f240e2e86b70c963e7f0d90381656210e
28,240
def test(model,X, y): """ Predicts given X dataset with given model Returns mse score between predicted output and ground truth output Parameters ---------- X: Test dataset with k features y: Ground truth of X with k features """ return mse(model.predict(X).flatten...
5e27125def948478b98eac997009de29a44a64a9
28,241
def solver(objectives): """Returns a solver for the given objective(s). Either a single objective or a list of objectives can be provided. The result is either an IKSolver or a GeneralizedIKSolver corresponding to the given objective(s). (see klampt.robotsim.IKSolver and klampt.robotsim.Gener...
685bed37629c57a7041f3cdcee0d98c3c93b1d77
28,242
def model_fn_builder(config: NeatConfig): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): """The `model_fn` for TPUEstimator.""" tf.logging.info("*** Features ***") for name in sorted(features.keys()): tf.logging.info(" name...
572ceb93e9907e1bb960e3c66f34c14e8bacce7c
28,243
def solve_case(rectangle, tree, io_obj): """ Main program to recursively fill a rectangle with pentominos """ return tuple(map(_solve_rect_with_x(rectangle)(tree)([ len(rectangle) // 2, len(rectangle) % 2, len(rectangle[0]) // 2, len(rectangle[0]) % 2])(io_obj), tupl...
4afa8b6a1e723e5900d14ec252a131086b1b15f1
28,244
def keras_weights_to_caffemodel(keras_model): """ Only Implement the conv layer and fc layer :param keras_model: :return: """ net = caffe.Net() layers = keras_model.layers for layer in layers: if type(layer) == keras.layers.Convolution2D: w, b = layer.get_weights() ...
088c5040e3c3cba962d4fee7caee74761f9dbb21
28,245
def get_db(): """ :return: """ db = getattr(g, "_database", None) if db is None: db = g._database = connect() db.row_factory = make_dicts return db
d462dd6d82ce1c5f13ab5acfc3f613c4d9bdba33
28,246
import scipy def interpolate(X, Y, Z, x_coords, y_coords, factor=4, method='cubic'): """ :return: Interpolated X, Y, Z coordinate tuples, given by a factor, and a method in `scipy.interpolate.griddata` """ X_f, Y_f, Z_f = X.flatten(), Y.flatten(), Z.flatten() x_inter = scale(x_coords, fact...
6520fb7a9e1c7b25a3030d97ad9a43253fd7b976
28,247
def weighted_rmsd(x, y, weights=None, dim=None, apply_nan_mask=True): """ Compute weighted root-mean-square-deviation between two `xarray.DataArray` objects. Parameters ---------- x, y : `xarray.DataArray` objects xarray objects for which to compute `weighted_rmsd`. weights : array_like, ...
da975ff48dcdee1a7f2c44a58d171d7c4579e553
28,248
def _default_value(argument, default): """Returns ``default`` if ``argument`` is ``None``""" if argument is None: return default else: return argument
52eed8ddaf3c52adba69044cc462fc11279670c5
28,249
def setup(opp, config): """Set up the w800rf32 component.""" # Declare the Handle event def handle_receive(event): """Handle received messages from w800rf32 gateway.""" # Log event if not event.device: return _LOGGER.debug("Receive W800rf32 event in handle_receiv...
9604e79c23baf155d36568cd32f86507747e78c3
28,250
def all_feature_functions(): """ Returns all feature functions from the function module :rtype list[callable] :returns List of feature functions """ exclude = ['n_gram_frequency', 'term_frequency'] functions = [] for name in dir(features): feature_function = getattr(features, nam...
3e2fb73def3791a64d1e3868bf5c7188d593e3cf
28,251
def unsupplied_buses(net, mg=None, slacks=None, respect_switches=True): """ Finds buses, that are not connected to an external grid. INPUT: **net** (pandapowerNet) - variable that contains a pandapower network OPTIONAL: **mg** (NetworkX graph) - NetworkX Graph or MultiGraph that rep...
e8f7da1735ab56ad5a4ffd9b4ef27088b7e89fd1
28,252
import os import time def last_check(): """Return the date of the last check""" cache = cache_file() if cache: return os.path.getmtime(cache_file()) # Fallback return time.time()
31badaf58b708a6318f20d8d6aad18e86aedbec4
28,253
def is_constant_type(expression_type): """Returns True if expression_type is inhabited by a single value.""" return (expression_type.integer.modulus == "infinity" or expression_type.boolean.HasField("value") or expression_type.enumeration.HasField("value"))
66a3237971299df3c7370f039d87a8b5f4ae2be5
28,254
def compute_tuning_improvement_sds_5_4(): """Compute average improvement during tuning, in sds""" data = _get_tuning_results_df() delta = data['delta'].dropna() result = delta.mean() fn = OUTPUT_DIR.joinpath('5_4_tuning_improvement_sds.txt') with fn.open('w') as f: f.write( ...
b1adc3c2c7f2dd22217ec4be63d8e6c49d5827bc
28,255
def make_grid(batch_imgs, n_rows): """Makes grid of images.""" batch_imgs = np.array(batch_imgs) assert len(batch_imgs.shape) == 4, f'Invalid shape {batch_imgs.shape}' batchsize, height, width, channels = batch_imgs.shape n_cols = (batchsize + n_rows - 1) // n_rows grid = np.zeros((n_rows * height, n_cols...
6da67c75407df6ff1a4b85e5a2c0aa6992a6ffe6
28,256
import random def getTypes(parasites): """Take parasites and assign a type to them -- like in pokemon! Then return the list of parasites.""" bugsOut = [] for i in range(len(parasites)): bugsOut.append([i+1, parasites[i], random.choice(["fire", "water", "grass"])]) r...
905466f92349d97f8fe7c3b7c446327cd52216df
28,257
def jsonUsers(request): """Export user list to JSON""" user_list = list(CustomUser.objects.values()) return JsonResponse(user_list, safe=False)
625669fd38730b9fd759812b11904e5aef3bf76e
28,258
def farthest_point_sample(points, num_points=1024): """ Input: points: a point set, in the format of NxM, where N is the number of points, and M is the point dimension num_points: required number of sampled points """ def compute_dist(centroid, points): return np.sum((centroid - ...
a96ace38c6d2a18cc247e2131fc095eeccca1a84
28,259
def resolve_shx_font_name(font_name: str) -> str: """ Map SHX font names to TTF file names. e.g. 'TXT' -> 'txt_____.ttf' """ # Map SHX fonts to True Type Fonts: font_upper = font_name.upper() if font_upper in SHX_FONTS: font_name = SHX_FONTS[font_upper] return font_name
013e944160f7fc71849e3e7f6869620a1fd6a328
28,260
def select_event_by_name(session, event_name): """ Get an event by name Parameters ---------- session : database connexion session event_name : str name of the RAMP event Returns ------- `Event` instance """ event = session.query(Event).filter(Event.name ==...
779bf47b812fdc920ff4359f4766a63689ced195
28,261
import torch def attention_mask_creator(input_ids): """Provide the attention mask list of lists: 0 only for [PAD] tokens (index 0) Returns torch tensor""" attention_masks = [] for sent in input_ids: segments_ids = [int(t > 0) for t in sent] attention_masks.append(segments_ids) retu...
06a5880069cdc88ea33fe987bf4ac77aceef13eb
28,262
def extension_from_parameters(): """Construct string for saving model with annotation of parameters""" ext = '' ext += '.A={}'.format(ACTIVATION) ext += '.B={}'.format(BATCH_SIZE) ext += '.D={}'.format(DROP) ext += '.E={}'.format(NB_EPOCH) if FEATURE_SUBSAMPLE: ext += '.F={}'.format(...
009bd3dd0b105cbbd060ced37776e011487be415
28,263
import time import six from re import S def gen_image_coeff(filter_or_bp, pupil=None, mask=None, module='A', coeff=None, coeff_hdr=None, sp_norm=None, nwaves=None, fov_pix=11, oversample=4, return_oversample=False, use_sp_waveset=False, **kwargs): """Generate PSF Create an image (direct, coronagr...
38d1ed576adbb49a32fb200c7b3346b04e7d7b36
28,264
def rotateBoard90(b): """b is a 64-bit score4 board consists of 4 layers Return: a 90 degree rotated board as follow (looking from above) C D E F 0 4 8 C 8 9 A B ==> 1 5 9 D 4 5 6 7 2 6 A E 0 1 2 3 3 7 B F """ return rotateLayer90(b & 0xFFFF) \ | rota...
d4069e8f7953abdcf56fc9bc713da69e33f1fdbe
28,265
def register_preset_path(path): """Add filepath to registered presets :param path: the directory of the preset file(s) :type path: str :return: """ if path in _registered_paths: return log.warning("Path already registered: %s", path) _registered_paths.append(path) return path
231d151c0b01e13312539ad592faa9f01acdce42
28,266
def set_pause_orchestration( self, ne_pk_list: list[str], ) -> bool: """Set appliances to pause orchestration .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - pauseOrchestration - POST - /pauseOrchestration ...
72ebb32a6bc1bef1faf09f646dfad90a9b29da32
28,267
def unwrap(value: str, wrap_char: str) -> str: """Unwraps a given string from a character or string. :param value: the string to be unwrapped :param wrap_char: the character or string used to unwrap :return: unwrapped string or the original string if it is not quoted properly with the w...
d1c1aceb0c92e0ccda26f6444eea5056c56d5d44
28,268
def round_to_memory_units(memory_bytes, round_up): """Round bytes to the nearest memory unit.""" return from_memory_units(to_memory_units(memory_bytes, round_up))
9402592d20832dd3149e8b9bc14115711aeee51a
28,269
import os import zipfile from datetime import datetime import time def get_modification_time(input_dir_or_zip): """Get time of most recent content modification as seconds since the epoch.""" path = 'routes.txt' if os.path.isdir(input_dir_or_zip): return int(os.stat(os.path.join(input_dir_or_zip, p...
53ff7763897e046d36db28b668fe6c33607fe69b
28,270
import gettext import types def clone(translation): """ Clones the given translation, creating an independent copy. """ clone = gettext.GNUTranslations() clone._catalog = translation._catalog.copy() if hasattr(translation, 'plural'): clone.plural = types.FunctionType( translation.p...
269756db03954d7b6539e941fe07db532e81b17d
28,271
def get_general_channel(): """Returns just the general channel of the workspace""" channels = get_all_channels() for channel in channels: if (channel['is_general']): return channel
f350c87a57dc54580729a29b456e25d5b0c6797f
28,272
def nonrigid_rotations(spc_mod_dct_i): """ Determine if the rotational partition function for a certain species should be calculated according to some non-rigid model. This determination solely relies on whether has specified the use of a non-rigid model for the species. :param spc...
5ef94d4dc1b267ffab6bb654d58aae592b69d367
28,273
def general_standing(): """ It gives the general standing based on the current matchday. Note that it depends on the parameters that are imported at the beginning of the notebook, specifically Results, hence in order to refresh it needs to be run after Results is created from the utilities script. T...
2a5f48a34209ff9568b9c4afb447df4eac944391
28,274
def pixwt(xc, yc, r, x, y): """ ; --------------------------------------------------------------------------- ; FUNCTION Pixwt( xc, yc, r, x, y ) ; ; Compute the fraction of a unit pixel that is interior to a circle. ; The circle has a radius r and is centered at (xc, yc). The center of ; t...
35e8937456fa1a4c8ca251ff55449001c6f64859
28,275
def predict(net, inputs, use_GPU=False, in_type='numpy'): """Make predictions using a well-trained network. Parameters ---------- inputs : numpy array or torch tensor The inputs of the network. use_GPU : bool If True, calculate using GPU, otherwise, calculate using CPU. ...
4a07a8171024fe50f56a94a416f4745f8db01759
28,276
import os def tag_from_ci_env_vars(ci_name, pull_request_var, branch_var, commit_var): """ Checks if the CI environmental variables to check for a pull request, commit id and band commit branch are present. :return: String with the CI build information, or None if the CI environmental var...
73a4f5dda860edf1748b5abf833c73914075d0da
28,277
import os import requests def load_model() -> modellib.MaskRCNN: """ This function loads the segmentation model and returns it. The weights are downloaded if necessary. Returns: modellib.MaskRCNN: MRCNN model with trained weights """ # Define directory with trained model weights r...
bbbe02b268bce94df0761b9a5ae952282183e734
28,278
def svn_mergeinfo_catalog_merge(*args): """ svn_mergeinfo_catalog_merge(svn_mergeinfo_catalog_t mergeinfo_catalog, svn_mergeinfo_catalog_t changes_catalog, apr_pool_t result_pool, apr_pool_t scratch_pool) -> svn_error_t """ return _core.svn_mergeinfo_catalog_merge(*args)
dd79ece86fab697b519f4ec2b5b294e085701364
28,279
import numpy def normalize_const(v): """ Normalize a numpy array of floats or doubles. """ return v / numpy.linalg.norm(v)
927ad9d2d94735263ac10a445f4f7fe4b3150c95
28,280
import re def _decode_block_str(block_str): """ Decode block definition string Gets a list of block arg (dicts) through a string notation of arguments. E.g. ir_r2_k3_s2_e1_i32_o16_se0.25_noskip All args can exist in any order with the exception of the leading string which is assumed to indicate ...
271b8c11ea100a7b86cd4ee958ed13d8c19ab3ac
28,281
import collections def make_lc_resolver(type_: type[_T], /) -> collections.Callable[..., collections.Awaitable[_T]]: """Make an injected callback which resolves a LazyConstant. Notes ----- * This is internally used by `inject_lc`. * For this to work, a `LazyConstant` must've been set as a type ...
30190cfb0f74eab96bafabfc55ef63d18ea25a0f
28,282
import hashlib def get_md5(string): """ Get md5 according to the string """ byte_string = string.encode("utf-8") md5 = hashlib.md5() md5.update(byte_string) result = md5.hexdigest() return result
968b8f8ec28720e4ed4d020093f815b6af33eea7
28,283
def clean_docs_and_uniquify(docs): """ normalize docs and uniquify the doc :param docs: :return: """ docs = [normalize(t) for t in docs if isinstance(t, str)] docs = dedupe(docs) return docs
6a267c1b5b6744cf28b2b6c73e6cf49f25f95727
28,284
from typing import Any import torch def shard_init_helper_(init_method, tensor: Tensor, **kwargs: Any) -> None: """ Helper function to initialize shard parameters. """ if hasattr(tensor, _PARALLEL_DIM): local_rank = get_rank() group = get_group() world_size = get_world_size() ...
df692b2766ed49d3358c72450aa5d4159915e4b5
28,285
def segment_zentf_tiling(image2d, model, tilesize=1024, classlabel=1, overlap_factor=1): """Segment a singe [X, Y] 2D image using a pretrained segmentation model from the ZEN. The out will be a binary mask from the prediction of ZEN ...
7f88124b86bfe6bde147aeedd9385ea7b19063e3
28,286
import os def setup_train_and_sub_df(path): """ Sets up the training and sample submission DataFrame. Args: path (str): Base diretory where train.csv and sample_submission.csv are located Returns: tuple of: train (pd.DataFrame): The prepared training dataframe with the extr...
25dae06b76aa395c46d126d44129f7f75fc4a622
28,287
def key2cas(key): """ Find the CAS Registry Number of a chemical substance using an IUPAC InChIKey :param key - a valid InChIKey """ if _validkey(key): hits = query('InChIKey=' + key, True) if hits: if len(hits) == 1: return hits[0]['rn'] else:...
d0919e2e6c1b6b149409e2b6333bcd3129c53379
28,288
import time import re def connect_server(server, username, startpage, sleep_func=time.sleep, tracktype='recenttracks'): """ Connect to server and get a XML page.""" if server == "libre.fm": baseurl = 'http://alpha.libre.fm/2.0/?' urlvars = dict(method='user.get%s' % tracktype, ...
694bfa6b1ace0ed51338983b4901f06c78f44afd
28,289
def eigenvalue_nonunitary_diamondnorm(A, B, mxBasis): """ Eigenvalue nonunitary diamond distance between A and B """ d2 = A.shape[0] evA = _np.linalg.eigvals(A) evB = _np.linalg.eigvals(B) return (d2 - 1.0) / d2 * _np.max(_tools.minweight_match(evA, evB, lambda x, y: abs(abs(x) - abs(y)), ...
97716d88829e4bf0beef914f38bd40d24c1fc32a
28,290
def str_to_int(value): """Convert str to int if possible Args: value(str): string to convert Returns: int: converted value. str otherwise """ try: return int(value) except ValueError: return value
30bd55fc34abffa67c79117b0941ba7e6388efeb
28,291
import json def json_response(data): """this function is used for ajax def route(request): return json_response(t.json()) """ header = 'HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n' body = json.dumps(data, ensure_ascii=False, indent=8) r = header + '\r\n' + body return r....
8678a8f62fab10d9120d354889387b6d70cddea9
28,292
from operator import sub from operator import add def linePointXY(l,p,inside=True,distance=False,params=False): """ For a point ``p`` and a line ``l`` that lie in the same XY plane, compute the point on ``l`` that is closest to ``p``, and return that point. If ``inside`` is true, then return the clos...
b91f1497ba2dffb72caa4cbf4a6f43972ee3853e
28,293
def config_port_type(dut, interface, stp_type="rpvst", port_type="edge", no_form=False, cli_type="klish"): """ API to config/unconfig the port type in RPVST :param dut: :param port_type: :param no_form: :return: """ commands = list() command = "spanning-tree port type {}".format(port...
a0a8672b3fea945a57367236debd1a420e270185
28,294
from os import path def compute_output_pattern(mask_path, crop_output): """ Computes the output pattern of the region cropped (without the source file prefix) Args: mask_path: path to the masks crop_output: If True the output is cropped, and the descriptor CropRoi must exist Returns: ...
2f8fa42b7c3efeb753eed9545beec87638a9dfdc
28,295
def check_strand(strand): """ Check the strand format. Return error message if the format is not as expected. """ if (strand != '-' and strand != '+'): return "Strand is not in the expected format (+ or -)"
9c2e720069ad8dcc8f867a37925f6e27e91dcb3f
28,296
def to_halfpi(rin, za): # match with a shunt input l net, rin > za.real """ """ ra, xa = za.real, za.imag xd = np.sqrt(ra * (rin - ra)) if np.iscomplex(xd): raise ValueError x2 = np.array([-xa - xd, -xa + xd]) x1 = -(ra**2 + (x2 + xa)**2) / (x2 + xa) return np.transpose([x1 * 1j, x2...
210e4bb008cd58323fab1ab66ad6ef84456c569b
28,297
from pathlib import Path import yaml def load_config_or_exit(workdir="."): """Loads the challenge configuration file from the current directory, or prints a message and exits the script if it doesn't exist. Returns: dict: The config """ path = Path(workdir) if (path / "challenge.yml").exi...
e58a7725422d3ae053ab56ae81ab98a7d13be0b5
28,298
def checkOnes(x, y): """ Checks if any of the factors in y = 1 """ _ = BranchingValues() _.x = 1 for i in _range(len(y)): if _if(y[i][0] == 1): _.x = 0 _endif() if _if(y[i][1] == 1): _.x = 0 _endif() _endfor() return _.x
fec6b2aeae13750ec1b37d4b5d187d6836ab5aaa
28,299