content
stringlengths
22
815k
id
int64
0
4.91M
def _transpose_list_array(x): """Transposes a list matrix """ n_dims = len(x) assert n_dims > 0 n_samples = len(x[0]) rows = [None] * n_samples for i in range(n_samples): r = [None] * n_dims for j in range(n_dims): r[j] = x[j][i] rows[i] = r return ro...
21,700
def load_businessgroup(request): """ Business Group Dependent/Chained Dropdown List """ business_type_id = request.GET.get('business_type') business_group_list = BusinessGroup.objects.filter( business_type_id=business_type_id).order_by('name') context = {'business_group_list': business_group_li...
21,701
def seed_normalization(train_X, train_Y, test_X, testY, nor_method=0, merge=0, column=0): """ 0 for minmax 1 for standard, 2 for nothing :param nor_method: :param merge:是否训练集测试集一起归一化 :return: """ # imp_mean = SimpleImputer(missing_values=np.nan, strategy="mean") imp_mean = KNNImputer(n_n...
21,702
def combine_matrix_runs(path, runs, pacc_file): """Combine a set of transition matrix files. Args: path: The base path containing the data to combine. runs: The list of runs to combine. pacc_file: The name of the file to combine. Returns: A TransitionMatrix object ...
21,703
def submit_tweet_with_media(message, mediafile, tweet_to_reply=None, handle=None): """ imfile is the path to an media tweet_to_reply is a tweet that you're replying to, if not None """ if not handle: handle = twitter_handle() media_ids = handle.upload_media(media=open(mediafile)) if ...
21,704
def get_pkg_descr(package, version=None, last_modified=None): """ Get package description from registry """ json_data = fetch_page('http://registry.npmjs.org/%s' % package, last_modified=last_modified) if json_data is None: # NB: empty string is not None but will fail the check return N...
21,705
def has_pattern(str_or_strlist): """When passed a string, equivalent to calling looks_like_pattern. When passed a string list, returns True if any one of the strings looks like a pattern, False otherwise.""" strlist = [str_or_strlist] if isinstance(str_or_strlist, str) else str_or_strlist retu...
21,706
def update_hidden_area(*args): """update_hidden_area(hidden_area_t ha) -> bool""" return _idaapi.update_hidden_area(*args)
21,707
def after_update_forecast_datasets(msg, config, checklist): """Calculate the list of workers to launch after the update_forecast_datasets worker ends. :arg msg: Nowcast system message. :type msg: :py:class:`nemo_nowcast.message.Message` :arg config: :py:class:`dict`-like object that holds the nowc...
21,708
def index(request): """Homepage for this app. """ with open('index.html') as fp: return HttpResponse(fp.read())
21,709
def SECH(*args) -> Function: """ The SECH function returns the hyperbolic secant of an angle. Learn more: https//support.google.com/docs/answer/9116560 """ return Function("SECH", args)
21,710
def read_ATAC_10x(matrix, cell_names='', var_names='', path_file=''): """ Load sparse matrix (including matrices corresponding to 10x data) as AnnData objects. read the mtx file, tsv file coresponding to cell_names and the bed file containing the variable names Parameters ---------- matrix: spa...
21,711
def print_header(): """ Prints header for app :return: """ print('-------------------------------------------') print(' Weather APP') print('-------------------------------------------') print()
21,712
def _resolve_placeholder(placeholder, original): """Resolve a placeholder to the given original object. :param placeholder: The placeholder to resolve, in place. :type placeholder: dict :param original: The object that the placeholder represents. :type original: dict """ new = copy.deepcopy...
21,713
def get_html_subsection(name): """ Return a subsection as HTML, with the given name :param name: subsection name :type name: str :rtype: str """ return "<h2>{}</h2>".format(name)
21,714
def test_load_pandas_df( size, num_samples, num_movies, movie_example, title_example, genres_example, year_example, tmp, ): """Test MovieLens dataset load as pd.DataFrame""" # Test if correct data are loaded header = ["a", "b", "c"] df = load_pandas_df(size=size, local_ca...
21,715
def compute_norms(items): """ Compute the norms of the item vectors provided. Arguments: items -- a hashmap which maps itemIDs to the characteristic vectors """ norms = {} for item in items: norms[item] = np.sqrt(np.sum(np.square(items[item]))) ...
21,716
def check_cert_path(path): """Pass.""" build_path = path.parent / "build_certs.py" if not path.is_file(): error = "Cert {path!r} does not exist, run {build_path!r}" error = error.format(path=format(path), build_path=format(build_path)) raise Exception(error)
21,717
def do_part_1(): """ Solves part 1 """ digested_lines = list(map(digest_line, input_lines(2))) # Poor man's partial doubles = sum(map(lambda l: contains_nple(l, reps=2), digested_lines)) triples = sum(map(lambda l: contains_nple(l, reps=3), digested_lines)) print(doubles * triples) r...
21,718
def create_Rz_batch(a): """ Creates a batch of rotation matrices about z of angles a. Input (batch) Output (batch, 3, 3) """ return torch.stack([ torch.stack([torch.cos(a), torch.sin(a), torch.zeros_like(a)], dim=1), t...
21,719
def get_upsample_filter(size): """Make a 2D bilinear kernel suitable for upsampling""" factor = (size + 1) // 2 if size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = np.ogrid[:size, :size] filter = (1 - abs(og[0] - center) / factor) * \ (1 - abs(og[1...
21,720
def lst2gmst(longitude, hour, minute=None, second=None, longitudeDirection='W', longitudeUnits='DEGREES'): """ Converts Local Sidereal Time to Greenwich Mean Sidereal Time. Parameters ---------- longitude : float (any numeric type) ...
21,721
def find_components(package, base_class): """Find components which are subclass of a given base class. """ for filename in resource_listdir(package, ''): basename, extension = os.path.splitext(filename) if extension != '.py' or basename.startswith('.'): continue module_na...
21,722
def main(): """run this by default""" bigfix_cli = bescli.bescli.BESCLInterface() bigfix_cli.do_conf() # generate MSI uninstallers # use session relevance to get the name of the property to get the values from: property_name = bigfix_cli.bes_conn.session_relevance_array( 'unique value of...
21,723
def filter_funcs(node) -> bool: """Filter to get functions names and remove dunder names""" if not isinstance(node, ast.FunctionDef): return False elif node.name.startswith('__') or node.name.endswith('__'): return False else: return True
21,724
def test_disabled_enable_debug() -> None: """Check that enable_debug=False works.""" tc.assertTrue( is_file_exists(get_absolute_from_current_path(__file__, "0001.png")) ) copy_file( get_absolute_from_current_path(__file__, "0001.png"), get_absolute_from_current_path(__file__, "00...
21,725
def main(): """ Load the list of valid country codes and create output for each country. Two output files and one plot are created for each country. """ with open(DATA_FOLDER+COUNTRY_CODES, "r") as infile: infile.readline() info = [(int(_l.split("\t")[0]), _l.split("\t")[3]) for _l ...
21,726
def attach(address, log_dir=None, multiprocess=True): """Starts a DAP (Debug Adapter Protocol) server in this process, and connects it to the IDE that is listening for an incoming connection on a socket with the specified address. address must be a (host, port) tuple, as defined by the standard ...
21,727
def create_api_token( creator_id: UserID, permissions: set[PermissionID], *, description: Optional[str] = None, ) -> ApiToken: """Create an API token.""" num_bytes = 40 token = token_urlsafe(num_bytes) db_api_token = DbApiToken( creator_id, token, permissions, description=descri...
21,728
def parse_arguments(): """Parse command line arguments.""" parser = argparse.ArgumentParser(description="Update OCFL inventory sidecar file", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("path", type=str, nargs="*", ...
21,729
def match_image_widths( image_i1: Image, image_i2: Image ) -> Tuple[Image, Image, Tuple[float, float], Tuple[float, float]]: """Automatically chooses the target width (larger of the two inputs), and scales both images to that width. Args: image_i1: 1st image to match width. image_i2: 2...
21,730
def get_parameter_value_and_validate_return_type( domain: Optional[Domain] = None, parameter_reference: Optional[Union[Any, str]] = None, expected_return_type: Optional[Union[type, tuple]] = None, variables: Optional[ParameterContainer] = None, parameters: Optional[Dict[str, ParameterContainer]] = N...
21,731
def diff_tags(list_a, list_b): """ Return human readable diff string of tags changed between two tag lists :param list_a: Original tag list :param list_b: New tag list :return: Difference string """ status_str = text_type("") tags_added = [tag for tag in list_b if tag not in list_a] ...
21,732
def distance_on_great_circle(start_point, direction, distance): """compute the location of a point a specified distance along a great circle NOTE: This assumes a spherical earth. The error introduced in the location is pretty small (~15 km for a 13000 km path), but it totall screws with the altitude. Y...
21,733
def bigo(): """ User inputs corresponding Big O of randomly generated expression """ # Init algorithm 1 a1 = randint(0, 2) if (a1 == 0): a1 = Expression(terms=3) else : a1 = return_rterm() # Question user print(f"\nGive the corresponding Big O of {a1}.") user_inp = str(input("\nIn...
21,734
def test_extra_kwargs_error(): """Test that unrecognized kwargs gives a FutureWarning.""" with pytest.raises(TypeError) as wrn: widgets.Label(unknown_kwarg="hi") assert "unexpected keyword argument" in str(wrn)
21,735
def construct_tree_framework(bracket): """Given the tree in bracket form, creates a tree with labeled leaves and unlabeled inner nodes.""" if type(bracket)==int: #base case, creates leaf return Node(tree) else: #recursive step, inner nodes root = Node(None, construct_tree_framework(brac...
21,736
def eckart_transform(atommasses, atomcoords): """Compute the Eckart transform. This transform is described in https://gaussian.com/vib/. Parameters ---------- atommasses : array-like Atomic masses in atomic mass units (amu). atomcoords : array-like Atomic coordinates. Retu...
21,737
def plot_rdkit(mol, filename=None): """ Plots an RDKit molecule in Matplotlib :param mol: an RDKit molecule :param filename: save the image with the given filename :return: """ if rdc is None: raise ImportError('`draw_rdkit_mol` requires RDkit.') if filename is not None: ...
21,738
def as_java_array(gateway, java_type, iterable): """Creates a Java array from a Python iterable, using the given p4yj gateway""" java_type = gateway.jvm.__getattr__(java_type) lst = list(iterable) arr = gateway.new_array(java_type, len(lst)) for i, e in enumerate(lst): jobj = as_java_objec...
21,739
def match(a: np.ndarray, b: np.ndarray) -> np.ndarray: """Finds the matrix R that minimizes the frobenius norm of RA - B, where R is orthonormal. Args: a (np.ndarray[samples, features]): the first matrix to match b (np.ndarray[samples, features]): the second matrix to match Ret...
21,740
def macro_cons_silver_amount(): """ 全球最大白银ETF--iShares Silver Trust持仓报告, 数据区间从20060429-至今 :return: pandas.Series 2006-04-29 263651152 2006-05-02 263651152 2006-05-03 445408550 2006-05-04 555123947 2006-05-05 574713264 ... 2019-10-17 Show All ...
21,741
def shuffle(answers): """ Returns mixed answers and the index of the correct one, assuming the first answer is the correct one. """ indices = list(range(len(answers))) random.shuffle(indices) correct = indices.index(0) answers = [answers[i] for i in indices] return answers, correct
21,742
def annotations_to_xml(annotations_df: pd.DataFrame, image_path: Union[str, Path], write_file=True) -> str: """ Load annotations from dataframe (retinanet output format) and convert them into xml format (e.g. RectLabel editor / LabelImg). Args: annotations_df (DataFrame): ...
21,743
def depth(sequence, func=max, _depth=0): """ Find the nesting depth of a nested sequence """ if isinstance(sequence, dict): sequence = list(sequence.values()) depth_list = [ depth(item, func=func, _depth=_depth + 1) for item in sequence if (isinstance(item, dict) or u...
21,744
def tei_email(elem_text): """ create TEI element <email> with given element text """ email = etree.Element("email") email.text = elem_text return email
21,745
def rebuild(request): """Rebuild ``XPI`` file. It can be provided as POST['location'] :returns: (JSON) contains one field - hashtag it is later used to download the xpi using :meth:`xpi.views.check_download` and :meth:`xpi.views.get_download` """ # validate entries secre...
21,746
def get_requirements(req_file: str) -> List[str]: """ Extract requirements from provided file. """ req_path = Path(req_file) requirements = req_path.read_text().split("\n") if req_path.exists() else [] return requirements
21,747
def _generate_ngram_contexts(ngram: str) -> 'List[Acronym]': """ Generate a list of contextualized n-grams with a decreasing central n-gram and increasing \ lateral context. :param ngram: :return: """ tokens = ngram.split(" ") ngram_size = len(tokens) contexts = [] # Walk only...
21,748
def get_gmail_account(slug): """ Return the details of the given account - just pass in the slug e.g. get_account('testcity') """ service = get_gapps_client() if not service: return None try: return service.users().get(userKey=make_email(slug)).execute() except HttpError...
21,749
def _estimate_components(data, xdata): """Not implemented.""" raise NotImplementedError
21,750
def unisolate_machine_command(): """Undo isolation of a machine. Returns: (str, dict, dict). Human readable, context, raw response """ headers = ['ID', 'Type', 'Requestor', 'RequestorComment', 'Status', 'MachineID', 'ComputerDNSName'] machine_id = demisto.args().get('machine_id') commen...
21,751
def func(*listItems): """ 1、遍历所有的列表元素 2、遍历所有的列表元素里面的所有元素放进去一个列表里面 3、排序这个列表,返回最大的那个元素 """ tmp_list=[] for item in listItems: if isinstance(item,list): for i in item: tmp_list.append(i) tmp_list=list(filter(lambda k:isinstance(k,int),tmp_list)) tmp...
21,752
def factory(name: str): """Factory function to return a processing function for Part of Speech tagging. Parameters: ----------- name : str Identifier, e.g. 'spacy-de', 'stanza-de', 'flair-de', 'someweta-de', 'someweta-web-de' Example: -------- import nlptasks ...
21,753
def backoff_handler(debug_only=True): """Backoff logging handler for when polling occurs. Args: details (dict): Backoff context containing the number of tries, target function currently executing, kwargs, args, value, and wait time. """ def _wrapped(details): mes...
21,754
def align_dataframes(framea, frameb, fill_value = 0.0): """Use pandas DataFrame structure to align two-dimensional data :param framea: First pandas dataframe to align :param frameb: Other pandas dataframe to align :param fill_value: default fill value (0.0 float) return: tuple of aligned frames ...
21,755
def flip_ud(img): """ Expects shape to be (num_examples, modalities, depth, width, height) """ return np.flip(img.copy(), 3)
21,756
def download_facescrub((data_dir, genders, names, urls, bboxes)): """ download from urls into folder names using wget """ assert(len(names) == len(urls)) assert(len(names) == len(bboxes)) # download using external wget CMD = 'wget -c -t 1 -T 3 "%s" -O "%s"' for i in range(len(names)...
21,757
def data_context_service_interface_pointuuid_otsi_service_interface_point_spec_otsi_capability_get(uuid): # noqa: E501 """data_context_service_interface_pointuuid_otsi_service_interface_point_spec_otsi_capability_get returns tapi.photonic.media.OtsiCapabilityPac # noqa: E501 :param uuid: Id of service-in...
21,758
def test_select_all_columns(): """Validate select returning all columns using '*' (the default).""" _logger.debug(stack()[0][3]) config = deepcopy(_CONFIG) t = table(config) data = t.select(container='tuple') assert len(data[0]) == len(t.columns())
21,759
def _get_trial_event_times(events, units, trial_cond_name): """ Get median event start times from all unit-trials from the specified "trial_cond_name" and "units" - aligned to GO CUE :param events: list of events """ events = list(events) + ['go'] event_types, event_times = (psth.TrialCondition...
21,760
def is_path_exists_or_creatable(pathname=None): """ `True` if the passed pathname is a valid pathname for the current OS _and_ either currently exists or is hypothetically creatable; `False` otherwise. This function is guaranteed to _never_ raise exceptions. """ try: # To prevent "os" m...
21,761
def set_virtualenv_prefix(prefix_tuple): """ :return: Sets the virtualenv prefix given a tuple returned from get_virtualenv_prefix() """ if prefix_tuple[0] == 'sys.real_prefix' and hasattr(sys, 'real_prefix'): sys.real_prefix = prefix_tuple[1] elif prefix_tuple[0] == 'sys.base_prefix' and ha...
21,762
def draw_point(framebuffer, x, y, color): """ Draw a single pixel of given color at the specified coordinates. :param framebuffer: An instance of the framebuffer class. :param int x: The X-coordinate. :param int y: The Y-coordinate. :param color: An instance of the color class. """ ...
21,763
def select_region(selections, positions, region): """ selection in region from selections """ if not region: return selections region = list(region) + [None, None] assert all([x is None or isinstance(x, Iterable) and len(x) == 2 for x in region]), 'region should be collec...
21,764
def summarize_center_and_dispersion( analysis_layer, summarize_type=["CentralFeature"], ellipse_size=None, weight_field=None, group_field=None, output_name=None, context=None, gis=None, estimate=False, future=False): """ .. image::...
21,765
def rename_channel(channel_id, old_name, new_name): """Renames channel folders and updates channel.json""" channel_list_path = archive_path / "channels.json" with open(channel_list_path, 'r+') as channel_list: old_channel_list = json.load(channel_list) channel = next((ch for ch in old_channel_list if ch['id'] =...
21,766
def length_entropy(r: np.ndarray, minlen: int = 2) -> float: """Calculate entropy of diagonal lengths in RQ matrix. Args: r (np.ndarray[bool, bool]): Recurrence matrix minlen (int): Minimum length of a line Returns: float: Shannon entropy of distribution of segment lengths """ ...
21,767
def verify_scholarship_chair(user): """ Verify user has Scholarship Chair permissions """ user_id = user.brother.id if Position.objects.filter(title='President')[0].brother.id == user_id or \ Position.objects.filter(title='Scholarship Chair')[0].brother.id == user_id or \ debug: ...
21,768
def float_range(start=0, stop=None, step=1): """ Much like the built-in function range, but accepts floats >>> tuple(float_range(0, 9, 1.5)) (0.0, 1.5, 3.0, 4.5, 6.0, 7.5) """ start = float(start) while start < stop: yield start start += step
21,769
def rotate(posList, axis, angle): """Rotate the points about a given axis by a given angle.""" #normalize axis, turn angle into radians axis = axis/np.linalg.norm(axis) angle = np.deg2rad(angle) #rotation matrix construction ux, uy, uz = axis sin, cos = np.sin(angle), np.cos(angle) rotMa...
21,770
def _make_frame_with_filename(tb, idx, filename): """Return a copy of an existing stack frame with a new filename.""" frame = tb[idx] return FrameSummary( filename, frame.lineno, frame.name, frame.line)
21,771
def do_environment_session_create(mc, args): """Creates a new configuration session for environment ID.""" environment_id = args.id session_id = mc.sessions.configure(environment_id).id print("Created new session:") formatters = {"id": utils.text_wrap_formatter} utils.print_dict({"id": session_i...
21,772
def median(X): """ Middle value after sorting all values by size, or mean of the two middle values. Parameters ---------- X : np.array Dataset. Should be a two-dimensional array. Returns ------- a: np.array One-dimensional array that contains the median for each feature...
21,773
def setTextFont(self, strng): """ TOWRITE :param `strng`: TOWRITE :type `strng`: QString """ self.textFontSelector.setCurrentFont(QFont(strng)) self.setSettingsTextFont(strng)
21,774
def _filter_none_values(d: dict): """ Filter out the key-value pairs with `None` as value. Arguments: d dictionary Returns: filtered dictionary. """ return {key: value for (key, value) in d.items() if value is not None}
21,775
def new_project(request): """ if this is a new project, call crud_project without a slug and with action set to New """ return crud_project(request, slug=None, action="New")
21,776
def get_Simon_instance(simon_instance): """Return an instance of the Simon family as a `Cipher`.""" if simon_instance == SimonInstance.simon_32_64: default_rounds = 32 n = 16 m = 4 z = "11111010001001010110000111001101111101000100101011000011100110" elif simon_instance == Sim...
21,777
def load_mnist(path, kind="train"): """ Documentation: --- Description: Load MNIST images and labels from unzipped source files. --- Parameters: kind : str Used to identify training data vs. validation data. Pass "train" t...
21,778
def chop(data): """Split given data stream in normalized chunks. :param data: Data stream to be divided. :type data: python:bytes :returns: A three items tuple with the chunk start index, the chunk length and the chunk data. :rtype: ~typing.Tuple[python:int, python:int, python:byte...
21,779
def run_server(): """Run server.""" uvicorn.run( "hive_gns.server.serve:app", host=config['server_host'], port=int(config['server_port']), log_level="info", reload=False, workers=10 )
21,780
def clamp(val: float) -> int: """Clamp a number to that expected by a reasonable RGB component This ensures that we don't have negative values, or values exceeding one byte Additionally, all number inputs are rounded Args: val (float): Raw float value to clamp Returns: int: Clamped...
21,781
def componental_mfpt(trans: np.ndarray, **kwargs) -> np.ndarray: """Compute Markov mean first passage times per connected component of the chain.""" n_comps, comp_labels = scipy.sparse.csgraph.connected_components( trans, **kwargs ) hier_trans = transition_matrix(trans) absorbing = np.isclos...
21,782
def get_snippet(path): """Get snippet source string""" current_file_dir = os.path.dirname(__file__) absolute_path = os.path.join(current_file_dir, path) with open(absolute_path) as src: return src.read()
21,783
def atleast_1d(*arys): """ Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved. Parameters ---------- array1, array2, ... : array_like One or more input arrays. Returns --...
21,784
def post_inbox(): """ POST /v3/inbox/tests :return: """ data = { 'domain': 'domain.com', 'from': 'user@sending_domain.com', 'subject': 'testSubject', 'html': '<html>HTML version of the body</html>' } req = client.inbox_tests.create(domain=domain, data=data) p...
21,785
def test_list_negative_integer_white_space_nistxml_sv_iv_list_negative_integer_white_space_1_4(mode, save_output, output_format): """ Type list/negativeInteger is restricted by facet whiteSpace with value collapse. """ assert_bindings( schema="nistData/list/negativeInteger/Schema+Instance/NI...
21,786
def plot_fig_1(f, axs): """ Plot the figure labelled Figure 1 in our paper given the data. """ idx = 0 N = 5 x_values = [i + 1 for i in range(N)] axs[idx].plot( x_values, create_weights(N, "uniform"), CB_color_cycle[1], marker="o", label=r"\texttt{unif...
21,787
def cli(codelabel): """Click interface.""" try: code = Code.get_from_string(codelabel) except NotExistent: print("The code '{}' does not exist.".format(codelabel)) sys.exit(1) example_dft_atomic_kinds(code)
21,788
def write_formatted_mons(pkmn_string): """ Writes string with all Pokémon to txt file. params: pkmn_string (string) returns: None """ try: with open('pokemon_list.txt', 'w', encoding='utf8') as pkfile: pkfile.write(pkmn_string) pkfile.close() print("File save...
21,789
def _encode_mapping(mapping, f): """Encodes the mapping items in lexical order (spec)""" f.write(_TYPE_DICT) for key, value in sorted(mapping.items()): _encode_buffer(key, f) bencode(value, f) f.write(_TYPE_END)
21,790
def lines2str(lines, sep = "\n"): """Merge a list of lines into a single string Args: lines (list, str, other): a list of lines or a single object sep (str, optional): a separator Returns: str: a single string which is either a concatenated lines (using a custom or the ...
21,791
def tail(fname, n=10, with_tail='tail'): """Get the last lines in a file. Parameters ---------- fname : str File name. n : int, optional Number of lines to get (default is 10). with_tail : str, optional The 'tail' command to use (default is `tail`). Returns ----...
21,792
def caplog_handler_at_level(caplog_fixture, level, logger=None): """ Helper function to set the caplog fixture's handler to a certain level as well, otherwise it wont be captured e.g. if caplog.set_level(logging.INFO) but caplog.handler is at logging.CRITICAL, anything below CRITICAL wont be captured. ...
21,793
def evaluate(board): """ Evaluates chess board input parameter(s): board --> The chess board to be evaluated return parameter(s): score --> The board evaluation """ score = 0 for i in range(len(board)): for j in range(len(board[i])): # Add p...
21,794
def get_atom(value): """atom = [CFWS] 1*atext [CFWS] An atom could be an rfc2047 encoded word. """ atom = Atom() if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) atom.append(token) if value and value[0] in ATOM_ENDS: raise errors.HeaderParseError( ...
21,795
def create_page(): """新增页面""" tags = dbutils.get_tags() return render_template('edit.html', title='新建', edit=False, tags=tags)
21,796
def test_init_values(test_dbm_fx): """ Test and verify all values required for instantiation are not None. """ assert test_dbm_fx._initialized assert test_dbm_fx._dbhost assert test_dbm_fx._dbpass assert test_dbm_fx._dbname assert test_dbm_fx._dbport assert test_dbm_fx._dbuser
21,797
def calculate_class_weights(): """ :return: class-wise true-label-area / false-label-area as a dictionary """ df = collect_stats() df = df.fillna(0) df = df.pivot(index = 'Class', columns = 'ImageId', values = 'TotalArea') df = df.sum(axis=1) df = df / (2500. - df) return df.to_dict...
21,798
def get_data_layer(roidb, num_classes): """return a data layer.""" if cfg.TRAIN.HAS_RPN: if cfg.IS_MULTISCALE: layer = GtDataLayer(roidb) else: layer = RoIDataLayer(roidb, num_classes) else: layer = RoIDataLayer(roidb, num_classes) return layer
21,799