content
stringlengths
22
815k
id
int64
0
4.91M
def heat_degree_day(Tcolumn): """ Returns a list of the heating degree day from an outdoor temperature list params: df is a pandas dataframe with datetime index and field named 'outT' which contains outdoor temperature in Fahrenheit base -- temperature base for the heating degree day va...
36,500
def quantile_loss(y_true, y_pred, taus): """ The quantiles loss for a list of quantiles. Sums up the error contribution from the each of the quantile loss functions. """ e = skewed_absolute_error( K.flatten(y_true), K.flatten(y_pred[:, 0]), taus[0]) for i, tau in enumerate(taus[1:]): ...
36,501
def parse_a3m(a3m_string: str) -> Tuple[Sequence[str], DeletionMatrix]: """Parses sequences and deletion matrix from a3m format alignment. Args: a3m_string: The string contents of a a3m file. The first sequence in the file should be the query sequence. Returns: A tuple of: * A list of sequen...
36,502
def PyEval_GetFuncName(space, func): """Return the name of func if it is a function, class or instance object, else the name of funcs type.""" raise NotImplementedError
36,503
def build_sub_lattice(lattice, symbol): """Generate a sub-lattice of the lattice based on equivalent atomic species. Args: lattice (ASE crystal class): Input lattice symbol (string): Symbol of species identifying sub-lattice Returns: list of lists: sub_lattice:...
36,504
def make_url(connection_str): """ """ return _parse_rfc1738_args(connection_str)
36,505
def get_graphs_within_cutoff(structure: Union[Structure, MEGNetMolecule, Molecule], cutoff: float = 5.0, numerical_tol: float = 1e-8) -> Tuple[np.ndarray]: """ Get graph representations from structure within cutoff Args: structure: (pymatgen Structure) cutoff: (f...
36,506
def add_cals1(): """ Add nutrients to daily intake for products. """ if 'username' in session: food = request.form.get("keyword") pr = Product(food) lst = pr.get_products() for i in lst: lyst.append(i) if len(lst) != 0: return render_templa...
36,507
def format_percent(percentage, pos): """ Formats percentages for the 'x' axis of a plot. :param percentage: The fraction between 0.0 and 1.0 :type percentage: float :param pos: The position argument :type pos: int :return: A formatted percentage string :rtype: str """ # pylint: ...
36,508
def iterate_minibatches_u(datasize, batchsize, shuffle=False): """ This function tries to iterate unlabeled data in mini-batch for batch_data in iterate_minibatches_u(data, batchsize, True): #processing batch_data """ if shuffle: indices = np.arange(datasize) np.random.Ra...
36,509
def simple_repr(obj, attrs: tp.Optional[tp.Sequence[str]] = None, overrides: dict = {}): """ Return a simple representation string for `obj`. If `attrs` is not None, it should be a list of attributes to include. """ params = inspect.signature(obj.__class__).parameters attrs_repr ...
36,510
def verify_empty_search_table(self): """ Verifyies that there are not members in a local group members search table :param self: MainController object :return: None """ searc_members_table_is_empty = self.wait_until_visible(type=By.XPATH, ...
36,511
def Gaussian_RadialBasis(basis_size: int, max_radius: float, min_radius=0., num_layers: int = 0, num_units: int = 0, activation_function='relu'): """ Note: based on e3nn.radial.GaussianRadialModel. :param basis_size: :param max_radius: :param min_radius: :param num_lay...
36,512
def _get_column_outliers_std(column, m=3): """ given a pandas Series representing a column in a dataframe returns pandas Series without the values which are further than m*std :param column: pandas Series representing a column in a dataframe :param m: num of std as of to remove outliers :return:...
36,513
def scrape_website(url): """Sends a GET request to a certain url and returns the Response object if status code is 200. Returns None if the server responds with a different code. """ result = requests.get(url) # if (True): # debugging if result.status_code == 200: return result ...
36,514
def set_filters(request, query, result, static_items=None): """ Sets filters in the query """ query_filters = query['filter']['and']['filters'] used_filters = {} if static_items is None: static_items = [] # Get query string items plus any static items, then extract all the fields ...
36,515
def generate_random_initial_population(population_size, n_nodes, al): """ Randomly create an initial population :param population_size: population size :type population_size: int :param n_nodes: number of nodes :type n_nodes: int :param al: adjacency list :type al: list of lists :re...
36,516
def main(): """ Main entry point for module execution :returns: ansible_facts """ argument_spec = { 'gather_subset': dict(default=['software_info', 'software_images', 'host_name', 'platform_name', 'management_inter...
36,517
def initialization(): """Инициализация нужных файлов игры""" pygame.init() pygame.display.set_icon(pygame.image.load("data/icon.bmp")) pygame.display.set_caption('SPACE')
36,518
def test_new_valid_is_pack_display_name_already_exist(): """ Given - pack_metadata file with a pack name that does not exist in our repo. When - _is_pack_display_name_already_exist is called Then - Ensure it is valid and no error is returned. """ validator = IDSetValidati...
36,519
def import_mlp_args(hyperparameters): """ Returns parsed config for MultiLayerPerceptron classifier from provided settings *Grid-search friendly """ types = { 'hidden_layer_sizes': make_tuple, 'activation': str, 'solver': str, 'alpha': float, 'batch_size': int...
36,520
def download_map( location: List[str], node_tags: Optional[List[str]] = None, edge_tags: Optional[List[str]] = None, api_key: Optional[str] = None, ) -> networkx.DiGraph: """ Download map from OSM for specific locations. """ logger.info(f"Download map for {location}") return custom_g...
36,521
def getLayers(model): """ get each layer's name and its module :param model: :return: each layer's name and its module """ layers = [] def unfoldLayer(model): """ unfold each layer :param model: the given model or a single layer :param root: root name ...
36,522
def test_statement_dunder_getitem(sample_statement_object): """Verifies `s.__getitem__()`.""" assert ( # sample_statement_object.__getitem__(item="start_time") == sample_statement_object.sql sample_statement_object.__getitem__(item="start_time") == sample_statement_object.start_time )
36,523
def get_config_pdf_version(config_version: str, max_input_version: str) -> str: """ From the PDF version as set in the configuration and the maximum version of all input files, checks for the best PDF output version. Logs a warning, if the version set in the configuration is lower than any of the input ...
36,524
def threshold_otsu(hist): """Return threshold value based on Otsu's method. hist : array, or 2-tuple of arrays, optional Histogram from which to determine the threshold, and optionally a corresponding array of bin center intensities. An alternative use of this function is to pass it onl...
36,525
def filter_options(v): """Disable option v""" iris = dataframe() return [ {"label": col, "value": col, "disabled": col == v} for col in iris.columns ]
36,526
def scatter(x): """ matrix x x^t """ x1 = np.atleast_2d(x) xt = np.transpose(x1) s = np.dot(xt,x1) assert np.array_equal( np.shape(s), [len(x),len(x)] ) return s
36,527
def assert_allclose( actual: Tuple[complex, complex], desired: Tuple[numpy.complex128, numpy.complex128], err_msg: str, ): """ usage.scipy: 1 """ ...
36,528
def get_owned_object_or_40x(klass, owner, include_staff=False, include_superuser=True, *args, **kwargs): """ Returns an object if it can be found (using get_object_or_404). If the object is not owned by the supplied owner a 403 will be raised. """ obj = get_object_or_404(...
36,529
def ampMeritFunction2(voltages,**kwargs): """Simple merit function calculator. voltages is 1D array of weights for the influence functions distortion is 2D array of distortion map ifuncs is 4D array of influence functions shade is 2D array shade mask Simply compute sum(ifuncs*voltages-distortion...
36,530
def get_transpose_graph(graph): """Get the transpose graph""" transpose = {node: set() for node in graph.keys()} for node, target_nodes in graph.items(): for target_node in target_nodes: transpose[target_node].add(node) return transpose
36,531
def _game_data_path(game_id): """ Find the path to the data file for a given game. This fully trusts game_id, and is not safe on unsanitised input. """ return os.path.join(_DATA_STORES, "{}{}".format(game_id, _EXTENSION))
36,532
def varimax(x, iteration=14): """ http://www.real-statistics.com/linear-algebra-matrix-topics/varimax/""" # TODO: set more intelligent angle evaluator # parameter: x np.array(m_features,c_factors) def _calculate_rotation_angle(x, y): u = np.square(x) - np.square(y) v = 2 * x * y ...
36,533
def websocket_trace_contexts(opp, connection, msg): """Retrieve contexts we have traces for.""" key = (msg["domain"], msg["item_id"]) if "item_id" in msg else None if key is not None: values = {key: opp.data[DATA_TRACE].get(key, {})} else: values = opp.data[DATA_TRACE] contexts = {...
36,534
def inventory_to_kml_string( inventory, icon_url="https://maps.google.com/mapfiles/kml/shapes/triangle.png", icon_size=1.5, label_size=1.0, cmap="Paired", encoding="UTF-8", timespans=True, strip_far_future_end_times=True): """ Convert an :class:`~obspy.core.inventory.inventory.In...
36,535
def concatenate_recordings(logPath, fileList, outFileName, odourClassesRecorded, nrSamples, nrInputNeurons, nrVR, spikeLengthSample, alpha, baselineValues): """Concatenates spike times vectors for all recording session. Input: ...
36,536
def get_feature_embedding(config, data_loader, topk): """Iterate through all items in the data loader and maintain a list of top k highest entropy items and their embeddings topk - the max number of samples to keep. If None, don't bother with entropy, and just return embeddings for items in the data l...
36,537
def extract_yelp_data(term, categories, price, location, limit, sort_by, attributes, yelp_api_key=yelp): """ This function takes search results (a dictionary) and obtains the name, zip code, address of the possible restaurant matches in the form of a pandas dataframe. Inputs:...
36,538
def collect_photo_info(api_key, tag, max_count): """Collects some interesting info about some photos from Flickr.com for a given tag """ photo_collection = [] url = "http://api.flickr.com/services/rest/?method=flickr.photos.search&tags=%s&format=json&nojsoncallback=1&api_key=%s" %(tag, api_key) resp = ...
36,539
def yolo_eval(yolo_outputs, image_shape=(720., 1280.), max_boxes=10, score_threshold=.6, iou_threshold=.5): """ Converts the output of YOLO encoding (a lot of boxes) to your predicted boxes along with their scores, box coordinates and classes. Arguments: yolo_outputs -- output of the encoding mode...
36,540
def flattenLists(l): """Flatten only lists""" for el in l: #print type(el) if type(el) == types.ListType: #print "bla" for sub in flattenLists(el): yield sub else: yield el
36,541
def task(name, required=None): """ A decorator for creating new tasks Args: name (str): Name of the task required (list): A list of required message keys that the task expects to be present """ def decorator(fn): @wraps(fn) def wrapper(...
36,542
def heterograph(g, max_level=4): """ Constructing hypergraph from homograph. Parameters ---------- g : `dgl.DGLGraph` Input graph. max_level : `int` (Default value = 4) Highest level of hypernodes. Returns ------- hg : `dgl.DGLHeteroGraph` Output graph....
36,543
def test_cpphello(): """ Test the cpphello() function. """ assert cpphello() == "Greetings from C++!" return
36,544
def ireduce_ufunc(arrays, ufunc, axis=-1, dtype=None, ignore_nan=False, **kwargs): """ Streaming reduction generator function from a binary NumPy ufunc. Generator version of `reduce_ufunc`. ``ufunc`` must be a NumPy binary Ufunc (i.e. it takes two arguments). Moreover, for performance reasons, ufun...
36,545
def check_date_mention(tweet): """Check the tweet to see if there is a valid date mention for the three dates of pyconopenspaces: 5/11, 5/12, 5/13. Quick fix to override SUTime defaulting to today's date and missing numeric info about event's date """ date_pat = re.compile("([5]{1}\/\d{2})") v...
36,546
def parse(args): """[--starved <int>] [--control <int>] [--other <int>]""" parser = argparse.ArgumentParser() parser.add_argument('--control', metavar='level', type=int, default=2) parser.add_argument('--other', metavar='level', type=int, default=1) parser.add_argument('--starved', metavar='level',...
36,547
def make_nointer_beta(): """Make two random non-intersecting triangles in R^3 that pass the beta test.""" # Corners of triangle B. b1, b2, b3 = np.random.random(3), np.random.random(3), np.random.random(3) # Two edges of B. p1 = b2 - b1 p2 = b3 - b1 n = np.cross(p1, p2) n /= np.linalg....
36,548
def get_all_with_given_response(rdd, response='404'): """ Return a rdd only with those requests that received the response code entered. Default set to '404'. return type: pyspark.rdd.PipelinedRDD """ def status_iterator(ln): try: status = ln.split(' '...
36,549
async def get_neighbourhood(postcode_like: PostCodeLike) -> Optional[Neighbourhood]: """ Gets a police neighbourhood from the database. Acts as a middleware between us and the API, caching results. :param postcode_like: The UK postcode to look up. :return: The Neighbourhood or None if the postcode d...
36,550
def test_MAE_sldiff(): """ MAE is 1/3 for two arrays that are the same but for one entry which differs by one unit. """ yhat = np.array([[1, 2, 3]]) y = np.array([[1, 1, 3]]) obs_i = MAE(yhat, y) exp_i = 1/3 assert approx(obs_i, 0.01) == exp_i return
36,551
def get_refl_weight(value, source_node): """Returns the reflection weight for Redshift Material :param value: :param source_node: :return: """ refl_color_map = source_node.ParameterBlock.texmap_reflection.Value refl_color_map_name = None try: refl_color_map_name = refl_color_map...
36,552
def createSMAbasis(delta, pistonMode, pistonProj): """ Input args: <delta> is the geometric covariance matrix of actuators, it is computed elsewhere. It is a square, symmetric matrix 60x60 <pistonMode> : piston mode (will be used in sparta) This will create a basis orthogonal to pi...
36,553
def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the g...
36,554
def s3_put_bucket_website(s3_obj, bucketname, website_config): """ Boto3 client based Put bucket website function Args: s3_obj (obj): MCG or OBC object bucketname (str): Name of the bucket website_config (dict): Website configuration info Returns: dict : PutBucketWebsit...
36,555
def admin_route(): """Route to admin portal for uploading and managing datasets. .. :quickref: admin; Route to admin portal for uploading and managing datasets. Notes: - flash() uses Bootstrap 4.0 alert categories, https://getbootstrap.com/docs/4.0/components/alerts/ # GET REQUEST...
36,556
def check_assignment(tokenlist : List[str], current_line : int) -> Tuple[bool, List[Token.Token]]: """Checks if the given construction is of the type 'assignment'. If it is, the first value will return True and the second value will return a list of tokens. If it isn't of the type 'assignment', the first value...
36,557
def test_view_empty_posts(app, database, test_client, default_groups): """Test to show empty product posts page""" url = url_for('product.posts') r = test_client.get(url) assert r.status_code == 200
36,558
def load_nifc_fires(): """load nifc data for 2020/2021 fire season NB this is a bit of an undocumented NIFC feature -- the data supposedly only cover 2021 but there are definitely 2020 fires included at the endpoint. This might not be true in the future. https://data-nifc.opendata.arcgis.com/datas...
36,559
def test_post_an_asset_with_invalid_data(client, setup_api_test_data): """ Add an asset with some fields having invalid data and one field missing. The right error messages should be in the response and the number of assets has not increased. """ with UserContext("test_admin_user@seita.nl") as prosu...
36,560
def setup(client): """This is called when the cog is loaded via load_extension""" client.add_cog(Jail(client))
36,561
def test_remove_layer_shapefile(tmpdir): """Removal of layer in shapefile actually deletes the datasource""" filename = str(tmpdir.join("a_filename.shp")) create_sample_data(filename, "ESRI Shapefile") fiona.remove(filename, layer=0) assert not os.path.exists(filename)
36,562
def test_adjacent_nodes(graph_with_edges): """Ensure we get adjacent edges.""" assert graph_with_edges.adjacent('A', 'B')
36,563
def test_api_query_paginated_trades_pagination(mock_bitstamp): """Test pagination logic for trades works as expected. First request: 2 results, 1 valid trade (id 2) Second request: 2 results, no trades Third request: 2 results, 1 valid trade (id 5) and 1 invalid trade (id 6) Trades with id 2 and 5...
36,564
def eigenvalue_nonunitary_entanglement_infidelity(a, b, mx_basis): """ Returns (d^2 - 1)/d^2 * (1 - sqrt(U)), where U is the eigenvalue-unitarity of a*b^{-1} Parameters ---------- a : numpy.ndarray The first process (transfer) matrix. b : numpy.ndarray The second process (trans...
36,565
def blah(): """ docstring """ print("blah") pass
36,566
def project_create_folder_structures(project_folder_path): """Creates a project structure. Assumes current directory is root of project""" # create the pm folder structure project_init_pm_folder(project_folder_path) # create other folder structures make_folder_if_doesnt_exist(os.path.join(...
36,567
def upload_to_s3(local_filepath, file_name, s3_path, bucket_name=BUCKET_NAME): """ Returns ---------- Uploads local file to appropriate s3 key, and prints status Parameters ---------- local_filepath : str ex. 'my/local/path' file_name : str ex. 'cleaned_data.csv' or 'model.pkl' bucket_name : str ...
36,568
def morph(word, rootlist, Indo = False, n = 5): """ Bagi sesuatu perkataan ("word"), kembalikan n analisis morphologi yang paling mungkin berdasarkan senarai akar ("rootlist"). Format output: akar, perkataan, proklitik/awalan, akhiran/enklitik, apitan, reduplikasi @param Indo: Jika benar, awalan N-...
36,569
def get_logger(name): """ Returns a logger from the registry Parameters ---------- name : str the name indicating the logger to return Returns ------- :class:`delira.logging.base_logger.Logger` the specified logger object """ return _AVAILABLE_LOGGERS[name]
36,570
def load_yaml(path: Union[str, Path], pure: bool = False) -> dict: """config.yaml file loader. This function converts the config.yaml file to `dict` object. Args: path: .yaml configuration filepath pure: If True, just load the .yaml without converting to EasyDict and exclude extr...
36,571
def InterpolatedCurveOnSurfaceUV1(thisSurface, points, tolerance, closed, closedSurfaceHandling, multiple=False): """ Returns a curve that interpolates points on a surface. The interpolant lies on the surface. Args: points (System.Collections.Generic.IEnumerable<Point2d>): List of at least two UV p...
36,572
def show(request, url, alias_model, template): """List all vouched users with this group.""" group_alias = get_object_or_404(alias_model, url=url) if group_alias.alias.url != url: return redirect('groups:show_group', url=group_alias.alias.url) group = group_alias.alias in_group = group.memb...
36,573
def index(): """ Home page. Displays subscription info and smart-sorted episodes. """ client = JsonClient(session["username"], session["password"]) subs = get_subscriptions(client, session["username"]) recent_episodes = smart_sort(client, session["username"]) for ep in recent_episodes: ep['d...
36,574
def range( lower: int, upper: int, step: Optional[int] = None, name: Optional[str] = None ) -> Series: """ Create a Series that ranges from lower bound to upper bound. Parameters ---------- lower Lower bound value. upper Upper bound value. step Optional step size....
36,575
def local_gpu_masked_careduce(node): """ Detects eligible CAReduce{add}(GpuElemwise{Switch}) instances and replaces them with a masked CAReduce. """ # TODO: Probably don't need this hack checking for both GpuCAReduce and its # non-gpu counterpart anymore. Just the GPU should be fine. if not...
36,576
def cli(): """Interact with the https://n26.com API via the command line."""
36,577
def ticks_lt(exact_price): """ Returns a generator for all the ticks below the given price. >>> list(ticks_lt(Decimal('0.35'))) [Decimal('0.34'), Decimal('0.33'), Decimal('0.20'), Decimal('0.10'), Decimal('0.01')] >>> list(ticks_lt(Decimal('0.20'))) [Decimal('0.10'), Decimal('0.01')] >>> li...
36,578
def _decode_to_string(to_decode): """ This function is needed for Python 3, because a subprocess can return bytes instead of a string. """ try: return to_decode.decode("utf-8") except AttributeError: # bytesToDecode was of type string before return to_decode
36,579
def nn(x_dict): """ Implementation of a shallow neural network.""" # Extract Input. x = x_dict["images"] # First Hidden Layer. layer_1 = tf.layers.dense(x, 256) # Second Hidden Layer. layer_2 = tf.layers.dense(layer_1, 256) # Output Layer. output_layer = tf.layers.dense(layer_2, 10)...
36,580
def find_negamax_move_alphabeta(game_state, valid_moves, depth, alpha, beta, turn_multiplier): """ NegaMax algorithm with alpha beta pruning. Alpha beta pruning eliminates the need to check all moves within the game_state tree when a better branch has been found or a branch has too low of a score. ...
36,581
def create_segment(context_dir: str, segment: dict, is_be: bool): """Create segment in IDA and map in the data from the file :param context_dir: Parent directory of the context files :param segment: Segment information from _index.json :param is_be: True if processor is big endian, otherwise False ...
36,582
def sum_kernel(X, Y, kernels = None): """ Meta Kernel for summing multiple kernels. """ _sum = 0 for kernel in kernels: print("Doing", kernel["class"], "with parameters:", kernel["parameters"]) _sum = _sum + globals()[kernel["class"]](X, Y, **kernel["parameters"]) return _sum
36,583
def pretvori_v_sekunde(niz): """ Pretvori niz, ki predstavlja dolžino skladbe v formatu hh:mm:ss v število sekund. """ h, m, s = map(int, niz.split(":")) return s + m*60 + h*3600
36,584
def _get_profiling_data(filename): """Read a given file and parse its content for profiling data.""" data, timestamps = [], [] try: with open(filename, "r") as f: file_data = f.readlines() except Exception: logging.error("Could not read profiling data.", exc_info=True) ...
36,585
def parse_dataset_name(dataset_name: str) -> (str, str): """ Split the string of the dataset name into two parts: dataset source name (e.g., cnc_in_domain) and dataset part (e.g., train). :param dataset_name: :return: dataset source name (e.g., cnc_in_domain) and dataset part (e.g., train). """ ...
36,586
def test_filter_schema(): """Test filter schema.""" conf = { 'include_domains': ['light'], 'include_entities': ['switch.kitchen'], 'exclude_domains': ['cover'], 'exclude_entities': ['light.kitchen'] } filt = FILTER_SCHEMA(conf) assert filt.config == conf
36,587
def get_analytics_zoo_classpath(): """ Get and return the jar path for analytics-zoo if exists. """ if os.getenv("BIGDL_CLASSPATH"): return os.environ["BIGDL_CLASSPATH"] jar_dir = os.path.abspath(__file__ + "/../../") jar_paths = glob.glob(os.path.join(jar_dir, "share/lib/*.jar")) if...
36,588
def add_predictions_to_tsv(file: str): """ takes a tsv file that already contains the following columns ['id', 'target_domain', 'source_domain', 'in_sent', 'out_sent', 'lemma_pos', 'word_type'] and adds predictions from our metaphor generation models The resulting extended file is stored separately...
36,589
def _add_layers(sequential, num_layers, num_units, kernel_init, activation, normalizer, residual_connections): """Adds several layers to a tf.keras.Sequential instance.""" for i in range(num_layers): sequential.add( _Layer(num_units, kernel_init, activation, normalizer(), ...
36,590
def plot_pq(df_pq, df_pq_std=None, columns=('mae', 'r2s'), title='Performance-Quantile'): """Plot the quantile performance plot from the prepared metrics table. Args: df_pq (pd.DataFrame): The QP table information with mean values. df_pq_std (pd.DataFrame): The QP table information ...
36,591
def protoToOpenAPISchemaRecursive(lines, schemas, schemaPrefix, basename): """ Recursively create a schema from lines read from a proto file. This method is recursive because proto messages can contain internal messages and enums. If this is the case the method will call itself recursively. :param...
36,592
def to_binary(s: typing.Union[str, bytes], encoding='utf8') -> bytes: """Cast function. :param s: object to be converted to bytes. """ return s if isinstance(s, bytes) else bytes(s, encoding=encoding)
36,593
def _generate_proto(): """Generate MetricsPayload for global_monitor.send().""" proto = metrics_pb2.MetricsPayload() # Key: Target, value: MetricsCollection. collections = {} # Key: (Target, metric name) tuple, value: MetricsDataSet. data_sets = {} count = 0 for (target, metric, start_time, end_time,...
36,594
def visualize_q_percolation(Q): """ Takes a python dictionary of variables (keys) and values :param Q: :return: """ values = Q plt.ylabel('Number of Components for Q-Dimension') plt.title('Q-Value Percolation') plt.plot(values) fig = matplotlib.pyplot.gcf() fig.set_size_inche...
36,595
def multilabel(ctx, text_column, label_names, balance): """Train Multilabel classification This will use columns passed as the last argument [LABEL_NAMES] Each column should be binary integer encoded """ texts, labels = load_multilabel_data( ctx["input_data"], text_column=text_column, label...
36,596
def test_config_from_toml_001(): """ Arrange: Create an `ElastalkConf` instance. Act: Configure the instance from configuration 001. Assert: The configuration matches expectations. """ config = ElastalkConf() for toml in get_config('001'): config.from_toml(toml_=toml) # ...
36,597
def load_numpy(data_path, save_disk_flag=True): """Load numpy.""" if save_disk_flag: # Save space but slow f_data = gzip.GzipFile(f'{data_path}.gz', "r") data = np.load(f_data) else: data = np.load(data_path) return data
36,598
def _teardown_logger(logger: logging.Logger, handler_list: List[logging.Handler]) -> None: """Closes and removes log handlers from the logger.""" for handler in handler_list: logger.removeHandler(handler) handler.close()
36,599