content
stringlengths
22
815k
id
int64
0
4.91M
def bio_hash_loss(weights: Array, x: Array, probs: Array) -> Array: """Calculates bio-hash loss from "Bio-Inspired Hashing for Unsupervised Similarity Search" (arXiv:2001.04907) Args: weights: model weights of shape output_features x input_features x: input of shape batch x input_features probs: p...
5,313,400
def bar_plot(attribute, faults, times, steps=[], ax=[]): """ Bar plot of fault network attribute Parameters ---------- attribute : np.array Attribute to plot faults : np.array Fault labels times : np.array Times used for plotting Returns ---...
5,313,401
def _c2024(node: ast.IfExp) -> Iterable[Tuple[int, int, str, type]]: """ A conditional expression should span over multiple lines. """ if lineno(node) == end_lineno(node): yield _error_tuple(2024, node)
5,313,402
def start_jupyter(instance, local_port=8889): """ This function tries to SSH onto the instance, remotely start a Jupyter notebook server, and forward given local port to it. """ # Check onif key is available key_name = instance["KeyName"] key_path = os.path.dirname(os.path.realpath(__file__)...
5,313,403
def train_model(data: Dict[str, Dataset], parameters: dict) -> Booster: """Train a model with the given datasets and parameters""" # The object returned by split_data is a tuple. # Access train_data with data[0] and valid_data with data[1] model = lightgbm.train(params=parameters, ...
5,313,404
def validateYaml(yaml, schema, yamlLoader=yaml.UnsafeLoader): """ Confirms that a given yaml follows the given schema. The schema can be a json string/dict. Throws a "jsonschema.exceptions.ValidationError" otherwise. """ assert YAML, "Must install PyYAML before attempting to load yaml files!" ...
5,313,405
def _bblock_hack(bc, bblock): """ The Tcl compiler has some annoying implementation details which must be recognised before any reduction. """ # 'variable' does not push a result so the Tcl compiler inserts a push. variableis = [] changes = [] for i, inst in enumerate(bblock.insts): ...
5,313,406
def yaml_add_odict(): """Add YAML serialization support for ``OrderedDict`` objects.""" if OrderedDict not in yaml.SafeDumper.yaml_representers: yaml.SafeDumper.add_representer(OrderedDict, _represent_odict)
5,313,407
def yellow_bold(payload): """ Format payload as yellow. """ return '\x1b[33;1m{0}\x1b[39;22m'.format(payload)
5,313,408
def add_trial_name_as_number(warm_up_data_df): """add column where trial_name is converted to number and before-/after-correction is added""" warm_up_data_df.insert( warm_up_data_df.shape[1], "trial_name_corrected_by_before_and_after", float(100) ) offset = 0 for index, row in warm_up_data_d...
5,313,409
def get_language(request: Request) -> str: """Get language based on request Accept-Language header or 'lang' query parameter.""" lang: Optional[str] = request.query_params.get("lang") language_code: Optional[str] = getattr(request, "LANGUAGE_CODE", None) if lang and lang in available_languages: ...
5,313,410
def test_cl_sa_h5py_4(): """ Test cluster info string round trip. """ locs = {"x" : numpy.arange(10, dtype = numpy.float), "y" : numpy.arange(10, dtype = numpy.float)} filename = "test_clusters_sa_h5py.hdf5" h5_name = storm_analysis.getPathOutputTest(filename) storm_analysis.rem...
5,313,411
def is_installed(package_name): """Checks if the app is installed.""" output = adb.run_shell_command(['pm', 'list', 'packages']) package_names = [line.split(':')[-1] for line in output.splitlines()] return package_name in package_names
5,313,412
def int_L1_keldysh(ngr, ngi, L1f, L1b, L1i, tir, tii, D1, gr, gi, Gr, Gi): """Return L1bar.""" L1i_out = numpy.zeros(L1i.shape, dtype=complex) for s in range(ngi): dt = numpy.zeros((ngi)) for y in range(s, ngi): dt[y] = tii[s] - tii[y] gtemp = numpy.exp(dt[:, None, None]*...
5,313,413
def cosine_similarity(v, u): """Calculate the cosine similarity between two vectors.""" v_norm = np.linalg.norm(v) u_norm = np.linalg.norm(u) similarity = v @ u / (v_norm * u_norm) return similarity
5,313,414
def test_loqusdb_exe_variant_CalledProcessError(loqus_exe_app, monkeypatch): """Test fetching a variant from loqusdb executable that raises an exception""" # GIVEN replacing subprocess.check_output to raise CalledProcessError def mockcommand(*args): raise subprocess.CalledProcessError(123, "case_co...
5,313,415
def normalize(rendered): """Return the input string without non-functional spaces or newlines.""" out = ''.join([line.strip() for line in rendered.splitlines() if line.strip()]) out = out.replace(', ', ',') return out
5,313,416
def calculateM10L5(e, epochPeriod, summary): """Calculates the M10 L5 relative amplitude from the average acceleration from the ten most active hours and 5 least most active hours :param pandas.DataFrame e: Pandas dataframe of epoch data :param int epochPeriod: Size of epoch time window (in seconds) ...
5,313,417
def _load_dismatch_prefix_params(net, parameter_dict, param_not_load): """When some net parameter did not load, try to continue load.""" prefix_name = "" longest_name = param_not_load[0] while prefix_name != longest_name and param_not_load: logger.debug("Count: {} parameters has not been loaded,...
5,313,418
def merge_subsentences_initializer( to_write_file, to_write_storage, to_read_file, to_read_storage, sentidx2offset_file ): """Merge subsentences initializer for multiprocessing. Args: to_write_file: file to write to_write_storage: mmap storage type to_read_file: file to read ...
5,313,419
async def test_download_speed(session: aiohttp.ClientSession, url: str) -> int: """Count the amount of data successfully downloaded.""" result = 0 try: async with session.get(url) as resp: while True: chunk = await resp.content.read(56) if not chunk: ...
5,313,420
def write_matrix_binary(fn, X, dtype="int"): """ write 2darray to binary file @param @return """ with open(fn, "wb") as fo: outdata = "" if dtype == "int": fmt = "i" elif dtype == "short": fmt = "h" elif dtype == "float": fmt = "f" ...
5,313,421
def dump(obj, f, **kwargs): # description {{{3 """Write the *NestedText* representation of the given object to the given file. Args: obj: The object to convert to *NestedText*. f (str, os.PathLike, io.TextIOBase): The file to write the *NestedText* content to. The f...
5,313,422
def dataload_update(args, api, configs): """ Creates threads to update records if any of them were marked as duplicates during import Args: args: arguments captured from CLI api: object to perform the API calls configs: shared configuration variables used across the script "...
5,313,423
def scale_design_mtx(X): """utility to scale the design matrix for display This scales the columns to their own range so we can see the variations across the column for all the columns, regardless of the scaling of the column. """ mi, ma = X.min(axis=0), X.max(axis=0) # Vector that is True ...
5,313,424
def quiet_errors(exc_type, exc_value, traceback): """Define error format suitable for end user scripts. Usage: enter the following lines in your script from isbnlib import quiet_errors sys.excepthook = quiet_errors """ sys.stderr.write('Error: %s\n' % exc_value)
5,313,425
def check_domain_filter(item: Dict, cfg: Config) -> bool: """ Validate that a given post is actually one that we can (or should) work on by checking the domain of the post against our filters. :param item: a dict which has the post information in it. :param cfg: the config object. :return: True...
5,313,426
def get_epistatic_seqs_for_landscape(landscape: potts_model.PottsModel, distance: int, n: int, adaptive: bool = True, max_reuse: Optional[int] = None, ...
5,313,427
def compare_nodal_prices(df_dcopf, df_mppdc): """Find max absolute difference in nodal prices between DCOPF and MPPDC models Parameters ---------- df_dcopf : pandas DataFrame Results from DCOPF model df_mppdc : pandas DataFrame Results from MPPDC model R...
5,313,428
def add(a, b): """A dummy function to add two variables""" return a + b
5,313,429
def get_interconnect_regs(interconnect: Interconnect): """function to loop through every interconnect object and dump the entire configuration space """ result = [] for x, y in interconnect.tile_circuits: tile = interconnect.tile_circuits[(x, y)] # cb first for cb_name, cb in...
5,313,430
def add_bg(sc): """ Choose a background and add it to a scaper object (check the duration). Args: sc: scaper.Scaper, a scaper object to add a background to. Returns: scaper.Scaper object with the background added. """ sc.add_background( label=("choose", []), source_file=("c...
5,313,431
def pipeline( *, dataset: HintOrType[DatasetLoader], model: HintOrType[Model], model_kwargs: Optional[Mapping[str, Any]] = None, optimizer_cls: Type[Optimizer] = torch.optim.Adam, optimizer_kwargs: Optional[Mapping[str, Any]] = None, loss_cls: Type[_Loss] = torch.nn.BCELoss, loss_kwargs:...
5,313,432
def test_list_items_282(): """ Test case 282: (part 2) Changing the bullet or ordered list delimiter starts a new list: """ # Arrange source_markdown = """1. foo 2. bar 3) baz""" expected_tokens = [ "[olist(1,1):.:1:3:]", "[para(1,4):]", "[text(1,4):foo:]", "[en...
5,313,433
def sha224(binary: bytes) -> str: """ Overview: SHA224 hash. Arguments: - binary (:obj:`bytes`): Binary data to be hashed. Returns: - digest (:obj:`str`): SHA224 digest string. Examples:: >>> from hbutils.encoding import sha224 >>> sha224(b'') 'd14a...
5,313,434
def get_telephone_number(input: Dict[str, Any]) -> str: """loop through JSON sample to find a specific response where element reference is equal to 'TelNo' and extract the telephone value of that specific response""" print(f"Getting telephone number, please wait...") for response_list in __valid_top...
5,313,435
async def async_setup(hass: HomeAssistant, config: dict): """Cannot setup using YAML""" return True
5,313,436
def _make_thread_locks_pickleable() -> None: """ This makes it so that thread-locked connections can be pickled """ LockType: type = type(threading.Lock()) RLockType: type = type(threading.RLock()) copyreg.pickle(LockType, lambda lock: (threading.Lock, ())) # type: ignore copyreg.pickle( ...
5,313,437
def get_next_on_schedule(): """Returns a list of current and 6 next assigned slots No request params. """ try: data = [{ 'time' : slot.time.strftime( '%H:%M' ), 'editor' : slot.editor.first_name + ' ' + slot.editor.last_name } for slot in Slot.get_nex...
5,313,438
def getErdosSectors(topm_dict,minimum_incidence=None): """Make Erdös sectorialization and return dict with main variables""" if not minimum_incidence: minimum_incidence=max(2,int(topm_dict["nnodes"]*0.01)) t=topm_dict max_degree_empirical=max(t["degrees_"]) prob=t["nedges"]/(t["nnodes"]*(t[...
5,313,439
def test_predict_path(): """ Test the main method of predict-path """ pytest_enable_socket() ## Testing with grch37-autosomal-dominant-genes-berg-v1 data package ## Test bad package name args = Namespace(channel='genomics', command='predict-path', file_name='grch37-autosomal-dominant-g...
5,313,440
def test_castep_summary_builder(sto_calc_inps_or_builder): """Test the get_castep_input_summary method""" from aiida_castep.calculations.tools import castep_input_summary keys = [ "kpoints", "structure", "code", "computer", "resources", "custom_scheduler_commands", "wallclock", "label", "ps...
5,313,441
def truncate(s, eps): """ Find the smallest k such that sum(s[:k]**2) \geq 1-eps. """ mysum = 0.0 k=-1 while (mysum < 1-eps): k += 1 mysum += s[k]**2 return k+1
5,313,442
def transform_pose_msg(msg, child_frame_current, child_frame_new): """ transform pose in given msg """ def pose_msg_to_matrix(msg): translate = [msg.position.x, msg.position.y, msg.position.z] angles = tf.transformations.euler_from_quaternion([msg.orientation.x, msg.orientation.y, msg.or...
5,313,443
def preprocess( input_folder: Path, output_folder: Path, level: int, tile_size: int, overlap: float, rotate: bool, ): """Create tiles and masks for all pairs of slides and annotations in a folder. The input folder and all its subfolders are searched. Args: input_folder (Pat...
5,313,444
def validate_uuid4(uuid_string): """Validate that a UUID string is in fact a valid uuid4. Happily, the uuid module does the actual checking for us. It is vital that the 'version' kwarg be passed to the UUID() call, otherwise any 32-character hex string is considered valid. """ if not isins...
5,313,445
def nmi(vanilla_result, fair_result, seed=0): """ calculate normalized mutual information (NMI) :param vanilla_result: vanilla mining result :param fair_result: debiased mining result :param seed: random seed :return: NMI between vanilla mining result and debiased mining result """ # kme...
5,313,446
def test_pick_channels_mixin(): """Test channel-picking functionality.""" raw, events, picks = _get_data() epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, preload=True) ch_names = epochs.ch_names[:3] epochs.preload = False pytest.raises(RuntimeError, epochs.dr...
5,313,447
def list_to_str(items): """ :param items: :return: """ mystr = '' for item in items: mystr += item return mystr
5,313,448
def prefixed_collapsible_map(m, prefix): """ Return a dict of params corresponding to those in m with the added prefix """ if m == values.unset: return {} def flatten_dict(d, result=None, prv_keys=None): if result is None: result = {} if prv_keys is None: ...
5,313,449
def to_minmax_form(boxes): """ :param boxes: (n, 4) tensor, (xmin, ymin, xmax, ymax) form. :return: (n, 4) tensor, (cx, cy, w, h) form """ xmin = boxes[:, 0] - boxes[:, 2] / 2 + 0.5 ymin = boxes[:, 1] - boxes[:, 3] / 2 + 0.5 xmax = boxes[:, 0] + boxes[:, 2] / 2 - 0.5 ymax = boxes[:, 1] ...
5,313,450
def apps(request): """ apps """ return render_mako_context(request, '/demo/apps.html')
5,313,451
def check_MADE_mask_dimensions(blocks, degrees_in, dimension_in, dimensions_hidden, out_per_dimension, dimension_conditioning, weight_norm): """Used by test_MADE_mask_dimensions and test_MADE_mask_dimensions_blocks.""" made = MADE( dimension_in=dimension_in, dimens...
5,313,452
def compute_unfolded_dimension(xtypes): """ Returns x dimension (int) taking into account unfolded categorical features """ res = 0 for xtyp in xtypes: if xtyp == FLOAT or xtyp == INT: res += 1 elif isinstance(xtyp, tuple) and xtyp[0] == ENUM: res += xtyp[1] ...
5,313,453
def evaluate_model(dataset_path, model_path): """ evaluate the model in test mode using a dataset """ # Load the trained model model = load_model(model_path) # Get data set x_test, y_test = get_dataset(dataset_path) # Evluate the model metrics = model.evaluate(x_test, y_test) # Di...
5,313,454
def store_remote_ca(ca): """ Store the remote ca :param ca: the CA """ with open(ca_cert_file, 'w+') as fp: fp.write(ca) try_set_file_permissions(ca_cert_file)
5,313,455
def nguniversal_setup_workspace(): """This repository rule should be called from your WORKSPACE file. It creates some additional Bazel external repositories that are used internally to build Angular Universal """ # Use Bazel managed node modules. See more below: # https://github.com/bazelb...
5,313,456
async def report_exc_info( exc_info=None, request=None, extra_data=None, payload_data=None, level=None, **kw ): """ Asynchronously reports an exception to Rollbar, using exc_info (from calling sys.exc_info()) exc_info: optional, should be the result of calling sys.exc_info(). If omitted, sys.exc_info()...
5,313,457
def publish_message(message_type, payload): """ Publishes a message to all alive clients :param message_type: Message type, should be in between 0 and 127 :param payload: The payload of the message :type message_type: int :type payload: bytes """ pass
5,313,458
def validate_input_parameters( input_parameters: Dict, original_parameters: Dict ) -> Dict: """Validate input parameters. :param input_parameters: dictionary which represents additional workflow input parameters. :param original_parameters: dictionary which represents original workflow input parameters...
5,313,459
def test_log_scatter(): """Issue #1799""" fig, ax = plt.subplots(1) x = np.arange(10) y = np.arange(10) - 1 ax.scatter(x, y) buf = io.BytesIO() fig.savefig(buf, format='pdf') buf = io.BytesIO() fig.savefig(buf, format='eps') buf = io.BytesIO() fig.savefig(buf, format='sv...
5,313,460
def getHirlamSimulationEndTime(root, datetime_format): """Helper function for getting the ending time for the latest simulation from HIRLAM XML-response.""" try: # get the starting time by finding the tags "resultTime" and "timePosition" result_time_elem = [elem for elem in root.iter() if "resul...
5,313,461
def GFFParse(ref_file): """Extracting annotated features from a GFF file based on feature identifier mapping.""" genes, transcripts, exons, utr5, utr3, cds = dict(), dict(), dict(), dict(), dict(), dict() ref_fh = open(ref_file, 'rU') for gln in ref_fh: gln = gln.strip('\n\r').split('\t') ...
5,313,462
def get_all_compiler_versions(): """Returns a sorted list of strings, like "70" or "80" or "9.0" with most recent compiler version first. """ versions=[] if is_windows: if is_win64: keyname = 'Software\\WoW6432Node\\Intel\\Compilers\\C++' else: keyname = 'Soft...
5,313,463
def detect_resolution(paths): """Attempt to detect the input resolution from a list of paths. Args: paths (list): List of file paths. Raises: ResolutionDetectionException: If there are too many possible resolutions in a path. ResolutionDetectionException: If there are inconsistent ...
5,313,464
def configure_plotting_functions( db_conn, read_bundled_simulation_results_from_db, extract_simulation_result, n_simulation_results, simulation_result_name, extract_display_info, compile_plot_annotation_text, node_names, output_dirpath, is_single_process, pdf_page_limit, image_formats_an...
5,313,465
def compute_mean_nutrient_intake(nutrient_intake): """Compute mean nutrient intake""" nutrient_totals = nutrient_intake.sum() total_count = nutrient_intake.count() carb_mean = (nutrient_totals[0]/total_count) fiber_mean = (nutrient_totals[1]/total_count) fat_mean = (nutrient_totals[2]/total...
5,313,466
def readbcvs(): """ readbcvs() Defined at ../src/readbcvs.f lines 61-89 """ _min3p.f90wrap_readbcvs()
5,313,467
def load_includes(paths): """ load python modules from the specified paths """ import os import sys from importlib.util import spec_from_file_location, module_from_spec import logging for path in paths: name = f"profit_include_{os.path.basename(path).split('.')[0]}" if name in sy...
5,313,468
def __(string): """Emojize a text, wrapping ``use_aliases``. Args: string (str): string to emojize. Returns: An emojized string. """ return emojize(string, use_aliases=True)
5,313,469
def preserve_channel_dim(func): """Preserve dummy channel dim.""" @wraps(func) def wrapped_function(img, *args, **kwargs): shape = img.shape result = func(img, *args, **kwargs) if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2: result = np.expand_dims(resul...
5,313,470
def redirect_auth_oidc(auth_code, fetchtoken=False, session=None): """ Finds the Authentication URL in the Rucio DB oauth_requests table and redirects user's browser to this URL. :param auth_code: Rucio assigned code to redirect authorization securely to IdP via Rucio Auth server ...
5,313,471
def inception_crop_with_mask( image, mask, resize_size=None, area_min=5, area_max=100): """Applies the same inception-style crop to an image and a mask tensor. Inception-style crop is a random image crop (its size and aspect ratio are random) that was used for training Inception models, see https://www.cs....
5,313,472
def delete_outputs(config, outcfg): """ Remove pipeline outputs to save memory after running the job Parameters ---------- config : dict-like Input configuration of job. Uses config["management"]["delete"] (list of key used to index outcfg) to determine which f...
5,313,473
def should_build_new_prices() -> bool: """ Determine if prices were built recently enough that there is no reason to build them again :return: Should prices be rebuilt """ cache_file = CACHE_PATH.joinpath("last_price_build_time") if not cache_file.is_file(): return True stat_ti...
5,313,474
def config_nat_pool_binding(dut, **kwargs): """ Config NAT pool bindings Author:kesava-swamy.karedla@broadcom.com :param :dut: :param :config: add/del: :param :binding_name: :param :pool_name: :param :nat_type: :param :twice_nat_id: :param :acl_name: usage: config_nat_p...
5,313,475
def database_obj_to_py(obj, fingerprints_in_song=False): """ Recursively convert Fingerprint and Song sqlalchemy objects to native Python types (lists and dicts). Args: obj (database.schema.Fingerprint|database.schema.Song): ``audio`` module Fingerprint or Song object. finge...
5,313,476
def validate_parts(): """ Validate found Items by matching them with possible parts. :return: - """ print("Validating Parts against local DB...") session = Session() queried_items = session.query(Item, File).filter(Item.file_id == File.id).all() try: for item in tqdm(queried_i...
5,313,477
def get_outputs(output_file): """ Parse ``output_file`` which is a csv file and defines the semantics of the output of a neural network. For example, output neuron 1 means class "0" in the MNIST classification task. """ outputs = [] mode = "rt" with open(output_file, mode, newline="...
5,313,478
def auto_adjust(img): """Python translation of ImageJ autoadjust function. Parameters ---------- img : ndarray Returns ------- (vmin, vmax) : tuple of numbers """ # calc statistics pixel_count = int(np.array((img.shape)).prod()) # get image statistics # ImageStatistics ...
5,313,479
def ChanPcaKmeansDS(ds, xvec='bias', chan='cf', mod=lambda y: y, comps=6,nclust=4, fig=None): """ :param ds: xarray dataset :param xvec: name of dataset coordinate :param chan: selected channel :param mod: if desired, pass the modifier for the plotting of the histogram via lambda functions :...
5,313,480
def elements(elements, axis=0): """ Calculates an node 2-d-array from an element 2-d-array, uses the [:, 1], [:, -2] entries of the calculated node 2-d-array to fill the first als last row of the node 2-d-array. """ nodes = np.asarray((elements[:, :-1] + elements[:, 1:])) * .5 return np.hsta...
5,313,481
def convert_date_to_unix(date_string): """Convert date input to unix timestamp. Args: date_string: the date input string. Returns: (int) converted timestamp. """ if not date_string: return None return int(dateparser.parse(date_string).timestamp() * 1000)
5,313,482
def decoder(decoder_inputs, initial_state, cell, output_size, loop_function=None, dtype=None, scope=None): """ The Decoder Function which returns the decoder hidden states after decoding the whole output args: decoder_inputs: The inputs to the decoder, either the targets during training or t...
5,313,483
def kron(nodes: Sequence[BaseNode]) -> BaseNode: """Kronecker product of the given nodes. Kronecker products of nodes is the same as the outer product, but the order of the axes is different. The first half of edges of all of the nodes will appear first half of edges in the resulting node, and the second half ...
5,313,484
def diskmounter() -> Mounter: """Fixture with an unversioned disk filesystem mounter.""" return unversioned_mounter(DiskFilesystem)
5,313,485
def _sysapp_expect_count(apps): """yield all sysapp app monitors """ sysproid = _get_cell_proid() cell_name = context.GLOBAL.cell for app in apps: app = '{}.{}.{}'.format(sysproid, app, cell_name) count = _get_appmonitor(app) try: # FIXME: at the moment, we suppo...
5,313,486
def stations(): """Return a JSON list of stations from the dataset.""" # most_active_stations = session.query(measurement.station, func.count(measurement.station)).\ # group_by(measurement.station).\ # order_by(func.count(measurement.station).desc()).all() stationr...
5,313,487
def search_sorted_matrix(matrix, target): # Write your code here. """ 1 4 7 12 15 1000 2 50 500 1001 3 1002 4 """ result = [-1, -1] row = 0 if len(matrix) == 0: return result col = len(matrix[0]) - 1 while col >= 0 and row < len(matrix): ...
5,313,488
def listen(client: socket.socket, username: str, group: Group): """ listening thread for the server :param client: socket object of the user :param username: username of the user :param group: group object of the user's group :return: None """ while True: try: if grou...
5,313,489
def get_io_functions_from_lib(lib, load_func_name='load', dump_func_name='dump', load_kwargs={}, dump_kwargs={}): """Helper to create loader and dumper functions for libraries""" def loader(input_stream, args): return getattr(lib, load_func_name)(input_stream, **load_kwargs) def dumper(output, outpu...
5,313,490
def get_pane_id(session: str, window: int, pane: int): """ Get a given pane ID Parameters ---------- session : str Name of the session window : int Window number of pane pane : int Pane index in the window """ injected = get_injected_pane_data(session, window...
5,313,491
def normalize_signs(arr1, arr2): """Change column signs so that "column" and "-column" compare equal. This is needed because results of eigenproblmes can have signs flipped, but they're still right. Notes ===== This function tries hard to make sure that, if you find "column" and "-column"...
5,313,492
def cleanup_unused_files(output_path: str): """ Cleanup the unused folders, as the data now exists in the VISSL compatible format. """ file_to_delete = os.path.join(output_path, "oxbuild_images.tgz") cleanup_dir(file_to_delete)
5,313,493
def draw_lines(img, lines, scale): """ this function draw lines on a picture, according to scale first point from the left is added in case of absence last point from the right is added in case of absence returns updated image """ if lines is not None and len(lines) > 0: # calculate...
5,313,494
def tokenize_de(text): """ 将德语文本从字符串标记为字符串列表 """ return [tok.text for tok in spacy_de.tokenizer(text)]
5,313,495
def port_in_use(port, host=LOCALHOST): """Returns True when a port is in use at the given host. Must actually "bind" the address. Just checking if we can create a socket is insufficient as it's possible to run into permission errors like: - An attempt was made to access a socket in a way forbidde...
5,313,496
def construct_model(lbann): """Construct LBANN model. Args: lbann (module): Module for LBANN Python frontend """ # TODO (tym): Figure out how to switch between LBANN builds. See # GitHub Issue #1289. import lbann.models # Layer graph input_ = lbann.Input() images = lbann....
5,313,497
async def video_feed(): """Video streaming route. Put this in the src attribute of an img tag.""" return StreamingResponse(gen(Camera()), media_type='multipart/x-mixed-replace; boundary=frame')
5,313,498
def logout(): """ Log out the user """ session.clear() return json_response(status=200, response_data={"success": True})
5,313,499