content
stringlengths
22
815k
id
int64
0
4.91M
def video_info_url_age_restricted(video_id: str, embed_html: str) -> str: """Construct the video_info url. :param str video_id: A YouTube video identifier. :param str embed_html: The html contents of the embed page (for age restricted videos). :rtype: str :returns: :samp:`ht...
60,900
def memcached(servers, key=None, from_cache=None, to_cache=None, time=0, min_compress_len=0, debug=False): """memcached memoization function decorator. The wrapped function is expected to return a value that is stored to a memcached server, first translated by `to_cache` if provided. In the e...
60,901
def favorite_book(title): """Display a message that shares a favorite book title.""" print("One of my favoite books is " + title + ".")
60,902
def slice_length(key: slice, length: int) -> int: """Calculate the length of the slice. Args: key: The slice to calculate the length of. length: The maximum length of the slice. Returns: The length of the slice. """ return len(range(*_slice_default_bounds(key, length)))
60,903
def navamsa_from_long(longitude): """Calculates the navamsa-sign in which given longitude falls 0 = Aries, 1 = Taurus, ..., 11 = Pisces """ one_pada = (360 / (12 * 9)) # There are also 108 navamsas one_sign = 12 * one_pada # = 40 degrees exactly signs_elapsed = longitude / one_sign fraction_left = sig...
60,904
def LogNormalRiskyDstnDraw(RiskyAvg=1.0, RiskyStd=0.0): """ A class for generating functions that draw random values from a log-normal distribution as parameterized by the input `RiskyAvg` and `RiskyStd` values. The returned function takes no argument and returns a value. """ RiskyAvgSqrd = Risk...
60,905
def register(add_parser, _): """Adds this sub-command's parser and returns the action function""" parser = add_parser('cat', help='output files by job or instance uuid') parser.add_argument('target-entity', nargs=1, help='Accepts either a job or an instance UUID or URL. The latest in...
60,906
def is_serialised(serialised): """ Detects whether some bytes represent an enumerated type. :param serialised: The bytes of which the represented type is unknown. :return: ``True`` if the bytes represent an enumerated type, or ``False`` if it doesn't. """ try: unicode_string = io.TextIOWrapper(io.BytesIO(seria...
60,907
def test_list_time_min_length_3_nistxml_sv_iv_list_time_min_length_4_1(mode, save_output, output_format): """ Type list/time is restricted by facet minLength with value 8. """ assert_bindings( schema="nistData/list/time/Schema+Instance/NISTSchema-SV-IV-list-time-minLength-4.xsd", instanc...
60,908
def compare_connexion(conn1, conn2): """See if two connexions are the same. Because the :class:`connexion` could store the two components in different orders, or have different instances of the same component object, direct comparison may fail. This function explicitly compares both possible combina...
60,909
def download_weights(VGG19_mat,verbose=False): """ Download the VGG19 weights trained on """ if(VGG19_mat=='imagenet-vgg-verydeep-19.mat'): download_url = os.path.join("http://www.vlfeat.org/matconvnet/models/imagenet-vgg-verydeep-19.mat") else: raise(NotImplementedError) i...
60,910
def save_dfs_to_csv(df_list: list, data_name: str): """ Save the split, cleaned list of 4 bio reactors dataframes to csv file. If files already exists, skips saving. Parameters ---------- df_list: list data_name: str desirable csv file name """ assert data_name in {"svi", "m...
60,911
def calculate_and_update_precise_bn(loader, model, num_iters=200): """ Update the stats in bn layers by calculate the precise stats. Args: loader (loader): data loader to provide training data. model (model): model to update the bn stats. num_iters (int): number of iterations to comp...
60,912
def get_station(station_number: str, db: Session = Depends(get_db)): """ Get information about a stream monitoring station. Data sourced from the National Water Data Archive. https://www.canada.ca/en/environment-climate-change/services/water-overview/quantity/monitoring/survey/data-products-services/nation...
60,913
def get_reminder_timezone( bot: Union[Sopel, SopelWrapper], reminder: Reminder ) -> pytz.BaseTzInfo: """Select the appropriate timezone for the ``reminder``. :param bot: bot instance :param reminder: reminder to get the timezone for :return: the appropriate timezone for ``reminder`` """ ...
60,914
def gen_function(): """ Generator function to continue animation. Will stop yielding if all sheep have been eaten (so carry_on = False) or if num_of_moves has been reached. Yields ------ i : int Iteration of the model. """ global carry_on i = 0 while (i < num_of_moves) ...
60,915
def is_successful_result(value: Union[MiddlewareResult, Any]) -> bool: """Returns ``True``, if given value is a successful middleware result.""" if value == MiddlewareResult.IGNORE: return False return True
60,916
def insert_ontology_value(value_name): """ insert ontology value to the file tools/ontology/src/ontology/qual/OntologyValue.java which is the enum class manages all the ontology values, annotaion would be gnereated in the form of @Ontology(values="{OntologyValue.ontology_value_name}") """ ontology_qual_dir ...
60,917
def generate_dynamic_multicommand( commands: List[Any], callback_function: Callable, create_short_names: bool = False ) -> Any: """Use provided dict to create a dynamic click.MultiCommand.""" has_short_names = False if create_short_names: __create_short_names_for_commands(com...
60,918
def save_papers_pickle(papers: list[dict[str, Any]], filename: str): """save papers (dict format) to file in folder data/papers""" with open(f"data/papers/{filename}", 'wb') as papers_file: pickle.dump(papers, papers_file, pickle.HIGHEST_PROTOCOL)
60,919
def get_verifier_repo_dir(verifier_id): """ Returns installed verifier repo directory for Tempest """ if not verifier_id: verifier_id = get_verifier_id() return os.path.join(getattr(config.CONF, 'dir_rally_inst'), 'verification', 'verifier-{}'...
60,920
def rmssd(nni: np.ndarray) -> float: """ Root mean square of differences. Params: nni (np.ndarray): R-peak intervals Returns: float """ return np.sqrt(np.mean(np.square(np.diff(nni))))
60,921
def get_kernel_pos_from_iomem(machine=None): """Get the position of some kernel segments using /proc/iomem Since Linux 4.6, access to physical addresses in /proc/iomem is restricted to privileged users, cf. commit 51d7b120418e ("/proc/iomem: only expose physical resource addresses to privileged users")...
60,922
def without_end_slash(url): """Makes sure there is no end slash at the end of a url.""" return url.rstrip("/")
60,923
def get_ipython_dir(): """Find the ipython local directory. Usually is <home>/.ipython""" if hasattr(itango, "get_ipython_dir"): return itango.get_ipython_dir() if hasattr(IPython.iplib, 'get_ipython_dir'): # Starting from ipython 0.9 they hadded this method return IPython.iplib.get...
60,924
def find_cutlevels(image, min_percent=None, max_percent=None, percent=None): """ Find pixel values of the minimum and maximum image cut levels from percentiles of the image values. Parameters ---------- image : array_like The 2D array of the image. min_percent : float, optional ...
60,925
def get_products(product_id): """ Retrieve a single Product This endpoint will return a Product based on its id """ app.logger.info("Request for product with id: %s", product_id) product = Product.find(product_id) if not product: raise NotFound("Product with id '{}' was not found.".f...
60,926
def test_score_fn_all_layers_rescale_with_baseline(preds, targets): """Tests for functional with baseline rescaling.""" original_score = original_bert_score( preds, targets, model_type=MODEL_NAME, lang="en", num_layers=8, idf=False, batch_size=3, r...
60,927
def _parse_file(): """Parse the config from a file. Note: Assumes any value that ``"$LOOKS_LIKE_THIS"`` in a service definition refers to an environment variable, and attempts to get it accordingly. """ file_name = path.join( path.abspath(path.dirname(path.dirname(__file__)))...
60,928
def get_answers() -> dict: """Return a dictionary containing every answer.""" with open(sys.argv[1], "r") as f: answers = json.load(f) return answers
60,929
def add_extensions_argument(parser): """Add the ``-x/--extension`` argument to an argument parser. Args: parser (:py:class:`argparse.ArgumentParser`): Arguments parser to extend. """ parser.add_argument( '-x', '--extension', '--ext', dest='extensions', action='append', ...
60,930
async def encode_md5(ctx,*args): """encodes text with md5""" original_text="".join(args) hash_obj = hashlib.md5(original_text.encode()) emb= discord.Embed(title="md5 encryption",description=f"original text is: {original_text} \nresult is: {hash_obj.hexdigest()}" ,color=random.choice(colors)) await ctx.send(em...
60,931
def calc_hexes_zscore_walk(gpkg_output, cityNames): """ Calculate zscore of hexagon-level indicators and walkability relative to all city, and save to output geopackage These indicators include (z-score of population weighted indicators relative to all cities): "all_cities_z_nh_population_density",...
60,932
def enter_password(prompt: str, default: str = '') -> str: """Hidden password input""" try: password = getpass(prompt) except (KeyboardInterrupt, EOFError): click.echo(None) sys.exit(1) if not password and default: password = default return password
60,933
def CloneNodeList(nodeList): """Return a clone of the given nodeList.""" # This is tricky because we want to maintain client/server links # make a list of cloned nodes, map maps original nodes to new nodes cloneList = [] map = {} for node in nodeList: newNode = node.Clone() newNode.RemoveAllServers() clone...
60,934
def last_bytes(path, num): """Return num bytes from the end of the file and unread byte count. Returns a tuple containing some content from the file and the number of bytes that appear in the file before the point at which reading started. The content will be at most ``num`` bytes, taken from the e...
60,935
def project_stabilized_state(stabilizer_list, num_qubits=None, classical_state=None): """ Project out the state stabilized by the stabilizer matrix |psi> = (1/2^{n}) * Product_{i=0}{n-1}[ 1 + G_{i}] |vac> :param List stabilizer_list: set of PauliTerms that are the stabiliz...
60,936
def newMenuItem(restaurant_id): """ Create a menu item with a specific restaurant's id. :param restaurant_id: Restaurant's id to which new menu item belongs. :return: on GET: Render new menu form template. on POST: Redirect to the menu page if the create request has been succeeded. """ r...
60,937
async def test_convert_seconds_to_iso_time( event_loop: AbstractEventLoop, ) -> None: """Test the convert_seconds_to_iso_time tool.""" with raises(CalculationError) as exc_info: await convert_seconds_to_iso_time(event_loop, -1) assert exc_info.type is CalculationError try: ...
60,938
def visualize_pred_frag( frag_confs, frag_coords, output_size, model_store, vis_prefix, vis_dir, vis_ext='png'): """Visualizes predicted fragment fields. Args: frag_confs: Predicted fragment confidences of shape [output_h, output_w, num_objs, num_frags]. frag_coords: Predicted 3D fragment...
60,939
def get_license_banner(comment: str = "") -> str: """Returns a commented out license banner. comment is the style of comment supported by the source file type. """ return apply_comment(LICENSE_BANNER, comment)
60,940
def execute_transaction(qldb_session, transaction, statement, parameter): """ Execute statement with parameters. If it was unsuccessful, retry with a new transaction. :type qldb_session: :py:class:`pyqldb.session.qldb_session.QldbSession` :param qldb_session: An instance of the QldbSession class. ...
60,941
def _cycle_list(l): """Loop in a list forever, even if its size changes. Error if empty.""" i = -1 while True: i = (i + 1) % len(l) yield l[i]
60,942
def parseXML(xml_filename: str) -> dict: """ This function generates an annotation dictionary representation of the contents of the specified XML filename. Args: xml_filename (str): Relative path to the XML file Returns: annotation (dict): Fepresentation of the entire XML file """ ...
60,943
async def direct_messages(sessionid: str = Form(...), thread_id: int = Form(...), amount: Optional[int] = Form(20), clients: ClientStorage = Depends(get_clients)) -> List[DirectMessage]: """ Get only Messages in Thread """ cl = clients...
60,944
def dt_bestrefs_catalog_dataset(): """ Compute simple bestrefs for 1 catalog datasets using hst.pmap: >>> old_state = test_config.setup() >>> BestrefsScript(argv="bestrefs.py --new-context hst.pmap --datasets LB6M01030")() # doctest: +ELLIPSIS CRDS - INFO - Dumping dataset parameters from CRDS se...
60,945
def randfor_cv(Xs, ys, folds=8, iterations=1, n_estimators=50, max_features='log2', random_state=44, n_jobs=8): """Compute random forest regression accuracy statistics, shuffling at the sequence level.""" r2s = [] pcors = [] for i in range(iterations): rs_iter = random_state + i ...
60,946
def fetch_download(file_path, url): """Circumvent the cache for large file downloads.""" session = requests.Session() session.headers.update(HEADERS) log.info("Fetching artifact", path=file_path.as_posix(), url=url) file_path.parent.mkdir(exist_ok=True, parents=True) with session.get(url, stream...
60,947
def var(u: Vec) -> float: """Computes the variance of the vector components Args: u (Vec): vector of values Raises: ValueError: if u is not provided or u is of non-numeric integral type Returns: float: the variance of the vectors components """ if not u: raise ...
60,948
def calculate_final_assembly_tipracks(final_assembly_dict): """Calculates the number of final assembly tipracks required ensuring no more than MAX_FINAL_ASSEMBLY_TIPRACKS are used. """ final_assembly_lens = [] for values in final_assembly_dict.values(): final_assembly_lens.append(len(values...
60,949
def main(): """Run application.""" logging.root.setLevel(logging.DEBUG) args = parse_args(sys.argv[1:]) logging.debug('Message: %s', args.message) if args.message.lower() != 'hello': logging.error('Please say "hello".') exit(1) logging.info('Hello.') exit(0)
60,950
def enforce_timeout_range(timeout_delta): """Enforce the range of allowed timeout values based on constants TIMEOUT_MIN Warnings are raised if the timeout is outside of the range. timeout_delta(timedelta): Timeout setting as instance of timedelta. """ if timeout_delta < TIMEOUT_MIN: logging...
60,951
def cross_validation_split(dataset, folds=10): """Return dataset split into 10 folds""" dataset_split = list() dataset_copy = list(dataset) fold_size = int(len(dataset) / folds) for i in range(folds): fold = list() while len(fold) < fold_size: index = randrange(len(datase...
60,952
def cleanup(): """This fixture removes modules under test from sys.modules. This ensures that each module is fully re-imported, along with the fixtures for each test function. """ yield None del sys.modules["unicornhatmini"]
60,953
def assert_configs_work(backend, client_config, server_config, hostname=None): """ Given a pair of configs (one for the client, and one for the server), creates contexts and buffers, performs a handshake, and then sends a bit of test data to confirm the connection is up. Returns the client and serv...
60,954
def insertClient(chatId, username=''): """ Добавление нового пользователя в БД :param chatid: id пользователя :param username: username пользователя :return: """ connection = connectDB() cursor = connection.cursor() query = ("INSERT INTO Clients (chatId, username) VALUES (" + str(ch...
60,955
def read_result_file(fname): """ read file with world record distances/paces """ running_paces = [] with open(fname, 'r') as result_file: for line in result_file: ent = line.split() if 'distance' in ent[0]: continue dist_meters = float(ent[0]) * 10...
60,956
def show_research(df, layout=None, average_repetitions=False, log_scale=False, rolling_window=None): """Show plots given by research dataframe.""" if layout is None: layout = [] for nlabel, ndf in df.groupby("name"): ndf = ndf.drop(['config', 'name', 'iteration', 'repetition'], axis=...
60,957
def version(): """ Show last commit to the deployed repo. """ with cd(env.code_dir): run('git log -1')
60,958
def psdChannelOutliner(*args, **kwargs): """ Dynamic library stub function """ pass
60,959
def is_droid_in_network_generation(log, ad, nw_gen, voice_or_data): """Checks if a droid in expected network generation ("2g", "3g" or "4g"). Args: log: log object. ad: android device. nw_gen: expected generation "4g", "3g", "2g". voice_or_data: check voice network generation or...
60,960
def _getMatricesFromDft2Outfile(outPath): """ Parses all hamiltonian and overlap matrices from a dft2 file Args: outPath: Full path to the output file Returns allMatrices: types.SimpleNamespace with two fields, hamil and overlap. Both are lists of square numpy arrays (dtype=complex). The ind...
60,961
def test_subject_observer_with_default_observer_performance(benchmark): """Testing simple notification process.""" observer = DefaultObserver() subject = Subject() subject.add_observer(observer) benchmark(subject.notify)
60,962
def verifySignatureFromBytes(data, publicKey, signature): """ Verify signature. Arguments: data (bytes) -- data in bytes publicKey (str) -- a public key as hex string signature (str) -- a signature as hex string Return bool """ if len(publicKey) == 66: publicKey = uncompressEcdsaPublicKey(publicKey) verif...
60,963
def load_setting_api_access_token(logger, config_settings): """ Attempt to parse API token from config settings :param logger: the logger :param config_settings: config settings loaded from config file :return: API token if valid, else None """ try: api_to...
60,964
def limit_posts(posts, limit=POST_LIMIT): """Restrict posts to the <limit> most recent.""" return posts.order_by(desc(Post.published_datetime)).limit(limit).from_self()
60,965
def command(login_required=True): """a decorator for handling authentication and exceptions""" def decorate(f): def wrapper(self, args): if login_required and self.api_client is None: self.stdout.write("Please 'login' to execute this command\n") return ...
60,966
def do(ModeName, CaMap, IndentationSetup, IncidenceDb, ReloadState, dial_db): """________________________________________________________________________ Counting whitespace at the beginning of a line. .-----<----+----------<--------------+--<----. | | count ...
60,967
def list_imports( python_script_path: str, ) -> None: """ List all project importable object into script. """ project_import_helper = ProjectImportHelper.of_filepath( SyntacticModuleLoader(), python_script_path, ) if project_import_helper is None: print('Failed to load pr...
60,968
def list_remote_files(con, directory): """ List the files and folders in a remote directory using an active SFTPClient from Paramiko :param con: SFTPClient, an active connection to an SFTP server :param directory: string, the directory to search :return: (generator, generator), the files and directories as separat...
60,969
def potential_aneurysm(data, box_size=64, accuracy=0.005, neighbours=False, pix_close=10): """ Goes through the given image and returns a list of possible aneurysms Parameters ---------- data : numpy.ndarray Data array of the MRA image of interest box_size : int Siz...
60,970
def debug_build(enabled: bool): """Decorator logs Layer.build() input shape. `@debug_build(DEBUG)`""" @wrapt.decorator(enabled=enabled) def wrapper(wrapped, instance, args, kwargs): print('{} build() (in {}) input_shape {}'.format( instance.__class__.__name__, instance.__class__.__module__, *args)...
60,971
def execute_script(script, *args): """Execute JavaScript in the currently selected frame or window. Within the script, use `document` to refer to the current document. For example:: execute_script('document.title = "New Title"') :argument script: The script to execute. :argument args: A ...
60,972
def det_curve(y_true, scores, distances=False): """DET curve Parameters ---------- y_true : (n_samples, ) array-like Boolean reference. scores : (n_samples, ) array-like Predicted score. distances : boolean, optional When True, indicate that `scores` are actually `distan...
60,973
def _get_nary_broadcast_shape(*shapes): """ Broadcast any number of shapes to a result shape. Parameters ---------- shapes : tuple[tuple[int]] The shapes to broadcast. Returns ------- tuple[int] The output shape. Raises ------ ValueError If the inpu...
60,974
def transcode(binaries_ent, videofiles, transcode_set, output_path, **kwargs): """ Make batch transcode. One-shot function. Args: binaries_ent: Dictionary with binaries and their path. videofiles: Iterable containing path to video files. transcode_set: Transcode_setting object. ...
60,975
def test_works_with_filterwarnings(testdir): """Ensure our warnings capture does not mess with pre-installed filters (#2430).""" testdir.makepyfile( """ import warnings class MyWarning(Warning): pass warnings.filterwarnings("error", category=MyWarning) clas...
60,976
def html_to_dot_sequential_name( root: lxml.html.HtmlElement, graph_name: str, with_text: bool = False ) -> graphviz.Digraph: """ The names of the nodes are defined by `{tag}-{seq - 1}`, where: tag: the html tag of the node seq: the sequential order of that tag ex: if it is the 2...
60,977
def get_exception_for_sqlstate(code): """Translate the sqlstate to a relevant exception. See for a list of possible errors: http://www.postgresql.org/docs/current/static/errcodes-appendix.html """ if isinstance(code, six.binary_type): code = bytes_to_ascii(code) if code[0] == '0': ...
60,978
def action_from_policy(policy, deterministic=False): """ Samples an action from a given policy using numpy. """ if not deterministic: return np.random.choice(range(len(policy)), p=policy) else: argmaxes = np.argwhere(policy == np.max(policy)).reshape(-1) return choice(argmaxe...
60,979
def error_rate(predictions, imgs): """Return the error rate based on dense predictions and sparse labels.""" return 0.5 * ((predictions - imgs)**2).mean()
60,980
def analyzeOptQuartz(libraryFile, gensize=8, topCartoons=1, optMax=False): """Analyzes the result of an optimization, plotting average and optimum diffusivity versus time. Input: libraryFile - pickled file containing the structure library gensize - (default 8) size of a generation ...
60,981
def setup_configs(args): """ args: ::dataset_name ::resolution """ ic(args) config = Munch( dataset_name=args.dataset_name, y_col="family", threshold=0, resolution="original" ) target_config = Munch( dataset_name=args.dataset_name, resolution=args.resolutio...
60,982
def powerset(seq): """ Returns all the subsets of this set. This is a generator. https://www.technomancy.org/python/powerset-generator-python/ """ if len(seq) <= 1: yield seq yield [] else: for item in powerset(seq[1:]): yield [seq[0]]+item yield i...
60,983
def fmap(func, obj): """fmap(func, obj) creates a copy of obj with func applied to its contents. Override by defining obj.__fmap__(func). For numpy arrays, uses np.vectorize. """ obj_fmap = _coconut.getattr(obj, "__fmap__", None) if obj_fmap is not None: try: result = obj_fmap(f...
60,984
def last_month(date): """get the name of month""" date = str(date) date = date[:4] + '-' + date[4:] date0 = arrow.get(date) lastmon = date0.shift(months=-1) lastmon = lastmon.format('YYYYMM') return lastmon
60,985
def test_issue1333(data): """Fail if asked to create more than one 1x1 overview""" inputfile = str(data.join('RGB.byte.tif')) with pytest.raises(OverviewCreationError): with rasterio.open(inputfile, 'r+') as src: overview_factors = [1024, 2048] src.build_overviews( ...
60,986
def camera_to_sky(pos_x, pos_y, focal, pointing_alt, pointing_az): """ Parameters ---------- pos_x: X coordinate in camera (distance) pos_y: Y coordinate in camera (distance) focal: telescope focal (distance) pointing_alt: pointing altitude in angle unit pointing_az: pointing altitude i...
60,987
def static_field(*args, **kwargs): """Substitute for dataclasses.field, which also marks a field as static.""" kwargs["metadata"] = kwargs.get("metadata", {}) kwargs["metadata"][FIELD_METADATA_STATIC_MARKER] = True return dataclasses.field(*args, **kwargs)
60,988
def load_resources(fhir_url: str, username: str = None, password: str = None, verify: bool = True): """ Loads resources into a target FHIR server :param fhir_url: The fhir server base url :param username: The fhir server username for basic auth (Optional) :param password: The fhir server password fo...
60,989
def _standardize_overhangs_pair(overhangs): """Standardize a pair of overhangs (o1, o2). Returns either ``(o1, o2)`` or its reverse complement ``(rev_o2, rev_o1)``, whichever is smaller in alphabetical order. """ o1, o2 = overhangs ro1, ro2 = [reverse_complement(o) for o in (o1, o2)] return...
60,990
def unjsonb(bytes): """bytes -> list""" return [json.loads(s.decode("utf-8")) for s in bytes.splitlines()]
60,991
def set_password(username, password, logger, client): """Set a new password for a user `USERNAME` is the username of the user """ logger.info('Setting new password for user {0}...'.format(username)) client.users.set_password(username, password) logger.info('New password set')
60,992
def get_nixtime_from_msec(msec): """ Convert unix epoch time in microseconds to a date string """ seconds, msec= divmod(msec, 1000000) days, seconds = divmod(seconds, 86400) if days > 20000 or days < 9000: days = 0 seconds = 0 msec = 0 return datetime.datetime(1970, 1, 1) + d...
60,993
def explode_fasta(fasta, log): """split input fasta into individuals""" in_file = False outdir = "fastas" if not os.path.exists(outdir): os.mkdir(outdir) with open(fasta, 'r') as infile: for line in infile: if line.startswith(">"): if in_file: ...
60,994
def doHammingByte(byte): """Secures one byte by hamming code""" #P1 = A1 xor A2 xor A4 xor A5 xor A7 P1 = str( int(byte[0]) ^ int(byte[1]) ^ int(byte[3]) ^ int(byte[4]) ^ int(byte[6]) ) #P2 = A1 xor A3 xor A4 xor A6 xor A7 P2 = str( int(byte[0]...
60,995
def partial_flatten(x): """Flatten all but the first dimension of an ndarray.""" return np.reshape(x, (x.shape[0], -1))
60,996
def get_spawn_day_counts(input: list[int], days: int) -> dict[int, int]: """Count the total number of fish after a given number of days and starting fish (number of days until they spawn another fish). """ spawn_day_counter: dict[int, int] = {} for spawn_day in range(days, -9, -1): # get ...
60,997
def get_all(*, db_session): """Returns all tickets.""" return db_session.query(Ticket)
60,998
def segment_rttm(in_file, out_file, boundaries): """output (sub-)meeting rttm file""" with open(in_file, 'r') as fin, open(out_file, 'w') as fout: for line in fin: info = line.split() meeting_name = info[1].split('-')[1] start = float(info[3]) end = start ...
60,999