content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def rand_population_uniform(m, a, b): """ Creates a starting population of size `m` using a uniform random distribution, where `a` is the lower bound, and `b` is the upper bound for the design variables. """ a = np.array(a) b = np.array(b) d = len(a) return [list(np.multiply(a + np.r...
576c2d77591356615347f3b119660b673e0f5453
59,058
from typing import Union from typing import Tuple def prepare_data( data: np.ndarray, lookback_steps: int, num_inputs: int = None, num_outputs: int = None, input_steps: int = 1, forecast_step: int = 0, forecast_len: int = 1, known_future_inputs: bool = F...
390f045a0bd9c423d261277028cfa2228abe00fe
59,059
def najnowsze(request): """ List the newest offers """ oferty = OfertyEst.objects.filter(status=0).select_related() oferty = oferty.order_by('-data', '-id')[:10] paginator = Paginator(oferty, 10) page = request.GET.get('page') try: oferty = paginator.page(page) except Page...
b3f4b671344a423f27e0d7b32808993495756558
59,061
import base64 import zlib def decompress_data(content_data): """ Handles the actual decompression of Base64 data. Args: content_data: String of Base64 content Returns: content_data: Decompressed content of ASCII printable """ decoded = base64.b64decode(content_data) # IO...
fd93747ec3bf7759e385eba7397c6b9ad22ccd7f
59,062
def get_module_class(module_name, hetero=False): """Retrieve the module classes from the module name.""" # List all the modules and their string name in this dictionary module_dict = { 'pointnet': [PointNet, PointNetHetero], # pointnet 'mlpdecoder': [MlpDecoder, MlpDecoderHetero], # mlpdeco...
4a0c593086de6325aee8042d292dd8b862ce6875
59,063
def generate_election_partial_key_challenge( backup: ElectionPartialKeyBackup, polynomial: ElectionPolynomial, ) -> ElectionPartialKeyChallenge: """ Generate challenge to a previous verification of a partial key backup :param backup: Election partial key backup in question :param poynomial: Polynomi...
4069ccb1ed90b39804a5c5fa78563f8d8b44681e
59,065
from datetime import datetime import json def bplist_write_bplist_to_json(bplist_file_path, to_file_path): """ Reads a bplist file and writes it to a json file. Args: bplist_file_path (str): to_file_path (str): """ def _convert_datetime(o): if isinstance(o, datetime): ...
e8fd57ea660a5ed0313e7d429736c6e13c362af0
59,066
import numpy def stEnergyEntropy(frame, n_short_blocks=10): """Computes entropy of energy""" Eol = numpy.sum(frame ** 2) # total frame energy L = len(frame) sub_win_len = int(numpy.floor(L / n_short_blocks)) if L != sub_win_len * n_short_blocks: frame = frame[0:sub_win_len * n_short...
aad28aef8871246aa8c369fa786b0669e69da546
59,067
def patch_url(options): """Returns a Review Board or a GitHub URL for a patch.""" if options['review_id']: # Reviewboard REST API expects '/' at the end of the URL. return '{base}/{review}/diff/raw/'.format( base=REVIEWBOARD_REVIEW_URL, review=options['review_id']) el...
fbd1b37e087738bf1b895ee0dd1e3c51d48b7037
59,068
def _gaussian_log_cdf(x, mu, sigma): """Log CDF of a normal distribution.""" if not isinstance(x, chainer.Variable): x = chainer.Variable(x) return _log_ndtr((x - mu) / sigma)
dc82b95cb61c17ae40a565d26279dd3d6c1987cf
59,070
from typing import Dict import yaml def load_yaml(filepath: str) -> Dict: """ Read content from yaml file. :param filepath: str path to yaml file. :return: dict YAML content """ with open(filepath, "r") as f: try: return yaml.safe_load(f) except yaml.YAMLError as ...
37dfcc6fa463174059414fe93efe891389be2f22
59,071
import csv import logging def load_patterns(file_path): """ loads the patterns from csv file """ patternsDict = {} try: with open(file_path, mode='r') as csvfile: reader = csv.reader(csvfile) patternsDict = {rows[0]: (rows[1], rows[2]) for rows in reader} except...
330472f0507ffc4e9d967ef3027e362e47e0d4d2
59,072
def calculate_AUC(x, y): """ Simple function to calculate AUC of an ROC curve, given a set of points (x,y) Parameters ---------- x: list The x coordinates of the points of the ROC curve. y: list The y coordinates of the points of the ROC curve. Returns ------- ...
ba890f3348c9e5aa7b20e643b6369bdc16d7fe5c
59,073
from typing import List def get_personnel_list( personnel_file: str = CONFIG['input_personnel_list_path'], ) -> List[str]: """Get Personnel list Args: personnel_file (str): Path to '\n' delimited text file containing list of personnel. Returns: int: Number of rows """ ...
54259fd73542478eb9808bb8af9023e819cde56b
59,075
import requests def sf_put(path='', token=None, data=None): """ Sends a PUTS to PetSafe SmartFeed API. Example: sf_put(path='feeders', token=user_token, data=my_data) :param path: the path on the API :param token: the account's token :param data: the PUT data :return: the request respons...
9ae31119cd2422314939760c8fda1b6a18ca05d2
59,076
def read_params_Coulomb(fname='in.params.Coulomb'): """ Read in.params.Coulomb. But only for fixed or fixed_bvs charges. """ with open(fname,'r') as f: lines = f.readlines() mode = None chgtype = None chgs = {} coul = {} bvs = {} for line in lines: if line[0] in ...
a870d1a7b504fdbbc87f09db758bfd11b770be63
59,078
def get_programs_by_type_slug(site, program_type_slug): """ Keyword Arguments: site (Site): The corresponding Site object to fetch programs for. program_type_slug (string): The type slug that matching programs must have. Returns: A list of programs for the given site with the given ...
7a3b697718f081a1d55c74e70de401829dfd42c6
59,080
def timeshifted_data_2d(data, shift, padding_value='zero'): """ Same as timeshifted_data_1d but with a 2D array as input. In other words, performs shifting of multiple data vectors (e.g. multiple voxel timeseries). Inputs data: 2D numpy array, with shape (n, v), where n is the length of a...
e877933870d19eff3d1f3697a42b6c2e36fd600a
59,081
def dice_from_confusion_matrix(cm: ndarray) -> ndarray: """ Computes Dice scores from a confusion matrix Parameters ---------- cm N x N Input confusion matrix Returns ------- 1d ndarray containing Dice scores for all N classes """ if cm.ndim != 2 or cm.shape[0] != cm.s...
6c2b256166fb9eb54d02bbcc013eeafd5e49255f
59,083
def find_attribute_helpers(attr_type, name, custom_formatter): """ Tries to format following the OIDs info and format_helper specification. Search for attribute oid, then attribute name (can be multiple), then attribute syntax Precedence is: 1. attribute name 2. attribute oid(from schema) 3....
d98c08bf40275131f24395566a62d1ac5e80e2ca
59,085
def getValidationHandlers(template, cohort_start_year, val_feature_start, val_feature_end, cohort_name, engine): """ Queries database for active handlers within the given train/test dates. :param template: string, SQL template from config file :param cohort_start_year: starting year for cohort :para...
ad4b4171d6d4f2bdb25decd0dd8da02a77786f84
59,086
def integrate_dopri5(dydt, t, y0, *args): """ Integrate an ODE system with the Runge-Kutte Dormand Prince method (with step-size control). Parameters ---------- dydt : function A function returning the momenta of the ODE system. t : numpy.ndarray of float Array of time point...
b9db428a04bb8d03c294fa2cf9562aeeda265e87
59,087
import json def mac_entry_info_get(client, vlan_name, port, peer_mac_addr): """based on the input information,found any mac entry is matched. :returns: True if one entry is matched """ status = False # show ethernet-switching table interface xxx command = 'exec cli show ethernet-switching tabl...
d8e01b4aa60741c355d80125d87b0a1ae02ee6f6
59,088
from typing import Optional from typing import Dict from typing import Any def render_packager_template(template_name: str, values: Optional[Dict[str, Any]] = None) -> str: """ Helper function to read template from a file and render it :param template_name: name of a rest packager template :param val...
ae778e7c82616fd85e0cb1c0b71a27e5d74f11bf
59,089
def read_datafiles(): """Returns lines from files in current directory. Exits with error message if it encounters: * file that has an invalid name * file that is not UTF8-encoded * file that has blank lines.""" visiblefiles_list = get_visible_filenames() all_datalines = [] for datafile ...
2a30029a453069c53add23c5d3f55799a95e638b
59,090
def _calculate_normals(rr, tris): """Efficiently compute vertex normals for triangulated surface""" # ensure highest precision for our summation/vectorization "trick" rr = rr.astype(np.float64) # first, compute triangle normals r1 = rr[tris[:, 0], :] r2 = rr[tris[:, 1], :] r3 = rr[tris[:, 2]...
30b06bf23cf3322f59d4feb1dad56fb23e544ada
59,092
def _GetMaxDup(data): """Find the maximum i inside ABCD{i}. data should be a [[[Key]]], where Key is a string that may look like ABCD{i}. """ max_dup = 0 for label in data: for run in label: for key in run: match = _DUP_KEY_REGEX.match(key) if match: max_dup = max(max_du...
c865d1ebb862da5be799154d67f06a4fd2812c58
59,093
def parse_workflows(bactopia_path, include_merlin=False, build_all=False): """Parse Bactopia's workflows.conf to get modules per-workflow""" workflows = {} available_workflows = [] nf_config, stderr = execute(f'nextflow config -flat {bactopia_path}/main.nf', capture=True) for line in nf_config.split...
38eb03793a76431b959fbe76e9cfd217309fc926
59,095
def price_attractiveness_on_afv(): """ Real Name: b'Price Attractiveness on AFV' Original Eqn: b'lagged effect of price on attractiveness on AFV*Reference price Attractiveness on AFV' Units: b'Dmnl' Limits: (None, None) Type: component b'' """ return lagged_effect_of_price_on_attrac...
c81be938d55e6e4f2be0c4dea790512e46e551a3
59,096
def write_climate_file(filename, datadir, arrs, time, changes=None): """Write climate file Parameters ---------- filename : str template file name datadir : Path directory to write to arrs : list of 1D arrays data to write to columns time : 1D array of datetime.datet...
b00e7510d5eb7bc6f70fbc9771720c4171dcdf3c
59,099
def merge_dict(o, keys_to_uppercase=False): """Utility function to assist in merging python dictionary objects. It uses python way which is tricky to do so, by separating keys and values of dictionary objection into separate data structure """ print("log: {}".format(log)) # log.info("-------") K = [] V = ...
b2ae52a034972b771efce793ccd9bfde9af67f42
59,100
def get_optimal_betas_df(lambda_vec, epsilon_vec, lambda_arrays_list, model_string='G1'): """Return a dataframe containing the optimal values for beta.""" running_list = [] model_repeated = np.repeat(model_string, len(epsilon_vec)) for i, lambda_array in enumerate(lambda_arrays_list): lambda_rep...
57c8e92937964a0b52dcb5b4110c16d325153d53
59,101
from multiprocessing import Pool def multiprocessing_write_abstracts_for_gensim(): """ Takes an abstract and id number and saves the abstract text to a folder and the int values to a folder :param tuple_in: tuple of form (abstract, int_tokens) :return: True on success, False on error out """ ...
daca6b9aa890dc36938d754d964784462ac28011
59,104
def re2_full_match(input, pattern): # pylint: disable=redefined-builtin """Extract regex groups Args: dataset: A `tf.string` tensor pattern: A pattern string. """ return core_ops.re2_full_match(input, pattern)
60ea0c474dee26d4a03c4089c7d68ccd3816fa37
59,105
def resnet101(pretrained=True, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) # if pretrained: # model.load_state_dict(model_zoo.load_url( # mod...
d7011d753169b5ab5f2cc3a4a6018eae0134451b
59,106
def get_formatted_message(message): """Gets a log-friendly format of the given message.""" if message.edited_timestamp: edited = ' (edited {})'.format(message.edited_timestamp) else: edited = '' if message.attachments: urls = [attachment['url'] for attachment in message.attachmen...
f41d0da41751f7ded28b230d68c38415820ae7f1
59,107
def generate_graph(data, course_to_id): """ Method to read the JSON and build the directed graph of courses (= DAG of course IDs) The graph is represented in an adjacency list format :return: A graph in adjacency list format, with vertices as course IDs and directed edges implying prerequisite relation :rtype: L...
0a6fe305e39bd812e000a1d22d2374636a7900b2
59,109
def vpt(*args, **kwargs): """ Compute the valid prediction time for a set of parameters Parameters: ----------- system (rescomp.optimizer.System): the system to get data from pred_type: Predict continuation of training trajectory or predict evolution of a random initial ...
7bf5fe47672fc06c4fa872bc53f847e5d2433687
59,112
import select def recipebook(): """ Recipe book provides the user with a select menu containing all their recipes. When they select one and press the "let's cook!" button, a screen appears displaying the desired recipe. """ # If user arrives via GET (that is, if they've clicked on "Book o' Re...
a9c0fd2cd802977dd4cf4b61b8f419d5e00f19a4
59,113
def _build_external_session(conn_params): """ new a sqlalchemy database session. """ conn_info = '{conn_type}://{username}:{password}@{host}:{port}/{schema}' conn_info = conn_info.format(**conn_params) global _session_class if conn_info not in _session_class: engine = create_engine(c...
45b9efb84fd0ec00937815e8b33ad482e51f11ca
59,117
def stats(token="", version="stable", filter="", format="json"): """https://iexcloud.io/docs/api/#stats-intraday Args: token (str): Access token version (str): API version filter (str): filters: https://iexcloud.io/docs/api/#filter-results format (str): return format, defaults t...
c523444e0f7f3484664fc78dd648365b4d80e693
59,118
from typing import Optional import math def round_for_theta( v: float, theta: Optional[float] ) -> float: """ Round a value based on the precision of theta. :param v: Value. :param theta: Theta. :return: Rounded value. """ if theta is None: return v else: ...
ef6d18df588df8a80be9dc6c9b7f9104e3109d69
59,119
def _resolve_name(name, package, level): """Return the absolute name of the module to be imported.""" if not hasattr(package, 'rindex'): raise ValueError("'package' not set to a string") dot = len(package) for x in range(level, 1, -1): try: dot = package.rindex('.', 0, dot) ...
61841fd4d854a59978e82fa5708332b91d8e7680
59,120
import torch def calculate_contrastive_empowerment( discriminator, obs, next_obs, latents, num_prior_samples=512, distribution_type='uniform', split_group=4096*32, obs_mean=None, obs_std=None, return_diagnostics=False, prior=None,...
71f3819054072f1141e63da1b95bc894ede76099
59,122
def sql_column_old(key, sqltype, lst, sqlval_func=lambda x: x, fileval_func=lambda x: x): """ Examples -------- >>> _vals = [25,50,75] >>> vals = sql_column('ecutfwc', 'float', _vals, ... fileval_func=lambda x: 'ecutfwc=%s'%x) >>> for v in vals: ... print(v.key, v.s...
0262f7ebf7d63dbe391507fe8156885815c04730
59,125
from typing import List def split_badge_list(badges: str, separator: str) -> List[str]: """ Splits a string of badges into a list, removing all empty badges. """ if badges is None: return [] return [badge for badge in badges.split(separator) if badge]
6dc53d45cc8390422e5a511e39475ae969bf37c9
59,126
def delete_firewall(name): """Delete a firewall with the given name""" log("Deleting firewall '" + name + "'. This may take a while...", prefix=True) return run('compute firewall-rules delete ' + name + ' -q')
f91c76c6358d9fadd79630b1cfe126d4f6f90e07
59,127
from subroutines import permutations_m_to_n_str def euler_problem_43(): """ The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. Let d1 be the 1st digit, d2 be the 2nd ...
c81d14e3e773e5c0b3c2e4e6f6eebc01b9a5a186
59,128
def indexify(expr): """ Given a SymPy expression, return a new SymPy expression in which all AbstractFunction objects have been converted into Indexed objects. """ mapper = {} for i in retrieve_functions(expr): try: if i.is_AbstractFunction: mapper[i] = i.inde...
27b4a00dfde7eee13fbb9be92060853e55feed72
59,129
def trepeat(elem, n): """ >>> trepeat(1, 2) (1, 1) """ return tuple(repeat(elem, n))
e908b9e2634bfff882ae8d88fadcfbbb95cfb0bb
59,130
def parse_table(file_name, sep, header=False, excel=False): """Opens standard delimited files and outputs a nested list.""" with open_plus(file_name) as infile: line = infile.readline() # First figure out if this table came from excel and has \r for line breaks if line.count('\r') > 0: ...
378432271ac11a733a7d78e58671ef52652320bf
59,131
def merge_dicts(*dicts): """ Merges dicts in reversed order. :param dicts: dicts to be merged :return: merged dict """ result = {} for d in reversed(dicts): if d: result.update(d) return result
2076a23f8cb5d92fc4fa93c3ea4e872eec5202b6
59,132
def chol_reindex_params(params_sdcorr): """ Creates the params Df with Cholesky factors and the right indices for respy. This transformation holds only true for the parametrization in KW94 Dataset 1. Thus, this function simply changes SD-Corr indices to cholesky indices. Without the slicing and ...
3dc6d59edd051ec9fab4e64b531b8298c04b4be2
59,133
def preprocess_images_from_directory(train_dir_path, test_dir_path , label_mode, img_size, seed=45, batch_size=32, val_split=0.2, ): """ preprocess images using the training and testing directories only, a separate validiation dataset is ...
41814554c544858c15af0fbfadb4e077bc20ae62
59,134
def get_model_name(name, batch_size, learning_rate, epoch): """ Generate a name for the model consisting of all the hyperparameter values Args: config: Configuration object containing the hyperparameters Returns: path: A string with the hyperparameter name and value concatenated """ ...
6f2d8ae3d9ae03eb9cf30b538196b7cb08cbdbe2
59,135
import torch def soft_weighted_medoid_k_neighborhood( A: torch_sparse.SparseTensor, x: torch.Tensor, k: int = 32, temperature: float = 1.0, with_weight_correction: bool = True, threshold_for_dense_if_cpu: int = 5_000, **kwargs ) -> torch.Tensor: """Soft Weighted Medoid in the top `k` n...
f0a5e799d45c5338d2f423a74fc0c9369d9eecfb
59,136
def compute_area_signed(pr) -> float: """Return the signed area enclosed by a ring using the linear time algorithm at http://www.cgafaq.info/wiki/Polygon_Area. A value >= 0 indicates a counter-clockwise oriented ring.""" xs, ys = map(list, zip(*pr)) xs.append(xs[1]) ys.append(ys[1]) return s...
9c0e3a8daf5a1fb8a3bd25b28aaa7b941df7b29b
59,137
def get_teams_of_coach(cursor, coach): """gets all the teams a coach has Args: cursor: the cursor coach: the name of the coach Returns: a list of all the teams a coach has """ cursor.execute( "Select team_name from TeamsCoaches where coach_name = '{}'".format(coach...
3d189a20ee23a2ace4b16bb66aca134f65635efb
59,139
def get_timeline(api, screen_name=None, user_id=None): """ Get tweets of a selected user. """ count = constants.MaxCount.TIMELINE tweet_mode = constants.TweetMode.EXTENDED cursor = tweepy.Cursor( api.user_timeline, screen_name=screen_name, user_id=user_id, count=...
c75d58bf9fb2e013fa36cc8cfc96d258d145d7d6
59,140
import random def seq_generator(): """ Generate each part of sequence. :return: sequence part as str """ return random.choice(["T", "H"])
4714194dea06611b269a7157ac6f0f0cb7c1415c
59,141
def svn_ra_get_lock(*args): """ svn_ra_get_lock(svn_ra_session_t session, svn_lock_t lock, char path, apr_pool_t pool) -> svn_error_t """ return apply(_ra.svn_ra_get_lock, args)
0dd4185a9aef9f6ac7c8e249a428ad1db0a47222
59,142
def check_if_image_file(file: FileStorage) -> bool: """ Checks, if file is image file based on ending of file. Currently supported: png, gif, jpg/ jpeg :param file: File from request body :return: Boolean, if file is an image file or not """ return any([file.filename.endswith(image_format) for i...
697f16908c8d8f6d16eb04e1b3e4c89a4422ea13
59,143
import re import html def convert_html_escapes_to_xml(html_text): """Avoid XML parsing errors by converting HTML escape codes to XML.""" html_entities = set( re.findall(r'&(?!quot|lt|gt|amp|apos)[a-zA-Z]{1,30};', html_text) ) for entity in html_entities: html_text = html_text.replace(e...
0ada386b69c8249db7cf1b356051e167a1b8dbdf
59,144
def column(matrix, col): """Returns a column from a matrix given the (0-indexed) column number.""" res = [] for r in range(len(matrix)): res.append(matrix[r][col]) return res
f5214b5a41bf265f6892fdfd9422061b02f61c63
59,146
import re def parse_scenario_gtest_name(name): """Parse scenario name to form acceptable by gtest""" # strip name = name.strip() # space and tab to _ name = name.replace(" ", "_").replace("\t", "_") # remove dots. commas name = re.sub('[^a-zA-Z_]+', '', name) # make lower name = na...
faca8406a6b033536c3f9e0da21d9dc818fd2a7e
59,147
def comma_ai(width, height, channels): """ Get the model, this is a slight modification of comma.ai model """ # image size should be (45,160) with 3 color channels ch, row, col = channels, height, width model = Sequential() model.add(Lambda(lambda x: x / 255. - 0.5, input_s...
9e50e5a705a1697fbb96fe0431d0485ee23b0581
59,148
def data_loader(dataroot, trainset, valset, batch_size, shuffle, num_workers): """dataset Loader. Args: trainset: training set valset: validation set batch size shuffle ratio num_workers: number of workers in DataLoader Returns: trainloader (torch.utils.data....
c4797cbf6fa0322b607113196b7f4c2240c9dfed
59,149
def assign_inband_ip(module): """ Method to assign in-band ips to switches. :param module: The Ansible module to fetch input parameters. :return: String describing if in-band ip got assigned or not. """ global CHANGED_FLAG inband_ip = module.params['pn_inband_ip'] leaf_list = module.para...
d21da3a1d74648f1ea8bf49ffaaafcf8bbb55d4b
59,150
def one_hot_matrix(labels, C): """ Creates a matrix where the i-th row corresponds to the ith class number and the jth column corresponds to the jth training example. So if example j had a label i. Then entry (i,j) will be 1. Arguments: l...
4d8c95dab95d398f6ea6639b6b566036f293f92c
59,151
def check_stl(filename, threshold): """ Parse the (poorly-formatted) STL file and check that no face has an area below a certain threshold (in angstroms squared). """ # Load stl vertex_data = [] with open(filename) as fp: for line in fp: if line.split(" ")[0] == " vertex...
8d8a97efa109e0e501eadb5c4ef61bb17f4a956e
59,152
import json def load_json(filepath): """Load a json file. Args: filepath (str): A path to an input json file. Returns: dict: A dictionary data loaded from a json file. """ with open(filepath, 'r') as f: ret = json.load(f) return ret
c64fec0c861d223e28001051906e32d3aa9ffc7a
59,153
import json from datetime import datetime from dateutil import tz def puzzle_view(request, puzzle_id): """ A view to handle answer submissions via POST, handle response update requests via AJAX, and render the basic per-puzzle pages. """ puzzle = get_object_or_404(Puzzle, puzzle_id__iexact=puzzle_...
8a8fe907d176769102be636b6281ccfe67948b4a
59,154
def linear_unbin(arr): """ Convert a categorical array to value. See Also -------- linear_bin """ if not len(arr) == 15: raise ValueError('Illegal array length, must be 15') b = np.argmax(arr) a = b * (2 / 14) - 1 return a
ef4154d4f32b8e14f19beba848d54a848ed04e2b
59,155
def student_detail_url(student_id): """return url for the student detail""" return reverse('user:student-detail', args=[student_id])
e0ce19282b9e5bc596965fe2fa1d888cbc75d377
59,156
def get_orders_from_gunboat_openings(power_name): """ Samples openings orders from the gunboat openings :param power_name: The name of the power we are playing :return: A list of opening orders for that power """ gunboat_openings = {'AUSTRIA': {('A VIE - GAL', 'F TRI - ALB', 'A BUD - SER'): ...
142c4e3871e3e26746f6ccfbe018662e394ccb43
59,157
def is_insensitive(): """Check if user name should be treated case-insensitive.""" case_spec = getattr(settings, 'HTTP_BASIC_AUTH_CASE', "y") if isinstance(case_spec, str): return case_spec[:1].lower() in ("0", "f", "n") return not bool(case_spec)
ff210f4bec2df61792ba3777d2ff33744ceaf720
59,158
def get_images_paths(path): """ Get sorted images paths. Args: path (str): Images directory. Returns: list: Sorted images paths. """ return _get_sorted_paths(path, "jpg")
d923b290cb986a554facc5de058ed48ef8980d67
59,159
def split_msg(msg, newline_type): """Split a HTTP message and return the head and body in a list.""" double_newline = msg.find(newline_type + newline_type) if not bool(~double_newline): raise errors.NewlineError('Missing double newline!') return SplitMessage( head=msg[:double_newline], ...
0f3d37692dfa4d363d40468b6a166ec9cc51e06c
59,162
def render_state_history_pca_3d( hidden_history, lw=0.1, alpha=0.1, color="k", _show=True, actors=None, mark_start=False, start_color="k", mark_end=False, end_color="k", axes=0, color_by_trial=False, pca=None, ): """ Fits a PCA to high dim hidden state history...
9b5962758fec40bbd4c5fb736f0205716f1b9a25
59,163
import re def branch_config_map(option): """Return {branch: <|option| value>} for all branches.""" try: reg = re.compile(r'^branch\.(.*)\.%s$' % option) lines = get_config_regexp(reg.pattern) return {reg.match(k).group(1): v for k, v in (l.split() for l in lines)} except subprocess2.CalledProcessErr...
5417055f37c5dfd6fa87b51db1c7661a66ded9d1
59,164
def plot_bars(info, metric, data, regnam): """Add legend and save plot to either png or pdf. Parameters ---------- info : dict compilation of plot properties metric : str plot type [area, fraction or bias] data : list list of floats for plotting regnam : list ...
038aa61ff4a1f2016730d02ef25b8632d51a13ae
59,165
def row_sums( x, na_rm=False, # dims=1, # weights = None, # freq = None, # n = None ): """Calculate sum of a data frame by row Args: x: The data frame na_rm: Specifies how to handle missing values in `x`. Returns: The sums by row. """ _check_all_nume...
0598208eb8c4ff52a4a6fc6eed73eb6063479b95
59,166
import math from numpy import zeros, sum def rs1_score(sequence): """ Generates a binary matrix for DNA/RNA sequence, where each column is a possible base and each row is a position along the sequence. Matrix column order is A, T/U, C, G """ # Import Libraries # Function """ Scoring al...
00736fc2002eebeb2d1fec4a0999c96ae5ff580d
59,167
def _count_atoms(expr, **kwargs): """Counts the occurrences of atoms in SymPy expression "expr". Internal function; implementation for count_atoms(). Used also as-is by analyze(). Number atoms are ignored by default. See kwargs. Return value: dictionary: atom -> (#occurrences, topmost_level_...
fb52938fd842ae84b742193ffe9f5b0c7be6fbe7
59,169
def compute_tpm(input_counts): """ Default TPM normalization """ tpm = input_counts.copy() sc.pp.normalize_per_cell(tpm, counts_per_cell_after=1e6) return(tpm)
b8254905f826238e6a6222cab267ab52eeea777c
59,170
def listdata(): """ List the available datasets by querying the DB and returning metadata about the available user uploaded data. """ cuid = current_user.get_id() response = {'status':'success','links':[]} links = response['links'] for i in getdatalist(cuid).itervalues(): response['link...
65b1602b6dd3f5550a30d773b5f48d377b32fc55
59,171
def load_from_file(filename): """load from .yaml file or .sql file""" suffix = filename.split('.')[-1] loader = SchemaLoader() if suffix == 'yaml': return loader.load_from_file(filename) if suffix == 'sql': return loader.read_from_oracle(filename)
1b752ded3b3f9d0d525a0cbbeb2c17e674ac5ba5
59,172
def makeTitlePage(title, subtitle1='', subtitle2='', subtitle3='', center=False): """ Draw a title page, return a PIL image """ font = ImageFont.truetype(config.titleFont, config.titleFontsize) imgsize = [800,800] bgcolor = (0,0,0) fgcolor = (200,200,200) img = Image.new("RGBA", imgsi...
3cd888923a8b6850f3855ce7fdc2177c6281f3e1
59,174
import ctypes def macos_api_ignore(): """ Starting with macOS 11, the security API becomes non-viable except on universal2 binaries. Ref #525. """ try: ctypes.CDLL(ctypes.util.find_library('Security')).SecItemAdd return False except Exception: return True
68c2a9e7f3b59cc0a2c59ba06506de28b4c3f49b
59,175
def preprocess(img, img_shape, detection, margin=0.25): """Preprocessing""" left = detection.left() right = detection.right() top = detection.top() bottom = detection.bottom() w, h = abs(left - right), abs(top - bottom) face_size = max(w, h) desired_size = 1 - 2 * margin desired_size...
fa7de290d1cf079f6ca1fcbc0215832651e64293
59,176
def get_email_of_user(auth0_id): """ Get the email of a user given their auth0 ID Parameters ---------- auth0_id : str The auth0 ID of the user Returns ------- str The email if found, otherwise 'Unable to retrieve' Raises ------ ValueError If the au...
f3e09d7c225888489c38c1f32574b7a9a1511fa8
59,177
def represent_str(dumper, data): """Allows PyYaml module to dump strings as literals """ if utils.is_multiline(data): return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') return dumper.represent_scalar('tag:yaml.org,2002:str', data)
0e40b7cad8f13c1e2a31aaf0077f7efecc81ca28
59,179
def get_cert_contents(public_key_filename): """ Print cert """ if public_key_filename.endswith('.pub'): public_key_filename = public_key_filename[:-4] cert_filename = public_key_filename + '-cert.pub' with open(cert_filename, 'r') as pub_key: cert_contents = pub_key.read() re...
7be010d5a8f0d86129748f3936cc3afccb641e81
59,180
def rw_simul(prob): """simulate RW for prob as probability of going left""" x_pos = np.zeros((10000, 10)) for i in range(10000): pos = 0 for j in range(10): for _ in range(100): pos = rw_next(pos, prob) x_pos[i, j] = pos x_mean = np.mean(x_pos,...
89acfbae89ef07a0aeb841d9179a1b7de071f613
59,181
def sort_states(state, columns, reverse=True): """ Sort the states according to the list given by prioritize_jobs. prioritize_jobs (or columns in this case) is list of according to which state should be prioritized for job submission. The position in the list indicates the prioritization. columns =...
ae8c042d87e5bd2553ceaa08f5e7c88ea7ac2909
59,182
def phase(J): """Return the phase.""" gamma = np.angle(J[..., 1]) - np.angle(J[..., 0]) return gamma
40187ef149d14b7bde755ed4c76153ffd8a10887
59,183
async def vocprez_profiles(request: Request): """Returns a JSON list of the profiles accepted by VocPrez""" return await profiles_func(request, "VocPrez")
4138b121bb852b3e64f9b626a2cac03fe02f32f1
59,184
def get_thread_id() -> str: """Returns thread_id.""" return current_process().name
f625d7c2f1b95367123efa50291046866c6dcfd3
59,185
import numpy as np def fearly3_kasen(td, rstar, band): """ This function produces the shock-heated emssion light curve. Written for the SN 2015F work based on the Kasen (2010) model [2015. M. Im]. Currently, the explosion energy is set to 10^51 erg which is appropriate for Type Ia SN. This value may n...
a30efff373685840531e268ef596e098e24f48d9
59,186
def get_job_chart_metadata(job: Job) -> str: """ Get a string containing a javascript object used to draw the Gannt chart for a job's timing :param job: :return: """ job.refresh() return job.get_chart_metadata()
107ea87b5ed82c9745e953ee0eaf8e3284074ebd
59,187