import numpy as np
import matplotlib.pyplot as plt
import matplotlib.text as mpl_text
import matplotlib.transforms as mpl_transforms

from .csc import reconstruct

def plot_atom_and_coefs(D_hat, z_hat, prefix):
    n_atoms = D_hat.shape[0]

    E = np.sum(z_hat > 0, axis=(1, 2))
    i0 = E.argsort()[::-1]

    n_cols = 5
    n_rows = int(np.ceil(n_atoms / n_cols))
    fig = plt.figure(figsize=(3*n_cols + 2, 3*n_rows + 2))
    fig.patch.set_alpha(0)
    for i in range(n_rows):
        for j in range(n_cols):
            if n_cols * i + j >= n_atoms:
                continue
            k = i0[n_cols * i + j]
            ax = plt.subplot2grid((n_rows, n_cols), (i, j))
            scale = 1 / D_hat[k].max() * .99
            Dk = np.clip(scale * D_hat[k].swapaxes(0, 2), 0, 1)
            ax.imshow(Dk)
            ax.axis('off')
    fig.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95,
                        wspace=.1, hspace=.1)

    fig.savefig(f"hubble/{prefix}dict.pdf", dpi=300,
                bbox_inches='tight', pad_inches=0)

    fig = plt.figure()
    fig.patch.set_alpha(0)
    plt.imshow(z_hat.sum(axis=0).T > 0, cmap='gray')
    plt.axis('off')
    fig.tight_layout()
    fig.savefig(f"hubble/{prefix}z_hat.pdf", dpi=1200,
                bbox_inches='tight', pad_inches=0)

    fig = plt.figure()
    fig.patch.set_alpha(0)
    X_hat = np.clip(reconstruct(z_hat, D_hat), 0, 1)
    plt.imshow(X_hat.swapaxes(0, 2))
    plt.axis('off')
    fig.tight_layout()
    fig.savefig(f"hubble/{prefix}X_hat.pdf", dpi=1200,
                bbox_inches='tight', pad_inches=0)

def display_atom(atom, ax=None, style=None):
    """Display one atom in 1D/2D with the correct formating.

    * For 1D atom, plot all the signals of all channels.
    * For 2D atom, show the image with the correct cmap for
      grayscale image with only 1 channel.

    Parameters
    ----------
    atom: ndarray, shape (n_channels, *atom_support)
        Atom to display. This should be a 1D or 2D multivariate atom.
    ax: mpl.Axes or None
        Matplotlib axe to plot the atom.
    style: dict or None
        Style info for the atom. Can include color, linestyle, linewidth, ...
    """
    if style is None:
        style = {}
    if ax is None:
        fig, ax = plt.subplots(111)

    if atom.ndim == 2:
        ax.plot(atom.T, **style)
    elif atom.ndim == 3:
        cmap = 'gray' if atom.shape[0] == 1 else None
        atom = np.rollaxis(atom, axis=0, start=3).squeeze()
        ax.imshow(atom, cmap=cmap)
        ax.set_xticks([])
        ax.set_yticks([])
        for spine in ax.spines.values():
            spine.set(**style)
    else:
        raise ValueError(
            'display_atom utility can only be used for multivariate atoms in '
            f'1D or 2D. Got atom with shape {atom.shape}'
        )

def display_dictionaries(*list_D, styles=None, axes=None, filename=None):
    """Display utility for dictionaries

    Parameters
    ----------
    list_D: List of ndarray, shape (n_atoms, n_channels, *atom_support)
        Dictionaries to display in the figure.
    styles: Dict of style or None
        Style to display an atom

    """
    n_dict = len(list_D)
    D_0 = list_D[0]

    if styles is None and n_dict >= 1:
        styles = [dict(color=f'C{i}') for i in range(n_dict)]

    # compute layout
    n_atoms = D_0.shape[0]
    n_cols = max(4, int(np.sqrt(n_atoms)))
    n_rows = int(np.ceil(n_atoms / n_cols))

    if axes is None:
        fig, axes = plt.subplots(ncols=n_cols, nrows=n_dict * n_rows,
                                 squeeze=False)
    else:
        assert axes.shape >= (n_rows*n_dict, n_cols), (
            f"axes argument should have at least shape ({n_rows*n_dict}, "
            f"{n_cols}). Got {axes.shape}."
        )
        fig = axes[0, 0].get_figure()

    used_axes = 0
    for id_ax, D in enumerate(zip(*list_D)):
        used_axes += 1
        i, j = np.unravel_index(id_ax, (n_rows, n_cols))
        for k, (dk, style) in enumerate(zip(D, styles)):
            ik = n_dict * i + k
            ax = axes[ik, j]
            display_atom(dk, ax=ax, style=style)

    # hide the unused axis
    for id_ax in range(used_axes, n_cols * n_rows):
        i, j = np.unravel_index(id_ax, (n_rows, n_cols))
        for k in range(n_dict):
            ik = n_dict * i + k
            axes[ik, j].set_axis_off()

    if filename is not None:
        fig.savefig(f'{filename}.pdf', dpi=300)

    return fig

def median_curve(times, pobj):
    """Compute the Median curve, given a list of curves and their timing.

    Parameters
    ----------
    times : list of list
        Time point associated to pobj
    pobj : list of list
        Value of the cost function at a given time.

    Returns
    -------
    t: ndarray, shape (100,)
        Time points for the curve
    median_curve: ndarray, shape (100)
        Median value for the curves
    """
    T = np.max([np.max(tt) for tt in times])
    # t = np.linspace(0, T, 100)
    t = np.logspace(-1, np.log10(T), 100)
    curves = []
    for lt, lf in zip(times, pobj):
        curve = []
        for tt in t:
            i0 = np.argmax(lt > tt)
            if i0 == 0 and tt != 0:
                value = lf[-1]
            elif i0 == 0 and tt == 0:
                value = lf[0]
            else:
                value = (lf[i0] - lf[i0-1]) / (lt[i0] - lt[i0-1]) * (
                    tt - lt[i0-1]) + lf[i0-1]
            curve.append(value)
        curves.append(curve)
    return t, np.median(curves, axis=0)

class RotationAwareAnnotation(mpl_text.Annotation):
    """Text along a line that self adapt to rotation in the figure.

    this class is derived from the SO answer:
    https://stackoverflow.com/questions/19907140/keeps-text-rotated-in-data-coordinate-system-after-resizing#53111799

    Parameters
    ----------
    text: str
        Text to display on the figure
    anchor_point: 2-tuple
        Position of this text in the figure. The system of coordinates used to
        translate this position is controlled by the parameter ``xycoords``.
    next_point: 2-tuple
        Another point of the curve to follow. The annotation will be written
        along the line of slope dy/dx where dx = next_pt[0] - anchor_pt[0] and
        dy = next_pt[1] - anchor_pt[1].
    ax: Artiste or None
        The Artiste in which the
    **kwargs: dict
        Key-word arguments for the Annotation. List of available kwargs:
        https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.annotate.html
    """

    def __init__(self, text, anchor_pt, next_pt, ax=None, **kwargs):
        # Get the Artiste to draw on
        self.ax = ax or plt.gca()

        # Save the anchor point
        self.anchor_pt = np.array(anchor_pt)[None]

        # Compute the slope of the text in data coordinate system.
        dx = next_pt[0]-anchor_pt[0]
        dy = next_pt[1]-anchor_pt[1]
        ang = np.arctan2(dy, dx)
        self.angle_data = np.rad2deg(ang)

        # Create the text objects and display it
        kwargs.update(rotation_mode=kwargs.get("rotation_mode", "anchor"))
        kwargs.update(annotation_clip=kwargs.get("annotation_clip", True))
        super().__init__(text, anchor_pt, **kwargs)
        self.set_transform(mpl_transforms.IdentityTransform())
        self.ax._add_text(self)

    def _get_rotation(self):
        return self.ax.transData.transform_angles(
            np.array((self.angle_data,)), self.anchor_pt)[0]

    def _set_rotation(self, rotation):
        pass

    _rotation = property(_get_rotation, _set_rotation)


import re
import torch
import torch.distributed

from typing import List, Optional, Type

from transformers import (
    AutoTokenizer,
    AutoConfig,
    PreTrainedTokenizerBase,
)
from text_generation_server.models import CausalLM
from text_generation_server.models.causal_lm import CausalLMBatch
from text_generation_server.pb import generate_pb2
from text_generation_server.models.custom_modeling.opt_modeling import OPTForCausalLM
from text_generation_server.utils import (
    NextTokenChooser,
    StoppingCriteria,
    initialize_torch_distributed,
    weight_files,
    Weights,
)

# CREDIT: Papers with code => https://github.com/paperswithcode/galai/blob/main/galai/utils.py

# we split individual characters inside special tokens like [START_DNA]
CUSTOM_SEQ_RE = re.compile(r"(\[START_(DNA|SMILES|I_SMILES|AMINO)])(.*?)(\[END_\2])")

# token added to implement a custom sequence tokenization. This token is added at
# corpus cleaning step and removed in pretokenization. The digits are added to increase the chance
# that they do not occur in the corpus. The digits are escaped so that the token does not appear
# literally in the source code in case we ever include it in the training data.
SPLIT_MARKER = f"SPL{1}T-TH{1}S-Pl3A5E"

def _insert_split_marker(m: re.Match):
    """
    Applies split marker based on a regex match of special tokens such as
    [START_DNA].
    Parameters
    ----------
    n : str
        Input text to split
    Returns
    ----------
    str - the text with the split token added
    """
    start_token, _, sequence, end_token = m.groups()
    sequence = re.sub(r"(.)", rf"{SPLIT_MARKER}\1", sequence, flags=re.DOTALL)
    return f"{start_token}{sequence}{SPLIT_MARKER}{end_token}"

def escape_custom_split_sequence(text):
    """
    Applies custom splitting to the text for GALILEO's tokenization
    Parameters
    ----------
    text : str
        Input text to split
    Returns
    ----------
    str - the text with the split token added
    """
    return CUSTOM_SEQ_RE.sub(_insert_split_marker, text)

# END CREDIT

class GalacticaCausalLMBatch(CausalLMBatch):
    @classmethod
    def from_pb(
        cls,
        pb: generate_pb2.Batch,
        tokenizer: PreTrainedTokenizerBase,
        dtype: torch.dtype,
        device: torch.device,
    ) -> "GalacticaCausalLMBatch":
        inputs = []
        next_token_choosers = []
        stopping_criterias = []
        prefix_offsets = []
        top_n_tokens = []
        read_offsets = []
        requests_idx_mapping = {}

        # Parse batch
        max_truncation = 0
        padding_right_offset = 0
        max_decode_tokens = 0
        for i, r in enumerate(pb.requests):
            requests_idx_mapping[r.id] = i
            # Add escape_custom_split_sequence to the CausalLMBatch logic
            inputs.append(escape_custom_split_sequence(r.inputs))
            next_token_choosers.append(NextTokenChooser.from_pb(r.parameters, device))
            stopping_criteria = StoppingCriteria.from_pb(
                r.stopping_parameters, tokenizer
            )
            stopping_criterias.append(stopping_criteria)
            top_n_tokens.append(r.top_n_tokens)
            max_truncation = max(max_truncation, r.truncate)
            max_decode_tokens += stopping_criteria.max_new_tokens
            padding_right_offset = max(
                padding_right_offset, stopping_criteria.max_new_tokens
            )

        tokenized_inputs = tokenizer(
            inputs,
            return_tensors="pt",
            padding=True,
            return_token_type_ids=False,
            truncation=True,
            max_length=max_truncation,
        ).to(device)
        for _ in pb.requests:
            input_len = tokenized_inputs["input_ids"].shape[1]
            prefix_offsets.append(0)
            read_offsets.append(input_len)

        input_lengths = tokenized_inputs["attention_mask"].sum(1)
        max_input_length = input_lengths.max()

        input_ids = tokenized_inputs["input_ids"]
        # Allocate maximum attention_mask
        attention_mask = input_ids.new_zeros(
            (pb.size, max_input_length + padding_right_offset)
        )
        # Copy tokenizer attention_mask into fully allocated attention_mask
        attention_mask[:, :max_input_length] = tokenized_inputs["attention_mask"]

        position_ids = tokenized_inputs["attention_mask"].long().cumsum(-1) - 1
        position_ids.masked_fill_(tokenized_inputs["attention_mask"] == 0, 1)
        all_input_ids = tokenized_inputs["input_ids"].T.split(1, dim=1)
        top_n_tokens_tensor = torch.tensor(
            top_n_tokens, device=device, dtype=torch.int64
        )

        max_tokens = len(inputs) * max_input_length + max_decode_tokens

        return cls(
            batch_id=pb.id,
            requests=pb.requests,
            requests_idx_mapping=requests_idx_mapping,
            input_ids=input_ids,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=None,
            all_input_ids=list(all_input_ids),
            input_lengths=input_lengths.tolist(),
            prefix_offsets=prefix_offsets,
            read_offsets=read_offsets,
            next_token_choosers=next_token_choosers,
            stopping_criterias=stopping_criterias,
            top_n_tokens=top_n_tokens,
            top_n_tokens_tensor=top_n_tokens_tensor,
            max_input_length=max_input_length.item(),
            padding_right_offset=padding_right_offset,
            max_tokens=max_tokens,
        )

class GalacticaSharded(CausalLM):
    def __init__(
        self,
        model_id: str,
        revision: Optional[str] = None,
        quantize: Optional[str] = None,
        dtype: Optional[torch.dtype] = None,
        trust_remote_code: bool = False,
    ):
        self.process_group, rank, world_size = initialize_torch_distributed()
        if torch.cuda.is_available():
            device = torch.device(f"cuda:{rank}")
            dtype = torch.float16 if dtype is None else dtype
        else:
            device = torch.device("cpu")
            dtype = torch.float32 if dtype is None else dtype

        tokenizer = AutoTokenizer.from_pretrained(
            model_id,
            revision=revision,
            padding_side="left",
            truncation_side="left",
            trust_remote_code=trust_remote_code,
        )

        config = AutoConfig.from_pretrained(
            model_id,
            revision=revision,
            tp_parallel=True,
            trust_remote_code=trust_remote_code,
        )
        config.quantize = quantize
        tokenizer.pad_token_id = config.pad_token_id

        torch.distributed.barrier(group=self.process_group)
        filenames = weight_files(model_id, revision=revision, extension=".safetensors")
        weights = Weights(
            filenames, device=device, dtype=dtype, process_group=self.process_group
        )
        if config.quantize == "gptq":
            weights._set_gptq_params(model_id)

        model = OPTForCausalLM(config, weights)

        torch.distributed.barrier(group=self.process_group)
        super(CausalLM, self).__init__(
            model=model,
            tokenizer=tokenizer,
            requires_padding=True,
            dtype=dtype,
            device=device,
            rank=rank,
            world_size=world_size,
        )

    @property
    def batch_type(self) -> Type[CausalLMBatch]:
        return GalacticaCausalLMBatch

    def decode(self, generated_ids: List[int]) -> str:
        # Do not skip special tokens as they are used for custom parsing rules of the generated text
        return self.tokenizer.decode(
            generated_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False
        )

    def forward(
        self, input_ids, attention_mask, position_ids, past_key_values: Optional = None
    ):
        outputs = self.model.forward(
            input_ids=input_ids,
            attention_mask=attention_mask,
            past_key_values=past_key_values,
            use_cache=True,
        )
        return outputs.logits, outputs.past_key_values


"""
	This module converts string to voice using PyTtsx3 and win32com module
	* To use it's function just import like this -
		from tts import tts
"""
import pyttsx3
def tts(msg):
	engine = pyttsx3.init()
	rate = engine.getProperty('rate')
	engine.setProperty('rate', rate-60)
	# voices = engine.getProperty('voices')
	# engine.setProperty('voice',voices[1].id)
	engine.setProperty('voice', 'Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0')
	engine.say(msg)
	engine.runAndWait()

# tts('say neola')

# engine = pyttsx3.init()
# rate = engine.getProperty('rate')
# engine.setProperty('rate', rate-60)
# voices = engine.getProperty('voices')
# engine.setProperty('voice',voices[1].id)
# engine.say('The quick brown fox jumped over the lazy dog.')
# engine.runAndWait()


# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
import torchvision.models as models
import os
from torch.utils.data import Dataset, DataLoader, random_split
from sklearn.metrics import matthews_corrcoef
import numpy as np
from PIL import Image
import sys
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import pandas as pd
import logging
import os
import sys
import random
from tqdm import tqdm
from time import sleep
import time
import csv
import matplotlib.pyplot as plt
from .transformers import BertTokenizer, BertModel
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")

from .modelconfig import get_args
args= get_args()

SEED = args.seed
data_dir = args.GLUE_path
output_path = args.output_path
model_path = os.path.join(output_path, 'model')
pred_path = os.path.join(output_path, 'result')
if not os.path.exists(model_path):
    os.makedirs(model_path)
if not os.path.exists(pred_path):
    os.makedirs(pred_path)
max_len = args.mnli_len
batch_size = args.mnli_batch
lr = args.mnli_lr

random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
torch.cuda.manual_seed_all(SEED)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False

# +
train_path = os.path.join(data_dir,'MNLI/train.tsv')
df_train = pd.read_csv(train_path, sep='\t',error_bad_lines=False, keep_default_na = False)

val_match_path = os.path.join(data_dir,'MNLI/dev_matched.tsv')
df_val_match = pd.read_csv(val_match_path, sep='\t',error_bad_lines=False, keep_default_na = False)

val_mismatch_path =os.path.join(data_dir,'MNLI/dev_mismatched.tsv')
df_val_mismatch = pd.read_csv(val_mismatch_path, sep='\t',error_bad_lines=False, keep_default_na = False)

test_match_path = os.path.join(data_dir,'MNLI/test_matched.tsv')
df_test_match = pd.read_csv(test_match_path, sep='\t',error_bad_lines=False, keep_default_na = False)

test_mismatch_path = os.path.join(data_dir,'MNLI/test_mismatched.tsv')
df_test_mismatch = pd.read_csv(test_mismatch_path, sep='\t',error_bad_lines=False, keep_default_na = False)

tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")

# +
class Allen(Dataset):
    def __init__(self, mode):
        self.mode = mode
        if self.mode == 'train':
            self.len = len(df_train)
        elif self.mode == 'val_m':
            self.len = len(df_val_match)
        elif self.mode == 'val_mm':
            self.len = len(df_val_mismatch)
        elif self.mode == 'test_m':
            self.len = len(df_test_match)
        else:
            self.len = len(df_test_mismatch)

    def __getitem__(self, index):
        if self.mode == 'train':
            encoded = tokenizer.encode_plus(
                df_train['sentence1'][index],  # the sentence to be encoded
                df_train['sentence2'][index],
                add_special_tokens=True,  # Add [CLS] and [SEP]
                max_length = max_len,  # maximum length of a sentence
                padding='max_length',  # Add [PAD]s
                return_attention_mask = True,  # Generate the attention mask
                return_tensors = 'pt',  # ask the function to return PyTorch tensors
            )
            if df_train['gold_label'][index] == 'entailment':
                label = 2
            elif df_train['gold_label'][index] == 'neutral':
                label = 1
            else:
                label = 0
        elif self.mode == 'val_m':
            encoded = tokenizer.encode_plus(
                df_val_match['sentence1'][index],  # the sentence to be encoded
                df_val_match['sentence2'][index],
                add_special_tokens=True,  # Add [CLS] and [SEP]
                max_length = max_len,  # maximum length of a sentence
                padding='max_length',  # Add [PAD]s
                return_attention_mask = True,  # Generate the attention mask
                return_tensors = 'pt',  # ask the function to return PyTorch tensors
            )
            if df_val_match['gold_label'][index] == 'entailment':
                label = 2
            elif df_val_match['gold_label'][index] == 'neutral':
                label = 1
            else:
                label = 0
        elif self.mode == 'val_mm':
            encoded = tokenizer.encode_plus(
                df_val_mismatch['sentence1'][index],  # the sentence to be encoded
                df_val_mismatch['sentence2'][index],
                add_special_tokens=True,  # Add [CLS] and [SEP]
                max_length = max_len,  # maximum length of a sentence
                padding='max_length',  # Add [PAD]s
                return_attention_mask = True,  # Generate the attention mask
                return_tensors = 'pt',  # ask the function to return PyTorch tensors
            )
            if df_val_mismatch['gold_label'][index] == 'entailment':
                label = 2
            elif df_val_mismatch['gold_label'][index] == 'neutral':
                label = 1
            else:
                label = 0
        elif self.mode == 'test_m':
            encoded = tokenizer.encode_plus(
                df_test_match['sentence1'][index],  # the sentence to be encoded
                df_test_match['sentence2'][index],
                add_special_tokens=True,  # Add [CLS] and [SEP]
                max_length = max_len,  # maximum length of a sentence
                padding='max_length',  # Add [PAD]s
                return_attention_mask = True,  # Generate the attention mask
                return_tensors = 'pt',  # ask the function to return PyTorch tensors
            )
            label = 0
        elif self.mode == 'test_mm':
            encoded = tokenizer.encode_plus(
                df_test_mismatch['sentence1'][index],  # the sentence to be encoded
                df_test_mismatch['sentence2'][index],
                add_special_tokens=True,  # Add [CLS] and [SEP]
                max_length = max_len,  # maximum length of a sentence
                padding='max_length',  # Add [PAD]s
                return_attention_mask = True,  # Generate the attention mask
                return_tensors = 'pt',  # ask the function to return PyTorch tensors
            )
            label = 0

        input_ids = encoded['input_ids'][0][:max_len]
        attn_mask = encoded['attention_mask'][0][:max_len]
        token_type_ids = encoded['token_type_ids'][0][:max_len]
        return input_ids.view(max_len), attn_mask.view(max_len), token_type_ids.view(max_len), torch.tensor(label, dtype=torch.long)

    def __len__(self):

        return(self.len)
# +
train_dataset = Allen('train')
val_m_dataset = Allen('val_m')
val_mm_dataset = Allen('val_mm')
test_m_dataset = Allen('test_m')
test_mm_dataset = Allen('test_mm')

train_dataloader = DataLoader(train_dataset,batch_size=batch_size,shuffle=True)
val_m_dataloader = DataLoader(val_m_dataset,batch_size=batch_size/2)
val_mm_dataloader = DataLoader(val_mm_dataset,batch_size=batch_size/2)
test_m_dataloader = DataLoader(test_m_dataset,batch_size=batch_size)
test_mm_dataloader = DataLoader(test_mm_dataset,batch_size=batch_size)

# -

class Model(nn.Module):
    def __init__(self, backbond):
        super(Model, self).__init__()
        self.backbond = backbond
        self.weight_lst= []
        self.param_lst = []

        for name,param in self.backbond.named_parameters():
            if 'LayerNorm' in name and 'attention' not in name:
                self.param_lst.append(param)
                continue
            elif 'adapter' in name:
                if 'bias' in name:
                    self.param_lst.append(param)
                elif 'fix' in output_path and 'vector' in name:
                    print('大哥好，您把vector fix住了哦！！！')
                    param.requires_grad = False
                else:
                    self.weight_lst.append(param)
                continue
            else:
                param.requires_grad = False

        self.fc = nn.Sequential(
            nn.Dropout(),
            nn.Linear(768,3),
        )

        for name,param in self.fc.named_parameters():
            self.weight_lst.append(param)

    def forward(self, tokens, mask, type_id):
        embedding = self.backbond(input_ids=tokens, attention_mask=mask, token_type_ids = type_id)[1]
        answer = self.fc(embedding)
        return answer

# +
backbond = BertModel.from_pretrained("bert-base-uncased").to(device)
model = Model(backbond).to(device)
loss_funtion = nn.CrossEntropyLoss()

optimizer_weight = optim.AdamW(model.weight_lst, lr = lr)
optimizer_bias = optim.AdamW(model.param_lst, lr = lr, weight_decay=0)

print('Start training MNLI!!!')
best_acc_m = 0
best_epoch_m =0
best_acc_mm = 0
best_epoch_mm =0
accuracy_m = []
accuracy_mm = []
for epoch in range(args.mnli_epoch):
    epoch_start = time.time()
    model.train()
    correct = 0
    count = 0
    my_ans = []
    real_ans = []
    for batch_id, data in enumerate(tqdm(train_dataloader)):

        tokens, mask, type_id, label = data
        tokens, mask, type_id, label = tokens.to(device),mask.to(device), type_id.to(device), label.to(device)
        output = model(tokens = tokens, mask = mask, type_id = type_id)

        loss = loss_funtion(output, label)
        optimizer_weight.zero_grad()
        optimizer_bias.zero_grad()
        loss.backward()
        optimizer_weight.step()
        optimizer_bias.step()
        output = output.view(-1,3)
        pred = torch.max(output, 1)[1]
        for j in range(len(pred)):
            if pred[j] == label[j]:
                correct+=1
            count+=1
    train_score = correct/count

    epoch_finish = time.time()
    model.eval()
    with torch.no_grad():
        correct_m = 0
        count_m = 0
        correct_mm = 0
        count_mm = 0
        for batch_id, data in enumerate(tqdm(val_m_dataloader)):
            tokens, mask, type_id, label = data
            tokens, mask, type_id, label = tokens.to(device),mask.to(device), type_id.to(device), label.to(device)
            output = model(tokens = tokens, mask = mask, type_id = type_id)
            output = output.view(-1,3)
            pred = torch.max(output, 1)[1]
            for j in range(len(pred)):
                if pred[j] == label[j]:
                    correct_m+=1
                count_m+=1
        for batch_id, data in enumerate(tqdm(val_mm_dataloader)):
            tokens, mask, type_id, label = data
            tokens, mask, type_id, label = tokens.to(device),mask.to(device), type_id.to(device), label.to(device)
            output = model(tokens = tokens, mask = mask, type_id = type_id)
            output = output.view(-1,3)
            pred = torch.max(output, 1)[1]
            for j in range(len(pred)):
                if pred[j] == label[j]:
                    correct_mm+=1
                count_mm+=1

    score_m = correct_m/count_m
    score_mm = correct_mm/count_mm
    accuracy_m.append(score_m)
    accuracy_mm.append(score_mm)
    if score_m >= best_acc_m:
        best_acc_m = score_m
        best_epoch_m = epoch
        torch.save(model.state_dict(), os.path.join(model_path, 'MNLI_m.ckpt'))
    if score_mm >= best_acc_mm:
        best_acc_mm = score_mm
        best_epoch_mm = epoch
        torch.save(model.state_dict(), os.path.join(model_path, 'MNLI_mm.ckpt'))

    end = time.time()
    print('epoch = ', epoch+1)
    print('best epoch match = ', best_epoch_m +1)
    print('best cor match = ', best_acc_m)
    print('best epoch mismatch = ', best_epoch_mm +1)
    print('best cor mismatch = ', best_acc_mm)
    if epoch == 0:
        print('預計train時間 = ', args.mnli_epoch*(end-epoch_start)/60, '分鐘')
    print('=====================================')

print('Start predict MNLI!!!')

model = Model(backbond).to(device)
ckpt = torch.load(os.path.join(model_path, 'MNLI_m.ckpt'))
model.load_state_dict(ckpt)
model.eval()
ans = []
with torch.no_grad():
    for batch_id, data in enumerate(tqdm(test_m_dataloader)):
        tokens, mask, type_id, _ = data
        tokens, mask, type_id = tokens.to(device),mask.to(device), type_id.to(device)
        output = model(tokens = tokens, mask = mask, type_id = type_id)
        output = output.view(-1,3)
        pred = torch.max(output, 1)[1]
        for i in range(len(pred)):
            ans.append(int(pred[i]))

with open(os.path.join(pred_path, 'MNLI-m.tsv'), 'wt') as out_file:
    tsv_writer = csv.writer(out_file, delimiter='\t')
    tsv_writer.writerow(['Id', 'Label'])
    for idx, label in enumerate(ans):
        if label == 0:
            tsv_writer.writerow([idx, 'contradiction'])
        if label == 1:
            tsv_writer.writerow([idx, 'neutral'])
        else:
            tsv_writer.writerow([idx, 'entailment'])

model = Model(backbond).to(device)
ckpt = torch.load(os.path.join(model_path, 'MNLI_mm.ckpt'))
model.load_state_dict(ckpt)
model.eval()
ans = []
with torch.no_grad():
    for batch_id, data in enumerate(tqdm(test_mm_dataloader)):
        tokens, mask, type_id, _ = data
        tokens, mask, type_id = tokens.to(device),mask.to(device), type_id.to(device)
        output = model(tokens = tokens, mask = mask, type_id = type_id)
        output = output.view(-1,3)
        pred = torch.max(output, 1)[1]
        for i in range(len(pred)):
            ans.append(int(pred[i]))

with open(os.path.join(pred_path, 'MNLI-mm.tsv'), 'wt') as out_file:
    tsv_writer = csv.writer(out_file, delimiter='\t')
    tsv_writer.writerow(['Id', 'Label'])
    for idx, label in enumerate(ans):
        if label == 0:
            tsv_writer.writerow([idx, 'contradiction'])
        if label == 1:
            tsv_writer.writerow([idx, 'neutral'])
        else:
            tsv_writer.writerow([idx, 'entailment'])


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics.pairwise import pairwise_distances
import networkx as nx
import itertools
from networkx.drawing.nx_agraph import graphviz_layout
from __future__ import division
import collections
from networkx.algorithms.richclub import rich_club_coefficient
import seaborn as sns
import random
import math
from operator import itemgetter
from community import community_louvain
from networkx.algorithms import community
from itertools import count
import community
from math import floor

def Hist_degree(G,prob, Rand, Type):
    """ Plots the degree distribution of the directed graph G and of a random network.
    Inputs:
        G : directed graph
        prob: probability to add an edge between a pair of nodes in the Erdos Renyi model
        Rand: type of random model: CM (configuration model) or ER (Erdos-Renyi) or WS (Watts-Strogatz) or BA (Bbarabasi-Albert)
        Type: type of degree to be plotted: degree (both), in-degree (in) or out-degree (out)
    """

    if Rand=="ER":
        # erdos renyi
        random_graph= nx.erdos_renyi_graph(n= len(G), p= prob, directed = True)

    elif Rand=='CM':
        #configuration model
        random_graph= nx.configuration_model(sorted([d for n, d in G.degree()]))
    elif Rand=='WS':
        # watts strogatz model
        random_graph= nx.watts_strogatz_graph(n= len(G), k=floor(stat.mean(sorted([d for n, d in G.degree()]))), p=prob)
    else:
        # barabasi albert graph
                random_graph= nx.barabasi_albert_graph(n= len(G), m=floor(stat.mean(sorted([d for n, d in G.degree()]))))

    if Type == 'out':
        out_list =[]
        out_list_r = []
        for elmt in G.out_degree:
            out_list.append(elmt[1])

        for relmt in random_graph.out_degree :
            out_list_r.append(relmt[1])
        x1 = pd.Series(out_list_r)
        x2 = pd.Series(out_list)

        newbins = np.arange(min(x2), max(x2), 1)
        plt.hist(x1, density=True, bins = newbins,alpha=0.5, color = 'grey')
        plt.hist(x2, density=True, bins = newbins, alpha=0.3, color='blue')
        plt.title('Out degree distribution')
        plt.xlabel('out degree')
        plt.ylabel('density')

    if Type == 'in':
        in_list =[]
        in_list_r = []
        for elmt in G.in_degree:
            in_list.append(elmt[1])
        for relmt in random_graph.in_degree :
            in_list_r.append(relmt[1])
        x1 = pd.Series(in_list_r)
        x2 = pd.Series(in_list)

        newbins = np.arange(min(x2), max(x2), 1)
        plt.hist(x1, density=True, bins = newbins,alpha=0.5, color = 'grey')
        plt.hist(x2, density=True, bins = newbins,alpha=0.3, color='green')
        plt.title('In degree distribution')
        plt.xlabel('In degree')
        plt.ylabel('density')

    if Type == 'both':
        random_graph.to_undirected()
        both_list =[]
        both_list_r =[]
        for elmt in G.degree():
            both_list.append(elmt[1])
        for relmt in random_graph.degree :
            both_list_r.append(relmt[1])

        x1 = pd.Series(both_list_r)
        x2 = pd.Series(both_list)
        newbins = np.arange(min(x2), max(x2), 1)
        plt.hist(x1, density=True,bins = newbins, alpha=0.5, color = 'grey')
        plt.hist(x2, density=True, bins = newbins,alpha=0.3, color='red')
        plt.title('Degree distribution')
        plt.xlabel('degree')
        plt.ylabel('density')

    plt.legend(['random graph distribution', 'degree distribution'])

    return x2 , x1, random_graph


from .models import SpotifyToken
from django.utils import timezone
from datetime import timedelta
from .credentials import CLIENT_ID, CLIENT_SECRET
from requests import post, put, get
import math

BASE_URL = "http://api.spotify.com/v1/me/"

def get_user_tokens(session_id):
    user_tokens = SpotifyToken.objects.filter(user=session_id)
    if user_tokens.exists():
        return user_tokens[0]
    else:
        return None

# save the spotify token in a new model or update a new model
# with the new spotify tokens
def update_or_create_user_tokens(session_id, access_token,
                                 token_type, expires_in, refresh_token):
    tokens = get_user_tokens(session_id)
    # change the expires in into a time stamp
    # expires in is just a number of seconds
    expires_in = timezone.now() + timedelta(seconds=expires_in)

    if tokens:
        tokens.access_token = access_token
        tokens.refresh_token = refresh_token
        tokens.expires_in = expires_in
        tokens.token_type = token_type
        tokens.save(update_fields=['access_token',
                                   'refresh_token',
                                   'token_type', 'expires_in'])
    else:
        tokens = SpotifyToken(user=session_id, access_token=access_token,
                              refresh_token=refresh_token,
                              token_type=token_type, expires_in=expires_in)
        tokens.save()

# tell us if the user is already authenticated

def is_spotify_authenticated(session_id):
    tokens = get_user_tokens(session_id)
    if tokens:
        expiry = tokens.expires_in
        if expiry <= timezone.now():
            # refresh token if the expiry has passed
            refresh_spotify_token(session_id)
        return True

    return False

def refresh_spotify_token(session_id):
    refresh_token = get_user_tokens(session_id)
    response = post('https://accounts.spotify.com/api/token', data={
        'grant_type': 'refresh_token',
        'refresh_token': refresh_token,
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET
    }).json()
    access_token = response.get('access_token')
    token_type = response.get('token_type')
    expires_in = response.get('expires_in')

    update_or_create_user_tokens(
        session_id, access_token, token_type, expires_in, refresh_token)

# session_id = host session id in this case
def execute_spotify_api_request(session_id, endpoint, method='GET'):
    if method not in ['POST', 'PUT', 'GET']:
        return {'Error': f'{method} is not a valid method'}
    tokens = get_user_tokens(session_id)
    headers = {'Content-Type': 'application/json',
               'Authorization': "Bearer " + tokens.access_token}
    if method == 'POST':
        print("Trying POST: " + BASE_URL + endpoint)
        response = post(BASE_URL + endpoint, headers=headers)
        print(response)
    elif method == 'PUT':
        response = put(BASE_URL + endpoint, headers=headers)
        print(response)
    elif method == 'GET':
        response = get(BASE_URL + endpoint, {}, headers=headers)
        try:
            return response.json()
        except:
            return {'Error': 'Issue with request'}

def toggle_play_pause_song(session_id, play):
    if play:
        endpoint = "player/play"
        execute_spotify_api_request(session_id, endpoint, 'PUT')
        return
    else:
        endpoint = "player/pause"
        execute_spotify_api_request(session_id, endpoint, 'PUT')
        return

def skip_song(session_id, back=False):
    tokens = get_user_tokens(session_id)
    headers = {'Content-Type': 'application/json',
               'Authorization': "Bearer " + tokens.access_token}
    if back:
        response = post("https://api.spotify.com/v1/me/player/previous", headers=headers)
    else:
        response = post("https://api.spotify.com/v1/me/player/next", headers=headers)

def seek_in_song(session_id, ms):
    ms = float(ms)
    tokens = get_user_tokens(session_id)
    headers = {'Content-Type': 'application/json',
               'Authorization': "Bearer " + tokens.access_token}
    url = f"https://api.spotify.com/v1/me/player/seek?position_ms={math.floor(ms)}"

    response = put(url, headers=headers)
    print(response)
    return response

def update_volume(session_id, new_volume):
    tokens = get_user_tokens(session_id)
    headers = {'Content-Type': 'application/json',
               'Authorization': "Bearer " + tokens.access_token}
    url = f"https://api.spotify.com/v1/me/player/volume?volume_percent={int(new_volume)}"
    response = put(url, headers=headers)
    return response


# coding: utf-8

# In[32]:

import numpy as np
import cv2
img_k1 = cv2.imread('key1.png')
gray_k1 = cv2.cvtColor(img_k1, cv2.COLOR_BGR2GRAY)
gray_k1 = np.array(gray_k1)
img_k2 = cv2.imread('key2.png')
gray_k2 = cv2.cvtColor(img_k2, cv2.COLOR_BGR2GRAY)
gray_k2 = np.array(gray_k2)
img_E = cv2.imread('E.png')
gray_E = cv2.cvtColor(img_E, cv2.COLOR_BGR2GRAY)
gray_E = np.array(gray_E)
img_I = cv2.imread('I.png')
gray_I = cv2.cvtColor(img_I, cv2.COLOR_BGR2GRAY)
gray_I = np.array(gray_I)
img_Eprime = cv2.imread('Eprime.png')
gray_Eprime = cv2.cvtColor(img_Eprime, cv2.COLOR_BGR2GRAY)
gray_Eprime = np.array(gray_Eprime)

gray_I2= np.zeros(gray_Eprime.shape,np.uint8)
w = [0,0,0]
w = np.array(w)
x = [0,0,0]
x = np.array(x)
e = [0,0,0]
e = np.array(e)
size = gray_k1.shape;
W = size[1]
H = size[0]

r = 0.00001
epoch = 1
while epoch < 2:

    for i in range(1,W):
            for j in range(1,H):
                k1 = gray_k1[j,i]
                k2 = gray_k2[j,i]
                I = gray_I[j,i]
                x[0] = k1
                x[1] = k2
                x[2] = I  #x[k1,k2,I]
                a = np.dot(w,x)
                e = gray_E[j,i] - a
                w = w + r * e * x

    epoch = epoch + 1

for i in range(1,W):
        for j in range(1,H):
            color = (gray_Eprime[j,i] - w[0]*gray_k1[j,i] - w[1]*gray_k2[j,i])/w[2]
            if color > 255:
                color = 255
            if color < 0:
                color = 0
            gray_I2[j,i] = color

cv2.imshow('My Image', gray_I2)
cv2.imwrite('Decryption.jpg', gray_I2)
cv2.waitKey(0)
cv2.destroyAllWindows()

# In[29]:

print(w)


import cv2
import numpy as np

img = cv2.imread("101/ders6/wolf.jpg")

cv2.rectangle(img,(500,210),(150,150),[0,0,255],3)
cv2.imshow("new",img)

cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)


from twilio.rest import Client
def make_call():
    account_sid = "Your Account"
    auth_token = "Your Auth"
    client = Client(account_sid, auth_token)

    call = client.calls.create(
                            url='http://demo.twilio.com/docs/voice.xml',
                            to='+918210410103',
                            from_='+19402919532')
    print(call.sid)


#!/usr/bin/env python3
"""
Usage:
signature_server.py [--host HOST] [--port PORT] [--delay DELAY] [--quiet]

Options:
--quiet             Do not print each request
--host HOST         The host to bind the server to. [default: localhost]
--port PORT         The port to bind the server to. [default: 9000]
--delay DELAY       The artificial delay (in ms) between each comparison of bytes of the signature [default: 0.05]
"""
import base64
import random
from docopt import docopt
from bottle import request, run, response, get
import time
import itertools
import sys
import util

__author__ = 'peter'

KEY = util.get_random_bytes(random.randint(10, 100))

@get('/check_signature')
def check_signature():
    file = base64.urlsafe_b64decode(request.query.file)
    sig = base64.urlsafe_b64decode(request.query.signature)
    if not insecure_compare(file, sig):
        response.status = 500
        return 'Boo!'
    else:
        return 'Yay!'

@get('/get_key')
def get_key():
    return KEY

def insecure_compare(file, sig):
    s = util.sha1_hmac(file, KEY)
    if not quiet:
        print(util.to_hex(sig))
        print(util.to_hex(s))
    for b1, b2 in itertools.zip_longest(s, sig):
        if b1 != b2:
            return False
        time.sleep(delay)
    return True

def main(argv=None):
    args = docopt(__doc__, argv=argv)
    global delay, quiet

    try:
        delay = float(args['--delay'])
        quiet = args['--quiet']
    except ValueError:
        print('Provided delay "{}" is no valid float!'.format(args['--delay']))
        sys.exit(-1)
    run(host=args['--host'], port=args['--port'], quiet=args['--quiet'])

if __name__ == '__main__':
    main()


from faker.providers import BaseProvider
from faker import Faker
fake = Faker()

level_list = [
    'Junior', 'Mid-level', 'Experienced', 'Senior', 'Lead'
]

tech_list = [
    'Python', 'Javascript', 'Django', 'Flask', 'React',
    'Angular', 'Java', 'C', 'C++', 'C#', '.NET', 'Vue',
    'Ruby', 'Golang', 'Sinatra', 'PHP', 'Laravel', 'AWS'
]

position_list = [
    'Developer', 'Engineer', 'Architect'
]

class Provider(BaseProvider):
    def job_title(self):
        level = fake.word(ext_word_list=level_list)
        tech = fake.word(ext_word_list=tech_list)
        position = fake.word(ext_word_list=position_list)

        return f'{level} {tech} {position}'


import telebot as tb
from telebot import types

bot = tb.TeleBot('Insert your token here.')

name, last_name, age = '', '', 0

@bot.message_handler(content_types=['text'])
def start(message):
    if message.text == '/reg':
        bot.send_message(message.from_user.id, "What's your name?")
        bot.register_next_step_handler(message, get_name)
    else:
        bot.send_message(message.from_user.id, 'Write /reg')

def get_name(message):
    global name
    name = message.text
    bot.send_message(message.from_user.id, "What's your last name?")
    bot.register_next_step_handler(message, get_last_name)

def get_last_name(message):
    global last_name
    last_name = message.text
    bot.send_message(message.from_user.id, 'How old are you?')
    bot.register_next_step_handler(message, get_age)

def get_age(message):
    global age
    if age == 0:
        try:
            age = int(message.text)
        except Exception:
            bot.send_message(message.from_user.id, 'Enter only numbers!')

    key = types.InlineKeyboardMarkup()
    yes = types.InlineKeyboardButton(text='Yes', callback_data='Yes')
    key.add(yes)
    no = types.InlineKeyboardButton(text='No', callback_data='No')
    key.add(no)

    question = f"Your name is {name}, " \
               f"\nyour last name is {last_name} " \
               f"\nand you're {age} years old, right?"

    bot.send_message(message.from_user.id, text=question, reply_markup=key)

@bot.callback_query_handler(func=lambda call: True)
def callback_worker(call):
    if call.data == 'Yes':
        bot.send_message(call.message.chat.id, 'Nice to meet you!')
    elif call.data == 'No':
        bot.send_message(call.message.chat.id, "Let's do it again! Write /reg")

bot.polling(none_stop=True, interval=1)


import numpy as np
import matplotlib.pyplot as plt
import random
from math import pi, sin, cos

def check(radius, point):
    return (radius/2)**2 > (point[0]**2+point[1]**2)

def get1(radius):
    x = 1
    y = 1
    while(x**2+y**2 > 1):
        x = random.random()*2-1
        y = random.random()*2-1
    return [x*radius, y*radius]

def get2(radius):
    dist = random.random()*radius
    theta = random.random()*2*pi
    return [dist*cos(theta), dist*sin(theta)]

def get3(radius):
    phi = random.random()*2*pi
    theta = random.random()*pi
    return [radius*cos(theta)*cos(theta+phi), radius*cos(theta)*sin(theta+phi)]

def draw(arr, radius, index, trys, save):
    fig, ax = plt.subplots(figsize=(10, 10))
    circle = plt.Circle((0, 0), radius, fill=False, color='black', lw=0.2)
    ax.set_xlim((-radius, radius))
    ax.set_ylim((-radius, radius))
    ax.add_artist(circle)
    ax.scatter(arr[0], arr[1], s=0.001)
    if save: fig.savefig('res'+str(index+1)+'.png')
    else: plt.show()

if __name__ == '__main__':
    radius = 1.00
    trytimes = 1000000
    get = [get1, get2, get3]
    for i in range(3):
        res = np.array([get[i](radius) for j in range(trytimes)])
        draw(res.T, radius, i, trytimes, True)
        compared = np.array([check(radius, point) for point in res])
        print(i, np.count_nonzero(compared))


"""
https://www.acmicpc.net/problem/11724
"""

import collections
import sys

sys.setrecursionlimit(10**6)

# n = number of vertex, m = number of line
n, m = map(int, sys.stdin.readline().split())
graph = collections.defaultdict(list)
for i in range(m):
    a, b = map(int, sys.stdin.readline().split())
    graph[a].append(b)
    graph[b].append(a)

# idea : dfs
been = [0 for _ in range(n)]
been.append(0)
been[0] = 1

def dfs(v):
    next_l = graph[v]
    for next_v in next_l:
        if been[next_v] == 1:
            continue
        been[next_v] = 1
        dfs(next_v)

ans = 0
idx = 0
while idx != -1:
    try:
        idx = been.index(0)
        ans += 1
        been[idx] = 1
        dfs(idx)
    except ValueError:
        idx = -1
print(ans)


import poseidon.poseidon
from requests.models import PreparedRequest

def CreateLogicalAsset(accessKey, secretKey, orgId, url, modelId):
    accessURL = url + '/asset-service/v2.1/logical-assets'
    params = {"action": "create", "orgId": orgId}
    req = PreparedRequest()
    req.prepare_url(accessURL, params)
    print(req.url)

    body={"assetInstance": {"modelId": modelId,
                            "name": {"defaultValue": "Demo_Python_Asset",
                                    "i18nValue": {"zh_CN": "演示Python断言", "en_US": "Asset_Demo_Python_Asset",
                                    "ja_JP": "デモPythonアサート", "es_ES": "DeclaraciónDePythonDeDemostración"}},
                            "timezone": "+08:00",
                            "description": "Asset_Description",
                            "attributes": {"Int_Attribute": 1,
                                           "Float_Attribute": 1.23,
                                           "String_Attribute": "Asset"},
                            "tags": {"AssetKey1":"AssetValue1",
                                     "AssetKey2":"AssetValue2",
                                     "AssetKey3":"AssetValue3"}
                            }
        }
    print(body)

    response = poseidon.poseidon.urlopen(accessKey, secretKey, req.url, body)
    print(response)

    AssetId = response["data"]
    return AssetId


import atexit
import time
from multiprocessing import Pool

from loguru import logger
from tqdm import tqdm

from reprobench.core.worker import BenchmarkWorker
from reprobench.managers.base import BaseManager

class LocalManager(BaseManager):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.num_workers = kwargs.pop("num_workers")
        self.start_time = None
        self.workers = []

    def exit(self):
        for worker in self.workers:
            worker.terminate()
            worker.join()

        logger.info(f"Total time elapsed: {time.perf_counter() - self.start_time}")

    def prepare(self):
        atexit.register(self.exit)
        self.start_time = time.perf_counter()

    @staticmethod
    def spawn_worker(job):
        server_address, run_id = job
        worker = BenchmarkWorker(server_address, run_id)
        worker.run()

    def spawn_workers(self):
        self.pool = Pool(self.num_workers)
        jobs = ((self.server_address, run_id) for run_id in self.queue)
        self.pool_iterator = self.pool.imap_unordered(self.spawn_worker, jobs)
        self.pool.close()

    def wait(self):
        progress_bar = tqdm(desc="Executing runs", total=len(self.queue))
        for _ in self.pool_iterator:
            progress_bar.update()
        progress_bar.close()
        self.pool.join()


from openpyxl import Workbook, load_workbook
from openpyxl.utils import get_column_letter

ori_wb = load_workbook('original.xlsx')
ori_ws = ori_wb.active

rank_wb = Workbook()

branch = 'AA'

rlist = []

for row in range(1, 1367):
  rollno = ori_ws['A' + str(row)].value
  dep = rollno[2:4]
  student = ori_ws['B' + str(row)].value
  cg = float((ori_ws['C' + str(row)].value).split(' ')[0])
  data = [cg, rollno, student]
  if not dep == branch:
    rlist.sort(reverse=True)
    rank_wb.create_sheet(branch)
    thisdep = rank_wb[branch]
    thisdep.append(['Rank', 'Roll No.', 'Name', 'CGPA'])
    for rank in range(1, len(rlist) + 1):
      data = [rank, rlist[rank-1][1], rlist[rank-1][2], rlist[rank-1][0]]
      thisdep.append(data)

    branch = dep
    rlist = []

  record = [cg, rollno, student]
  rlist.append(record)

rank_wb.save('Dep-RankList.xlsx')
print('Done')


#!/usr/bin/env python3

######################## IMPORT MODULES ##########################

import numpy as np				# If you find it required
import rospy
from sensor_msgs.msg import Image 	# Image is the message type for images in ROS
from cv_bridge import CvBridge	# Package to convert between ROS and OpenCV Images
import cv2
import cv2.aruco as aruco				# OpenCV Library
from cmath import atan # If you find it required
from geometry_msgs.msg import Pose2D	# Required to publish ARUCO's detected position & orientation

############################ GLOBALS #############################

aruco_publisher = rospy.Publisher('detected_aruco', Pose2D)
pi = 3.14
marker_coords = np.array([[0, 0], [500, 0], [500, 500], [0, 500]], dtype=np.float32)

##################### FUNCTION DEFINITIONS #######################

# NOTE :  You may define multiple helper functions here and use in your code
def pose(corners,ids):
	aruco_msg = Pose2D()
	bot = corners[np.where(ids == 15)[0][0]][0]
	x_axis = (bot[1][0]-bot[0][0])
	y_axis = (bot[0][1]-bot[1][1])
	angle = atan(y_axis/x_axis)
	if x_axis<0:
		if y_axis >0:
			angle += pi
		elif y_axis  <0:
			angle -= pi
	aruco_msg.x =(bot[0][0]+bot[1][0]+bot[2][0]+bot[3][0])*0.25
	aruco_msg.y =(bot[0][1]+bot[1][1]+bot[2][1]+bot[3][1])*0.25
	aruco_msg.theta = angle.real
	return aruco_msg

def crop(corners,ids,current_frame):

	marker_coords_detected = []
	marker_coords_detected.append(corners[np.where(ids == 4)[0][0]][0][3])
	marker_coords_detected.append(corners[np.where(ids == 8)[0][0]][0][0])
	marker_coords_detected.append(corners[np.where(ids == 10)[0][0]][0][1])
	marker_coords_detected.append(corners[np.where(ids == 12)[0][0]][0][2])
	marker_coords_detected = np.array(marker_coords_detected, dtype=np.float32)
	M = cv2.getPerspectiveTransform(marker_coords_detected, marker_coords)
	img_proj = cv2.warpPerspective(current_frame, M, (500, 500))
	return img_proj

def callback(data):
	# Bridge is Used to Convert ROS Image message to OpenCV image
	br = CvBridge()
	# rospy.loginfo("receiving camera frame")
	current_frame 		= br.imgmsg_to_cv2(data, "mono8")		# Receiving raw image in a "grayscale" format
	# current_frame 	= cv2.resize(get_frame, (500, 500), interpolation = cv2.INTER_LINEAR)
	aruco_dict		= aruco.Dictionary_get(aruco.DICT_4X4_50)
	arucoParameters = aruco.DetectorParameters_create()

	corners, ids, _ = aruco.detectMarkers(current_frame , aruco_dict, parameters=arucoParameters)

	if ids is not None:
		# corners=corners
		new_frame = crop(corners,ids,current_frame)
		arucoParameters.errorCorrectionRate = 1
		arucoParameters.adaptiveThreshConstant = 10
		corners, ids, _ = aruco.detectMarkers(new_frame , aruco_dict, parameters=arucoParameters)
		# print(ids)
		# if _ is not None:
		# 	print(_[1])

		aruco_msg = pose(corners,ids)
		length = f"{aruco_msg.x}, {aruco_msg.y}"
		cv2.putText(new_frame,length, (20,40), cv2.FONT_HERSHEY_SIMPLEX,0.5,(255, 255, 255),2)
		length = f"{aruco_msg.theta}"
		cv2.putText(new_frame,length, (20,60), cv2.FONT_HERSHEY_SIMPLEX,0.5,(255, 255, 255),2)
		image = aruco.drawDetectedMarkers(new_frame,corners,ids)
		cv2.imshow('Display',image)
		cv2.waitKey(1)
	else:
		print("Aruco markers not detected in image.")

def main():
	rospy.init_node('aruco_feedback_node')
	rospy.Subscriber('usb_cam/image_rect', Image, callback)
	rospy.spin()

if __name__ == '__main__':
  main()

Real Time Version 1/Trail/seperate nodes/feedback.py


from django.db import models

# Create your models here.
from django.urls import reverse

class AuditEntity(models.Model):
    created_on = models.DateTimeField(
        auto_now_add=True,
    )
    updated_on = models.DateTimeField(
        auto_now=True,
    )

    class Meta:
        abstract = True

class Department(AuditEntity):
    name = models.CharField(
        max_length=30,
    )

    def get_absolute_url(self):
        return reverse('department details', kwargs={
            'id': self.id,
        })

class Employee(models.Model):
    WEB_DEVELOPER = 1
    QA = 2
    DEV_OPS = 3

    GOOGLE = 'Google'
    SOFT_UNI = 'Softuni'

    COMPANIES = (
        GOOGLE,
        SOFT_UNI
    )

    first_name = models.CharField(
        max_length=30,
    )
    last_name = models.CharField(
        max_length=30,
        null=True,
        blank=True,
    )
    egn = models.CharField(
        max_length=10,
        unique=True,
        verbose_name='EGN',
    )
    job_title = models.IntegerField(
        choices=(
            (WEB_DEVELOPER, 'Web Developer'),
            (QA, 'QA'),
            (DEV_OPS, 'DevOps'),
        ),
    )

    company = models.CharField(
        max_length=max(len(i) for i in COMPANIES),
        choices=((c, c) for c in COMPANIES)  # geez
    )

    # one to many
    # department = models.ForeignKey(
    #     Department,
    #     on_delete=models.CASCADE,
    # )

    image = models.ImageField(
        null=True,
        blank=True,
        upload_to='profiles'
    )

    def __str__(self):
        return self.first_name

    class Meta:
        ordering = ('company', '-first_name',)

class Project(models.Model):
    name = models.CharField(
        max_length=30,
    )
    dead_line = models.DateField(
        null=True,
        blank=True,
    )

    # employeeS --> PLURAL
    # many to many
    employees = models.ManyToManyField(
        to=Employee,
    )  # ----> many to many -> exists only in one of the tables that are related, doesn't matter which one

class User(models.Model):
    email = models.EmailField()

    # one to one
    employee = models.OneToOneField(
        to=Employee,
        on_delete=models.CASCADE,
        primary_key=True,
    )

# class TestModel(models.Model):
#     id2 = models.IntegerField(
#         auto_created=True,
#         primary_key=True,
#     )


import cv2

def resize_and_save(image_path, output_path):
    # 读取图像
    img = cv2.imread(image_path)

    # 检查是否正确读取图像
    if img is None:
        print(f"Error: Unable to open image file: {image_path}")
        return

    # 调整图像大小
    resized_img = cv2.resize(img, (320, 240))

    # 保存调整后的图像
    cv2.imwrite(output_path, resized_img)

# 使用方式
resize_and_save('path_to_input_image', 'path_to_output_image')
"""
if（第一位等于 0x05 && 第二位等于）
{
    左转的GPIO
    while(1)
    {
        6050
        if （大于一定值）
        {
            break;
        }
    }
}
else if （第一位等于 0x05 && 第二位等于）
    {
        右转的GPIO
    while(1)
    {
        6050
        if （大于一定值）
        {
            break;
        }
    }
    }

"""


# coding:utf-8
# --author-- lanhua.zhou
from __future__ import print_function

import logging

import maya.cmds as cmds

import zfused_api

import zfused_maya.core.record as record

from zwidgets.assetwidget import assetmanagewidget

from zfused_maya.ui.widgets import window

import zfused_maya.node.core.attr as attr

__all__ = ["AssetManageWidget"]

logger = logging.getLogger(__name__)

class AssetManageWidget(window._Window):
    def __init__(self, parent = None):
        super(AssetManageWidget, self).__init__()
        self._build()

        self.asset_widget.reference_by_attr.connect(self._reference)

    def _reference(self, version_id, output_attr_id):
        _version = zfused_api.version.Version(version_id)

        # asset type
        _type = _version.project_entity().type()
        _type_code = _type.code()
        _type_code = "{}_group".format(_type_code)
        if not cmds.objExists(_type_code):
            cmds.createNode("transform", name = _type_code)

        _task = _version.task()
        _project_step = _task.project_step()
        _output_attr = zfused_api.attr.Output(output_attr_id)

        _production_file = _version.production_file()
        _production_file = ".".join(_production_file.split(".{:0>4d}.".format(_version.index())))

        _ori_assemblies = cmds.ls(assemblies=True)
        _ns = "{}__ns__00".format(_task.project_entity().file_code())
        rf = cmds.file(_production_file, r = True, ns = _ns)
        rfn = cmds.referenceQuery(rf, rfn = True)
        _new_assemblies = cmds.ls(assemblies=True)
        _asset_tops = list(set(_new_assemblies) - set(_ori_assemblies))
        if _asset_tops:
            for _asset_top in _asset_tops:
                try:
                    cmds.parent(_asset_top, _type_code)
                except:
                    pass

    def _build(self):
        self.resize(1600, 900)
        self.set_title_name(u"资产管理(asset management)")
        self.set_help_url("tool/utility/asset_management")

        self.asset_widget = assetmanagewidget.AssetManageWidget()
        self.set_central_widget(self.asset_widget)

    def showEvent(self, event):
        _project_id = record.current_project_id()
        _company_id = record.current_company_id()
        self.asset_widget.load_project_id(_project_id, _company_id)
        super(AssetManageWidget, self).showEvent(event)


import pickle
import itertools
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
import numpy as np
from sklearn.utils import class_weight
from sklearn import metrics
import matplotlib.pyplot as plt
from imblearn.under_sampling import RandomUnderSampler
from sklearn.metrics import classification_report
from sklearn.model_selection import StratifiedKFold

class Random_Forest_model:
    def __init__(self, labels=None, dataset=None, title=None):
        self.labels = labels
        self.dataset = dataset
        self.title = title

    #split train 80, test 20
    #save the datasets in pickle files
    def train_test_stratified(self):
        train_set, test_set, train_label, test_label = train_test_split(self.dataset, self.labels, stratify=self.labels,test_size=0.30)
        title = "../datasets/train_set.p"
        with open(title, 'wb') as fp:
            pickle.dump(train_set, fp)
        title = "../datasets/train_label.p"
        with open(title, 'wb') as fp:
            pickle.dump(train_label, fp)
        title = "../datasets/test_set.p"
        with open(title, 'wb') as fp:
            pickle.dump(test_set, fp)
        title = "../datasets/test_label.p"
        with open(title, 'wb') as fp:
            pickle.dump(test_label, fp)

    def train_validation_undersampling(self, train_set, train_label, sampling_strategy):
        self.train_set, self.validation_set, self.train_label, self.validation_label = train_test_split(train_set, train_label, stratify=train_label,test_size=0.15)
        # RandomUnderSampler
        sampler = RandomUnderSampler(sampling_strategy=sampling_strategy, random_state=42)
        self.train_set, self.train_label = sampler.fit_sample(self.train_set, self.train_label)
        print(self.train_set.shape)
        print(self.train_label.shape)
        sampler = RandomUnderSampler(sampling_strategy=sampling_strategy, random_state=42)
        self.validation_set, self.validation_label = sampler.fit_sample(self.validation_set, self.validation_label)
        print(self.validation_set.shape)
        print(self.validation_label.shape)
        title = "../datasets/train_under_set.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.train_set, fp)
        title = "../datasets/train_under_label.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.train_label, fp)
        title = "../datasets/validation_under_set.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.validation_set, fp)
        title = "../datasets/validation_under_label.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.validation_label, fp)

    def train_validation_raw(self, train_set, train_label):
        self.train_set, self.validation_set, self.train_label, self.validation_label = train_test_split(train_set, train_label, stratify=train_label, test_size=0.15)
        title = "../datasets/train_raw_set.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.train_set, fp)
        title = "../datasets/train_raw_label.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.train_label, fp)
        title = "../datasets/validation_raw_set.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.validation_set, fp)
        title = "../datasets/validation_raw_label.p"
        with open(title, 'wb') as fp:
            pickle.dump(self.validation_label, fp)

    def random_forest_model(self, weight_flag=False):
        if weight_flag is True:
            #fit the model
            model = RandomForestClassifier(class_weight='balanced', bootstrap= True, max_depth= 20, max_features= 5, min_samples_leaf= 15, min_samples_split= 30, n_estimators= 100)
        else:
            model = RandomForestClassifier(bootstrap=False, max_depth=20, max_features=4, min_samples_leaf=5,
                                           min_samples_split=10, n_estimators=400, criterion='entropy')
        return model

    def random_forest_fit(self, model, train_set, train_label):
        model = model.fit(train_set, train_label)
        #saving the model into a pickle file
        title_model = '../results/trained_rf_'+str(self.title)+'.p'
        pickle.dump(model, open(title_model, 'wb'))
        return model

    def random_forest_prediction(self, model, test_set, test_label):
        self.predictions = model.predict(test_set)
        score = model.score(test_set, test_label)
        report = classification_report(test_label, self.predictions)
        title = "../results/report_"+self.title+".txt"
        write_report = open(title,"w")
        write_report.write(report)
        print(report)
        return report

    def plot_confusion_matrix_multi(self, cm,target_names, cmap=None, normalize=True):
        accuracy = np.trace(cm) / float(np.sum(cm))
        misclass = 1 - accuracy
        if cmap is None:
            cmap = plt.get_cmap('Blues')
        plt.figure(figsize=(8, 6))
        plt.imshow(cm, interpolation='nearest', cmap=cmap)
        plt.title('Confusion Matrix for the Random Forest for mobility data \n Stratified sample \n', size=16)
        plt.colorbar()
        if target_names is not None:
            tick_marks = np.arange(len(target_names))
            plt.xticks(tick_marks, target_names, size=14)
            plt.yticks(tick_marks, target_names, size=14)
        if normalize:
            cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        thresh = cm.max() / 1.5 if normalize else cm.max() / 2
        for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
            if normalize:
                plt.text(j, i, "{:0.4f}".format(cm[i, j]),
                         horizontalalignment="center",
                         color="grey" if cm[i, j] > thresh else "black", size=14)
            else:
                plt.text(j, i, "{:,}".format(cm[i, j]),
                         horizontalalignment="center",
                         color="grey" if cm[i, j] > thresh else "black", size=14)
        plt.tight_layout()
        plt.ylabel('True label', size=14)
        plt.gcf().subplots_adjust(bottom=0.20)
        plt.xlabel('\n Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass), size=14)
        plt.savefig('../results/cm_'+str(self.title)+'.png')

    def confusion_matrix(self, test_label, target_names, cmap=None, normalize=True):
        cm = metrics.confusion_matrix(test_label, self.predictions)
        accuracy = np.trace(cm) / float(np.sum(cm))
        misclass = 1 - accuracy
        if cmap is None:
            cmap = plt.get_cmap('Blues')
        plt.figure(figsize=(8, 6))
        plt.imshow(cm, interpolation='nearest', cmap=cmap)
        plt.title('confusion_matrix'+self.title)
        plt.colorbar()
        if target_names is not None:
            tick_marks = np.arange(len(target_names))
            plt.xticks(tick_marks, target_names, rotation=45)
            plt.yticks(tick_marks, target_names)
        if normalize:
            cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        thresh = cm.max() / 1.5 if normalize else cm.max() / 2
        for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
            if normalize:
                plt.text(j, i, "{:0.4f}".format(cm[i, j]),
                         horizontalalignment="center",
                         color="white" if cm[i, j] > thresh else "black")
            else:
                plt.text(j, i, "{:,}".format(cm[i, j]),
                         horizontalalignment="center",
                         color="white" if cm[i, j] > thresh else "black")
        plt.tight_layout()
        plt.ylabel('True label')
        plt.xlabel('Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))
        plt.savefig('../results/cm_'+str(self.title)+'.png')


from rest_framework import serializers
from rest_framework.relations import SlugRelatedField

from posts.models import Comment, Post, Group, User, Follow

class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = '__all__'

class CommentSerializer(serializers.ModelSerializer):
    author = serializers.SlugRelatedField(
        read_only=True, slug_field='username'
    )
    post = serializers.PrimaryKeyRelatedField(
        read_only=True
    )

    class Meta:
        fields = '__all__'
        model = Comment

class PostSerializer(serializers.ModelSerializer):
    author = SlugRelatedField(slug_field='username', read_only=True)
    comments = CommentSerializer(read_only=True, many=True)

    class Meta:
        fields = '__all__'
        model = Post

class FollowSerializer(serializers.ModelSerializer):
    user = serializers.SlugRelatedField(
        read_only=True,
        slug_field='username',
        default=serializers.CurrentUserDefault()
    )
    following = serializers.SlugRelatedField(
        slug_field='username',
        queryset=User.objects.all()
    )

    class Meta:
        fields = '__all__'
        model = Follow


import pandas as pd
from webScrapping import toDF
import folium
import webbrowser

pd.set_option('display.width', 340)
pd.set_option('display.max_columns', 8)
earthquakeDF = toDF()
print(earthquakeDF.to_string())
earthquakeMap = folium.Map(location=[39.16, 35.66], zoom_start=5.5, tiles="Stamen Terrain")
folium.GeoJson('https://raw.githubusercontent.com/fraxen/tectonicplates/master/GeoJSON/PB2002_boundaries.json',
               name="geojson").add_to(earthquakeMap)
folium.LayerControl().add_to(earthquakeMap)

def addCircles(df):
    for x, y, z, *a in zip(df['Latitude'], df['Longitude'], df['Magnitude [ML]'], df['Location'], df['Date'], df['Time']):
        popUp = f"
Magnitude : {z} ML
" \
                f"
Location - Date: {a}
"
        iframe = folium.IFrame(popUp, width=450, height=70)
        popup = folium.Popup(iframe, max_width=450)
        folium.CircleMarker(location=(x, y), radius=float(z) * 4, weight=2, opacity=1, popup=popup,
                            color="red", fill_color="red", fill_opacity=0.1).add_to(earthquakeMap)

addCircles(earthquakeDF)
earthquakeMap.save("map.html")
webbrowser.open("map.html")


from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
from random import random
from bs4 import BeautifulSoup
import pandas as pd

def to_float(x): # converts strange strings to float
    a = ""
    flag = 0 # have we met "," or "."
    for i in x:
        if ord(i) >= ord("0") and ord(i) <= ord("9"):
            a += i
        elif not flag and (i == "." or i == ","):
            a += i
            flag = 1
    a = a.replace(",", ".")
    return float(a)

options = webdriver.ChromeOptions() # setting options for window
options.add_argument('headless')
options.add_argument('window-size=1920x1080')
options.add_argument("disable-gpu")

driver = webdriver.Chrome('chromedriver', options=options) # start and get target page
driver.get("https://store.steampowered.com/specials#p=0&tab=TopSellers")
html = driver.page_source
soup = BeautifulSoup(html, "html.parser")
totalpages = (soup.find("span", {"id" : "TopSellers_links"})).find_all("span", {"class" : "paged_items_paging_pagelink"})
totalpages = int(totalpages[-1].getText())

header = ["Game", "Original price", "Discount", "Final price"]
table = []
current_page = 0

while (current_page < totalpages):
    html = driver.page_source
    soup = BeautifulSoup(html, "html.parser")
    soup = soup.find("div", {"id" : "TopSellersTable"})
    games = soup.find_all("div", {"class" : "tab_item_name"})
    original_prices = soup.find_all("div", {"class" : "discount_original_price"})
    discounts = soup.find_all("div", {"class": "discount_pct"})
    final_prices = soup.find_all("div", {"class": "discount_final_price"})
    for i in range(len(games)):
        games[i] = games[i].getText()
        original_prices[i] = to_float(original_prices[i].getText())
        discounts[i] = to_float(discounts[i].getText())
        final_prices[i] = to_float(final_prices[i].getText())
        table.append([games[i], original_prices[i], discounts[i], final_prices[i]])
    sleep(1 + 2 * random()) # 1 - 3 sec
    current_page += 1
    element = driver.find_element(By.ID, "TopSellers_btn_next")  # find and push button to increase list of games to parse
    element.click()
    sleep(1 + 2 * random())

pd.DataFrame(table).to_csv('SteamDiscounts.csv', index=False, header=header)

driver.quit()


import asyncore
import select
import time
import uuid

from .util import debug

TIMERS = {}

def loop(timeout=1, use_poll=False, map=None, count=None):
    if map is None:
        map = asyncore.socket_map

    if use_poll and hasattr(select, 'poll'):
        poll_fun = asyncore.poll2
    else:
        poll_fun = asyncore.poll

    if count is None:
        while map:
            poll_fun(timeout, map)
            _check_timers()
    else:
        while map and count > 0:
            poll_fun(timeout, map)
            _check_timers()
            count = count - 1

def _check_timers():
    now = time.time()
    calls = {}
    for timer_id, timer in TIMERS.items():
        if now >= timer.get('when'):
            calls[timer_id] = timer.get('what')
            if timer.get('interval') is not None:
                timer['when'] = time.time() + timer.get('interval')

    for timer_id, call in calls.items():
        try:
            call()
        except Exception as e:
            debug("ERRO", "Exception running interval callback for timer {}: ".format(timer_id), e)
            import traceback
            traceback.print_exc()

def set_timeout(callback, timeout):
    def call_and_expire():
        del TIMERS[timer_id]
        return callback()

    timer_id = uuid.uuid4()
    TIMERS[timer_id] = {
        'when': time.time() + timeout,
        'what': call_and_expire,
        'interval': None,
    }
    return timer_id

def set_interval(callback, timeout):
    timer_id = uuid.uuid4()
    TIMERS[timer_id] = {
        'when': time.time() + timeout,
        'what': callback,
        'interval': timeout,
    }
    return timer_id

def cancel_timeout(timer_id):
    if timer_id not in TIMERS:
        debug("WARN", "Trying to cancel timeout timer {} which doesn't exist. This should be fixed".format(timer_id))
        return
    del TIMERS[timer_id]

def cancel_interval(timer_id):
    if timer_id not in TIMERS:
        debug("WARN", "Trying to cancel interval timer {} which doesn't exist. This should be fixed".format(timer_id))
        return
    del TIMERS[timer_id]


import discord
from discord.ext import commands
from discord.ext.commands import has_permissions
from functions import *
from utils import *

intents = discord.Intents(messages=True, guilds=True, reactions=True, members=True, presences=True)
Bot = commands.Bot(command_prefix='.', intents=intents)
game = Game()
bot = discord.ext.commands.Bot(command_prefix="your_prefix");

@Bot.event
async def on_ready():
    print("Let's Go ")

@Bot.event
async def on_member_join(member):
    channel = discord.utils.get(member.guild.text_channels, name="gelenler")
    await channel.send(f"{member} Sunucuya Katıldı.")
    print(f"{member} Sunucuya Katıldı.")

@Bot.event
async def on_member_remove(member):
    channel = discord.utils.get(member.guild.text_channels, name="gelenler")
    await channel.send(f"{member} Sunucudan Ayrıldı.")
    print(f"{member} Sunucudan Ayrıldı.")

@Bot.command()
# @has_permissions(administrator=True)
async def sil(ctx, amount=5):
    await ctx.channel.purge(limit=amount)
    print(f"Başarı ile temizlendi.")

    # @Bot.command()
    # async def join(ctx):
    #    channel = message.author.voice.channel
    #    await channel.connect()

    # @Bot.command(pass_content=True)
    # async def join(ctx):
    #    channel = ctx.author.voice.channel
    #    await channel.connect()

@Bot.command()
async def join(ctx):
    if (ctx.author.voice):
        channel = ctx.author.voice.channel
        await channel.connect()
        await ctx.send('Bot joined')
    else:
        await ctx.send("You must be in a voice channel first so I can join it.")

@Bot.command()
async def leave(
        ctx):
    if (ctx.voice_client):
        await ctx.guild.voice_client.disconnect()
        await ctx.send('Bot left')
    else:
        await ctx.send("I'm not in a voice channel, use the join command to make me join")

# @Bot.command(pass_content=True)
# async def leave(ctx):
#   channel = ctx.message.author

# await ctx.send(f'Bot Herhangi Bir Odada Değil')py
# return

@Bot.command(aliases=["kopyala"])
@has_permissions(administrator=True)
async def clone_channel(ctx, amount=1):
    for i in range(amount):
        await ctx.channel.clone()

@Bot.command(pass_context=True)
@has_permissions(administrator=True)
async def kick(ctx, user: discord.Member):
    await ctx.send(f'The Kicking Hammer Has Awoken! {user.name} Has Been Banished', )
    await ctx.guild.kick(user)

@Bot.command(pass_context=True)
@has_permissions(administrator=True)
async def ban(ctx, user: discord.Member):
    await ctx.send(
        f'Ban Çekicini Kafasına Yedi! {user.name} Artık Uzaklarda!' 'https://media1.giphy.com/media/fe4dDMD2cAU5RfEaCU/giphy.gif?cid=ecf05e47kie7ltgktey7bkzrng32arpvxbfuk6fyd3niq0da&rid=giphy.gif')
    await ctx.guild.ban(user)
    return

@Bot.command()
@has_permissions(administrator=True)
async def unban(ctx, *, member):
    banned_users = await ctx.guild.bans()
    member_name, member_discriminator = member.split('#')

    for bans in banned_users:
        user = bans.user

        if (user.name, member_discriminator) == (member_name, member_discriminator):
            await ctx.guild.unban(user)
            await ctx.send(
                f'Geri Getirme Büyüsü Yapıldı! {user.name} Artık Aramıza Gelebilir!' 'https://media0.giphy.com/media/MB6OMCu3uQQrgVIsSu/giphy.gif')
            return

@Bot.command()
async def komutlar(ctx):
    await ctx.send('amcıemre1 amcıemre2 join leave zar at')

@Bot.command()
async def amciemre1(ctx, *args):
    await ctx.send('https://tenor.com/view/polis-emre-amcık-görüyor-gif-19133767')

@Bot.command()
async def amciemre2(ctx, *args):
    await ctx.send('https://tenor.com/view/seemih-fidan-emre-amcıemre-31-gif-19753463')

@Bot.command()
async def yarra(ctx):
    await ctx.send('https://tenor.com/view/yarra-yarra-beni-yarra-aşkına-beter-beter-ali-gif-16749214')

@Bot.command()
async def fcukyou(ctx):
    await ctx.send('https://media.discordapp.net/attachments/763053037332725790/805519690617192518/image0-34.gif')

@Bot.command()
@has_permissions(administrator=True)
async def aktif(ctx):
    await ctx.send('https://cdn.discordapp.com/attachments/814893842469617665/817484594706251776/giphy.gif')

@Bot.command(aliases=["zar"])
async def lafıkoyunca(ctx, *args):
    if "at" in args:
        await ctx.send(game.at_dice())
    else:
        await ctx.send(
            '@everyone,https://tenor.com/view/kerpeten-ali-kerpeten-ali-kerpeten-dans-hip-hop-dans-gif-19947997')

@Bot.command()
async def lspd(ctx,):
        await ctx.send(
            'https://media.giphy.com/media/QUY2pzDAKVpX3QacCg/giphy.gif')

@Bot.command()
async def ip(ctx, ):
        await ctx.send(
            'F8 connect 185.88.174.226 TS3 IP : navyts3')

@Bot.command()
async def woul(ctx, ):
        await ctx.send(
            'connect 185.126.178.26 TeamSpeak: woulroleplay')

Bot.run(TOKEN)


import numpy as np
from matplotlib import pyplot as plt
import time

start = time.time()

B_ex = 2
J_par = 1
J_tan = 1
# Runtime around 9 seconds with n_max = 8, almost instant for lower values.
# n_max = 10 takes quite some time.
n_max = 10
beta_const = 0.5
kb = 1.3806485279e-23

def gen_spin_conf(n):
	spin_conf = np.ones([2**n, n])
	for i in range(n):
		spin_conf.T[i] = np.array([[1]*2**(i) + [-1]*2**(i)] * ((2**n)//(2**(i+1)))).flatten()
	return spin_conf

# Generates A, B and C without prefactors Be and beta
def gen_ABC(spin_conf, Jp=J_par, Jt=J_tan):
	dim = spin_conf.shape[0]
	A = Jp * np.matmul(spin_conf, spin_conf.T)
	B = Jt * np.repeat(np.sum(spin_conf * np.apply_along_axis(np.roll, 1, spin_conf, 1), axis=1).reshape(dim,1), dim, axis=1)
	sum_vec = np.sum(spin_conf, axis=1)
	C = (1/2) * (np.tile(sum_vec, [dim, 1]).T + sum_vec.T)
	return A, B, C

def max_eigen_value(A, B, C, spin_conf, beta, Be):
	P = np.exp(beta*A + beta*B + beta*Be*C)
	e_vals = np.linalg.eigvals(P)
	return np.amax(np.real(e_vals))

beta_vals = np.linspace(0.005, 1, 100)
B_vals = np.linspace(-1, 1, 100)
T_vals = 1/(kb*beta_vals)
eigen_val_vec = np.zeros([n_max, 100])
eigen_val_vec_b = np.zeros([n_max, 100])
eigen_val_vec_d = np.zeros([n_max, 100])
spes_heat_vec = np.zeros([4, 100])

# Loop computes everything using functions and values defined above:
for i in range(n_max):
	spin_conf = gen_spin_conf(i+1)
	print("n: ",i+1)
	A, B, C = gen_ABC(spin_conf)
	for j in range(beta_vals.size):
		eigen_val_vec[i][j] = np.log(max_eigen_value(A, B, C, spin_conf, beta_vals[j], B_ex))
		eigen_val_vec_b[i][j] = np.log(max_eigen_value(A, B, C, spin_conf, beta_const, B_vals[j]))
	if i+1 <= 5 and i+1 >= 2:
		for k in range(beta_vals.size):
			spes_heat_vec[i-1] = np.gradient(np.gradient(eigen_val_vec[i], beta_vals), beta_vals)*((beta_vals[k]**2)/(i+2))
	eigen_val_vec_d[i] = np.gradient(eigen_val_vec_b[i], B_vals)/((i+2)*beta_const)
	print(i+1," done", n_max - i -1, " to go.")

end = time.time()
print("Computation time: ", end - start, " seconds")

# Computations done, plotting:
for i in range(eigen_val_vec.shape[0]):
	plt.plot(beta_vals, eigen_val_vec[i], label="n = " + str(i+1))
plt.title("Largest eigenvalues -  $B=$" + str(B_ex) + ", $Jp=$" + str(J_par) + ", $Jt=$" + str(J_tan))
plt.legend()
plt.xlabel("beta - $1/k_{b}} \dot T$")
plt.ylabel("Eigenvalue")
plt.savefig("fig1.pdf")
plt.show()

for i in range(eigen_val_vec_d.shape[0]):
	plt.plot(B_vals, eigen_val_vec_d[i], label="n=" + str(i+1))
plt.title("Magnetization per spin - $beta = $" + str(beta_const)  + ",$ Jp=$" + str(J_par) + ", $Jt=$" + str(J_tan))
plt.legend()
plt.xlabel("External magnetic field - $B$")
plt.ylabel("Magnetization per spin - $m$")
plt.savefig("fig2.pdf")
plt.show()

for i in range(spes_heat_vec.shape[0]):
	# Not sure what's best of plotting with regards to T or beta(T)
	plt.plot(T_vals, spes_heat_vec[i], label="n=" + str(i+2))
plt.title("Specific heat per spin -  $B=$" + str(B_ex) + ", $Jp=$" + str(J_par) + ", $Jt=$" + str(J_tan))
plt.legend()
plt.xlabel("Temperature - $T$")
plt.ylabel("Spesific heat per spin - $C_{B}$")
plt.savefig("fig3.pdf")
plt.show()


# -*- coding: utf-8 -*-
import json
from selenium import webdriver
import re

def save_json_file(data, filename):
    # save data in json file
    with open(filename + '.json', 'w', encoding='utf8') as outfile:
        json.dump(data, outfile)

def read_json_file(filename):
    # read json file and return json object
    data = []
    with open(filename, 'r') as outfile:
        data = json.load(outfile)
    return data

def web_driver():
    # web driver for headless chrome
    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    options.add_argument('--ignore-certificate-errors')
    options.add_argument('window-size=1200x600')

    driver = webdriver.Chrome(chrome_options=options)
    driver.maximize_window()
    return driver

def get_emails(source):
    # find email in source using regex match
    regex = re.compile('[\w\.-]+@[\w\.-]+\.\w+')
    return [email for email in re.findall(regex, source)]


import numpy as np
import matplotlib.pyplot as plt

import mapsList

class Map:

    def __init__(self, F, dimension: int, param, name: str):
        ''' A class for maps.

        A map is a discrete-time dynamical system.
        It is characterized by a function F: X -> X, where X is the space in which the map acts.

        Parameters
        ----------
        F:
            The function characterizing the map such that F(x(t)) = x(t+1)
        dimension:
            the dimensionality of the space X
        param
            the parameters of the map
        name: string
            The name of the map
        '''

        self.dimension = dimension
        self.param = param
        self.F = F
        self.name = name
        self.n_iter = None

    def trajectory(self, x_0: np.array, n_iter: int) -> np.array:
        '''
        return a trajectory of the map.

        Parameters
        ----------
        x_0 : np.array[dimension]
            An arraywith the initial conditions of the system.
            Its dimension must be the same of the map.
        n_iter: int
            the number of iteration that the map has to do.

        Returns
        -------
        X : np.array
            np.array with dimensions (dimension, n_iter+1)
        '''
        self.n_iter = n_iter

        X = np.zeros((self.dimension, self.n_iter))
        X[:, 0] = x_0
        x = x_0

        for k in range(1, n_iter):
            y = self.F(x, self.param)
            X[:, k] = y
            x = y

        self.X = X
        return X

    def _repeated(self, x, n: int):
        ''' Applies the map 'n' times to a point x.
        This means computing F^n(x)

        Parameters
        ----------
        x
            The point starting from which the map is iterated
        n
            The number of iteration
        Returns
        -------
        F^n(x), i.e., the map iterated n times

        '''
        for _ in range(n):
            x = self.F(x, self.param)
            # print x
        return x

    def plot_map(self, n_iter=1, x_min=0, x_max=1):
        ''' A function plotting the graph of the map.

        The map must be 1-dimensional!
        The x-axis represent x(t) while the y-axis is x(t+1) = F(x(t)).
        It can be used to plot multiple iteration of a map, i.e., plotting G(x) = F^n(x).

        Parameters
        ----------
        n_iter : int, default=1
            number of iteration of the map.
        x_min,x_max : int, default = 0,1
            The min and max value to be visualized, for both axis.
        '''
        x = np.arange(x_min, x_max, 0.0001)
        Fig = plt.figure(figsize=(5, 5))
        ax = Fig.add_subplot(111)

        ax.plot(x, self._repeated(x, n_iter))
        ax.plot(x, x, 'k')

        ax.set_xlim(x_min, x_max)
        ax.set_ylim(x_min, x_max)

        ax.set_xlabel('x[n]')
        ax.set_ylabel('x[n+1]')

        if n_iter == 1:
            ax.set_title('{} map'.format(self.name, n_iter), fontsize=16)
        else:
            ax.set_title('{} map iterated {} times'.format(self.name, n_iter), fontsize=16)

        plt.tight_layout()
        plt.show()

# ------------------------------------------------------

class Logistic(Map):
    def __init__(self, r=3.5):
        ''' Logistic map F(x) = r*x*(1-x)

        Parameters
        ----------
        r : float, default = 3.5
            the value of the parameter r of the map.
        '''
        super().__init__(mapsList.logistic, 1, r, "Logistic")

# -----------------------------------------------------------
class Tent(Map):
    def __init__(self, r=2):
        ''' Tent map  F(x) = r*min(x, 1-x)
        Parameters
        ----------
        r : float, default = 2
            the value of the parameter r of the map.
        '''
        super().__init__(mapsList.tent, 1, r, "Tent")

# ---------------------------------------------------------------

class Shift(Map):
    def __init__(self, r=1):
        ''' Shift map F(x) = r*( 2*x mod(1) )

        Parameters
        ----------
        r: float, default = 1
            the value of the parameter r of the map.
        '''
        super().__init__(mapsList.shift, 1, r, "Shift")

# -------------------------------------------------

class Quadratic(Map):
    def __init__(self, r=2):
        ''' Quadratic map F(x) = x**2 - r

        Parameters
        ----------
        r: float, default = 2
            the value of the parameter r of the map.
        '''
        super().__init__(mapsList.quadratic, 1, r, "Quadratic")


from django.conf.urls import url
from .views import (get_issues, show_issue, new_issue,
                    display_screenshot, voting)

urlpatterns = [
    url(r'^all/', get_issues, name="issues"),
    url(r'^(?P<pk>\d+)$', show_issue, name="show_issue"),
    url(r'^new/', new_issue, name="new_issue"),
    url(r'^(?P<pk>\d+)/screenshot$', display_screenshot, name="screenshot"),
    url(r'^(?P<pk>\d+)/voting$', voting, name="voting"),
    ]


import pygame

class Cloud:

    def __init__( self, x, y, width, height ):
        self.mX = x
        self.mY = y
        self.mWidth = width
        self.mHeight = height
        self.mColor = ( 251, 200, 122 )
        return

    def darken( self ):
        r, g, b = self.mColor
        r *= 0.9
        g *= 0.9
        b *= 0.9
        self.mColor = (int(r),int(g),int(b))
        return

    def lighten( self ):
        r, g, b = self.mColor
        r *= 1.1
        g *= 1.1
        b *= 1.1
        self.mColor = (min(int(r),255), min(int(g),255), min(int(b),255) )
        return

    def evolve( self, dt ):
        return

    def draw( self, surface ):

        rect = pygame.Rect( int ( self.mX ), int ( self.mY ), int ( self.mWidth ), int ( self.mHeight ) )
        pygame.draw.ellipse( surface, self.mColor, rect, 0 )

        return


"""Run job in the background on the same system."""
from __future__ import annotations

import logging
import os
import subprocess
from pathlib import Path
from typing import ClassVar, Optional

from .core import Job

logger = logging.getLogger(__name__)

class LocalJob(Job):
    __doc__ = """ Use Jobqueue with local bash commands

    This is mostly for testing.  It uses all the same machinery of
    jobqueue, but rather than submitting jobs to some external job
    queueing system, it launches them locally.

    Parameters
    ----------
    plugin args
    """

    config_name: ClassVar[str] = "local"
    cancel_command: ClassVar[str] = "kill -QUIT"

    def __init__(
        self,
        name: Optional[str] = None,
        queue: Optional[str] = None,
        project: Optional[str] = None,
        resource_spec: Optional[str] = None,
        walltime: str = "",
        job_extra: Optional[list[str]] = None,
        env_extra: Optional[list[str]] = None,
        **kwargs,
    ):
        # Instantiate args and parameters from parent abstract class
        env_extra = env_extra or []
        env_extra = [
            "cleanup() {",
            "      echo 'Caught SIGINT, cleaning up...'",
            "      kill -QUIT $PLUGIN_ID",
            "      exit 1",
            "}",
            "trap 'cleanup' QUIT",
            "PID=$(pgrep -f $0)",
        ] + env_extra
        kwargs["memory"] = 1
        super().__init__(
            name=name,
            shebang="#!/usr/bin/env bash",
            env_extra=env_extra,
            **kwargs,
        )

        # Declare class attribute that shall be overridden
        self.job_header = ""
        if self.log_directory:
            out_file = Path(self.log_directory) / f"{self.job_name}-$PID.out"
            self._command_template += f" &> {out_file} &\n"
        self._command_template += "PLUGIN_ID=$!\nwait $PLUGIN_ID"
        logger.debug(f"Job script: \n {self.job_script()}")

    def _submit_job(self, script_filename):
        # Should we make this async friendly?
        cmd = ["/usr/bin/env", "bash", script_filename]
        process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            encoding="utf-8",
            env=os.environ.copy(),
        )
        return str(process.pid)

    @classmethod
    def _close_job(cls, job_id, cancel_command):
        os.kill(int(job_id), 9)


#!/usr/bin/env python3
# --------------------------------------------------
# Fábio Sousa.
# SAVI, December 2022.
# --------------------------------------------------

import cv2
import open3d as o3d
from copy import deepcopy
import numpy as np
from point_cloud_processing import PointCloudProcessing
from matplotlib import cm
from more_itertools import locate

def main():

    #Initial view parameters
    view = {
	"class_name" : "ViewTrajectory",
	"interval" : 29,
	"is_loop" : False,
	"trajectory" :
	[
		{
			"boundingbox_max" : [ 0.90000000000000002, 0.90000000000000002, 0.5 ],
			"boundingbox_min" : [ -0.90000000000000002, -0.90000000000000002, -0.10000000000000003 ],
			"field_of_view" : 60.0,
			"front" : [ 0.57428340315845261, 0.72415504342386261, 0.38183510307530683 ],
			"lookat" : [ -0.23064077816298553, -0.2045093977126011, 0.17408966530741635 ],
			"up" : [ -0.36479928025136604, -0.19118507801017759, 0.91124626258455921 ],
			"zoom" : 0.79999999999999893
		}
	],
	"version_major" : 1,
	"version_minor" : 0
}

    # ------------------------------------------
    # Initialization
    # ------------------------------------------
    p = PointCloudProcessing() #Calls the class
    p.loadPointCloud('../data/scene.ply') #Gives the filename to class

    # ------------------------------------------
    # Execution
    # ------------------------------------------
    p.preProcess(voxel_size=0.01) #PreProcessing

    #?Center the origin in the table
    p.transform(-110, 0, 0, 0, 0, 0) #Rotate in x
    p.transform(0, 0, 52, 0, 0, 0) #Rotate in z
    p.transform(0, 0, 0, 1.1, -0.8, 0.37) #Translation in xyz

    #?Creates a bbox of points to keep
    p.crop(-0.9, -0.9, -0.3, 0.9, 0.9, 0.3)
    #Order: (x,y,z) min and (x,y,z) max

    outliers = p.findPlane() #Find the table plane
    p.inliers.paint_uniform_color([0,1,0]) #Paints the plane in green

    #?Now we isolate the objects (cluster the points for each one)
    cluster_idxs = list(outliers.cluster_dbscan(eps=0.035, min_points=60, print_progress=True))
    #Cluster returns points associated to an ID and gives the same ID for points in the defined range
    #If eps small, no object is going to be detected

    object_idxs = list(set(cluster_idxs))
    object_idxs.remove(-1) #Removes -1 cluster ID (-1 are the points not clustered)

    number_of_objects = len(object_idxs)

    #Color each cluster with a different color using colormap
    colormap = cm.Pastel1(list(range(0,number_of_objects)))

    #Create the objects list
    objects = []

    #Here we find the points for each object and reunite them
    for object_idx in object_idxs:

        #Locate the points, comparing each cluster id to the object id, grouping them and converts the result to list because it's easier
        object_point_idxs = list(locate(cluster_idxs, lambda x: x == object_idx))
        object_points = outliers.select_by_index(object_point_idxs)

        #Create a dictionary to define the objects
        d = {}
        d['idx'] = str(object_idx)
        d['points'] = object_points
        d['color'] = colormap[object_idx, 0:3]
        d['points'].paint_uniform_color(d['color']) #Paints the point in the defined color
        d['center'] = d['points'].get_center()
        objects.append(d) #Add the dict of this object to the list

    # ------------------------------------------
    # Visualization
    # ------------------------------------------

    #Create a list of entities to draw
    entities = []

    #Create a frame with the orthogonal directions
    frame = o3d.geometry.TriangleMesh().create_coordinate_frame(size=0.5, origin=np.array([0., 0., 0.]))
    entities.append(frame)

    # Draw bbox
    bbox_to_draw = o3d.geometry.LineSet.create_from_axis_aligned_bounding_box(p.bbox)
    entities.append(bbox_to_draw)

    #Draw objects
    for object in objects:
        entities.append(object['points'])

    # #Show only object idx = 2
    # for object_idx, object in enumerate(objects):
    #     if object_idx == 2:
    #         entities.append(object['points'])

    #Draws entities and show PointCloud in the defined view
    o3d.visualization.draw_geometries(entities,
                                    zoom=view['trajectory'][0]['zoom'],
                                    front=view['trajectory'][0]['front'],
                                    lookat=view['trajectory'][0]['lookat'],
                                    up=view['trajectory'][0]['up'])

    # ------------------------------------------
    # Termination
    # ------------------------------------------
    if cv2.waitKey(0) == ord('q'):
        exit()

if __name__ == "__main__":
    main()