content
stringlengths
22
815k
id
int64
0
4.91M
def test_get_train_test_val(capsys): """Tests imbDRL.data.get_train_test_val.""" X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) y = np.array([1, 0, 0, 0]) with pytest.raises(ValueError) as exc: data.get_train_test_val(X, y, X, y, 0.2, [0], [1, 2], val_frac=0.0) assert "not in interval" in s...
28,600
def readExampleInfos(fpath, examples): """ Add the example infos for the file fpath to the global dictionary examples. """ # Create doctree t = SConsDoc.SConsDocTree() t.parseXmlFile(fpath) # Parse scons_examples for e in stf.findAll(t.root, "scons_example", SConsDoc.dbxid, ...
28,601
def keep_row(row): """ :param row: a list for the row in the data :return: True if we should keep row; False if we should discard row """ if row[_INDICES["Actor1CountryCode"]] in _COUNTRIES_OF_INTEREST or \ row[_INDICES["Actor2CountryCode"]] in _COUNTRIES_OF_INTEREST: return True ...
28,602
def test_estimator_results(): """ creating some planes pointing in different directions (two north-south, two east-west) and that have a slight position errors (+- 0.1 m in one of the four cardinal directions """ horizon_frame = AltAz() p1 = SkyCoord(alt=43 * u.deg, az=45 * u.deg, frame=horizon...
28,603
def _grad_shapelets(X, y, n_classes, weights, shapelets, lengths, alpha, penalty, C, fit_intercept, intercept_scaling, sample_weight): """Compute the gradient of the loss with regards to the shapelets.""" n_samples, n_timestamps = X.shape # Derive distances between s...
28,604
def get_tags_list(server_address: str, image_name: str) -> List[str]: """ Returns list of tags connected with an image with a given name :param server_address: address of a server with docker registry :param image_name: name of an image :return: list of tags connected with a given image In...
28,605
def build_graph(graph_attrs, meta_data, nodes, edges): """ Build the Graph with specific nodes and edges. :param graph_attrs: dictionary with graph attributes :param nodes: list of nodes where each node is tuple (node_name, type, attrs) nodes=[ ('input', 'Parameter'...
28,606
def test_run(s3_stubber, caplog, reset_unmatched): """ Test that the command updates the specified records (ignoring ones with errors). If `reset_unmatched` is False, the existing records not in the CSV are kept untouched, otherwise they are set to None. """ caplog.set_level('ERROR') new_on...
28,607
def test_get_status_api_down(mocker, connector): """ It should fail if the third-party api is down. """ mockreq = mocker.patch(f'{import_path}.requests') mockehttperror = mockreq.get mockehttperror.side_effect = HttpError assert connector.get_status().status is False
28,608
def cached_value(func: Callable[[], Any], path) -> Any: """ Tries to load data from the pickle file. If the file doesn't exist, the func() method is run and its results are saved into the file. Then the result is returned. """ if exists(path): with open(path, 'rb') as file: resu...
28,609
def copy_images(root_path): """Copy images. Will be done from images directory of subdirectories to images directory in the src directory """ subdir_list = [] # walk through the src directory to find subdirectories named 'images' # and copy contents to the 'images' directory in the duplicat...
28,610
def expensehistory(): """Show history of expenses or let the user update existing expense""" # User reached route via GET if request.method == "GET": # Get all of the users expense history ordered by submission time history = tendie_expenses.getHistory(session["user_id"]) # Get the...
28,611
def resize(a, new_shape): """resize(a,new_shape) returns a new array with the specified shape. The original array's total size can be any size. """ a = ravel(a) if not len(a): return zeros(new_shape, a.typecode()) total_size = multiply.reduce(new_shape) n_copies = int(total_size / len(a)) ...
28,612
def rotate180(image_np): """Rotates the given image by 180 degrees.""" if image_np is None: return None return np.fliplr(np.flipud(image_np))
28,613
def proxy_view(request, url, domain=None, secure=False, requests_args=None, template_name="proxy/debug.html"): """ Forward as close to an exact copy of the request as possible along to the given url. Respond with as close to an exact copy of the resulting response as possible. If there are any add...
28,614
def poll_for_staleness(id_or_elem, wait=10, frequency=1): """Use WebDriverWait with expected_conditions.staleness_of to wait for an element to be no longer attached to the DOM. :argument id_or_elem: The identifier of the element, or its element object. :argument wait: The amount of seconds to wait befor...
28,615
def configure_parser(parser): """Configure parser for this action """ qisys.parsers.worktree_parser(parser) qisys.parsers.project_parser(parser)
28,616
def test_extraplate(): """ Test basic stuff. """ a = np.array([np.nan, np.nan, 9, 9, 9, 9, 9, 2, 3, 9, 2, 1, 1, 3, 4, 9, 9, 9, np.nan, np.nan]) m = extrapolate(a) t = np.array([9, 9, 9, 9, 9, 9, 9, 2, 3, 9, 2, 1, 1, 3, 4, 9, 9, 9, 9, 9]) assert len(a) == len(m) assert np.allclose(m, t)
28,617
def check_y(y, allow_empty=False, allow_constant=True): """Validate input data. Parameters ---------- y : pd.Series allow_empty : bool, optional (default=False) If True, empty `y` raises an error. allow_constant : bool, optional (default=True) If True, constant `y` does not raise...
28,618
def show_disabled_locators(): """ Print in console enabled locators ordered by preference. :return: None """ enabled_locators_set = set(_get_enabled_locators_list()) complete_locators_set = set(config.DEFAULT_LOCATORS_PREFERENCE) disabled_locators_set = complete_locators_set - enabled_locators_...
28,619
def preprocess_features(features): """Row-normalize feature matrix and convert to tuple representation""" rowsum = np.array(features.sum(1), dtype=float) r_inv = np.power(rowsum, -1).flatten() r_inv[np.isinf(r_inv)] = 0. r_mat_inv = sp.diags(r_inv) features = r_mat_inv.dot(features) return s...
28,620
def CheckReachability(urls, http_client=None): """Check whether the hosts of given urls are reachable. Args: urls: iterable(str), The list of urls to check connection to. http_client: httplib2.Http, an object used by gcloud to make http and https connections. Defaults to an non-authenticated Http obj...
28,621
def dataset_prediction_results(dataset, event, model_factory_fn=pohmm_factory, min_history=90, max_history=None, out_name=None): """ Obtain predictions for each model. Create stratified folds Train on 1-n_folds. Use the last fold to make predictions for each event """...
28,622
def num(value): """Parse number as float or int.""" value_float = float(value) try: value_int = int(value) except ValueError: return value_float return value_int if value_int == value_float else value_float
28,623
def __ensure_testcase_module(path: Text) -> NoReturn: """ ensure pytest files are in python module, generate __init__.py on demand """ init_file = os.path.join(os.path.dirname(path), "__init__.py") if os.path.isfile(init_file): return with open(init_file, "w", encoding="utf-8") as f: ...
28,624
def __format_event_start_date_and_time(t): """Formats datetime into e.g. Tue Jul 30 at 5PM""" strftime_format = "%a %b %-d at %-I:%M %p" return t.strftime(strftime_format)
28,625
def collect_properties(service_instance, view_ref, obj_type, path_set=None, include_mors=False): """ Collect properties for managed objects from a view ref Check the vSphere API documentation for example on retrieving object properties: - http://goo.gl/erbFDz Args: ...
28,626
def to_all_gpus( cpu_index: faiss.Index, co: Optional['faiss.GpuMultipleClonerOptions'] = None ) -> faiss.Index: """ TODO: docstring """ n_gpus = faiss.get_num_gpus() assert n_gpus != 0, 'Attempting to move index to GPU without any GPUs' gpu_index = faiss.index_cpu_to_all_gpus(cpu_ind...
28,627
def parse_template_mapping( template_mapping: List[str] ) -> MutableMapping[str, str]: """Parses a string template map from <key>=<value> strings.""" result = {} for mapping in template_mapping: key, value = mapping.split("=", 1) result[key] = value return result
28,628
def _AllDirsToRoot(dir): """Return all parent paths of a directory.""" dir = os.path.abspath(dir) while True: yield dir parent = os.path.dirname(dir) if parent == "" or parent == dir: break dir = parent
28,629
def isGZ(fn): """ Tests whether a file is gz-compressed. :param fn: a filename :type fn: str :returns: True if fn is gz-compressed otherwise False """ assert os.path.exists(fn) with open(fn, 'rb') as fi: b1, b2 = fi.read(1), fi.read(1) return b1 == b'\x1f' and b2 == b'\...
28,630
def select_dim_over_nm(max_n, max_m, d, coef_nd, coef_md, coef_nm, coef_n, coef_m, rest, max_mem): """Finds the optimal values for `n` and `m` to fit in available memory. This function should be called for problems where the GPU needs to hold two blocks of data (one of size m, one of size n) and one kernel...
28,631
def _file_extension(filename): """Return file extension without the dot""" # openbabel expects the extension without the dot, but os.path.splitext # returns the extension with it dotext = os.path.splitext(filename)[1] return dotext[1:]
28,632
def atomic_tmp_file(final_path): """Return a tmp file name to use with atomic_install. This will be in the same directory as final_path. The temporary file will have the same extension as finalPath. It the final path is in /dev (/dev/null, /dev/stdout), it is returned unchanged and atomic_tmp_install ...
28,633
def hzAnalyticDipoleF(r, freq, sigma, secondary=True, mu=mu_0): """ 4.56 in Ward and Hohmann .. plot:: import matplotlib.pyplot as plt from SimPEG import EM freq = np.logspace(-1, 6, 61) test = EM.Analytics.FDEM.hzAnalyticDipoleF(100, freq, 0.001, secondary=False) p...
28,634
def dockerCall(job, tool, parameters=None, workDir=None, dockerParameters=None, outfile=None, defer=None): """ Throws CalledProcessorError if the Docker invocation returns a non-zero exit code This function blocks unti...
28,635
def test_generate_signature(): """Test we can get correct signature.""" data = signature.generate_signature('test_key', 'test_msg') assert data == b'TC9wro8movj4HGMphrpEdES3oBdPsq+y+2tAt6kM/Tw='
28,636
def test_parse_date(): """ Check that the date is parsed correctly, and that the output types are string. """ year, month, day = standardcitations.parse_date("1982-06-23") assert year == "1982" assert day == "23" assert month == "6"
28,637
def _compute_net_budget(recarray, zonenamedict): """ :param recarray: :param zonenamedict: :return: """ recnames = _get_record_names(recarray) innames = [ n for n in recnames if n.startswith("FROM_") or n.endswith("_IN") ] outnames = [ n for n in recnames...
28,638
def check_thrown_events_histogram(thrown_events_hist1, thrown_events_hist2): """ Check that two ThrownEventsHistogram class are compatible with each other Parameters ---------- thrown_events_hist1: `lstchain.io.lstcontainers.ThrownEventsHistogram` thrown_events_hist2: `lstchain.io.lstcontainers...
28,639
def CheckAllNonHistoricalVariables(model_part): """Check the consistency of all non-historical variables.""" for variable in GetHistoricalVariableList(model_part, model_part.Nodes): debug_utilities.ChecknonHistoricalVariable(model_part, model_part.Nodes, variable) for variable in GetHistoricalVaria...
28,640
def bg_white(msg): """ return msg with a white background """ return __apply_style(__background_colors['white'],msg)
28,641
def read_image_from_s3(bucket_name, key): """S3 to PIL Image""" s3 = boto3.resource('s3') bucket = s3.Bucket(bucket_name) object = bucket.Object(key) response = object.get() return Image.open(response['Body'])
28,642
def count_indra_apis(graph: BELGraph) -> typing.Counter[str]: """Count the APIs reported by INDRA.""" return Counter( api for _, _, d in graph.edges(data=True) if ANNOTATIONS in d and 'INDRA_API' in d[ANNOTATIONS] for api in d[ANNOTATIONS]['INDRA_API'] if api and isinstan...
28,643
def integrate_sed(wavelength, flambda, wlmin=None, wlmax=None): """ Calculate the flux in an SED by direct integration. A direct trapezoidal rule integration is carried out on the flambda values and the associated wavelength values. Parameters ---------- wavelength: A numpy float arr...
28,644
def unpack_unknowns(segment): """Unpacks the unknowns set in the mission to be available for the mission. Assumptions: N/A Source: N/A Inputs: segment.state.unknowns.throttle [Unitless] segment.state.unknowns.body_angle [Radians] segment.state.unknowns.fli...
28,645
def computeMSSIM(groundTruth, recovered): """ Compute Mean Structural SImilarity Measure (MSSIM) between the recovered and the corresponding ground-truth image Args: :param groundTruth: ground truth reference image. numpy.ndarray (Height x Width x Spectral_Dimension) :param ...
28,646
def get_integrations_from_cache(ctx, python, bucket, branch, integrations_dir, target_dir, integrations, awscli="aws"): """ Get cached integration wheels for given integrations. python: Python version to retrieve integrations for bucket: S3 bucket to retrieve integration wheels from branch: namespac...
28,647
def full_n_graphs(n_reps=3, full=False): """ Test varying the number of input graphs. """ varied_param = 'n_input_graphs' p = {} p[varied_param] = [2, 3, 4, 5, 6, 7] p['duplicates'] = 5 p['density_multiplier'] = 1.5 p['p_keep_edge'] = 0.7 p['g'] = 0.5 p['f'] = 2 p['gap_co...
28,648
def test_cache_memoize_ttl(cache, timer): """Test that cache.memoize() can set a TTL.""" ttl1 = 5 ttl2 = ttl1 + 1 @cache.memoize(ttl=ttl1) def func1(a): return a @cache.memoize(ttl=ttl2) def func2(a): return a func1(1) func2(1) assert len(cache) == 2 key1,...
28,649
def build_param_structure(params, target, value, index=None): """ This method provides a basic reverse JMESPath implementation that lets you go from a JMESPath-like string to a possibly deeply nested object. The ``params`` are mutated in-place, so subsequent calls can modify the same element by its ...
28,650
def queues(request): """ We get here from /queues """ return render("queues.html", request, { "queuelist" : request.jt.queues()})
28,651
def shorten_str(string, length=30, end=10): """Shorten a string to the given length.""" if string is None: return "" if len(string) <= length: return string else: return "{}...{}".format(string[:length - end], string[- end:])
28,652
def A2cell(A): """Compute unit cell constants from A :param A: [G11,G22,G33,2*G12,2*G13,2*G23] G - reciprocal metric tensor :return: a,b,c,alpha, beta, gamma (degrees) - lattice parameters """ G,g = A2Gmat(A) return Gmat2cell(g)
28,653
def main(): """Demonstration main function that you can run just to see what it does with a few phrases.""" logging.basicConfig(level=logging.INFO) rrc_classifier = RRCLanguageClassifier.default_instance() texts = ["This is English", "Esto es español"] for text in texts: winner = rrc_classi...
28,654
def update_user_post( slug: str, post: schemas.PostCreate, db: Session = Depends(get_db), current_user: schemas.User = Depends(get_current_active_user), ) -> Any: """ Update a user Post if its owner """ post_data = get_post(db, slug) if post_data is None: raise HTTPException(...
28,655
def loadNetParameter(caffemodel): """ Return a NetParameter protocol buffer loaded from the caffemodel. """ from backend.caffe.path_loader import PathLoader proto = PathLoader().importProto() net = proto.NetParameter() try: with open(caffemodel, 'rb') as f: net.ParseFromStri...
28,656
def extract_keywords(header, *args): """ For a given header, find all of the keys and return an unnested dict. """ try: header = pvl.load(header) except: header = pvl.loads(header) res = {} # Iterate through all of the requested keys for a in args: try: ...
28,657
def plot_parcel_stats_profile(fnames, figure="save", fmt="png", **kwargs): """ Plot parcel statistics """ n = len(fnames) labels = kwargs.pop("labels", n * [None]) dset = kwargs.pop("dset", "aspect-ratio") no_xlabel = kwargs.pop("no_xlabel", False) beg = kwargs.pop("begin", None) en...
28,658
def dot(p, q): """ Compute dot product between two 3D vectors p: array Cartesian coordinates for one of the vectors q: array Cartesian coordinates for one of the vectors """ return p[0] * q[0] + p[1] * q[1] + p[2] * q[2]
28,659
def cl_do_all(command, workdirs): """Run the same command line argument from each working directory""" for workdir in workdirs: os.system("( cd %s ; %s)" % (workdir, command))
28,660
def color_code_MGS_image(T_id,data,img_path,output_path): """Function to visualize the MGS of a given image by color coding labelled images Parameters: T_id: Tissue id/Name of the image data: grouped dataframe that contains the centroid and MGS of nuclei img_path: pa...
28,661
def test_command_line_interface(): """Test the CLI.""" runner = CliRunner() result = runner.invoke(cli.main) assert result.exit_code == 0 assert "lazypredict.cli.main" in result.output help_result = runner.invoke(cli.main, ["--help"]) assert help_result.exit_code == 0 assert "--help Sho...
28,662
def create(protocol, host, port, objname): """ Sets up an environment through which the program can be re-invoked by itself. In this new environment, the output will be the username and password stored in the keyring for the specified server. Refer to `credentials.keyring` for what the arguments me...
28,663
def install_completion(ctx, attr, value): # pragma: no cover """Install completion for the current shell.""" import click_completion.core if not value or ctx.resilient_parsing: return value shell, path = click_completion.core.install() click.secho("{0} completion installed in {1}".format(...
28,664
def _extractSetsSingleUser(df, time_window): """Get activity set and trip set for each individual.""" # total weeks and start week weeks = (df["endt"].max() - df["startt"].min()).days // 7 start_date = df["startt"].min().date() aSet = pd.DataFrame([], columns=["userid", "locid", "dur_s", "class", "...
28,665
def _ed25519(): """Edwards curve Ed25519. Link: https://en.wikipedia.org/wiki/EdDSA#Ed25519 """ q = 2 ** 255 - 19 order = 2 ** 252 + 27742317777372353535851937790883648493 gf = GF(q) ed = CurveParams(name="ED25519", order=order, gf=gf, is_cyclic = True) ed.set_constants(a=gf(-1...
28,666
def from_raw_bytes(raw_bytes): """Take raw bytes and turn it into a DmailRequest""" return from_json(json.loads(raw_bytes.decode(encoding='UTF-8')))
28,667
def show_evaluation_cli( configuration: Configuration, number: int, verbosity: str, ): """Show past evaluation.""" try: evaluation = configuration.cache.get_evaluation(number - 1) except CacheError: click.echo( failure_style(f"Could not find evaluation with given inde...
28,668
def BRepApprox_TheMultiLineToolOfApprox_FirstPoint(*args): """ :param ML: :type ML: BRepApprox_TheMultiLineOfApprox & :rtype: int """ return _BRepApprox.BRepApprox_TheMultiLineToolOfApprox_FirstPoint(*args)
28,669
def push_message(token, user, message, **kwargs): """ Send message to selected user/group/device. :param str token: application token :param str user: user or group id to send the message to :param str message: your message :param str title: your message's title, otherwise your app's name is us...
28,670
def _rrv_div_ ( s , o ) : """Division of RooRealVar and ``number'' >>> var = ... >>> num = ... >>> res = var / num """ if isinstance ( o , _RRV_ ) and not o.isConstant() : o = o.ve () elif hasattr ( o , 'getVal' ) : o = o.getVal () # v = ...
28,671
def getWindowsAt(x: int, y: int, app: AppKit.NSApplication = None, allWindows=None): """ Get the list of Window objects whose windows contain the point ``(x, y)`` on screen :param x: X screen coordinate of the window(s) :param y: Y screen coordinate of the window(s) :param app: (optional) NSApp() o...
28,672
def find_closest_vertices(surface_coords, point_coords): """Return the vertices on a surface mesh closest to some given coordinates. The distance metric used is Euclidian distance. Parameters ---------- surface_coords : numpy array Array of coordinates on a surface mesh point_coords : ...
28,673
def blob_utils_get_loss_gradients(model, loss_blobs): """Generate a gradient of 1 for each loss specified in 'loss_blobs'""" loss_gradients = {} for b in loss_blobs: loss_grad = model.net.ConstantFill(b, [b + '_grad'], value=1.0) loss_gradients[str(b)] = str(loss_grad) return loss_gradie...
28,674
def _list_indexing(X, key, key_dtype): """ Index a Python list """ if np.isscalar(key) or isinstance(key, slice): # key is a slice or a scalar return X[key] if key_dtype == 'bool': # key is a boolean array-like return list(compress(X, key)) # key is a integer array-like o...
28,675
def extract_hubs_from_motifs(list_of_motifs: list, genes_to_remove: list, check_conflict: bool = True, debug: bool = False, gene_ids_file: str = None, top_pc: float = 1.): ...
28,676
def credit_rating(): """ credit_rating http api """ return_dict = {'rescode': '200', 'credit-rating': '1', 'description': 'Good credit'} if request.get_data() is None: return_dict['rescode'] = '5004' return json.dumps(return_dict, ensure_ascii=False) role_dict = {'farm...
28,677
def updateGlobalInventory(D_SKUs: pd.DataFrame, inventoryColumn: str): """ Update the global inventory of the warehouse Args: D_SKUs (pd.DataFrame): Input SKUs dataframe. inventoryColumn (str): column name with the inventory. Returns: D_inventory (pd.DataFrame): Output DataFram...
28,678
def generate_code(): """ This method reads the template file, fills it with the appropriate contents, and writes the result in the mini_lambda_generated.py file. All contents of the destination file are overriden by this operation. :return: """ # (1) generate the to-do list for the first templa...
28,679
def _query_checks(start, end, owner_id=''): """Get the number of rules checks from `start` to `end` in 1-day windows""" series = [] assert (isinstance(end, datetime.datetime) and isinstance(start, datetime.datetime)) while start < end: stop = start + datetime.timedelta(days=1) ...
28,680
def _FilterManufacturedEvents(results): """Return a list of results where first question is 'MANUFACTURED'. Manufactured events are either Recording events that correspond to an instrumented event in the browser, or Showed notification events that correspond to when the user was invited to take a survey. Ar...
28,681
def test_naive_fusion_2d_with_overlaps() -> None: """Test naive fusion with really overlaping points in 2d that need to be marked.""" n_rays = 20 s = 8 shape = (s, s) dists = np.zeros(shape + (n_rays,)) probs = np.zeros(shape) # object 1 z0 = s // 4 dist = 3 dists[z0, z0, :] = ...
28,682
def setup(client): """ Adds the command to the client object """ client.add_cog(Ping(client)) print("\tLoaded Ping cog!")
28,683
def get_bgp(host, username, password) -> None: """Gets device BGP configuration""" session = create_netconf_connection(host, username, password) config_data = session.get(get_policies) qos_details = xmltodict.parse(config_data.xml)["rpc-reply"]["data"] bgp_details = qos_details["native"].get(...
28,684
def pca_loadings_bar(axi, coefficients, xvars, plot_type='bar'): """Plot the loadings for a single component in a bar plot. Parameters ---------- axi : object like :class:`matplotlib.axes.Axes` The plot we will add the loadings to. coefficients : object like :class:`numpy.ndarray` T...
28,685
def Max(data): """Returns the maximum value of a time series""" return data.max()
28,686
def write_qif_orders(app_ui, orders, qif_file): """Write orders to a .qif file.""" for order_id in sorted(orders): order = orders[order_id] print("D{}".format(order.order_date), file=qif_file) print("POpenSky order {}".format(order_id), file=qif_file) print("L{}".format(app_ui.ar...
28,687
def mcf_and(modal_context, fml, clausal_form_dict, id_mc, distributive): """ Takes AND fml, and applies transformation rules. """ global max_mc_id left_fml = fml[1] right_fml = fml[2] max_mc_id = max(id_mc, max_mc_id) # if modal context distributes over the 'and' operator if not distri...
28,688
def clean_words(words, remove_stopwords=False, language='portuguese'): """Stems and removes stopwords from a set of word-level tokens using the RSLPStemmer. Args: words (list): Tokens to be stemmed. remove_stopwords (bool): Whether stopwords should be removed or not. language (str): Ide...
28,689
def prompt_input(message: str): """ Prompt user for input.""" while True: try: num = input(message+':\n') if num==stop_word: print(f'Max: {max(nums)} Min: {min(nums)}') else: nums.append(int(num)) continue except...
28,690
def load_model(model_dir, model_file=None): """Loads the model. The model object is pickled in `model_dir` to make the model configuration optional for future runs. Args: model_dir: The model directory. model_file: An optional model configuration. Returns: A `opennmt.models.Model` object. """...
28,691
def generate(args): """ Generate snapshot of sources of kernel functions. This involves: - find source code with functions definitions - compile the source codes into LLVM IR - copy LLVM and C source files into snapshot directory - create YAML with list mapping functions to their LLV...
28,692
def parse_healing_and_target(line): """Helper method that finds the amount of healing and who it was provided to""" split_line = line.split() target = ' '.join(split_line[3:split_line.index('for')]) target = target.replace('the ', '') amount = int(split_line[split_line.index('for')+1]) return...
28,693
def trim_os_hidden_files(abs_path): """trim os hidden files and folder like: .DS_Store, """ pass
28,694
def _decode_and_center_crop( image_bytes: tf.Tensor, jpeg_shape: Optional[tf.Tensor] = None, image_size: Sequence[int] = (224, 224), ) -> tf.Tensor: """Crops to center of image with padding then scales.""" if jpeg_shape is None: jpeg_shape = get_shape(image_bytes) image_height = jpeg_shape[0] im...
28,695
def print_stat(test_list, stat_dict): """ """ for t_name in test_list: print('| {}: MRE: {:.4f} SDR: {:.4f} SCR: {:.4f}'.format( t_name, stat_dict[t_name]['MRE']['average'].cpu().numpy(), stat_dict[t_name]['SDR'][20]['average'].cpu().numpy(), stat_dict[t_name]['SCR'].cpu().mean(), ...
28,696
def inq_affine(inp, n_outmaps, base_axis=1, num_bits=4, inq_iterations=(), selection_algorithm='random', seed=-1, w_init=None, i_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True): """Incremental Network Quantization Affine Layer During training...
28,697
def is_greater_equal(min_value): """Check if the attribute value is greater than or equal to a minimum value. This validator can handle both lists and single element attributes. If it is a list, it checks if the element with the smallest value is greater than or equal to the specified minimum value. ...
28,698
def save_lyrics(list_: List[Text], location: Text) -> None: """Writes 'list_' to 'location' as txt file. Returns None.""" with open(location, "w+") as f: for element in list_: f.write(element) f.write("\n") return None
28,699