content
stringlengths
22
815k
id
int64
0
4.91M
def temporal_filter(record_date_time, time_or_period, op): """ Helper function to perform temporal filters on feature set :param record_date_time: datetime field value of a feature :type record_date_time: :class:`datetime.datetime` :param time_or_period: the time instant or time span to use as a fi...
3,700
def fill_replay_buffer(env, replay_buffer: ReplayBuffer, desired_size: int): """ Fill replay buffer with random transitions until size reaches desired_size. """ assert ( 0 < desired_size and desired_size <= replay_buffer._replay_capacity ), f"It's not true that 0 < {desired_size} <= {replay_buffer._...
3,701
def configure_logging(): """ Configure logging for pandoc subprocess. This is for use when passing Python filter modules to pandoc using the --filter option. """ format_string = ("%s: %%(name)s: [%%(levelname)s] %%(message)s" % __name__) logging.basicConfig(format=form...
3,702
def package_conda_env(folder: Union[str, Path]) -> Path: """Creates a .rar file of the current conda environment for use in jobs. For efficiency, existing tarred env are not updated. Parameter --------- folder: str/Path folder where the environment must be dumped Returns ------- ...
3,703
def get_couchbase_superuser_password(manager, plaintext: bool = True) -> str: """Get Couchbase superuser's password from file (default to ``/etc/gluu/conf/couchbase_superuser_password``). To change the location, simply pass ``GLUU_COUCHBASE_SUPERUSER_PASSWORD_FILE`` environment variable. :params manag...
3,704
def GetAvailableDialogs(): """Returns available dialogs in a list""" list_path = sys.path found = 0 for i in range (0,len(list_path)): if os.path.exists(list_path[i]+"/dialogs"): found = 1 break if found == 0: print ("Could not find /dialogs directo...
3,705
def convert_rgb2gray(image, convert_dic): """convert rgb image to grayscale Parameters ---------- image: array RGB image. Channel order should be RGB. convert_dic: dict dictionary key is str(rgb list), value is grayscale value Returns ------- image_gray: array Grayscale im...
3,706
def get_external_storage_path(): """Returns the external storage path for the current app.""" return _external_storage_path
3,707
def organize_stanford_data(path=None, clear_previous_afq=False): """ If necessary, downloads the Stanford HARDI dataset into DIPY directory and creates a BIDS compliant file-system structure in AFQ data directory: ~/AFQ_data/ └── stanford_hardi ├── dataset_description.json └── derivatives ...
3,708
def make_and_print_table(datas): """ Generated a contamination table columns are reference genomes, and rows are samples. """ sample_names = {} header = ['sample_id'] with open(datas[0]) as data_file: for line in data_file: header.append(line.split()[0]) ...
3,709
def at_server_start(): """ This is called every time the server starts up, regardless of how it was shut down. """ # load data from muddery.server.database.worlddata.worlddata import WorldData WorldData.reload() # reset settings from muddery.server.utils.game_settings import GAME_SE...
3,710
def test_elem_o004_elem_o004_v(mode, save_output, output_format): """ TEST :3.3.2 XML Representation of Element Declaration Schema Components : Document with element with complexType """ assert_bindings( schema="msData/element/elemO004.xsd", instance="msData/element/elemO004.xml", ...
3,711
def blur(old_img): """ :param old_img: a original image :return: a blurred image """ blur_img = SimpleImage.blank(old_img.width, old_img.height) for x in range(old_img.width): for y in range(old_img.height): if x == 0 and y == 0: # Upper left cor...
3,712
def main(): """Main training program.""" # Disable CuDNN. torch.backends.cudnn.enabled = False # Timer. timers = Timers() # Arguments. args = get_args() # if args.load_huggingface: # args.make_vocab_size_divisible_by = 1 # Pytorch distributed. initialize_dist...
3,713
def user_mysqrt(): """Calculate mysqrt() of a number and compare to the math.sqrt().""" # Show initial message print("Program calculates square root of a given number using " "Newton's guess method and compares it to the Python's " "math.sqrt() function.") # Take user's input ...
3,714
def _log_validation_error(func_name, **kwargs): """ function responsible for handling the logging of the failed validations :param func_name: :param type: :param kwargs: :return: """ logged_string = f'{func_name} - failed to meet this value : {kwargs.get("validation_value")}' if kwa...
3,715
def print_sentence(sentence): """Displays words in terminal. Param: sentence(list of str) """ for word in sentence: print(word, end=" ") # move to next line in terminal print("")
3,716
def generate_table_row(log_file, ancestry, official_only, code): """ Takes an imported log and ancestry and converts it into a properly formatted pandas table. Keyword arguments: log_file -- output from import_log() ancestry -- a single ancestry code official_only -- a boolean indicating if all ...
3,717
def read_preflib_file(filename, setsize=1, relative_setsize=None, use_weights=False): """Reads a single preflib file (soi, toi, soc or toc). Parameters: filename: str Name of the preflib file. setsize: int Number of top-ranked candidates that voters approve. ...
3,718
def get_row(client, instance, file_=None): """Get one row of a family table. Args: client (obj): creopyson Client. instance (str): Instance name. `file_` (str, optional): File name. Defaults is currently active model. Returns: (dict): ...
3,719
def callback_red(*args): """ red slider event handler """ global red_int col = "red" str_val = str(r_slide_val.get()) red_int = code_shrtn(str_val, 20, 30, 60, 80, col) update_display(red_int, green_int, blue_int)
3,720
def expdb_exp(batch=False,batch_size=10): """ 从exploit-db.com中提取CVE exp label,弥补不足 更新策略:增量覆盖 """ create_table(db='exp2',table='expdb',key=['edb_id','cve_id','author','type','platform','date'],primary_key='edb_id') so,exist_eid=cve_exists(db='exp2',table='expdb',key='edb_id') all_eid=expdb_ex...
3,721
def hospitalization_to_removed(clip_low=2, clip_high=32.6, mean=8.6, std=6.7): """ Returns the time for someone to either get removed after being hospitalized in days within range(clip_low, clip_high), of a truncated_norm(mean, std). """ return sample_truncated_norm(clip_low, clip_high, mean, st...
3,722
def test_inheritance(): """ test inheritance from different module """ # test module test_data = doc.MatObject.matlabify('test_data') test_submodule = test_data.getter('test_submodule') sfdm = test_submodule.getter('super_from_diff_mod') ok_(isinstance(sfdm, doc.MatClass)) e...
3,723
def test_create(): """ Test creating a row in the Project table. """ project = models.Project.create(DummyLoader()) # Check columns populated by ORM assert project.id is not None assert project.createdAt is not None assert project.finished is None # None until project is done asser...
3,724
def split_mon_unmon(data, labels): """ Splits into monitored and unmonitored data If a data point only happens once, we also consider it unmonitored @return monitored_data, monitored_label, unmonitored_data """ from collections import Counter occurence = Counter(labels) monitored_data,...
3,725
def test_template_filedates_now(setlocale): """Test {now}""" autofile.plugins.templates.filedates.TODAY = None template = FileTemplate(PHOTO_FILE) rendered = template.render("{now}", options=RenderOptions()) assert rendered == ["2021-10-29T05:39:00.012345-07:00"] rendered = template.render("{now...
3,726
def test_profiles_manager_filter_method_empty(): """ Should filter if profile manager is None. """ mocked_api = MagicMock() mocked_api.get.return_value = [{"a": "b"}, {"a": "c"}] profiles = Profiles(api=mocked_api) assert profiles.filter(a="b") == [Profile(mocked_api, {"a": "b"})]
3,727
def supress_stdout(func): """Wrapper, makes a function non-verbose. Args: func: function to be silenced """ import contextlib import os def wrapper(*a, **ka): with open(os.devnull, "w") as devnull: with contextlib.redirect_stdout(devnull): func(*a, *...
3,728
def sum_and_count(x, y): """A function used for calculating the mean of a list from a reduce. >>> from operator import truediv >>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9] >>> truediv(*reduce(sum_and_count, l)) == 20.11111111111111 True >>> truediv(*fpartial(sum_and_count)(l)) == 20.11111111111111...
3,729
def animTempCustom(): """ Temporarily play a custom animation for a set amount of time. API should expect a full `desc` obect in json alongside a timelimit, in ms. """ colorList = request.form.get('colors').split(',') colorsString = "" for colorName in colorList: c = Color(colorName...
3,730
def datatype(self, dt): """Set data type of histogram variable. Set data type of the variable represented by the histogram. :param type dt: type of the variable represented by the histogram :raises RunTimeError: if datatype has already been set, it will not overwritten """ if hasattr(self, "_d...
3,731
def mock_stripe_invoice(monkeypatch): """Fixture to monkeypatch stripe.Invoice.* methods""" mock = Mock() monkeypatch.setattr(stripe, "Invoice", mock) return mock
3,732
def read_project(output_dir): """Read existing project data """ try: yaml = YAML() with open(project_yaml_file(output_dir), encoding='utf-8') as project: project_data = yaml.load(project) for key, value in project_data.items(): if value == None: ...
3,733
def test_create_as_anonymous(default_client, weekly_business_post_data): """An anonymous user should not be able to create weekly_business.""" response = default_client.post( _get_weekly_business_url(), weekly_business_post_data ) assert response.status_code == status.HTTP_403_FORBIDDEN
3,734
def process_data(): """INPUT: chunk OUTPUT: Dictionary of Tuples """ pass
3,735
def test_bool(): """Check bool(Property).""" assert bool(Property('Name', '')) is False assert bool(Property('Name', 'value')) is True assert bool(Property('Name', [])) is False assert bool(Property('Name', [ Property('Key', 'Value') ])) is True
3,736
def bytes_to_int(byte_array: bytes) -> int: """ Bytes to int """ return int.from_bytes(byte_array, byteorder='big')
3,737
def ask(query, default=None): """Ask a question.""" if default: default_q = ' [{0}]'.format(default) else: default_q = '' inp = input("{query}{default_q}: ".format(query=query, default_q=default_q)).strip() if inp or default is None: return inp else: return defaul...
3,738
def _clean_kwargs(keep_name=False, **kwargs): """ Sanatize the arguments for use with shade """ if "name" in kwargs and not keep_name: kwargs["name_or_id"] = kwargs.pop("name") return __utils__["args.clean_kwargs"](**kwargs)
3,739
def transfer_file(user, source_endpoint, source_path, dest_endpoint, dest_path, label): """ :param user: Must be a Django user with permissions to initiate the transfer :param source_endpoint: Source Endpoint UUID :param source_path: Source path, including the filename :param ...
3,740
def calculate_pnl_per_equity(df_list): """Method that calculate the P&L of the strategy per equity and returns a list of P&L""" pnl_per_equity = [] # initialize the list of P&L per equity for df in df_list: # iterates over the dataframes of equities pnl = df['Strategy Equity'].iloc[-1] - df['Buy and...
3,741
def search(q_str: str) -> dict: """search in genius Args: q_str (str): query string Returns: dict: search response """ data = {'songs': [], 'lyric': []} response = http.get( 'https://genius.com/api/search/multi?per_page=5', params={'q': q_str}, headers=headers).json() ...
3,742
def build_shed_app(simple_kwargs): """Build a Galaxy app object from a simple keyword arguments. Construct paste style complex dictionary. Also setup "global" reference to sqlalchemy database context for tool shed database. """ log.info("Tool shed database connection: %s", simple_kwargs["database_c...
3,743
def geocode(level=None, names=None, countries=None, states=None, counties=None, scope=None) -> NamesGeocoder: """ Create a `Geocoder`. Allows to refine ambiguous request with `where()` method, scope that limits area of geocoding or with parents. Parameters ---------- level : {'country', 'state'...
3,744
def fpAbs(x): """ Returns the absolute value of the floating point `x`. So: a = FPV(-3.2, FSORT_DOUBLE) b = fpAbs(a) b is FPV(3.2, FSORT_DOUBLE) """ return abs(x)
3,745
def volumes(container:str) -> list: """ Return list of 'container' volumes (host,cont) """ buf = StringIO() _exec( docker, 'inspect', '-f', "'{{json .Mounts}}'", container, _out=buf ) res = buf.getvalue().strip() vols_list = json.loads(res[1:-1]) # vols = {d['Source']:d['D...
3,746
def test_launch_lsf_orc(fileutils, wlmutils): """test single node orchestrator""" exp_name = "test-launch-lsf-orc-batch" exp = Experiment(exp_name, launcher="lsf") test_dir = fileutils.make_test_dir(exp_name) # batch = False to launch on existing allocation network_interface = wlmutils.get_test...
3,747
def names(): """Return stock summary information""" helper = SQLHelper() conn = helper.getConnection() repo = robinhoodRepository(conn) stockInfo = repo.getAllStocks() return json_response(stockInfo, 200)
3,748
def test_delpay_payment_split(node_factory, bitcoind): """ Test behavior of delpay with an MPP """ MPP_TARGET_SIZE = 10**7 # Taken from libpluin-pay.c amt = 5 * MPP_TARGET_SIZE l1, l2, l3 = node_factory.line_graph(3, fundamount=10**5, wait_for_announce=...
3,749
def get_bot_group_config(bot_id): """Returns BotGroupConfig for a bot with given ID. Returns: BotGroupConfig or None if not found. Raises: BadConfigError if there's no cached config and the current config at HEAD is not passing validation. """ cfg = _fetch_bot_groups() gr = cfg.direct_matches...
3,750
def add_utm(url_, campaign, source='notification', medium='email'): """Add the utm_* tracking parameters to a URL.""" return urlparams( url_, utm_campaign=campaign, utm_source=source, utm_medium=medium)
3,751
def check_job_token_attributes(token): """Check that the given JOB token contains all required attributes.""" attribs = ["limit", "remaining", "reset"] for attr in attribs: assert attr in token assert int(token[attr]) >= 0
3,752
def is_forest(G): """Return True if the input graph is a forest Parameters ---------- G : NetworkX Graph An undirected graph. Returns ------- True if the input graph is a forest Notes ----- For undirected graphs only. """ for graph in nx.connected_component_subg...
3,753
def package_to_pretty_string(package): """ Given a PackageMetadata instance, returns a pretty string.""" template = "{0.name} {0.version}" constraint_kinds = ( (ConstraintKinds.install_requires, package.install_requires), (ConstraintKinds.conflicts, package.conflicts), (ConstraintKin...
3,754
def parse_uri(uri): """ This implies that we are passed a uri that looks something like: proto://username:password@hostname:port/database In most cases, you can omit the port and database from the string: proto://username:password@hostname Also, in cases with no username, you c...
3,755
def ITAparamsheet_itaparammatchinfo_data(): """ ITAパラメータ抽出条件データ作成(正常系テスト用) """ module = import_module('web_app.models.ITA_models') ItaParameterMatchInfo = getattr(module, 'ItaParameterMatchInfo') ItaParameterMatchInfo( match_id = 999, ita_driver_id = 999, menu_id = 999,...
3,756
def pwgen(pw_len=16): """Generate a random password with the given length. Allowed chars does not have "I" or "O" or letters and digits that look similar -- just to avoid confusion. """ return get_random_string( pw_len, 'abcdefghjkmnpqrstuvwxyz' 'ABCDEFGHJKLMNPQRSTUVWXYZ' '23456789' )
3,757
def absolute_path(secured_filename: str, curr_file: str = __file__) -> str: """ Prepend `secured_filename` with the current path. Args: secured_filename (str): Safe file name. Can be a sub path without the first '/'. curr_file (str): File name of the module. Returns: str: Strin...
3,758
def test_non_fourier_params_are_consistent(): """ Check that StandardParams, StandardWithBiasParams and ExtendedParams give the same rotation angles, given the same data""" p1 = StandardParams.linear_ramp_from_hamiltonian(hamiltonian, 2, time=2) p2 = ExtendedParams.linear_ramp_from_hamiltonian(hamil...
3,759
def compute_tree_distances(tree): """ Computes the matrix of pairwise distances between leaves of the tree """ num_leaves = len(get_leaves(tree)) - 1 distances = np.zeros([num_leaves, num_leaves]) for leaf in range(num_leaves): distance_dictionary, tmp = nx.multi_source_dijkstra(tree.to_...
3,760
def create_rndm_backgr_selections(annotations, files, length, num, no_overlap=False, trim_table=False): """ Create background selections of uniform length, randomly distributed across the data set and not overlapping with any annotations, including those labelled 0. The random sampling is performe...
3,761
def to_BED(stats, manifest_or_array_type, save=True, filename='', genome_build=None, columns=None): """Converts & exports manifest and probe p-value dataframe to BED format. - https://en.wikipedia.org/wiki/BED_(file_format) - BED format: [ chromosome number | start position | end position | p-values] Wh...
3,762
def test_show_module(database_connection: mysql.connector.connect): """Run tests against show module""" print("Testing wwdtm.show module") # Start Time start_time = time.perf_counter() # Testing show.utility.id_exists test_show.test_id_exists(1083, database_connection) test_show.test_id_n...
3,763
def GetPartition(partition_name, target_os): """Return the partition to install to. Args: partition_name: partition name from command-line {'primary', 'secondary', 'other'} target_os: 'fiberos' or 'android' Returns: 0 or 1 Raises: Fatal: if no partition could be determined...
3,764
def sync_code_to_masters(cluster: Cluster, dcos_checkout_dir: Path) -> None: """ Sync files from a DC/OS checkout to master nodes. This syncs integration test files and bootstrap files. This is not covered by automated tests, and it is non-trivial. In the following instructions, running a test mi...
3,765
def extendHeader(files): """ Add new draft keywords. """ for filename in files: try: print(filename) #open file in update mode f = pyf.open(filename, memmap=True, ignore_missing_end=True, mode='update') #grab primary header hdr = f[0].header ...
3,766
async def call_dialogflow(message, config, lang=DEFAULT_LANGUAGE): """Call the Dialogflow api and return the response.""" async with aiohttp.ClientSession() as session: payload = { "v": DIALOGFLOW_API_VERSION, "lang": lang, "sessionId": message.connector.name, ...
3,767
def gettgd(sat, eph, type=0): """ get tgd: 0=E5a, 1=E5b """ sys = gn.sat2prn(sat)[0] if sys == uGNSS.GLO: return eph.dtaun * rCST.CLIGHT else: return eph.tgd[type] * rCST.CLIGHT
3,768
def random_sign_uniform(shape, minval=None, maxval=None, dtype=dtypes.float32, seed=None): """Tensor with (possibly complex) random entries from a "sign Uniform". Letting `Z` be a random variable equal to `-1` and `1` w...
3,769
def ones_v(n): """ Return the column vector of ones of length n. """ return matrix(1, (n,1), 'd')
3,770
def test_encrypt_and_decrypt_two(benchmark: BenchmarkFixture) -> None: """Benchmark encryption and decryption run together.""" primitives.decrypt = pysodium.crypto_aead_xchacha20poly1305_ietf_decrypt primitives.encrypt = pysodium.crypto_aead_xchacha20poly1305_ietf_encrypt def encrypt_and_decrypt() -> b...
3,771
def truncate(fh, length): """Implementation of perl $fh->truncate method""" global OS_ERROR, TRACEBACK, AUTODIE try: if hasattr(fh, 'truncate'): fh.truncate(length) else: os.truncate(fh, length) return True except Exception as _e: OS_ERRO...
3,772
def get_fy_parent_nucl(fy_lib): """Gets the list of fission parents from a fission yield dictionnary. Parameters ---------- fy_lib: dict A fission yield dictionnary """ fy_nucl = get_fy_nucl(fy_lib) fy_parent = [] sample_zamid = fy_nucl[0] sample = fy_lib[sample_zamid] ...
3,773
def block_input(): """Block all user input unconditionally. :command: `BlockInput <https://www.autohotkey.com/docs/commands/BlockInput.htm>`_ """ ahk_call("BlockInput", "On") yield ahk_call("BlockInput", "Off")
3,774
def initialize ( is_test, no_cam ) : """job machine Tableをもとに個体、世代の初期設定""" from functools import partial jmTable = getJmTable ( is_test ) MAX_JOBS = jmTable.getJobsCount() MAX_MACHINES = jmTable.getMachinesCount() # makespan最小化 creator.create ( "FitnessMin", base.Fitness, weights=(-1.0,) ) # 個体はジョブ番号のリスト #crea...
3,775
def run(): """Unleash payments in USA.""" (AddonExcludedRegion.objects .exclude(addon__premium_type=amo.ADDON_FREE) .filter(region=mkt.regions.US.id).delete())
3,776
def perform_variants_query(job, **kwargs): """Query for variants. :param job: API to interact with the owner of the variants. :type job: :class:`cibyl.sources.zuul.transactions.JobResponse` :param kwargs: See :func:`handle_query`. :return: List of retrieved variants. :rtype: list[:class:`cibyl....
3,777
def get_model(share_weights=False, upsample=False): # pylint: disable=too-many-statements """ Return a network dict for the model """ block0 = [{'conv1_1': [3, 64, 3, 1, 1]}, {'conv1_2': [64, 64, 3, 1, 1]}, {'pool1_stage1': [2, 2, 0]}, {'conv2_1': [64, 128, 3, 1, 1]}, ...
3,778
def bootstrap(config_uri, request=None, options=None): """ Load a WSGI application from the PasteDeploy config file specified by ``config_uri``. The environment will be configured as if it is currently serving ``request``, leaving a natural environment in place to write scripts that can generate URLs an...
3,779
def add_subparser( subparsers: SubParsersAction, parents: List[argparse.ArgumentParser] ) -> None: """Add all rasa x parsers. Args: subparsers: subparser we are going to attach to parents: Parent parsers, needed to ensure tree structure in argparse """ x_parser_args = { "par...
3,780
def readSegy(filename) : """ Data,SegyHeader,SegyTraceHeaders=getSegyHeader(filename) """ printverbose("readSegy : Trying to read "+filename,0) data = open(filename).read() filesize=len(data) SH=getSegyHeader(filename) bps=getBytePerSample(SH) ntraces = (filesize-3600)/(SH['ns']*bps+240) # ntraces = 100...
3,781
def chdir(request): """Reset CWD directory: 1. At start of test the CWD will be in the directory that contains the test file. 2. After test completes the CWD will be reset to the CWD before the test started. """ oldcwd = pathlib.Path.cwd() request.fspath.dirpath()...
3,782
def planar_transform(imgs, masks, pixel_coords_trg, k_s, k_t, rot, t, n_hat, a): """transforms imgs, masks and computes dmaps according to planar transform. Args: imgs: are L X [...] X C, typically RGB images per layer masks: L X [...] X 1, indicating which layer pixels are valid pixel_coords_trg: [......
3,783
def writeRLE(grid, rule): """ Writes grid out to a text file in RLE format """ if not os.path.exists("saved-RLEs"): os.mkdir("saved-RLEs") filename = unique_file("saved-RLEs/RLEfile", "rle") f = open(filename, "w") top, bot, minCol, maxCol = findBoundaries(grid) #write x,y header f.w...
3,784
def convertDynamicRenderStates(data, builder): """ Converts dynamic render states. The data map is expected to contain the following elements: - lineWidth: float width for the line. Defaults to 1. - depthBiasConstantFactor: float value for the depth bias constant factor. Defaults to 0. - depthBiasClamp: float valu...
3,785
def binary_search(a, search_value): """ @name binary_search @param a array """ N = len(a) l = 0 r = len(a) - 1 while(True): try: result = binary_search_iteration(a, l, r, search_value) l, r = result except TypeError: return -1 if not re...
3,786
def touch(filepath): """ Creates an empty file at filepath, if it does not already exist """ with open(filepath, 'a'): pass
3,787
def _key_match(d1: Dict[str, Any], d2: Dict[str, Any], key: str) -> bool: """ >>> _key_match({"a": 1}, {"a": 2}, "a") False >>> _key_match({"a": 1}, {"a": 2}, "b") True >>> _key_match({"a": 2}, {"a": 1}, "a") False >>> _key_match({"a": 1}, {"a": 1}, "a") True >>> _key_match({"a":...
3,788
def calculate(over): """Returns the value of the first triangle number to have over the specified number of divisors""" triangle = 0 count = sum(range(triangle)) while True: if num_divisors(count) > over: answer = count return answer triangle += 1 coun...
3,789
def convert_image_to_kernel(im: Image, oversampling, kernelwidth): """ Convert an image to a griddata kernel :param im: Image to be converted :param oversampling: Oversampling of Image spatially :param kernelwidth: Kernel width to be extracted :return: numpy.ndarray[nchan, npol, oversampling, overs...
3,790
def groupby(keys: Iterable, *arrays) -> Iterator[tuple]: """Generate unique keys with associated groups. Args: keys: *arrays (Iterable): """ arrays = tuple(map(np.asarray, arrays)) try: items = _arggroupby(asiarray(keys)) except TypeError: # fallback to sorting ...
3,791
def prob(X, w): """ X: Nxd w: dx1 --- prob: N x num_classes(2)""" y = tf.constant(np.array([0.0, 1.0]), dtype=tf.float32) prob = tf.exp(tf.matmul(X, w) * y) / (1 + tf.exp(tf.matmul(X, w))) return prob
3,792
def test_warped_vrt_dimensions(path_rgb_byte_tif): """ A WarpedVRT with target dimensions has the expected dataset properties. """ with rasterio.open(path_rgb_byte_tif) as src: extent = (-20037508.34, 20037508.34) size = (2 ** 16) * 256 resolution = (extent[1] - extent[0]) / ...
3,793
def get_similar_genes_Quantiles( gene_expr: np.array, n_genes: int, candidate_quants: np.ndarray, candidate_genes: np.array, quantiles=(0.5, 0.75, 0.85, 0.9, 0.95, 0.97, 0.98, 0.99, 1), ): """Gets genes with a similar expression distribution as the inputted gene, by measuring distance be...
3,794
def get_date_strings(): """ Get date strings for last month and this month in "%Y%m" format, e.g. "202201" """ today = date.today() first = today.replace(day=1) last_month = first - timedelta(days=1) this_month_string = today.strftime("%Y%m") last_month_string = last_month.strftime("%Y%...
3,795
def get_gpa(cookie, sno, year='', term=''): """ 获取已取得的总基点: 专必 公必 公选 专选 """ logging.debug('Getting gpa: %s %s %s %s', sno, year, term, cookie) url = 'http://uems.sysu.edu.cn/jwxt/xscjcxAction/xscjcxAction.action?method=getAllJd' query_json = """ { header: { "code": -100, ...
3,796
def get_status(conf): """ Find out in what state we are, ie. what steps have been done, etc - are there unjudged terms? update with judgements from the file (if existings) - if all terms are judged, we can proceed to the next step, so we set the new seed terms """ conn, domain, mode...
3,797
def hosts_disable_all(): """ status de host 0 = enabled status de host 1 = disabled """ logger.info('Disabling all hosts, in blocks of 1000') hosts = zapi.host.get(output=[ 'hostid' ], search={ 'status': 0 }) maxval = int(ceil(hosts.__len__())/1000+1) bar = ProgressBar(maxval=maxval,widgets=[Percentage(...
3,798
def run_vep_annotator(vep_data: str, vcf_path: str, out_path: str, fasta: str, vep_custom: Union[str,list]=None, overwrite: bool=False, vep_n_fork: int=4): """ Run variant ensembl predictor alone with custom options. See options details at https://www.ensembl.org/info/docs/tools/vep/script/vep_options.html#...
3,799