content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def store_tweets(statuses): """ Stores the tweet in the mongoDB :param tweet: dict or list of dicts to store """ if isinstance(statuses, dict): statuses = [statuses] try: result = db.tweets.insert_many(statuses, ordered=False) return result except BulkWriteError as ...
7349074c4c0087a333b3a7385585e85b1ce57b83
3,618,300
def test_func(G, p0, q0, bif_type): """ Parameters ---------- """ q0 = np.zeros(q0.shape) q0[0] = 1 p0 = np.zeros(p0.shape) p0[0] = 1 return bordered_system(G, p0, q0, bif_type)
99f59e76e912565e54254d7e1238b66fd814846d
3,618,301
from typing import List def build_actions_embed(actions: List[LoggingActions]) -> discord.Embed: """ A method that generates an embed detailing with LoggingActions are currently enabled. Parameters: actions (List[LoggingActions]): A list of currently enabled logging actions. Returns: ...
bc9c452aea4d70456d24f24cd4d5fc7fd8135502
3,618,302
import os def add_derived_cols_to_modeldata(dfmodel, derived_cols, dimensions=None, t_model_init_seconds=None, wid_init=None, modelpath=None): """add columns to modeldata using e.g. derived_cols = ('velocity', 'Ye')""" if dimensions is None: dimensions = get_dfmodel_d...
7d4e079daa464e35396373a05adcd20197983b1d
3,618,303
def get_tag_for_physical_resolution(res): """Input a physical resolution string or value, output a formatted string tag to be used in filenames. """ check_flag, res_value = is_physical_resolution(res, return_value=True) if check_flag: sigfigs = 0 fmt_str = '{:.%df}'%(sigfigs) res...
3db530e14f6bc5894ac63a58c6e5f1f580e8d62e
3,618,304
def search_dnb(query_params): """ Queries the dnb-service with the given query_params. E.g.: {"duns_number": "29393217", "page_size": 1} {"search_term": "brompton", "page_size": 10} """ if not settings.DNB_SERVICE_BASE_URL: raise ImproperlyConfigured('The setting DNB_SERVICE_BAS...
64a1034398b65f48dd7adf8f0169ab5e609bf901
3,618,305
def connect_to_zone(zone, access_key_id, secret_access_key, lowercase=True): """ Connect to one of zones in shanhe by access key. """ if lowercase: zone = zone.strip().lower() return APIConnection(access_key_id, secret_access_key, zone)
757ab871338e08fdca4dac1a5950dda88f56101d
3,618,306
import re def compare_versions(value, required, verbose): """Compares the numerical value of two dot-separated version strings :type value: str :type required: str """ # allow for unexpected input for value. # required is within our control. val = [int(x) for x in re.split(r"\D+", value)...
636550b35235dcb661e78cc38df3d856fcd263ae
3,618,307
def single_resonance_statistics(r): """ Compute global, sequence-specific ncIDP-based chemical shifts using resonance list """ seq = sequence.molecule_sequence(r.condition.molecule).one_letter_codes path = get_sparky_home()+'/Python' prediction = compute_RC(path+'/ncIDP-cs.tab', path+'/ncIDP-dev.tab', seq...
ba19d8b338a7bcf36d668810fba8503b93af3751
3,618,308
def get_response(message, code): """ Create a response. Args: message (str): The message to include in the response code (str): The return code to include in the response Return: a dict, if present key = 'Accept' """ response = HttpResponse(status=code) # pylint: d...
9f7adc270d8d4183b93664bb705482abbd577d79
3,618,309
def rk4(data, critic, step, num_step = 1): """Assumes data is a batch of images, critic is a Kantorovich potential, and step is desired step size. Applies fourth order Runge-Kutta to the data num_step times with stepsize step/num_step. Unused in TTC""" h = step/num_step for j in range(num_step): ...
11f4892e1b91b2f50823d6865cdbd4420a965735
3,618,310
def configure_subinterfaces_for_vlan_range( device, interface, vlan_id_start, vlan_id_step, vlan_id_count, network_start, network_step,host_address_step, netmask, ospf_network_type=None): """ Configures multiple subinterfaces looping through vlan range Args: device ('obj'): Device t...
127c592acc36d98425bbfde529efd712457f64d1
3,618,311
import logging from datetime import datetime def post_new_patient(): """This is the function that receive the post request fom patient client The in_data is sent by the patient side client. It is a dictionary with the following keys: "patient_name" (str): the uploaded patient's name "MRI" (str): ...
a0325f5ca13497c7b1c4a23c806eed0f5680f68f
3,618,312
def weighted_scalarizer(xs: np.ndarray, ws: np.ndarray) -> np.ndarray: """A simple linear weight based scalarizer. Args: xs (np.ndarray): Values to be scalarized. ws (np.ndarray): Weights to multiply each value in the summation of xs. Returns: np.ndarray: An array of scalar...
73dcc450fe59fdcd81e80d6da6681b3cfc92c858
3,618,313
def blueschist_felsic(): """ Elastic constants of Felsic Blueschist (GPa) from Cao et al. (2013), in Voigt notation - Abbreviation: ``'BS_f'`` Returns: (tuple): tuple containing: * C (np.ndarray): Elastic stiffness matrix (shape ``(6, 6)``) * rho (float): Density (2...
96243d1ff842d01838e5be0e7f1f8b5205432d72
3,618,314
def ensure_wide_weights_is_1D_or_2D_ndarray(wide_weights): """ Ensures that `wide_weights` is a 1D or 2D ndarray. Raises a helpful ValueError if otherwise. """ if not isinstance(wide_weights, np.ndarray): msg = "wide_weights MUST be a ndarray." raise ValueError(msg) ndim = wide_w...
28757950b28d37edad7796daed8ec9803a4aad9a
3,618,315
def LMPR_complexity(dist, rvs=None, rv_mode=None): """ Compute the LMPR complexity. Parameters ---------- dist : Distribution Distribution to compute the LMPR complexity of. rvs : list, None The indexes of the random variable used to calculate the LMPR complexity. If Non...
49de6fc709f4894298e013b9a319381308aceccd
3,618,316
from typing import List async def read_users( skip: int = 0, limit: int = 100, db: Session = Depends(get_db), token: str = Depends(oauth2_scheme) ) -> List[User]: """ Read all users with all the information: - **skip**: Number of records to be skipped ...
55e9ee59e7aca321209bc10b6785d315e0f136e9
3,618,317
import typing def load_private_key( data: bytes, passphrase: typing.Optional[bytes] = None, ) -> RSAPrivateKey: """Loads the private key and returns a Key interface. If the private key was not encrypted duting the serialization, ``passphrase`` must be ``None``, otherwise it must be a ``bytes`` ob...
381bdcdfe8f354080dd5b3ee96971fad0f33fc1f
3,618,318
def nb_argsort(x, axis): """ Implementation of numpy.argsort in numba. """ assert (axis==0) | (axis==1), "axis must be set to either 0 or 1." ordered = np.zeros_like(x) if axis == 0: for i in range(x.shape[1]): ordered[:, i] = np.argsort(x[:, i]) return ordered elif axis ...
b8200775307bd28413a10532f8487bd26cb9db52
3,618,319
def edge_color(lattice: Lattice, n_colors:int = 3, all_solutions = False, n_solutions = None, fixed = []): """Return a coloring of the edges using n_colors different labels. Args: adjacency (np.ndarray): A list of pairs of vertex indices representing edges. n_colors (int): The maximum number of...
6179524dbc3ba2e3f475b83dbc732d3b46702def
3,618,320
def read_labels(geojson_dict, crs_transformer, extent): """Construct ClassificationLabels from GeoJSON containing grid of cells. If the GeoJSON already contains a grid of cells, then it can be constructed in a straightforward manner without having to infer the class of cells. Args: geojson_dic...
812ce5d999d0d571b8ab4ce96f5b7996aed4acac
3,618,321
import six def server_hardware_from_local_link_information_list( oneview_client, local_link_information_list): """Get the Server Hardware from Local Link Information. :param oneview_client: a instance of the OneView Client; :param local_link_information_list: an list of local link information; ...
69e38d20d4bc0eb48804e2226d52a8a688b61977
3,618,322
def maya_window(): """Return the MayaWindow if in Maya else None.""" for each in QtWidgets.QApplication.topLevelWidgets(): if each.objectName() == "MayaWindow": return each return None
f119e7f985001671b8003ef26f5adc50dec3e1c5
3,618,323
def get_ode_solver(args): """get the ODE solver based on the given argument""" if args.ode_solver == 'heun': return heun_solver if args.ode_solver == 'euler': return euler_solver if args.ode_solver == 'rk4': return rk4_solver if args.ode_solver == 'midpoint': return m...
2eddd0e6803563e3d79d8d0f6a0877fc4742d225
3,618,324
import sys def user_agent_info(sdk_version, custom_user_agent=None): # type: (str, Optional[str]) -> str """Return the user agent info along with the SDK and Python Version information. :param sdk_version: Version of the SDK being used. :type sdk_version: str :param custom_user_agent: Custom ...
d384b63f3b466ed7d74bc3c5e294d2bfd846bef2
3,618,325
def create_metadata_dict(): """A Python dictionary will be created to hold the relevant metadata. :return: dictionary with keys for the relevant metadata :rtype: dict """ metadata = {'Directory': None, 'Filename': None, 'Extension': None, 'ImageType'...
1cb7a42e21df76c13eed3fe905030bd55c7f4af9
3,618,326
import time def email_change_emails(driver, inbox, Users, ISAAC_WEB, GUERRILLAMAIL, WAIT_DUR, **kwargs): """Test if the email change confirmation emails are recieved. - 'driver' should be a Selenium WebDriver. - 'inbox' should be a GuerrillaInbox object. - 'Users' must be a TestUsers obje...
7bdfb744f6cc9d87030100b98c9465e749e7b41a
3,618,327
def compute_power(rawvolts, rawamps): """ Compute the power. Looks trivial, but I'm gonna implement smoothing later. """ power = rawvolts * 1.58 power_low = rawvolts * 1.51 power_high = rawvolts * 1.648 return power, power_low, power_high
9202e456d4655de12ec5608011e80647cf62f7ab
3,618,328
import yaml def custom_ceph_config(suite_config, custom_config, custom_config_file): """ Combines and returns custom configuration overrides for ceph. Hierarchy is as follows: custom_config > custom_config_file > suite_config Args: suite_config: ceph_conf_overrides that currently exis...
e0efbae4f2f9f3d93441d6257159fa27c7f51cae
3,618,329
import argparse def arguments(): """ Builds a generic argparse :return: parser """ workdir = '/opt/nuvlabox/installation' parser = argparse.ArgumentParser(description='NuvlaBox Agent') parser.add_argument('--nuvlabox-installation-trigger-json', dest='nb_trigger_content', default=None, metav...
70c4a81131c5e19a43271905e4f7b5623715cfd4
3,618,330
async def selector(ctx, header, select_from, timeout=120, max_len=20): """ Interactive routine to prompt the `ctx.author` to select an item from a list. Returns the list index that was selected. Parameters ---------- header: str String to put at the top of each page of selection options...
e13f7343d24706c1121fc9630877d1c2c7cc1504
3,618,331
def prettify_labels(labels, format=None): """ Prettify label for typesetting in various formats :param labels: a list of length-2 tuples, in the format(position, label) :param format: a string with the format for the prettifier (e.g. 'agr', 'matplotlib', ...) :return: the same list as labe...
dbcf4ed5d553d732c4bb3509f226fcb8ec8b22d9
3,618,332
def get_activity_score(target_gene, haplotype_call): """Convert haplotype call to activity score. Parameters ---------- target_gene : str Name of the target gene (e.g. cyp2d6). haplotype_call : str Haplotype call. Returns ------- float Activity_score. """ ...
b26d1db765cbd8189a3878cd4398db186412a4dd
3,618,333
import matplotlib.pyplot as plt import matplotlib.collections as mpcollections def drawTree( tree, label_func=str, show_confidence=False, # For power users orientation='horizontal', inverted=False, branch_labels=None, label_colors=None, *args, **kwargs ): """Plot the given ...
6c2de88f8e78c8bd553edd1045f99e0fe660a0cd
3,618,334
def replace_naics_w_naics_from_another_year(df_load, sectorsourcename): """ Replace any non sectors with sectors. :param df_load: df with sector columns or sector-like activities :param sectorsourcename: str, sector source name (ex. NAICS_2012_Code) :return: df, with non-sectors replaced with sector...
b1aac675146c71b043e6331d6185684ac8b68d3f
3,618,335
def datagroup1D(kwsd=None, _larch=None): """utility to perform wrapped operations on a list of 1D data groups""" return DataGroup1D(kwsd=kwsd, _larch=_larch)
269eff221f149567aefe9c37ed8a763d7f2cc3cf
3,618,336
from personal_info.api import home_blueprint import os import warnings def create_app(config_filename=None, config=None): """Application factory function that returns the flask app with the configs loaded correctly. Use YGGDRASIL_CFG to point to a right configuration file. The CFG file *needs* to se...
6e0048445ccaabbe8dd969796dd3a8d5a6cb7bef
3,618,337
import time def wait_for_status(client, stream_name, status, wait_timeout=300, check_mode=False): """Wait for the status to change for a Kinesis Stream. Args: client (botocore.client.EC2): Boto3 client stream_name (str): The name of the kinesis stream. status (str):...
c7a14e069d7c356e2bac3f05c15ee85f1b7141c3
3,618,338
import csv def read_aa_losses(filename): """ Read AA losses from data file. (assume fixed structure...) """ aa_losses = {} with open(filename, 'r') as f: reader = csv.reader(f, delimiter=',') next(reader) # skip headers for line in reader: if len(line) == 0: ...
b1ba8349d01d43112ef67436fa2bb09d3bed768c
3,618,339
def filter_document(ctx, user_id, project_id, id_str): """Gets and returns the first document by project id and id str Admin level access will ignore user_id parameter. :param ctx: context :param user_id: user id (not username) :param project_id: project id :param id_str: :return: """ ...
66bfdf1f6ef82be8abffb7b9f6c50935ec36c4c0
3,618,340
def message_in_state(message, state_slug): """ Checks if a message is tagged with a race that is in a given state. """ races = get_races_from_message(message) for race in races: if race.split("-")[0].lower() == slug_to_postal(state_slug).lower(): return True return False
b917bb5ce1a68cdb6d017289d6569d9fcd930137
3,618,341
def get_matching_taxon(brow): """ Searches taxon objects for taxa matching an occurrence :param row: :return: returns a single element record set """ # get data from all taxon fields and collect them in a list # e.g. ["Animalia", "Chordata", "Mammalia", "Primates", "", "Hominidae", "", "", "...
8d1edf3250035a890b25cb1bebd907dce88581de
3,618,342
from typing import OrderedDict def calc_injection(request): """Calculates injection dosages based on weight. GET parameters: weight: weight in lbs Contxt: calculated dose rounded to 3 decimal places """ meds = Injection.objects.all() rx = dict() # default displayed dos...
aeefe317f76cfb2dc4d802360758729aa97843f5
3,618,343
def convert(iterable, remove_tags=None, prepend_tags=None, append_tags=None): """ >>> convert('red green blue banana APPLE nogreen purple red'.split()) ['banana', 'APPLE', <purple>, <red>] """ items = [] my_removes = remove_tags[:] if remove_tags else [] my_prepends = prepend_tags[:] if prepend_tags else [] my_ap...
7771b4cf093c90fb2ccec6447f1647f035670cc6
3,618,344
def add(M1, M2): """ Returns a matrix Q, where Q[i][j] = M1[i][j] + M2[i][j]. M2 is replaced by Q. """ m = len(M1) n = len(M1[0]) for p in range(m): for q in range(n): M2[p][q] = M2[p][q] + M1[p][q] return M2
ac86e9109f6287cde062392992bf64dbf49614f5
3,618,345
def compute_groupwise(y_hat, y, ct, num_groups): """ :param y_hat: (N, ). Prediction from M, binary :param y: (N, ) true label :param ct: (N, ) group membership fo each instance :param num_groups: int :return: """ tpr = np.zeros((num_groups,)) fpr = np.zeros((num_groups,)) tnr =...
06b548b3ed3939a3a704337edc208fed002c97b2
3,618,346
def attention(inputs, input_shape, attention_size, context=None, context_shape=None): """General attention mechanism model. It return the weighted average of inputs and the weights. Args: inputs: A 3D shaped Tensor [batch_size x time x input_...
fe5cdd3b01ef39332a9bca3be65b0808c0113127
3,618,347
def cal_zscores(gdf, fieldNames): """ claculate z-scores for variables in sample point dataframe columns Arguments: gdf {GeoDataFrame} -- some new fields will add to zscore fieldNames {list} -- field names, the columns needed to calculate zscores Returns: GeoDataFrame -- the da...
36300245d5096cb511de33ec3f1575027c0af7a8
3,618,348
def analyze_tower(img, mask, data): """ Detects tower using horizontal coins """ out_img, infos = analyze_horizontal_coin(img, mask, data) if infos: tower_info = init_detected_object('tower', data) tower_info.centroid = [np.mean([i.centroid[0] for i in infos]), ...
03bc23c0cada6b22e80b0e8e959d4e2421d50369
3,618,349
from re import X def whowinner(board): """ Returns the winner of the game, if there is one. """ for i in range(bs-nt+1): for j in range(bs-nt+1): subboard = [[board[i+row][j+col] for col in range(nt)] for row in range(nt)] if X_winner(subboard): return X...
7504363df97285684ea8790cc048da7d1b2b49e7
3,618,350
import sys def azure_pipelines_broken(): """Azure pipelines has multiple major versions of python that are broken. The fixes for this will take a month since the regression was first noted since they have to rebuild thier images and roll them out which apparently takes a while (which makes me wonder ...
1550835cf548c97fd46f6faf5f00444a46f22649
3,618,351
from typing import Optional async def get_leak_cable_id( cable_id: str, from_date: Optional[str] = None, to_date: Optional[str] = None, token: str = Security(access_token_header), ): """ Download probalilities of leak on a single oilcables Args: cable_id: cable id ...
076c0c4f424583e03f553c3fe5166473599304c5
3,618,352
def _async_register_events_and_services(hass: HomeAssistant): """Register events and services for HomeKit.""" hass.http.register_view(HomeKitPairingQRView) def handle_homekit_reset_accessory(service): """Handle start HomeKit service call.""" for entry_id in hass.data[DOMAIN]: i...
a0c713d3815827dd96e8aa3b4d8f8f18fd7fd5b7
3,618,353
import requests def manual_action(request, **kwargs): """ Create an instance of Event. Make a request to raspberry pi to lock/unlock. Chanage lock status to pending. Redirect to dashboard """ lock = Lock.objects.get(pk=kwargs['pk']) data = { 'lock_id': kwargs['pk'], 'actio...
95403408292435020ac68129eacd5b09f02df2b2
3,618,354
def displace_PSF_moffat(x, y, FWHM, beta): """ :param x: x-coordinate of light ray :param y: y-coordinate of light ray :param FWHM: full width at half maximum :param beta: Moffat beta parameter :return: displaced ray by PSF """ X = draw_moffat_r(FWHM, beta) dx, dy = draw_xy(X) r...
8ed0c7625c5f36aca3b456fcc1688b3298fa9c10
3,618,355
def generate_config(context): """ Entry point for the deployment resources. """ properties = context.properties name = properties.get('name', context.env['name']) project_id = properties.get('project', context.env['project']) zone = properties.get('zone') # Network formatting if 'network' ...
8398401dea1c6a2251a7ccc9c763337fa7f0e7e5
3,618,356
def set_parameters(goal,bifurcation,parentDir): """Set all needed node and network parameters Parameters ---------- goal : string, can be 'sync' or 'switch' the control task bifurcation : string, can be 'low' or 'high' bifurcation lne close to which parameter...
540ae1fd21075d8d7b5beecf6fdb0ad21e07ef22
3,618,357
def get_config_by_url(cfg, url): """ :param cfg: dictionary :param url: path to value separated by dot, e.g, key1.key2.key3 :return: value from dictionary """ keys = url.split('.') for key in keys: cfg = cfg[key] return cfg
0dd2a01a2ecd198f044eebcd3f854f96dbf945bd
3,618,358
import math def entropy(values): """A slow way to calculate the entropy of the input values""" values = values.flatten() #calculate the probablility of a value in a vector vUni = sp.unique(values) vlen = len(vUni) lenval = float(len(values)) FreqData = sp.zeros_like(vUni) for...
db759d0ddcc910123722d20a5b9c8ca66e07276d
3,618,359
def remove_brackets(s: pd.Series) -> pd.Series: """ Remove content within brackets and the brackets itself. Remove content from any kind of brackets, (), [], {}, <>. Examples -------- >>> import texthero as hero >>> import pandas as pd >>> s = pd.Series("Texthero (round) [square] [curl...
f2faabd9b347c70fdf05cea4137d27d941469f5a
3,618,360
def test_executor_error_override( batch_submit_mock, iter_batch_job_status_mock, parse_task_logs_mock, get_aws_user_mock ) -> None: """ Some AWS Batch errors should be overridden. """ @task() def task1(x): return x + 10 @task(script=True) def task_script1(x): return "ls...
adc9b74a38981ebe6413ab6ce49d7963bbbb5970
3,618,361
def blur(img): """ :param img: SimpleImage, the image to be blurred :return: SimpleImage, the blurred image """ # Create a blank frame for blurred pixels. blur_img = SimpleImage.blank(img.width, img.height) # Loop the original image. for x in range(img.width): for y in range(img....
88442ebe166983509e11b0ca48eda796addab0c6
3,618,362
from typing import Any def not_a_seq_complex(request: Any) -> Any: """Provide random values that are not sequences of complexs.""" return request.param[1]
ad28133edced67801deab511100b19606dfa2cd3
3,618,363
def generate_markov_models(user_names): """ Builds a dictionary of user_name :: Markov text models from the text corpus of each user. :param user_names: A list of the users' names to build. Assumes there is a corresponding "user.txt" corpus available :return: text_models - a dictionary of users and thei...
01517bdc11728ec0324021538ed497d637955e99
3,618,364
import math def planckian_table(uv, cmfs, start, end, count): """ Returns a planckian table from given *CIE UCS* colourspace *uv* chromaticity coordinates, colour matching functions and temperature range using *Yoshi Ohno (2013)* method. Parameters ---------- uv : array_like *uv* ...
357a3f645dee2c9d81431596855d65355feb5e7c
3,618,365
def vault_subscribe(): """ Subscribe to a remote vault service on the specific hive node, where would create a new vault service if no such vault existed against the DID used. A user can subscribe to only one vault service on the specific hive node with a given DID, then should declare that service end...
fd9b899329db11c34759b01c34fdd098770350a9
3,618,366
def atrim(stream: Stream, *args, **kwargs) -> FilterableStream: """https://ffmpeg.org/ffmpeg-filters.html#atrim""" return filter(stream, atrim.__name__, *args, **kwargs)
5f0faba73697f6e73d6d93a2cbeac52cec82f63e
3,618,367
def cut_transcript_seq(seq: str, tag: str): """ Some of the sequences contain length % 3 != 0, because they have ambiguous start and/or end. If this is the case, they should be cut until length % 3 == 0 There are sequences which have both ambiguous start and end => no solution yet :param seq: dna se...
3fdc6512f1edc47157778b828b944fdf940fa37a
3,618,368
def kama(df, price, kama, n, fast_ema=2, slow_ema=30): """ Kaufman's Adaptive Moving Average (KAMA) is a moving average designed to account for market noise or volatility. KAMA will closely follow prices when the price swings are relatively small and the noise is low. KAMA will adjust when the price...
58969929ad098c92346e21910002f1d5c9428ed6
3,618,369
import base64 def NumpyDecoder(dct): """ Decodes a previously encoded numpy ndarray with proper shape and dtype :param dct: (dict) json encoded ndarray :return: (ndarray) if input was an encoded ndarray """ if isinstance(dct, dict) and '__ndarray__' in dct: if 'dtype' in dct: ...
9f6e42998bfbcbf6437c63798e906748f0cc75d6
3,618,370
import warnings def get_silverkite_uncertainty_dict( uncertainty, simple_freq=SimpleTimeFrequencyEnum.DAY.name, coverage=None): """Returns an uncertainty_dict for `~greykite.algo.forecast.silverkite.forecast_silverkite.SilverkiteForecast.forecast` input parameter: uncertainty_dict....
be1b954191d1a8c8a18d33a30ed93a728219e22c
3,618,371
def get_xclarity_client(): """Generates an instance of the XClarity client. Generates an instance of the XClarity client using the imported xclarity_client library. :returns: an instance of the XClarity client :raises: XClarityError if can't get to the XClarity client """ try: xcla...
f19e6c19708817fe3f65e68cf461b69f826acbc0
3,618,372
def create_vgg_model_2d(input_image_size, number_of_classification_labels=1000, layers=(1, 2, 3, 4, 4), lowest_resolution=64, convolution_kernel_size=(3, 3), pool_size=(2, 2), ...
2b8554cdda1eabcc6e0ec37ba455216420dbd93c
3,618,373
def _transition_down_block(x, nb_filter, bn_momentum, weight_decay=1e-4, transition_pooling='max', block_prefix='TransitionDown', data_format='channels_last'): """ Adds a pointwise convolution layer (with batch normalization and relu), and a pooling layer. The block cuts...
db5aaedb5d04d16da8414eb4162ff357f737d5c9
3,618,374
from typing import Union from typing import List from typing import Optional from typing import Sequence from typing import Tuple from typing import Dict def collect_mentioned( obj: Union[RawFactor, List[Union[RawFactor, str]]], mentioned: Optional[Mentioned] = None, ignore: Sequence[str] = ( "pre...
6e3995087e438d450572ea60bc86bddde89aa86c
3,618,375
def add(x, y): """相加""" return x + y
cddb73c428639231bc993ffa775717bf10e0a04b
3,618,376
import os def save_in_cpu_load_in_cpu(): """ cpu 下训练 save cpu load :return: """ seed = 90 epoch_num = 1 BATCH_SIZE = 64 # np.set_printoptions(precision=3, suppress=True) diff_var_save = {} diff_var_load = {} with fluid.dygraph.guard(fluid.CPUPlace()): fluid.defaul...
920372c81757f1d67c75c1561f7fc7c728447011
3,618,377
def calculate_mmc(y_true, y_pred): """Using sklearn to compute the Matthews correlation coefficient (MCC). Arguments: y_true {numpy.array} -- the true labels corresponding to each input y_pred {numpy.array} -- the model's predictions Returns: mmc {float} -- the calcu...
cbd66eba6c8fa5d0d00bfa36aea363ec9441113d
3,618,378
import os def find_deepest_user_frame(tb): """ Find the deepest stack frame that is not part of SCons. Input is a "pre-processed" stack trace in the form returned by traceback.extract_tb() or traceback.extract_stack() """ tb.reverse() # find the deepest traceback frame that is not part ...
11753ebbb734058fe4e6dd42d43ba95cbe07c88e
3,618,379
def _get_element_imports(*elements: Element) -> str: """Get the import string for the elements in use.""" prefix = "from statham.schema.elements import " max_length = 80 import_names = [ elem_type.__name__ for elem_type in set.union( *(_get_single_element_imports(element) for...
83bac80556ce0804d00307cab406e2545046787d
3,618,380
def getSpawnProcPIDs(): """Fetch all running DummyMP system process IDs. Looking through all of the DummyMP processes, determine if any are running, and if any, retrieve their system process IDs. Args: None Returns: list: An list with the system process IDs of current ...
da6601f53d80d3decdb64f3bc548e7c36eb31160
3,618,381
def posdef(m): """Map a matrix to a positive definite matrix, where all eigenvalues are >= 1e-5.""" mlambda, mvec = jnp.linalg.eigh(m) mlambda = jnp.maximum(mlambda, 1e-5) return (mvec * jnp.expand_dims(mlambda, -2)) @ jnp.swapaxes(mvec, -2, -1)
1830e673f9972d0ab8ad31f5a847e5d8d8c4892c
3,618,382
def error_500_view(request): """ Renders the 500 error page. """ return render(request, 'climate/500.html')
d9315290ac4c3b29505ef5c2411e6dcf5c528d3c
3,618,383
def get_congratulation_template(elapsed_time: int) -> str: """ Получение шаблона при победе, в зависимости от окончания числа секунд игры. """ if 11 <= elapsed_time <= 19 or elapsed_time % 10 in (0, 5, 6, 7, 8, 9): template = "Поздравляем, вы прошли игру за {elapsed_time} секунд!" elif e...
ad683c224e8db8f9cbacc500561420e5fbb82e0f
3,618,384
import six def _get_column(column): """ Helper to get a ``Column`` object if the given argument is a string """ if isinstance(column, six.text_type): column = col(column) if not isinstance(column, Column): raise ValueError('A Column or a column name (as a string) is expected. Got {...
3d344dca81408031111179f2f58adefd0081bc1e
3,618,385
def smooth(path, weight_data=0.1, weight_smooth=0.2, tolerance=0.000001): """ Creates a smooth path for a n-dimensional series of coordinates. Arguments: path: List containing coordinates of a path weight_data: Float, how much weight to update the data (alpha) weight_smooth: Float, h...
e98e1cd0122a820ed6559ef8255e121cd6ca4bdb
3,618,386
def CDLDOJI(barDs, count): """Doji""" return call_talib_with_ohlc(barDs, count, talib.CDLDOJI)
3aec27b5ad91132b63ec294cc675c83ef9b954e0
3,618,387
from typing import List import json import logging def google_auth_installed( secret_file: str, token_file: str, scopes: List[str] ) -> Credentials: """Authenticate installed applications with Google""" try: with open(token_file, "rt") as token_file: token_data = json.load(token_file) ...
788e46aa049e3e1060cc4533c95f0e8d3f40cd4d
3,618,388
import json import yaml from pathlib import Path from openghg.util import get_datapath def get_ceda_file( # type: ignore filepath=None, site=None, instrument=None, height=None, write_yaml=False, date_range=None, ): """Creates a JSON (with a yaml extension for CEDA reasons) object for ...
da9d4d9b4221acead21e34f0b258f6c02349b521
3,618,389
import os def _find_notebook(fullname, path=None): """ Find a notebook, given its fully qualified name and an optional path This turns "foo.bar" into "foo/bar.ipynb" and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar does not exist. """ name = fullname.rsplit('.', 1)[-1] if not path: ...
9b1b08fb804ed0054566015de1cf7b9de02d94fe
3,618,390
def parse_variable_name(packed_bytes): """ Unpack a 6-bit packed variable name """ variable_name = "" this_char = 0 read_bits = 0 for byte in packed_bytes: # Read six bits at a time for bit in range(0, 8): bit_value = 1 & (byte >> (7 - bit)) this_char = this_...
4aea77c7433ec9c6b411a939c2ac411f74928383
3,618,391
def divide(self, other, op_cols, **kwargs): """ Divide values (self / other) Parameters ---------- other : :class:`ScmRun <scmdata.run.ScmRun>` :class:`ScmRun <scmdata.run.ScmRun>` containing data to divide op_cols : dict of str: str Dictionary containing the columns to drop be...
5094f6fffd5841dd97c395bd50ae66ba96ba6162
3,618,392
import ast def tokenize_code(blob, language='java'): """ :param blob: :param language: :return: """ if language == 'python': parsed_code = astor.to_source(ast.parse(blob)) tokenized_code = [x for x in RegexpTokenizer(r'\w+').tokenize(parsed_code) if not is_numeric(x)] ...
8b77748a2878ab7b862a9da022741768088e7d9f
3,618,393
def create_love_relationship(user, posts): """Creates a love relationship between a profile/user and a post Args: user -- user who is a fan of the post post -- a list of posts Returns: a list of loves """ loves = [] for post in posts: loves.append(LoveFactory(fan=...
433fe7cf2f809534c21edb3b7e113de1e716038b
3,618,394
def task_run_black(): """ calls black code formatter """ task = { 'actions': ['black textwalker'], 'verbosity': 2 } return task
794fc232bb9096c39885d8ffe25c14b8105ac6b6
3,618,395
def to_weld_vec(weld_type, ndim): """Convert multi-dimensional data to WeldVec types. Parameters ---------- weld_type : WeldType WeldType of data. ndim : int Number of dimensions. Returns ------- WeldVec WeldVec of 1 or more dimensions. """ for i in ran...
a131226065087d8923ac66f137f34691a673f6ed
3,618,396
def imq_kernel(x, y, score_x, score_y, g=1, beta=0.5, return_kernel=False): """Compute the IMQ Stein kernel between x and y Parameters ---------- x : torch.tensor, shape (n, p) Input particles y : torch.tensor, shape (n, p) Input particles score_x : torch.tensor, shape (n, p) ...
08c95b04789f47b557645df975a20c1f1b478a0d
3,618,397
def get_target_config_dict(target_obj): """Gets target config as a dict from object :param target_obj: target object :type target_obj: :return: Target config :rtype: `dict` """ target_config = dict(TARGET_CONFIG) if target_obj: for key in list(TARGET_CONFIG.keys()): ...
828375d4883c32e1d99f14efc4264de278d9ce95
3,618,398
def blend(m): """Blend colors.""" base = m.group('base') color = m.group('color') blend_type = m.group('type') percent = m.group('percent') if percent.endswith('%'): percent = float(percent.strip('%')) else: percent = int(alpha_dec_normalize(percent), 16) * (100.0 / 255.0) ...
5b23a8650acca1fb81cb843466152395e616f130
3,618,399