content
stringlengths
22
815k
id
int64
0
4.91M
def run_question_generation(trainer, dset, model, tokenizer, device, num_beams): """ Generate a set of questions from a source text and list of answers (named entities) :param trainer: HuggingFace trainer :param dset: The dataset to generate questions from :param model: Question generation model ...
5,314,900
def get_queue_ids(client: Client) -> list: """ Creating a list of all queue ids that are in the system. Args: client: Client for the api. Returns: list of queue ids. """ queues = client.queues_list_request() queues = queues.get('Queues', []) queues_id = [] for q in qu...
5,314,901
def get_image_palette(img, nclusters): """ Extract tuple of (Image, Palette) in LAB space """ lab = rgb2lab(np.array(img)) palette = kmeans_get_palette(lab, nclusters) return lab, palette
5,314,902
def get_diaresnet_cifar(classes, blocks, bottleneck, model_name=None, pretrained=False, ctx=cpu(), root=os.path.join("~", ".mxnet", "models"), **kwargs)...
5,314,903
def isbuffer(obj) -> bool: """ Test whether `obj` is an object that supports the buffer API, like a bytes or bytearray object. """ try: with memoryview(obj): return True except TypeError: return False
5,314,904
def _get_mqtt_data(file_name): """ Reads mqtt fake data and expected results from file """ mqtt_data = [] with open(file_name, newline='') as mqtt_data_csv: csv_reader = csv.DictReader(mqtt_data_csv, quotechar="'", delimiter=';') for row in csv_reader: row[MqttCVS.in_topi...
5,314,905
def yes_maybe_condition_true(x: dict) -> bool: """ The yes maybe condition is true if 35% or 2 (or more) out of 3 users 2 (or more) out of 4 users 2 (or more) out of 5 users have classified as 'yes' or 'maybe' """ if x["yes_share"] + x["maybe_share"] > 0.35: return True else...
5,314,906
def load_texture(filename): """ This fuctions will return the id for the texture""" textureSurface = pygame.image.load(filename) textureData = pygame.image.tostring(textureSurface,"RGBA",1) width = textureSurface.get_width() height = textureSurface.get_height() ID = glGenTextures(1) glBindTe...
5,314,907
def test_nops(): """ Test that nops (no prefer shifts) will honored per rule. """ grammar = """ Program: "begin" statements=Statements ProgramEnd EOF; Statements: Statements1 | EMPTY; Statements1: Statements1 Statement | Statement; ProgramEnd: End; Statement...
5,314,908
def search(pattern, doc, flags=0): """Scan through string looking for a match to the pattern, returning a match object, or None if no match was found.""" return _compile(pattern, flags).search(string)
5,314,909
def yolo4_mobilenetv3small_body(inputs, num_anchors, num_classes, alpha=1.0): """Create YOLO_V4 MobileNetV3Small model CNN body in Keras.""" mobilenetv3small = MobileNetV3Small(input_tensor=inputs, weights='imagenet', include_top=False, alpha=alpha) # input: 416 x 416 x 3 # activation_31(layer 165...
5,314,910
def main(): """ Go do something """ form = cgi.FieldStorage() include_latlon = (form.getfirst('gis', 'no').lower() == 'yes') myvars = form.getlist('vars') myvars.insert(0, 'station') myvars.insert(1, 'obtime') delimiter = DELIMITERS.get(form.getfirst('delim', 'comma')) what = form.getfir...
5,314,911
def test_recover_training_mean_teacher_model(test_output_dirs: OutputFolderForTests) -> None: """ Tests that training can be recovered from a previous checkpoint. """ config = DummyClassification() config.mean_teacher_alpha = 0.999 config.recovery_checkpoint_save_interval = 1 config.set_outp...
5,314,912
def get_all_effects(fname): """ Give fname from a direct effect file """ # Step 1: Load results for current file print(fname) indirect_result_df = pd.read_csv(fname) analyze_effect_results( results_df=indirect_result_df, effect="indirect" ) fname = fname.replace("_indirect_"...
5,314,913
def cart_key(user_id=DEFAULT_USER_ID): """Sub model for representing an author.""" return ndb.Key('addSong2Cart', user_id)
5,314,914
def format_datetime(date_str): """ Convert Twitter's date time format ("Thu Jul 20 19:34:20 +0000 2017") to ISO 8601 International Standard Date and Time format. :param date_str: :return: """ with suppress(TypeError, ValueError): dt = datetime.datetime.strptime(date_str, '%a ...
5,314,915
def git_named_refs(git_hash: str, git_dir: Path) -> Dict[str, str]: """ Returns all named tag or reference for the provided hash and the hash. This method does not need nor uses a git client installation. """ refs = dict(hash=git_hash) ref_dir = git_dir / 'refs' for item in ref_dir.glob('**...
5,314,916
def migrate_data(filename): """ Migrate old AC bot data from the pickle file to a database. :param filename: :return: """ am = AcManager() am.build_db() tz = pytz.timezone("America/Los_Angeles") with open(filename, 'rb') as ac_file: ac_data = pickle.load(ac_file) # crea...
5,314,917
async def react_as_pinned(message: discord.Message) -> None: """React to the message to indicate that it is pinned already.""" # TODO: Custom reaction support try: await message.add_reaction("📌") except discord.HTTPException as e: # If for some reason reactions are full and the pushpin ...
5,314,918
def check_string(seq): """Checks if seq is a string""" if not isinstance(seq, str): assert False, "Input is not a string." else: pass return None
5,314,919
def shift_right(sized: Sized, n: int) -> Sized: """Return a copy of sized with it's elements shifted n places to the left but keeping the same size. sized: A sized object which's elements to shift n: How many places to shift sized's items to the left """ return [None] * n + sized[n : len(sized)]
5,314,920
def backport_makefile( self, mode="r", buffering=None, encoding=None, errors=None, newline=None ): """ Backport of ``socket.makefile`` from Python 3.5. """ if not set(mode) <= {"r", "w", "b"}: raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,)) writing = "w" in m...
5,314,921
def epoch_seconds(d: datetime = None) -> int: """ Return the number of seconds for given date. If no date, return current. :param d: timestamp datetime object :return: timestamp in epoch """ if not d: d = datetime.utcnow() return int((d - datetime.utcfromtimestamp(0)).total_seconds()...
5,314,922
def parse_json(json_file): """JSON poem parser for 'Gongocorpus'. We read the data and find elements like title, author, year, etc. Then we iterate over the poem text and we look for each stanza, line, word and syllable data. :param json_file: Path for the json file :return: Dict with the data ...
5,314,923
def chou_pseudo_aa_composition(*sequences): """ M.K. Gupta , R. Niyogi & M. Misra (2013) An alignment-free method to find similarity among protein sequences via the general form of Chou’s pseudo amino acid composition, SAR and QSAR in Environmental Research, 24:7, 597-609, DOI: 10.1080/1062936X.20...
5,314,924
def calculate_wire_sweeping_const(h_over_d): """Calculate the wire-sweeping constant for the Upgraded Cheng-Todreas friction factor constant calculation""" ws = {} if h_over_d == 0.0: ws['turbulent'] = 0.0 ws['laminar'] = 0.0 else: ws['turbulent'] = -11.0 * np.log10(h_over_d)...
5,314,925
def create_subscription_definition(subscription_definition_dict): """Create a subscription definition.""" cli_input = json.dumps(subscription_definition_dict) cmd = [ "aws", "greengrass", "create-subscription-definition", "--cli-input-json", cli_input ] output...
5,314,926
def sync_labels(src_repo, dst_repo, dry_run, delete): """ Main subroutine: sync labels between source/destination Github repos :param src_repo: full repo name for source of labels :param dst_repo: full repo name for destination of label actions :param dry_run: do a dry run, do not perform the actio...
5,314,927
def compile(element, compiler, **_kw): # pylint: disable=function-redefined """ Get length of array defined in a JSONB column """ return "jsonb_typeof(%s)" % compiler.process(element.clauses)
5,314,928
def guid(fn): """Server mock; grab the object guid from the url""" @wraps(fn) def wrapper(self, request, context, *args, **kwargs): guid = uuid_url_matcher('.+').match(request.path).group(1) return fn(self, request=request, context=context, guid=guid, *args, **kwargs) return wrapper
5,314,929
def magma_sgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, iwork, info): """ SDD decomposition. """ status = _libmagma.magma_sgesdd(jobz, m, n, int(a), lda, int(s), int(u), ldu, int(vt), ldvt, int(work)...
5,314,930
def pil_to_numpy(img: Image.Image) -> np.ndarray: """ Args: img: an Image.Image from `read_img()` Returns: np.ndarray, RGB-style, with shape: [3, H, W], scale: [0, 255], dtype: float32 """ return np.asarray(img.convert('RGB'), dtype='float32').transpose((2, 0, 1))
5,314,931
def convert_bart_tf(model, config, model_name): """TF converter Args: model_hf: HuggingFace Model (TF) model: tf_transformers model/layer config: dict Returns: a function """ # When dropout, use_auto_regressive is enabled assertion won't work SKIP_ASSERT = False ...
5,314,932
async def on_member_remove(member: discord.Member) -> None: """Emitted when a member leaves a guild"""
5,314,933
def main(cmd=None): """Run TTS model decoding.""" print(get_commandline_args(), file=sys.stderr) parser = get_parser() args = parser.parse_args(cmd) kwargs = vars(args) kwargs.pop("config", None) inference(**kwargs)
5,314,934
def reference(t, viscosity, density, concentration_init, concentration_init_dev, solutes, permittivity, enable_NS, enable_EC, **namespace): """ This contains the analytical reference for convergence analysis. """ mu = viscosity[0] rho_0 = density[0] ...
5,314,935
def std_err_mean(data): """ calculates deviation from mean. data: all spikes """ return data.std(0).mean()/np.sqrt(data.shape[0])
5,314,936
def mock_history(initial): """ mock the commands that interact with the .history file, to fake history management """ releases = copy.copy(initial) project = 'project' def list_releases(): return releases def _append_to_history(release): releases.append(release) d...
5,314,937
def _EpoOff(opts, node_list, inst_map): """Does the actual power off. @param opts: The command line options selected by the user @param node_list: The list of nodes to operate on (all need to support OOB) @param inst_map: A dict of inst -> nodes mapping @return: The desired exit status """ if not _Insta...
5,314,938
def available_numbers(request): """Uses the Twilio API to generate a list of available phone numbers""" form = AreaCodeForm(request.POST) if form.is_valid(): # We received a valid area code - query the Twilio API area_code = form.cleaned_data['area_code'] available_numbers = search...
5,314,939
def stress_vmss_instance_cpu(filter: str = None, duration: int = 120, timeout: int = 60, configuration: Configuration = None, secrets: Secrets = None): """ Stress CPU up to 100% at random machines...
5,314,940
def ztp(dic, data): """ 3D Matrix Transpose """ raise NotImplementedError
5,314,941
def raw_to_clean(env): """ Runs scripts to move data from raw tables to cleaned tables in PSQL. Parameters ========== env : dict Dictionary with PSQL environment variables. Returns ======= None """ DIR = '../../sql/clean/' # 0. Open database connection db_url =...
5,314,942
def configure_ansible(): """ Configure ansible to work with service.ansible and subspace. """ subspace.set_constants("HOST_KEY_CHECKING", False) subspace.set_constants( "DEFAULT_ROLES_PATH", settings.ANSIBLE_ROLES_PATH) if settings.ANSIBLE_CONFIG_FILE: os.environ["ANSIBLE_CONFIG"...
5,314,943
def get_julia_version(path): """Return version of the Julia installed in *path*""" return exec_shell_cmd('julia.exe -v', path).splitlines()[0].split(" ")[-1]
5,314,944
def get_pvc_file(flags, spa, pvc_name): """ Get pvc config """ outfile = os.path.join(os.getenv('TMPDIR', '/tmp'), pvc_name + '.yaml') args = [ 'spa', 'get', '-A', flags.account_arg, '--id', spa['meta']['id'], '-K', 'k8sPvcYaml', '-...
5,314,945
def video_feed(): """Video streaming route. Put this in the src attribute of an img tag.""" return Response(attendence(), mimetype='multipart/x-mixed-replace; boundary=frame')
5,314,946
def current(ticker): """ Return the current price for a stock """ return rh.get_latest_price(ticker)[0]
5,314,947
async def amain() -> None: """ Aynchronous main method of command-line program. Async so it can call async methods without messing around with event loops. :return: nothing """ async with ClientSession() as session: reply = await session.get(argv[1]) raw = await reply.read() ...
5,314,948
def _file(*args): """ Wrapper around os.path.join and os.makedirs.""" filename = os.path.join(*args) _makedirs_for_file(filename) return filename
5,314,949
def get_root_data_dir() -> str: """ Return the directory where the mephisto data is expected to go """ global loaded_data_dir if loaded_data_dir is None: default_data_dir = os.path.join(get_root_dir(), "data") actual_data_dir = get_config_arg(CORE_SECTION, DATA_STORAGE_KEY) i...
5,314,950
def fetch_indicators_command( client, initial_interval, limit, last_run_ctx, fetch_full_feed: bool = False, filter_args: Optional[dict] = None, ) -> Tuple[list, dict]: """ Fetch indicators from TAXII 2 server :param client: Taxii2FeedClient :param initial_interval: initial interv...
5,314,951
def aggregate(loss, weights=None, mode='mean'): """Aggregates an element- or item-wise loss to a scalar loss. Parameters ---------- loss : Theano tensor The loss expression to aggregate. weights : Theano tensor, optional The weights for each element or item, must be broadcastable to...
5,314,952
def test_get_account_fail(): """ Tests getting an account with a bad token """ invalid_token = "invalid-customer-token" assert accounts.get_account(invalid_token) == {'error': 'Token not found'}
5,314,953
def mirror_ud(image): """Mirrors an image between up and down :param image: An input image to convert :type image: array_like :return: Mirrored image. Same dimensions as input. :rtype: ndarray """ return np.flipud(image)
5,314,954
def better_savefig(fig, figfile, format="pdf", **kwargs): """To be used instead of .savefig This function saves pdfs without creation date. So subsequent overwrites of pdf files does not cause e.g. git modified. """ if format == "pdf": with PdfPages(figfile, metadata={"CreationDate": None})...
5,314,955
def test_escaped_unicode_literal(source): """Test a C source file may contain string literals containing escaped unicode characters.""" self = CSlug(anchor(name()), source) self.make() assert self.dll.a() == "㟐"
5,314,956
def ifftn(input, s=None, dim=-1, norm='backward', real=None): """N-dimensional discrete inverse Fourier transform. Parameters ---------- input : tensor Input signal. If torch <= 1.5, the last dimension must be of length 2 and contain the real and imaginary parts of the signal, u...
5,314,957
def list_del(): """ del """ mylist = ['dog', 'lion', 'snake', 'elephant', 'cow', 'donkey', 'goat', 'duck'] del mylist[2] return mylist
5,314,958
def _get_group_definition(group): """Get an instance of the group definition for the specified item. This definition can be used to clone or download the group. Keyword arguments: group - The arcgis.GIS.Group to get the definition for.""" return _GroupDefinition(dict(group), thumbnail=None, portal_...
5,314,959
def fetch_bike_dataset(years, data_dir="data"): """ Dowload bike dataset for a given year and return the list of files. """ base_url = "https://s3.amazonaws.com/capitalbikeshare-data/" files = [] for year in years: filename = str(year) + "-capitalbikeshare-tripdata.zip" filepath = os...
5,314,960
def assert_rank(x, rank, data=None, summarize=None, message=None, name=None): """Assert `x` has rank equal to `rank`. Example of adding a dependency to an operation: ```python with tf.control_dependencies([tf.compat.v1.assert_rank(x, 2)]): output = tf.reduce_sum(x) ``` Args: x: Numeric `Tensor`....
5,314,961
def test_random_vertical_valid_prob_c(): """ Test RandomVerticalFlip op with c_transforms: valid non-default input, expect to pass """ logger.info("test_random_vertical_valid_prob_c") original_seed = config_get_set_seed(0) original_num_parallel_workers = config_get_set_num_parallel_workers(1) ...
5,314,962
def add_gif_info(additional_info: dict, img: Image.Image) -> None: """ If the image is a GIF retrieve GIF specific metadata :param additional_info: The additional_indo dict in which the metadata is stored :param img: The Image object from which we can gather the metadata """ additional_info['gif...
5,314,963
def get_lo_hi_from_CI(s, exclude=None): """ Parse the confidence interval from CI. >>> get_lo_hi_from_CI("20-20/40-60") (40, 60) """ a, b = s.split("|") ai, aj = a.split("-") bi, bj = b.split("-") los = [int(ai), int(bi)] his = [int(aj), int(bj)] if exclude and exclude in l...
5,314,964
def get_pretrained_model(path='saved_models/checkpoint-1480'): """Gets a BERT classification model from a given pretrained model checkpoint (supplied with a filepath). Args: path (str): a valid filepath that contains the checkpoint of a DistilBert model Returns: transformers.DistilBertForSequenceClassification...
5,314,965
def get_docstring_summary( cls: Type, *, fallback_to_ancestors: bool = False, ignored_ancestors: Iterable[Type] = (object,) ) -> Optional[str]: """Get the summary line(s) of docstring for a class. If the summary is one more than one line, this will flatten them into a single line. """ # This will f...
5,314,966
def get_input_evaluation_tensors(reader, data_pattern, batch_size=1024, num_readers=1): """Creates the section of the graph which reads the evaluation data. Args: reader: A class which parses the training d...
5,314,967
def pause(interval: float) -> None: """Redraw the current Matplotlib figure **without stealing focus**. **IMPORTANT**: Works after `plt.show()` has been called at least once. **Background**: Matplotlib (3.3.3) has a habit of popping the figure window to top when it is updated using show() or...
5,314,968
def parse_ped(ped_infile, ped_outfile): """ Randomly select allele at heterozygous site in ped file and convert to homozygous """ with open(ped_infile, 'r') as fin: with open(ped_outfile, 'w') as fout: for line in fin: row = line.split() info = row[0:...
5,314,969
def load_extensions(app): """ To load navitaire extension :param app: :param name: :return: """ if 'stargate' not in app.extensions: raise GeneralError({ "code": "General Error", "description": "{name} not exist".format(name='stargate') }, 'info', http...
5,314,970
def blur(img): """ This function will blur the original image --------------------------------------------- :param img: SimpleImage, the original image :return: SimpleImage, the blurred image """ new_img = SimpleImage.blank(img.width, img.height) for x in range(img.width): for y ...
5,314,971
def check_virustotal(domain, api_key, threshold): """ Checks VirusTotal to see if the domain is malicious """ #resource = "{0}domain".format("http://www.", domain) url = 'https://www.virustotal.com/vtapi/v2/url/report' params = {'resource': domain, 'apikey': api_key, 'allin...
5,314,972
def describe_db_instances( name=None, filters=None, jmespath="DBInstances", region=None, key=None, keyid=None, profile=None, ): """ Return a detailed listing of some, or all, DB Instances visible in the current scope. Arbitrary subelements or subsections of the returned dataset ...
5,314,973
def get_parent_until(path): """ Given a file path, determine the full module path. e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields 'numpy.core' """ dirname = osp.dirname(path) try: mod = osp.basename(path) mod = osp.splitext(mod)[0] imp.find_mo...
5,314,974
def test_download_hashes(cbcloud_api_mock, hashes): """Unit test _download_hashes function.""" cbcloud_api_mock.mock_request("POST", "/ubs/v1/orgs/test/file/_download", FILE_DOWNLOAD_RESP) hash_dl = _download_hashes(cbcloud_api_mock.api, hashes, 60) assert len(hash_dl.found) == 1 assert len(hash_dl....
5,314,975
def DSHAPE(tmpdir_factory): """Run DSHAPE example.""" input_path = ".//tests//inputs//DSHAPE" output_dir = tmpdir_factory.mktemp("result") desc_h5_path = output_dir.join("DSHAPE_out.h5") desc_nc_path = output_dir.join("DSHAPE_out.nc") vmec_nc_path = ".//tests//inputs//wout_DSHAPE.nc" booz_nc...
5,314,976
def clear_alarm(token, fm_uuid="", fm_service=OPENSTACK_SERVICE.FM): """ Clear customer alarm to Fault Management """ url = token.get_service_url(fm_service) if url is None: raise ValueError("OpenStack FM URL is invalid") api_cmd = assemble_api_cmd(url, "alarms") api_cmd_headers = ...
5,314,977
def get_control_changes(midi, use_drums=True): """Retrieves a list of control change events from a given MIDI song. Arguments: midi (PrettyMIDI): The MIDI song. """ midi_control_changes = [] for num_instrument, midi_instrument in enumerate(midi.instruments): if not midi_instrument.i...
5,314,978
def _write_neighbors(neighbor_indices, neighbor_distances): """Write neighbor indices and distances.""" logging.info('Writing neighbors') indices_path = Path(FLAGS.data_root) / data_utils.NEIGHBOR_INDICES_FILENAME distances_path = ( Path(FLAGS.data_root) / data_utils.NEIGHBOR_DISTANCES_FILENAME) indices...
5,314,979
def is_workinprogress(change): """Return True if the patchset is WIP :param dict change: De-serialized dict of a gerrit change :return: True if one of the votes on the review sets it to WIP. """ # This indicates WIP for older Gerrit versions if change['status'] != 'NEW': return True ...
5,314,980
def get_bot() -> NoneBot: """ 获取全局 NoneBot 对象。可用于在计划任务的回调中获取当前 NoneBot 对象。 返回: NoneBot: 全局 NoneBot 对象 异常: ValueError: 全局 NoneBot 对象尚未初始化 用法: ```python bot = nonebot.get_bot() ``` """ if _bot is None: raise ValueError('NoneBot instance has no...
5,314,981
def nbr(nir_agg: xr.DataArray, swir2_agg: xr.DataArray, name='nbr'): """ Computes Normalized Burn Ratio. Used to identify burned areas and provide a measure of burn severity. Parameters ---------- nir_agg : xr.DataArray 2D array of near-infrared band. swir_agg : xr.D...
5,314,982
def white_noise(sigma, T, seed): """Реализация независимого белого шума длины T, ε ~ N(0, sigma^2)""" np.random.seed(seed) noise = np.random.normal(loc=0, scale=sigma, size=(1, T)) return noise
5,314,983
def all_derivatives(Ybus, Vbus, Sbus, Ibus, Cf, Ct, Cg): """ :param Ybus: :param Vbus: :param Sbus: :param Ibus: :param Cf: :param Ct: :param Cg: :return: """ n = len(Vbus) Vm = np.abs(Vbus) Va = np.angle(Vbus) E = diags(Vbus / Vm) V = diags(Vbus) I = d...
5,314,984
def register_serializable(cls): """A class decorator registering the class for serialization.""" __types[type2str(cls)] = cls return cls
5,314,985
def generate_realized_trips_from_gtfs(gtfs_path): """Transforms a GTFS feed to realized_trips format (see README for specification). It can either read a feed zip file or a folder. Parameters ---------- gtfs_path : str GTFS feed zip file or folder path Returns ------- pd.D...
5,314,986
def get_stockdata_from_sql(mode,begin,end,name): """ get stock market data from sql,include: [Open,High,Low,Close,Pctchg,Vol, Amount,total_shares,free_float_shares,Vwap] """ try: conn = pymysql.connect(**config) cursor = conn.cursor() if mode == 0: query = "SELECT...
5,314,987
def full_isomorphism(gra1, gra2): """ full graph isomorphism """ assert gra1 == explicit(gra1) and gra2 == explicit(gra2) nxg1 = _networkx.from_graph(gra1) nxg2 = _networkx.from_graph(gra2) iso_dct = _networkx.isomorphism(nxg1, nxg2) return iso_dct
5,314,988
def downgrade(): """ Drop trigger and function that synchronize `releases`. """ op.execute("DROP TRIGGER releases_requires_python ON releases") op.execute("DROP FUNCTION update_release_files_requires_python()") op.drop_column("release_files", "requires_python")
5,314,989
def likelihood_overlap(lk1, lk2): """ Returns overlap area of two likelihood functions. Parameters ---------- lk1 : numpy.ndarray First likelihood function. lk2 : numpy.ndarray Second likelihood function. Returns ------- overlap : float Overlap area. ""...
5,314,990
def get_total_cpu_time_and_memory_usage(): """ Gives the total cpu time of itself and all its children, and the maximum RSS memory usage of itself and its single largest child. """ me = resource.getrusage(resource.RUSAGE_SELF) children = resource.getrusage(resource.RUSAGE_CHILDREN) total_cpu...
5,314,991
def require_single_skillet(func): """Commands decorated with this require one skillet to be uniquely specified""" def wrap(command): if not command.sli.options.get("name") and len(command.sli.skillets) > 1: raise InvalidArgumentsException( f"Specify a skillet to run with --n...
5,314,992
def get_ecf_player(database, key): """Return ECFrefDBrecordECFplayer instance for dbrecord[key].""" p = database.get_primary_record(filespec.ECFPLAYER_FILE_DEF, key) pr = ECFrefDBrecordECFplayer() pr.load_record(p) return pr
5,314,993
def pickle_load(namefile: str): """Load Python variable, given name of file. :param namefile: A string of file to load. :return output: A loaded variable. """ with open(namefile, 'rb') as load_file: output = pickle.load(load_file) return output
5,314,994
def load_preset_linelist(name): """ Returns one of our preset line lists, loaded into an astropy QTable """ metadata = get_linelist_metadata() if name not in metadata.keys(): raise ValueError("Line name not in available set of line lists. " + "Valid list names are: {...
5,314,995
def scale_matrix(matrix): """ nn works best with values between 0.01 and 1 """ return matrix / 255 * 0.99 + 0.01
5,314,996
def load_record_set(path): """ 加载训练/测试集 """ record_list = [] if not os.path.isfile(path): raise IOError("File not Found!") with open(path, "r") as f: content = list(f) record_list = encapsule(content) return record_list
5,314,997
def _dist_mz_interval( index: faiss.Index, vectors: np.ndarray, precursor_mzs: np.ndarray, rts: np.ndarray, batch_size: int, n_neighbors: int, n_neighbors_ann: int, precursor_tol_mass: float, precursor_tol_mode: str, rt_tol: float, distances: np.ndarray, indices: np.ndarray, indp...
5,314,998
def glTexCoord4iv(v): """ v - seq( GLint, 4) """ if 4 != len(v): raise TypeError(len(v), "4-array expected") _gllib.glTexCoord4iv(v)
5,314,999