content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from datetime import datetime def get_slurm_params(n,runtime=None,mem=None,n_jobs=None): """Get remaining parameters to submit SLURM jobs based on specified parameters and number of files to process. Parameters ---------- n : int Number of files to process. runtime : str, None Tim...
f2bf08430fbde0dcc430fd3e01d6b5ca1bd64487
9,000
import time import os from datetime import datetime def get_db_comment_text(file_name) -> DataFrame: """ db_comment 파일에서 text를 추출하여 DataFrame type으로 return :param file_name: 입력 파일명 (str type) :return: 입력 파일에서 추출한 text """ # :return: 입력 파일에서 추출한 text에 형태소 분석기로 명사 추출한 DataFrame start_time =...
ec36b3ac6a25e3fb5052f32fc11efe306db12a0e
9,001
def source_open() -> bool: """Open a source MS Excel spreadsheet file. Returns ------- boolean Flag about successful processing. """ try: Source.wbook = openpyxl.load_workbook(cmdline.workbook) except Exception: logger.error( 'Cannot open the MS Excel wo...
19a2c214131afa6c1126bc1e0a4b4892a13bc32b
9,002
from pathlib import Path import yaml import os import requests import json def make_prompt(token: str, config: Path, model: str = ''): """Make a summary using the Studio21 API Args: token (str): Your api token to use. config (Path): The path to the config file. model (str, optional): ...
865dde67278c21c1dee075c5a831281d59a311c8
9,003
import re def get_license_match_error(lic, lic_file_path): """Returns an Error of the type 'warning' if the FreeRTOS license is present in the input file. Otherwise an empty list is returned. """ # Get the words in the license template with open('license.templ', 'r') as file: template_lic ...
d3f53f3d25c4d56b41fb561cf37b845d1efdc9fe
9,004
import queue def start_workers(size, delete=False, migrate=False): """Starts FluxxWorkers. :returns: Pair of queues. """ streams = (queue.Queue(), queue.Queue(maxsize=size)) for _ in range(THREAD_COUNT): worker = FluxxWorker(streams, delete, migrate) worker.daemon = True ...
358d8d3bc0d12edbe9e422cdfc206de626fd2a7d
9,005
def harmonizationApply(data, covars, model): """ Applies harmonization model with neuroCombat functions to new data. Arguments --------- data : a numpy array data to harmonize with ComBat, dimensions are N_samples x N_features covars : a pandas DataFrame contains covar...
7789d3a75d043df5048a7b0adced771c7e1ddd81
9,006
import re def from_rkm(code): """Convert an RKM code string to a string with a decimal point. Parameters ---------- code : str RKM code string. Returns ------- str String with a decimal point and an R value. Examples -------- >>> from pyaedt.circuit import fr...
8cb41a58fab685e5e7de4af533fade1aeee09c2c
9,007
def get_arguments(method, rpc_version): """ Get arguments for method in specified Transmission RPC version. """ if method in ('torrent-add', 'torrent-get', 'torrent-set'): args = constants.TORRENT_ARGS[method[-3:]] elif method in ('session-get', 'session-set'): args = constants.SESSI...
dcd8b3f0e5e93409518d7e9d72ffe954c3b99915
9,008
import functools def compose_local_noises(*functions: NoiseModel) -> NoiseModel: """Helper to compose multiple NoiseModel. Args: *functions: a list of functions Returns: The mathematical composition of *functions. The last element is applied first. If *functions is [f, g, h], it ...
4b6e90ff2def9a988d8aa66782d990971b8de586
9,009
import copy def sls_build( repository, tag="latest", base="opensuse/python", mods=None, dryrun=False, **kwargs ): """ .. versionchanged:: 2018.3.0 The repository and tag must now be passed separately using the ``repository`` and ``tag`` arguments, rather than together in the (now d...
d3d047334ea8b02e61d26b3fc471eb2cedd7a8c5
9,010
import re from datetime import datetime def parse_date(date): """ Parses a date string and returns number of seconds from the EPOCH. """ # yyyy-mm-dd [hh:mm:ss[.s][ [+-]hh[:][mm]]] p = re.compile( r'''(?P<year>\d{1,4}) # yyyy - # ...
44dbf7c9ded2004118b64827e5c5016dc3967ec6
9,011
def CorrectOrWrong(Input,word): """Check if Input is inside word""" if Input in word: return True else: return False
fa3f06fd156c2523334a057366e88c5b7b376eb1
9,012
def get_fair_metrics(dataset, pred, pred_is_dataset=False): """ Measure fairness metrics. Parameters: dataset (pandas dataframe): Dataset pred (array): Model predictions pred_is_dataset, optional (bool): True if prediction is already part of the dataset, column name 'labels'. Retu...
1cf4a8655bf569f5d8ddfa530f46c65fe8f2be3f
9,013
from typing import Sequence from typing import Dict from typing import Union from typing import Tuple def make_params( key_parts: Sequence[str], variable_parts: VariablePartsType) -> Dict[str, Union[str, Tuple[str]]]: """ Map keys to variables. This map\ URL-pattern variables to\ a URL...
4da736f2057e06be1ceb51968d6c205cd28b7093
9,014
def load_sentiments(file_name=DATA_PATH + "sentiments.csv"): """Read the sentiment file and return a dictionary containing the sentiment score of each word, a value from -1 to +1. """ sentiments = {} for line in open(file_name): word, score = line.split(',') sentiments[word] = float(...
a98ae77a051ea3b599ee2fd5036e1bd33c1f4d64
9,015
def run_example( device_id: str, server_host: str = "localhost", server_port: int = 8004, plot: bool = True, scope_length: int = 8192, historylength: int = 1, ): """run the example.""" apilevel_example = 6 # The API level supported by this example. # Call a zhinst utility function ...
e7f46a532b90fc1f208ebc2ae37b2216e2bd7561
9,016
def get_draft_url(url): """ Return the given URL with a draft mode HMAC in its querystring. """ if verify_draft_url(url): # Nothing to do. Already a valid draft URL. return url # Parse querystring and add draft mode HMAC. url = urlparse.urlparse(url) salt = get_random_string(...
f8eaaa7daaba2b5bfe448b5386e88d9f738b0f5d
9,017
def make_datum(source: str, img_id: str, sent_id: int, sent: str): """ Create a datum from the provided infos. :param source: the dataset of the particular sentence. :param img_id: id of the image :param sent_id: id of the sentence (of the image) :param sent: the sentence :return: a dict of ...
4814093519aad09e0f81d6e0841d130e1b2e43a4
9,018
def list_for_consumer(req): """List allocations associated with a consumer.""" context = req.environ['placement.context'] context.can(policies.ALLOC_LIST) consumer_id = util.wsgi_path_item(req.environ, 'consumer_uuid') want_version = req.environ[microversion.MICROVERSION_ENVIRON] # NOTE(cdent):...
37575bb0d05491d8a2e0933134fa530bf7699b3b
9,019
import os def get_supermean(name, season, data_dir, obs_flag=None): """Calculated supermeans from retrieved data, which are pickled Iris cubes. :param name: Cube name. Should be CF-standard name. If no CF-standard name exists the STASH code in msi format (for example m01s30i403) ...
22872ceeb6754ba33f6755cae5d2c363bf30f559
9,020
def get_zcl_attribute_size(code): """ Determine the number of bytes a given ZCL attribute takes up. Args: code (int): The attribute size code included in the packet. Returns: int: size of the attribute data in bytes, or -1 for error/no size. """ opts = (0x00, 0, 0x...
99782c86be2413410c6819a59eadf0daba326af2
9,021
def get_mappings(): """We process the mappings for two separate cases. (1) Variables that vary by year, and (2) variables where there are multiple realizations each year. """ # Set up grid for survey years. Note that from 1996 we can only expect information every other # year. We start with 1978 as ...
a02ac60889ab2ef9524a50ec7eb03fe6a8b54917
9,022
def _get_function_name_and_args(str_to_split): """ Split a string of into a meta-function name and list of arguments. @param IN str_to_split String to split @return Function name and list of arguments, as a pair """ parts = [s.strip() for s in str_to_split.split(" | ")] if len(parts) < 2: ...
1dae51c87e727d7fa6a3a8012f9768b9ca3364e7
9,023
import os import time def runAndWatch(container, cgroup, watchCgroup, notify=None, wallClockLimit=None, cpuClockLimit=None, pollInterval=1, notifyInterval=10): """ Run a container and watch it for time limits. Returns a dictionary with container statistics. """ inspection = inspectCont...
24179f4e2f554bedb0ee0b8507d777723cf220b1
9,024
import requests def replicas_on_delete(): """ This is a route for ALL NODES. A (previous) neighbor node sends POST requests to this route, so that a key-value pair replica is deleted in the current NODE. """ # The hash ID of the node-owner of the primary replica start_id = request.form[...
ff8b4cc06ce7a640914bdd58ff897dc060f22d4b
9,025
import os def load(train_dir=train_dir, test_dir=test_dir): """ Load the dataset into memory. This uses a cache-file which is reloaded if it already exists, otherwise the dataset is created and saved to the cache-file. The reason for using a cache-file is that it ensure the files are ordered ...
f19c9d2220cd68a7f2722b6fdc2170d70cff4367
9,026
def pdf2(sigma_matrix, grid): """Calculate PDF of the bivariate Gaussian distribution. Args: sigma_matrix (ndarray): with the shape (2, 2) grid (ndarray): generated by :func:`mesh_grid`, with the shape (K, K, 2), K is the kernel size. Returns: kernel (ndarrray): un-norm...
7477b33eab034d9ca5cac63fd1eedd4f6789f1ba
9,027
def spell_sql(*args,**kwargs): """ list=[] """ if len(args[0])<=0: return None sql="SELECT * from `emotion_data` WHERE id ={}".format(args[0][0]) for index in args[0][1:]: sql +=" or id ={}".format(index) return sql
5e5b231be2dabca75abed332864c8ae3d93b750e
9,028
def is_within_bounds(bounds, point): """ Returns true if point is within bounds. point is a d-array and bounds is a dx2 array. bounds is expected to be an np.array object. """ point = np.array(point) if point.shape != (bounds.shape[0],): return False above_lb = np.all((point - bounds[:, 0] >= 0)) ...
926c107a808d98f62c0323746112b6f73b5f89fe
9,029
def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. reduction (str): Same as built-in losses of PyTorch. avg_factor (float): Ava...
b19b937f9b774dcac09f8949c2d1762743e7958e
9,030
def list_of_paths(): """ It lists all the folders which not contain PET images """ return ['.DS_Store', 'localizer', 'Space_3D_T2_FLAIR_sag_p2', 'AXIAL_FLAIR', 'MPRAGE_ADNI_confirmed_REPEATX2', 'Axial_PD-T2_TSE', 'Axial_PD-T2_TSE_repeat', 'MPRAGE_SAG_ISO_p2_ND', 'Axial_PD-T2_TSE_confi...
bc74024d49396f80947b3cb0a45066381b7d3af4
9,031
def convert_onnx_to_ell(path, step_interval_msec=None, lag_threshold_msec=None): """ convert the importer model into a ELL model, optionally a steppable model if step_interval_msec and lag_threshold_msec are provided. """ _logger = logger.get() _logger.info("Pre-processing... ") converter = ...
28843c1b588d4c1772c5c4be10e1a535b940703d
9,032
def cdfRosconi(cdfThickness=np.linspace(0,1,1000), alpha=1.71e11, beta=8.17, gamma=55.54): """ TODO: Not Yet Implemented * Input to this function has units of mm for default parameters. ** Default values of alpha, beta and gamma derived from: Rosconi et al. Quantitative appro...
3f774c4be62c2b1b01430c7dce6aae4374693ae1
9,033
def compute_error_model(model_metadata, X_test, y_test, target,error_metric): """Computes the model MRR based on test data :param model_metadata: a dictionary containing metadata about a model :param X_test: a dataframe containing features specfic to the model being evaluated :param y_test: a datafra...
9cb1ede604f863c1eeab12a593c8b62527599d12
9,034
def column(df, s, column) -> ReturnType: """Gets the series of the column named `column` """ return df.loc[s, column].to_numpy(), 0
8d400c2425a062566e61c23361dd6a1f6e0ba8b7
9,035
def features_to_id(features, intervals): """Convert list of features into index using spacings provided in intervals""" id = 0 for k in range(len(intervals)): id += features[k] * intervals[k] # Allow 0 index to correspond to null molecule 1 id = id + 1 return id
74b0b201888a69c045ef140959876dd3e909f20d
9,036
import torch def index_initial(n_batch, n_ch, tensor=True): """Tensor batch and channel index initialization. Args: n_batch (Int): Number of batch. n_ch (Int): Number of channel. tensor (bool): Return tensor or numpy array Returns: Tensor: Batch in...
52a16ad4afcf931ba4cda9c014d47050970995c5
9,037
from distutils.spawn import find_executable import os def which(binary_name, pathvar=None): """ Deduces the path corresponding to an executable name, as per the UNIX command `which`. Optionally takes an override for the $PATH environment variable. Always returns a string - an empty one for...
6a1c02ea939e119df72c4ad1b3e685614218574d
9,038
def load_titanic(test_size=0.2, random_state=1, cache_dir=None, cache_subdir='datasets'): """ load titanic database """ path = find_path(DatasetEnum.titanic, cache_dir=cache_dir, cache_subdir=cache_subdir) df = pd.read_csv(path, sep=",", na_values=["?"], keep_default_na=True) # Shuffle DF and compute ...
a222a684a55bde482664b0b3072fb04047360f50
9,039
def mock_function_fail(*args, **kwargs): """ Mock a function that 'fails', i.e., returns a 1. """ print("\nmock> f({}) ==> 1".format(args)) # pragma: no cover return 1 # pragma: no cover
ec2085e51a0809c9656d1831429858e14baf3f63
9,040
def get_field_result(client_id, field_id, count=1): """ на входе: id-поля, id-карты, выход: последний результат поля :return: """ with connection.cursor() as cursor: cursor.execute( """ SELECT directions_napravleniya.client_id, directions_issledovaniya.napravleniy...
7191705462f1fceb3dfca866c5fed96fa8019886
9,041
def parse_basic_profile_forms(): """Parses and validates basic profile forms in the request. Returns: A dictionary containing user profile. Raises: ValueError: When validation failed. """ return { 'display_name': get_form_string('display_name', 32), 'contact_email':...
c8409bcc7de6a2c0a320859f90d54215888febf8
9,042
def fixture_success(request): """ Test Cases: 1. Hitting uncovered route as base user (logged in flow). Will return 200 since uncovered route is an open endpoint and thus Anonymous users can also access it. 2. Hitting uncovered route as base user and HEAD request 3. Hitting uncovered route a...
26603ce9203372e9ced217f75505b149942eee98
9,043
from typing import Optional import csv def get_quote_name(quote_number: int) -> Optional[str]: """ used to help applications look up quote names based on the number users. """ assert type(quote_number) in (int, type(None)) if quote_number is None: return None for key, value in cs...
4a96ee42b37879469a67cb657d97aa321770fd83
9,044
def calc_floodzone(row): """Extracts the FEMAZONE of an SFHA based on each row's attributes. This function acts on individual rows of a pandas DataFrame using the apply built-in. Parameters ---------- row : Pandas Series A row of a pandas DataFrame Returns ------- str ...
5bb6f3f7cfc1b6bce41ad7a752845287759c16ad
9,045
def trans_you(ori_image, img_db, target_size=(8, 8)): """Transfer original image to composition of images. Parameters ---------- ori_image : numpy.ndarray the original image img_db : h5py.File image datasets target_size : tuple Returns ------- res_img : numpy.ndarra...
f9717d2ddc9052bee103010a23328f5445c4edc5
9,046
from re import A from re import T def new_assessment(): """ RESTful CRUD controller to create a new 'complete' survey - although the created form is a fully custom one """ # Load Model table = s3db.survey_complete s3db.table("survey_series") def prep(r): if r.interact...
a4b1f9ba0a7e70349607f5cc70fdac72d75fb236
9,047
import types import random async def random_pokemon(connection: asyncpg.Connection, /) -> types.Pokemon: """Returns a random :class:`types.Pokemon`.""" records = await tables.Pokemon.fetch(connection) return await _pokemon(connection, random.choice(records))
b60659f236a4cbea998a77df211da92c18e4f0b8
9,048
import re def remove_space(text): """ Funcion que elimina espacios :param str text: texto a procesar """ return re.sub(r"\s+", " ", text).strip()
729d26bb6acbaa8da4c945d2ea6646ebb90f3122
9,049
import base64 def getFilePathBase(): """ 获取请求url文件的文件路径 :return: php->base64 code """ code = """ @ini_set("display_errors","0"); @set_time_limit(0); @set_magic_quotes_runtime(0); header("Content-Type:application/json"); $res = array();$res["path"] = dirname(__FILE__); echo ("<ek>...
afcb1a5bf2972a2b13a32edcd8a9b968742bf7f3
9,050
def extractHeldSimple(q, factoryConfig=None): """All Held Glideins: JobStatus == 5 q: dictionary of Glideins from condor_q factoryConfig (FactoryConfig): Factory configuartion (NOT USED, for interface) Returns: dict: dictionary of Held Glideins from condor_q """ # Held==5 ...
c942991bb0370b63364c1b8d5644713865d9ea82
9,051
def neighbors(stats1, stats2, max_val=1e5): """stats from cv.connectedComponentsWithStats.""" pts1 = np.concatenate( (stats1[:, :2], stats1[:, :2] + stats1[:, 2:4]), axis=0) pts2 = np.concatenate( (stats2[:, :2], stats2[:, :2] + stats2[:, 2:4]), axis=0) dist = np.abs(pts1[:, None] - pts...
1b6aecad76f968cd83d40ee6531fcbd6b3b0df6c
9,052
from typing import Optional def shortest_substring_containing_characters(text: str, char_set: set) -> Optional[str]: """ O(n) & O(k) """ start = 0 end = -1 count_char = defaultdict(int) # char and its count found_set = set() for index, char in enumerate(text): if char in char...
4682a01b1a4331dbada7a234c908d1c53639e69a
9,053
def refine_grid( grid, cb, grid_additions=(50, 50), ntrail=2, blurs=((), ()), metric=None, atol=None, rtol=None, extremum_refinement=None, snr=False, ): """Refines an existing grid by adding points to it. Parameters ---------- grid : array cb : callbable ...
c84a365bcc271622fd49a01d89303aa2adb1c624
9,054
from datetime import datetime def last_week(today: datetime=None, tz=None): """ Returns last week begin (inclusive) and end (exclusive). :param today: Some date (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is N...
a210707e2a479fe4e8b98a137c0ade684d4dd6da
9,055
def get_velocity_limits(): """ """ velocity_limits = {} for i in range(6): try: velocity_limits['a{}'.format(i+1)] = float(pm.textField( 't_A{}vel'.format(i+1), q=True, ...
68f58ed715a39478d119af1e1aabe54fa7ec6094
9,056
def decode_item_length(encoded_data: Bytes) -> int: """ Find the length of the rlp encoding for the first object in the encoded sequence. Here `encoded_data` refers to concatenation of rlp encoding for each item in a sequence. NOTE - This is a helper function not described in the spec. It was ...
d005b8050abaaba76bd5d3a24419f86c462af2b2
9,057
def pxor(a1, a2, fmt=None): """Bitwise XOR""" return c2repr(_inconv(a1) ^ _inconv(a2), fmt)
a65ada1901fc5bfa202af5128c3e5b6e54d5f6dc
9,058
from typing import Tuple def milestone_2_test_1_initial_val(lattice_grid_shape: Tuple[int, int]) -> Tuple[np.ndarray, np.ndarray]: """ Return initial conditions Args: lattice_grid_shape: lattice grid [lx, ly] Returns: density with 0.5, but one peak in the middle, velocities 0 ""...
89d6ed57e93859182a92946e94adc2d26631f6e3
9,059
def test_element_html_call_get_attribute(monkeypatch, browser_driver): """Calls el_or_xpath WebElement attr get_attribute""" called = [] class FakeWebElement: def get_attribute(self, val): called.append(('get_attribute', val)) return 42 @browser_driver.register cla...
7b3bcc3ba4a8c030b15649b240f75bf9bed71570
9,060
import time def moving_dictators(session, system_ids): """ Show newly controlling dictators in the last 5 days. Show all controlling dictators in monitored systems. Subqueries galore, you've been warned. Returns: A list of messages to send. """ gov_dic = session.query(Government.id).\ ...
9d9808d608190dae0a9f57980312e2ae830c492c
9,061
def get_alt_for_q_with_constant_mach(q, mach, tol=5., SI=False, nmax=20): # type: (float, float, float, bool, int) -> float """ Gets the altitude associated with a dynamic pressure. Parameters ---------- q : float the dynamic pressure lb/ft^2 (SI=Pa) mach : float the mach to...
f9286d7f742a8e8e3f25d63210180dbd7bc2fcc7
9,062
def addMetadataFlags(metadataChunk, numberOfMetadataChunks): """Adds binary flag the number of metadata chunks this upload has (uint8). Arguments: metadataChunk {bytes} -- First metadata chunk already encrypted, but before signing. numberOfMetadataChunks {int} -- Self-explanatory. Returns: bytes -- Metadat...
aeaefd8e1cd62524d435ee95bc272a9a676680c0
9,063
def table(a): """get tabular view of obj, if available, else return obj""" if misc.istablarray(a): return a.__view__('table') return a
e04b53f40203fbeeb3104f5e46bab87ab3304269
9,064
def parse_quadrupole(line): """ Quadrupole (type 1) V1: zedge V2: quad gradient (T/m) V3: file ID If > 0, then include fringe field (using Enge function) and V3 = effective length of quadrupole. V4: radius (m) V5: x misalignment error (m) V6: y misalignment error (m)...
2e9748fb0eabe51383fcb1ff47a7278dda622e44
9,065
def cases_vides(pave): """fonction qui cherche toutes les cases vides ayant des cases adjacentes pleines dans un pavé (où pavé est un tableau de tuiles ou de cases vides) retourne le tableau contenant les positions de ces cases vides et les cases adjacentes en fonction de leur position""" result = [...
2d2de1651f000f48ab32e484f3f6b465231248b5
9,066
def _create_scalar_tensor(vals, tensor=None): """Create tensor from scalar data""" if not isinstance(vals, (tuple, list)): vals = (vals,) return _create_tensor(np.array(vals), tensor)
ef41eabc66eda8739a78931d53ccc6feb8dfc6bb
9,067
import importlib def is_importable(name): """ Determines if a given package name can be found. :param str name: The name of the pacakge :returns: True if the package can be found :rtype: bool """ return bool(importlib.util.find_spec(name))
548044b06d250af7f49dc3c9b4144490a5bbcc83
9,068
def make_pipeline(*steps, **kwargs): """Construct a Pipeline from the given estimators. This is a shorthand for the Pipeline constructor; it does not require, and does not permit, naming the estimators. Instead, their names will be set to the lowercase of their types automatically. Parameters ...
a036c345208333b6f6d9d33998d06b282c9aa711
9,069
import logging def say_hello(name): """ Log client's name which entered our application and send message to it """ logging.info('User %s entered', name) return 'Hello {}'.format(name)
b79865cca34d1430bf47afabf7c96741d59ac560
9,070
import numpy def dual_edges_2(vertices): """ Compute the dual edge vectors of a triangle, expressed in the triangle plane orthonormal basis. :param vertices: The triangle vertices (3 by n matrix with the vertices as rows (where n is the dimension of the space)). :returns: The triangle dua...
64ff173ef00dc4d916f00f67c7a35da25d81b535
9,071
def merge_dicts(dictionaries): """Merges multiple separate dictionaries into a single dictionary. Parameters ---------- dictionaries : An iterable container of Python dictionaries. Returns ------- merged : A single dictionary that represents the result of merging the all the ...
1a2b5f3c539937e2e27a55ce3914f7368f0a7296
9,072
from typing import Union from typing import Callable def noise_distribution_to_cost_function( noise_distribution: Union[str, Callable] ) -> Callable[[str], str]: """ Parse noise distribution string to a cost function definition amici can work with. The noise distributions listed in the follow...
d26ae31211ab5a9fae2b350391ab2a835ba02758
9,073
from datetime import datetime def serializer(cls, o): """ Custom class level serializer. """ # You can provide a custom serialize/deserialize logic for certain types. if cls is datetime: return o.strftime('%d/%m/%y') # Raise SerdeSkip to tell serde to use the default serializer/deseri...
6e9bfbb83ede2c2da412b70741d793c6e24e05ef
9,074
def parse_args(): """ parse command-line arguments """ usage = """Usage: bcfg2_svnlog.py [options] -r <revision> <repos>""" parser = OptionParser(usage=usage) parser.add_option("-v", "--verbose", help="Be verbose", action="count") parser.add_option("-c", "--config", help="Config file", ...
30ac6035e375b692a516903055b7916a601e98a5
9,075
import array def compute_com(kpt_ids, pose_keypoints): """Computes center of mass from available points for each pose. Requires at least one arm (shoulder, elbow, wrist), neck and hips. Required keypoints to return result: at least one arm with hip, neck and [nose OR ear] :param kpt_id: IDs of keypo...
16e884ef76bdc21695349e6f0f9f9948426c5b8c
9,076
import os def certificate(cert_name): """Return the path to the PEM file with the given name.""" return os.path.join(os.path.dirname(__file__), 'lib', cert_name)
5dc02c85158ae7b020f069976a581d41f31d338c
9,077
def _MinimumLineCount(text: str, min_line_count: int) -> str: """Private implementation of minimum number of lines. Args: text: The source to verify the line count of. Returns: src: The unmodified input src. Raises: NoCodeException: If src is less than min_line_count long. """ if len(text.str...
037400aed0503dabee61a8d5088ca2e4b3ab34a6
9,078
def RationalQuadratic1d( grid, corrlen, sigma, alpha, prior=None, mu_basis=None, mu_hyper=None, energy=0.99 ) -> Formula: """Rational quadratic kernel formula """ kernel_kwargs = { "corrlen": corrlen, "sigma": sigma, "a...
56d61ef851ac5c84336f7f6bda19885d85b42b26
9,079
def plot_feature_importance(feature_keys, feature_importances, ax=None, **kwargs): """ Plot features importance after model training (typically from scikit-learn) Parameters ---------- feature_keys: list of string feature_importances: `numpy.ndarray` ax: `matplotlib.pyplot.axes` Return...
aa3a747002d7c82f91de52e011b269b105c4bb70
9,080
def simulate_timestamps_till_horizon(mu, alpha, beta, Thorizon = 60, \ seed=None, node=None, output_rejected_data=False): """ Inputs: mu, alpha, beta are parameters of intensity function of HP """ ################# # Initialisation ################# rng = default_rng(seed) # get ins...
6d9e7a7c747c7a07fe94069017b32a47e3d35ac2
9,081
import logging import time import torch from datetime import datetime def jp_inference_on_dataset(model, data_loader, evaluator): """ Run model on the data_loader and evaluate the metrics with evaluator. Also benchmark the inference speed of `model.forward` accurately. The model will be used in eval m...
e18113b4fc47bf48562bdee8dc8e4a2bdbe4c884
9,082
def boolToYes(b): """Convert a Boolean input into 'yes' or 'no' Args: b (bool): The Boolean value to be converted Returns: str: 'yes' if b is True, and 'no' otherwise. """ if b: return "yes" else: return "no"
ff94b66b5a166592062bf1d5b286b425e7997304
9,083
def top_symptoms(dic, title): """Find and plot top symptoms in the dictionary based on count Args: dic (dict): Dictionary containing text-count pair Returns: [dictionary]: Top 5 symptoms with their count """ assert isinstance(dic, dict) and len(dic) > 0, "dic is not a nonempty dict...
1acfcec04d2a5c11f7f1a4e90eb9142de042c875
9,084
def _calc_z(h: DataArray, zice: DataArray, zeta: DataArray, s: DataArray, Cs: DataArray, hc: float, Vtransform: int) -> DataArray: """ Calculate grid z-coord depth given water depth (h), iceshelf depth (zice), sea surface (zeta), and vertical grid transformation parameters. Inpu...
6580d3c2825cbea0bba33d03b2c0ad62bbd5b227
9,085
def gap_loss(preds, D, A): """ This module implement the loss function in paper [Azada Zazi, Will Hang. et al, 2019] Nazi, Azade & Hang, Will & Goldie, Anna & Ravi, Sujith & Mirhoseini, Azalia. (2019). GAP: Generalizable Approximate Graph Partitioning Framework. Args: preds (tensor(float)): output ...
9418ee8bda3e7b1a5284c36412fefa158eec0f91
9,086
def number_of_hole(img, hole_img, hole_counter): """ 判斷hole的數量去執行相對應的函式 0個hole執行zero_of_hole 1個hole執行one_of_hole 2個hole執行my_text.set("Answer : 8") 大於2個hole則執行my_text.set("Error : holes number = " + str(hole_counter) + "( > 2 )")) """ switcher = { ...
583fd05b0f10e3ea1c7cee11bd416b8d41d7f840
9,087
def get_merged_by_value_coords(spans_value, digits=None): """returns adjacent spans merged if they have the same value. Assumes [(start, end, val), ..] structure and that spans_value is sorted in ascending order. Arguments: - digits: if None, any data can be handled and exact values are ...
c186c503972b4b48e627c14df77bd5a780b59f5b
9,088
def vint_mask_for_length(length): """ Returns the bitmask for the first byte of a variable-length integer (used for element ID and size descriptors). :arg length: the length of the variable-length integer :type length: int :returns: the bitmask for the first byte of the variable-length integer :rtype: int ...
92fe3cb0fa09713ff4b650349294a2b241bb3918
9,089
from itertools import tee def parse(tokens): """ S-expr ::= ( S-expr* ) | AtomSymbol | ' S-expr ' S-expr = (quote S-expr) """ def _parse(tokens): while True: token = next(tokens) if token == "(": s_expr = [] while True: ...
90c8e3cd8482899749d30d5344390cfd5f24989f
9,090
import numpy import warnings def preproc(raw, dark=None, flat=None, solidangle=None, polarization=None, absorption=None, mask=None, dummy=None, delta_dummy=None, normalization_factor=1.0, empty=None...
9a21af39470b1f48c81d043a1d4a9ca045804093
9,091
import scipy def lB_2_T(lB, T0=298, sigma=4E-10, ret_res=False): """Solves for temperature at given Bjerrum length under condition from Adhikari et al. 2019 that lB/l = 1.2 at 298 K.""" def cond(T, lB, sigma=sigma): """condition function whose root gives the temperature T given Bjerrum length lB.""" ...
73d349d95cd69076874e7147280322535b6b1651
9,092
from typing import Iterable from typing import Union import dataclasses def make_datacls( cls_name: str, fields: Iterable[Union[tuple[str, type], tuple[str, type, dataclasses.Field]]], init: bool = True, **kwargs, ) -> type: """ Return a new dataclass. This function wraps the Python dataclasse...
d3797443212504605310ed75fbcb5ce37570b868
9,093
def square_loss(X, y, theta, reg_beta=0.0): """Computes squared loss and gradient. Based on mean square margin loss. X: (k, n) data items. y: (k, 1) result (+1 or -1) for each data item in X. theta: (n, 1) parameters. reg_beta: optional regularization strength, for L2 regularization. Retu...
3a1cc74eed3abd9c3a7921c9ea02e2169594f504
9,094
import glob def open_mf_wrf_dataset(paths, chunks=None, compat='no_conflicts', lock=None, preprocess=None): """Open multiple WRF files as a single WRF dataset. Requires dask to be installed. Note that if your files are sliced by time, certain diagnostic variable computed out of a...
9cf95b6da852406b2b24862604cd357c01f88a93
9,095
from typing import Optional from pathlib import Path def parse_args_and_add_yaml_variables(parser: ArgumentParser, yaml_config_file: Optional[Path] = None, project_root: Optional[Path] = None, fail_on_unk...
7d4c560a4887afd432da13df1e839cada329dd5a
9,096
def load_graph(model_file): """Loads a TensorFlow graph from file.""" graph = tf.Graph() with graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(model_file, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(o...
41e097afd34631ce8b2b94c9a67121886a568ede
9,097
def find_children(node, tag, xml_ns, ns_key): """ Finds the collection of children nodes Parameters ---------- node : ElementTree.Element tag : str xml_ns : None|dict ns_key : None|str """ if xml_ns is None: return node.findall(tag) elif ns_key is None: retu...
b51d9f588661c3f609dc53adaa328f974e17d5fb
9,098
import re def normalize_string(string, ignore_spaces, ignore_punctuation): """Normalizes strings to prepare them for crashing comparison.""" string = string.upper() if ignore_punctuation: string = re.sub(r"[^1-9a-z \n\r\t]", "", string, flags=re.I) if ignore_spaces: string = re.sub(r"\...
31de2b9644eb0943470430c6c3f2ea8a94dfb3cf
9,099