content
stringlengths
22
815k
id
int64
0
4.91M
def get_high(pair, path="https://api.kraken.com/0/public"): """ Get the last 24h high price of `pair`. Parameters ---------- pair : str Code of the requested pair(s). Comma delimited if several pair. path : str Path of the exchange to request. Returns ------- float or d...
5,354,000
def SIx(): """ Reads in future LENS SI-x data Returns ---------- leafmean : array leaf indices (ens x year x lat x lon) latmean : array last freeze indices (ens x year x lat x lon) lat : array of latitudes lon : array of longitudes lstfrz : list last freeze indices """ ...
5,354,001
def test_destroy_invalid_proxy(): """ Test if we can destroy an invalid proxy """ result = toxiproxy.destroy("invalid_proxy") assert result is False
5,354,002
def test_pinned_task_recovers_on_host(): """Tests that when a pinned task gets killed, it recovers on the node it was pinned to.""" app_def = apps.sleep_app() app_id = app_def["id"] host = common.ip_other_than_mom() common.pin_to_host(app_def, host) client = marathon.create_client() client...
5,354,003
def insert_nhl_ids(tds, players): """ Insert nhl ids for each player into the according team's html roster representation. """ # modifying each of the specified table cells for td in tds: # retrieving player's jersey number from current table cell no = int(td.text_content()) ...
5,354,004
def make_truncnorm_gen_with_bounds(mean, std, low_bound, hi_bound): """ low_bound and hi_bound are in the same units as mean and std """ assert hi_bound > low_bound clipped_mean = min(max(mean, low_bound), hi_bound) if clipped_mean == low_bound: low_sigma = -0.01 * std hi_sigma ...
5,354,005
def resolve_item_from_loan(item_pid): """Resolve the item referenced in loan based on its PID type.""" from invenio_app_ils.ill.api import BORROWING_REQUEST_PID_TYPE from invenio_app_ils.ill.proxies import current_ils_ill from invenio_app_ils.items.api import ITEM_PID_TYPE from invenio_app_ils.proxi...
5,354,006
def mkdir(d): """make a directory if it doesn't already exist""" if not os.path.exists(d): try: os.makedirs(d) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise
5,354,007
def lascolor(strPathInLAS, strPathOutLAS, strPathTif, strAdlSwitches = None): """ Function lascolor args: strPathInLAS = input LAS file strPathOutLAS = output LAS file strPathTif = Tif source of RGB values strAdlSwitches = optional additional switches ...
5,354,008
def delta(s1, s2): """ Find the difference in characters between s1 and s2. Complexity: O(n), n - length of s1 or s2 (they have the same length). Returns: dict, format {extra:[], missing:[]} extra: list, letters in s2 but not in s1 missing: list, letters in s1 but not in s2...
5,354,009
def test_get_involved_cs_handles_error(github, test_client): """ If error happens when generating the 'get_involved_cs' page, the view should handle it and still display most of the content. The issues section should contain an error message with some useful links """ def get_issues(self, *args,...
5,354,010
def mean_predictive_value(targets, preds, cm=None, w=None, adjusted=False): """ :purpose: Calculates the mean predictive value between a discrete target and pred array :params: targets, preds : discrete input arrays, both of shape (n,) cm : if you have previously calculated a confus...
5,354,011
def delta(phase,inc, ecc = 0, omega=0): """ Compute the distance center-to-center between planet and host star. ___ INPUT: phase: orbital phase in radian inc: inclination of the system in radian OPTIONAL INPUT: ecc: omega: // OUTPUT: distance center-to-center, doubl...
5,354,012
def preconfigureExternalDeps(cfgCtx): """ Configure external dependencies. Returns dict with configuration of dependency producers ready to use in ZenMake command 'configure' but not in others. """ resultRules = [] bconfManager = cfgCtx.bconfManager allTasks = cfgCtx.allTasks rootd...
5,354,013
def count_mementos(): """ Helper function to count mementos from timemap in 11/2016 """ directory = "data/timemaps/" print("For the month of November 2016") for filename in os.listdir(directory): with open(directory + filename) as f: resp = json.load(f) counter = 0 ...
5,354,014
def theoritical_spectrum(peptide_sequence): """Returns the theoritical spectrum of a given amino acid sequence. INPUT : peptide_sequence: string. The peptide sequence to get its theoritical spectrum OUTPUT: .: List. The theoritical spectrum of the given peptide sequence. """ linear_...
5,354,015
def is_amazon(source_code): """ Method checks whether a given book is a physical book or a ebook giveaway for a linked Amazon account. :param source_code: :return: """ for line in source_code: if "Your Amazon Account" in line: return True return False
5,354,016
def transdecodeToPeptide(sample_name, output_dir, rerun_rules, sample_dir, mets_or_mags = "mets", transdecoder_orf_size = 100, nt_ext = ".fasta", pep_ext = ".faa", run_transdecoder = False): """ Use TransDecoder to convert input nucleotide metatranscriptomic se...
5,354,017
def fechaTurmaSeNaoTemAlunoForm(modelo, y, p, turmasPermitidas): """Fecha as turmas que nao possuem alunos de formulario.""" for t in turmasPermitidas: alunosForm = [y[k][t] for k in y] modelo.solver.Add(p[t] <= sum(alunosForm))
5,354,018
def test_convert_invalid(schema, value, exception): """ GIVEN invalid schema and expected exception WHEN convert is called with the schema THEN the expected exception is raised. """ with pytest.raises(exception): utility_base.to_dict.simple.convert(schema=schema, value=value)
5,354,019
def data_dim(p): """ Return the dimensionality of the dataset """ dataset_class = DATASETS[p.dataset] return dataset_class(p).get_in_dim()
5,354,020
def create_supervised_evaluator(model, metrics=None, device=None, non_blocking=False, prepare_batch=_prepare_batch, output_transform= lambda x, y, y_pred: (y_pred, y,)): """ Factory fu...
5,354,021
def historical_earning_calendar( apikey: str, symbol: str, limit: int = DEFAULT_LIMIT ) -> typing.Optional[typing.List[typing.Dict]]: """ Query FMP /historical/earning_calendar/ API. Note: Between the "from" and "to" parameters the maximum time interval can be 3 months. :param apikey: Your API key....
5,354,022
def muteblockdelmenu(): """ Submenu to hide away all the unpalatable things. Arguments: none User input: The command to execute. """ choice = input(""" | mute/block/delete | delp = delete a post muteu = mute a user unmuteu = unmute a user mutec = mute a channel unmutec = unmute a channel [return] = back """...
5,354,023
def config_section_data(): """Produce the default configuration section for app.config, when called by `resilient-circuits config [-c|-u]` """ config_data = u"""[fn_query_tor_network] base_url = https://onionoo.torproject.org/details #The Flag can be 'Running','Exit' for more information on flag sett...
5,354,024
def test_PearsonCorrlation_MIP_AlgoTesting_3p1(): """ Results from 2019_MIP_Algo_Testing/PearsonCorrelation var1 vs var2 Pearson's r -0.006 p-value 0.867 95% CI Upper 0.067 95% CI Lower -0.079 """ logging.info("---------- TEST : Pearson Correlati...
5,354,025
def show_object_id_by_date( move_data, create_features=True, kind=None, figsize=(21, 9), return_fig=True, save_fig=True, name='shot_points_by_date.png', ): """ Generates four visualizations based on datetime feature: - Bar chart trajectories by day periods - Bar char...
5,354,026
def raw_escape(pattern, unix=None, raw_chars=True): """Apply raw character transform before applying escape.""" return _wcparse.escape(util.norm_pattern(pattern, False, raw_chars, True), unix=unix, pathname=True, raw=True)
5,354,027
def interpolate_effective_area_per_energy_and_fov( effective_area, grid_points, target_point, min_effective_area=1. * u.Unit('m2'), method='linear', ): """ Takes a grid of effective areas for a bunch of different parameters and interpolates (log) effective areas to given value of those p...
5,354,028
def extract_edge(stats:np.ndarray, idxs_upper:np.ndarray, runner:int, max_index:int, maximum_offset:float, iso_charge_min:int = 1, iso_charge_max:int = 6, iso_mass_range:int=5)->list: """Extract edges. Args: stats (np.ndarray): Stats array that contains summary statistics of hills. idxs_upper ...
5,354,029
def _neq_attr(node, attr, gens, container): """ Calcs fitness based on the fact that node's target shall not have an attr with a certain value. """ trg_nd = container.nodes[gens[node]] if attr[0] in trg_nd and attr[1] == trg_nd[attr[0]]: return 10.1 return 0.0
5,354,030
def test_query_works_with_string(fredo): """Str is allowed in query""" _, query = fredo.parse_query('test') assert 'test' == query
5,354,031
def init_call_probabilities(size, calls_per_hrs): """Precomputes table of boolean call probabilities shared for all users.""" global _rand_bool, _rand_bool_init, _rand_bool_num, _rand_bool_prob _rand_bool_prob = float(calls_per_hrs) / 3600.0 _rand_bool = np.random.rand(size) < _rand_bool_prob _rand...
5,354,032
def getItem( user, list, itempk ): """ Get a single item from a list. :param user: user who owns list :param list: list containing item :param itempk: private key of item :return: item or None """ itemType = list.itemType item = None if itemType == 'Item': ite...
5,354,033
def set_user_to_vendor(sender, instance, **kwargs): """Set the user is_vendor attribut to True when VendorProfile is saved.""" instance.user.is_vendor = True instance.user.save()
5,354,034
def metric_divergence(neighborhood_vectors: np.ndarray, dL: float, polarity: int) -> float: """ Calculates the divergence of a sampling volume neighborhood. Note: For JIT to work, this must be declared at the top level. @param neighborhood_vectors: Sampling volume neighborhood vectors (six 3D vectors)...
5,354,035
def parse_args(): """ Parse command line arguments. Parameters: None Returns: parser arguments """ parser = argparse.ArgumentParser(description='LeNet model') optional = parser._action_groups.pop() required = parser.add_argument_group('required arguments') required.add_argument('--dataset', dest='datase...
5,354,036
def tag(request): """ Add/Remove tag to email """ if request.is_ajax(): mail = request.POST.get("mail") tag = request.POST.get("tag") op = request.POST.get("op") mail = get_object_or_404(Mail, pk=mail) if op == "ADD": mail.tags.add(tag) elif op...
5,354,037
def sid_to_smiles(sid): """Takes an SID and prints the associated SMILES string.""" substance = pc.Substance.from_sid(sid) cid = substance.standardized_cid compound = pc.get_compounds(cid)[0] return compound.isomeric_smiles
5,354,038
def view_static(request, **kwargs): """Outputs static page.""" template = kwargs.get('template', None) if not template: raise Http404 template = '.'.join([template, 'html']) title = kwargs.get('title', 'static page') img = kwargs.get('img', 'bgag.jpg') return render_to_response(temp...
5,354,039
def start_call(called_ident, skicall): """When a call is initially received this function is called. Unless you want to divert to another page, this function should return called_ident which would typically be the ident of a Responder or Template page dealing with the call. If a ServeFile excep...
5,354,040
def getmemory(): """ Returns the memory limit for data arrays (in MB). """ return NX_MEMORY
5,354,041
def get_object_syncing_state(): """ Get a dictionary mapping which object trackers are active. The dictionary contains name:bool pairs that can be fed back into the func:`set_object_syncing_state()` function. """ states = { "selection": bool(this._on_selection_changed_cb_id), "duplic...
5,354,042
def determine_nohit_score(cons, invert): """ Determine the value in the matrix assigned to nohit given SeqFindr options :param cons: whether the Seqfindr run is using mapping consensus data or not :param invert: whether the Seqfindr run is inverting (missing hits to ...
5,354,043
def handle_requests(): """ This function handle requests. """ while True: requests_batch = [] while not ( len(requests_batch) > BATCH_SIZE or (len(requests_batch) > 0 and time.time() - requests_batch[0]['time'] > BATCH_TIMEOUT) ): try: ...
5,354,044
def changesettings(): """ Changes global settings. Arguments: none User input: The setting to change: retrievecount and channelcount = the number of posts fetched from the server. No input validation. """ global retrievecount, channelcount choice = input((""" | settings | gc = change general count? ({0}...
5,354,045
def estimate_csd(lfp, coord_electrode, sigma, method='standard', diam=None, h=None, sigma_top=None, tol=1E-6, num_steps=200, f_type='identity', f_order=None): """ Estimates current source density (CSD) from local field potential (LFP) recordings from multiple depths of the ...
5,354,046
def library_get_monomer_desc(res_name): """Loads/caches/returns the monomer description objec MonomerDesc for the given monomer residue name. """ assert isinstance(res_name, str) try: return MONOMER_RES_NAME_CACHE[res_name] except KeyError: pass mon_desc = library_construct...
5,354,047
def parse_single_sequence_example( serialized, context_features=None, sequence_features=None, example_name=None, name=None): # pylint: disable=line-too-long """Parses a single `SequenceExample` proto. Parses a single serialized [`SequenceExample`](https://www.tensorflow.org/code/tensorflow/core/example/e...
5,354,048
def getBase64PNGImage(pD, cmapstr, logfloor_quantile=0): """ Get an image as a base64 string """ D = np.array(pD) if logfloor_quantile > 0: floor = np.quantile(pD.flatten(), logfloor_quantile) D = np.log(D + floor) c = plt.get_cmap(cmapstr) D = D-np.min(D) D = np.round(25...
5,354,049
def iter_objects(inst, exp_type): """Iterate over all descriptor objects accessible from inst. Yields (name, obj) tuples.""" seen = set() # Note: The visibility rules here aren't exactly right, but I # think it's fine for our purposes. The difference only comes up # if the user is dynamically ...
5,354,050
def method_dispatcher(*args, **kwargs): """Try to dispatch to the right HTTP method handler. If an HTTP method isn't on the approved list, defer to the error handler. Otherwise, the HTTP Method is processed by the appropriate handler. :param args: Expect arguments in format (http_method, url). ...
5,354,051
def filter_pathways( pathways, source=None, target=None, compounds=[], enzymes=[], context={}, ): """ Yield pathways that meet filtering conditions. The effect of filterig parameters is explained below. Filters automatically pathways, that repeate...
5,354,052
def add_song_to_playlist(result): """ Add a song from the search results to the playlist. If the playlist already contains the song it will not be added again :param result: """ result_track = result["track"] result_score = result["score"] result_string = result_track["artist"] + " - " ...
5,354,053
def _seqfix(ref_seq, seq, comp_len, rev): """ Fill or trim a portion of the beginning of a sequence relative to a reference sequence Args: ref_seq (str): reference sequence e.g. germline gene seq (str): sequence to compare to reference comp_len (int): length of s...
5,354,054
def burn_volume_func(func_below, func_above, volume, surface_raster, height_to_z, below=False, ignore_nan=False, inclusive=False): """ Reusable function, not for end user. Process parts of a xyz volume given a surface, below or above the intersection of the volume with the surface """ dim_x,dim_y,dim_z=...
5,354,055
def get_dedup_tokens(logits_batch: torch.Tensor) \ -> Tuple[torch.Tensor, torch.Tensor]: """Converts a batch of logits into the batch most probable tokens and their probabilities. Args: logits_batch (Tensor): Batch of logits (N x T x V). Returns: Tuple: Deduplicated tokens. The first e...
5,354,056
def install( name=None, testnr=None, identity=None, delete=False, mount=True, email=None, words=None, server=False, zerotier=False, pull=True, secret=None, explorer=None, code_update_force=False, ): """ create the 3bot container and install jumpscale inside ...
5,354,057
def com(im): """ Compute the center of mass of im. Expects that im is leveled (ie zero-centered). Ie, a pure noise image should have zero mean. Sometimes this is improved if you square the im first com(im**2) Returns: y, x in array form. """ im = np.nan_to_num(im) mass = np.sum(i...
5,354,058
def merge_tiffs(root): """ merge folds """ mergefolder = os.path.join(root, 'merged') if not os.path.exists(mergefolder): os.makedirs(mergefolder) prob_files = {f for f in os.listdir(root) if os.path.splitext(f)[ 1] in ['.tif', '.tiff']} unfolded = {f[6:] for f in prob_files...
5,354,059
def get_fitting_custom_pipeline(): """ Pipeline looking like this lagged -> custom -> ridge """ lagged_node = PrimaryNode('lagged') lagged_node.custom_params = {'window_size': 50} # For custom model params as initial approximation and model as function is necessary custom_node =...
5,354,060
def get_regularizable_variables(scope): """ Get *all* regularizable variables in the scope. :param scope: scope to filter variables by :return: """ return tf.get_collection(REGULARIZABLE_VARS, scope)
5,354,061
def TestRapiInstanceReplaceDisks(instance): """Test replacing instance disks via RAPI""" if not IsDiskReplacingSupported(instance): print qa_logging.FormatInfo("Instance doesn't support disk replacing," " skipping test") return fn = _rapi_client.ReplaceInstanceDisks _Wait...
5,354,062
def check_state(seat): """Check whether the rules may be applied on given seat. If no occupied seat around - add to list of seats to occupy. If more than or exactly 4 seats are occupied, add to the list to release.""" occupied = 0 neighbours = find_neighbours(seat) for neighbour in neighbours: ...
5,354,063
def load(midi_path: str, config: dict): """ returns a 3-tuple of `tf.Dataset` each returning `(input_seq, target_seq)`, representing train, validation, and test portions of the overall dataset. `input_seq` represents the `inp_split` portion of each midi sequence in `midi_path`. """ batch_size = config...
5,354,064
def update_config(from_cli, from_file): """Merge the two given dictionaries Updates the first dict with items from second if they're not already defined""" from_cli.update( { key: val for key, val in from_file.items() # Keep item if it is not already defined ...
5,354,065
def test_page_title_specified_two_pages(tmp_path, param): """For parameters that require that only one page is in config - make sure exception is raised if there are more pages in the config""" config_file = mk_tmp_file( tmp_path, key_to_update="pages.page2", value_to_update={"page_t...
5,354,066
def git(command): """ Run the given git command. Args: command (str): Complete git command with or without the binary name. """ command = command.split() command = ["git"] + command if command[0] != "git" else command run(command, stdout=PIPE, stderr=PIPE, check=True)
5,354,067
async def test_form_create_entry_without_auth(hass): """Test that the user step without auth works.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == SOURCE_US...
5,354,068
def _parse_docstring(doc): """Extract documentation from a function's docstring.""" if doc is None: return _Doc('', '', {}, []) # Convert Google- or Numpy-style docstrings to RST. # (Should do nothing if not in either style.) # use_ivar avoids generating an unhandled .. attribute:: directiv...
5,354,069
def extract_remove_outward_edges_filter(exceptions_from_removal): """ This creates a closure that goes through the list of tuples to explicitly state which edges are leaving from the first argument of each tuple. Each tuple that is passed in has two members. The first member is a string representing a sing...
5,354,070
def test_query_request_validator_username_present_but_empty(): """Tests the QueryRequestValidator class with empty username. Expects validation failure and correct error message.""" request = create_mock_request(master_password='abcd', master_key='1234', ...
5,354,071
def ln_addTH(x : torch.Tensor, beta : torch.Tensor) -> torch.Tensor: """ out = x + beta[None, :, None] """ return x + beta[None, :, None]
5,354,072
def drude2(tags, e, p): """dielectric function according to Drude theory for fitting""" return drude(e, p[0], p[1], p[2], p[3])
5,354,073
def ParseFile(path): """Parse function names and comments from a .h path. Returns mapping from function name to comment. """ result = {} with open(path, 'r') as fp: lines = fp.readlines() i = 0 n = len(lines) while i < n: line = lines[i] m = MCRE.match(line) if m and not m.g...
5,354,074
def get_records(data: Dict[_Expr, Dict], column_order): """Output data as a list of records""" def cell_callback(expr, i, val, spreadsheet_data): spreadsheet_data[-1].append(val) return spreadsheet_data def row_callback(spreadsheet_data): spreadsheet_data[-1] = tuple(spreadsheet_data...
5,354,075
def support_mask_to_label(support_masks, n_way, k_shot, num_points): """ Args: support_masks: binary (foreground/background) masks with shape (n_way, k_shot, num_points) """ support_masks = support_masks.view(n_way, k_shot*num_points) support_labels = [] for n in range(support_masks.shap...
5,354,076
def cal_covered_users(positions, heat_map, radius): """ :param positions: $k$ positions array of !!!(y, x)!!! :param heat_map: grid data with count :param radius: 0(1 grid), 1(8 grids), 2(25 grids) :return: coverage score """ row_num, col_num = heat_map.shape mask = np.zeros(heat_map.sha...
5,354,077
def certificate_from_file( filename: Union[str, pathlib.Path], format=OpenSSL.crypto.FILETYPE_PEM, ) -> TS.X509: """Load an X509 certificate from ``filename``. :param filename: The path to the certificate on disk. :param format: The format of the certificate, from :doc:`OpenSSL:api/crypto`. """...
5,354,078
def import_syllable_csv(corpus_context, call_back=None, stop_check=None): """ Import a syllable from csv file Parameters ---------- corpus_context: :class:`~polyglotdb.corpus.syllabic.SyllabicContext` the corpus to load into """ import time speakers = corpus_context.speakers ...
5,354,079
def redistributeHitsForNode(node, hits, rank): """ recursive call used by redistributeHits if rank is not rank and any children have hits, redistribute hits to children """ if rank is not None and rank == node.rank: logger.debug("Node %s has rank %s, skipping" % (node.name, rank)) ...
5,354,080
def get_welcome_response(session): """ Welcome the user to my python skill """ card_title = "Welcome" speech_output = "Welcome to my python skill. You can search for GitHub repositories. " # If the user either does not reply to the welcome message or says something # that is not understood...
5,354,081
def password_dialog(title, message): """ Show a Gtk password dialog. :param str title: :param str message: :returns: the password or ``None`` if the user aborted the operation :rtype: str :raises RuntimeError: if Gtk can not be properly initialized """ Gtk = require_Gtk() builde...
5,354,082
def addFiles(path, tar, exclude_func): """ Add files in path to tar """ for root, dirs, files in os.walk(path): files.sort() # sorted page revs may compress better for name in files: path = os.path.join(root, name) if exclude_func(path): continue ...
5,354,083
def rotate_quaternion ( angle, axis, old ): """Returns a quaternion rotated by angle about axis relative to old quaternion.""" import numpy as np # Note that the axis vector should be normalized and we test for this # In general, the old quaternion need not be normalized, and the same goes for the res...
5,354,084
def apogeeSpectroReduxDirPath(dr=None): """ NAME: apogeeSpectroReduxDirPath PURPOSE: returns the path of the spectro dir INPUT: dr= return the path corresponding to this data release OUTPUT: path string HISTORY: 2014-11-25 - Written - Bovy (IAS) """...
5,354,085
def rochepot_dl(x, y, z, q): """ Dimensionless Roche potential (:math:`\\Phi_n`, synchronous rotation) More massive component (:math:`m_1`) is centered at (x,y,z) = (0,0,0). Less massive component (:math:`m_2`) is at (1,0,0). The unit of length is the distance between the objects. Both objects ...
5,354,086
def health_check(config): """ Tests the API to ensure it is working. """ itglue = ITGlue(config['api_key'], config['itglue_host']) try: itglue._make_request('organizations', {}) return True except: return False
5,354,087
def capture_image(resolution=(1024, 768), size=(320, 240), sleep=2): """ Captures image from raspberry pi camera resolution -- resolution of capture size -- size of output sleep -- sleep time in seconds """ stream = io.BytesIO() with picamera.PiCamera() as camera: #camera.led = F...
5,354,088
def MLVR(XDATA,YDATA,xreference=0,residual=1,xlabel='',ylabel='',title='',alpha = 0.01,iters = 1000,plot=1): """Does Multivariant Linear Regression properties: XDATA = The Feature Dataframe YDATA = The Target Dataframe xreference = 1/0 -> The column index in XDATA for ploting graph xlabel = Label for X in Gr...
5,354,089
def test_modifier_with_nested_modifier(): """Test instantiation of potential forms that has a modifier that has a nested modifier in its argument list""" k = u"A" v = u"zero >=1.0 sum(nested(constant 1.0 >2 zero), buck 10.0 0.1 32.0)" parser = ConfigParser(io.StringIO()) potential_forms = [ PMT(u'nest...
5,354,090
def FilterAndTagWrapper(target, dontRemoveTag=False): """\ Returns a component that wraps a target component, tagging all traffic going into its inbox; and filtering outany traffic coming out of its outbox with the same unique id. """ if dontRemoveTag: Filter = FilterButKeepTag else:...
5,354,091
def print_progress_bar(count: int) -> None: """Print progress bar in 20% increments. Args: count (int): Number of 1000 query chunks. """ # left side of progress bar progress_bar = '[' # Fill in progress bar for i in range(0, count): progress_bar += '#' #...
5,354,092
def format_time(seconds: Union[int, float]) -> str: """Convert the seconds to human readable string with days, hours, minutes and seconds.""" s = int(np.rint(seconds)) if s < 60: return "{0}s".format(s) elif s < 60 * 60: return "{0}m {1:02}s".format(s // 60, s % 60) elif s < 24 * 60...
5,354,093
def run_model(df, i, name, gscv, calibrate=True): """Given customercode values in dict_folds, 1. create balanced dataset 2. split into train, test sets 3. run grid search 4. get probability scores 5. calibrate as directed 6. find optimal cutoff from precision-recall 7. return predictions...
5,354,094
def launch_process(a_project, a_routine, a_work_text, a_done_text, a_focus_on_error=False, a_always_focus=False, post_routine=None): """ Standard launch for eiffel tools buffer management. It create/show the eiffel tools buffer in a window, launch `a_routine' wi...
5,354,095
def prepare_runkos(main_dir, discard_file=None): """Identify the positions with variations between 0.2 to 0.8 in the training population and calculate the mean and std for the variation. """ THRESHOLD_DROPNA = 32 # more than 40 columns should have a value not a nan. file_count = 0 list_of_dfs ...
5,354,096
def extract_date(db): """Extract Release Date from metadata and convert it into YYYY MM format""" date_pattern = 'releaseDate\":(\d{9,10})' def format_date(x): """Takes epoch time as argument and returns date in YYYY MM format""" date = re.search(date_pattern, x) if date: ...
5,354,097
def set_provisioner_data(response, metrics, pod_name, pod_details): """ Update provisioner related metrics""" # Data from provisioner is the source of truth # Update only those metrics.storages data which is present in # provisioner, rest will remain with default values. storage_data_from_csi = res...
5,354,098
def split_test_image(aa): """ Separate image created by mk_test_image into x,y components """ if aa.dtype.kind == 'f': y = np.round((aa % 1)*1024) x = np.floor(aa) else: nshift = (aa.dtype.itemsize*8)//2 mask = (1 << nshift) - 1 y = aa & mask x = aa >>...
5,354,099