from django.http import HttpResponse, Http404
from rest_framework import viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
import json

from .serializers import departmentSerializer, departmenttimingsSerializer
from .models import department, departmenttimings

@api_view(['GET', 'POST'])
def department_list(request):
    if request.method == 'GET':
        data = department.objects.all()

        serializer = departmentSerializer(
            data, context={'request': request}, many=True)

        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = departmentSerializer(data=request.data)
        if serializer.is_valid():
            print("serialized data")
            serializer.save()
            print(serializer.data)
            departmentschedule(request.data, serializer.data)
            return Response(status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def departmentschedule(departmentData, data):
    print('entered')
    schedule = departmentData['departmentSchedules']
    print(schedule)

    departmentid = data['id']
    depart = department.objects.get(id=departmentid)
    depart.departmenttimings_set.all().delete()
    timings = []

    for week in schedule:
        print(week)
        timing = departmenttimings(
            day=week['day'], availability=week['availability'], startTime=week['startTime'], endTime=week['endTime'], dayOfTheWeek=week['dayOfTheWeek'], department=depart)
        timings.append(timing)

    departmenttimings.objects.bulk_create(timings)

@api_view(['PUT', 'DELETE'])
def department_detail(request, id):
    try:
        departmentDto = department.objects.get(id=id)
    except department.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'PUT':
        serializer = departmentSerializer(
            departmentDto, data=request.data, context={'request': request})
        if serializer.is_valid():
            serializer.save()
            departmentschedule(request.data, serializer.data)

            return Response(status=status.HTTP_204_NO_CONTENT)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        departmentDto.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

@api_view(['GET'])
def default_department_schedule(request):
    department_default_schedule = [
        {
            "day": "sunday",
            "availability": 0,
            "startTime": "00:00:00",
            "endTime": "00:00:00",
            "department": 0,
            "dayOfTheWeek": 0
        },
        {
            "day": "monday",
            "availability": 0,
            "startTime": "00:00:00",
            "endTime": "00:00:00",
            "department": 0,
            "dayOfTheWeek": 1
        },
        {
            "day": "tuesday",
            "availability": 0,
            "startTime": "00:00:00",
            "endTime": "00:00:00",
            "department": 0,
            "dayOfTheWeek": 2
        },
        {
            "day": "wednesday",
            "availability": 0,
            "startTime": "00:00:00",
            "endTime": "00:00:00",
            "department": 0,
            "dayOfTheWeek": 3
        },
        {
            "day": "thursday",
            "availability": 0,
            "startTime": "00:00:00",
            "endTime": "00:00:00",
            "department": 0,
            "dayOfTheWeek": 4
        },
        {
            "day": "friday",
            "availability": 0,
            "startTime": "00:00:00",
            "endTime": "00:00:00",
            "department": 0,
            "dayOfTheWeek": 5
        },
        {
            "day": "saturday",
            "availability": 0,
            "startTime": "00:00:00",
            "endTime": "00:00:00",
            "department": 0,
            "dayOfTheWeek": 6
        }
    ]
    return Response(department_default_schedule)

@api_view(['GET', 'POST'])
def departmenttimings_list(request, dept):

    if request.method == 'GET':
        try:
            depart = department.objects.get(id=dept)
            data = depart.departmenttimings_set.all()
        except:
            raise 404

        serializer = departmenttimingsSerializer(
            data, context={'request': request}, many=True)

        return Response(serializer.data)

    elif request.method == 'POST':
        print(dept)
        timings = []
        depart = department.objects.get(id=dept)
        data = depart.departmenttimings_set.all().delete()
        # departmenttimings.objects.get(department=dept).delete()
       # departmenttimings.objects.bulk_create(request.data)

        for week in request.data:
            print(week)
            timing = departmenttimings(
                day=week['day'], availability=week['availability'], startTime=week['startTime'], endTime=week['endTime'], dayOfTheWeek=week['dayOfTheWeek'], department=department.objects.get(id=dept))
            timings.append(timing)

        departmenttimings.objects.bulk_create(timings)
        serializer = departmenttimingsSerializer(data=request.data)
        # print(request.data)
        # print(serializer.is_valid)
        # # {"weekday":"sunday","startTime":"09:00","endTime":"05:00","department":"1"}
        # if serializer.is_valid():
        #     print("entered")
        #     serializer.save()
        #     return Response(status=status.HTTP_201_CREATED)

        return Response(status=status.HTTP_400_BAD_REQUEST)


# -*- coding: utf-8 -*-
#
# project-template documentation build configuration file, created by
# sphinx-quickstart on Mon Jan 18 14:44:12 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

from datetime import date
from distutils.version import LooseVersion
import gc
import os
import os.path as op
import sys
import warnings

import sphinx
import sphinx_gallery  # noqa
from sphinx_gallery.sorting import FileNameSortKey
from numpydoc import docscrape
import mne  # noqa
from mne_realtime import __version__

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.8'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'sphinx.ext.doctest',
    'sphinx.ext.intersphinx',
    'sphinx.ext.viewcode',
    'numpydoc',
    'sphinx_gallery.gen_gallery',
    'sphinxcontrib.bibtex',
    'sphinx_copybutton'
]

# configure sphinx-copybutton
copybutton_prompt_text = r">>> |\.\.\. |\$ "
copybutton_prompt_is_regexp = True

# this is needed for some reason...
# see https://github.com/numpy/numpydoc/issues/69
numpydoc_show_class_members = False

# pngmath / imgmath compatibility layer for different sphinx versions
if LooseVersion(sphinx.__version__) < LooseVersion('1.4'):
    extensions.append('sphinx.ext.pngmath')
else:
    extensions.append('sphinx.ext.imgmath')

autosummary_generate = True
autodoc_default_options = {'inherited-members': None}

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# Generate the plots for the gallery
# plot_gallery = True

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'MNE-Realtime'
td = date.today()
copyright = u'2012-%s, MNE Developers. Last updated on %s' % (td.year,
                                                              td.isoformat())

nitpicky = True
suppress_warnings = ['image.nonlocal_uri']  # we intentionally link outside

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = __version__
# The full version, including alpha/beta/rc tags.
release = __version__

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build', '_templates']

# The reST default role (used for this markup: `text`) to use for all
# documents.
default_role = "autolink"

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# Custom style
html_style = 'css/project-template.css'

# A list of ignored prefixes for module index sorting.
modindex_common_prefix = ['mne_realtime.']

# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'pydata_sphinx_theme'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
html_theme_options = {
    "icon_links": [  # TODO: This should work but doesn't, fix later...
        {
            "name": "GitHub",
            "url": "https://github.com/mne-tools/mne-realtime",
            "icon": "fa-brands fa-square-github",
        }
    ],
    "logo": {
        "text": "MNE-Realtime",
    },
    "navigation_with_keys": False,
}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = "_static/mne.svg"

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = "_static/favicon.ico"

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
html_show_sourcelink = False
html_copy_source = False

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
html_show_sphinx = False

# Example configuration for intersphinx: refer to the Python standard library.
# intersphinx configuration
intersphinx_mapping = {
    'python': ('https://docs.python.org/3', None),
    'numpy': ('https://numpy.org/devdocs', None),
    'scipy': ('https://scipy.github.io/devdocs', None),
    'matplotlib': ('https://matplotlib.org', None),
    'sklearn': ('https://scikit-learn.org/stable', None),
    'joblib': ('https://joblib.readthedocs.io/en/latest', None),
    'pandas': ('https://pandas.pydata.org/pandas-docs/stable', None),
    'mne': ('https://mne.tools/dev', None),
    'mne_lsl': ('https://mne.tools/mne-lsl/stable', None),
    'eeglabio': ('https://eeglabio.readthedocs.io/en/latest', None),
    'nitime': ('https://nipy.org/nitime/', None),
    'qdarkstyle': ('https://qdarkstylesheet.readthedocs.io/en/latest', None),
    'pyqtgraph': ('https://pyqtgraph.readthedocs.io/en/latest/', None),
}

##############################################################################
# sphinxcontrib-bibtex

bibtex_bibfiles = ['./references.bib']
bibtex_style = 'unsrt'
bibtex_footbibliography_header = ''

##############################################################################
# sphinx-gallery

examples_dirs = ['../examples']
gallery_dirs = ['auto_examples']

scrapers = ('matplotlib',)

class Resetter(object):
    """Simple class to make the str(obj) static for Sphinx build env hash."""

    def __repr__(self):
        return '<%s>' % (self.__class__.__name__,)

    def __call__(self, gallery_conf, fname):
        import matplotlib.pyplot as plt
        reset_warnings(gallery_conf, fname)
        # in case users have interactive mode turned on in matplotlibrc,
        # turn it off here (otherwise the build can be very slow)
        plt.ioff()
        gc.collect()

def reset_warnings(gallery_conf, fname):
    """Ensure we are future compatible and ignore silly warnings."""
    # In principle, our examples should produce no warnings.
    # Here we cause warnings to become errors, with a few exceptions.
    # This list should be considered alongside
    # setup.cfg -> [tool:pytest] -> filterwarnings

    # remove tweaks from other module imports or example runs
    warnings.resetwarnings()
    # restrict
    warnings.filterwarnings('error')
    # allow these, but show them
    warnings.filterwarnings('default', module='sphinx')  # internal warnings
    # allow these warnings, but don't show them
    warnings.filterwarnings('ignore', '.*is currently using agg.*')
    for key in ('HasTraits', r'numpy\.testing', 'importlib', r'np\.loads',
                'Using or importing the ABCs from',  # internal modules on 3.7
                "DocumenterBridge requires a state object",  # sphinx dev
                "'U' mode is deprecated",  # sphinx io
                'pkg_resources is deprecated as an API',  # bibtex
                'Deprecated call to `pkg_resources',
                ):
        warnings.filterwarnings(  # deal with other modules having bad imports
            'ignore', message=".*%s.*" % key, category=DeprecationWarning)
    warnings.filterwarnings(
        "ignore",
        message=".*is non-interactive, and thus cannot.*",
    )
    warnings.filterwarnings(  # deal with other modules having bad imports
        'ignore', message=".*ufunc size changed.*", category=RuntimeWarning)
    warnings.filterwarnings(  # realtime
        'ignore', message=".*unclosed file.*", category=ResourceWarning)
    warnings.filterwarnings(
        'ignore', message='The str interface for _CascadingStyleSheet.*')
    warnings.filterwarnings('ignore', message='Exception ignored in.*')
    # allow this ImportWarning, but don't show it
    warnings.filterwarnings(
        'ignore', message="can't resolve package from", category=ImportWarning)

reset_warnings(None, None)
sphinx_gallery_conf = {
    'doc_module': 'mne_realtime',
    'reference_url': dict(mne_realtime=None),
    'examples_dirs': examples_dirs,
    'default_thumb_file': os.path.join('_static', 'mne_helmet.png'),
    'backreferences_dir': 'generated',
    'plot_gallery': 'True',  # Avoid annoying Unicode/bool default warning
    'download_all_examples': False,
    'thumbnail_size': (160, 112),
    'min_reported_time': 1.,
    'abort_on_example_error': False,
    'reset_modules': ('matplotlib', Resetter()),  # called w/each script
    'image_scrapers': scrapers,
    'show_memory': True,
    'line_numbers': False,  # XXX currently (0.3.dev0) messes with style
    'within_subsection_order': FileNameSortKey,
    'junit': op.join('..', 'test-results', 'sphinx-gallery', 'junit.xml'),
}

##############################################################################
# numpydoc

# XXX This hack defines what extra methods numpydoc will document
docscrape.ClassDoc.extra_public_methods = mne.utils._doc_special_members
numpydoc_class_members_toctree = False
numpydoc_attributes_as_param_list = False
numpydoc_xref_param_type = True
numpydoc_xref_aliases = {
    # Matplotlib
    'colormap': ':ref:`colormap <matplotlib:colormaps>`',
    'color': ':doc:`color <matplotlib:api/colors_api>`',
    'Axes': 'matplotlib.axes.Axes',
    'Figure': 'matplotlib.figure.Figure',
    'Axes3D': 'mpl_toolkits.mplot3d.axes3d.Axes3D',
    # MNE
    'Epochs': 'mne.Epochs', 'Layout': 'mne.channels.Layout',
    'Raw': 'mne.io.Raw', 'Covariance': 'mne.Covariance',
    'Evoked': 'mne.Evoked', 'Info': 'mne.Info',
    'Montage': 'mne.channels.Montage', 'Forward': 'mne.Forward',
    'DigMontage': 'mne.channels.DigMontage',
    'ConductorModel': 'mne.bem.ConductorModel',
    'EpochsSpectrum': 'mne.time_frequency.EpochsSpectrum',
    'EpochsArray': 'mne.EpochsArray',
    # mne_realtime
    'RtEpochs': 'mne_realtime.RtEpochs',
}
numpydoc_xref_ignore = {
    # words
    'instance', 'instances', 'of', 'default', 'shape', 'or',
    'with', 'length', 'pair', 'matplotlib', 'optional', 'kwargs', 'in',
    'dtype', 'object', 'self.verbose',
    # shapes
    'n_channels', 'n_times', 'nchan', 'n_epochs', 'n_events', 'n_picks',
    'n_ch_groups',
    # unlinkable
    'mne_qt_browser.figure.MNEQtBrowser',
}


# Import modules
import os as os
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
import subprocess as sp
import pathlib as path
from sklearn.decomposition import PCA
import h5py
import time
from scipy.stats import pearsonr
import seaborn as sns
import cooler

# To generate .cool files from BEDPE count files using cooler cload pairs in command line:
# cooler cload pairs -c1 1 -p1 2 -c2 4 -p2 5 --field count=7:dtype=int --zero-based
# /Users/GBS/Master/Reference/hg19/chrom_hg19.sizes:1000000 /Users/GBS/Master/HiC-Data/testing_chrom_parallelization/output/temp_dir/bedpe/mcf10_1000000.bedpe matrix_mcf10.cool

class Directories:
    base_path = path.Path("/Users/GBS/Master/Figures")
    compartment_path = base_path / "comparment_plots"

    if not compartment_path.exists():
        compartment_path.mkdir(parents=True)

class Dirs:
    root_path = path.Path("/Users/GBS/Master/HiC-Data")
    base_path_figures = path.Path("/Users/GBS/Master/Figures")

    chrom_sizes_file = "/Users/GBS/Master/Reference/hg19/chrom_hg19.sizes"
    hg19_cytoband_file = "/Users/GBS/Master/Reference/hg19/cytoBand_hg19.txt"

    compartments_path = root_path / "compartments"
    bedpe_path_intra = root_path / "bedpe_files/bedpe_intra"
    bedpe_path_inter = root_path / "bedpe_files/bedpe_inter"
    cool_path_intra = root_path / "coolfiles/intra"
    cool_path_inter = root_path / "coolfiles/inter"

    heatmap_dir_intra = base_path_figures / "heatmaps/intra"
    distance_dir_intra = base_path_figures / "decay_distances"
    heatmap_dir_inter = base_path_figures / "heatmaps/inter"
    distance_dir_inter = base_path_figures / "decay_distances/inter"

def bedpe_to_cool(bedpe_file, chrom_sizes_file, bin_size, cool_file):
    """
    Convert a BEDPE file to a COOL file using the Cooler command-line tool.

    Parameters:
    bedpe_file (str): The path to the BEDPE file.
    chrom_sizes_file (str): The path to the chrom_sizes file.
    bin_size (int): The bin size in base pairs.
    cool_file (str): The path to the output COOL file.
    """
    command = [
        "cooler",
        "cload",
        "pairs",
        "-c1",
        "1",
        "-p1",
        "2",
        "-c2",
        "4",
        "-p2",
        "5",
        "--field",
        "count=7:dtype=int",
        "--zero-based",
        f"{str(chrom_sizes_file)}:{str(bin_size)}",
        str(bedpe_file),
        str(cool_file)
    ]

    sp.run(command, check=True)

def bedpe_to_cool_py(bedpe_file, chrom_file, resolution, output_file):

    # API is not working
    """
    Convert a BEDPE file to a COOL file using the Cooler Python API.

    Parameters:
    bedpe_file (str): The path to the BEDPE file.
    chrom_file (str): The path to the chromosome sizes file.
    resolution (int): The resolution in base pairs.
    output_file (str): The path to the output COOL file.
    """
    # Load the BEDPE file into a DataFrame
    pairs_df = pd.read_csv(bedpe_file, sep='\t', names=['chrom1', 'start1', 'end1', 'chrom2', 'start2', 'end2', 'count'])

    # Generate the bins
    chromsizes = cooler.util.read_chromsizes(chrom_file)
    bins = cooler.binnify(chromsizes, resolution)

    # Generate the pixels
    pixels = cooler.tools.digest(bins, pairs_df, cooler.util.get_binsize(resolution))

    # Create the COOL file
    cooler.create_cooler(cool_uri=f'{output_file}::{resolution}', bins=bins, pixels=pixels)

# bedpe_to_cool_py("/Users/GBS/Master/HiC-Data/bedpe_files/bedpe_intra/mcf7_1000000.bedpe", "/Users/GBS/Master/Reference/hg19/chrom_hg19.sizes", 1000000, "/Users/GBS/Master/HiC-Data/coolfiles/intra/mcf7_1000000.cool")

def plot_contact_decay(cool_path, log_bins=True, bin_num=100):
    """
    Generate contact decay plot for Hi-C data.

    Parameters:
    cool_path: string
        Path to the .cool file.
    log_bins: Boolean
        - If True, use logarithmic bins.
        - If False, use linear bins.
    bin_num: The number of bins to use

    Returns:
    Matplotlib figure
    """

    # Load the Cooler file
    c = cooler.Cooler(cool_path)

    # Get the genomic positions of the bins
    bin_positions = c.bins()[:]["start"].values

    # Get the pairs DataFrame
    pairs = c.pixels()[:]

    # Calculate the genomic distances for each interaction
    pairs["genomic_distance"] = np.abs(bin_positions[pairs["bin2_id"]] - bin_positions[pairs["bin1_id"]])

    # If log_bins is True, calculate log bin edges
    if log_bins:
        bin_edges = np.logspace(np.log10(pairs["genomic_distance"].min()), np.log10(pairs["genomic_distance"].max()), num=bin_num)
        pairs['bin'] = pd.cut(pairs["genomic_distance"], bins=bin_edges)
        pairs.dropna(subset=["bin"], inplace=True)  # Drop any pairs not falling into a bin
        pairs["bin_center"] = pairs["bin"].apply(lambda x: (x.right + x.left) / 2)

    # Otherwise, use linear bins
    else:
        pairs['bin_center'] = pd.cut(pairs['genomic_distance'], bins=bin_num, labels=False)

    # Compute average interaction frequency for each genomic distance bin
    average_interactions = pairs.groupby("bin_center")["count"].mean()

    # Plot
    plt.figure(figsize=(10, 7))
    plt.loglog(average_interactions.index.values, average_interactions.values)
    plt.title("Contact Decay")
    plt.xlabel("Genomic Distance (bp)")
    plt.ylabel("Average Interaction Frequency")
    plt.show()

# plot_contact_decay("/Users/GBS/matrix_mcf10.cool", log_bins=True, bin_num=100)

def balance_cooler_file(cool_file):
    """Load and balance a cooler file."""
    c = cooler.Cooler(str(cool_file))
    if "weight" in c.bins().columns:
        print(f"The cooler file {cool_file} is already balanced.")
        return c
    else:
        weights, _ = cooler.balance.balance_cooler(c)
        bins = c.bins()[:]
        bins['weight'] = weights
        pixels = c.pixels()[:]
        pixels = pixels[['bin1_id', 'bin2_id', 'count']]
        pixels = pixels.join(bins['weight'], on='bin1_id', how='left').rename(columns={'weight': 'weight1'})
        pixels = pixels.join(bins['weight'], on='bin2_id', how='left').rename(columns={'weight': 'weight2'})
        pixels['weight'] = pixels['weight1'] * pixels['weight2']
        return c, bins, pixels

def validate_and_save_cooler(bins, pixels, balanced_file):
    """Save a balanced cooler file and validate it."""
    cooler.create_cooler(cool_uri=str(balanced_file), bins=bins, pixels=pixels)
    time.sleep(5)
    if os.path.exists(balanced_file):
        if h5py.is_hdf5(str(balanced_file)):
            print("Balanced cooler file was successfully created and is a valid HDF5 file.")
        else:
            print("File exists but is not a valid HDF5 file.")
    else:
        print("File does not exist.")
    print(f"The cooler file is now balanced and saved to {balanced_file}.")

def create_cooler_file():
    bedpe_file = Dirs.bedpe_path_intra / "mcf7_1000000.bedpe"
    chrom_file = Dirs.chrom_sizes_file
    resolution = 1000000
    output_file = Dirs.cool_path_intra / "mcf7_1000000.cool"

    bedpe_to_cool_py(bedpe_file, chrom_file, resolution, output_file)

# create_cooler_file()

def balance_and_save_cooler(cool_file, balanced_file):
    """Balance and save a cooler file."""
    c, bins, pixels = balance_cooler_file(cool_file)
    validate_and_save_cooler(bins, pixels, balanced_file)

# balance_and_save_cooler("/Users/GBS/Master/HiC-Data/coolfiles/inter/mcf7_1000000.cool", "/Users/GBS/Master/HiC-Data/coolfiles/intra/mcf7_1000000_balanced.cool")

def process_chromosome(chrom, cooler_obj, bins_df):
    """
    Process a single chromosome: compute its correlation matrix,
    perform PCA, and assign compartments
    """

    # Fetch the contact matrix for the chromosome
    chrom_matrix = cooler_obj.matrix(balance=True, as_pixels=False, join=True).fetch(chrom)

    # Skip chromosome if it only contains one bin
    if chrom_matrix.shape[0] <= 1:
        print(f"Skipping chromosome {chrom} because it only contains one bin.")
        return None

    # Replace zero values with a small number (e.g., 1e-10)
    small_value = 1e-10
    chrom_matrix = np.where(chrom_matrix == 0, small_value, chrom_matrix)

    # Prepare the observed/expected matrix
    distance_matrix = np.abs(np.arange(chrom_matrix.shape[0])[:, None] - np.arange(chrom_matrix.shape[0]))
    expected = np.bincount(distance_matrix.flatten(), weights=chrom_matrix.flatten()) / np.bincount(distance_matrix.flatten())
    oe_matrix = chrom_matrix / expected[distance_matrix]

    # Compute the correlation matrix and replace NaN/infinite values (no NaNs/infs in oe_matrix)
    correlation_matrix = np.corrcoef(oe_matrix)
    correlation_matrix = np.nan_to_num(correlation_matrix)

    # Compute the first principal component
    pca = PCA(n_components=1)
    principal_components = pca.fit_transform(correlation_matrix)

    # Assign compartments based on the sign of PC1
    compartments = np.sign(principal_components)

    # Create and return a DataFrame for this chromosome
    chrom_bins = bins_df[bins_df['chrom'] == chrom]
    chrom_df = pd.DataFrame({
        "chrom": chrom,
        "start": chrom_bins["start"].values,
        "end": chrom_bins["end"].values,
        "compartment": ['A' if x > 0 else 'B' for x in compartments.flatten()],
        "eigenvector": principal_components.flatten()  # save the eigenvectors
    })

    return chrom_df

def calculate_distance_matrix(bin_starts):
    """
    Calculate a matrix where each cell contains the genomic distance between two bins.
    """
    bin_starts = bin_starts.reshape(-1, 1)  # convert to column vector
    return np.abs(bin_starts - bin_starts.T)

def call_compartments(balanced_file, output_file):
    """
    Call chromatin compartments using Hi-C data in a cooler file
    """

    # Load the balanced cooler file
    c_balanced = cooler.Cooler(str(balanced_file))

    # Fetch all the bins once
    all_bins = c_balanced.bins()[:]

    # Create a DataFrame to hold the results
    result = pd.DataFrame(columns=["chrom", "start", "end", "compartment", "eigenvector"])

    # Loop over each chromosome
    for chrom in c_balanced.chromnames:
        if chrom in ['chrM', 'chrX', 'chrY']:
            print(f"Skipping {chrom}.")
            continue
        chrom_bins = all_bins[all_bins['chrom'] == chrom]
        chrom_df = process_chromosome(chrom, c_balanced, chrom_bins)
        if chrom_df is not None:
            result = result.append(chrom_df)

    # Save the results to a BED file
    result.to_csv(output_file, sep='\t', header=False, index=False)

def inspect_cooler(file_path):
    c = cooler.Cooler(file_path)
    df = c.matrix(balance=False, as_pixels=True)[:]

    # print basic statistics
    print(df.describe())

    # print the variance
    print("\nVariance:\n", df.var())

    # print number of zero values
    print("\nNumber of zero values:\n", (df==0).sum())

    # print the number of NaN values
    print("\nNumber of NaN values:\n", df.isna().sum())

    # print the number of infinite values
    print("\nNumber of infinite values:\n", np.isinf(df).sum())

    # print the number of negative values
    print("\nNumber of negative values:\n", (df<0).sum())

    # print the number of positive values
    print("\nNumber of positive values:\n", (df>0).sum())

# inspect_cooler("/Users/GBS/Master/HiC-Data/coolfiles/intra/mcf10_1000000_balanced.cool")

def compartment_calling():
    balanced_cool_file = Dirs.cool_path_intra / "mcf10_1000000_balanced.cool"
    output_file = Dirs.compartments_path / "mcf10_1mb_pca1_compartments.bed"

    call_compartments(balanced_cool_file, output_file)

# compartment_calling()

def compute_pearson_and_plot(bed_file1, bed_file2, cell_line1, cell_line2):
    # Load BED files into pandas DataFrames
    df1 = pd.read_csv(bed_file1, sep='\t', header=None)
    df2 = pd.read_csv(bed_file2, sep='\t', header=None)

    # Extract the eigenvector values and compartment calls
    eigenvector1 = df1.iloc[:, 4]
    eigenvector2 = df2.iloc[:, 4]
    compartments1 = df1.iloc[:, 3]
    compartments2 = df2.iloc[:, 3]

    # Compute the Pearson correlation coefficient
    correlation = pearsonr(eigenvector1, eigenvector2)[0]

    # Create a new column in the DataFrame indicating whether the compartment call changed
    compartment_change = compartments1 != compartments2

    # Create a scatter plot with points colored based on the compartment call
    plt.figure(figsize=(8, 6))
    plt.scatter(eigenvector1[compartment_change], eigenvector2[compartment_change], color='red', alpha=0.5, label='Compartment change')
    plt.scatter(eigenvector1[~compartment_change], eigenvector2[~compartment_change], color='blue', alpha=0.5, label='No compartment change')
    plt.xlabel(f'Eigenvector - {cell_line1}')
    plt.ylabel(f'Eigenvector - {cell_line2}')
    plt.title(f'Correlation between {cell_line1} and {cell_line2}: r = {correlation:.2f}')
    plt.legend()
    plt.show()

    # Return the correlation
    return correlation

def compare_compartments():
    # Load the BED files
    bed_file1 = Dirs.compartments_path / "mcf7_1mb_compartments.bed"
    bed_file2 = Dirs.compartments_path / "mcf10_1mb_compartments.bed"

    # Compute the Pearson correlation coefficient
    correlation = compute_pearson_and_plot(bed_file1, bed_file2, 'MCF7', 'MCF10')

# compare_compartments()

def merge_bed_files(bed_file1, bed_file2):
    # Load BED files into pandas DataFrames
    df1 = pd.read_csv(bed_file1, sep='\t', header=None, names=['chrom', 'start', 'end', 'compartment', 'eigenvector'])
    df2 = pd.read_csv(bed_file2, sep='\t', header=None, names=['chrom', 'start', 'end', 'compartment', 'eigenvector'])

    # Merge the two dataframes on chrom, start and end
    merged_df = pd.merge(df1, df2, on=['chrom', 'start', 'end'], suffixes=('_1', '_2'))

    return merged_df

def plot_compartments_on_heatmap_sns(cool_path, compartments_bed_path, chrom=None, saveas=None):
    clr = cooler.Cooler(str(cool_path))
    if chrom == "all":
        matrix = clr.matrix()[:]
    else:
        matrix = clr.matrix(balance=True).fetch(chrom)

    diag_sums = [np.nansum(np.diagonal(matrix, offset=i)) for i in range(matrix.shape[0])]
    diag_counts = [np.sum(~np.isnan(np.diagonal(matrix, offset=i))) for i in range(matrix.shape[0])]
    exp_const = 1e-10
    expected = np.array(diag_sums) - np.array(diag_counts) + exp_const
    print(matrix)
    print(expected)
    observed_over_expected = matrix / expected[:, None]
    print(observed_over_expected)

    corr = np.corrcoef(observed_over_expected, rowvar=False)
    compartments = pd.read_csv(compartments_bed_path, sep="\t", header=None, names=["chrom", "start", "end", "compartment", "score"])

    # Convert the genomic coordinates to bin coordinates
    binsize = clr.binsize
    if chrom != "all":
        compartments = compartments[compartments["chrom"] == chrom]
        compartments["start"] = compartments["start"] // binsize
        compartments["end"] = compartments["end"] // binsize

    # Generate the plot
    # fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(10, 10), gridspec_kw={'height_ratios': [1, 4]}, sharex="all")
    fig, ax2 = plt.subplots(figsize=(10, 10))

    # Plot PCa1
    # ax1.plot(compartments["start"], compartments["score"], color='k')

    # Plot the contact map
    vmax = np.percentile(corr[~np.isnan(corr)], 99)
    vmin = np.percentile(corr[~np.isnan(corr)], 1)

    # Make colors not blend:
    colormap = ["blue", "blue", "black", "red", "red"]
    gradient = [0.0, 0.3, 0.5, 0.7, 1.0]
    cmap = mcolors.LinearSegmentedColormap.from_list("cmap", list(zip(gradient, colormap)))
    sns.heatmap(corr, cmap=cmap, ax=ax2)

    # Create ticks at every 25 Mb
    tick_frequency = 25
    ticks = np.arange(0, matrix.shape[0], tick_frequency * 10 ** 6 // binsize)

    # Create tick labels with 'Mb' added
    tick_labels = [f"{tick * binsize // 10 ** 6} Mb" for tick in ticks]

    ax2.set_xticks(ticks[1:])
    ax2.set_xticklabels(tick_labels[1:])
    ax2.set_yticks(ticks[1:])
    ax2.set_yticklabels(tick_labels[1:])

    ax2.set_title(f"Contact map for {chrom}")
    # ax1.set_title(f"Compartments for {chrom}")
    plt.tight_layout()

    if saveas:
        plt.savefig(saveas, dpi=1000, format="png")

    plt.show()

# plot_compartments_on_heatmap_sns(Dirs.cool_path_intra / "mcf7_1000000_balanced.cool", Dirs.compartments_path / "mcf10_250kb_compartments.bed", chrom="chr2")  # :0-95000000")  # , saveas=Dirs.heatmap_dir_intra / "mcf10_250kb_chr2_compartments_plot.png")

def plot_heatmap2(cool_file, chrom=None, saveas=None, log=False):
    # Load the Cooler file
    c = cooler.Cooler(str(cool_file))

    # Define the region to plot
    if chrom == "all":
        matrix = c.matrix(balance=False)[:]
    else:
        matrix = c.matrix(balance=False).fetch(chrom)

    # Copy matrix for processing
    matrix_copy = matrix.copy()

    if log:
        matrix_copy = np.log1p(matrix_copy)
        matrix_copy[matrix_copy == -np.inf] = 0

    # Calculate the limits for the color scale
    vmin, vmax = np.percentile(matrix_copy, [0, 100])

    # Define colormap
    cmap = mpl.cm.get_cmap("YlOrRd")
    cmap.set_bad("white")

    # Plot the heatmap
    plt.matshow(matrix_copy, cmap=cmap, norm=mcolors.PowerNorm(gamma=0.2, vmin=vmin, vmax=vmax))
    plt.title(f"Heatmap of {chrom}")

    # Get current axes
    ax = plt.gca()

    # Create ticks at every 25 Mb
    tick_frequency = 25
    ticks = np.arange(0, matrix.shape[0], tick_frequency * 10 ** 6 // c.binsize)

    # Create tick labels with 'Mb' added
    tick_labels = [f"{tick * c.binsize // 10 ** 6} Mb" for tick in ticks]

    ax.set_xticks(ticks[1:])
    ax.set_xticklabels(tick_labels[1:])
    ax.set_yticks(ticks[1:])
    ax.set_yticklabels(tick_labels[1:])
    ax.xaxis.tick_bottom()
    plt.xticks(rotation='vertical')
    ax.tick_params(axis='x', which='major', pad=10)
    ax.tick_params(axis='x', labelsize=7)
    ax.tick_params(axis='y', labelsize=7)

    ax.set_title(f"Contact map for chromosome 2")
    plt.tight_layout()

    if saveas:
        plt.savefig(saveas, dpi=1000, format="png", bbox_inches='tight')

    plt.show()

# plot_heatmap2(Dirs.cool_path_intra / "imr90_250000_balanced.cool", chrom="chr2", saveas=Dirs.heatmap_dir_intra / "imr90_example250kb_chr2.png")

if __name__ == "__main__":
    print("RUN")


import numpy as np
# import math
import matplotlib.pyplot as plt

def f(x_n, y_n):
    # y_this = -y_n + x_n + 2
    # Exercicio 10.2.1 - livro-py.pdf
    y_this = -0.5*y_n + x_n + 2
    # derivada da solução exata
    # y_this = 2 - 8 * np.exp(-x_n/2)
    return y_this

def euler(n_max, h, x, y):

    for n in range(0, n_max):
        y[n + 1] = y[n] + h * f(x[n], y[n])
        x[n + 1] = x[n] + h

    return x, y

def rk4(n_max, h, x, y):

    for n in range(0, n_max):
        k1 = h * f(x[n], y[n])
        k2 = h * f(x[n] + h / 2, y[n] + k1 / 2)
        k3 = h * f(x[n] + h / 2, y[n] + k2 / 2)
        k4 = h * f(x[n] + h, y[n] + k3)

        y[n + 1] = y[n] + (k1 + 2 * k2 + 2 * k3 + k4) / 6
        x[n + 1] = x[n] + h

    return x, y

def initializeParams(x_max_, h,  x0, y0):
    n_max = int(x_max_ / h)  # numero de passos
    x = [None] * (n_max + 1)
    x[0] = x0
    y = [None] * (n_max + 1)
    y[0] = y0
    return n_max, x, y

if __name__ == '__main__':
    X_max = 1.0       # max valor em x
    h = 0.5         # passo em x
    x0 = 0.0
    y0 = 8.0

    n_max, x, y = initializeParams(X_max, h, x0, y0)
    print("X max = {}\nPasso = {}\nPassos = {}".format(X_max, h, n_max))
    sol_exata = 2 + 8 * np.exp(-0.5)
    print("Usando solução exata: Para x=1 => y= {}".format(sol_exata))
    for i in range(0, n_max+1):
        y[i] = 2 * x[i] + 8 * np.exp(-x[i]/2)
        if(i < n_max):
            x[i+1] = x[i] + h

    print("Usando equação diferencial exata:\nx = {}\ny = {}".format(x, y))
    plt.text(x[n_max], y[n_max], str(y[n_max]))
    plt.plot(x, y, label="Exata = " + str(y[n_max]))

    x0 = 0.0
    n_max, x, y = initializeParams(X_max, h, x0, y0)
    x, y = euler(n_max, h, x, y)
    print("Usando Euler: \nx = {}\ny = {}".format(x, y))
    plt.plot(x, y, label="Euller = " + str(y[n_max]))

    n_max, x, y = initializeParams(X_max, h, x0, y0)
    x, y = rk4(n_max, h, x, y)
    print("Usando Runge-Kuta de 4a ordem: \nx = {}\ny = {}".format(x, y))
    # plt.plot(x, y, label="RK4   = " + str(y[n_max]))
    plt.legend()
    plt.show()


import random
from termcolor import colored
import pandas as pd
import time
import numpy as np

def roll_dice(dice_size=6):

  roll = random.randint(1,dice_size)
  if roll == 1:
    print(f'You rolled a {roll}! Critical Fail')
  elif roll == dice_size:
    print(f'You rolled a {roll}! Critical Success!')
  else:
    print(f'You rolled a {roll}')
  return roll

def ludo():
  """
  This program mimics the ludo game.

  Will start with a very simple algorithm and improve it with time

  """
  print(colored("\n\nLUDO Game!!!\n", "blue", attrs=['bold']))

  num_players = int(input("Enter number of players: "))
  while num_players <2 or num_players>4:
    num_players = int(input("Enter number of players: "))

  # dice_size = int(input('How many sides are the dice? '))
  winning_score = int(input('What is your winning score? '))

  players = ["p_" + str(i+1) for i in range(0, num_players)]
  num = 0
  score_table = pd.DataFrame(columns = players)
  score_table.loc['score'] = 0
  score_table.loc[num, :] = 0
  # print(score_table)
  # print(players)

  while not any(i>=winning_score for i in score_table.loc['score']):
    num += 1
    score_list = list()
    score_table.loc['score'] = 0
    for i in range(0, len(players)):
      score_list.append(roll_dice())
      time.sleep(2)

    score_table.loc[num] = score_list
    score_table.loc['score']= score_table.sum(axis=0)
    # print("no winner")
    # print(score_table.loc['score'])
    # print(score_list)
    print(score_table)

  # check winner
  winner_s = score_table.loc['score'].ge(winning_score)
  winner_s = np.where(score_table.loc['score'].ge(winning_score), score_table.columns, '')
  winner_s = np.delete(winner_s, np.where(winner_s=='')).tolist()
  print(winner_s)
  print(len(winner_s))
  if len(winner_s) >=2:
    print("Yaay!, more than one winner")
    print('\n'.join(winner_s))
    gt_score = score_table.loc['score'].max()
    print(gt_score)
    print(f"Overall winner: {score_table.loc['score'].eq(gt_score).keys()}")
  else:
    print(f"Player {winner_s} wins!!!")

if __name__== "__main__":
  ludo()


import sys

from kafka import KafkaConsumer, KafkaProducer
import json

bootstrap_servers = 'localhost:9092'
consumer_topic = sys.argv[1]
producer_topic = sys.argv[2]

consumer = KafkaConsumer(
    consumer_topic,
    bootstrap_servers=bootstrap_servers,
    group_id='python_consumer'
)

producer = KafkaProducer(bootstrap_servers=bootstrap_servers)

for message in consumer:
    message_value = json.loads(message.value)
    program_id = message_value['ProgramId']
    loop_counter = message_value['LoopCounter']

    print(
        f"Python received message: Program ID={program_id}, Loop Counter={loop_counter}"
    )

    # Increase the loop counter
    loop_counter += 1

    # Create the response message
    response_message = {'ProgramId': program_id, 'LoopCounter': loop_counter}

    # Serialize the response message to JSON
    response_json = json.dumps(response_message)

    # Produce the response message to the response topic
    producer.send(producer_topic, value=response_json.encode())

    # Stop when the loop counter reaches 100
    if loop_counter >= 6:
        break

consumer.close()
producer.close()

print("python finished")


import torch
import torch.nn as nn

class MultiScaleLoss:
    """
    Applies multi-scale loss function, as done in MelGAN
    Inspired by https://github.com/seungwonpark/melgan/blob/master/model/multiscale.py
    """

    def __init__(self, loss_fn, num_scales=2):
        self.loss_fn = loss_fn
        self.downsample = nn.AvgPool1d(kernel_size=4, stride=2, padding=2)
        self.num_scales = num_scales

    def for_generator(self, real_audio, fake_audio):
        return self._get_loss(real_audio, fake_audio, self.loss_fn.for_generator)

    def for_discriminator(self, real_audio, fake_audio):
        return self._get_loss(real_audio, fake_audio, self.loss_fn.for_discriminator)

    def _get_loss(self, real_audio, fake_audio, loss_fn):
        loss = 0
        real = real_audio
        fake = fake_audio
        for _ in range(self.num_scales + 1):
            loss += loss_fn(real, fake)
            real = self.downsample(real)
            fake = self.downsample(fake)

        return loss / (self.num_scales + 1)


import json
import os
from datetime import datetime
from typing import Dict

from hummingbot import data_path
from hummingbot.connector.connector_base import ConnectorBase
from hummingbot.core.event.event_forwarder import SourceInfoEventForwarder
from hummingbot.core.event.events import OrderBookEvent, OrderBookTradeEvent
from hummingbot.strategy.script_strategy_base import ScriptStrategyBase

class DownloadTradesAndOrderBookSnapshots(ScriptStrategyBase):
    exchange = os.getenv("EXCHANGE", "binance_paper_trade")
    trading_pairs = os.getenv("TRADING_PAIRS", "ETH-USDT,BTC-USDT")
    depth = int(os.getenv("DEPTH", 50))
    trading_pairs = [pair for pair in trading_pairs.split(",")]
    last_dump_timestamp = 0
    time_between_csv_dumps = 10

    ob_temp_storage = {trading_pair: [] for trading_pair in trading_pairs}
    trades_temp_storage = {trading_pair: [] for trading_pair in trading_pairs}
    current_date = None
    ob_file_paths = {}
    trades_file_paths = {}
    markets = {exchange: set(trading_pairs)}
    subscribed_to_order_book_trade_event: bool = False

    def __init__(self, connectors: Dict[str, ConnectorBase]):
        super().__init__(connectors)
        self.create_order_book_and_trade_files()
        self.order_book_trade_event = SourceInfoEventForwarder(self._process_public_trade)

    def on_tick(self):
        if not self.subscribed_to_order_book_trade_event:
            self.subscribe_to_order_book_trade_event()
        self.check_and_replace_files()
        for trading_pair in self.trading_pairs:
            order_book_data = self.get_order_book_dict(self.exchange, trading_pair, self.depth)
            self.ob_temp_storage[trading_pair].append(order_book_data)
        if self.last_dump_timestamp < self.current_timestamp:
            self.dump_and_clean_temp_storage()

    def get_order_book_dict(self, exchange: str, trading_pair: str, depth: int = 50):
        order_book = self.connectors[exchange].get_order_book(trading_pair)
        snapshot = order_book.snapshot
        return {
            "ts": self.current_timestamp,
            "bids": snapshot[0].loc[:(depth - 1), ["price", "amount"]].values.tolist(),
            "asks": snapshot[1].loc[:(depth - 1), ["price", "amount"]].values.tolist(),
        }

    def dump_and_clean_temp_storage(self):
        for trading_pair, order_book_info in self.ob_temp_storage.items():
            file = self.ob_file_paths[trading_pair]
            json_strings = [json.dumps(obj) for obj in order_book_info]
            json_data = '\n'.join(json_strings)
            file.write(json_data)
            self.ob_temp_storage[trading_pair] = []
        for trading_pair, trades_info in self.trades_temp_storage.items():
            file = self.trades_file_paths[trading_pair]
            json_strings = [json.dumps(obj) for obj in trades_info]
            json_data = '\n'.join(json_strings)
            file.write(json_data)
            self.trades_temp_storage[trading_pair] = []
        self.last_dump_timestamp = self.current_timestamp + self.time_between_csv_dumps

    def check_and_replace_files(self):
        current_date = datetime.now().strftime("%Y-%m-%d")
        if current_date != self.current_date:
            for file in self.ob_file_paths.values():
                file.close()
            self.create_order_book_and_trade_files()

    def create_order_book_and_trade_files(self):
        self.current_date = datetime.now().strftime("%Y-%m-%d")
        self.ob_file_paths = {trading_pair: self.get_file(self.exchange, trading_pair, "order_book_snapshots", self.current_date) for
                              trading_pair in self.trading_pairs}
        self.trades_file_paths = {trading_pair: self.get_file(self.exchange, trading_pair, "trades", self.current_date) for
                                  trading_pair in self.trading_pairs}

    @staticmethod
    def get_file(exchange: str, trading_pair: str, source_type: str, current_date: str):
        file_path = data_path() + f"/{exchange}_{trading_pair}_{source_type}_{current_date}.txt"
        return open(file_path, "a")

    def _process_public_trade(self, event_tag: int, market: ConnectorBase, event: OrderBookTradeEvent):
        self.trades_temp_storage[event.trading_pair].append({
            "ts": event.timestamp,
            "price": event.price,
            "q_base": event.amount,
            "side": event.type.name.lower(),
        })

    def subscribe_to_order_book_trade_event(self):
        for market in self.connectors.values():
            for order_book in market.order_books.values():
                order_book.add_listener(OrderBookEvent.TradeEvent, self.order_book_trade_event)
        self.subscribed_to_order_book_trade_event = True


# rest_framework
from rest_framework.decorators import (api_view,permission_classes)
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

# Serializers
from .serializers import (
    postLikeSerializer,
    comentLikeSerializer,
    subComentLikeSerializer
)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def createLikeBySubComent(request,comentId,subComentId) -> (Response):
    subComentId = subComentId
    comentId = comentId

    return Response('Sub coment like')

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def createLikeByComent(request,comentId) -> (Response):
    data = {'comentId':comentId}

    serailizer = comentLikeSerializer(data=data)
    serailizer.is_valid(raise_exception=True)
    resultLike = serailizer.create_like(
        user=request.user,
        comentId=serailizer.data['comentId']
    )

    return Response(resultLike)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def createLikeByPost(request,postId) -> (Response):

    data = {'postId':postId}

    serailizerResult = postLikeSerializer(data=data)
    serailizerResult.is_valid(raise_exception=True)

    likePostResult = serailizerResult.create_like(
        user=request.user,
        postId=serailizerResult.data['postId']
    )

    return Response(likePostResult)


from ._base_metric import _BaseMetric
from .. import _timing
import numpy as np
from scipy.optimize import linear_sum_assignment
from copy import deepcopy
class OSPA2(_BaseMetric):
    def __init__(self):
        self.joint_names = ['head',
                            'right eye',
                            'left eye',
                            'right shoulder',
                            'neck',
                            'left shoulder',
                            'right elbow',
                            'left elbow',
                            'tailbone',
                            'right hand',
                            'right hip',
                            'left hip',
                            'left hand',
                            'right knee',
                            'left knee',
                            'right foot',
                            'left foot']
        self.n_joints = 17
        self.loss_fields = ['OSPA', 'OSPA_CARD', 'OSPA_LOC','OSPA_INVI',
                            'OSPA_OCCL', 'OSPA_VIS']
        self.occl_level = {0:'OSPA_INVI', 1:'OSPA_OCCL', 2:'OSPA_VIS', 3:'OSPA'}
        self.occl_level_avg = {0:'OSPA_INVI_AVG', 1:'OSPA_OCCL_AVG', 2:'OSPA_VIS_AVG'}
        self.fields = self.loss_fields
        self.summary_fields = self.loss_fields

        self.integer_fields = []
        self.integer_array_fields = []
        self.float_array_fields = []
        self.float_fields = self.loss_fields

    def eval_sequence(self, data):
        res = {}
        for field in self.fields:
            res[field] = 0

        keypoint_visibilities = data['keypoint_visibilities']
        # for occ_lvl in range(4):
            # if occ_lvl < 3:
            #     similarity_scores = deepcopy(data['oks_kpts_sims'])
            # else:
        per_kpt_sim = deepcopy(data['oks_kpts_sims'])
        similarity_scores = deepcopy(data['similarity_scores'])
        dist_sum = {i: np.zeros((data['num_gt_ids'], data['num_tracker_ids'])) for i in range(4)}
        dist_per_occl = {i: np.zeros((data['num_gt_ids'], data['num_tracker_ids'])) for i in range(4)}

        counts = np.zeros((data['num_gt_ids'], data['num_tracker_ids']))

        for t, (gt_ids_t, tracker_ids_t,), in enumerate(zip(data['gt_ids'], data['tracker_ids'])):
            if len(tracker_ids_t) == 0:
                continue
            for occ_lvl in range(4):
                if occ_lvl < 3:
                    mask = np.stack([keypoint_visibilities[t]==occ_lvl]*len(tracker_ids_t), axis=1)
                    kpts_sim_t = per_kpt_sim[t] * mask
                    dist = (1 - kpts_sim_t) * mask
                    dist = np.sum(dist,axis=-1)/np.maximum(1,np.sum(dist>0,axis=-1))
                    dist_t = np.zeros((data['num_gt_ids'], data['num_tracker_ids'],))

                    dist_t[gt_ids_t] = 1
                    dist_t[:, tracker_ids_t] = 1
                    dist_t[gt_ids_t[:, None], tracker_ids_t] = dist
                    dist_sum[occ_lvl] += dist_t

                else:
                    dist = 1 - similarity_scores[t]
                    dist_t = np.zeros((data['num_gt_ids'],data['num_tracker_ids'],))

                    dist_t[gt_ids_t] = 1
                    counts[gt_ids_t] += 1
                    dist_t[:,tracker_ids_t] = 1
                    counts[:,tracker_ids_t] += 1

                    dist_t[gt_ids_t[:,None],tracker_ids_t] = dist
                    counts[gt_ids_t[:,None],tracker_ids_t] -= 1
                    dist_sum[occ_lvl] += dist_t

        counts[counts == 0] = 1
        trk_dist = dist_sum[3] / counts

        match_rows, match_cols, = linear_sum_assignment(trk_dist)
        for occ_lvl in range(4):
            cost_per_occ = dist_sum[occ_lvl] / counts
            cost = np.sum(cost_per_occ[match_rows, match_cols])
            m=data['num_gt_ids']
            n=data['num_tracker_ids']
            ospa2 = np.power(((1 * np.absolute(m-n) + cost) / max(m,n)), 1)
            term1 = np.absolute(m-n) / max(m,n)
            term2 = cost / max(m,n)
            res[self.occl_level[occ_lvl]]=ospa2
        res['OSPA_CARD']=term1
        res['OSPA_LOC']=term2
        return res

    def combine_sequences(self, all_res):
        """Combines metrics across all sequences"""
        res = {}
        for field in self.loss_fields:
            res[field] = self._combine_average(all_res, field)
        return res

    @staticmethod
    def _combine_average(all_res, field):
        """Combine sequence results via sum"""
        tmp=[all_res[k][field] for k in all_res.keys()]
        return sum(tmp)/len(tmp)

    def combine_classes_class_averaged(self, all_res, ignore_empty_classes=None):
        """Combines metrics across all classes by averaging over the class values"""
        res = {}
        for field in self.loss_fields:
            res[field] = self._combine_sum(all_res, field)
        return res

    def combine_classes_det_averaged(self, all_res):
        """Combines metrics across all classes by averaging over the detection values"""
        res = {}
        for field in self.loss_fields:
            res[field] = self._combine_sum(all_res, field)
        return res


import numpy as np
import spacy
from sklearn.feature_extraction.text import CountVectorizer

nlp = spacy.load("en_core_web_sm")

string = 'Dr. Strange loves Pav Bhaji of Mumbai. Hulk loves Strange chaat of Delhi'

def stemming(word):
    return (word.lemma_)

def tokenize(text):
    sen = nlp(text)
    sentence = []
    for sent in sen.sents:
        for token in sent:
            sentence.append(token)
    return(sentence)

vectorizer = CountVectorizer()

def bag_of_words(sentences):
    X = vectorizer.fit_transform(sentences)
    print(vectorizer.get_feature_names_out())
    print(vectorizer.vocabulary_)
    bag_of_words_array = X.toarray()
    return (bag_of_words_array)


from app import app
from flask import Flask, render_template, request, redirect, url_for
import requests
import json
import os
import pandas as pd
from bs4 import BeautifulSoup
from app.utils import get_element, selectors

@app.route("/")
@app.route("/main")
def main():
    return render_template("main.html")

@app.route("/extraction", methods=['POST', 'GET'])
def extraction():
    if request.method == 'POST':
        url = f"https://www.ceneo.pl/{product_code}#tab=reviews"
        all_opinions = []
        while(url):
            print(url)
            response = requests.get(url)
            page_dom = BeautifulSoup(response.text, "html.parser")
            opinions = page_dom.select("div.js_product-review")
            for opinion in opinions:
                single_opinion = {}
                for key, value in selectors.items():
                    single_opinion[key] = get_element(opinion, *value)
                all_opinions.append(single_opinion)
            try:
                url = "https://www.ceneo.pl"+get_element(page_dom,"a.pagination__next","href")
            except TypeError:
                url = None
        if not os.path.exists("./app/data/opinions"):
            os.mkdir("./app/data/opinions")
        with open(f"./app/data/opinions/{product_code}.json", "w", encoding="UTF-8") as jf:
            json.dump(all_opinions, jf, indent=4, ensure_ascii=False)
    return render_template("extraction.html")

@app.route("/product_list")
def product_list():
    return render_template("p_list.html")

@app.route("/product")
def product():
    return render_template("product.html")


"""isogen4 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from apps.projects import views
from apps.api.views import task_collection

urlpatterns = [
    url(r'^$', views.index),
    url(r'^terminal/?$', views.terminal),
    url(r'^physics/?$', views.physics),
    url(r'^snippets/?$', views.bad_design),
    url(r'^soundcloud/?$', views.soundcloud),
    url(r'^tasks/([a-z0-9]+)?', task_collection),
    url(r'^projects/([a-z]+)/?$', views.projects),
    url(r'^share$', views.share),
]


from telegram.objects import TelegramObject, telegram_field as field

class User(TelegramObject):
    def __init__(self,
                 dct,
                 id,
                 is_bot,
                 first_name,
                 last_name=None,
                 username=None,
                 language_code=None,
                 **kwargs):
        super().__init__(dct)
        # required
        self.id = field(int, id, required=True)  # type: int
        self.is_bot = field(bool, is_bot, required=True)  # type: bool
        self.first_name = field(str, first_name, required=True)  # type: str
        # optional
        self.last_name = field(str, last_name)  # type: str
        self.username = field(str, username)  # type: str
        self.language_code = field(str, language_code)  # type: str


import torch
import torch.nn as nn
import torch.nn.functional as F

class Decoder(nn.Module):
    def __init__(self, num_inputs, hidden_dim, output_dim):
        super(Decoder, self).__init__()

        self.linear1 = nn.Linear(num_inputs, hidden_dim)
        self.linear2 = nn.Linear(hidden_dim, hidden_dim)
        self.linear3 = nn.Linear(hidden_dim, output_dim)

    def forward(self, state):
        x = F.relu(self.linear1(state))
        x = F.relu(self.linear2(x))
        x = self.linear3(x)
        return x


import json

data = {
    'no': 1,
    'name': 'Runoob',
    'url': 'http://www.runoob.com'
}

# -- dictionary to json
json_string = json.dumps(data) # {"no": 1, "name": "Runoob", "url": "http://www.runoob.com"}
print(json_string)

# -- json to dictionary
data = json.loads(json_string)
print(type(data))
print(data)
print('--- the data name = {0}'.format(data['name']))

"""
Hint:
    w：覆盖写入模式，写入后原本档案的内容会被覆盖掉。
    a：附加写入模式，写入的资料会附加在原本档案内容的后面。
"""
with open('myJson.txt', "a") as f:
    print(json.dumps(data), file=f)  # file参数代表资料要存入何处？
    # json.dump(data,f) #json.dump 用来写入档案用

with open('myJson.txt', "r") as f:
    #mydata = json.load(f)
    for i in f:
        mydata = json.loads(i)
        print(mydata)


import numpy as np
import pytest

from probnum import randprocs, randvars
from tests.test_randprocs.test_markov.test_discrete import test_linear_gaussian

class TestLTIGaussian(test_linear_gaussian.TestLinearGaussian):

    # Replacement for an __init__ in the pytest language. See:
    # https://stackoverflow.com/questions/21430900/py-test-skips-test-class-if-constructor-is-defined
    @pytest.fixture(autouse=True)
    def _setup(
        self,
        test_ndim,
        spdmat1,
        spdmat2,
        forw_impl_string_linear_gauss,
        backw_impl_string_linear_gauss,
    ):

        self.transition_matrix = spdmat1
        self.noise = randvars.Normal(mean=np.arange(test_ndim), cov=spdmat2)

        self.transition = randprocs.markov.discrete.LTIGaussian(
            transition_matrix=self.transition_matrix,
            noise=self.noise,
            forward_implementation=forw_impl_string_linear_gauss,
            backward_implementation=backw_impl_string_linear_gauss,
        )

        # Compatibility with superclass' test
        self.transition_matrix_fun = lambda t: self.transition_matrix
        self.noise_fun = lambda t: self.noise
        self.transition_fun = lambda t, x: self.transition_matrix @ x
        self.transition_fun_jacobian = lambda t, x: self.transition_matrix

    # Test access to system matrices

    def test_transition_matrix(self):
        received = self.transition.transition_matrix
        expected = self.transition_matrix
        np.testing.assert_allclose(received, expected)

    def test_noise(self):
        received = self.transition.noise
        expected = self.noise
        np.testing.assert_allclose(received.mean, expected.mean)
        np.testing.assert_allclose(received.cov, expected.cov)


import numpy as np
import torch
import torch.nn as nn
from scipy.optimize import linear_sum_assignment

from detrex.layers.box_ops import box_cxcywh_to_xyxy, generalized_box_iou

class GroupHungarianMatcher(nn.Module):
    """HugarianMatcher supports Group-DETR

    Args:
        cost_class (float): The relative weight of the classification error
            in the matching cost. Default: 1.
        cost_bbox (float): The relative weight of the L1 error of the bounding box
            coordinates in the matching cost. Default: 1.
        cost_giou (float): This is the relative weight of the giou loss of
            the bounding box in the matching cost. Default: 1.
    """

    def __init__(self, cost_class: float = 1, cost_bbox: float = 1, cost_giou: float = 1):
        super().__init__()
        self.cost_class = cost_class
        self.cost_bbox = cost_bbox
        self.cost_giou = cost_giou
        assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, "all costs cant be 0"

    @torch.no_grad()
    def forward(self, outputs, targets, group_nums=1):
        """Performs the matching
        Params:
            outputs: This is a dict that contains at least these entries:
                 "pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
                 "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
            targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:
                 "labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
                           objects in the target) containing the class labels
                 "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates
            group_nums: Number of groups used for matching.
        Returns:
            A list of size batch_size, containing tuples of (index_i, index_j) where:
                - index_i is the indices of the selected predictions (in order)
                - index_j is the indices of the corresponding selected targets (in order)
            For each batch element, it holds:
                len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
        """
        bs, num_queries = outputs["pred_logits"].shape[:2]

        # We flatten to compute the cost matrices in a batch
        out_prob = (
            outputs["pred_logits"].flatten(0, 1).sigmoid()
        )  # [batch_size * num_queries, num_classes]
        out_bbox = outputs["pred_boxes"].flatten(0, 1)  # [batch_size * num_queries, 4]

        # Also concat the target labels and boxes
        tgt_ids = torch.cat([v["labels"] for v in targets])
        tgt_bbox = torch.cat([v["boxes"] for v in targets])

        # Compute the classification cost.
        alpha = 0.25
        gamma = 2.0
        neg_cost_class = (1 - alpha) * (out_prob**gamma) * (-(1 - out_prob + 1e-8).log())
        pos_cost_class = alpha * ((1 - out_prob) ** gamma) * (-(out_prob + 1e-8).log())
        cost_class = pos_cost_class[:, tgt_ids] - neg_cost_class[:, tgt_ids]

        # Compute the L1 cost between boxes
        cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)

        # Compute the giou cost betwen boxes
        cost_giou = -generalized_box_iou(box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox))

        # Final cost matrix
        C = self.cost_bbox * cost_bbox + self.cost_class * cost_class + self.cost_giou * cost_giou
        C = C.view(bs, num_queries, -1).cpu()

        sizes = [len(v["boxes"]) for v in targets]
        indices = []
        g_num_queries = num_queries // group_nums
        C_list = C.split(g_num_queries, dim=1)
        for g_i in range(group_nums):
            C_g = C_list[g_i]
            indices_g = [linear_sum_assignment(c[i]) for i, c in enumerate(C_g.split(sizes, -1))]
            if g_i == 0:
                indices = indices_g
            else:
                indices = [
                    (
                        np.concatenate([indice1[0], indice2[0] + g_num_queries * g_i]),
                        np.concatenate([indice1[1], indice2[1]]),
                    )
                    for indice1, indice2 in zip(indices, indices_g)
                ]
        return [
            (torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64))
            for i, j in indices
        ]


# from distutils.command.config import config
from flask import Flask, jsonify, render_template, request
from predict_pune_model.utils import PuneHouse
import config

app = Flask(__name__)

@app.route('/')
def hello_flask():
    print("Welcome to Predict the price of house")
    return render_template("index.html")

@app.route('/predict_price', methods = ["POST","GET"])
def get_home_price():
    if request.method == "GET":
        print("We are using GET method")
        data = request.form
        print("Data-->",data)

        # size = eval(data['size'])
        # bath = eval(data['bath'])
        # balcony = eval(data['balcony'])
        # new_total_sqft = eval(data['new_total_sqft'])
        # area_type = data['area_type']
        # site_location = data['site_location']

        size = eval(request.args.get("size"))
        bath = eval(request.args.get("bath"))
        balcony = eval(request.args.get("balcony"))
        new_total_sqft = eval(request.args.get("new_total_sqft"))
        area_type = request.args.get("area_type")
        site_location = request.args.get("site_location")

        print("size,bath,balcony,new_total_sqft,area_type,site_location\n",size,bath,balcony,new_total_sqft,area_type,site_location)

        house_price = PuneHouse(size,bath,balcony,new_total_sqft,area_type,site_location)
        price = house_price.get_predicted_house_price()
        return render_template("index.html",prediction = price)

        # return jsonify({"Result": f"predicted price of pune house is {price} lac"})

    else:
        print("We are using POST method")

        size = eval(request.form.get("size"))
        bath = eval(request.form.get("bath"))
        balcony = eval(request.form.get("balcony"))
        new_total_sqft = eval(request.form.get("new_total_sqft"))
        area_type = request.form.get("area_type")
        site_location = request.form.get("site_location")

        print("size,bath,balcony,new_total_sqft,area_type,site_location\n",size,bath,balcony,new_total_sqft,area_type,site_location)

        house_price = PuneHouse(size,bath,balcony,new_total_sqft,area_type,site_location)
        price = house_price.get_predicted_house_price()

        return render_template("index.html",prediction = price)

if __name__ == "__main__":
    app.run(host = '0.0.0.0', port = config.PORT_NUMBER, debug =True)


import re
from datetime import datetime, timezone

import iso8601

from response_operations_ui.common.dates import localise_datetime

def format_short_name(short_name):
    """
    This regex function returns a pretty-printed short name value WITH spaces
    e.g. Sand&Gravel -> Sand & Gravel
    """
    return re.sub("(&)", r" \1 ", short_name)

def convert_events_to_new_format(events):
    formatted_events = {}
    for event in events:
        date_time_utc = iso8601.parse_date(event["timestamp"])
        localised_datetime = localise_datetime(date_time_utc)
        formatted_events[event["tag"]] = {
            "day": localised_datetime.strftime("%A"),
            "date": localised_datetime.strftime("%d %b %Y"),
            "month": localised_datetime.strftime("%m"),
            "time": localised_datetime.strftime("%H:%M"),
            "is_in_future": date_time_utc > iso8601.parse_date(datetime.now(timezone.utc).isoformat()),
            "event_status": event["eventStatus"],
        }
    return formatted_events

def get_collex_event_status(events):
    """
    Maps each event to relevant status
    :param events:
    :type events:
    :return: mapped status
    :rtype: Str
    """
    collex_event_status = None
    for event in events:
        if event["eventStatus"] == "RETRY":
            collex_event_status = "Retrying"
        if event["eventStatus"] == "FAILED":
            collex_event_status = "Failed"
        if event["eventStatus"] == "PROCESSING":
            collex_event_status = "Processing"
    return collex_event_status

def convert_event_list_to_dictionary(events):
    """
    This function converts a list of events, which are dicts, for a collection exercise into a dictionary where
    the key is the name of the event and the value is the timestamp.
    This can aid in finding the exact event you want without having to loop through the
    entire list to find the one you want.

    :param events: A list of events for a collection exercise
    :type events: list
    :raises KeyError: If the 'tag' or 'timestamp' keys aren't present in the list of dicts
    :return: A dictionary of events where the name of the events are the keys and the values are the timestamps
    :rtype: dict
    """
    if events is None:
        return {}
    return {event["tag"]: event["timestamp"] for event in events}

def map_collection_exercise_state(ce_state):
    return {
        "CREATED": "Created",
        "SCHEDULED": "Scheduled",
        "READY_FOR_REVIEW": "Ready for review",
        "FAILEDVALIDATION": "Ready for review",
        "EXECUTION_STARTED": "Setting ready for live",
        "VALIDATED": "Setting ready for live",
        "EXECUTED": "Setting ready for live",
        "READY_FOR_LIVE": "Ready for live",
        "LIVE": "Live",
        "ENDED": "Ended",
    }.get(ce_state, ce_state)

def map_ce_response_status(ce_response_status):
    return {
        "NOTSTARTED": "Not started",
        "INPROGRESS": "In progress",
        "COMPLETE": "Completed",
        "COMPLETEDBYPHONE": "Completed by phone",
        "NOLONGERREQUIRED": "No longer required",
    }.get(ce_response_status, ce_response_status)

def map_region(region):
    return "NI" if region == "YY" else "GB"

def get_display_text_for_event(event):
    """
    Takes an event from a collection exercise and returns a version of it that can be displayed to the user.
    If the string isn't found in the map, it just returns the string the function was given.

    :param event: A name of an event from a collection exercise
    :type event: str
    :return: A version of that event that can be displayed to the user
    """
    mapping = {
        "mps": "MPS (Main print selection)",
        "go_live": "Go live",
        "return_by": "Return by",
        "reminder": "First reminder",
        "reminder2": "Second reminder",
        "reminder3": "Third reminder",
        "nudge_email_0": "First nudge email",
        "nudge_email_1": "Second nudge email",
        "nudge_email_2": "Third nudge email",
        "nudge_email_3": "Fourth nudge email",
        "nudge_email_4": "Fifth nudge email",
        "exercise_end": "Exercise end",
    }
    return mapping.get(event, event)

def get_event_name(tag: str) -> str | None:
    event_names = {
        "mps": "Main print selection",
        "go_live": "Go Live",
        "return_by": "Return by",
        "exercise_end": "Exercise end",
        "reminder": "First reminder",
        "reminder2": "Second reminder",
        "reminder3": "Third reminder",
        "ref_period_start": "Reference period start date",
        "ref_period_end": "Reference period end date",
        "employment": "Employment date",
        "nudge_email_0": "Schedule nudge email",
        "nudge_email_1": "Schedule nudge email",
        "nudge_email_2": "Schedule nudge email",
        "nudge_email_3": "Schedule nudge email",
        "nudge_email_4": "Schedule nudge email",
    }
    return event_names.get(tag)


import os
import time
import boto3

AWS_s3_client = boto3.client('s3')
AWS_transcribe_client = boto3.client('transcribe')
BUCKETPATH = 'https://s3.amazonaws.com/s2bwavbucket/_dir/tmp.wav'

def transcribe(JOB_URL):
    try:
        response = AWS_transcribe_client.delete_transcription_job(
            TranscriptionJobName='speech2txt'
        )
        print('Delete Previous Job Status: ', response)
    except:
        print('No previous job found!')
    AWS_transcribe_client.start_transcription_job(
        TranscriptionJobName='speech2txt',
        Media={'MediaFileUri': JOB_URL},
        MediaFormat='wav',
        LanguageCode='en-US'
    )

    while True:
        status = AWS_transcribe_client.get_transcription_job(TranscriptionJobName='speech2txt')
        if status['TranscriptionJob']['TranscriptionJobStatus'] in ['COMPLETED', 'FAILED']:
            break
        print("Not ready yet...")
        time.sleep(1)
    return(status)

def process(path):
    open('_dir/aws_lock', 'a').close()
    AWS_s3_client.upload_file(path, 's2bwavbucket', path)
    print('NEWFILE')
    result = transcribe(BUCKETPATH)
    print('TRANSCRIPTION: ', result)
    os.remove('_dir/aws_lock')

while True:
    time.sleep(0.1)
    if 'check' in os.listdir('_dir') and os.path.isfile('_dir/gpio_on'):
        process('_dir/tmp.wav')
        os.remove('_dir/check')
        os.remove('_dir/tmp.wav')


import os
import pygame
from pygame import Surface
from data.exceptions import *

def load_image(name, colorkey=None) -> Surface:
    if not os.path.isfile(name):
        raise BadLoadImage(f"Файл с изображением {name} не найден")
    image = pygame.image.load(name)
    if colorkey is not None:
        image = image.convert()
        if colorkey == -1:
            colorkey = image.get_at((0, 0))
        image.set_colorkey(colorkey)
    else:
        try:
            image = image.convert_alpha()
            pass
        except pygame.error as e:
            print(e)
    return image


import cv2
import numpy as np

img = cv2.imread("ruleta.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

#VERDE
verde_bajo = np.array([50,100,100])
verde_alto = np.array([80,255, 255])

#MORADO
morado_bajo = np.array([140,255,100])
morado_alto = np.array([170,255, 255])

#AZUL
azul_bajo = np.array([100,50,50])
azul_alto = np.array([130,255, 255])

#AMARILLO
amarillo_bajo = np.array([20,50,50])
amarillo_alto = np.array([40, 255, 255])

#ROJO
redBajo1 = np.array([0, 100, 20])
redAlto1 = np.array([8, 255, 255])
redBajo2=np.array([175, 100, 20])
redAlto2=np.array([179, 255, 255])
maskRed1 = cv2.inRange(hsv, redBajo1, redAlto1)
maskRed2 = cv2.inRange(hsv, redBajo2, redAlto2)

mask_verde = cv2.inRange(hsv, verde_bajo, verde_alto)
mask_morado= cv2.inRange(hsv, morado_bajo,morado_alto)

mask_azul = cv2.inRange(hsv, azul_bajo, azul_alto)
mask_amarillo = cv2.inRange(hsv, amarillo_bajo, amarillo_alto)

mask_unionRojo = cv2.bitwise_or(maskRed1, maskRed2)

mask_unionMV = cv2.bitwise_or(mask_morado, mask_verde)
mask_unionAA = cv2.bitwise_or(mask_amarillo, mask_azul)
mask_unionMVAA = cv2.bitwise_or(mask_unionAA, mask_unionMV)
mask_union= cv2.bitwise_or(mask_unionMVAA,mask_unionRojo )
cv2.imshow("Original", img)
cv2.imshow("copia detectando colores", mask_union)
print("pulsa pa salir \n")
cv2.waitKey(0)
cv2.destroyAllWindows()


from measurement.base import base_measurement
from statistics import median

class median_absolute_scaled_error(base_measurement):

    def calculate(self, actual_set, forecasted_set):
        denominator = 0
        for x in range(1, len(actual_set)):
            denominator += abs(actual_set[x] - actual_set[x-1])
        denominator /= len(actual_set) - 1

        results = []
        for actual, forecasted in zip(actual_set, forecasted_set):
            results.append(abs(actual - forecasted) / denominator)

        return median(results) ** 0.5

    def get_name(self):
        return 'MdASE'


"""add_subcategoryId_to_offer

Revision ID: f8f80e3ca099
Revises: b59aa6de9662
Create Date: 2021-06-30 14:38:34.701860

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = "f8f80e3ca099"
down_revision = "b59aa6de9662"
branch_labels = None
depends_on = None

def upgrade():
    op.add_column("offer", sa.Column("subcategoryId", sa.Text(), nullable=True))

def downgrade():
    op.drop_column("offer", "subcategoryId")


import logging

from broker.brokers import Brokers
from broker_transaction_management_system.base_transaction_manager import BaseTransactionManager

class ZerodhaTransactionManager(BaseTransactionManager):

    def __init__(self) -> None:
        super().__init__(Brokers.ZERODHA)

    def test_connection(self):
        logging.info('%s: Going to test the broker connection',self.broker)
        kite = self.broker_handle
        try:
            profile = kite.profile()
            return profile
        except Exception as e:
            logging.info('%s Broker Connection failed: %s', self.broker, str(e))
            raise Exception(str(e))

    def get_orders(self):
        logging.info('%s: Going to fetch the user orders', self.broker)
        kite = self.broker_handle
        try:
            orders = kite.orders()
            return orders
        except Exception as e:
            logging.info('%s Failed to fetch the orders: %s',self.broker, str(e))
            raise Exception(str(e))

    def get_positions(self):
        logging.info('%s: Going to fetch the user positions', self.broker)
        kite = self.broker_handle
        try:
            positions = kite.positions()
            return positions
        except Exception as e:
            logging.info('%s Failed to fetch the positions: %s',self.broker, str(e))
            raise Exception(str(e))

    def get_holdings(self):
        logging.info('%s: Going to fetch the user holdings', self.broker)
        kite = self.broker_handle
        try:
            holdings = kite.holdings()
            return holdings
        except Exception as e:
            logging.info('%s Failed to fetch the holdings: %s',self.broker, str(e))
            raise Exception(str(e))


#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @IDE          :PyCharm
# @FileName     :AttendanceService
# @CreatTime    :2022/3/20 19:25
# @CreatUser    :DaneSun
# @Author       :孙智涵
import datetime
from django.db import transaction
from app.models.Attendance import AttendanceView,Attendance

def getAttendanceList(time):
    try:
        with transaction.atomic():
            if time == "today":
                today = datetime.datetime.now()
                tomorrow = today + datetime.timedelta(days=1)
                attendanceList = AttendanceView.objects.filter(start_time__gt = datetime.date(today.year, today.month, today.day)).filter(start_time__lt=datetime.date(tomorrow.year,tomorrow.month,tomorrow.day)).order_by("start_time").values()
                return 1,list(attendanceList)
            elif time == "all":
                attendanceList = AttendanceView.objects.all().order_by("start_time").values()
                return 1,list(attendanceList)
    except Exception as e:
        print(e)
        return 0,None

def getExceptAttendanceList(time):
    try:
        with transaction.atomic():
            if time == "today":
                today = datetime.datetime.now()
                tomorrow = today + datetime.timedelta(days=1)
                attendanceList = AttendanceView.objects.filter(start_time__gt = datetime.date(today.year, today.month, today.day)).filter(start_time__lt=datetime.date(tomorrow.year,tomorrow.month,tomorrow.day)).order_by("start_time")
                attendanceList = attendanceList.filter(tempture__gte = 37).values()
                return 1,list(attendanceList)
            elif time == "all":
                attendanceList = AttendanceView.objects.filter(tempture__gte = 37).order_by("start_time").values()
                return 1,list(attendanceList)
    except Exception as e:
        print(e)
        return 0,None
# 创建函数addAttendanceInfo，参数为uid，tempture
def addAttendanceInfo(uid,tempture):
    try:
        with transaction.atomic():
            attendance = AttendanceView(uid=uid,tempture=tempture)
            attendance.save()
            return 1,None
    except Exception as e:
        print(e)
        return 0,None

# 创建函数更新checkTempture,opertrator,
def updateCheckTempture(id,checkTempture,operator):
    try:
        with transaction.atomic():
            Attendance.objects.filter(id = id).update(checkTempture = checkTempture,operator = operator)
            return 1
    except Exception as e:
        print(e)
        return 0


from vkbottle_types.responses import prettyCards
from typing import Optional, Any, List
from .base_category import BaseCategory

class PrettyCardsCategory(BaseCategory):
    async def create(
        self,
        owner_id: int,
        photo: str,
        title: str,
        link: str,
        price: Optional[str] = None,
        price_old: Optional[str] = None,
        button: Optional[str] = None,
        **kwargs
    ) -> prettyCards.CreateResponseModel:
        """prettyCards.create method
        :param owner_id:
        :param photo:
        :param title:
        :param link:
        :param price:
        :param price_old:
        :param button:
        """

        params = self.get_set_params(locals())
        response = await self.api.request("prettyCards.create", params)
        model = prettyCards.CreateResponse
        return model(**response).response

    async def delete(
        self, owner_id: int, card_id: int, **kwargs
    ) -> prettyCards.DeleteResponseModel:
        """prettyCards.delete method
        :param owner_id:
        :param card_id:
        """

        params = self.get_set_params(locals())
        response = await self.api.request("prettyCards.delete", params)
        model = prettyCards.DeleteResponse
        return model(**response).response

    async def edit(
        self,
        owner_id: int,
        card_id: int,
        photo: Optional[str] = None,
        title: Optional[str] = None,
        link: Optional[str] = None,
        price: Optional[str] = None,
        price_old: Optional[str] = None,
        button: Optional[str] = None,
        **kwargs
    ) -> prettyCards.EditResponseModel:
        """prettyCards.edit method
        :param owner_id:
        :param card_id:
        :param photo:
        :param title:
        :param link:
        :param price:
        :param price_old:
        :param button:
        """

        params = self.get_set_params(locals())
        response = await self.api.request("prettyCards.edit", params)
        model = prettyCards.EditResponse
        return model(**response).response

    async def get(
        self,
        owner_id: int,
        offset: Optional[int] = None,
        count: Optional[int] = None,
        **kwargs
    ) -> prettyCards.GetResponseModel:
        """prettyCards.get method
        :param owner_id:
        :param offset:
        :param count:
        """

        params = self.get_set_params(locals())
        response = await self.api.request("prettyCards.get", params)
        model = prettyCards.GetResponse
        return model(**response).response

    async def get_by_id(
        self, owner_id: int, card_ids: List[int], **kwargs
    ) -> prettyCards.GetByIdResponseModel:
        """prettyCards.getById method
        :param owner_id:
        :param card_ids:
        """

        params = self.get_set_params(locals())
        response = await self.api.request("prettyCards.getById", params)
        model = prettyCards.GetByIdResponse
        return model(**response).response

    async def get_upload_url(self, **kwargs) -> prettyCards.GetUploadURLResponseModel:
        """prettyCards.getUploadURL method"""

        params = self.get_set_params(locals())
        response = await self.api.request("prettyCards.getUploadURL", params)
        model = prettyCards.GetUploadURLResponse
        return model(**response).response


from __future__ import annotations

import logging
from typing import TYPE_CHECKING

from discord.webhook.async_ import Webhook

if TYPE_CHECKING:
    from typing import Type, Optional

import aiohttp
import discord
import pytomlpp
import jishaku
from discord.ext import commands

from .webhook_logger import WebhookLogger

jishaku.Flags.FORCE_PAGINATOR = True
jishaku.Flags.NO_UNDERSCORE = True
jishaku.Flags.NO_DM_TRACEBACK = True

class Bot(commands.Bot):
    session: aiohttp.ClientSession
    context: Type[commands.Context]

    def __init__(self, session: aiohttp.ClientSession):
        self.logger = logging.getLogger(__name__)
        self.session = session
        self.config = pytomlpp.load("./config.toml")

        self.hook = Webhook.from_url(
            self.config["bot"]["keys"]["webhook"],
            session=session,
            bot_token=self.config["bot"]["keys"]["token"],
        )

        root = logging.getLogger()
        root.setLevel(logging.INFO)
        handler = logging.StreamHandler()
        handler.setFormatter(
            logging.Formatter("[%(asctime)s] [%(levelname)s] %(name)s: %(message)s")
        )
        root.addHandler(handler)
        handler = WebhookLogger(webhook=self.hook)
        handler.setFormatter(
            logging.Formatter("[%(asctime)s] [%(levelname)s] %(name)s: %(message)s")
        )
        root.addHandler(handler)

        intents = discord.Intents.default()
        intents.members = True

        super().__init__(
            **self.config["bot"]["config"],
            intents=intents,
            allowed_mentions=discord.AllowedMentions.none(),
        )

        for extension in self.config["bot"]["extensions"]:
            try:
                self.load_extension(extension)
            except commands.ExtensionError:
                self.logger.exception("failed to load extension `%s`", extension)
            else:
                self.logger.info("loaded extension `%s`", extension)

    async def get_context(
        self, message, *, cls: Optional[Type[commands.Context]] = None
    ):
        return await super().get_context(message, cls=cls or self.context)