import os
try:
    print(os.environ['PYTHONPATH'].split(os.pathsep))
finally:
    pass

try:
    import neoradio2
    print(neoradio2.__file__)
except Exception as ex:
    input(str(ex))
import time

if __name__ == "__main__":
    for device in neoradio2.find():
        print("Opening {} {}...".format(device.name, device.serial_str))
        handle = neoradio2.open(device)
        print("Opened {} {}...".format(device.name, device.serial_str))
        try:
            while True:
                neoradio2.chain_identify(handle)
                time.sleep(2)

                print("Requesting Settings {} {}...".format(device.name, device.serial_str))
                neoradio2.request_settings(handle, 0, 0xFF)
                time.sleep(0.5)
                for i in range(8):
                    if (1 << i) & banks:
                        print("Reading Settings {} {}...".format(device.name, device.serial_str))
                        settings = neoradio2.read_settings(handle, 0, i)
                        time.sleep(0.05)

                time.sleep(1)
        except Exception as ex:
            print(ex)
            time.sleep(1)
        finally:
            neoradio2.close(handle)
            input("Press any key to continue...")

"""
if __name__ == "__main__":
    for device in neoradio2.find():
        print("Opening {} {}...".format(device.name, device.serial_str))
        handle = neoradio2.open(device)
        print("Opened {} {}...".format(device.name, device.serial_str))
        try:
            while True:
                neoradio2.chain_identify(handle)
                s = time.time()

                #points = [-50,0,50,600]
                header = neoradio2.neoRADIO2frame_calHeader()
                header.channel = 0
                header.range = 0
                header.num_of_pts = 4
                e = time.time()
                msg = str(e-s)

                print("Requesting Calibration {} {}...".format(device.name, device.serial_str))
                neoradio2.request_calibration(handle, 0, 0xFF, header)
                time.sleep(0.5)
                neoradio2.request_calibration_points(handle, 0, 0xFF, header)
                time.sleep(0.5)
                for x in range(8):
                    print("Reading Calibration {} {}...".format(device.name, device.serial_str))
                    cal = neoradio2.read_calibration_array(handle, 0, x, header)
                    print(x, cal)
                    #time.sleep(0.05)
                    print("Reading Calibration Points {} {}...".format(device.name, device.serial_str))
                    cal_points = neoradio2.read_calibration_points_array(handle, 0, x, header)
                    print(x, cal_points)
                    time.sleep(0.05)

                time.sleep(1)
        except Exception as ex:
            print(ex)
            time.sleep(1)
        finally:
            neoradio2.close(handle)
            input("Press any key to continue...")

"""
"""
if __name__ == "__main__":
    for device in neoradio2.find():
        print("Opening {} {}...".format(device.name, device.serial_str))
        handle = neoradio2.open(device)
        print("Opened {} {}...".format(device.name, device.serial_str))
        try:
            while True:
                neoradio2.chain_identify(handle)
                s = time.time()

                points = [ -50, 0, 75, 650 ]
                cal = [ -48.67, 1.19, 75.72, 650.36 ]
                #points = [1,1,1,1]
                header = neoradio2.neoRADIO2frame_calHeader()
                header.channel = 0
                header.range = 0
                header.num_of_pts = len(points)
                e = time.time()
                msg = str(e-s)

                #neoradio2.request_calibration_info(handle, 0, 0xFF)
                for x in range(8):
                    print("Writing Calibration Points {} {}...".format(device.name, device.serial_str))
                    neoradio2.write_calibration_points(handle, 0, (1 << x), header, points)
                    print("Writing Calibration {} {}...".format(device.name, device.serial_str))
                    neoradio2.write_calibration(handle, 0, (1 << x), header, cal)
                    print("Storing Calibration {} {}...".format(device.name, device.serial_str))
                    neoradio2.store_calibration(handle, 0, (1 << x))
                    time.sleep(0.1)
                    is_stored = neoradio2.is_calibration_stored(handle, 0, x)
                    print("{} is cal stored: {}".format(x, is_stored))

                time.sleep(0.1)
        except Exception as ex:
            print(ex)
            time.sleep(1)
        finally:
            neoradio2.close(handle)
            input("Press any key to continue...")
"""

"""
if __name__ == "__main__":
    for device in neoradio2.find():
        print("Opening {} {}...".format(device.name, device.serial_str))
        handle = neoradio2.open(device)
        print("Opened {} {}...".format(device.name, device.serial_str))

        try:
            #print("Starting App {} {}...".format(device.name, device.serial_str))
            #neoradio2.app_start(handle, 0, 1)
            while True:
                s = time.time()
                print("Requesting Calibration {} {}...".format(device.name, device.serial_str))
                neoradio2.request_calibration_info(handle, 0, 1)
                e = time.time()
                msg = str(e-s)
                for x in range(8):
                    cal_info = neoradio2.read_calibration_info(handle, 0, x)
                    print("num_of_pts:    {}".format(cal_info.num_of_pts))
                    print("channel:       {}".format(cal_info.channel))
                    print("range:         {}".format(cal_info.range))
                    print("cal_is_valid:  {}".format(cal_info.cal_is_valid))
                time.sleep(0.1)
        except Exception as ex:
            print(ex)
            time.sleep(1)
        finally:
            neoradio2.close(handle)
            input("Press any key to continue...")
            #time.sleep(3)
        #time.sleep(10)
"""
"""
if __name__ == "__main__":
    for device in neoradio2.find():
        print("Opening {} {}...".format(device.name, device.serial_str))
        handle = neoradio2.open(device)
        print("Opened {} {}...".format(device.name, device.serial_str))

        neoradio2.app_start(handle, 0, 0xFF)

        try:
            while True:
                s = time.time()
                neoradio2.request_calibration(handle, 0, 0xFF)
                e = time.time()
                msg = str(e-s)
                for x in range(8):
                    value = neoradio2.read_calibration_array(handle, 0, x)
                    #try:
                    #    neoradio2.toggle_led(handle, 0, 0xFF, neoradio2.neoRADIO2_LEDMode.ON, 1, 255)
                    #except neoradio2.Exception as ex:
                    #    print(ex)
                    #value = neoradio2.get_manufacturer_date(handle, 0, x)
                    msg += ", {}".format(value)
                print(msg)
                time.sleep(0.1)
        except Exception as ex:
            print(ex)
            time.sleep(1)
        finally:
            neoradio2.close(handle)
            input("Press any key to continue...")
            #time.sleep(3)
        #time.sleep(10)
"""
"""
if __name__ == "__main__":
    for device in neoradio2.find():
        print("Opening {} {}...".format(device.name, device.serial_str))
        handle = neoradio2.open(device)
        print("Opened {} {}...".format(device.name, device.serial_str))

        neoradio2.app_start(handle, 0, 0xFF)

        try:
            while True:
                s = time.time()
                neoradio2.request_sensor_data(handle, 1, 0xFF)
                e = time.time()
                msg = str(e-s)
                for x in range(8):
                    value = neoradio2.read_sensor_float(handle, 1, x)
                    #try:
                    #    neoradio2.toggle_led(handle, 0, 0xFF, neoradio2.neoRADIO2_LEDMode.ON, 1, 255)
                    #except neoradio2.Exception as ex:
                    #    print(ex)
                    #value = neoradio2.get_manufacturer_date(handle, 0, x)
                    msg += ", {}".format(value)
                print(msg)
                time.sleep(0.1)
        except Exception as ex:
            print(ex)
            time.sleep(3)
        finally:
            neoradio2.close(handle)
            input("Press any key to continue...")
            time.sleep(3)
        time.sleep(10)
"""

"""
def get_bank_info(handle, device, bank):
    application_level = "Application" if neoradio2.app_is_started(handle, device, bank) else "Bootloader"
    month, day, year = neoradio2.get_manufacturer_date(handle, device, bank)
    fw_major, fw_minor = neoradio2.get_firmware_version(handle, device, bank)
    hw_major, hw_minor = neoradio2.get_hardware_revision(handle, device, bank)
    try:
        pcb_sn = neoradio2.get_pcbsn(handle, device, bank)
    except neoradio2.Exception as ex:
        pcb_sn = str(ex)

    print('\tFirmware State: {}'.format(application_level))
    print('\tManufacturer Date: {}/{}/{}'.format(month, day, year))
    print('\tFirmware Version: {}.{}'.format(fw_major, fw_minor))
    print('\tHardware Revision: {}.{}'.format(hw_major, hw_minor))
    print('\tFirmware State: {}'.format(application_level))
    print('\tPCB Serial Number: {}'.format(pcb_sn))

def get_sensor_info(handle, device, bank):
    value = neoradio2.read_sensor_float(handle, device, bank)
    print('\tSensor Value: {}'.format(value))

if __name__ == "__main__":
    import time
    input("Press any key to start...")
    try:
        devices = neoradio2.find()
        for device in devices:
            print("Opening {} {}...".format(device.name, device.serial_str))
            handle = neoradio2.open(device)
            print("Opened {} {}.".format(device.name, device.serial_str))

            print("Handle: {}".format(handle))

            #neoradio2.enter_bootloader(handle, 0, 2)
            #time.sleep(30)

            how_many_in_chain = neoradio2.get_chain_count(handle, True);
            print("%d devices in the chain" % how_many_in_chain)
            for d in range(how_many_in_chain):
                    print("Entering Bootloader on device {}...".format(d+1))
                    neoradio2.enter_bootloader(handle, d, 0xFF)
                    #time.sleep(0.5)

            for d in range(how_many_in_chain):
                for x in range(8):
                    print("Getting Info of device {} bank {}...".format(d+1, x+1))
                    get_bank_info(handle, d, x)

            for d in range(how_many_in_chain):
                    print("Entering Application on device {}...".format(d+1))
                    neoradio2.app_start(handle, d, 0xFF)

            for d in range(how_many_in_chain):
                neoradio2.request_pcbsn(handle, d, 0xFF)
                time.sleep(0.5)
                for x in range(8):

                    print("Getting Info of device {} bank {}...".format(d+1, x+1))
                    get_bank_info(handle, d, x)

                neoradio2.request_sensor_data(handle, d, 0xFF)
                time.sleep(0.5)
                for x in range(8):
                    print("Getting Sensor info of device {} bank {}...".format(d+1, x+1))
                    get_sensor_info(handle, d, x)

            for d in range(how_many_in_chain):
                print("Toggling LEDs on device {}...".format(d+1))
                for x in range(50):
                    neoradio2.toggle_led(handle, d, 0xFF, 50)
                    time.sleep(0.1)

            print("Closing {} {}...".format(device.name, device.serial_str))
            neoradio2.close(handle)
    except Exception as ex:
        print("ERROR: ", ex)
    finally:
        input("Press any key to continue...")

"""


import os

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

from pdas.data_utils import load_unified_helper, calc_mesh_bounds
from pdas.prom_utils import load_pod_basis

# mpl.rc("font", family="serif", size="10")
mpl.rc("font", family="sans", size="10")
mpl.rc("axes", labelsize="x-large")
mpl.rc("figure", facecolor="w")
mpl.rc("text", usetex=False)

def plot_contours(
    varplot,
    meshlist=None,
    datalist=None,
    meshdirs=None,
    datadirs=None,
    nvars=None,
    dataroot=None,
    merge_decomp=True,
    savefigs=False,
    outdir=None,
    plotlabels=None,
    nlevels=20,
    skiplevels=1,
    contourbounds=[None,None],
    draw_colorbar=True,
    plottime=10,
    plotskip=1,
    stopiter=-1,
    varlabel=None,
    plotbounds=False,
    bound_colors=None,
    figdim_base=[6.4, 4.8],
    vertical=True,
):

    # TODO: check dimension, slice if 3D

    # some input checking
    if stopiter != -1:
        assert stopiter >= 0
    if savefigs:
        assert outdir is not None
        if not os.path.isdir(outdir):
            os.mkdir(outdir)

    meshlist, datalist = load_unified_helper(
        meshlist,
        datalist,
        meshdirs,
        datadirs,
        nvars,
        dataroot,
        merge_decomp=merge_decomp,
    )
    ndata = len(datalist)

    if plotbounds:
        assert meshdirs is not None
        assert len(meshdirs) == ndata
        dom_bounds = calc_mesh_bounds(meshdirs)

    # prepping some lists
    if (plotlabels is None) or isinstance(plotlabels, str):
        plotlabels = [plotlabels] * ndata
    if not isinstance(plotskip, list):
        plotskip = [plotskip] * ndata
    assert len(plotskip) == ndata

    # set up time plot progression
    nt_min = np.infty
    for data_idx, data in enumerate(datalist):
        nt_min = min(nt_min, int(data.shape[-2] / plotskip[data_idx]))
    pause_time = plottime / nt_min

    # set up axes
    if vertical:
        fig, ax = plt.subplots(nrows=ndata, ncols=1)
        fig.set_figwidth(figdim_base[0])
        fig.set_figheight(figdim_base[1] * ndata)
    else:
        fig, ax = plt.subplots(nrows=1, ncols=ndata)
        fig.set_figwidth(figdim_base[0] * ndata)
        fig.set_figheight(figdim_base[1])
    if not isinstance(ax, np.ndarray):
         ax = np.array([ax])

    # set up contour parameters
    # assume first plot provides reasonable bounds, TODO: could improve
    if any([bound is None for bound in contourbounds]):
        contourbounds[0] = np.amin(datalist[0][:, :, :, varplot])
        contourbounds[1] = np.amax(datalist[0][:, :, :, varplot])
    levels = np.linspace(contourbounds[0], contourbounds[1], nlevels)
    ticks = levels[::skiplevels]

    itercounter = 0
    for t in range(0, nt_min):

        for plotnum in range(ndata):
            ax[plotnum].cla()

            # plot monolithic or merged decomposed solution
            if True:
                cf = ax[plotnum].contourf(
                    meshlist[plotnum][:, :, 0],
                    meshlist[plotnum][:, :, 1],
                    datalist[plotnum][:, :, t * plotskip[plotnum], varplot],
                    levels=levels,
                    extend="both",
                )

            # plot non-combined decomposed solution
            else:
                raise ValueError("Decomposed solution plotting not implemented")

            # plot domain boundaries
            if plotbounds:
                if dom_bounds[plotnum] is not None:
                    for dom_idx, bounds in enumerate(dom_bounds[plotnum]):
                        ax[plotnum].plot(
                            [bounds[0][0], bounds[0][1], bounds[0][1], bounds[0][0], bounds[0][0]],
                            [bounds[1][0], bounds[1][0], bounds[1][1], bounds[1][1], bounds[1][0]],
                            color=bound_colors[dom_idx],
                            linestyle="--",
                        )

            ax[plotnum].set_title(plotlabels[plotnum], fontsize=18)
            ax[plotnum].tick_params(axis='both', which='major', labelsize=14)

        fig.supxlabel('x', fontsize=16)
        fig.supylabel('y', fontsize=16)

        if (t == 0) and draw_colorbar:
            plt.tight_layout()
            if vertical:
                fig.subplots_adjust(right=0.8)
                cbar_ax = fig.add_axes([0.85, 0.1, 0.025, 0.8])
                cbar = fig.colorbar(cf, cax=cbar_ax, orientation="vertical")
            else:
                # fig.subplots_adjust(bottom=0.2)
                # cbar_ax = fig.add_axes([0.1, 0.1, 0.8, 0.025])
                fig.subplots_adjust(top=0.8)
                cbar_ax = fig.add_axes([0.1, 0.9, 0.8, 0.025])
                cbar = fig.colorbar(cf, cax=cbar_ax, orientation="horizontal")
                cbar.ax.xaxis.set_label_position('top')
            cbar.set_ticks(ticks)
            if varlabel is not None:
                cbar.set_label(varlabel)

        plt.pause(pause_time)
        if (stopiter != -1) and (itercounter >= stopiter):
            breakpoint()

        if savefigs:
            plt.savefig(os.path.join(outdir, f'fig_{t}.png'))

        itercounter += 1

    plt.show()
    print("Finished")

def plot_lines(
    ylist,
    outdir,
    outname,
    linecolors,
    xlist=None,
    varplot=None,
    linestyles="-",
    xlabel=None,
    ylabel=None,
    legendlabels=None,
    legendloc="best",
    xbounds=[None,None],
    ybounds=[None,None],
    figdim=[6.4, 4.8],
):
    """
    Inputs:
        - xlist: a (list of) 1D array(s)
        - ylist: a (list of) 1D/2D arrays. If 2D, must provide varplot, and
            assumed that trailing dimension is variable dimension
    """

    if not os.path.isdir(outdir):
        os.mkdir(outdir)

    if not isinstance(ylist, list):
        ylist = [ylist]
    nlines = len(ylist)

    if legendlabels is not None:
        assert len(legendlabels) == nlines

    # must have unique colors for plots
    if not isinstance(linecolors, list):
        linecolors = [linecolors]
    assert len(linecolors) >= nlines

    # non-unique linestyles fine
    if not isinstance(linestyles, list):
        linestyles = [linestyles] * nlines
    assert len(linestyles) >= nlines

    # get 1D arrays
    for yidx, yarr in enumerate(ylist):
        assert yarr.ndim <= 2

        if yarr.ndim == 2:
            assert varplot is not None
            ylist[yidx] = yarr[:, varplot]

    # check dimensions
    nvals_list = [y.shape[0] for y in ylist]
    allsame = all([val == nvals_list[0] for val in nvals_list])

    # handling certain edge cases for xlist
    # WARNING: may be incorrect if same number of samples but over different range
    #   Better to just be explicit
    if xlist is None:
        assert allsame
        xlist = [np.arange(ylist[0].shape[0])] * nlines
    else:
        if not isinstance(xlist, list):
            assert allsame
            xlist = [xlist] * nlines
    assert len(xlist) == nlines

    # plot
    fig, ax = plt.subplots(1, 1, figsize=figdim)
    for line_idx in range(nlines):

        ax.plot(
            xlist[line_idx], ylist[line_idx],
            color=linecolors[line_idx], linestyle=linestyles[line_idx]
        )

    if legendlabels is not None:
        ax.legend(legendlabels, loc=legendloc)
    ax.set_xlim(xbounds)
    ax.set_ylim(ybounds)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    plt.tight_layout()
    outfile = os.path.join(outdir, outname + ".png")
    print(f"Saving image to {outfile}")
    plt.savefig(outfile)

def plot_pod_res_energy(
    outdir,
    basis_dirs=None,
    svals=None,
    xlim=[None, None],
    plotcolors=["k", "r", "b"],
    linestyles=["-", "--", ":"],
    legend_labels=None,
    outsuff="",
):

    assert os.path.isdir(outdir)
    assert (basis_dirs is not None) != (svals is not None)

    if svals is None:
        if not isinstance(basis_dirs, list):
            basis_dirs = [basis_dirs]
        svals = []
        for basis_dir in basis_dirs:
            svals_in, = load_pod_basis(basis_dir, return_basis=False, return_svals=True)
            if isinstance(svals_in, list):
                svals += svals_in
            else:
                svals.append(svals_in.copy())
    else:
        if not isinstance(svals, list):
            assert isinstance(svals, np.ndarray)
            svals = [svals]

    nlines = len(svals)
    assert len(plotcolors) >= nlines
    assert len(linestyles) >= nlines
    if legend_labels is not None:
        assert len(legend_labels) == nlines

    fig, ax = plt.subplots(1, 1)
    for line_idx, sval_arr in enumerate(svals):

        # compute residual energy
        svals_sq = np.square(sval_arr)
        energy = 100* (1.0 - np.cumsum(svals_sq) / np.sum(svals_sq))

        nmodes = np.arange(1, energy.shape[0]+1)

        ax.semilogy(nmodes, energy, color=plotcolors[line_idx], linestyle=linestyles[line_idx])

    ax.set_xlim(xlim)
    ax.set_ylim([1e-2, 100])
    ax.set_xlabel("# POD modes")
    ax.tick_params(axis="both", which="major", labelsize=12)
    ax.set_ylabel("Residual POD energy, %")
    if legend_labels is not None:
        ax.legend(legend_labels, loc="upper right", fontsize=12)
    ax.set_yticks(
        [1e-2, 1e-1, 1, 10, 100],
        ["0.01", "0.1", "1", "10", "100"],
    )

    plt.tight_layout()
    outfile = os.path.join(outdir, f"S{outsuff}.png")
    print(f"Saving image to {outfile}")
    plt.savefig(outfile)


import torch

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

src_langs = ['en', 'de', 'it']
tgt_langs = ['de', 'it', 'en']

subset_size = 25000
batch_size = 32
num_epochs = 10
embed_dim = 256
hidden_dim = 512
n_layers = 2
dropout = 0.5
lr = 0.01

make_plots = False

train = True
evaluate = True


#! /bin/python
# -*- coding: utf-8 -*-  #
"""
Created 20161014

@author: wcgrizolli
"""

import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import itertools
#import sys

#sys.path.append('/home/grizolli/workspace/pythonWorkspace/wgTools/')

#import wgTools as wgt

import wavepy.utils as wpu

positions = np.array([-22.5, -7.5, -1.5, 0, 3, 12])

labels = ['33']
rho = [0.0]

for m, n in itertools.combinations(range(np.size(positions)), 2):
    print('mn: {:d}{:d} \t {:.3f}'.format(m, n, positions[m] - positions[n]))

    labels.append('{:d}{:d}'.format(m, n))
    rho.append(positions[m] - positions[n])

# %% convert to array

rho = np.abs(rho)
labels = np.array(labels)

# %%

labels = labels[np.argsort(rho)]
rho.sort()

# %%

print('mn \t j \t rho_j')

for j in range(np.size(rho)):

    print('{:s} \t {:d} \t {:.2f}'.format(labels[j], j, rho[j]))

# %%
sigma = 20e-6
#intensity = np.exp(-((positions-1)*1e-6/sigma)**2)

intensity = 1./(np.pi*sigma*(1.+(positions*1e-6-0.0)**2/sigma**2))

intensity /= np.max(intensity)

# %%

print('mn \t rho_j \t j \t S_j')
S_j = []
#for j in range(np.size(rho)):

for j in range(np.size(rho)):

    m = int(labels[j][0])
    n = int(labels[j][1])

    S_j.append(intensity[m]*intensity[n])

    print('mn: {:d}{:d} \t {:.2f} \t {:d} \t {:.3g}'.format(m, n, rho[j], j, intensity[m]*intensity[n]))

# %%

S_j = np.array(S_j)

c_j_over_c_0 = np.array([1e2, 0.8203, 0.7483, 0.595, 0.48, 0.5857, 0.3745, 0.3221])

max_j = c_j_over_c_0.shape[0]

# %%

plt.figure()
plt.plot(rho[:max_j], S_j[:max_j], '-ro', label='S_j')
plt.plot(rho[:max_j], c_j_over_c_0*1e-3, '-bo', label='c_j')
plt.legend()
plt.show()

# %%

plt.figure()
plt.plot(rho[:max_j], np.log10(c_j_over_c_0[:max_j]/S_j[:max_j]), '-go')
plt.show()


"""
Code from lucidrains https://github.com/lucidrains/phenaki-pytorch/blob/main/phenaki_pytorch/phenaki_pytorch.py and modified
"""

import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat

def exists(val):
    return val is not None

def default(val, d):
    return val if exists(val) else d

def log(t, eps=1e-20):
    return torch.log(t + eps)

def gumbel_noise(t):
    noise = torch.zeros_like(t).uniform_(0, 1)
    return -log(-log(noise))

def gumbel_sample(t, temperature=1., dim=-1):
    return ((t / max(temperature, 1e-10)) + gumbel_noise(t)).argmax(dim=dim)

def top_k(logits, thres=0.5):
    num_logits = logits.shape[-1]
    k = max(int((1 - thres) * num_logits), 1)
    val, ind = torch.topk(logits, k)
    probs = torch.full_like(logits, float('-inf'))
    probs.scatter_(1, ind, val)
    return probs

def FeedForward(dim, mult=4):
    inner_dim = int(mult * dim)
    return nn.Sequential(
        nn.LayerNorm(dim),
        nn.Linear(dim, inner_dim, bias=False),
        nn.GELU(),
        nn.Linear(inner_dim, dim, bias=False)
    )

class Attention(nn.Module):
    def __init__(
            self,
            dim,
            dim_context=None,
            dim_head=64,
            heads=8,
            causal=False,
            num_null_kv=2
    ):
        super().__init__()
        self.heads = heads
        self.causal = causal
        self.scale = dim_head ** -0.5
        inner_dim = dim_head * heads
        dim_context = default(dim_context, dim)

        self.norm = nn.LayerNorm(dim)

        self.null_kv = nn.Parameter(torch.randn(heads, 2 * num_null_kv, dim_head))

        self.to_q = nn.Linear(dim, inner_dim, bias=False)
        self.to_kv = nn.Linear(dim_context, inner_dim * 2, bias=False)
        self.to_out = nn.Linear(inner_dim, dim, bias=False)

    def forward(
            self,
            x,
            mask=None,
            context=None
    ):
        batch, device, dtype = x.shape[0], x.device, x.dtype

        kv_input = default(context, x)

        x = self.norm(x)

        q, k, v = self.to_q(x), *self.to_kv(kv_input).chunk(2, dim=-1)

        q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h=self.heads), (q, k, v))

        q = q * self.scale

        nk, nv = repeat(self.null_kv, 'h (n r) d -> b h n r d', b=batch, r=2).unbind(dim=-2)

        k = torch.cat((nk, k), dim=-2)
        v = torch.cat((nv, v), dim=-2)

        sim = einsum('b h i d, b h j d -> b h i j', q, k)

        i, j = sim.shape[-2:]

        if exists(mask):
            mask = F.pad(mask, (j - mask.shape[-1], 0), value=True)
            mask = rearrange(mask, 'b j -> b 1 1 j')
            sim = sim.masked_fill(~mask, -torch.finfo(sim.dtype).max)

        if self.causal:
            causal_mask = torch.ones((i, j), device=device, dtype=torch.bool).triu(j - i + 1)
            sim = sim.masked_fill(causal_mask, -torch.finfo(sim.dtype).max)

        attn = sim.softmax(dim=-1)

        out = einsum('b h i j, b h j d -> b h i d', attn, v)

        out = rearrange(out, 'b h n d -> b n (h d)')
        return self.to_out(out)

class Transformer(nn.Module):
    def __init__(
            self,
            dim,
            *,
            depth,
            dim_context=None,
            causal=False,
            dim_head=64,
            heads=8,
            ff_mult=4,
            attn_num_null_kv=2,
            has_cross_attn=False
    ):
        super().__init__()
        self.layers = nn.ModuleList([])

        for _ in range(depth):
            self.layers.append(nn.ModuleList([
                Attention(dim=dim, dim_head=dim_head, heads=heads, causal=causal),
                Attention(dim=dim, dim_head=dim_head, dim_context=dim_context, heads=heads, causal=False,
                          num_null_kv=attn_num_null_kv) if has_cross_attn else None,
                FeedForward(dim=dim, mult=ff_mult)
            ]))

        self.norm_out = nn.LayerNorm(dim)

    def forward(self, x, context=None, mask=None):

        for self_attn, cross_attn, ff in self.layers:
            x = self_attn(x) + x

            if exists(cross_attn) and exists(context):
                x = cross_attn(x, context=context, mask=None) + x

            x = ff(x) + x

        return self.norm_out(x)

class MaskGit(nn.Module):
    def __init__(
            self,
            *,
            dim,
            num_tokens,
            max_seq_len,
            **kwargs
    ):
        super().__init__()
        self.mask_id = num_tokens

        self.token_emb = nn.Embedding(num_tokens + 1, dim)  # last token is used as mask_id
        self.pos_emb = nn.Embedding(max_seq_len, dim)

        self.transformer = Transformer(
            dim=dim,
            attn_num_null_kv=2,
            has_cross_attn=True,
            **kwargs
        )

        self.to_logits = nn.Linear(dim, num_tokens)

        self.loss_fn = nn.CrossEntropyLoss(label_smoothing=0.1)

    def gamma(self, r):
        return (r * torch.pi / 2).cos()

    def add_noise(self, x, r):
        r = self.gamma(r)[:, None]
        mask = torch.bernoulli(r * torch.ones_like(x))
        mask = mask.round().bool()
        x = x * (~mask) + self.mask_id * mask
        return x, mask

    def forward(self, x, text_cond=None, **kwargs):
        b, n = x.shape

        x = self.token_emb(x)
        x = self.pos_emb(torch.arange(n, device=x.device)) + x

        x = self.transformer(x, text_cond, **kwargs)

        return self.to_logits(x)

    def loss(self, pred, video_indices, mask):
        acc = (pred.permute(0, 2, 1).argmax(1) == video_indices).float().mean()
        video_indices = video_indices[mask]  # 839
        # video_indices = video_indices.flatten()
        mask = mask.flatten()  # 1536
        pred = pred.view(-1, pred.shape[-1])[mask]  # 839x1024
        # pred = pred.view(-1, pred.shape[-1])  # 839x1024
        return self.loss_fn(pred, video_indices), acc

class MaskGitTrainWrapper(nn.Module):
    def __init__(
            self,
            maskgit,
            *,
            steps
    ):
        super().__init__()
        self.maskgit = maskgit
        self.mask_id = maskgit.mask_id

        self.steps = steps

    def forward(self, x, **kwargs):
        batch, seq, device = *x.shape, x.device

        self.maskgit.train()

        rand_step = torch.randint(0, self.steps, (1,), device=device)
        num_tokens_mask = (seq * torch.cos(rand_step * math.pi * 0.5 / self.steps)).round().long().clamp(
            min=1)  # cosine schedule was best

        _, indices = torch.randn((batch, seq), device=device).topk(num_tokens_mask.item(), dim=-1)
        mask = torch.zeros((batch, seq), device=device).scatter(1, indices, 1.).bool()

        masked_input = torch.where(mask, self.mask_id, x)

        logits = self.maskgit(masked_input, **kwargs)

        loss = F.cross_entropy(logits[mask], x[mask])
        return loss

class Phenaki(nn.Module):
    def __init__(
            self,
            *,
            maskgit: MaskGit,
            steps=18,  # 18 is the ideal steps with token critic
            sample_temperature=0.,
            text_embed_dim=None,
            cond_drop_prob=0.25,
            max_text_len=128
    ):
        super().__init__()

        self.maskgit = maskgit
        self.mask_id = maskgit.mask_id
        self.maskgit_trainer = MaskGitTrainWrapper(maskgit, steps=steps)

        # sampling

        self.steps = steps
        self.sample_temperature = sample_temperature

        assert cond_drop_prob > 0.
        self.cond_drop_prob = cond_drop_prob  # classifier free guidance for transformers - @crowsonkb

    @torch.no_grad()
    def sample( self, *, text, num_frames, cond_scale=3., starting_temperature=0.9, noise_K=1.):
        device = next(self.parameters()).device
        num_tokens = self.cvivit.num_tokens_per_frames(num_frames)

        with torch.no_grad():
            text_embeds = self.encode_texts([text], output_device=device)
            text_mask = torch.any(text_embeds != 0, dim=-1)

        shape = (1, num_tokens)

        video_token_ids = torch.full(shape, self.mask_id, device=device)
        mask = torch.ones(shape, device=device, dtype=torch.bool)

        scores = None

        for step in range(self.steps):
            is_first_step = step == 0
            is_last_step = step == (self.steps - 1)

            steps_til_x0 = self.steps - (step + 1)

            if not is_first_step and exists(scores):
                time = torch.full((1,), step / self.steps, device=device)
                num_tokens_mask = (num_tokens * torch.cos(time * math.pi * 0.5)).round().long().clamp(min=1)

                _, indices = scores.topk(num_tokens_mask.item(), dim=-1)
                mask = torch.zeros(shape, device=device).scatter(1, indices, 1).bool()

            video_token_ids = torch.where(mask, self.mask_id, video_token_ids)

            logits = self.maskgit.forward_with_cond_scale(
                video_token_ids,
                context=text_embeds,
                mask=text_mask,
                cond_scale=cond_scale
            )

            temperature = starting_temperature * (step / steps_til_x0)
            pred_video_ids = gumbel_sample(logits, temperature=temperature)

            video_token_ids = torch.where(mask, pred_video_ids, video_token_ids)

            if not is_last_step:
                scores = logits.gather(2, rearrange(pred_video_ids, '... -> ... 1'))
                scores = 1 - rearrange(scores, '... 1 -> ...')
                scores = torch.where(mask, scores, -1e4)

        video = self.cvivit.decode_from_codebook_indices(video_token_ids)
        return video

if __name__ == '__main__':
    # m = MaskGit(dim=2048, num_tokens=1024, max_seq_len=1536, depth=32, dim_context=512, heads=32)  # paper version
    m = MaskGit(dim=1224, num_tokens=8192, max_seq_len=1536, depth=22, dim_context=512, heads=22)  # 6 x 16 x 16
    # print(sum([p.numel() for p in m.parameters()]))
    for name, p in m.named_parameters():
        print(name)
        print(p.shape)
    # x = torch.randint(low=0, high=8192, size=(6, 16, 16)).view(1, -1)
    # text_cond = torch.randn(1, 10, 512)
    # print(m(x, text_cond).shape)


l=[1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6]

ls=set(l)
print(ls)

low=[]
high=[]

for i in ls:
    count=l.count(i)
    low.append(l.index(i))
    high.append(l.index(i)+count-1)

l=set(low)
h=set(high)

lh=list(zip(l,h))

lss=list(ls)

res=list(zip(lss,lh))

print("set is {}".format(res))


# utilities
import re
import numpy as np
import pandas as pd
import nltk
# plotting
import seaborn as sns
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# nltk
from nltk.stem import WordNetLemmatizer
# sklearn
from sklearn.svm import LinearSVC
from sklearn.naive_bayes import BernoulliNB
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import confusion_matrix, classification_report
from nltk.tokenize import RegexpTokenizer
from sklearn import preprocessing

#Sentiment finder
from textblob import TextBlob
# Importing the dataset
##DATASET_COLUMNS=['ids','date','user','text']
#DATASET_ENCODING = "ISO-8859-1"
df = pd.read_csv('cleaned_superbowl_halftime_tweets.csv')

df.tweet = df.tweet.astype(str)
df.drop(columns=['Unnamed: 0.1', 'Unnamed: 0'], inplace=True)

df['polarity'] = df.apply(lambda x: TextBlob(x['tweet']).sentiment.polarity, axis=1)
df['tweet']=df['tweet'].str.lower()

tokenizer = RegexpTokenizer(r'\w+')
df['tweet'] = df['tweet'].apply(tokenizer.tokenize)
#print(df['tweet'].head())

st = nltk.PorterStemmer()
def stemming_on_text(data):
    text = [st.stem(word) for word in data]
    return data

df['tweet']= df['tweet'].apply(lambda x: stemming_on_text(x))
print(df['tweet'].head())

lm = nltk.WordNetLemmatizer()
def lemmatizer_on_text(data):
    text = [lm.lemmatize(word) for word in data]
    return data

df['tweet'] = df['tweet'].apply(lambda x: lemmatizer_on_text(x))
print(df['tweet'].head())

tweet_list = df['tweet']
df["tweet"] = df["tweet"].astype(str)

X=df.tweet
y=df.polarity

X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.05, random_state =26105111)
print(X_train.dtype)
vectoriser = TfidfVectorizer(ngram_range=(1,2), max_features=500000)

vectoriser.fit(X_train)
print('No. of feature_words: ', len(vectoriser.get_feature_names()))

X_train = vectoriser.transform(X_train)
X_test  = vectoriser.transform(X_test)

def model_Evaluate(model):
    # Predict values for Test dataset
    y_pred = model.predict(X_test)
    # Print the evaluation metrics for the dataset.
    print(classification_report(y_test, y_pred))
    # Compute and plot the Confusion matrix
    cf_matrix = confusion_matrix(y_test, y_pred)
    categories = ['Negative','Positive']
    group_names = ['True Neg','False Pos', 'False Neg','True Pos']
    group_percentages = ['{0:.2%}'.format(value) for value in cf_matrix.flatten() / np.sum(cf_matrix)]
    labels = [f'{v1}n{v2}' for v1, v2 in zip(group_names,group_percentages)]
    labels = np.asarray(labels).reshape(2,2)
    sns.heatmap(cf_matrix, annot = labels, cmap = 'Blues',fmt = '',
    xticklabels = categories, yticklabels = categories)
    plt.xlabel("Predicted values", fontdict = {'size':14}, labelpad = 10)
    plt.ylabel("Actual values" , fontdict = {'size':14}, labelpad = 10)
    plt.title ("Confusion Matrix", fontdict = {'size':18}, pad = 20)

print("X TRAIN DTYPE",X_train.dtype)
print("Y TRAIN DTYPE",y_train.dtype)
lab_enc = preprocessing.LabelEncoder()
training_scores_encoded = lab_enc.fit_transform(y_train)
LRmodel = LogisticRegression(C = 2, max_iter = 1000, n_jobs=-1)
LRmodel.fit(X_train, training_scores_encoded)
model_Evaluate(LRmodel)
y_pred3 = LRmodel.predict(X_test)


from collections import deque
import sys

read = sys.stdin.readline

for _ in range(int(read())):
    command = read().rstrip()
    n = read().rstrip()
    nums = read().rstrip()[1:-1].split(',')
    R = False
    e_flag = False

    nums = deque(nums)
    if n == '0':
        nums = deque()
    for s in command:
        if s == 'R':
            if R: R = False
            else: R = True
        else:
            if not nums:
                print('error')
                e_flag = True
                break
            if R:
                nums.pop()
            else:
                nums.popleft()
    if not e_flag:
        if R:
            nums = reversed(nums)
        print('[' + ','.join(nums) + ']')


import pandas as pd
import os

pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

# 합칠 종목
code = '090430'

# 저장할 경로
savepath = 'D:/project/rltrader-master/data/c/'

# 파일 불러오기
path1 = 'D:/project/rltrader-master/data/raw/ohlcv/ohlcv_{}.csv'.format(code)            # 시고저종
file1 = pd.read_csv(path1)

path2 = 'D:/project/rltrader-master/data/raw/priceperhour_pre/pph_{}.csv'.format(code)   # 시간별가격
file2 = pd.read_csv(path2)

path3 = 'D:/project/rltrader-master/data/raw/investor/inv_{}.csv'.format(code)           # 투자주체
file3 = pd.read_csv(path3, encoding='cp949')

path4 = 'D:/project/rltrader-master/data/raw/GSO.csv'                                    # 금은원유가격
file4 = pd.read_csv(path4)

# 전처리 : 중복컬럼 제거 및 컬럼명 변경
file1 = file1[file1.columns.difference(['time'])]
file3 = file3[file3.columns.difference(['close'])]
file3 = file3.rename({'개인':'individual',
                      '외국인':'foreign',
                      '국가,지자체':'government',
                      '금융투자':'financial',
                      '기관계':'institutional',
                      '기타금융':'otherFinancial',
                      '기타법인':'legal',
                      '기타외인':'otherForeign',
                      '보험':'insurance',
                      '연기금':'pensionFund',
                      '은행':'bank',
                      '투신':'investment'}, axis='columns')

# 파일 합치기
final = pd.merge(file1, file2, how='inner', on='date')
final = pd.merge(final, file3, how='inner', on='date')
final = pd.merge(final, file4, how='inner', on='date')

# 정렬 및 저장
final.sort_values(by=['date'], ascending=True, inplace=True)
final = final[['date', 'open', 'high', 'low', 'close', 'volume',
               'p9', 'p10', 'p11', 'p12', 'p13', 'p14', 'p15',
               'individual', 'foreign', 'institutional', 'financial', 'insurance', 'investment', 'bank', 'otherFinancial', 'pensionFund', 'government', 'legal', 'otherForeign',
               'Gold', 'Silver', 'Oil']]
final.to_csv(savepath + '{}.csv'.format(code), index=False, encoding='cp949')
print(final)


from typing import Any, List
from .constants._sync_mode import ASYNC
import random
from ..native import make_native_object

import sys
matx = sys.modules['matx']

class _SolarizeOpImpl:
    """ SolarizeOp Impl """

    def __init__(self,
                 device: Any,
                 threshold: float = 128.0,
                 prob: float = 1.1) -> None:
        self.op: matx.NativeObject = make_native_object(
            "VisionSolarizeGeneralOp", device())
        self.prob: float = prob
        self.threshold: float = threshold

    def __call__(self,
                 images: List[matx.runtime.NDArray],
                 threshold: List[float] = [],
                 sync: int = ASYNC) -> List[matx.runtime.NDArray]:
        batch_size: int = len(images)
        if len(threshold) != 0 and len(threshold) != batch_size:
            assert False, "The length of threshold should be 0 or equal to input images"
        if len(threshold) == 0:
            threshold = [self.threshold for _ in range(batch_size)]
        if self.prob >= 1.0:
            return self.op.process(images, threshold, sync)
        for i in range(batch_size):
            if random.random() >= self.prob:
                threshold[i] = 256.0
        return self.op.process(images, threshold, sync)

class SolarizeOp:
    """ Apply solarization on images. i.e. invert the pixel value if the value is above the given threshold.
    """

    def __init__(self,
                 device: Any,
                 threshold: float = 128.0,
                 prob: float = 1.1) -> None:
        """ Initialize SolarizeOp

        Args:
            device (Any) : the matx device used for the operation
            threshold (float, optional): solarization threshold for all images, 128 by default.
            prob (float, optional): probability for solarization on each image. Apply on all by default.
        """
        self.op_impl: _SolarizeOpImpl = matx.script(_SolarizeOpImpl)(device=device,
                                                                     threshold=threshold,
                                                                     prob=prob)

    def __call__(self,
                 images: List[matx.runtime.NDArray],
                 threshold: List[float] = [],
                 sync: int = ASYNC) -> List[matx.runtime.NDArray]:
        """ Apply solarization on images. Only support uint8 images

        Args:
            images (List[matx.runtime.NDArray]): target images.
            threshold (List[float], optional): solarization threshold for each image. If not given the threshold for op initialization would be used.
            sync (int, optional): sync mode after calculating the output. when device is cpu, the params makes no difference.
                                    ASYNC -- If device is GPU, the whole calculation process is asynchronous.
                                    SYNC -- If device is GPU, the whole calculation will be blocked until this operation is finished.
                                    SYNC_CPU -- If device is GPU, the whole calculation will be blocked until this operation is finished, and the corresponding CPU array would be created and returned.
                                  Defaults to ASYNC.

        Example:

        >>> import cv2
        >>> import matx
        >>> from matx.vision import SolarizeOp

        >>> # Get origin_image.jpeg from https://github.com/bytedance/matxscript/tree/main/test/data/origin_image.jpeg
        >>> image = cv2.imread("./origin_image.jpeg")
        >>> device_id = 0
        >>> device_str = "gpu:{}".format(device_id)
        >>> device = matx.Device(device_str)
        >>> # Create a list of ndarrays for batch images
        >>> batch_size = 3
        >>> nds = [matx.array.from_numpy(image, device_str) for _ in range(batch_size)]
        >>> threshold = [80, 160, 240]

        >>> op = SolarizeOp(device)
        >>> ret = op(nds, threshold)
        """
        return self.op_impl(images, threshold, sync)


import math

import torch
import torch.nn as nn

from fairseq.models import FairseqEncoder

from sightseq.modules.features_getter import ConvFeaturesGetter

# output dimensionality for supported architectures
OUTPUT_DIM = {
    'resnet18': 512,
    'resnet34': 512,
    'resnet50': 2048,
    'resnet101': 2048,
    'resnet152': 2048,
    'densenet_cifar': 342,
    'densenet121': 512,
    'densenet161': 2208,
    'densenet169': 1664,
    'densenet201': 1920,
    'mobilenet_v2': 1280,
}

class TextRecognitionEncoder(FairseqEncoder):
    """Text Recognition encoder."""
    def __init__(self, args):
        super(FairseqEncoder, self).__init__()
        self.embed_dim = OUTPUT_DIM[args.backbone]
        self.features = ConvFeaturesGetter(args.backbone, args.pretrained)
        self.avgpool = nn.AdaptiveAvgPool2d((1, None))

        self.embed_positions = PositionalEncoding(
            embedding_dim=self.embed_dim,
            num_embeddings=self.max_positions(),
        ) if not args.no_token_positional_embeddings else None

        self.decoder_need_rnn = not args.no_token_rnn
        if self.decoder_need_rnn:
            hidden_size = args.decoder_hidden_size

            init_layers = args.decoder_layers
            if args.decoder_bidirectional:
                init_layers *= 2

            self.init_hidden_w = nn.Parameter(
                torch.rand(init_layers, self.embed_dim, hidden_size)
            )  # init_layers x embed_dim x hidden_size
            self.init_hidden_b = nn.Parameter(
                torch.rand(init_layers, 1, hidden_size)
            )  # init_layers x 1 x hidden_size
            self.init_cell_w = nn.Parameter(torch.rand_like(self.init_hidden_w))
            self.init_cell_b = nn.Parameter(torch.rand_like(self.init_hidden_b))

    def forward(self, src_tokens):
        """
        Args:
            src_tokens (Tensor): tokens in the source src_tokens of shape
                `(bsz, channel, img_h, img_w)`

        Returns:
            dict:
                - **encoder_out** (Tensor): the last encoder layer's output of
                  shape `(src_len, bsz, embed_dim)`
        """
        # src_tokens -> features
        x = self.features(src_tokens)  # bsz x embed_dim x H' x W', where W' stands for `seq_len`
        # features -> pool -> flatten
        x = self.avgpool(x)
        x = x.permute(3, 0, 1, 2).view(x.size(3), x.size(0), -1)  # seq_len x bsz x embed_dim

        final_hiddens, final_cells = None, None

        if self.decoder_need_rnn:
            final_hiddens, final_cells = self.init_hidden(x)

        if self.embed_positions is not None:
            x += self.embed_positions(x)

        return {
            'encoder_out': (x, final_hiddens, final_cells),
            'encoder_padding_mask': None,
        }

    def reorder_encoder_out(self, encoder_out, new_order):
        encoder_out['encoder_out'] = tuple(
            eo.index_select(1, new_order)
            for eo in encoder_out['encoder_out']
        )
        if encoder_out['encoder_padding_mask'] is not None:
            encoder_out['encoder_padding_mask'] = \
                encoder_out['encoder_padding_mask'].index_select(1, new_order)
        return encoder_out

    def init_hidden(self, x):
        mean = torch.mean(x, dim=0)  # bsz x embed_dim

        h0 = mean @ self.init_hidden_w + self.init_hidden_b  # init_layers x bsz x hidden_size
        h0 = torch.tanh(h0)

        c0 = mean @ self.init_cell_w + self.init_cell_b  # init_layers x bsz x hidden_size
        c0 = torch.tanh(c0)

        return (h0, c0)

    def max_positions(self):
        """Maximum sequence length supported by the encoder."""
        return 128

class PositionalEncoding(nn.Module):
    "Implement the PE function."
    def __init__(self, embedding_dim, num_embeddings=128):
        super().__init__()

        # Compute the positional encodings once in log space.
        pe = torch.zeros(num_embeddings, embedding_dim)  # embed_num x embed_dim
        position = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(1)
        emb = math.log(10000.0) / embedding_dim
        emb = torch.exp(torch.arange(0, embedding_dim, 2, dtype=torch.float) * -emb)
        pe[:, 0::2] = torch.sin(position * emb)
        pe[:, 1::2] = torch.cos(position * emb)
        self.register_buffer('pe', pe)

    def forward(self, x):
        out = self.pe[:x.size(0)]  # seq_len x embed_dim
        out = out.unsqueeze(1)
        out = out.expand_as(x)
        return out


import os
import subprocess as subp
from sys import executable

from pyrogram import filters
from pyrogram.enums import ChatType
# from pyrogram.errors import RPCError
from pyrogram.types import (CallbackQuery, InlineKeyboardButton,
                            InlineKeyboardMarkup, Message)

from configs import *
# from extra import *
from help import *
from Powers import *

pre = PREFIX_HANDLER
CT = ChatType

from pyrogram.types import ChatMemberUpdated

grp = [-1001752851548]

channel = list(
    set(CHANNEL + grp)
)

sudoer = []

SUDOER = list(
    set(
        [int(OWNER_ID)] + sudoer + SUDO
    )
)

default = [-1001752851548]

yus = []

@psy.on_message(filters.command(["restart", "update"], pre))
async def restart_the_bot(c:psy,m:Message):
    if m.from_user.id not in [1355478165,5301411431,1344569458]:
        await m.reply_text("NONONONONONONO")
        return
    try:
        cmds = m.command
        await m.reply_text(f"Restarting{' and updating ' if cmds[0] == 'update' else ' '}the bot...\nType `/ping` after few minutes")
        if cmds[0] == "update":
            try:
                out = subp.check_output(["git", "pull"]).decode("UTF-8")
                if "Already up to date." in str(out):
                    return await m.reply_text("Its already up-to date!")
                await m.reply_text(f"```{out}```")
            except Exception as e:
                return await m.reply_text(str(e))
            m = await m.reply_text("**Updated with main branch, restarting now.**")
        os.execvp(executable, [executable, "-m", "Powers"])
    except Exception as e:
        await m.reply_text(f"Failed to restart the bot due to\n{e}")
        return

async def pic_sender():
    for OwO in yus:
        caption = OwO["caption"]
        path = OwO["file"]
        if len(OwO) == 3:
            chat_id = OwO["id"]
            x = await psy.send_photo(chat_id, path, caption)
            await x.reply_document(path)
            os.remove(path)
        else:
            if not default:
                for chat_id in channel:
                    if caption:
                        x = await psy.send_photo(chat_id, path, caption)
                        await x.reply_document(path)
                        return
                    x = await psy.send_photo(chat_id, path)
                    await x.reply_document(path)
                    os.remove(path)
            chat_id = default[0]
            if caption:
                x = await psy.send_photo(chat_id, path, caption)
                await x.reply_document(path)
                os.remove(path)
            x = await psy.send_photo(chat_id, path)
            await x.reply_document(path)
    yus.clear()
    return

@psy.on_message(filters.command(["start"], pre))
async def start(_, m: Message):
    me = await psy.get_me()
    BOT_ID = me.id
    BOT_NAME = me.first_name
    BOT_USERNAME = me.username
    if m.chat.type != CT.PRIVATE:
        await m.reply_text(
            "I am alive",
            reply_markup=InlineKeyboardMarkup(
                [
                    [
                        InlineKeyboardButton(
                        "Switch to pm",
                        url=f"https://t.me/{BOT_USERNAME}?start=start_start",
                        ),
                    ],
                ],
            )
        )
        return
    else:
        if len(m.text.split()) > 1:
            help_option = (m.text.split(None, 1)[1]).lower()
            if help_option.split("_")[1] == "help":
                await psy.send_message(
                    m.chat.id,
                    "What do you want to see",
                    reply_markup=help_kb,
                )
                return
            elif help_option.split("_")[1] == "start":
                await psy.send_message(
                    m.chat.id,
                    "Forward me any media or message I will forward to the targeted chat.\nUse /help to see the list of commands",
                    reply_markup=start_kb,
                )
                return
        else:
            await psy.send_message(
                m.chat.id,
                "Forward me any media or message I will forward to the targeted chat.\nUse /help to see the list of commands",
                reply_markup=start_kb,
            )
            return

@psy.on_message(filters.command(["help"], pre))
async def help(_, m: Message):
    me = await psy.get_me()
    BOT_ID = me.id
    BOT_NAME = me.first_name
    BOT_USERNAME = me.username
    if m.chat.type != CT.PRIVATE:
        await m.reply_text(
            "What do u want to know",
            reply_markup=InlineKeyboardMarkup(
                [
                    [
                        InlineKeyboardButton(
                        "Help",
                        url=f"t.me/{BOT_USERNAME}?start=start_help",
                        ),
                    ],
                ],
            )
        )
    else:
        await psy.send_message(
            m.chat.id,
            "What do you want to see",
            reply_markup=help_kb,
        )
    return

@psy.on_message(filters.command(["addchannel"], pre))
async def addchannel(_, m: Message):
    if m.from_user.id not in SUDOER:
        return await m.reply_text("You can't do that")
    try:
        splited = m.text.split(None,1)[1]
        c_id = int(splited)
    except Exception:
        c_id = int(m.chat.id)
        if m.chat.type == CT.PRIVATE:
            return await m.reply_text("**USAGE:**\n`/addchannel <channel id>`")
        x = await m.reply_text(f"Either no chat id is provided or provided arg is not int type.\nAdding current chat ({c_id}) to list")
    channel.append(c_id)
    x.delete()
    return await m.reply_text(f"Added `{c_id}` in the Channel list")

@psy.on_message(filters.command(["rmchannel", "removechannel"], pre))
async def rmchannel(_, m: Message):
    if m.from_user.id not in SUDOER:
        return await m.reply_text("You can't do that")
    try:
        splited = m.text.split(None, 1)[1]
        c_id = int(splited)
    except Exception:
        if splited.lower() == "all":
            x = await m.reply_text("Clearing all channel id from list")
            channel.clear()
            x.delete()
            return await m.reply_text("Done")
        c_id = int(m.chat.id)
        if m.chat.type == CT.PRIVATE:
            return await m.reply_text("**USAGE:**\n`/rmchannel <channel id> / all`")
        x = await m.reply_text(f"Either no chat id is provided or provided arg is not int type.\nRemoveing current chat ({c_id}) from list")
    if c_id in channel:
        channel.remove(c_id)
        x.delete()
        return await m.reply_text(f"Removed `{c_id}` from the channel list")
    return await m.reply_text(f"{c_id} is not in the list. How am I supposed to remove it?")

@psy.on_message(filters.command(["addsudo", "appendsudo"], pre))
async def addsudo(_, m: Message):
    if m.from_user.id != OWNER_ID:
        return await m.reply_text("You can't do that")
    splited = m.text.split(None, 1)
    replied = m.reply_to_message
    if len(splited) != 2 and not replied:
        return await m.reply_text("**USAGE:** `/addsudo` <user id>")
    if (len(splited)==2) and not replied:
        try:
            u_id = int(splited[1])
        except Exception:
            return await m.reply_text("**USAGE:** `/addsudo` <user id>")
    elif replied and not (len(splited)==2):
        try:
            u_id = int(replied.from_user.id)
        except Exception:
            return await m.reply_text("**USAGE:** `/addsudo` <user id>")
    else:
        return await m.reply_text("Either reply to a user or pass user id don't do both thing at once")
    SUDOER.append(u_id)
    return await m.reply_text(f"Added `{u_id}` in sudoer list")

@psy.on_message(filters.command(["rmsudo", "removesudo"], pre))
async def rmsudo(_, m: Message):
    if m.from_user.id != OWNER_ID:
        return await m.reply_text("You can't do that")
    splited = m.text.split(None, 1)
    replied = m.reply_to_message
    if len(splited) != 2 and replied:
        return await m.reply_text("**USAGE:** `/rmsudo` <user id>")
    if splited:
        try:
            if splited not in SUDOER:
                return await m.reply_text("User is not a sudoer")
            u_id = int(splited[1])
        except Exception:
            if splited.lower() == "all":
                x = await m.reply_text("Clearing all channel id from list")
                channel.clear()
                x.delete()
                return await m.reply_text("Done")
            return await m.reply_text("**USAGE:** `/rmsudo` <user id>")
    if replied:
        try:
            if replied.from_user.id not in SUDOER:
                return await m.reply_text("User is not a sudoer")
            u_id = int(replied.from_user.id)
        except Exception:
            return await m.reply_text("**USAGE:** `/rmsudo` <user id>")
    SUDOER.remove(u_id)
    return await m.reply_text(f"Removed `{u_id}` from sudoer list")

@psy.on_message(filters.command(["forwardto", "fto"], pre) & filters.text)
async def forwardto(_, m: Message):
    if m.from_user.id not in SUDOER:
        return await m.reply_text("You can't do that")
    splited = m.text.split(None, 1)
    replied = m.reply_to_message
    if len(splited) != 2 and not replied:
        return await m.reply_text("**USAGE:** `/forwardto` <channel id>\n**REPLY TO A MESSAGE**")
    me = await psy.get_me()
    BOT_ID = me.id
    BOT_NAME = me.first_name
    BOT_USERNAME = me.username
    try:
        c_id = int(splited[1])
    except Exception:
        if splited[1].startswith("@"):
            c_id = splited[1]
        elif "t.me" in splited[1]:
            li = splited[1].split("/")[-1]
            if not li:
                li = splited[1].split("/")[-2]
            if not li.endswith("t.me"):
                c_id = li
            else:
                c_id = li.split("/")[-1].split(".")[0]
        return await m.reply_text("**USAGE:** `/forwardto` <channel id>")
    z = replied
    await psy.forward_messages(c_id,m.chat.id,z.id)
    return

@psy.on_message(filters.command(["channels", "sudos", "default"], pre))
async def channel_sudo(_, m: Message):
    if len(m.text.split()) != 1:
        return await m.reply_text("Do /help to get help")
    try:
        if m.text.lower() == "/channels":
            ch = [str(i) for i in channel]
            if not ch:
              return await m.reply_text("No channel is added use `/addchannel` to add one")
            req = ", ".join(ch)
            return await m.reply_text(f"Here is the list of channel:\n`{req}`")
        elif m.text.lower() == "/default":
          if not default:
            return await m.reply_text("No default channel is set use `/apdefault` to add one")
          return await m.reply_text(f"The Default chat is `{default[0]}`")
        else:
            sudoers = [str(sudo) for sudo in SUDOER]
            if not sudoers:
              return await m.reply_text("No sudoers are added use `/addsudo` to add one")
            req = ", ".join(sudoers)
            return await m.reply_text(f"Here is the list of channel:\n`{req}`")
    except Exception as e:
        return await m.reply_text(f"Got an error:\n{e}")

@psy.on_message(filters.command(["apdefault"], pre))
async def add_default(_, m: Message):
    if m.from_user.id not in SUDOER:
        return await m.reply_text("You can't do that")
    try:
        splited = m.text.split(None,1)[1]
        c_id = int(splited)
    except IndexError:
        c_id = int(m.chat.id)
        if m.chat.type == CT.PRIVATE:
            return await m.reply_text("**USAGE:**\n`/apdefault <channel id>`")
    except Exception as e:
        return await m.reply_text(f"Got an error:\n{e}")
    x = await m.reply_text(f"Either no chat id is provided or provided arg is not int type.\nAdding current chat ({c_id}) as default")
    default.clear()
    default.append(c_id)
    x.delete()
    return await m.reply_text(f"Added `{c_id}` as default channel")

@psy.on_message(filters.command(["rmdefault"], pre))
async def rm_default(_, m: Message):
    if m.from_user.id not in SUDOER:
        return await m.reply_text("You can't do that")
    try:
        if m.chat.type == CT.PRIVATE:
            return await m.reply_text("**USAGE:**\n`/rmdefault <channel id>`")
        x = await m.reply_text(f"Clearing default channel.")
        default.clear()
        x.delete()
        return await m.reply_text("Cleared default channel")
    except Exception as e:
        return await m.reply_text(f"Got an error:\n{e}")

@psy.on_message(filters.command(["send", "upload"], pre))
async def pic_uploader(_, m: Message):
    if m.from_user.id not in SUDOER:
        return await m.reply_text("You can't do that")
    if not yus:
        return await m.reply_text("No file to upload.\nSee help to know more")
    try:
      x = await m.reply_text("Uploading in process..")
      await pic_sender()
      await x.delete()
      await m.reply_text("Successfully uploaded the files")
      return
    except Exception as e:
        return await m.reply_text(f"Got an error:\n{e}")

@psy.on_message(filters.private & filters.media)
async def forwarder(_, m: Message):
    # me = await psy.get_me()
    # BOT_ID = me.id
    if m.from_user.id not in SUDOER:
        return
    elif m.from_user.id in SUDOER:
        me = await psy.get_me()
        BOT_ID = me.id
        BOT_NAME = me.first_name
        BOT_USERNAME = me.username
        if not bool(m.photo or m.document or m.video):
            return await m.reply_text("Send photo or document or video")
        if m.caption:
            caption = m.caption
        size, f_id = await size_fetcher(m)
        try:
            if round(size) > 10:
                file = f_id
                to_dwl = False
            else:
                file = await m.download()
                to_dwl = True
        except Exception as e:
            return await m.reply_text(f"Got an error:\n{e}")
        if not file:
            return await m.reply_text("I can't download that!")
        if to_dwl:
            fsplit = file.replace("\\","/").split("/")
            name = fsplit[-1]
            path = file.replace("\\","/").strip(name)
            os.rename(file, f"{path}@{BOT_USERNAME}_{name}")
            file = f"{path}@{BOT_USERNAME}_{name}"
        if m.caption:
            splited = caption.split()[-1]
            try:
                c_id = int(splited)
                caption = caption.strip(str(c_id))
                if m.photo or m.document.mime_type.split("/")[0]=="image":
                    yus.append({"file":file, "id": c_id, "caption": caption})
                    return await m.reply_text("Done!")
                elif m.document:
                    await psy.send_document(c_id, file, caption=caption)
                    os.remove(file)
                    return await m.reply_text("Done!")
                elif m.video:
                    await psy.send_video(c_id, file, caption=caption)
                    os.remove(file)
                    return await m.reply_text("Done!")
            except Exception:
                pass
        try:
            if not default:
                channel = list(set(channel))
                for c_id in channel:
                    if m.photo or file.endswith(exe):
                        if m.caption:
                            yus.append({"file":file, "caption": caption})
                        elif not m.caption:
                            yus.append({"file":file, "caption": False})
                        return await m.reply_text("Done!")
                    elif m.document:
                        if m.caption:
                            await psy.send_document(c_id, file, caption=caption)
                        elif not m.caption:
                                await psy.send_document(c_id, file)
                        return await m.reply_text("Done!")
                    elif m.video:
                        if m.caption:
                            await psy.send_video(c_id, file, caption=caption)
                        elif not m.caption:
                            await psy.send_video(c_id, file)
                        return await m.reply_text("Done!")
                    if to_dwl and not (m.photo or file.endswith(exe)):
                        os.remove(file)
            c_id = default[0]
            if m.photo or file.endswith(exe):
                if m.caption:
                    yus.append({"file":file, "caption": caption})
                elif not m.caption:
                    yus.append({"file":file, "caption": False})
                return await m.reply_text("Done!")
            elif m.document:
                if m.caption:
                    await psy.send_document(c_id, file, caption=caption)
                elif not m.caption:
                    await psy.send_document(c_id, file)
                return await m.reply_text("Done!")
            elif m.video:
                if m.caption:
                    await psy.send_video(c_id, file, caption=caption)
                elif not m.caption:
                    await psy.send_video(c_id, file)
            if to_dwl and not (m.photo or file.endswith(exe)):
                os.remove(file)
                return await m.reply_text("Done!")
        except Exception as e:
            os.remove(file)
            return await m.reply_text(f"Got an error:\n{e}")
    else:

        return

@psy.on_callback_query(filters.regex("^help_lao"),69)
async def help_lelo_guyz(_,q: CallbackQuery):
    data = q.data.split("_")
    typo = data[-1]
    if typo == "back":
        await q.edit_message_text(
            "What do you want to see",
            reply_markup=help_kb
        )
        return
    elif typo == "bc":
        await q.edit_message_text(
            helpmsg2,
            reply_markup=help_kb2
        )
        return
    elif typo == "re":
        if q.from_user.id not in SUDOER:
            await q.answer("Not for you give 500 stars on repo to convert it into free4all cmd",True)
            return
        await q.edit_message_text(
            helpmsg1,
            reply_markup=help_kb2
        )
        return

@psy.on_callback_query(group=0)
async def callbacks(_,q: CallbackQuery):
    try:
        data = q.data
        if data == "close":
            await q.message.delete()
            await q.answer("Closed")
            return
        elif data == "help":
            await q.edit_message_text(
                "What do you want to see",
                reply_markup=help_kb
            )
            await q.answer("Help")
            return
        elif data == "back":
            await q.edit_message_text(
                "Forward me any media or message I will forward to the targeted chat.\nUse /help to see the list of commands",
                reply_markup=start_kb
            )
            return await q.answer("Back")
    except Exception as e:
        c_id = q.message.chat.id
        await q.message.delete()
        return await psy.send_message(
            c_id,
            f"Got an error while handeling the callback quer:\n{e}")

async def size_fetcher(m: Message):
    """Return the file size in mb's and id"""
    if m.video:
        size = m.video.file_size
        id = m.video.file_id
    elif m.document:
        size = m.document.file_size
        id = m.document.file_id
    elif m.photo:
        size = m.photo.file_size
        id = m.photo.file_id
    x = (size/1024)/1024
    return x, id


import wave
import threading
from time import sleep
import pyaudio
import numpy as np
#import eyeD3
import sys

CHUNK = 1024

if len(sys.argv) < 2:
    print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
    sys.exit(-1)

wf = wave.open(sys.argv[1], 'rb')

p = pyaudio.PyAudio()

stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True)

data = wf.readframes(CHUNK)

while data != '':
    #stream.write(data)
    data = wf.readframes(CHUNK)
    eq_data = np.fromstring(data,dtype=np.int16)
    peak=np.average(np.abs(eq_data))*2
    bars="#"*int(50*peak/2**16)
    print("%05d %s"%(peak,bars))

stream.stop_stream()
stream.close()

p.terminate()


"""
Learn to navigate to a URL using Selenium

DISCLAIMER: This code is aimed at Selenium BEGINNERS
For more advanced tutorials and to learn how Qxf2 writes GUI automation, please visit our:
a) Our GUI automation guides: http://qxf2.com/gui-automation-diy
b) Other GitHub repos: https://github.com/qxf2

AUTHOR: Avinash Shetty
Contact: avinash@qxf2.com

SCOPE:
1) Launch Firefox Driver
2) Navigate to Qxf2 Tutorial page
3) Check the page title
4) Close the browser
"""
from selenium import webdriver

# Create an instance of Firefox WebDriver
browser = webdriver.Firefox()

# KEY POINT: The driver.get method will navigate to a page given by the URL
browser.get('http://qxf2.com/selenium-tutorial-main')

# Check if the title of the page is proper
if(browser.title=="Qxf2 Services: Selenium training main"):
    print ("Success: Qxf2 Tutorial page launched successfully")
else:
    print ("Failed: Qxf2 Tutorial page Title is incorrect")

# Quit the browser window
browser.quit()


#!/usr/bin/python
# coding: utf-8

from OpenGL.GL import *
import numpy

'''
頂点配列

====
属性
====
* 位置
'''
class VertexArray(object):
    def __init__(self, vertices):
        self.vertices=vertices

    def __str__(self):
        return "<VertexArray %d>" % len(self.vertices)

    def draw(self):
        # 位置属性
        glEnableClientState(GL_VERTEX_ARRAY)
        glVertexPointer(3, GL_FLOAT, 0, self.vertices)
        # 描画
        glDrawArrays(GL_TRIANGLES, 0, len(self.vertices))
        # 後始末
        glDisableClientState(GL_VERTEX_ARRAY)

'''
頂点配列

====
属性
====
* 位置
* UV
'''
class VertexArrayWithUV(object):
    def __init__(self, vertices, uvarray):
        self.vertices=vertices
        self.uvarray=uvarray

    def __str__(self):
        return "<VertexArrayWithUV %d>" % len(self.vertices)

    def draw(self):
        # 位置属性
        glEnableClientState(GL_VERTEX_ARRAY)
        glVertexPointer(3, GL_FLOAT, 0, self.vertices)
        # UV属性
        glEnableClientState(GL_TEXTURE_COORD_ARRAY)
        glTexCoordPointer(2, GL_FLOAT, 0, self.uvarray)
        # 描画
        triangle_count=int(len(self.vertices)/3)
        glDrawArrays(GL_TRIANGLES, 0, triangle_count)
        # 後始末
        glDisableClientState(GL_TEXTURE_COORD_ARRAY)
        glDisableClientState(GL_VERTEX_ARRAY)

    def get_boundingbox(self):
        vertices_size=len(self.vertices)
        if(vertices_size==0):
            return ([0, 0, 0], [0, 0, 0])
        def vertex_gen_factory():
            for i in range(0, vertices_size, 3):
                yield [
                        self.vertices[i],
                        self.vertices[i+1],
                        self.vertices[i+2]
                        ]
        vertex_gen=vertex_gen_factory()
        v=next(vertex_gen)
        max_v=v[:]
        min_v=v[:]
        for v in vertex_gen:
            min_v[0]=min(min_v[0], v[0])
            min_v[1]=min(min_v[1], v[1])
            min_v[2]=min(min_v[2], v[2])
            max_v[0]=max(max_v[0], v[0])
            max_v[1]=max(max_v[1], v[1])
            max_v[2]=max(max_v[2], v[2])
        return (min_v, max_v)

'''
インデックス参照頂点配列

====
属性
====
* 位置
* UV
'''
class IndexedVertexArray(object):
    def __init__(self):
        # vertices
        self.vertices=[]
        self.normal=[]
        self.colors=[]
        self.uvlist=[]
        self.b0=[]
        self.b1=[]
        self.w0=[]
        # indices
        self.materials=[]
        self.indicesMap={}

    def addVertex(self, pos, normal, uv, color, b0, b1, w0):
        self.vertices+=pos
        self.normal+=normal
        self.colors+=color
        self.uvlist+=uv
        self.b0.append(b0)
        self.b1.append(b1)
        self.w0.append(w0)

    def addMaterial(self, material):
        self.materials.append(material)
        indices=[]
        self.indicesMap[material]=indices
        return indices

    def draw(self):
        # 位置属性
        glEnableClientState(GL_VERTEX_ARRAY)
        glVertexPointer(4, GL_FLOAT, 0, self.vertices)
        # UV属性
        glEnableClientState(GL_TEXTURE_COORD_ARRAY)
        glTexCoordPointer(2, GL_FLOAT, 0, self.uvlist)
        # マテリアル毎の描画
        for m in self.materials:
            m.begin()
            # 順序維持
            indices=self.indicesMap[m]
            # indexによる描画
            glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, indices)
            m.end()
        # 後始末
        glDisableClientState(GL_TEXTURE_COORD_ARRAY)
        glDisableClientState(GL_VERTEX_ARRAY)

    def optimize(self):
        self.vertices=numpy.array(self.vertices, numpy.float32)
        self.uvlist=numpy.array(self.uvlist, numpy.float32)
        for m, indices in self.indicesMap.items():
            self.indicesMap[m]=numpy.array(indices, numpy.uint32)

    def get_boundingbox(self):
        vertices_size=len(self.vertices)
        if(vertices_size==0):
            return ([0, 0, 0], [0, 0, 0])
        def vertex_gen_factory():
            for i in range(0, vertices_size, 4):
                yield [
                        self.vertices[i],
                        self.vertices[i+1],
                        self.vertices[i+2]
                        ]
        vertex_gen=vertex_gen_factory()
        v=next(vertex_gen)
        max_v=v[:]
        min_v=v[:]
        for v in vertex_gen:
            if v[0]<min_v[0]:
                min_v[0]=v[0]
            if v[1]<min_v[1]:
                min_v[1]=v[1]
            if v[2]<min_v[2]:
                min_v[2]=v[2]
            if v[0]>max_v[0]:
                max_v[0]=v[0]
            if v[1]>max_v[1]:
                max_v[1]=v[1]
            if v[2]>max_v[2]:
                max_v[2]=v[2]
        return (min_v, max_v)