content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from sys import float_info def _format_layer_terms(layer): """Get the terms for the given layer for display in Graphviz""" formatter = FormattingHelper(layer) if hasattr(layer, 'inception_date') or hasattr(layer, 'expiry_date'): formatter.append_term('coverage', _format_coverage(layer)) form...
5698b2f526459b55a529607c13ec0a283d7ac6a5
3,626,600
import os def certify(): """Authenticate with Twitter using Tweepy and return Twitter API object. :returns: Twitter API object :rtype: Twitter API object """ consumer_key = os.environ["CONSUMER_KEY"].decode("utf_8") consumer_secret = os.environ["CONSUMER_SECRET"].decode("utf_8") access_to...
157f7acc0727b84178bfc24223770ec7c40ad2d5
3,626,601
def _get_mask(Size, idxi, idxj, win_type): """Compute a mask of zeros with a window at a given position. """ idxi = np.array(idxi).astype(int) idxj = np.array(idxj).astype(int) win_size = (idxi[1] - idxi[0] , idxj[1] - idxj[0]) wind = build_2D_tapering_function(win_size, win_type) mask =...
cf6426646703601c23ab9d8491eff656e2effaf0
3,626,602
import os import sys def rollup_command(): """ Maintain a collection of monthly rollup JSON blobs from raw observation JSON blobs """ direct_name = "w1rollup" _, applied_name = os.path.split(sys.argv[0]) p = LocalArgumentParser() if applied_name != direct_name: p.add_argument('roll...
321dd39828899737cbbb71d4fe483f07bebdc57b
3,626,603
import shutil import logging def _check_tool(cfg: config.Config, bin_name: str, name: str, min_version: Version) -> bool: """Check availability and version of a tool.""" if not _check_availability(bin_name, name): return False bin_path = shutil.which(bin_name) assert bin_path i...
15520d3b94ffac6957ca297aa1f4ae49bff8a45d
3,626,604
def init_func_global() -> JobInitStateReturn: """ Init function for the job :return: INIT or NOT_INIT state for the job """ return JobInitStateReturn(True)
e00c448dcc3f84cd53844d9d4a425ff4545a8135
3,626,605
def get_orbit_from_metadata(mds): """Get orbit for a set of SLC ids. They need to belong to the same day.""" day_dt, all_dts, mission = util.get_date_from_metadata(mds) logger.info("get_orbit_from_metadata : day_dt %s, all_dts %s, mission %s" %(day_dt, all_dts, mission)) return fetch("%s.0" % all_dts[0...
ff0b9d1a2f2d99dc5332abcd0fc4d402e0dd693f
3,626,606
def fibonacci(n): """Return the n-th Fibonacci number""" if n in (0,1): return n return (fibonacci(n - 2) + fibonacci(n - 1)) # Can trace the recursive function with a decorator
ab01aabbc2ef5c5bf2f3f0b83f44675254b555c7
3,626,607
def random_color() -> np.ndarray: """Generate a random color (RGB).""" return np.array(np.random.rand(3))
f77b72075fbbd89d87f6507d06a2ac713d49daa2
3,626,608
def get_king_moves(): """Generate the king's movement range.""" return [(1, 0), (1, -1), (-1, 0), (-1, -1), (0, 1), (0, -1), (-1, 1), (1, 1)]
5e6f5fcb8c57846b9b2ab112c27f90fc13a6d6b4
3,626,609
import ray import os def v206b_directga(): """ This tries to run """ np.random.seed(42) date = get_date() ray.init(num_cpus=5) @ray.remote def single_func(seed, index, name, game, method, results_directory, args, date, get_pop, w): # A single function to run one seed and one p...
f45f04d2ed610790cfd27bab12d90d855916d577
3,626,610
def _unpack_topk(topk, lp, hists, attn=None): """unpack the decoder output""" beam, _ = topk.size() topks = [t for t in topk] lps = [l for l in lp] k_hists = [(hists[0][:, i, :], hists[1][:, i, :], hists[2][i, :]) for i in range(beam)] if attn is None: return topks, lps, ...
7e9012b62f25ec7f4a09387235a0161143ec5029
3,626,611
def share_map(map_url_hash): """Create shareable version of current map using crypotgraphic hash at end of address""" user_map = Map.query.filter(Map.map_url_hash == map_url_hash).one() map_id = user_map.map_id places_on_map = Place.query.filter(Place.map_id == map_id, Place.place_active == True).all() ...
a92384b52e0b9beb36c783d5fec4036983289aef
3,626,612
def _darknet_reshape(inputs, params, attrs, prefix): """Process the reshape operation.""" new_attrs = {} new_attrs['shape'] = attrs.get('shape') return get_relay_op('reshape')(*inputs, **new_attrs)
90049d596aeca37074e2d9946eb0f2d0c6bc8513
3,626,613
import random import string import os def create_import_request(git_source_url, project=None, repository=None, requires_authorization=False, user_name=None, git_service_endpoint_id=None, organization=None, detect=N...
250a90902e4f6f496667bbe1add61ba7dae42b3c
3,626,614
def CreateVectorObject(volumeRef, name): """ Creates a c4d.VolumeObject with the VolumeRef passed. Names this VolumeObject with the passed argument. :param volumeRef: The VolumeRef to use within the VolumeObject. :type volumeRef: maxon.frameworks.volume.VolumeRef :param name: The name of the in...
11099d54def62f560227d3a97ea628bf15c55931
3,626,615
def box2start_row_col(box_num): """ Converts the box number to the corresponding row and column number of the square in the upper left corner of the box :param box_num: Int :return: len(2) tuple [0] start_row_num: Int [1] start_col_num: Int """ start_row_num = 3 * (box_num // 3...
b11e7d4317e1dd32e896f1541b8a0cf05a342487
3,626,616
def safe_referrer(meta, default): """ Takes request.META and a default URL. Returns HTTP_REFERER if it's safe to use and set, and the default URL otherwise. The default URL can be a model with get_absolute_url defined, a urlname or a regular URL """ referrer = meta.get('HTTP_REFERER') i...
b70f7799bf13fc2ee9229f037553047dd60334be
3,626,617
import re def create_title(chunk, sep, tags): """Helper function to allow doconce jupyterbook to automatically assign titles in the TOC If a chunk of text starts with the section specified in sep, lift it up to a chapter section. This allows doconce jupyterbook to automatically use the section's text...
67bd80c10733d79f84ba38cd44155e73bb2a2efd
3,626,618
import math def get_marker_size(number): """Same scaling as for year 2019. Produces more overlap between circles. But this was considered OK, since it does reflect the reality. """ return SCALE * (5 * math.sqrt(number) + 5)
252c9549fa0c568dd88361cbf1a8cbc467972e08
3,626,619
import argparse def parseCmd(): """Parse command line arguments Returns: dictionary: Dictionary with arguments """ parser = argparse.ArgumentParser(description='') parser.add_argument('--arg', type=str, help='') return parser.parse_args()
2b51a1b7f2b2286938d3b0ab88feb6dd9898aab8
3,626,620
import scipy import numpy def graph2VSM(graph): """ Convert an igraph model to a VSM Params: model the igraph model """ terms = graph.vcount() edges = graph.ecount() # Use sparse matrix representation if the matrix is less than 50% full # if terms > 20000 and graph.density() <...
e89b682d539879945fe5a1a970db1f8c56c27652
3,626,621
from functools import wraps from types import FunctionType import inspect import re import logging def cached(prefix=None, ext="xz"): """ Decorator to cache the function result in a file depending on args. The function source is stored together with the data, source code mismatch triggers recomputati...
516920b947882f804f7cc978c51736062913afec
3,626,622
import os def which(program, env=None): """ returns the path to an executable or None if it can't be found""" if env is None: env = os.environ.copy() def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: ...
51e6d2790dd4ef6f4a2e9f776b6536d5e534c284
3,626,623
def recurrence_memo(initial): """ Memo decorator for sequences defined by recurrence See usage examples e.g. in the specfun/combinatorial module """ cache = initial def decorator(f): @wraps(f) def g(n): L = len(cache) if n <= L - 1: retur...
6cb4ea4a2183bb98b915d966692fc5be40cdf494
3,626,624
def update_project_users(post_data=None, slug=None): """update-project-users (Site admins/Site managers/Project managers only) Usage: update-project-users [-h] <slug> (<username> <access_mode>) ... Arguments: <slug> The slug of the project <username> The username of the user to either update o...
71548b9203f1ce42cb469dd1ea0c37eaff722b8c
3,626,625
def satisfiesNodeConstraint(cntxt: Context, n: Node, nc: ShExJ.NodeConstraint, _: DebugContext) -> bool: """ `5.4.1 Semantics <http://shex.io/shex-semantics/#node-constraint-semantics>`_ For a node n and constraint nc, satisfies2(n, nc) if and only if for every nodeKind, datatype, xsFacet and values constr...
5620ca1c672ca632525edb933d8054dc04653cb8
3,626,626
def _gaussian(y_pred, y_true, scale): """ Computes the log-likelihood of each sample for a Gaussian GLM given the predicted expected values. """ return - 0.5 * (y_pred - y_true) ** 2 / scale ** 2 \ - 0.5 * np.log(2 * np.pi * scale**2)
0d3d1df54e1f785e696e39d649f6d8c1b10c80c4
3,626,627
from typing import Sequence def regression_report( y_true: Sequence, y_pred: Sequence, *, precision: int = 4, width: int = 32, use_percentage: bool = False, ) -> str: """ Returns detailed regression report as string :param y_true: sequence of ground truth values for regression pro...
6572f117b045414822ec391af292759d4dc9d7ea
3,626,628
def _extract_feats(data_test, model, what, skip=1, batch_size=16): """ :param data_test: test Dataset :param model: network model :param what: SK or IM :param skip: skip a certain number of image/sketches to reduce computation :return: a two-element list [extracted_labels, extracted_features] ...
5549c3131d98ae876609f52ad0dc581ec7c9bc76
3,626,629
def _getbkfile(repo): """Hook so that extensions that mess with the store can hook bm storage. For core, this just handles wether we should see pending bookmarks or the committed ones. Other extensions (like share) may need to tweak this behavior further. """ fp, pending = txnutil.trypending(re...
1c04da01ed277ab790f02cae0e282d8dc853e8a0
3,626,630
def perturb(graph_list, p): """ Perturb the list of (sparse) graphs by adding/removing edges. Args: p: proportion of added edges based on current number of edges. Returns: A list of graphs that are perturbed from the original graphs. """ perturbed_graph_list = [] for G_original i...
c3358dc0bbdcd75d5619ed1ee372d206ea7651b0
3,626,631
def hold_out_val(data, target, include_self=True, class_weight=None, features=None, cl='rf', verbose=False, random_state=None): """ performs simple hold-out validation :param data: list of datasets to evaluate :param verbose: if true print confusion matrix and classification report for ...
b4e934fa87add641067ff16cb3709f384d1675e8
3,626,632
import torch def train(model, train_loader, loss_func, optimizer, device): """ 训练模型 train model using loss_fn and optimizer in an epoch. model: CNN networks train_loader: a Dataloader object with training data loss_func: loss function device: train on cpu or gpu device """ total_lo...
610b03e10ebce886743a4b06c91a46de30ef586d
3,626,633
def sq_dist(x: np.ndarray, y: np.ndarray): """ distance functions for point-point distances :param x: nd array, T1 x D :param y: nd array, T2 x D :return: matrix with shape of (T1, T2) """ return np.sum((x[:, None, :] - y[None, :, :]) ** 2, axis=2)
97f3b6fc10dbf5f18c5eea4403f3662be8580097
3,626,634
import uuid def get_uuid(): """ Returns a uuid4 (random UUID) specified by RFC 4122 as a 32-character hexadecimal string """ return uuid.uuid4().hex
ce3f00569c3fa12aa203246bd5d3ae098f2dab2a
3,626,635
async def register_users(app, users): """Create multiple users from a list. Parameters ---------- app : aiohttp.web.Application The aiohttp application instance. users : list(dict) The list of new users with each user having username, password, permissions and cards (optional). ...
a7ca4cb451da4d542d9740f7e2d12511514a7612
3,626,636
def radmat_from_df_filter( df, radmat_field="signal", channel_i=None, return_df=False, **kwargs ): """ Apply the filter args from df_filter and return a radmat """ _df = df_filter(df, channel_i=channel_i, radmat_field=radmat_field, **kwargs) radmat = df_to_radmat(_df, channel_i=channel_i, radmat...
61782b513be331da08d7c9ceaada7c12ba83d3e6
3,626,637
def _populate_number_fields(data_dict): """Returns a dict with the number fields N_NODE, N_EDGE filled in. The N_NODE field is filled if the graph contains a non-`None` NODES field; otherwise, it is set to 0. The N_EDGE field is filled if the graph contains a non-`None` RECEIVERS field; otherwise, it is set ...
e80e506057ecbb9ab4987ce4383da494824f1d66
3,626,638
def tree_pretty_print(tree): """Pretty-print a tree of python objects. Examples:: >>> from pptree import Node >>> users = Node("users") >>> group = Node("group", users) >>> _ = Node("roles", group) >>> _ = Node("permissions", group) >>> _ = Node("comments", users) >>> print(tree_pr...
2598ae29d3d019c1c9613f4944d16c01f149529f
3,626,639
def branch_edit(request, branch_id): """/branch_edit/<branch> - Edit a Branch record.""" branch = models.Branch.get_by_id(int(branch_id)) if branch.owner != request.user: return HttpTextResponse('You do not own this branch', status=403) if request.method != 'POST': form = BranchForm(initial={'category':...
f9ce2ba616899174b4765c889d28a2cfa7d39787
3,626,640
def eul(f, u, x_0, d, param): """Integrate dynamics using forward Euler method x[k+1] = x[k] + delta*(f(x[k], u[k])) Input: dynamics f, control input u, initial condition x_0, step d Output: trajectory x """ if u.ndim == 1: return x_0 + d*(f(x_0, u, param)) N...
9ac8ad1fef149c96144ea9d2730752e0d18bc0bd
3,626,641
def input_network_name(): """ Prompt user to choose a network """ while True: network_name = input('network ({0})?'.format(','.join(NETWORK_NAMES))) if network_name in NETWORK_NAMES: return network_name
0a467259652a12aa2f4c71c57019aba8b02af889
3,626,642
import re def hashtag(phrase, plain=False): """ Generate hashtags from phrases. Camelcase the resulting hashtag, strip punct. Allow suppression of style changes, e.g. for two-letter state codes. """ words = phrase.split(' ') if not plain: for i in range(len(words)): try: if not words[i]: del word...
b6e7ab647330a42cf9b7417469565ce5198edd4f
3,626,643
from sys import getsizeof def _subtract(summary, o): """Remove object o from the summary by subtracting it's size.""" found = False row = [_repr(o), 1, getsizeof(o)] for r in summary: if r[0] == row[0]: (r[1], r[2]) = (r[1] - row[1], r[2] - row[2]) found = True if n...
5bdabae2df9febef259aa5ba3052ab5478caf228
3,626,644
def maxpool_to_same_maxpool(module): """Turn All MaxPool2d into SameMaxPool2d to match TF padding""" module_output = module if isinstance(module, nn.MaxPool2d): module_output = MaxPool2dSamePadding( kernel_size=module.kernel_size, stride=module.stride, padding=0, ...
70217073e0ec8d1bfd74ee5e79775b6b87e8dc62
3,626,645
def check_for_split(G, edge): """ Given an edge in tuple form, check if it splits the graph into two disjoint clusters. If so, it returns True. Otherwise, False. """ # Possibly keep a record of splits. try: return not G.edge_disjoint_paths(source=edge[0], target=edge[1]) # TO...
c47ad39cae0f8875f589d4a4a7be5d084623ab5e
3,626,646
from pathlib import Path from typing import List def process_boto3_stubs( output_path: Path, service_names: List[ServiceName] ) -> Boto3StubsPackage: """ Parse and write stubs package `boto3_stubs`. Arguments: output_path -- Package output path. Return: Parsed Boto3StubsPackage. ...
0ef1f0da354b384cbe70f9b3df5d5999c7063be9
3,626,647
def double_wedge_filter(sinogram, center=0, sino_type="180", iteration=5, mask=None, ratio=1.0, pad=250): """ Apply double-wedge filter to a sinogram image (Ref. [1]). Parameters ---------- sinogram : array_like 2D array. 180-degree sinogram or 360-degree sinogram. ...
300fdb1cc94e6c95479f02e540a542de7e461bea
3,626,648
def gather_data_to_plot(wells, df): """ Given a well ID, plot the associated data, pull out treatments. Pull in dataframe of all the data. """ data_to_plot = [] error_to_plot = [] legend = [] for well in wells: data_to_plot.append(df.loc[well, '600_averaged']) error_to_pl...
1870384b94c2cf3a8a5da84b848586e0a95d1713
3,626,649
def build_rust_cmdclass(cargo_toml_path, debug=False, extra_cargo_args=None, quiet=False, ext_name=None): """ Args: cargo_toml_path (str) The path to the cargo.toml manifest (--manifest) debug (boolean) Co...
e8f91ea54eefe21f745d07a9d75497dcb681ebb2
3,626,650
def create_data_frame_sfem(data_sfem, strategy_order): """ Create the DataFrame that will be used for the type classification. Args: data_sfem (DataFrame): Individual level data that is already subset to the correct level. strategy_order (list): Name of all st...
fa8c41ded771e34cba89c99cc4f9bfb80acb7a92
3,626,651
import re def is_ignored(filename, ignores): """ Checks if the filename matches any of the ignored keywords :param filename: The filename to check :type filename: `str` :param ignores: List of regex paths to ignore. Can be none :type ignores: `list` of `str` or...
3d5016d5ac86efdf9f67a251d5d544b06347a3bf
3,626,652
def public(): """ # TODO improve docstring Filtered version of the Alerts controller """ s3.filter = (FS("scope") == "Public") # TODO do this in the prep of alert() return alert()
8f40b5f51e35041fc7214bdf8e65c1e990c208d7
3,626,653
import requests def token(username: str, password: str, auth_url: str = 'https://api.sonetel.com/SonetelAuth/beta/oauth/token', refresh: str = "no", grant_type: str = "password", refresh_token: str = None) -> dict: """ Create an API access token from the user's Sonetel email address and password. ...
3a76a8882a35ba1d4c91132182323f5d4095e73c
3,626,654
async def present( hub, ctx, name, resource_group, sku, kind, location, custom_domain=None, encryption=None, network_rule_set=None, access_tier=None, https_traffic_only=None, is_hns_enabled=None, tags=None, connection_auth=None, **kwargs, ): """ .....
8d2264e765fd22b6777bbb460174ed42a4c511ca
3,626,655
import hashlib import os def ftp_file_hash(con): """ Get the file hashes inside the FTP server Assumes that the FTP connection is already in the wordpress dir. """ # Function to get MD5 Hash inside the FTP server def get_md5(fpath): """ Returns the md5 hash string of a file """ ...
fac1d9ee558a7339135ccf5f1a25191fef2aac4f
3,626,656
def check_transaction_threw(client, transaction_hash): """Check if the transaction threw/reverted or if it executed properly Returns None in case of success and the transaction receipt if the transaction's status indicator is 0x0. """ encoded_transaction = data_encoder(transaction_hash.decode(...
ec7d44c8824ea5613642e28a11e0ff635a38d9a2
3,626,657
def boldReplacements(tex): """ SPECIFIC TO shmem_reductions: Replace the Latex command: "\\textbf{<NAME>} \\newline <text> <code> \\newline...\\bigskip" --NAME will the title of a new section header with <text> as the immediate content. -- <code> will be replaced as normal (See function ...
27b7a80c36396d66218857348135d46beb1f760a
3,626,658
def stop_program(): """Small function to ask for input and stop if needed """ ok = input("Press S to Stop, and any other key to continue...\n") if ok in ["S", "s"]: return True return False
c076d4a443331d64ef5855f0d20f7db2adb0cf11
3,626,659
def rotate(n): """ Rotate 180 the binary bit string of n and convert to integer """ bits = "{0:b}".format(n) return int(bits[::-1], 2)
23fa595ee66c126ad7eae0fa1ca510cf0cebdfbd
3,626,660
def fixture_list_arg(): """Test for the correct stdout. Output in the tests should match what this returns """ def list_arg(*profiles): _string = "" for profile in profiles: _string += ( f"[{profile}]\n" f"reponame = {HOST}\n" ...
ee8a3829c95e5a0010a5474fba9b29da0df3b983
3,626,661
def tkForm(fields): """tkForm(fields: dict)->dict fields: {'label1': 'defVal1', ...} return: modified fields or {} if Esc >_> tkForm( {'Imię':'iii', 'Imię 2':'iii 2', 'Nazwisko':'Nnn'} ) {'Imię': 'iii 1', 'Imię 2': 'iii 2', 'Nazwisko': 'nnn 3'} """ master = tk.Tk() entries = {} for i, (field, defVal) ...
52d47e83f00dcd77b9a5bc279f5c1fe4aa9d429f
3,626,662
def concentration_at_M(Mass, k, P, n_s, Omega_b, Omega_m, h, T_CMB=2.7255, delta=200, Mass_type="crit"): """Concentration of the NFW profile at mass M [Msun/h]. Only implemented relation at the moment is Diemer & Kravtsov (2015). Note: only single concentrations at a time are allowed at the moment. Ar...
b5109273c2bc59da0d5723027ab9d3e15595f4d2
3,626,663
def flip_thetas(thetas, theta_pairs): """Flip thetas. Parameters ---------- thetas : numpy.ndarray Joints in shape (num_thetas, 3) theta_pairs : list List of theta pairs. Returns ------- numpy.ndarray Flipped thetas with shape (num_thetas, 3) """ thetas...
e19a274953a94c3fb4768bcd6ede2d7556020ab2
3,626,664
def Client(token=None, endpoint=None, config_path=None, connect_timeout=None): """Return global `RESTClientObject` with optional configuration. Missing configuration will be read from env or config file. Parameters ---------- token : str, optional API token endpoint : str, optional ...
d6909374b0d94fe86ed20296c3f7b25b7d14650d
3,626,665
def numeral_to_int(numeral: str) -> int: """Returns the integer value represented by the given Roman numeral.""" i = 0 numeral_len = len(numeral) total = 0 while i < numeral_len: curr_value = numeral_values[numeral[i]] if i < numeral_len - 1: next_value = numeral_values[n...
6d975a57691b392fa5726d97150c87e9f275bbca
3,626,666
def TopOpeBRepTool_TOOL_tryTg2dApp(*args): """ :param iv: :type iv: int :param E: :type E: TopoDS_Edge & :param C2DF: :type C2DF: TopOpeBRepTool_C2DF & :param factor: :type factor: float :rtype: gp_Vec2d """ return _TopOpeBRepTool.TopOpeBRepTool_TOOL_tryTg2dApp(*args)
6dbd60651c10d3a525ab440a600fd8615712c118
3,626,667
def GetMounts(filename=constants.PROC_MOUNTS): """Returns the list of mounted filesystems. This function is Linux-specific. @param filename: path of mounts file (/proc/mounts by default) @rtype: list of tuples @return: list of mount entries (device, mountpoint, fstype, options) """ # TODO(iustin): inve...
01e2b101489c5823c8a1f722f7c5613bd69732e3
3,626,668
def disable_slot(slot, con=None): """Return True on success, False on failure, if con given does not commit""" if not slot: return False if con is None: try: con = open_database() result = disable_slot(slot, con) if result: con.commit() ...
18b9e07f062e93f76dc7537ace1eac8c4884d327
3,626,669
def surface_analysis_function_for_tests(surface, a=1, c="bar"): """This function can be registered for tests.""" return {'name': 'Test result for test function called for surface {}.'.format(surface), 'xunit': 'm', 'yunit': 'm', 'xlabel': 'x', 'ylabel': 'y', ...
e6e58c172687ce3e0782abb07b9154afae9356cb
3,626,670
def add_or_update(record, key, timetable, name, force_refresh): """ Insert a new user record or update exist one :param name: user name identifier :param timetable: timetable list :param force_refresh: if refresh is required :param key: the key in database :param record: a User record :r...
b348fa1718753846fa1edb5864a1094c41935f5b
3,626,671
from pyquickhelper.pycode.profiling import profile import torch import numpy import time import os def benchmark(N=1000, n_features=20, hidden_layer_sizes="26,25", max_iter=1000, learning_rate_init=1e-4, batch_size=100, run_torch=True, device='cpu', opset=12, profile='fct'): """ Co...
7f1cc0b3d13cc7bac9b03a4216c6df16341692bc
3,626,672
def from_time (year=None, month=None, day=None, hours=None, minutes=None, seconds=None, microseconds=None, timezone=None): """ Convenience wrapper to take a series of date/time elements and return a WMI time of the form yyyymmddHHMMSS.mmmmmm+UUU. All elements may be int, string or omitted altogether. If omitted...
61d2bf9fb36225990ac0ac9d575c3931ef66e9f6
3,626,673
def plural(num, one, many): """Convenience function for displaying a numeric value, where the attached noun may be both in singular and in plural form.""" return "%i %s" % (num, one if num == 1 else many)
f29753d25e77bcda2fb62440d8eb19d9bd332d1e
3,626,674
def _handle_login_redirect(request, key): """ This function is used to redirect login request to Microsoft OneDrive login page. :param request: Data given to REST endpoint :param key: Key to search in state file :return: response authorization_url/admin_consent_url """ asset_id = request.GET.g...
7e18d4a0557bd03e39b7196cbf4d0d9f15dac586
3,626,675
def shape_element(element, node_attr_fields=NODE_FIELDS, way_attr_fields=WAY_FIELDS, problem_chars=PROBLEMCHARS, default_tag_type='regular'): """Clean and shape node or way XML element to Python dict""" node_attribs = {} way_attribs = {} way_nodes = [] tags = [] # Handle secondar...
0b1cf832731e3c4d8821a9fa5f7c54011d6fe0aa
3,626,676
import inspect def get_parent_module(): """Get parent filename.""" frame = inspect.currentframe() module = inspect.getmodule(frame) while module.__name__ == __name__: if frame.f_back is None: raise ValueError("Fell off the top of the stack.") frame = frame.f_back mo...
36c0a2c42e6eab7c68595c144d2b7c056ffa7918
3,626,677
from typing import Any import logging def log_response(response: str, trim_log_values: bool = False, **kwargs: Any) -> None: """Log a response""" return log_(response, response_logger, logging.INFO, trim=trim_log_values, **kwargs)
24929c959dac071fc313319cd651b110b6a328d5
3,626,678
def logged_in(browser: RoboBrowser): """ Returns true if we are still on the login page """ login_div = browser.find('div', content="Login") return True if not login_div else False
fb4211b21230df3e055b01fe7a6b70a56a89bb3e
3,626,679
def nan_dot(A, B): """ Returns np.dot(left_matrix, right_matrix) with the convention that nan * 0 = 0 and nan * x = nan if x != 0. Parameters ---------- A, B : np.ndarrays """ # Find out who should be nan due to nan * nonzero should_be_nan_1 = np.dot(np.isnan(A), (B != 0)) shoul...
4ac1629cf0517ecba7ebc4f3bd11775535ea955d
3,626,680
import os def get_log_files(): """ TODO: Document :return: """ files = set() for file in os.listdir(LOG_DIR): if file.endswith(".log"): files.add(os.path.join(LOG_DIR, file)) return files
93de992dbbd727b397a01c060bfc6947d63fa6bf
3,626,681
def metadata_record_validation_activity_show(context, data_dict): """ Return the latest validation activity for a metadata record. :param id: the id or name of the metadata record :type id: string :rtype: dictionary, or None if the record has never been validated """ log.debug("Retrieving ...
227ed9db7d97ffd399cde0b1f17e7376d8a423aa
3,626,682
def create_sample_lp(): """ Using gurobi create a sample LP. """ # Forest of 100 stands each assumed to be 1 ha in area stands = create_stands(100) # Minimum harvest age is 40 years, 10 year planning horizon schedules = schedule_generator(4, 10) # Track the age of each stand under eac...
564e68fdfa326f5e5ddc23bd593d1c1dca1a8bb4
3,626,683
import warnings def train_crabnet(model_name, csv_train, csv_val=None, val_frac=0.25): """ Function to train crabnet. This function allows a user to easily train crabnet by only supplying training data a model name. You can update epoch and batch size if desired. Parameters ---------- mod...
ae78009c10f4aa3fd441a81f998c94f05e43ef0c
3,626,684
import math import time def test_query_retry_maxed_out( mini_sentry, relay_with_processing, outcomes_consumer, events_consumer ): """ Assert that a query is not retried an infinite amount of times. This is not specific to processing or store, but here we have the outcomes consumer which we can us...
9339078c432cd087dcdbf799cad8d881defb41c2
3,626,685
def get_buckets(rdd, buckets): """Extracted from pyspark.rdd.RDD.histogram function """ if buckets < 1: raise ValueError("number of buckets must be >= 1") # filter out non-comparable elements def comparable(x): if x is None: return False if type(x) is float and i...
fe143075c8bd37702cbb23e76ea61ca32279ce32
3,626,686
def dollo_parsimony(phylo_tree, traitLossSpecies): """ simple dollo parsimony implementation Given a set of species that don't have a trait (in our hash), we do a bottom up pass through the tree. If two sister species have lost the trait, then the ancestor of both also lost it. Otherwise, the ancestor has the trait....
7929006e1625ba502642fcbd44c0dfff44569777
3,626,687
from datetime import datetime def localtime(t=None): """ localtime([seconds]) -> (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst) Convert seconds since the Epoch to a time tuple expressing local time. When 'seconds' is not passed in, convert the current time instead. Modifi...
9815211a160824c5e17b836a391a77a51647c648
3,626,688
def _to_bytes(str_bytes): """Takes UTF-8 string or bytes and safely spits out bytes""" try: bytes = str_bytes.encode('utf8') except AttributeError: return str_bytes return bytes
fd16c24e80bdde7d575e430f146c628c0000bf9a
3,626,689
import os def tile_num(fname): """ extract tile number from file name. """ l = os.path.splitext(fname)[0].split('_') # fname -> list i = l.index('tile') # i is the index in the list return int(l[i+1])
9f86598d5614fc986676491ad8b238960609148a
3,626,690
import random def extract_hidden_image(merged_image_path, mesg_image_path, secret_key): """ Unmerge an image. INPUT: The path to the input image. OUTPUT: The extracted hidden image. """ merged_img = Image.open(merged_image_path) message_image = Image.open(mesg_image_path) # Create the...
68c97dc7328abfa7e10f6db5aec1bd5fa8cc258f
3,626,691
from typing import Tuple import pytz def get_earliest_tables_last_updated_date(database_name: str, tables: Tuple[Tuple[str, str]]): """ Return the earliest of the last updated dates for a list of tables in UTC. """ with connections[database_name].cursor() as cursor: cursor.execute( ...
626c4407d2abfd4dd55ba3c5171b7390472c8bfe
3,626,692
def check_nested_model(required_attribute_type: str) -> bool: """ Takes the properties of a required attribute on a model and searches as to whether or not this attribute requires a model of its own Parameters ---------- required_attribute_type : str The type of the required attribute ...
f356476d6484fc52ade73a8ceda0bdefd39d31c4
3,626,693
def precision_and_recall(actual, predictions): """ Given predictions (an N-length numpy vector) and actual labels (an N-length numpy vector), compute the precision and recall: https://en.wikipedia.org/wiki/Precision_and_recall Hint: implement and use the confusion_matrix function! Args: ...
26d656884bbd708156dcd5a8a8658f3b15c3cc1e
3,626,694
import random from datetime import datetime def _insert_special_message(body): """Troll mode on special day for new pull request.""" tt = datetime.utcnow() # UTC because we're astronomers! dt = timedelta(hours=12) # This roughly covers both hemispheres tt_min = tt - dt tt_max = tt + dt # Se...
f466f5f6a198c37848ea2737f8d85dc8269eabac
3,626,695
def determine_host(environ): """ Extract the current HTTP host from the environment. Return that plus the server_host from config. This is used to help calculate what space we are in when HTTP requests are made. """ server_host = environ['tiddlyweb.config']['server_host'] port = int(serv...
6e91f93d5854600fe4942f093de593e53aaf2aa0
3,626,696
def gen_rand_sys(size): """ generate a grid with input size """ # Initialize grid with size grid = np.zeros(shape=(size, size), dtype=int, order='F') # Randomize grid randomize_sys(grid) # return the generated table return grid
694ca5181705b455968cd1e0d0042619738b6e33
3,626,697
def __get_size__(filename): """ Parses the filename to get the size of a file e.g. 128M+12, 110M-10 """ match = FILE_REGEX.search(filename) if match: size_str = match.group('size') si_unit = match.group('size_si') shift = __get_shift__(match) mul = 1 if si...
3aa192757ca94ca1e28b4881dd40897ad0aabd23
3,626,698
from pprint import pformat import sys def dbinfo(db, *patterns, **kw): """Gets types and lengths of keys matching given patterns. If any pattern is a list, then assumes it's a list of keys. Else, assumes it's a string and expands out using db.keys(). If no patterns are given, then processes all keys. ...
3b8a6288e5b66ad3305b6cc59d5e0c0b0c28e314
3,626,699