content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_domain_from_url(url): """get domain from url""" domain='' # url is http://a.b.com/ads/asds if re.search(r'://.*?/',url): try: domain = url.split('//', 1)[1].split('/', 1)[0] except IndexError, e: LOGGER.warn('Get domain error,%s,%s' % (url, e)) # http:...
6b364a74c86337108d21539c4a5678af2e6ea48a
3,644,900
import json def render_response(body=None, status=None, headers=None): """生成WSGI返回消息""" headers = [] if headers is None else list(headers) if body is None: body = '' status = status or (204, 'No Content') else: body = json.dumps(body, encoding='utf-8') headers.append((...
b31128db57ca99a840d4adce6f3116f629d8a0b8
3,644,901
def tests(request): """Print a list of tests.""" test_list = Test.objects.all() tag_list = Tag.objects.all().order_by(u'name') # check if we need to filter the test list based on tags # defaults to empty list because we're always passing the list to the template tags = request.GET.get(u'tag', [...
18c4077878f3864cf0771fd77a5ae324d9ee4630
3,644,902
def nashpobench_benchmark(params): """ The underlying tabulated blackbox does not have an `elapsed_time_attr`, but only a `time_this_resource_attr`. """ config_space = dict( CONFIGURATION_SPACE, epochs=params['max_resource_level'], dataset_name=params['dataset_name']) re...
74e1e619cc8c4a3201e41820f5f641c651a5f283
3,644,903
def horizontal_plate_natual_convection_2(Gr, Pr): """hot side downward, or cold side upward """ """ 1e5 < Ra < 1e10 """ Ra = Gr * Pr return 0.27 * Ra**0.25
bc44118e871e977a7ecb6a877f7232b837d1bf0e
3,644,904
import dill as pickle from drivebuildclient import create_client, send_request from config import SIM_NODE_PORT, FIRST_SIM_PORT from typing import Tuple def run_test_case(test_case: TestCase) -> Tuple[Simulation, Scenario, ExtThread, SimulationID]: """ This method starts the actual simulation in a separate th...
b8428763cb611b57069d74f7ebb5844f5b90df9d
3,644,905
import typing def translate_value_data( new_values: list, options: dict, parent_value: str, translate_dict: typing.Optional[dict], values: list, ): """Translates value data if necessary and checks if it falls within the Castor optiongroup""" for value in values: if pd.isnull(parent...
ccfc64e54fae868877c6852ebeeadae11bb1221b
3,644,906
def makeVocabFromText( filelist=None, max_size=10*10000, least_freq=2, trunc_len=100, filter_len=0, print_log=None, vocab_file=None, encoding_format='utf-8', lowercase = True): """ the core of this function...
2a3c0c42ee5c541d19bbe695c12f977fd29dfeaf
3,644,907
def import_supplemental(file_path): """Get data from a supplemental file""" data = sio.loadmat(file_path) data['move'] = np.squeeze(data['move']) data['rep'] = np.squeeze(data['rep']) data['emg_time'] = np.squeeze(data['emg_time']) return data
4544a0ee292cb4e323c31545009c4d1e17ca98e1
3,644,908
def _unpickle_injected_object(base_class, mixin_class, class_name=None): """ Callable for the pickler to unpickle objects of a dynamically created class based on the InjectableMixin. It creates the base object from the original base class and re-injects the mixin class when unpickling an object. :p...
1821509506ad31dcdb21f07a2b83c544ff3c3eb3
3,644,909
from pathlib import Path import re def parse_endfblib(libdir): """Parse ENDF/B library Parametres: ----------- libdir : str directory with ENDFB file structure""" filepaths = [] nuclidnames = [] endf_dir = Path(libdir) neutron_files = tuple((endf_dir / "neutrons").glob("*endf"))...
3587b849132e4b2eeb6ad184bf58755340473bd9
3,644,910
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser def get_parser(): """Get parser object.""" parser = ArgumentParser( description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter ) parser.add_argument( "-f", "--file", dest="filename", hel...
31f973d357762fa706191caa1d76f59c6d2b3d67
3,644,911
def build_val_col_list(tableName): """Build and return a schema to use for the sample data.""" statement = "( SELECT column_name, data_type, case when data_type='NUMBER' THEN NVL(DATA_PRECISION,38) + DATA_SCALE ELSE DATA_LENGTH END AS ORACLE_LENGTH FROM dba_tab_columns WHERE table_name = '" + tableName + "' or...
d6602078a458fa3f36de3558c8044749caf7f4d5
3,644,912
from datetime import datetime def save_image(user, filename, image_tif, process, latency, size, hist): """ Function that saves image to Mongo database Args: user: username filename: desired file name in database image_tif: tiff image in byte format process: processing algo...
ea416fcdc09c71aef56250a8e0b7f558e8e8a884
3,644,913
def run_simulation_with_params( sim_params, replicate, repeats=10, should_perform_gwas=True): """Runs simulation with given params and returns result object. """ try: simulation_result = run_simulation( simulation_params=sim_params) except Exception as e: print si...
a7a1383708c1b6e69c975488b03704698f9b1066
3,644,914
import colorsys def hsl_to_rgb(hsl): """Convert hsl colorspace values to RGB.""" # Convert hsl to 0-1 ranges. h = hsl[0] / 359. s = hsl[1] / 100. l = hsl[2] / 100. hsl = (h, s, l) # returns numbers between 0 and 1 tmp = colorsys.hls_to_rgb(h, s, l) # convert to 0 to 255 r = int...
4417ce8468e71b7139b57fe270809c7030b2c3df
3,644,915
import os def init_celery(app=None): """ Initialize celery. """ app = app or create_app(os.environ.get('APP_MODE')) celery.conf.update(app.config.get("CELERY", {})) class ContextTask(celery.Task): """ Make celery tasks work with Flask app context """ def __call...
8d0c6f6bc4882976812abe9967b56720b745b46a
3,644,916
import itertools async def test_filterfalse_matches_itertools_filterfalse( arange: ty.Type[ty.AsyncIterator[int]], stop: int ): """Ensure that our async filterfalse implementation follows the standard implementation. """ async def _pair(x): return (x % 2) == 0 target = list(itertool...
59fd932f3906eb411e21207d920f752f7f78df44
3,644,917
def extract_buffer_info(mod, param_dict): """ This function is to read the tvm.IRModule that contains Relay to TIR compiled IRModule. Thereafter, this will extract the buffer information as the shape and constant data (if any). Parameters ---------- mod : tvm.IRModule The NPU TI...
291f091d06aa768ceb28f2738823f5eeb336c47e
3,644,918
def find_external_nodes(digraph): """Return a set of external nodes in a directed graph. External nodes are node that are referenced as a dependency not defined as a key in the graph dictionary. """ external_nodes = set() for ni in digraph: for nj in digraph[ni]: if nj not i...
de63af1b649e450214907dd704bde782820d393d
3,644,919
import six def strip(val): """ Strip val, which may be str or iterable of str. For str input, returns stripped string, and for iterable input, returns list of str values without empty str (after strip) values. """ if isinstance(val, six.string_types): return val.strip() try: ...
893986e69f6d64167f45daf30dacb72f4b7f2bff
3,644,920
from matplotlib.backends.backend_pdf import PdfPages import os from datetime import datetime def durations_histo(filename: str, v1_2_1, v1_5_2): """Generate all the figures for the histograms. Returns a dictionary of dict with dict containing the full filename. """ ensure_path(os.path.dirname(filename...
6d05a7af348f4b88bf0437feb81a0f5172514d87
3,644,921
def construct_area_cube(var_name, area_data, global_atts, dim_coords): """Construct the new area cube """ dim_coords_list = [] for i, coord in enumerate(dim_coords): dim_coords_list.append((coord, i)) if var_name == 'areacello': long_name = 'Grid-Cell Area for Ocean Variables' else...
07c01610f800202ccbdebf834648840b77d47fb7
3,644,922
def _switch_obs_2_time_dim(ds): """Function to create a single time variable that is the midpoint of the ObsPack averaging interval, and make it the xarray coordinate. """ # Get the midpoint of the average pulled from the model: midpoint = pd.to_datetime(ds.averaging_interval_start.data) + \ n...
6fa53b3f1a0472f45fa59c11b5d869786b5a9f4f
3,644,923
def bitfield_v(val, fields, col=15): """ return a string of bit field components formatted vertically val: the value to be split into bit fields fields: a tuple of (name, output_function, (bit_hi, bit_lo)) tuples """ fmt = '%%-%ds: %%s' % col s = [] for (name, func, field) in fields: s.append(fmt % ...
139b9328190f61a1cd649826bfde806e565d4201
3,644,924
from typing import Tuple from typing import Iterable def split_housenumber_line(line: str) -> Tuple[str, bool, bool, str, Tuple[int, str], str, Tuple[int, str], Iterable[str], Tuple[int, str]]: """ Augment TSV Overpass house numbers result lines to aid sorting. ...
c3d93d459c9b004d199725b11e1b92340e6154b9
3,644,925
import math def tau_polinomyal_coefficients(z): """ Coefficients (z-dependent) for the log(tau) formula from Raiteri C.M., Villata M. & Navarro J.F., 1996, A&A 315, 105-115 """ log_z = math.log10(z) log_z_2 = log_z ** 2 a0 = 10.13 + 0.07547 * log_z - 0.008084 * log_z_2 a1 = -4.424 - ...
ebef7d773eeb400ef87553fc5838ee2cb97d0669
3,644,926
from typing import Optional import this def register( # lgtm[py/similar-function] fn: callbacks.ResourceHandlerFn, *, id: Optional[str] = None, errors: Optional[errors_.ErrorsMode] = None, timeout: Optional[float] = None, retries: Optional[int] = None, backoff:...
d2e539c97a4946f819616d0f596e68e190a68c78
3,644,927
def pd_read_csv_using_metadata(filepath_or_buffer, table_metadata, ignore_partitions=False, *args, **kwargs): """ Use pandas to read a csv imposing the datatypes specified in the table_metadata Passes through kwargs to pandas.read_csv If ignore_partitions=True, assume that partitions are not columns i...
bddc8da985c7e252effe566c640bca25acd01d6a
3,644,928
def read_parfile_dirs_props(filename): """Reads BRUKER parfile-dirs.prop file to in order to get correct mapping of the topspin parameters. Args: filename: input Bruker parfile-dirs.prop file Returns: A dict mapping parameter classes to the their respective directory. E.g. ...
ca54dc948923826bb81af94e41be42caadfe6004
3,644,929
def get_all_playlist_items(playlist_id, yt_client): """ Get a list of video ids of videos currently in playlist """ return yt_client.get_playlist_items(playlist_id)
c7a8cc806b552b1853eba1d8223aa00225d5539e
3,644,930
def _get_last_measurement(object_id: int): """ Get the last measurement of object with given ID. Args: object_id (int): Object ID whose last measurement to look for. Returns: (GamMeasurement): The last measurement of the object, or None if it doesn't exist. """ last_mea = (GamM...
a5ee460f57912bb885ae0cb534f6195c92983aad
3,644,931
def get_library_isotopes(acelib_path): """ Returns the isotopes in the cross section library Parameters ---------- acelib_path : str Path to the cross section library (i.e. '/home/luke/xsdata/endfb7/sss_endfb7u.xsdata') Returns ------- iso_array: array array of ...
d93d319b84c02b8156c5bad0998f5943a5bbe8ae
3,644,932
from typing import Mapping def read_wires(data: str) -> Mapping[int, Wire]: """Read the wiring information from data.""" wires = {} for line in data.splitlines(): wire_name, wire = get_wire(line) wires[wire_name] = wire return wires
87c8b82bceab0252204ababf842ca0b00ab6a059
3,644,933
def back_ease_out(p): """Modeled after overshooting cubic y = 1-((1-x)^3-(1-x)*sin((1-x)*pi))""" f = 1 - p return 1 - (f * f * f - f * sin(f * pi))
9946b8929211df4624ecc201ce026b981ffb3d0c
3,644,934
def configure_estimator_params(init_args, train_args): """Validates the initialization and training arguments and constructs a `params` dictionary for creating a TensorFlow Estimator object.""" params = {} init_val = ArgumentsValidator(init_args, "Initialization arguments") with init_val: params["rm_dir...
f132eaa4077dd197faed72d6805f15255b7dd680
3,644,935
def bit_lshift(bin_name, bit_offset, bit_size, shift, policy=None): """Creates a bit_lshift_operation to be used with operate or operate_ordered. Server left shifts bitmap starting at bit_offset for bit_size by shift bits. No value is returned. Args: bin_name (str): The name of the bin contain...
3e8224a3f48eade9ee01a43819b4c6aa88ef308e
3,644,936
def compute_ccas(sigma_xx, sigma_xy, sigma_yx, sigma_yy, epsilon, verbose=True): """Main cca computation function, takes in variances and crossvariances. This function takes in the covariances and cross covariances of X, Y, preprocesses them (removing small magnitudes) and outputs the raw results...
67827220cdbdd41250a8a40f140c8c21e0625df7
3,644,937
def generate_samples( segment_mask: np.ndarray, num_of_samples: int = 64, p: float = 0.5 ) -> np.ndarray: """Generate samples by randomly selecting a subset of the segments. Parameters ---------- segment_mask : np.ndarray The mask generated by `create_segments()`: An array of shape (image_w...
99ee42abf95bd338714e42beee42610e3ac2f09d
3,644,938
def get_mix_bandpassed(bp_list, comp, param_dict_file=None,bandpass_shifts=None, ccor_cen_nus=None, ccor_beams=None, ccor_exps = None, normalize_cib=True,param_dict_override=None,bandpass_exps=None,nus_ghz=None,btrans=None, dust_beta_para...
d4693e41c755dd1067c371bfa740ce1436dfc85a
3,644,939
def partition(data, label_name, ratio): """ Partitions data set according to a provided ratio. params: data - The data set in a pandas data frame label_name - the name of the collumn in the data set that contains the labels ratio - the training/total data ratio returns: ...
6f00c8df9e5fb42f4e3fb01744215214e732f441
3,644,940
import os def find_background2(data, mask, channels, apertureset_lst, method='poly', scale='linear', scan_step=200, xorder=2, yorder=2, maxiter=5, upper_clip=3, lower_clip=3, extend=True, display=True, fig_file=None, reg_file=None): """Subtract the background for an input FITS image. ...
20ed1499ed23252fb5d24cf892e3cd169b0027b9
3,644,941
def get_piesocket_api_key(): """ Retrieves user's Piesocket API key. Returns: (str) Piesocket API key. Raises: (ImproperlyConfigured) if the Piesocket API key isn't specified in settings. """ return get_setting_or_raise( setting="PIESOCKET_API_KEY", setting_str="PieSoc...
657bba650a914ed1a15d54b9d0000f37b99568d0
3,644,942
def downsample(myarr,factor,estimator=np.mean): """ Downsample a 2D array by averaging over *factor* pixels in each axis. Crops upper edge if the shape is not a multiple of factor. This code is pure numpy and should be fast. keywords: estimator - default to mean. You can downsample by sum...
45b6422cb7f9b01512bc4860229164b043201675
3,644,943
def getActiveWindow(): """Returns a Window object of the currently active Window.""" # Source: https://stackoverflow.com/questions/5286274/front-most-window-using-cgwindowlistcopywindowinfo windows = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListExcludeDesktopElements | Quartz.kCGWindowListOptionOn...
ca1c810525f0a49cd9f4b53d0d621cb39b3b733e
3,644,944
def _derivative_log(x): """Chain rule on natural log = (1/x)*(dx/dr)""" return _protected_inverse(x[0])[:, :, np.newaxis, np.newaxis]*x[1]
5f4bf5416575126cd93adaee6ccfca942ad6218f
3,644,945
def svn_wc_merge_props(*args): """ svn_wc_merge_props(svn_wc_notify_state_t state, char path, svn_wc_adm_access_t adm_access, apr_hash_t baseprops, apr_array_header_t propchanges, svn_boolean_t base_merge, svn_boolean_t dry_run, apr_pool_t pool) -> svn_error_t """ return _wc.svn_w...
54187e010f71798bee90eb179a10da11bf410fce
3,644,946
def is_paused(): """ Return True if is_paused is set in the global settings table of the database. """ try: is_paused_val = Settings.objects.get().is_paused except ObjectDoesNotExist: is_paused_val = False return is_paused_val
59b99d4a4842e14205376d7923d3e5c8b52c30a6
3,644,947
def info_request(request): """Information request form.""" if request.method == 'POST': form = InfoRequestForm(request.POST) if form.is_valid(): cd = form.cleaned_data # create out recipient list to = [] # cleaned_data converts the data to a list s...
124d2fc36823fb4e1c7b569c0c6d9c75a93297e8
3,644,948
import itertools def get_accurate(clustering_res_df, cluster_number, error=False): """ :param clustering_res_df: a pandas DataFrame about clustering result :param cluster_number: the number of the cluster (the first column is the index, the second column is the right information, the third col...
7ba71bcd82e70d9344994f9b6a2133676d58f683
3,644,949
import json def odict_to_json(odict): """ Dump an OrderedDict into JSON series """ json_series = json.dumps(odict) return json_series
d18a4e0f0d11a2c529edb395671052f15ad8071d
3,644,950
import ast def parenthesize(node: ast.AST, _nl_able: bool = False) -> str: """Wrap the un-parsed node in parentheses.""" return f"({unparse(node, True)})"
d61d6be6e5466559cdaba0602a95f3169d74aa36
3,644,951
def stack_nested_arrays(nested_arrays): """Stack/batch a list of nested numpy arrays. Args: nested_arrays: A list of nested numpy arrays of the same shape/structure. Returns: A nested array containing batched items, where each batched item is obtained by stacking corresponding items from the list ...
bf1e4bd35be871b9098d9789b189c48f36329646
3,644,952
from sys import version def temporal_statistics(da, stats): """ Obtain generic temporal statistics using the hdstats temporal library: https://github.com/daleroberts/hdstats/blob/master/hdstats/ts.pyx last modified June 2020 Parameters ---------- da : xarray.DataArray Da...
b3be6d8260a70dcb697de39dd04d146e53907997
3,644,953
def encode_data(data): """ Helper that converts :class:`str` or :class:`bytes` to :class:`bytes`. :class:`str` are encoded with UTF-8. """ # Expect str or bytes, return bytes. if isinstance(data, str): return data.encode('utf-8') elif isinstance(data, bytes): return data ...
3cd54389719439e8f18cf02b110af07799c946b5
3,644,954
def get_apps_final(the_apps_dummy): """ 计算出: 1.每个用户安装app的数量; 2.每个用户安装小众app的数量; 3.每个用户安装大众app的数量; 4.根据每个用户安装app的向量进行Mean-shift聚类的结果 """ core_data = the_apps_dummy.drop(['id'], axis=1) the_apps_final = get_minor_major(core_data, 'apps', 5, 90) # new_core_data = col_cluster(core_d...
afe92cf7fb79ac73464f7e9189bb56608e0fd424
3,644,955
from indico.modules.events.abstracts.util import (get_events_with_abstract_reviewer_convener, get_events_with_abstract_persons) from indico.modules.events.contributions.util import get_events_with_linked_contributions from indico.modules.events.papers.util import get_events_with_paper_roles from indico.modules.events.r...
145f33cec0b79d74ea1550d22fc8599484d2b16d
3,644,956
import time import os def get_run_callback(run_text, output_dir): """ function to generate tf run callback for tensor board """ root_logdir = f'{output_dir.rstrip("/")}/tensorboard_logs/' run_id = time.strftime(f'{run_text}_%Y_%m_%d-%H-%M-%S') log_path = os.path.join(root_logdir, run_id) t...
f5275515b061446fd2be0cd79ed4fa583a23f80a
3,644,957
def bert_keyword_expansion(keywords: str, num_similar: int, bert_model, tokenizer, bert_embedding_dict): """ Keyword expansion outputs top N most similar words from vocabulary. @param keywords: stri...
5976a52cfcdd8d80f1b3b0fcc0d32b92f40a1f62
3,644,958
def utc_to_tt_offset(jday=None): """Returns the offset in seconds from a julian date in Terrestrial Time (TT) to a Julian day in Coordinated Universal Time (UTC)""" if use_numpy: return utc_to_tt_offset_numpy(jday) else: return utc_to_tt_offset_math(jday)
f40c82840253cc9b9f1f9a2685134b9313cb42d1
3,644,959
from typing import Any import aiohttp async def get_async_request(url: str) -> [int, Any]: """Get the data from the url provided. Parameters ---------- url: str url to get the data from Returns ------- [int, Any] Tuple with the Response status code and the data returned f...
2ad07bf7394d4d7804802d201fab0027171bea3d
3,644,960
def scattering_probability(H, psi0, n_emissions, c_ops, tlist, system_zero_state=None, construct_effective_hamiltonian=True): """ Compute the integrated probability of scattering n photons in an arbitrary system. This function accepts a nonlinearly space...
d4509371303a729a160d1b3d92f5c5f2f8ac3339
3,644,961
def analytical_value_cond_i_shannon(distr, par): """ Analytical value of the conditional Shannon mutual information. Parameters ---------- distr : str-s Names of the distributions; 'normal'. par : dictionary Parameters of the distribution. If distr is 'normal': ...
a9a91d77863829de7f818aa6dcfe0216eb9a70af
3,644,962
from re import DEBUG import os def zexp(input, i=None): """ Point-wise complex exponential. :param input array: :param i bool: imaginary """ usage_string = "zexp [-i] input output" cmd_str = f'{BART_PATH} ' cmd_str += 'zexp ' flag_str = '' opt_args = f'' multituples =...
0a392013e3e7c5ac51d32f4fb7d228ecc3cf0250
3,644,963
def ekin2wl(ekin): """Convert neutron kinetic energy in electronvolt to wavelength in Angstrom""" if _np and hasattr(ekin,'__len__'): #reciprocals without zero division: ekinnonzero = ekin != 0.0 ekininv = 1.0 / _np.where( ekinnonzero, ekin, 1.0)#fallback 1.0 wont be used return ...
873ae25e10dfb3e6d9c6ca8ab1c56efa0066544a
3,644,964
def show_subscription(conn, customer): """ Retrieves authenticated user's plan and prints it. - Return type is a tuple, 1st element is a boolean and 2nd element is the response message from messages.py. - If the operation is successful; print the authenticated customer's plan and return tupl...
93a99075ea98697782845c2751362f9b319cea43
3,644,965
def maybe_gen_fake_data_based_on_real_data( image, label, reso, min_fake_lesion_ratio, gen_fake_probability): """Remove real lesion and synthesize lesion.""" # TODO(lehou): Replace magic numbers with flag variables. gen_prob_indicator = tf.random_uniform( shape=[], minval=0.0, maxval=1.0, dtype=tf.float...
fd3f1557930d63652f4dd39b2ba8031410bda711
3,644,966
def is_primitive_type (v) : """ Check to see if v is primitive. Primitive in this context means NOT a container type (str is the exception): primitives type are: int, float, long, complex, bool, None, str """ return type(v) in {int:0, float:0, long:0, complex:0, bool:0, None:0, str:0}
2d72e03aa1ec62f214b2a3b468948ff2354508dd
3,644,967
def _get_bit(h, i): """Return specified bit from string for subsequent testing""" h1 = int.from_bytes(h, 'little') return (h1 >> i) & 0x01
b9b672c87b35369dc86abec7005dfeed3e99eb67
3,644,968
def go_down_right_reward(nobs, high_pos, agent_num, act): """ Return a reward for going to the low or right side of the board :param nobs: The current observation :param high_pos: Tuple of lowest and most-right position :param agent_num: The id of the agent to check (0-3) :return: The reward f...
bd8c6f01b55e14cc498cc251b1c0cc92340506c7
3,644,969
def getChannelBoxMenu(): """ Get ChannelBox Menu, convert the main channel box to QT and return the Edit QMenu which is part of the channel box' children. :return: Maya's main channel box menu :rtype: QMenu """ channelBox = getChannelBox() # find widget menus = channelBox....
38957701044f4552cd355c8856abb8c3b486479b
3,644,970
def make_sid_cookie(sid, uri): """Given a sid (from a set-cookie) figure out how to send it back""" # sometime near 0.92, port got dropped... # uritype, uribody = urllib.splittype(uri) # host, path = urllib.splithost(uribody) # host, port = urllib.splitnport(host) # if port == -1: # port...
d194bcb8f47acfbbab9d7405ff9a23069b74f077
3,644,971
def identity_filter(element_tuple): """ element_tuple est consitute des (name, attrs) de chaque element XML recupere par la methode startElement """ return element_tuple
c50208f345f40acce58df86cdae4432aae24cf4b
3,644,972
def EoZ(N2, w0, f, ): """ Wave ray energy when variations can only occur in the vertical (i.e. N2 and flow only vary with depth not horizontally) - Olbers 1981 """ Ez = np.squeeze((w0**2 * (N2 - f**2)) / ((w0**2 - f**2)**(3 / 2) * (N2 - w0**2)**(1 / 2))) return Ez
7dfbcf3c0e29463ccf1663922486ffaad99b1ea5
3,644,973
from typing import Any def safe_string(value: Any) -> str: """ Consistently converts a value to a string. :param value: The value to stringify. """ if isinstance(value, bytes): return value.decode() return str(value)
0ba8dcfe028ac6c45e0c17f9ba02014c2f746c4d
3,644,974
def handle_older_version(upstream_version: Box) -> bool: """ Checks if the current version (local) is older than the upstream one and provides a message to the end-user. :return: :py:class:`True` if local is older. :py:class:`False` otherwise. """ version_utility = VersionUtility(PyFun...
130f825a59ca27a2e3d7d63e7d917f837153a2be
3,644,975
from typing import Union def tp(selector:Union[str, tuple]="@s", selector2:Union[str, tuple]=("~", "~", "~")): """ selector:Union[str, tuple] -> The position to be moved from selector2:Union[str, tuple] -> The position to be moved to """ if not ((isinstance(selector, str) or isinstance(selector, ...
81b3baf308f412bae3718fe165028a970fe56bda
3,644,976
def new_product() -> Product: """Generates an instance of Product with default values.""" return Product( product_id='', desc='', display_name='', capacity=0, image='')
ef50c2e90d5f512b2ae53c1111f501c13bdbca5d
3,644,977
def _rng_bit_generator_batching_rule(batched_args, batch_dims, *, shape, dtype, algorithm): """Calls RBG in a loop and stacks the results.""" key, = batched_args bd, = batch_dims if bd is batching.not_mapped: return lax.rng_bit_generator_p.bind(key, shape=shape, dtype=dtype, ...
6fdcdadb5a303a7f1f38033f7e69be781eee4a49
3,644,978
from typing import List def count_short_tail_keywords(keywords: List[str]) -> int: """ Returns the count of short tail keywords in a list of keywords. Parameters: keywords (List[str]): list with all keywords as strings. Returns: total (int): count of short tail keywords...
1af42d71be75d9279584a8c3edc090a39ec6cf77
3,644,979
def is_odd(number): """Determine if a number is odd.""" if number % 2 == 0: return False else: return True
4efe5114f2e25431808492c768abc0f750e63225
3,644,980
def fmt_quil_str(raw_str): """Format a raw Quil program string Args: raw_str (str): Quil program typed in by user. Returns: str: The Quil program with leading/trailing whitespace trimmed. """ raw_quil_str = str(raw_str) raw_quil_str_arr = raw_quil_str.split('\n') trimmed_qu...
e95c26f3de32702d6e44dc09ebbd707da702d964
3,644,981
from typing import Optional from typing import Collection from typing import cast def get_source_plate_uuid(barcode: str) -> Optional[str]: """Attempt to get a UUID for a source plate barcode. Arguments: barcode {str} -- The source plate barcode. Returns: {str} -- The source plate UUID; ...
b834d7740bfda86037d1d266c53f8618ff8e0bd3
3,644,982
def find_largest_digit(n): """ :param n: integers :return: the largest digit """ n = abs(n) # absolute the value if n < 10: return n else: return find_helper(n, 0)
f18af5c32263254e132ca405ad40c217083bd568
3,644,983
def extractChrononTranslations(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None item['title'] = item['title'].replace('’', '') if 'Weapons cheat'.lower() in item['title'].lower(): return bui...
3c4768745d54257d5654dac74b3278e95611288e
3,644,984
from sklearn.ensemble import RandomForestRegressor from sklearn.feature_selection import SelectFromModel def run_feature_selection(X, y, select_k_features): """Use a gradient boosting tree regressor as a proxy for finding the k most important features in X, returning indices for those features as output."...
0c730e2d2015b3ad0777cd493e2f5235bc9682a3
3,644,985
from typing import Optional from typing import Callable from typing import Literal def _not_json_encodable(message: str, failure_callback: Optional[Callable[[str], None]]) -> Literal[False]: """ Utility message to fail (return `False`) by first calling an optional failure callback. """ if failure_callback: ...
6979261a5f14a32c1ae34d01bad346344f38ed14
3,644,986
import functools def requires(*commands: str) -> RequiresT: """Decorator to require the given commands.""" def inner(func: ReturnT) -> ReturnT: """Decorates the function and checks for the commands.""" for command in commands: if not check_availability(command): ra...
a84199cfff7bf29a3a2c3ccb46cf65b3a09a7136
3,644,987
def _build_model(input_dim, num_classes, num_hidden_layers=0, hidden_dimension=128, normalize_inputs=False, dropout=0): """ Macro to generate a Keras classification model """ inpt = tf.keras.layers.Input((input_dim)) net = inpt # if we're normalizing input...
07386dbf2649463963d754959f7d389c1d2aae90
3,644,988
def get_client( project_id, cloud_region, registry_id, device_id, private_key_file, algorithm, ca_certs, mqtt_bridge_hostname, mqtt_bridge_port): """Create our MQTT client. The client_id is a unique string that identifies this device. For Google Cloud IoT Core, it must be in the format below."""...
6fa945892e7b0174e4fbfebc7e5f2f985982c6f0
3,644,989
def fake_image_sct_custom(data): """ :return: an Image (3D) in RAS+ (aka SCT LPI) space """ i = fake_image_custom(data) img = msct_image.Image(i.get_data(), hdr=i.header, orientation="LPI", dim=i.header.get_data_shape(), ) return img
9593240af25c3c4fc2cb8602dda902713721ebfb
3,644,990
def _get_property_header(resource, resource_type): """ Create a dictionary representing resources properties :param resource: The name of the resource for which to create a property header :param resource_type: The type of the resource (model, seed, etc.) :return: A dictionary representing ...
e9622282a83cfd1b0be5af54def817ed07ad8e21
3,644,991
def create_metapaths_parameters(filename, folder): """ creates a parameters file from the default """ default_filename = folder + PATHDELIM + 'resources'+ PATHDELIM + "template_param.txt" try: filep = open(default_filename, 'r') except: eprintf("ERROR: cannot open the default parameter ...
b859ee0791b3213cc48f253943122290ad5a67fa
3,644,992
def dist_prune(DELTA, prune=True): """ transform similarity matrix to distance matrix - prune matrix by removing edges that have a distance larger than condition cond (default mean distance) """ w = np.max(DELTA) DELTA = np.abs(DELTA - w) np.fill_diagonal(DELTA, 0.) if prune: ...
524c4f743ced455d67b276dfe4f66e9bcd2ca313
3,644,993
def bitwise_dot(x, y): """Compute the dot product of two integers bitwise.""" def bit_parity(i): n = bin(i).count("1") return int(n % 2) return bit_parity(x & y)
074b09a92e3e697eb08b8aaefa6ffd05d58698f4
3,644,994
import itertools def fit (samples, degree, sample_weights=None): """ Fit a univariate polynomial function to the 2d points given in samples, where the rows of samples are the points. The return value is the vector of coefficients of the polynomial (see p below) which minimizes the squared error of th...
4b7a7e77c5e55641a1a666f52abef32088bf680a
3,644,995
import os def get_engines(): """ Returns a list of all engines for tests """ engines = [] base_dir = os.getcwd() engines_dir = os.path.join(base_dir, 'search_engine_parser', 'core', 'engines') for filename in os.listdir(engines_dir): if os.path.isfile(os.path.join(engines_dir, filename))...
0b23da44ebd14c39f2e5b3ba240c37f3f3500cf9
3,644,996
import os def IsEncryptedCoredump(path): """ Function to find if the coredump is encrypted or not. """ if not os.path.exists('/bin/vmkdump_extract'): raise Exception('vmkdump_extract not present.') result, rc = RunCmd("/bin/vmkdump_extract -E {0}".format(path)) if rc != 0: raise Exce...
cbd15d8df2d9172a32c4f8e6f6cdd04e5d42c57f
3,644,997
def get_ahead_mask(tokens, i_pad=0): """ ahead mask 계산하는 함수 :param tokens: tokens (bs, n_seq) :param i_pad: id of pad :return mask: ahead and pad mask (ahead or pad: 1, other: 0) """ n_seq = tf.shape(tokens)[1] ahead_mask = 1 - tf.linalg.band_part(tf.ones((n_seq, n_seq)), -1, 0) ahea...
31a7bd2710cd86075f753227fa2e4c97b1948e19
3,644,998
def check_containment(row, query_index, reference_index, percent_identity=PERCENT_IDENTITY, covered_length=COVERED_LENGTH): """Checks if a row from a blast out format 6 file is a containment Takes in a row from a blast out format 6 table, a DataFrames with query sequence and reference sequence data. """ ...
a868d9c15abd5c73bc9483cc9a58d7c92875d15a
3,644,999