content
stringlengths
22
815k
id
int64
0
4.91M
async def test_t3_gc_will_not_intervene_for_regular_users_and_their_resources( simcore_services_ready, client, socketio_client_factory: Callable, aiopg_engine, fake_project: Dict, tests_data_dir: Path, ): """after a USER disconnects the GC will remove none of its projects or templates nor th...
17,500
def extraction_closure(video_root, frame_root): """Closure that returns function to extract frames for video list.""" def func(video_list): for video in video_list: frame_dir = video.rstrip('.mp4') frame_path = os.path.join(frame_root, frame_dir) os.makedirs(frame_pa...
17,501
def superimpose_tetrahedrons(listofvecs): """superimpose a list of different tetrahedrons (in the form of 4 vectors), and plot 3D figure of the superimposition.""" fig = plt.figure() vecs0 = np.mean(np.array(listofvecs), axis=0)#np.mean(listofvecs) for vecs in listofvecs: rotated_vecs = ma...
17,502
def make_input_data_kmls(rundata): """ Produce kml files for the computational domain, all gauges and regions specified, and all topo and dtopo files specified in rundata. This can be used, e.g. by adding the lines from clawpack.geoclaw import kmltools kmltools.make_input_data_kmls(ru...
17,503
def std(input, axis=None, keepdim=False, unbiased=True, out=None, name=None): """ :alias_main: paddle.std :alias: paddle.std,paddle.tensor.std,paddle.tensor.stat.std Computes the standard-deviation of the input Variable's elements along the specified axis. Args: input (Variable): The input...
17,504
def predict_model(model_name, data_file_name): """This function predicts house prices based on input data""" model_path = os.path.join(config.TRAINED_MODEL_DIR, model_name) data_file_path = os.path.join(os.path.join(config.DATA_DIR, data_file_name)) pipe = joblib.load(model_path) data = pd.read_csv(...
17,505
def test_tagging(): """Test the tagging functionality of this extension.""" try: # TODO: serial.save should be able to take an open file-like object so # we can direct its output to a StringIO or something and not need to # screw around like this in tests that don't actually need to touc...
17,506
def write_yaml(data, path): """Helper function to write data to a YAML file.""" path = Path(path) log.info('Writing {}'.format(path)) with path.open('w') as fh: ruamel.yaml.round_trip_dump(data, fh)
17,507
def check_file_behaviour(file_hash): """ Returns the file execution report. """ params = { 'hash': file_hash } api_endpoint = 'file/behaviour' return http_request('GET', api_endpoint, params, DEFAULT_HEADERS)
17,508
def usage(error=''): """ Application usage Args: error (string): error message to display """ if len(error) > 0: print(u'Error: %s' % error) print(u'') print(u'Usage: remotedev -E|--execenv -D|--devenv <-c|--conf "config filepath"> <-p|--prof "profile name"> <-d|--debug>...
17,509
def is_access_group(outter_key, inner_key) -> None: """Prints access-group """ values = {} if outter_key == "access-group": if inner_key.get('index') is not None: values['index'] = ', '.join(is_instance(inner_key.get('index', {}))) elif inner_key.get('name') is not None: ...
17,510
def test_brain_models(): """ Tests the introspection and creation of CIFTI-2 BrainModelAxis axes """ bml = list(get_brain_models()) assert len(bml[0]) == 3 assert (bml[0].vertex == -1).all() assert (bml[0].voxel == [[0, 1, 2], [0, 4, 0], [0, 4, 2]]).all() assert bml[0][1][0] == 'CIFTI_MO...
17,511
def update_documentation(): """ Update the documentation on the current host. This method is host agnostic """ root_path = '/opt/webshop-demo' with cd(root_path): with prefix("source %s/bin/activate" % root_path): run('pip install sphinx_rtd_theme') with cd('ner...
17,512
def SLC_deramp(SLC_1, SLC_par1, SLC_2, SLC_par2, mode, dop_ph='-', logpath=None): """ | Calculate and subtract Doppler phase from an SLC image | Copyright 2016, Gamma Remote Sensing, v1.5 4-Feb-2016 clw Parameters ---------- SLC-1: (input) SLC data file (fcomplex or scomplex format)...
17,513
def lidar_to_cam_frame(xyz_lidar, frame_calib): """Transforms points in lidar frame to the reference camera (cam 0) frame Args: xyz_lidar: points in lidar frame frame_calib: FrameCalib frame calibration Returns: ret_xyz: (N, 3) points in reference camera (cam 0) frame """ ...
17,514
def create_logger(model_name: str, saved_path: str): """Create logger for both console info and saved info """ logger = logging.getLogger(model_name) logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler(f"{saved_path}/{model_name}.log") ...
17,515
def hann_sinc_low_pass(x: Tensor, N: int, fs: int, fc: float) -> Tensor: """Hann windowed ideal low pass filter. Args: x: [n_batch, 1, n_sample] N: the window will be [-N, N], totally 2N+1 samples. Returns: y: [n_batch, 1, n_sample] """ w = continuous_hann_sinc_filter(fs, fc,...
17,516
def trusted_zone(engine_db, table: str): """ # TRUSTED ZONE Transform the JSON data into a tabular format for the `TRUSTED` schema/dataset. Parameters ---------- engine_db : connection The connection to send data into the data warehouse table : str The table name will be us...
17,517
def test_vi_green(spectral_index_test_data): """Test for PlantCV.""" index_array = spectral_index.vi_green(spectral_index_test_data.load_hsi(), distance=20) assert np.shape(index_array.array_data) == (1, 1600) and np.nanmax(index_array.pseudo_rgb) == 255
17,518
def _patch_doctest_namespace(doctest_namespace): """Patch the namespace for doctests. This function adds some packages to namespace of every doctest. """ doctest_namespace["np"] = np doctest_namespace["pd"] = pd
17,519
def viz_use(df, ticks, title='default', outpath='./ctt_shift/overlap.pdf'): """ Heatmap visualization :param df: an instance of pandas DataFrame :return: """ corr = df.corr() # Generate a mask for the upper triangle mask = np.zeros_like(corr, dtype=np.bool) mask[np.triu_...
17,520
def ask_for_missing_options(arguments: CommandLineArguments, root: tk.Tk) -> ProgramOptions: """ Complete the missing information by askin the user interactively. """ values = copy.deepcopy(arguments) if values.source_directory is None: values.source_directory = insist_for_directory( ...
17,521
def matrix2quaternion(m): """Returns quaternion of given rotation matrix. Parameters ---------- m : list or numpy.ndarray 3x3 rotation matrix Returns ------- quaternion : numpy.ndarray quaternion [w, x, y, z] order Examples -------- >>> import numpy >>> fro...
17,522
def paging_forward(data_func, *args): """ Создает кнопку вперед для переключения страницы списка :param data_func: func from UI.buttons. Действие, которое будет возвращать кнопка :return: InlineKeyboardButton """ g_data = loads(data_func(*args).callback_data) g_data['page'] += 1 text =...
17,523
def test_hydrogen_like_sgd_vmc(caplog): """Test the wavefn exp(-a * r) converges (in 3-D) to a = nuclear charge with SGD.""" ( params, nuclear_charge, nchains, nburn, nepochs, nsteps_per_param_update, std_move, learning_rate, log_psi_model,...
17,524
def synchronized(func): """Synchronizes method invocation on an object using the method name as the mutex""" def wrapper(self,*__args,**__kw): try: rlock = self.__get__('_sync_lock_%s' % func.__name__) #rlock = self._sync_lock except AttributeError: from ...
17,525
def vector(location_1, location_2): """ Returns the unit vector from location_1 to location_2 location_1, location_2: carla.Location objects """ x = location_2.x - location_1.x y = location_2.y - location_1.y z = location_2.z - location_1.z norm = np.linalg.norm([x, y, z]) + np.finfo(f...
17,526
def test_pandas_code_snippets( app, client, tmpdir, monkeypatch, template_name, script_name, expected_columns ): """Bit of a complicated test, but TLDR: test that the API example Python scripts work. This test is a bit complicated and is pretty low impact, so if you're struggling to mai...
17,527
async def test_step_user(opp): """Test that the user step works.""" conf = { CONF_USERNAME: "user@host.com", CONF_PASSWORD: "123abc", } with patch( "openpeerpower.components.tile.async_setup_entry", return_value=True ), patch("openpeerpower.components.tile.config_flow.async_...
17,528
def test_parse_date(): """ Test that the parse_date helper correctly parses a date """ assert parse_date("2020-10-01") == datetime.date(2020, 10, 1) assert parse_date(None) is None assert parse_date("Foo") == "Foo" assert parse_date("hello_a_long_string") == "hello_a_long_string"
17,529
def getOpenOCO(recvWindow=""): """# Query Open OCO (USER_DATA) #### `GET /api/v3/openOrderList (HMAC SHA256)` ### Weight: 3 ### Parameters: Name |Type |Mandatory |Description --------|--------|--------|-------- recvWindow |LONG |NO |The value cannot be greater than <code>60000</code> timestamp |LONG |YES | <stro...
17,530
def pixel_unshuffle(scale): """ Pixel unshuffle. Args: x (Tensor): Input feature with shape (b, c, hh, hw). scale (int): Downsample ratio. Returns: Tensor: the pixel unshuffled feature. """ if scale == 1: return lambda x: x def f(x): b, c, hh, hw = x.size() out_channel = c * (s...
17,531
def flag(name, thing=None): """Generate an Attribute with that name which is valued True or False.""" if thing is None: thing = Keyword(name) return attr(name, thing, "Flag")
17,532
def select_id_from_scores_dic(id1, id2, sc_dic, get_worse=False, rev_filter=False): """ Based on ID to score mapping, return better (or worse) scoring ID. >>> id1 = "id1" >>> id2 = "id2" >>> id3 = "id3" >>> sc_dic = {'id1' : 5, 'id2': ...
17,533
def add_args(parser): """Add arguments to the argparse.ArgumentParser Args: parser: argparse.ArgumentParser Returns: parser: a parser added with args """ # Training settings parser.add_argument( "--task", type=str, default="train", metavar="T", ...
17,534
def test_build_all_isolated(): """Test building all packages in an isolated workspace""" pass
17,535
def run_interactive(package: str, action: str, *args: Any, **_kwargs: Any) -> Any: """Call the given action's run""" action_cls = get(package, action) app, interaction = args return action_cls(app.args).run(app=app, interaction=interaction)
17,536
def test_input_files(files, test_type, tmpdir): """ Test for access to Sample input files. """ file_text = " ".join(files) sample_data = {SAMPLE_NAME_COLNAME: "test-sample", DATA_SOURCE_COLNAME: file_text} s = Sample(sample_data) assert file_text == s.data_source assert files == s.input_file_pat...
17,537
def test_droprows_2(generator): """ Test DropRows test for factor = 2, 3, 4, 8 that the output is equivalent to applying a rolling window and taking the mean over the samples. size of chunk is 5 rows. """ for factor in [2, 3, 4, 8]: generator.reset() node = DropRows(factor=facto...
17,538
def pythagorean_heuristic(start_point: Tuple[int, int], end_point: Tuple[int, int]) -> float: """Return the distance between start_point and end_point using the pythagorean distance """ x1, y1 = start_point x2, y2 = end_point distance = (((x2 - x1) ** 2) + ((y2 - y1) ** 2)) ** 0.5 return distanc...
17,539
def run_simulation(x, simulation_time, dt, rates, sampling_time): """ Runs a simulation and stores the sampled sequences the matrix sequences (nb_nucleotide * nb_sequences). x is modified during the simulation. The original sequence is included in the sequences matrix, in the first row. """ ii = 0 ...
17,540
def test_what_decoder_dtype(): """Verify what decoder output dtype.""" z_whats = torch.rand(3, 4, 5) decoder = WhatDecoder(z_what_size=5) outputs = decoder(z_whats) assert outputs.dtype == torch.float assert (outputs >= 0).all() assert (outputs <= 1).all()
17,541
def login(): """Log user in""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("username"): return apology("must provide username"...
17,542
def process_item(item_soup): """Parse information about a single podcast episode. @param item_soup: Soup containing information about a single podcast episode. @type item_soup: bs4.BeautifulSoup @return: Dictionary describing the episode. Contains keys name (str value), date (datetime.d...
17,543
def working_directory(path): """ Temporarily change working directory. A context manager which changes the working directory to the given path, and then changes it back to its previous value on exit. Usage: ```python # Do something in original directory with working_directory('/my/new...
17,544
def update_webhook(request, log, tenantId, groupId, policyId, webhookId, data): """ Update a particular webhook. A webhook may (but do not need to) include some arbitrary medata, and must include a name. If successful, no response body will be returned. Example request:: { ...
17,545
def configure_master_account_parameters(event): """ Update the Master account parameter store in us-east-1 with the deployment_account_id then updates the main deployment region with that same value """ parameter_store_master_account_region = ParameterStore(os.environ["AWS_REGION"], boto3) param...
17,546
def create_solutions_visualization(results_filename, html_filename): """ Create a multi-tab visualization of remixt solutions """ try: os.remove(html_filename) except OSError: pass bokeh.plotting.output_file(html_filename) logging.info('generating solutions tables') with pd...
17,547
def covariance_from_internal(internal_values, constr): """Undo a cholesky reparametrization.""" chol = chol_params_to_lower_triangular_matrix(internal_values) cov = chol @ chol.T return cov[np.tril_indices(len(chol))]
17,548
def find_result_node(desc, xml_tree): """ Returns the <result> node with a <desc> child matching the given text. Eg: if desc = "text to match", this function will find the following result node: <result> <desc>text to match</desc> </result> Parameters ----- ...
17,549
def y(instance): """Syntactic sugar to find all y-coordinates of a given class instance. Convenience function to return all associated x-coordinates of a given class instance. Parameters ---------- instance : DataContainer, Mesh, R3Vector, np.array, list(RVector3) Return the associated...
17,550
def interp_xzplane(y, u, y_target=0.0): """Perform linear interpolation of the 3D data at given y-location. Parameters ---------- y : numpy.ndarray of floats The y-coordinates along a vertical gridline as a 1D array. u : numpy.ndarray of floats The 3D data. y_target : float (opt...
17,551
def train_transfer(x_train, y_train, vocab_processor, pretrain_emb, x_dev, y_dev, source_ckpt, target_ckpt, pretrained_values=None): """ Train a transfer model on target task: must pass "pretrained_values" Build model architecture using target task data, then load pre-trained model's ...
17,552
def liste_vers_paires(l): """ Passer d'une structure en list(list(str)) ) list([str, str]) :param l: :return: """ res = [] for i in l: taille_i = len(i) for j in range(taille_i-1): for k in range(j+1, taille_i): res.append([i[j], i[k]]) return ...
17,553
def assert_typing( input_text_word_predictions: List[Dict[str, Any]] ) -> List[Dict[str, str]]: """ this is only to ensure correct typing, it does not actually change anything Args: input_text_word_predictions: e.g. [ {"char_start": 0, "char_end": 7, "token": "example", "tag": "O"},...
17,554
def download(file): """Download files from live server, delete recerds of those that 404. """ url = 'https://www.' + settings.DOMAIN.partition('.')[2] + file.url() try: print(url) return urllib.request.urlopen(url, timeout=15).read() except urllib.error.HTTPError as e: print(...
17,555
def plot_costs(costs): """ 利用costs展示模型的训练曲线 Args: costs: 记录了训练过程的cost变化的list,每一百次迭代记录一次 Return: """ costs = np.squeeze(costs) plt.plot(costs) plt.ylabel('cost') plt.xlabel('iterations (per hundreds)') plt.title("Learning rate = 0.00002") # plt.show() plt.savefig(...
17,556
def get_current_ledger_state(case_ids, ensure_form_id=False): """ Given a list of cases returns a dict of all current ledger data of the following format: { "case_id": { "section_id": { "product_id": StockState, "product_id": StockState, ...
17,557
def _FlattenPadding(padding): """Returns padding reduced to have only the time dimension.""" if padding is None: return padding r = tf.rank(padding) return tf.reduce_min(padding, axis=tf.range(1, r))
17,558
def revive_custom_object(identifier, metadata): """Revives object from SavedModel.""" if ops.executing_eagerly_outside_functions(): model_class = training_lib.Model else: model_class = training_lib_v1.Model revived_classes = { '_tf_keras_layer': (RevivedLayer, base_layer.Layer), '_tf_keras_...
17,559
async def _close_tasks(pending_tasks, timeout=5): """Close still pending tasks.""" if pending_tasks: # Give tasks time to cancel. with suppress(asyncio.CancelledError): await asyncio.wait_for(asyncio.gather(*pending_tasks), timeout=timeout) await asyncio.gather(*pending_t...
17,560
def all_users(): """Returns all users in database sorted by name Returns: QuerySet[User]: List containing each User instance """ # Return all unique users in Database. # sorted by full name # returns query set. same as python list. Each index in user_list is a user model. user_list...
17,561
def plugin_func_list(tree): """Return a list of expected reports.""" return [EXPECTED_REPORT + (type(plugin_func_list),)]
17,562
def entity_ids(value): """Validate Entity IDs.""" if value is None: raise vol.Invalid('Entity IDs can not be None') if isinstance(value, str): value = [ent_id.strip() for ent_id in value.split(',')] return [entity_id(ent_id) for ent_id in value]
17,563
def random_unitary(dim, seed=None): """ Return a random dim x dim unitary Operator from the Haar measure. Args: dim (int): the dim of the state space. seed (int): Optional. To set a random seed. Returns: Operator: (dim, dim) unitary operator. Raises: QiskitError: i...
17,564
def allc(IL, IR): """ Compute the all-chain set (ALLC). Parameters ---------- IL : ndarray Left matrix profile indices IR : ndarray Right matrix profile indices Returns ------- S : list(ndarray) All-chain set C : ndarray Anchored time series ch...
17,565
def build_resilient_url(host, port): """ Build basic url to resilient instance :param host: host name :type host: str :param port: port :type port: str|int :return: base url :rtype: str """ if host.lower().startswith("http"): return "{0}:{1}".format(host, port) retu...
17,566
def relative_angle(pos1, pos2): """ Angle between agents. An element (k,i,j) from the output is the angle at kth sample between ith (reference head) and jth (target base). arg: pos1: positions of the thoraces for all flies. [time, flies, y/x] pos2: positions of the heads for all flies. [time, fl...
17,567
def run_value_iteration(env): """Run a random policy for the given environment. Logs the total reward and the number of steps until the terminal state was reached. Parameters ---------- env: gym.envs.Environment Instance of an OpenAI gym. Returns ------- (float, int) F...
17,568
def get_shape(dset): """ Extract the shape of a (possibly constant) dataset Parameters: ----------- dset: an h5py.Dataset or h5py.Group (when constant) The object whose shape is extracted Returns: -------- A tuple corresponding to the shape """ # Case of a constant data...
17,569
def predict(reaction_mech, T_list, pressure_0, CCl4_X_0, mass_flow_rate, n_steps, n_pfr, length, area, save_fig=False, name='predict',fold_no=None,iter_CCl4=False): """ Load the saved parameters of StandardScaler() and rebuild the ML model to do predictions. =============== =====...
17,570
def server_params_test(client_context, server_context, indata=b"FOO\n", chatty=True, connectionchatty=False, sni_name=None, session=None): """ Launch a server, connect a client to it and try various reads and writes. """ stats = {} server = ThreadedE...
17,571
def _sanitize_bool(val: typing.Any, /) -> bool: """Sanitize argument values to boolean.""" if isinstance(val, str): return val.lower() == 'true' return bool(val)
17,572
def write_all(quality_annotations, filt_primer, filtered_annotations, dedup_ap, all_reads, motif_dir, motif_modules, index_rep, index_rep2, j, quiet=False): """ Write all output files: quality annotations, one-primer annotations, filtered annotations, statistics, repetitions + images. :param quality_annotat...
17,573
def isSameLinkedList(linked_list1, linked_list2): """ Check whether two linked lists are the same. Args: linked_list1: - linked_list2: - """ while linked_list1: if linked_list1.val != linked_list2.val: return False linked_list1, linked_list...
17,574
def ChenFoxLyndonBreakpoints(s): """Find starting positions of Chen-Fox-Lyndon decomposition of s. The decomposition is a set of Lyndon words that start at 0 and continue until the next position. 0 itself is not output, but the final breakpoint at the end of s is. The argument s must be of a type t...
17,575
async def async_get_config_entry_diagnostics( hass: HomeAssistant, config_entry: ConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" coordinator: SolcastUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id] return { "info": async_redact_data(config_entry.options...
17,576
def test_discard_report(class_testsuite, platforms_list, all_testcases_dict, caplog, tmpdir): """ Testing discard_report function of Testsuite class in sanitycheck Test 1: Check if apply_filters function has been run before running discard_report Test 2: Test if the generated report is not empty Tes...
17,577
def calculate_value_function(transition_costs): """Recursively apply the bellman equation from the end to the start. """ state_dim = [tc.shape[0] for tc in transition_costs] state_dim.append(transition_costs[-1].shape[1]) V = [np.zeros(d) for d in state_dim] V_ind = [np.zeros(d) for d in state_dim]...
17,578
def main() -> None: """Run the command.""" sources = sys.argv[1:] report_dir = "/reports/coverage/api" dest_dir = "/tmp/coverage/api" # nosec shutil.rmtree(dest_dir, ignore_errors=True) shutil.copytree(report_dir, dest_dir) cov = coverage.Coverage( data_file=os.path.join(dest_dir, "...
17,579
def load_config(fname: str) -> JSON_TYPE: """Load a YAML file.""" return load_yaml(fname)
17,580
def get_date_folders(): """ Return a list of the directories used for backing up the database. """ directories_in_curdir = list(filter(os.path.isdir, os.listdir(os.getcwd()))) date_folders = [ d for d in directories_in_curdir if re.match(r"([0-9]+(-[0-9]+)+)", d) ] return date_folder...
17,581
def show_header(): """Shows the project header.""" console = Console() text = Text("AWS Account Lifecycle Manager") text.stylize("bold magenta") console.print(text2art('AWS ALF CLI')) console.print(text)
17,582
def read_tree_color_map(filename): """Reads a tree colormap from a file""" infile = util.open_stream(filename) maps = [] for line in infile: expr, red, green, blue = line.rstrip().split("\t") maps.append([expr, map(float, (red, green, blue))]) name2color = make_expr_mapping(maps) ...
17,583
def sin_cos_encoding(arr): """ Encode an array of angle value to correspongding Sines and Cosines, avoiding value jump in 2PI measure like from PI to -PI. """ return np.concatenate((np.sin(arr), np.cos(arr)))
17,584
def run(f, ip="", counter=1024): """ Run Whitefuck script. Parameters ---------- f : str Script to run. ip : str, optional Input, by default "" counter : int, optional Number of counters to make, by default 1024 """ s = "" # Format to brainfuck for ...
17,585
def func_use_queue(q): """ 将数据存入队列,便于进程通信 :param q: Queue :return: """ q.put([1, "a", None])
17,586
def atom_free_electrons(mgrph, idx): """ number of unbound valence electrons for an atom in a molecular graph """ atms = atoms(mgrph) vlnc = valence(atms[idx]) bcnt = atom_bond_count(mgrph, idx) return vlnc - bcnt
17,587
def identify_guest(): """Returns with an App Engine user or an anonymous user. """ app_engine_user = users.get_current_user() if app_engine_user: return Guest.app_engine_user(app_engine_user) ip_address = ip_address_from_request(request) if ip_address: return Guest.ip_address(...
17,588
def compute_placevalues(tokens): """Compute the placevalues for each token in the list tokens""" pvs = [] for tok in tokens: if tok == "point": pvs.append(0) else: pvs.append(placevalue(get_value(tok)[0])) return pvs
17,589
def save_fgong(filename, glob, var, fmt='%16.9E', ivers=0, comment=['\n','\n','\n','\n']): """Given data for an FGONG file in the format returned by :py:meth:`~tomso.fgong.load_fgong` (i.e. two NumPy arrays and a possible header), writes the data to a file. Parameters ---------- ...
17,590
def get_model_damping(global_step, damping_init, decay_rate, total_epochs, steps_per_epoch): """get_model_damping""" damping_each_step = [] total_steps = steps_per_epoch * total_epochs for step in range(total_steps): epoch = (step + 1) / steps_per_epoch damping_here = damping_init * (dec...
17,591
def setup_minicluster(enable_k8s=False): """ setup minicluster """ log.info("setup cluster") if os.getenv("CLUSTER", ""): log.info("cluster mode") else: log.info("local minicluster mode") setup(enable_peloton=True, enable_k8s=enable_k8s) time.sleep(5)
17,592
def transformData(Z,Time,Spec): # transformData Transforms each data series based on Spec.Transformation # # Input Arguments: # # Z : T x N numeric array, raw (untransformed) observed data # Spec : structure , model specification # # Output Arguments: # # X ...
17,593
def torch_fn(): """Create a ReLU layer in torch.""" return ReLU()
17,594
def all_user_tickets(uid, conference): """ Versione cache-friendly della user_tickets, restituisce un elenco di (ticket_id, fare_type, fare_code, complete) per ogni biglietto associato all'utente """ qs = _user_ticket(User.objects.get(id=uid), conference) output = [] for t in qs: ...
17,595
def start(graph=get_graph_for_controllers(ALL_SERVICE_CONTROLLERS), strategy: Optional[str] = None, **kwargs): """Starts the ETL pipelines""" bonobo.run(graph, strategy=strategy, **kwargs)
17,596
def get_hardconcrete_linear_modules(module: nn.Module) -> List[nn.Module]: """Get all HardConcrete*Linear modules. Parameters ---------- module : nn.Module The input module Returns ------- List[nn.Module] A list of the HardConcrete*Linear module. """ modules = [] ...
17,597
def approx_partial(model, ori_target, param, current_val, params, loss_list, information_loss_list, xs_list, ys_list, train=False, optimizer=None): """Compute the approximate partial derivative using the finite-difference method. :param param: :param current_val: :param params: :return: """ ...
17,598
def check_successful_connections(_ctx: Context) -> bool: """Checks if there are no successful connections more than SUCCESSFUL_CONNECTIONS_CHECK_PERIOD sec. Returns True if there was successful connection for last NO_SUCCESSFUL_CONNECTIONS_DIE_PERIOD_SEC sec. :parameter _ctx: Context """ now_ns = ti...
17,599