content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
def sf_magnetic_neutron(q, r, moment, magnetic_formfactor=None, occ=None, debyewaller=None, **kwargs): """ Calculate the magnetic structure factor for the given HKL, using neutron magnetic form factor Assumes an unpolarised incident beam. Reference: G. L. Squires, Introduction to the Theory of Ther...
f21246bd66a89a523b08137acac639f84b6cbfb5
59,102
import os from glob import glob import math def get_chunksize(input_path): """ Calculate the appropriate chunksize for dask_cudf.read_csv to get a number of partitions equal to the number of GPUs. Examples -------- >>> import cugraph.dask as dcg >>> # chunksize = dcg.get_chunksize(edge_li...
06b74beedec692a5fd83bccd9b1be2339d1e55cb
59,103
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
import asyncio async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, component) for component in PLATFORMS ...
5a9b97dba3d0445942e71505227c6daddf03b2b0
59,108
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 PaintimgEdges(smap, MMasks, scale): """ Fill me in please. Args: smap: MMasks: scale: Returns: edgeImg2: edgeImg: edgeImg3: Todos: * Fill this in with proper summary """ if (scale == 1): stepX = 60 edgeImg = np.zeros...
6778f2fabdb398aaee01599ae78aa790b4dbef25
59,110
def parse_command(x): """Parse commands.""" line = x.split() for c in ',:': line = c.join(line).split(c) if line[0] not in config.verblist: print("I don't understand that.") else: args = line[1:] func = config.verblist.get(line[0]) # FIXME: not callable retur...
cdff7ff698be78562efe0970f65e3818b8b923c7
59,111
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 load_multi_samples_from_excel_with_pandas(filename): """ Load all columns from a selected sheet in Excel file. Uses pandas. Return pandas data frame""" # TODO: should be moved to dataIO but need to agree on refactoring IO xl = pd.ExcelFile(filename) dialog = ExcelSheetDlg(xl.sheet_names) #se...
63c8f89732726b080c8f76027588fc09dc370a59
59,114
import os def _download(path, url, archive_name, hash_, hash_type='md5'): """Download and extract an archive, completing the filename.""" martinos_path = '/cluster/fusion/sample_data/' + archive_name neurospin_path = '/neurospin/tmp/gramfort/' + archive_name remove_archive = False if op.exists(mar...
757c2657af4bac95a1246f2674ece21c540f772b
59,115
import os import base64 import pickle def exec_string_with_io(dll, s, cwd=None, globals={}, locals={}): """executes string s using dll and return stdin, stdout, stderr""" if cwd is None: cwd = os.getcwd() inr, inw = os.pipe() outr, outw = os.pipe() excr, excw = os.pipe() stdin = os.fdopen(inw, "w") stdout = ...
7e751326eea3287cc2649bad2f96d35dbb21bf93
59,116
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
from typing import Optional from typing import Tuple from sys import version def cluster_config( kubeconfig: Filepath, context: Optional[str]) -> Tuple[K8sConfig, bool]: """Return web session to K8s API. This will read the Kubernetes credentials, contact Kubernetes to interrogate its vers...
1497b78dbf566db30a97bed718e88fb3fb230445
59,121
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 construct(s, maxvalue, to_print=False, to_return=True): """ >>> construct([5, 4, 5, 5, 2, 1, 5, 6, 1, 3, 5, 0], 6, to_print=True, to_return=False) [1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0] [1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0] [1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0] num0: 4 start_positions: [0, 4...
406baac59d712af21a3b324149ba85d6c6ce2ee1
59,123
import argparse import sys import os import yaml def main(): """toil-signalAlign master script """ def parse_args(): parser = argparse.ArgumentParser(description=print_help.__doc__, formatter_class=argparse.RawTextHelpFormatter) subparsers = parser....
567ba6a166646ff9ebb9b75c2edc7cdd6c68a417
59,124
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
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import nibabel as nib from scipy import stats from ..morph import _get_subject_sphere_tris from mpl_toolkits.axes_grid1.inset_locator import inset_axes def _plot_mpl_stc(stc, subject=None, surface='inflated', hemi='lh', ...
5acf72493385c5ca9c585cf9a1fbc0709e09afcb
59,138
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
from re import T import os def read_bufr( path: T.Union[str, bytes, "os.PathLike[T.Any]"], columns: T.Iterable[str], filters: T.Mapping[str, T.Any] = {}, required_columns: T.Union[bool, T.Iterable[str]] = True, ) -> pd.DataFrame: """ Read selected observations from a BUFR file into DataFrame. ...
2a7268dfb7e4970c516fef9ee350b4314aec6b21
59,145
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 save_gsheet(df, filename): """ Saves a dataframe to a new spreadsheet using account with credentials on the local system. No try-except loop so that any errors are reported for easier debugging. Not totally user friendly! """ url = None gc = gspread.oauth() ss = gc.create(filename) ...
80220592b382c5a0495030ec0ec9026de548b658
59,160
import json def get_offer(): """ get offer """ # logger M_LOG.info("get_offer") # exist offer in dict ? if "offer" in gdct_data: # convert to JSON l_json = json.dumps(gdct_data["offer"]) M_LOG.debug("Requested offer: %s", str(l_json)) # remove offer from...
80bedf56912c8a9d4cc7e32065f51d6b0154d741
59,161
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 computeobjective(x,y,Ax,tau,noisetype,logepsilon,penalty,WT): """Compute the objective function""" ## (1) Compute log-likelyhood if noisetype.lower()=='poisson': precompute = y*np.log(Ax + logepsilon) objective = Ax.sum() - precompute.sum() elif noisetype.lower()=='gaussian': ...
2011de0ac5c112c942714f3db70ef153e16a7740
59,168
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 remove_overlapping_matches(matches): """ Remove overlapping matches. First, the function removes matches that include other matches of the same appliance (start1 < start2 and end1 > end2). Parameters ---------- matches : pandas.DataFrame with columns 'start', 'end', as well as other ...
ffc22cc9ac90da1b40cab0d7f18b66f05730b060
59,173
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
import os def backup_path(machine): """ Determine a machine's backup path """ return os.path.join(BACKUP_ROOT, machine['name'])
2735905972a846b1159c3fe9ed29a3417eafc3be
59,178
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
def index_w(wv, T, S): """ Calculates water refractive index mw(wv,T,S)=n0+(n1+n2T+n3T^2)S+n4T2+(n5+n6S+n7T)/wv+n8/wv^2+n9/wv^3; Inputs ------- wv : Wavelength (nm) T : Temperature (̊ C) S : Salinity (PPT) """ n0=1.31405 n1=1.779e-4 n2=-1.05e-6 n3=1.6e-8 n4=-2.0...
4f19d74341e7507c8d6f6c27a549da1291e99381
59,188
def special_copy(DL1,DL2): """ This function should return a new doubly linked list which contains the same element of DL1 concatenated with the elements of DL2 in reverse order. Ex. DL1 = 4 <-> 5 <-> 6, DL2 = 9 <-> 4 <-> 6 >>> returns DL3 = 4 <-> 5 <-> 6 <-> 6 <-> 4 <-> 9] Note: this function does...
1f8d08b96906c30cf197593e2420cbae047bd7b4
59,189
def create_tpu_estimator(t2r_model, model_dir, train_batch_size = 32, eval_batch_size = 1, use_tpu_hardware = True, params = None, export_to_cpu = True, ...
3cb1b32762f71cdc245f41a753d34ba126135113
59,190
from datetime import datetime def timestamp_to_datetime(timestamp): """将 13 位整数的毫秒时间戳转化成本地普通时间 (datetime 格式) :param timestamp: 13 位整数的毫秒时间戳 (1456402864242) :return: 返回 datetime 格式 {datetime}2016-02-25 20:21:04.242000 """ local_dt_time = datetime.fromtimestamp(timestamp / 1000.0) return local_d...
22b4dfdb09dde6ea3b09a80150a87dd992c32d46
59,191
def union_rbox(result,alpha=0.1): """ 按行合并box """ def diff(box1,box2): """ 计算box1,box2之间的距离 """ xy_sum1 = np.sum(box1['box'], axis=0) / 4.0 cy1 = xy_sum1[1] xy_sum2 = np.sum(box2['box'], axis=0) / 4.0 cy2 = xy_sum2[1] ...
a604a2f3f65ff6b362731225f7965ccd9d81ce00
59,192
def statement(prop, value, source): """ Returns a statement in the QuickStatements experted format """ return "LAST\t{}\t{}\tS854\t\"{}\"".format(prop, value, source)
2c0b6ea8f757c8586ca462d85fca3b9d281adb26
59,193
def transform_children(form, f): """Given a form and a form-transforming function f, apply the latter on all the child-forms of the form (but not to any non-form attribute of the form). """ if isinstance(form, IfForm): return IfForm(f(form.predicate), f(form.consequent), f(form.alternative)) ...
1316ac351ead3afff5d51a3ab7a32285eb0b9276
59,194
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload the config entry and platforms.""" unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: hass.data.pop(DOMAIN) return unload_ok
0af747fdf9af7520f6057fc5a3b9cb0d350b6a62
59,195
def get_id(uuid): """ >>> get_id('{8C65E04C-0383-4AE2-893F-4EC7C58F70DC}') 1 >>> get_id('{8C65E04C-0383-4AE2-893F-4EC7C58F70DC}') 1 """ id = redis.get('{}:{}'.format(KEY_PREFIX, uuid)) if id is None: id = create_id(uuid) return int(id)
16997d48332e5ca989da05e6277234cdfc38857d
59,196
import json def get_config_db_json_obj(dut): """ Get config_db content from dut Args: dut (SonicHost): The target device """ config_db_json = dut.shell("sudo sonic-cfggen -d --print-data")["stdout"] return json.loads(config_db_json)
92920197b2056d889ffb76ff66e01061f0654032
59,197
import argparse def get_arg_parser(parser=None): """Parse the command line arguments for merge using argparse Args: parser (argparse.ArgumentParser or CompliantArgumentParser): an argument parser instance Returns: ArgumentParser: the argument parser instance Notes: i...
f66745ab2d2d5ed80b4efc59bd90b5dfbefb1370
59,198
import os def get_python_filepaths(): """Helper to retrieve paths of Python files.""" python_paths = ['setup.py'] for root in ['ops', 'test']: for dirpath, dirnames, filenames in os.walk(root): for filename in filenames: if filename.endswith(".py"): ...
7d6f63973cb8afd4dee55026428ac87b55e874f3
59,199