content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def app_env(): """ Create a dict of environment variables. Mirrors the testing environment for use in subprocesses. """ return { 'DB_HOST': TEST_DATABASE_CONFIG.host, 'DB_PORT': str(TEST_DATABASE_CONFIG.port), 'DB_NAME': TEST_DATABASE_CONFIG.name, 'DB_USER': TEST_DAT...
ebc4c3e000a916c5506655f96047dd4c53714853
51,246
def determine_key_type(bucket, key, profile): """Return values : 'File', 'Folder' or 'Does not exist'""" if profile: s3 = boto3.session(profile_name=profile).client('s3') else: s3 = boto3.client('s3') if not key: raise Exception("Cannot determine key type - no key is specified") ...
a3c2f70da06e1cb1757454b8e7b8cdb9a1ffdc00
51,247
def correct_brenda_dtypes(r: pd.DataFrame): """Make sure the columns have the right dtypes. :param r: dataframe of reports """ df_out = r.copy() float_cols = ["ph", "mols", "temperature", "km", "kcat"] for col in float_cols: if col in r.columns: df_out[col] = r[col].astype(f...
f5c083e3b4422df58dea5b4c6e797d2d04d2c0ab
51,248
def vmtkmarchingcubes(image, level=0.0): """Generate an isosurface of given level from a 3D image. Args: image: vtkImageData object. level: Graylevel at which to generate the isosurface. Returns: Surface mesh of the isosurface. """ marcher = vmtkscripts.vmtkMarchingCubes()...
32182ff8cee665008ce84c4a8c18b0dd7840f370
51,249
def _update_dict(d, **kwargs): """little helper to modify and return a dict in one line""" d.update(kwargs) return d
0a28c5f82d439ceb65aa3afc39d30a29b589004e
51,250
def svg_icon(loader, name, css_class=""): """ Return inline SVG markup for an icon. This is a helper for generating inline SVGs for rendering icons in HTML that can be customized via CSS. See https://github.com/blog/2112-delivering-octicons-with-svg To color an icon dynamically (eg. on hover),...
1cddcecc954c6d8956c7e029bd4a99c86a33d98b
51,251
def right_stop(G, adorn=True): """ Compute the (adorned) right stop of G. Parameters ---------- G : Game The Game of interest. adorn : bool Whether to adorn the stop or not. Defaults to True. Returns ------- RS : Game The right stop of G. initiative : st...
1c1c48cfacd1b86511b38fb91694cc892a9dbae4
51,253
def value_and_multigrad(fun, argnums=[0]): """Returns a function that returns both value and gradients wrt multiple arguments simultaneously.""" def combined_arg_fun(multi_arg, *args, **kwargs): extra_args_list = list(args) for argnum_ix, arg_ix in enumerate(argnums): extra_args_...
5d55a547c6309d2db3324ebd05fe19f1c9d6c1f0
51,254
def deploy_disk_image(address, port, iqn, lun, image_path, node_uuid, configdrive=None, conv_flags=None): """All-in-one function to deploy a whole disk image to a node. :param address: The iSCSI IP address. :param port: The iSCSI port number. :param iqn: The ...
0eb796b5089597c916393bbbaf6f314460a8a856
51,255
from typing import Union from pathlib import Path from typing import Dict from typing import Tuple def read_tracking_data_txt( filepath_txt: Union[str, Path], links: Dict[str, Dict[int, int]] = None, ) -> Tuple[XY, XY, XY, XY, XY, XY]: """Parses a StatsPerform .txt file and extracts position data. I...
8ba9f17374eea860fa434e170e7d1ca6b6b22f9a
51,256
from typing import Optional from typing import Union from typing import List from typing import Dict def _estimate_segments(df: pd.DataFrame, target_field: str = None, max_segments: int = 30) -> Optional[Union[List[Dict], List[str]]]: """ Estimates the most important features and values on which to segment ...
ebdd75b64616da497a73004d502acd320322935b
51,257
def show_images(images, file_to_save, cols=1, titles=None): """Display a list of images in a single figure with matplotlib. Parameters --------- images: List of np.arrays compatible with plt.imshow. cols (Default = 1): Number of columns in figure (number of rows is set to n...
14f31b182ef2c80d1da720461cb994cb15b2493a
51,258
def WT_EC50s(unkVec_2_15, Traf=True): """Returns dataframe of the Wild Type EC50s""" df = pd.DataFrame(columns=["Time Point", "Cell Type", "IL", "Data Type", "EC50"]) x0 = [1, 2.0, 1000.0] tps = np.array([0.5, 1.0, 2.0, 4.0]) * 60.0 data_types = [] cell_types = [] EC50s_2 = np.zeros(len(cel...
88f8f57617ec9666a8c574e289bfccbcee0ee461
51,259
def implicit_op(op): """ implicit constant operand promotion """ if isinstance(op, ML_Operation): return op elif isinstance(op, SollyaObject) or isinstance(op, int) or isinstance(op, float): return Constant(op) elif isinstance(op, ML_FloatingPointException): return Constant(op, p...
31e7c36d47e8885631b79d74ae1cfb003f5fd848
51,260
def ToHex(data): """Return a string representing data in hexadecimal format.""" s = "" for c in data: s += ("%02x" % ord(c)) return s
1566962a89967ae0d812ef416d56867a85d824fb
51,261
def set_legend(ax, size=12, color=COLORS['black'], alpha=ALPHAS['translucent'], loc='best', frame=False, ncol=1, nscatter=1, **kwargs): """ Add and modify legend settings. :param ax: (mpl.axes) - plot axis :param size: (str) - size of legend labels :param color: (str) ...
e40db57e44692eb2c4852f3e173eef2f0cf137a9
51,262
from typing import List from typing import Tuple def fill_missing_test(parameters: List[Parameter]) -> Tuple[str]: """Convenience function for testing job parameter fill missing""" param_set = JobParameterSet(parameters) param_set.fill_missing_parameters() return ( param_set.get_param_by_type(...
5ef2566d535ef8dc877430337ecadc78d142a240
51,263
def test_PostPlot(): """Validation of the PostPlot class to plot airgap flux automatically as postprocessing at the end of the simulation""" IPMSM_A = load(join(DATA_DIR, "Machine", "IPMSM_A.json")) simu = Simu1(name="PostPlot", machine=IPMSM_A) # Definition of the enforced output of the electrical m...
111e2ef836659057e3db452a1bcf3309caa8bf6e
51,265
from datetime import datetime def parse_date(date_str: str, sep: str = None, format: str = None) -> datetime.date: """Returns a ``datetime.date`` if possible Args: date_str (str): The date which may not be in standard ISO format sep: Optional. The separator used to separate each time unit ...
0b6725b60cd8ce945a2c5d625bc5afe911f88c04
51,266
def scrub_properties(orig_props): """Scrubs fields in API object properties for use in DM properties. Scrubbed fields include: - output-only fields common for most resources - output-only fields specific to a particular resource type Args: orig_props: the resource properties that need to be scrubbed ...
d34d115c685123f88d921abc0d0a88bc49ed9bc3
51,267
def _trend_grid(concentration_cube, weight_cube, *, clipping_threshold): """Build a grid for a decadal trend.""" assert concentration_cube.shape == weight_cube.shape assert clipping_threshold rows, cols, periods = weight_cube.shape # Flatten rows and cols of the concentration/weight cubes # A ...
24b76b0959713c837e7288faced8d98e15f274e1
51,268
def uniquify_reference_names(comp): """Replaces all the bound reference names in `comp` with unique names. Notice that `uniquify_reference_names` simply leaves alone any reference which is unbound under `comp`. Args: comp: The computation building block in which to perform the replacements. Returns: ...
e5022b9ac377ff5397101ab75570faf0137f7dd7
51,269
def load_csv_data(train_path, test_path=None, sep=',', nrows=None, x_cols=None, y_cols=None, drop_cols=None, onehot_cols=None, n_cols=None, random_cols=False, shuffle=False, scaling=None, dtype=None, validation_split=None, return_dataframe=True, ...
9a873f0a7acf7f39675f6865b9cda79c82613908
51,270
def fclayer(in_features, out_features): """ fully connected layers or dense layer :param in_features: input_dimension => channels * features :param out_features: output_dimension :return: (batch, windows, channels * features) => (*, *, output_dimension) """ fc = nn.Linear(in_features, out_fe...
a723222d4ef045e329079832073302c077622761
51,271
def visual_mask(mask_img=None, mask_path=None): """ :param mask_path: :param palette: :return: """ palette = get_palette() if mask_img is None: mask_img = Image.open(mask_path) else: mask_img = Image.fromarray(np.array(mask_img, dtype=np.uint8)) mask_img.putpalette(p...
c65b612412b8c7ad6930da127a7a09dc6bb3e2e2
51,272
from typing import Callable def window_replaced_message(callback: Callable[[HWND, HWND], None]) -> MessageEntry: """Listens for when a window is hung, and needs to be recreated. The first HWND will be set to the HWND of the new window handle, and the second is the HWND of the replaced window. The cal...
01404005f7591673509fc6ae0891a941c533df7d
51,273
from typing import Iterable def get_sse_mat(mats: Iterable[sp.spmatrix]) -> sp.spmatrix: """ Given multiple matrices, return the matrix of position-wise sum of squared errors to median. All input matrices must have the same shape, nonzero coordinates and format. Output matrix will have the same format...
8fb8bd6b4ef162399a2ef87fd9a7377910302fc7
51,274
def energy_sum( df: pd.DataFrame, network: NetworkSchema, power_column: str = "generated" ) -> pd.DataFrame: """Takes the energy sum for a series of raw duid intervals and returns a fresh dataframe to be imported""" # These are the networks that run through the compat func COMPAT_NETWORKS = [Networ...
a4733c70f6e3d710e2d5f83a33aafd1b6ba01b39
51,275
import unicodedata def tokenise_word(string, strict=False, replace=False, tones=False, unknown=False): """ Tokenise the string into a list of tokens or raise ValueError if it cannot be tokenised (relatively) unambiguously. The string should not include whitespace, i.e. it is assumed ...
0c2ed6fc6f0f3748b63922a7743da3350ba58f4f
51,276
def latsrf(method, target, et, fixref, lonlat): """latsrf(ConstSpiceChar * method, ConstSpiceChar * target, SpiceDouble et, ConstSpiceChar * fixref, ConstSpiceDouble [1][2] lonlat)""" return _cspyce0.latsrf(method, target, et, fixref, lonlat)
a8f8705918caedb7477e6fa022fc1deead6cf6e6
51,277
def _parse_common(xml, the_dict): """ Parse things in common for both variables and functions. This should be run after a more specific function like _parse_func or _parse_variable because it needs a member dictionary as an input. Parameters ---------- xml : etree.Element The xml re...
a6606366ce9b0e4d2c848b16bc868532684b4abe
51,278
import collections import itertools def sliding_window(n, seq): """ Copied from toolz https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window A sequence of overlapping subsequences >>> list(sliding_window(2, [1, 2, 3, 4])) [(1, 2), (2, 3), (3, 4)] This functi...
67e65fa6690ecc6974713a0559d596718e7c6361
51,279
def change_course(request, pk): """ Изменение данных в курсе """ course = get_object_or_404(Course, pk=pk) if request.method == 'POST': form = CourseForm(request.POST, request.FILES, instance=course) if form.is_valid(): course = form.save() for csa in CourseStudentAc...
64c244eee6ea687d88757a621809f0b90f911229
51,280
def interaction(multiindex): """ Return tuple of interaction between variables which this multiindex represents. Eg. (a) (1,1,1) -> (), (b) (1,2,1) -> (1,), (c) (2,3,1) -> (0,1) Tuple is always ordered smallest dim-index to largest. """ return tuple(np.where(np.array(multiindex, dtype=np.int8)...
28dbe2161bc30f4bfba72625434b7d170b68722f
51,281
def home(request): """Dashboard home.""" return render( request, 'dashboard/home.html', { 'quests': Questionnaire.objects.filter( created_at__year=date.today().year, ) }, )
765582081a8d23a90dad7962a662f325be608203
51,282
def get_entities(config): """ Get a dictionary of lambda functions that create entity URLs :param config: dict :return: dict """ server = config['api'] entities = dict(project=lambda project: server + '/projects/{0}'.format(project), subject=lambda project, subject: serve...
2fa3aa0d42ecb027dee4f2610c5eaf5c72f55d44
51,283
def crypto_secretbox(message, nonce, key): """ Encrypts and returns the message ``message`` with the secret ``key`` and the nonce ``nonce``. :param message: bytes :param nonce: bytes :param key: bytes :rtype: bytes """ if len(key) != crypto_secretbox_KEYBYTES: raise exc.Valu...
6ce8bc311427e52568110bccec6747cc6b5f3149
51,284
def create_bins(bin_info_list, shuffle): """Creates a list of bins based on a string list of bin info.""" bins = [] for bin_info in bin_info_list: bins.append(DataBin(bin_info[0], bin_info[1], shuffle)) return bins
89273361df4fd8e1dff6145400685faf5a788818
51,285
def getEmissionSelf(dataDirBase, NCVariable, RCPScenario, decade): """This function uses makeEmissionNCFile() to get the nc file path of the desired species arguemnt and returns the nc connection to that species. Parameters: Same as makeEmissionNCFile() dataDirBase: Working hardrive NCVariable...
b4f93bc4266020a4044a3a1f4c4cf50a288402e8
51,286
def from_plus(path): """ Given the path to a CoNLL-U Plus file, return the corresponding plain CoNLL-U string. """ with open(path) as f: plus_fields = [field.upper() for field in parse_conllu_plus_fields(f)] plus_content = f.read() plus_sentences = parse(plus_content, plus_f...
d2c7e8dccf63c0d90416dbff7237cc6b7f6216a3
51,287
def __coord_n(n, **_kwargs): """Get bare positions""" return np.arange(n + 1)
697963a802598e4d3d1ec20c610760398eecbf3f
51,288
def vectorized_gaussian_logpdf(X, means, covariances): """ Compute log N(x_i; mu_i, sigma_i) for each x_i, mu_i, sigma_i https://stackoverflow.com/a/50809036/8395138 Args: X : shape (n, d) Data points means : shape (n, d) Mean vectors covariances : shape (...
80dfd7618647e2b00ff5b98693820aad5226c342
51,289
def elementWise(A, B, operation): """ execute an operate element wise and return result A and B are lists of lists (all lists of same lengths) operation is a function of two arguments and one return value """ return [[operation(x, y) for x, y in zip(rowA, rowB)] for row...
39e78ca7730bf8367daf3a55aeb617b2c0707a44
51,290
def create_test_baymodel(context, **kw): """Create and return a test baymodel object. Create a baymodel in the DB and return a BayModel object with appropriate attributes. """ baymodel = get_test_baymodel(context, **kw) try: baymodel.create() except exception.BayModelAlreadyExists: ...
eeed0905d907856593faa2b992492cbb0250b4fc
51,291
def test_forward_with_parameter_in_sub_cell(): """ Feature: Custom cell bprop Description: Get the gradients of inputs when the forward net using Parameter in the sub-cell. Expectation: Get the correct gradients. """ class Net(nn.Cell): def __init__(self): super(Net, self)._...
aaf570a83c29ec98e09b96377c2179a869f1d89c
51,292
def _GetRollbackRelease(release_id, pipeline_id, target_ref): """Gets the release that will be used by promote API to create the rollback rollout.""" ref_dict = target_ref.AsDict() if release_id: return resources.REGISTRY.Parse( release_id, collection='clouddeploy.projects.locations.deliveryPi...
a2d978093a4475df07a3dd56816c0a914daf5a58
51,293
def find_spaces(string_to_check): """Returns a list of string indexes for each string this finds. Args: string_to_check; string: The string to scan. Returns: A list of string indexes. """ spaces = list() for index, character in enumerate(string_to_check): if character == ' ': spaces.ap...
8bcd1d9911efab3c65e08524293b11afd449efa0
51,295
def calculate_activation_statistics(images, batch_size): """Calculates the statistics used by FID Args: images: torch.tensor, shape: (N, 3, H, W), dtype: torch.float32 in range 0 - 1 batch_size: batch size to use to calculate inception scores Returns: mu: mean over all activation...
9d1760c3aba636004bf158d2efaf021a035484a6
51,296
def _should_recurse(start, config_lines, initial_indent): """Sometimes object are not expected to document every parameter and contain all the description at the top. This is valid, therefore we should not recurse and analyze what's next after the whole object. Returns whether or not to recurse as long a po...
a89c5a641f13cba8b487a1e41b707450a5998e00
51,297
def unwrap_eth(): """ Withdraw ETH by depositing wETH """ account = get_account() # Need to get the ABI and the Address of the contract weth = interface.IWeth(config["networks"][network.show_active()]["weth_token"]) # Deposit amount = 0.1 tx = weth.withdraw( Web3.toWei(amo...
277bbf8a23e5d0d14f27e53b5d7787e9b6f991b2
51,298
def client() -> User: """Construct the User (client) class""" return User(username=USERNAME, auth=AUTH)
8c217f2ed6cd4a5e60948bdfcac1594b28e2197f
51,299
from typing import OrderedDict def dict_from_lst(lst, ordered=False): """ Return a dictionary from a Geosoft `geosoft.gxapi.GXLST` instance. :param lst: `geosoft.gxapi.GXLST` instance :param ordered: True to return an OrderedDict :returns: python dictionary from a Geosoft GXLST ...
54c87468f6eb633fda64d1373dc7a8c621d7991b
51,300
def parse_external_id(output, type=EXTERNAL_ID_TYPE_ANY): """ Attempt to parse the output of job submission commands for an external id.__doc__ >>> parse_external_id("12345.pbsmanager") '12345.pbsmanager' >>> parse_external_id('Submitted batch job 185') '185' >>> parse_external_id('Submitte...
9af3c73ffbfeac3273251230fe220f381b402214
51,301
def ldns_pkt_set_ra(*args): """LDNS buffer.""" return _ldns.ldns_pkt_set_ra(*args)
159dde50ee549980a2a92d21f5dce23327c4d6b3
51,302
def rehash(path, blocksize=1 << 20): # type: (str, int) -> Tuple[str, str] """Return (encoded_digest, length) for path using hashlib.sha256()""" h, length = hash_file(path, blocksize) digest = 'sha256=' + urlsafe_b64encode( h.digest() ).decode('latin1').rstrip('=') # unicode/str python2 ...
15c1f620d45cef116af6c221b326a208ab27acc4
51,303
import re def CombineLogFiles(list_of_lists, logger): """Splices together multiple logcats from the same device. Args: list_of_lists: list of pairs (filename, list of timestamped lines) logger: handler to log events Returns: list of lines with duplicates removed """ cur_device_log = [''] for...
a749e34e63163c8493e0d4923e78367a6396327f
51,304
from typing import Callable from typing import Any def step_decrease(f: Callable[[Any], Any], x, step=1e-2, step_multiplier=2, iteration_limit=100000000): """ Continues to increment x with x + step till f(x) returns a value that is bigger than the previous value i.e stop when f(x) > f(x+s) step on...
03b08e33ac6eaacc1e6939f9239058d90b9a6b04
51,305
def lcs_naive(first: str, index_f: int, second: str, index_s: int) -> int: """ Time Complexity: O(2^n) """ if index_f < 0 or index_s < 0: return 0 if first[index_f] == second[index_s]: return 1 + lcs_naive(first, index_f - 1, second, index_s - 1) return max( lcs_naive(f...
be2ef4013732d75ab14c69e8f93d38cc7f011e7c
51,306
from typing import List def cf_explain(examples: List[Example], nmols: int = 3) -> List[Example]: """From given :obj:`Examples`, find best counterfactuals using :ref:`readme_link:counterfactual generation` :param examples: Output from :func:`sample_space` :param nmols: Desired number of molecules """...
ebaadd0d7d235bcece99257e6d0debd02f6bb79a
51,308
def quantile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False): """ Compute the q-th quantile of the data along the specified axis. ..versionadded:: 1.15.0 Parameters ---------- a : array_like Input array or object that can be convert...
30af34a0806daf25370bb202aa2fe6dd6d2b5cb2
51,309
def build_classifier(img_shape, num_classes): """ Function: build_classifier Input: img_shape: image shape, num_classes: the number of image classes Output: CNN-based classifier model """ cinput = Input(shape=img_shape, name='classifier_input') H = Conv2D(64, kernel_size=(5, 5), acti...
ead6fa1190bf8a2e79b2f2b354853072ca5a7513
51,310
def filter_pair_by_len(p, maxlen=c.MAX_LENGTH): """ Filter out sentences if they are greater than maximum length. """ return len(p[0].split(" ")) < maxlen and len(p[1].split(" ")) < maxlen
6e659746f193b3a420fd8189f324b166d4374b70
51,311
def run_model(params, rollout_size=50, num_steps=50): """Perform the training operation. Parameters ---------- params : dict flow-specific parameters (see flow/utils/registry.py) rollout_size : int length of a single rollout num_steps : int total number of training steps...
86786ac27de7b4bd9a9ec75de745dfb45a00edf0
51,312
def func_lineno(func): """Get the line number of a function. """ try: return func.compat_co_firstlineno except AttributeError: try: if PYTHON_VERSION_MAJOR == 3: return func.__code__.co_firstlineno return func.func_code.co_firstlineno excep...
884f4fdfeeb22634d46f4f2651b0c5f93cb687e0
51,313
def calc_cl_metrics(acc_matrix): """ Calculate metrics based on an accuracy matrix of N train tasks on N test tasks The lower triangular matrix is the BWT, the higher triangular matrix is the FWT The metrics below are taking into account the accuracy of the model at every timestep / task by dividin...
4b1a1e12a6e2f06227f244ec8ba882ee634b135a
51,314
def ElectricField(q, r0, x, y): """ Return the electric field vector E=(Ex, Ey) due to charge q at r0. """ den = np.hypot(x - r0[0], y - r0[1]) ** 1.5 return q * (x - r0[0]) / den, q * (y - r0[1]) / den
76aee7a4c8c0254eee8fc0c99793c86d501514fe
51,315
import shelve import contextlib def readMirror(fileLocation): """Returns saved Model (mirror) from Pickled file at 'fileLocation' Needed to transfer model from IPY to PY3 """ #f = open(fileLocation,"rb") with contextlib.closing(shelve.open(fileLocation, 'r')) as shelf: mir = shelf['...
f6d6c56dbe99d544ccdc041f35e48e87883166c8
51,316
import json import httpx def get_api_es_client(session): """ Returns an Elasticsearch client for the catalogue cluster. """ secrets = session.client("secretsmanager") credentials = json.loads( secrets.get_secret_value(SecretId="elasticsearch/api_cleanup/credentials")[ "SecretS...
5adcdb58a8eabe8d84834f730ab080a2f0b227c9
51,317
def insertionsort(x, count = False): """ For each element e of x, move through the array until you come to a value that is less than e, or the end of the array, then place e at the new location. """ assignments, conditionals = 0, 0 for i in range(1, len(x)): element = x[i] j = i...
4a8ae9bda1dfee0cb41ae7544cb45d089e11f703
51,319
def vm_impl_concatOffset(self): """Generate vm_impl function for ConcatOffset""" def vm_impl(x): out = vm.ConcatOffset(x) # out is tuple return out return vm_impl
533041af510acf55c1337f6c2052053aa9669645
51,321
import requests def get_assimilator_data(mode, assimilator, text, link): """ This function is used for get parsed web/local document from a Tika-service mode: get metadata or content body assimilator: api address of the text assimilator, running apache tika text: piece of raw text link: web ur...
4af3970f8fd51e565c0d6bc5c2e92bf29eac98f5
51,322
def list_channel_messages_since_delta(session, *, deltaLink): """List channel messages for the team and channel session = requests.Session() instance with Graph access token deltaLink = the leftover delta you were given the last time you called list_channel_messages_since_time we will p...
fc51b10d6cbd5207d150fa5579c3c367f77a09ba
51,323
def get_default_title(): """ See description in Bootloader class below """ return __bootloader.get_default_title()
13ca4ce0e74994f993830c20ca6b0bb920918998
51,324
def parse_config(app): """Process the Sphinx Gallery configuration""" try: plot_gallery = eval(app.builder.config.plot_gallery) except TypeError: plot_gallery = bool(app.builder.config.plot_gallery) src_dir = app.builder.srcdir abort_on_example_error = app.builder.config.abort_on_exa...
c90f17a7e6912fc94f9b97463db2ec570c9d0aab
51,325
import json def get_leader(cluster_name, role_type): """ :param cluster_name: 集群名称 :param role_type: 角色类型 :return: overlord or coordinator """ cluster = model_manager.get_cluster_obj_by_name_type(cluster_name, DRUID) conn_info = json.loads(cluster.connection_info) zk_addr = conn_info[Z...
8d83f2f9625b92e4f1b355eaac5dd8e503155b7b
51,326
from typing import Any def _async_get_diagnostics( hass: HomeAssistant, entry: ConfigEntry, ) -> dict[str, Any]: """Return diagnostics for a config entry.""" pv_entry: PowerviewEntryData = hass.data[DOMAIN][entry.entry_id] shade_data = pv_entry.coordinator.data.get_all_raw_data() hub_info = as...
fa6cd381a0b2a2578fa8aaa9276715deb70e8de9
51,327
import requests import logging def execute_dax_query(credential, dataset_id, daxQuery): """Execute DAX query""" url = f"https://api.powerbi.com/v1.0/myorg/datasets/{dataset_id}/executeQueries" try: token = credential.get_token("https://analysis.windows.net/powerbi/api/.default").token ...
9adcd81d0bcfc642b0c0336d351f5ad9b71aad7a
51,328
import time def wait_for_tasks(session, tasks, timeout): """returns true if all tasks are no longer pending (ie success/failure/cancelled) and false if a timeout occurs""" finished = False start = time.time () while not(finished) and ((time.time () - start) < timeout): finished = True ...
8a4652060621ce3a7f3890578dea307f7e9bc8b5
51,330
import requests import json def get_previous(pair, end, qty): """get the previous pairs Arguments: pair {string} -- the name of the pair eg. EOSUSD end {int} -- time of the last records to request qty {int} -- the number of records to request Returns: list -- qty prices b...
f09845b2ae75e7ae3f9eca1da26f2d88790a1478
51,331
import copy def handle_multiple_variantcallers(data): """Split samples that potentially require multiple variant calling approaches. """ assert len(data) == 1 callers = get_variantcaller(data[0]) if isinstance(callers, basestring): return [data] elif not callers: return [] ...
93ea4dff458ad2aa937e776fe45acfca3d91298e
51,332
import yaml import re def guess_host_name(): """ Just a handy function for external use """ with open(join(package_path(), 'paths.yml')) as f: loc_by_name = yaml.load(f, Loader=yaml.FullLoader) for ld in loc_by_name.values(): if 'host_pattern' in ld: if re.match(ld['host_pa...
1d5d0503f4ac28d6bb96ad12469c19931065c082
51,333
def main(): """Runs the tests.""" defaults = { 'TEST_ID': 'MySimpleTest-' + KeystoreTestScenario.DEFAULT_TEST_ID } return citest.base.TestRunner.main( default_binding_overrides=defaults, test_case_list=[SynchronousKeystoreTest])
d7c51db5bf56de8f5c923b9c968707bb7962a61a
51,335
def get_maze(filename): """ Convenience function to get a grid from a file. Takes the filename of the maze to load, loads the maze from the file, and builds it into a grid. Then returns that grid. Args: filename: the file to load the maze from Returns: the grid representation ...
c9d0d3c3d7501afd4cd4a2fe178ad3f26877dfc3
51,336
def get_loss(name): """Returns loss_fn(outputs, ground_truths, **kwargs), where "outputs" are the model outputs. Args: name: The name of the loss function. Returns: loss_fn: A function that computes the loss between the inputs and the ground_truths Raises: ValueError: If Preprocessing `name` is n...
33ef3a864ded30265cf3641ace5128c6271333cc
51,337
def get_processed_invoices_df(): """ this function will read the dataframe and create a text string for each row separated by new line '\n' to match with resultant data for testing. """ process_invoices = spark.sql("select * from processedInvoiceTbl") text = "" for i in range(1, process_in...
e3ee7d2bc0880f1f8bd0fbd55338228814c01c2c
51,338
def resistance(v='x', i='x', p='x', l='x', a='x', pw='x'): """ Calculate and return the value of resistance using given values of the params How to Use: Give arguments for v and i params, or, give arguments for p,l and a params, or, give arguments for pw and i params or, giv...
d411cc6bb348e66d0f4eedab3a6ae7550a4cd4a7
51,339
async def edit_a_group(id: int, group: Group): """Updates the information stored about a group.""" updated_group = await Group.edit(id, group) if not updated_group: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="group not found.") return updated_group
e0e4d5faaf1cb9b071c899ab165c37cc6925bbfa
51,340
from typing import AnyStr from typing import Tuple def derive_password(password: AnyStr) -> Tuple[bytes, bytes]: """ Args: password: Password Returns: Encryption key, Mac key """ if isinstance(password, str): password = password.encode() tmp = PBKDF2HMAC(hashes.SHA25...
8b3268006d556bcd97c936ce0390ab18ecb12939
51,341
def get_setting(varname): """ Returns the value of a configuration variable. """ gl = globals() if varname not in gl.keys(): raise ValueError("Unknown setting %s"%varname) # Here, possibly add some code to raise exceptions if some # parameter isn't set set properly, explaining on how to set...
ed5d831a7f96439dfe8439750c96062eae434f43
51,343
def get_lr(curr_epoch, hparams, iteration=None): """Returns the learning rate during training based on the current epoch.""" assert iteration is not None batches_per_epoch = int(hparams.train_size / hparams.batch_size) if 'svhn' in hparams.dataset and 'wrn' in hparams.model_name: lr = step_lr(hp...
ebe5dc79bc03007dbffa8ee5c8d878d10cb5e690
51,344
def _timestamp_to_date_string(timestamp: pd.Timestamp): """Return a date-string (YYYY-MM-DD) from a pandas Timestamp.""" if timestamp.tzinfo: timestamp = timestamp.tz_convert('UTC') timestamp = timestamp.tz_localize(None) date = pd.Timestamp.date(timestamp) if pd.Timestamp(date) != timestamp...
c6b69be196cec2a0d3c9a7a246307227f6faba18
51,345
def beta_tcon(s_gkg,t_cels,p_dbar,tp_cels=None,chkvals=False, chktol=_CHKTOL,tp_cels0=None,chkbnd=False,useext=False, mathargs=None): """Calculate haline contraction wrt conservative temperature. Calculate the haline contraction coefficient of seawater at constant conservative temperature. ...
af4e6bb6903644ec7f25771240723b14429b1aaf
51,346
def workspace_list_table_format(result): """Format workspace list as a table""" table = [] for item in result: table.append(workspace_show_table_format(item)) return table
b8af25ff21930bed92fec15e4f11323f3270a3b9
51,347
def get_items(wiki, only_undone=False) -> list: """ all items page list """ items = [] for page in wiki.pages(): content: str = wiki.page_info(page["pageid"])["*"] if content.startswith("{{面包屑|物品信息"): if only_undone and content.find("{{施工中}}") == -1: continue ...
1637c04aa61f5efe882af6c7f1bed80c3cde3185
51,348
def cycle(n): """Return the cycle graph on n vertices.""" return circulant(n, [1])
25ea83b0c61fb653caca6e899dfade52304df8e7
51,349
from typing import Any def _attempt_cast_as_float(value: Any) -> float: """ :param vale: a value :return: the value as a float if casting is possible, otherwise return 1 """ try: return float(value) except (ValueError, TypeError): return 1.0
8616bf4d59a08f8e98d26231f7aa51d419d52550
51,350
from typing import Any from typing import Dict from typing import List import json def adjust_dict_property(property_value: Any, model_field: ModelField, depth: int): """Convert a dict property for the BigQuery schema""" dict_value_type = ModelFieldUtils.get_dict_value_type(model_field=model_field) # Scal...
29df072365e0c0b216744f790b627c868dbcd81e
51,351
def show_permission(permission_id): """Get permission.""" data = _get_request_args() return utils.make_json_response( 200, permission_api.get_permission(permission_id, user=current_user, **data) )
c1f06c1c055d09bc195323e2a66b74ae06dc9fd9
51,353
import gzip def train_markov_gz(fn): """ trains a Markov model on gzipped text data """ with gzip.open(fn, "rt", encoding="utf-8") as f: text = f.read() return markovify.Text(text, retain_original=False, state_size=3)
dfd6470cef3254f3521d62d81c96afc61b781418
51,354
import sqlite3 from typing import List from typing import Any from typing import Sequence from typing import Optional from typing import Type from re import T from typing import Tuple def execute_sql_by_id(db: sqlite3.Connection, sql: str, sql_values: List[Any], ids: Sequence[T2], return_type: Optional[Type[T...
beabdfaca28e78d9633b137ce98aceed64bdc9ae
51,355