import copy
import json
import logging
import os
import pickle
import warnings

import numpy as np
from typing import Any, List, Optional, Text, Dict, Tuple

import rasa.utils.io
from rasa.core.domain import Domain
from rasa.core.featurizers import (
    TrackerFeaturizer,
    FullDialogueTrackerFeaturizer,
    LabelTokenizerSingleStateFeaturizer,
    MaxHistoryTrackerFeaturizer,
)
from rasa.core.policies.policy import Policy
from rasa.core.constants import DEFAULT_POLICY_PRIORITY
from rasa.core.trackers import DialogueStateTracker
from rasa.utils import train_utils

import tensorflow as tf

# avoid warning println on contrib import - remove for tf 2
tf.contrib._warning = None
logger = logging.getLogger(__name__)

class EmbeddingPolicy(Policy):
    """Transformer Embedding Dialogue Policy (TEDP)

    Transformer version of the REDP used in our paper https://arxiv.org/abs/1811.11707
    """

    SUPPORTS_ONLINE_TRAINING = True

    # default properties (DOC MARKER - don't remove)
    defaults = {
        # nn architecture
        # a list of hidden layers sizes before user embed layer
        # number of hidden layers is equal to the length of this list
        "hidden_layers_sizes_pre_dial": [],
        # a list of hidden layers sizes before bot embed layer
        # number of hidden layers is equal to the length of this list
        "hidden_layers_sizes_bot": [],
        # number of units in transformer
        "transformer_size": 128,
        # number of transformer layers
        "num_transformer_layers": 1,
        # type of positional encoding in transformer
        "pos_encoding": "timing",  # string 'timing' or 'emb'
        # max sequence length if pos_encoding='emb'
        "max_seq_length": 256,
        # number of attention heads in transformer
        "num_heads": 4,
        # training parameters
        # initial and final batch sizes:
        # batch size will be linearly increased for each epoch
        "batch_size": [8, 32],
        # how to create batches
        "batch_strategy": "balanced",  # string 'sequence' or 'balanced'
        # number of epochs
        "epochs": 1,
        # set random seed to any int to get reproducible results
        "random_seed": None,
        # embedding parameters
        # dimension size of embedding vectors
        "embed_dim": 20,
        # the type of the similarity
        "num_neg": 20,
        # flag if minimize only maximum similarity over incorrect labels
        "similarity_type": "auto",  # string 'auto' or 'cosine' or 'inner'
        # the type of the loss function
        "loss_type": "softmax",  # string 'softmax' or 'margin'
        # how similar the algorithm should try
        # to make embedding vectors for correct labels
        "mu_pos": 0.8,  # should be 0.0 < ... < 1.0 for 'cosine'
        # maximum negative similarity for incorrect labels
        "mu_neg": -0.2,  # should be -1.0 < ... < 1.0 for 'cosine'
        # the number of incorrect labels, the algorithm will minimize
        # their similarity to the user input during training
        "use_max_sim_neg": True,  # flag which loss function to use
        # scale loss inverse proportionally to confidence of correct prediction
        "scale_loss": True,
        # regularization
        # the scale of L2 regularization
        "C2": 0.001,
        # the scale of how important is to minimize the maximum similarity
        # between embeddings of different labels
        "C_emb": 0.8,
        # dropout rate for dial nn
        "droprate_a": 0.1,
        # dropout rate for bot nn
        "droprate_b": 0.0,
        # visualization of accuracy
        # how often calculate validation accuracy
        "evaluate_every_num_epochs": 20,  # small values may hurt performance
        # how many examples to use for hold out validation set
        "evaluate_on_num_examples": 0,  # large values may hurt performance
    }
    # end default properties (DOC MARKER - don't remove)

    @staticmethod
    def _standard_featurizer(max_history: Optional[int] = None) -> "TrackerFeaturizer":
        if max_history is None:
            return FullDialogueTrackerFeaturizer(LabelTokenizerSingleStateFeaturizer())
        else:
            return MaxHistoryTrackerFeaturizer(
                LabelTokenizerSingleStateFeaturizer(), max_history=max_history
            )

    def __init__(
        self,
        featurizer: Optional["TrackerFeaturizer"] = None,
        priority: int = DEFAULT_POLICY_PRIORITY,
        graph: Optional["tf.Graph"] = None,
        session: Optional["tf.Session"] = None,
        user_placeholder: Optional["tf.Tensor"] = None,
        bot_placeholder: Optional["tf.Tensor"] = None,
        similarity_all: Optional["tf.Tensor"] = None,
        pred_confidence: Optional["tf.Tensor"] = None,
        similarity: Optional["tf.Tensor"] = None,
        dial_embed: Optional["tf.Tensor"] = None,
        bot_embed: Optional["tf.Tensor"] = None,
        all_bot_embed: Optional["tf.Tensor"] = None,
        attention_weights: Optional["tf.Tensor"] = None,
        max_history: Optional[int] = None,
        **kwargs: Any,
    ) -> None:
        """Declare instant variables with default values"""

        if not featurizer:
            featurizer = self._standard_featurizer(max_history)
        super().__init__(featurizer, priority)

        self._load_params(**kwargs)

        # encode all label_ids with numbers
        self._encoded_all_label_ids = None

        # tf related instances
        self.graph = graph
        self.session = session
        self.a_in = user_placeholder
        self.b_in = bot_placeholder
        self.sim_all = similarity_all
        self.pred_confidence = pred_confidence
        self.sim = similarity

        # persisted embeddings
        self.dial_embed = dial_embed
        self.bot_embed = bot_embed
        self.all_bot_embed = all_bot_embed

        self.attention_weights = attention_weights
        # internal tf instances
        self._iterator = None
        self._train_op = None
        self._is_training = None

    # init helpers
    def _load_nn_architecture_params(self, config: Dict[Text, Any]) -> None:
        self.hidden_layers_sizes = {
            "pre_dial": config["hidden_layers_sizes_pre_dial"],
            "bot": config["hidden_layers_sizes_bot"],
        }

        self.pos_encoding = config["pos_encoding"]
        self.max_seq_length = config["max_seq_length"]
        self.num_heads = config["num_heads"]

        self.transformer_size = config["transformer_size"]
        self.num_transformer_layers = config["num_transformer_layers"]

        self.batch_size = config["batch_size"]
        self.batch_strategy = config["batch_strategy"]

        self.epochs = config["epochs"]

        self.random_seed = config["random_seed"]

    def _load_embedding_params(self, config: Dict[Text, Any]) -> None:
        self.embed_dim = config["embed_dim"]
        self.num_neg = config["num_neg"]

        self.similarity_type = config["similarity_type"]
        self.loss_type = config["loss_type"]
        if self.similarity_type == "auto":
            if self.loss_type == "softmax":
                self.similarity_type = "inner"
            elif self.loss_type == "margin":
                self.similarity_type = "cosine"

        self.mu_pos = config["mu_pos"]
        self.mu_neg = config["mu_neg"]
        self.use_max_sim_neg = config["use_max_sim_neg"]

        self.scale_loss = config["scale_loss"]

    def _load_regularization_params(self, config: Dict[Text, Any]) -> None:
        self.C2 = config["C2"]
        self.C_emb = config["C_emb"]
        self.droprate = {"bot": config["droprate_b"], "dial": config["droprate_a"]}

    def _load_visual_params(self, config: Dict[Text, Any]) -> None:
        self.evaluate_every_num_epochs = config["evaluate_every_num_epochs"]
        if self.evaluate_every_num_epochs < 1:
            self.evaluate_every_num_epochs = self.epochs
        self.evaluate_on_num_examples = config["evaluate_on_num_examples"]

    def _load_params(self, **kwargs: Dict[Text, Any]) -> None:
        config = copy.deepcopy(self.defaults)
        config.update(kwargs)

        self._tf_config = train_utils.load_tf_config(config)
        self._load_nn_architecture_params(config)
        self._load_embedding_params(config)
        self._load_regularization_params(config)
        self._load_visual_params(config)

    # data helpers
    # noinspection PyPep8Naming
    @staticmethod
    def _label_ids_for_Y(data_Y: "np.ndarray") -> "np.ndarray":
        """Prepare Y data for training: extract label_ids."""

        return data_Y.argmax(axis=-1)

    # noinspection PyPep8Naming
    def _label_features_for_Y(self, label_ids: "np.ndarray") -> "np.ndarray":
        """Prepare Y data for training: features for label_ids."""

        if len(label_ids.shape) == 2:  # full dialogue featurizer is used
            return np.stack(
                [
                    np.stack(
                        [
                            self._encoded_all_label_ids[label_idx]
                            for label_idx in seq_label_ids
                        ]
                    )
                    for seq_label_ids in label_ids
                ]
            )
        else:  # max history featurizer is used
            return np.stack(
                [self._encoded_all_label_ids[label_idx] for label_idx in label_ids]
            )

    # noinspection PyPep8Naming
    def _create_session_data(
        self, data_X: "np.ndarray", data_Y: Optional["np.ndarray"] = None
    ) -> "train_utils.SessionDataType":
        """Combine all tf session related data into dict."""
        if data_Y is not None:
            # training time
            label_ids = self._label_ids_for_Y(data_Y)
            Y = self._label_features_for_Y(label_ids)
            # explicitly add last dimension to label_ids
            # to track correctly dynamic sequences
            label_ids = np.expand_dims(label_ids, -1)
        else:
            # prediction time
            label_ids = None
            Y = None

        return {
            "dialogue_features": [data_X],
            "bot_features": [Y],
            "action_ids": [label_ids],
        }

    def _create_tf_bot_embed(self, b_in: "tf.Tensor") -> "tf.Tensor":
        """Create embedding bot vector."""

        b = train_utils.create_tf_fnn(
            b_in,
            self.hidden_layers_sizes["bot"],
            self.droprate["bot"],
            self.C2,
            self._is_training,
            layer_name_suffix="bot",
        )
        return train_utils.create_tf_embed(
            b, self.embed_dim, self.C2, self.similarity_type, layer_name_suffix="bot"
        )

    def _create_tf_dial(self, a_in) -> Tuple["tf.Tensor", "tf.Tensor"]:
        """Create dialogue level embedding and mask."""

        # mask different length sequences
        # if there is at least one `-1` it should be masked
        mask = tf.sign(tf.reduce_max(self.a_in, -1) + 1)

        a = train_utils.create_tf_fnn(
            a_in,
            self.hidden_layers_sizes["pre_dial"],
            self.droprate["dial"],
            self.C2,
            self._is_training,
            layer_name_suffix="pre_dial",
        )

        self.attention_weights = {}
        hparams = train_utils.create_t2t_hparams(
            self.num_transformer_layers,
            self.transformer_size,
            self.num_heads,
            self.droprate["dial"],
            self.pos_encoding,
            self.max_seq_length,
            self._is_training,
        )

        a = train_utils.create_t2t_transformer_encoder(
            a, mask, self.attention_weights, hparams, self.C2, self._is_training
        )

        if isinstance(self.featurizer, MaxHistoryTrackerFeaturizer):
            # pick last label if max history featurizer is used
            a = a[:, -1:, :]
            mask = mask[:, -1:]

        dial_embed = train_utils.create_tf_embed(
            a, self.embed_dim, self.C2, self.similarity_type, layer_name_suffix="dial"
        )

        return dial_embed, mask

    def _build_tf_train_graph(self) -> Tuple["tf.Tensor", "tf.Tensor"]:
        """Bulid train graph using iterator."""
        # iterator returns a_in, b_in, action_ids
        self.a_in, self.b_in, _ = self._iterator.get_next()

        if isinstance(self.featurizer, MaxHistoryTrackerFeaturizer):
            # add time dimension if max history featurizer is used
            self.b_in = self.b_in[:, tf.newaxis, :]

        all_bot_raw = tf.constant(
            self._encoded_all_label_ids, dtype=tf.float32, name="all_bot_raw"
        )

        self.dial_embed, mask = self._create_tf_dial(self.a_in)

        self.bot_embed = self._create_tf_bot_embed(self.b_in)
        self.all_bot_embed = self._create_tf_bot_embed(all_bot_raw)

        return train_utils.calculate_loss_acc(
            self.dial_embed,
            self.bot_embed,
            self.b_in,
            self.all_bot_embed,
            all_bot_raw,
            self.num_neg,
            mask,
            self.loss_type,
            self.mu_pos,
            self.mu_neg,
            self.use_max_sim_neg,
            self.C_emb,
            self.scale_loss,
        )

    # prepare for prediction
    def _create_tf_placeholders(
        self, session_data: "train_utils.SessionDataType"
    ) -> None:
        """Create placeholders for prediction."""

        dialogue_len = None  # use dynamic time
        self.a_in = tf.placeholder(
            dtype=tf.float32,
            shape=(None, dialogue_len, session_data["dialogue_features"][0].shape[-1]),
            name="a",
        )
        self.b_in = tf.placeholder(
            dtype=tf.float32,
            shape=(None, dialogue_len, None, session_data["bot_features"][0].shape[-1]),
            name="b",
        )

    def _build_tf_pred_graph(
        self, session_data: "train_utils.SessionDataType"
    ) -> "tf.Tensor":
        """Rebuild tf graph for prediction."""

        self._create_tf_placeholders(session_data)

        self.dial_embed, mask = self._create_tf_dial(self.a_in)

        self.sim_all = train_utils.tf_raw_sim(
            self.dial_embed[:, :, tf.newaxis, :],
            self.all_bot_embed[tf.newaxis, tf.newaxis, :, :],
            mask,
        )

        self.bot_embed = self._create_tf_bot_embed(self.b_in)

        self.sim = train_utils.tf_raw_sim(
            self.dial_embed[:, :, tf.newaxis, :], self.bot_embed, mask
        )

        return train_utils.confidence_from_sim(self.sim_all, self.similarity_type)

    # training methods
    def train(
        self,
        training_trackers: List["DialogueStateTracker"],
        domain: "Domain",
        **kwargs: Any,
    ) -> None:
        """Train the policy on given training trackers."""

        logger.debug("Started training embedding policy.")

        # set numpy random seed
        np.random.seed(self.random_seed)

        # dealing with training data
        training_data = self.featurize_for_training(training_trackers, domain, **kwargs)

        # encode all label_ids with policies' featurizer
        state_featurizer = self.featurizer.state_featurizer
        self._encoded_all_label_ids = state_featurizer.create_encoded_all_actions(
            domain
        )

        # check if number of negatives is less than number of label_ids
        logger.debug(
            "Check if num_neg {} is smaller "
            "than number of label_ids {}, "
            "else set num_neg to the number of label_ids - 1"
            "".format(self.num_neg, domain.num_actions)
        )
        # noinspection PyAttributeOutsideInit
        self.num_neg = min(self.num_neg, domain.num_actions - 1)

        # extract actual training data to feed to tf session
        session_data = self._create_session_data(training_data.X, training_data.y)

        if self.evaluate_on_num_examples:
            session_data, eval_session_data = train_utils.train_val_split(
                session_data,
                self.evaluate_on_num_examples,
                self.random_seed,
                label_key="action_ids",
            )
        else:
            eval_session_data = None

        self.graph = tf.Graph()
        with self.graph.as_default():
            # set random seed in tf
            tf.set_random_seed(self.random_seed)

            # allows increasing batch size
            batch_size_in = tf.placeholder(tf.int64)

            (
                self._iterator,
                train_init_op,
                eval_init_op,
            ) = train_utils.create_iterator_init_datasets(
                session_data,
                eval_session_data,
                batch_size_in,
                self.batch_strategy,
                label_key="action_ids",
            )

            self._is_training = tf.placeholder_with_default(False, shape=())

            loss, acc = self._build_tf_train_graph()

            # define which optimizer to use
            self._train_op = tf.train.AdamOptimizer().minimize(loss)

            # train tensorflow graph
            self.session = tf.Session(config=self._tf_config)
            train_utils.train_tf_dataset(
                train_init_op,
                eval_init_op,
                batch_size_in,
                loss,
                acc,
                self._train_op,
                self.session,
                self._is_training,
                self.epochs,
                self.batch_size,
                self.evaluate_on_num_examples,
                self.evaluate_every_num_epochs,
            )

            # rebuild the graph for prediction
            self.pred_confidence = self._build_tf_pred_graph(session_data)

            self.attention_weights = train_utils.extract_attention(
                self.attention_weights
            )

    def continue_training(
        self,
        training_trackers: List["DialogueStateTracker"],
        domain: "Domain",
        **kwargs: Any,
    ) -> None:
        """Continue training an already trained policy."""

        batch_size = kwargs.get("batch_size", 5)
        epochs = kwargs.get("epochs", 50)

        with self.graph.as_default():
            for _ in range(epochs):
                training_data = self._training_data_for_continue_training(
                    batch_size, training_trackers, domain
                )

                session_data = self._create_session_data(
                    training_data.X, training_data.y
                )
                train_dataset = train_utils.create_tf_dataset(
                    session_data, batch_size, label_key="action_ids"
                )
                train_init_op = self._iterator.make_initializer(train_dataset)
                self.session.run(train_init_op)

                # fit to one extra example using updated trackers
                while True:
                    try:
                        self.session.run(
                            self._train_op, feed_dict={self._is_training: True}
                        )

                    except tf.errors.OutOfRangeError:
                        break

    def tf_feed_dict_for_prediction(
        self, tracker: "DialogueStateTracker", domain: "Domain"
    ) -> Dict["tf.Tensor", "np.ndarray"]:
        """Create feed dictionary for tf session."""

        # noinspection PyPep8Naming
        data_X = self.featurizer.create_X([tracker], domain)
        session_data = self._create_session_data(data_X)

        return {self.a_in: session_data["dialogue_features"][0]}

    def predict_action_probabilities(
        self, tracker: "DialogueStateTracker", domain: "Domain"
    ) -> List[float]:
        """Predict the next action the bot should take.

        Return the list of probabilities for the next actions.
        """

        if self.session is None:
            logger.error(
                "There is no trained tf.session: "
                "component is either not trained or "
                "didn't receive enough training data"
            )
            return [0.0] * domain.num_actions

        tf_feed_dict = self.tf_feed_dict_for_prediction(tracker, domain)

        confidence = self.session.run(self.pred_confidence, feed_dict=tf_feed_dict)

        return confidence[0, -1, :].tolist()

    def persist(self, path: Text) -> None:
        """Persists the policy to a storage."""

        if self.session is None:
            warnings.warn(
                "Method `persist(...)` was called "
                "without a trained model present. "
                "Nothing to persist then!"
            )
            return

        self.featurizer.persist(path)

        meta = {"priority": self.priority}

        meta_file = os.path.join(path, "embedding_policy.json")
        rasa.utils.io.dump_obj_as_json_to_file(meta_file, meta)

        file_name = "tensorflow_embedding.ckpt"
        checkpoint = os.path.join(path, file_name)
        rasa.utils.io.create_directory_for_file(checkpoint)

        with self.graph.as_default():
            train_utils.persist_tensor("user_placeholder", self.a_in, self.graph)
            train_utils.persist_tensor("bot_placeholder", self.b_in, self.graph)

            train_utils.persist_tensor("similarity_all", self.sim_all, self.graph)
            train_utils.persist_tensor(
                "pred_confidence", self.pred_confidence, self.graph
            )
            train_utils.persist_tensor("similarity", self.sim, self.graph)

            train_utils.persist_tensor("dial_embed", self.dial_embed, self.graph)
            train_utils.persist_tensor("bot_embed", self.bot_embed, self.graph)
            train_utils.persist_tensor("all_bot_embed", self.all_bot_embed, self.graph)

            train_utils.persist_tensor(
                "attention_weights", self.attention_weights, self.graph
            )

            saver = tf.train.Saver()
            saver.save(self.session, checkpoint)

        with open(os.path.join(path, file_name + ".tf_config.pkl"), "wb") as f:
            pickle.dump(self._tf_config, f)

    @classmethod
    def load(cls, path: Text) -> "EmbeddingPolicy":
        """Loads a policy from the storage.

        **Needs to load its featurizer**
        """

        if not os.path.exists(path):
            raise Exception(
                "Failed to load dialogue model. Path '{}' "
                "doesn't exist".format(os.path.abspath(path))
            )

        featurizer = TrackerFeaturizer.load(path)

        file_name = "tensorflow_embedding.ckpt"
        checkpoint = os.path.join(path, file_name)

        if not os.path.exists(checkpoint + ".meta"):
            return cls(featurizer=featurizer)

        meta_file = os.path.join(path, "embedding_policy.json")
        meta = json.loads(rasa.utils.io.read_file(meta_file))

        with open(os.path.join(path, file_name + ".tf_config.pkl"), "rb") as f:
            _tf_config = pickle.load(f)

        graph = tf.Graph()
        with graph.as_default():
            session = tf.Session(config=_tf_config)
            saver = tf.train.import_meta_graph(checkpoint + ".meta")

            saver.restore(session, checkpoint)

            a_in = train_utils.load_tensor("user_placeholder")
            b_in = train_utils.load_tensor("bot_placeholder")

            sim_all = train_utils.load_tensor("similarity_all")
            pred_confidence = train_utils.load_tensor("pred_confidence")
            sim = train_utils.load_tensor("similarity")

            dial_embed = train_utils.load_tensor("dial_embed")
            bot_embed = train_utils.load_tensor("bot_embed")
            all_bot_embed = train_utils.load_tensor("all_bot_embed")

            attention_weights = train_utils.load_tensor("attention_weights")

        return cls(
            featurizer=featurizer,
            priority=meta["priority"],
            graph=graph,
            session=session,
            user_placeholder=a_in,
            bot_placeholder=b_in,
            similarity_all=sim_all,
            pred_confidence=pred_confidence,
            similarity=sim,
            dial_embed=dial_embed,
            bot_embed=bot_embed,
            all_bot_embed=all_bot_embed,
            attention_weights=attention_weights,
        )


import re

def latent_representation_to_fasta(latent_representation, length):
    sequences = [latent_representation[i:i+length] for i in range(0, len(latent_representation), length)]
    fast_str = ""
    fast_str += "> oligo\n"
    fast_str += "\n> oligo\n".join(sequences)
    return fast_str

def get_value_from_fasta(key, fasta_str):
    values = re.findall(f">\s*{key}\s*\n([ACGT]+)\n", fasta_str)
    return values[0] if len(values) == 1 else values

def to_fastq(x):
    fasta = latent_representation_to_fasta(x, 200)
    with open(f"/Users/leonardopanattoni/Downloads/JPEG-DNA-BC-Transcoder-main/simulation/bikersFULL.fasta", "w+") as fd:
        fd.write(fasta)

def main():
    with open("/Users/leonardopanattoni/Downloads/JPEG-DNA-BC-Transcoder-main/transcoder_results/bikersDNA", "r") as fd:
        x = fd.read()
    to_fastq(x)

if __name__ == "__main__":
    main()


import math

class Entity():
    def __init__(self, x, y, char, color, name,
                 blocks=False, block_sight=None, explored=False,
                 fighter=None, ai=None):
        self.x = x
        self.y = y
        self.char = char
        self.color = color
        self.name = name
        self.blocks = blocks

        if block_sight is None:
            block_sight = blocks

        self.block_sight = block_sight
        self.explored = explored
        self.fighter = fighter
        self.ai = ai

        if self.fighter:
            self.fighter.owner = self

        if self.ai:
            self.ai.owner = self

    def move(self, dx, dy):
        self.x += dx
        self.y += dy

    def move_towards(self, target_x, target_y, game_map, entites):
        dx = target_x - self.x
        dy = target_y - self.y
        distance = math.sqrt(dx ** 2 + dy ** 2)

        dx = int(round(dx / distance))
        dy = int(round(dy / distance))
        x = self.x + dx
        y = self.y + dy
        if (not (x, y) in entites) and (not (x, y) in game_map.terrain):
            self.move(dx, dy)

    def distance_to(self, other):
        dx = other.x - self.x
        dy = other.y - self.y
        return math.sqrt(dx ** 2 + dy ** 2)


board = [' ' for x in range(10)]
def insertLetter(letter,pos):
	board[pos] = letter

def spaceIsFree(pos):
	return board[pos] == ' '

def printBoard(board):
	print('   |   |  ')
	print('  '+board[1]+'| '+board[2]+' | '+board[3])
	print('   |   |  ')
	print('-----------')
	print('   |   |  ')
	print('  '+board[4]+'| '+board[5]+' | '+board[6])
	print('   |   |  ')
	print('-----------')
	print('   |   |  ')
	print('  '+board[7]+'| '+board[8]+' | '+board[9])
	print('   |   |  ')

def isWinner(bo,le):
	return (bo[7]==le and bo[8]==le and bo[9]==le) or (bo[4]==le and bo[5]==le and bo[6]==le) or (bo[1]==le and bo[2]==le and bo[3]==le) or (bo[1]==le and bo[4]==le and bo[7]==le) or (bo[2]==le and bo[5]==le and bo[8]==le) or (bo[3]==le and bo[6]==le and bo[9]==le) or (bo[1]==le and bo[5]==le and bo[9]==le) or (bo[3]==le and bo[5]==le and bo[7]==le)

def playerMove():
	run = True
	while run:
		move = input('Select Your Position')
		try:
			new_move = int(move)
			print(new_move)
			if (new_move>0 and new_move<10):
				if spaceIsFree(new_move):
					run = False
					insertLetter('X',new_move)
				else:
					print('This space is already occupied by Computer')
			else:
				print('Please Enter a number between (1-9)')
		except:
			print('Please Enter a number')

def compMove():
	possibleMoves = [x for x, letter in enumerate(board) if letter == ' ' and x != 0]
	move = 0
	for let in ['O','X']:
		for i in possibleMoves:
			boardCopy = board[:]
			boardCopy[i] == let
			if isWinner(boardCopy,let):
				move = i
				return move

	cornersOpen = []
	for i in possibleMoves:
		if i in [1,3,7,9]:
			cornersOpen.append(i)
	if len(cornersOpen) > 0:
		a = selectRandom(cornersOpen)
		move = cornersOpen[a]
		return move

	if 5 in possibleMoves:
		move = 5
		return move

	edgesOpen = []
	for i in possibleMoves:
		if i in [2,4,6,8]:
			edgesOpen.append(i)
	if len(edgesOpen) > 0:
		c = selectRandom(edgesOpen)
		move = edgesOpen[c]
	return move

def selectRandom(li):
	import random
	ln = len(li)
	r = random.randrange(0,ln)
	return r

def isBoardFull(board):
	if board.count(' ')>1:
		return False
	else:
		return True

def main():
	print('Welcome To Tic Tac Toe!!!')
	printBoard(board)
	while not(isBoardFull(board)):
		if not(isWinner(board, 'O')):
			playerMove()
			printBoard(board)
		else:
			print('Computer Wins')
			break

		if not(isWinner(board, 'X')):
			move = compMove()
			if move == 0:
				print('We have a TIE Game')
			else:
				insertLetter('O',move)
				print('Computer played its move')
				printBoard(board)
		else:
			print('You Win')
			break
	if isBoardFull(board):
		print('We have a TIE Game')

main()


import scrapy
from scrapy.http import Request, Response

from xdvideo.items import XdvideoItem

class CrawlSpider(scrapy.Spider):
    name = 'xdvideo'
    allowed_domains = ['sme.xidian.edu.cn']

    VIDEOS_PER_PAGE = 15
    # start_urls = [f'https://sme.xidian.edu.cn/html/bkjj/zxkt/bdtwl1/list_92_{i}.html' for i in range(1, 4)]
    def __init__(self, url="https://sme.xidian.edu.cn/html/bkjj/zxkt/bdtwl1/list_92_{}.html", pages=3, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.url = url
        self.pages = int(pages)

    def start_requests(self):
        for i in range(1, self.pages + 1):
            yield Request(self.url.format(i), meta={"page": i})

    def parse(self, response: Response):
        XPATH_URL = "//body//div[@class='childinfo']//div//div[*]//a[1]/@href"
        urls = response.xpath(XPATH_URL).getall()

        for i in range(len(urls)):
            yield response.follow(urls[i], callback=self.parse_detail,
                meta = {"n": (response.meta["page"] - 1) * self.VIDEOS_PER_PAGE + i + 1})

    def parse_detail(self, response: Response):
        XPATH_TITLE = "//div[@class='text']//h4[1]/text()"
        XPATH_COURSE = "//div[@class='childtitle']//p/text()"
        XPATH_VIDEO = "//video/@src"
        title = response.xpath(XPATH_TITLE).get()
        course = response.xpath(XPATH_COURSE).get()
        video_url = response.urljoin(response.xpath(XPATH_VIDEO).get())
        return XdvideoItem(title=title, course=course, file_urls=[video_url], episode=response.meta["n"])


# import math

def check_prime(n):
    if n==1:
        return False
    if n==2 or n==3:
        return True
    if n%2==0 or n%3==0:
        return False
    # for i in range(5, math.floor(math.sqrt(n))):
    #     if n%i==0:
    #         return False
    i = 5
    while i*i <= n:
        if n%i==0:
            return False
        i+=1
    return True

n = int(input())
print(check_prime(n))


from __future__ import print_function
import bisect

########################################################################
# official recepi from doc.python.org                                  #
# https://docs.python.org/2/library/bisect.html#searching-sorted-lists #
########################################################################

def find_index(array, x):
    "Locate the leftmost value exactly equal to x"
    i = bisect.bisect_left(array, x)
    if i != len(array) and array[i] == x:
        return i
    raise ValueError

def find_lt(array, x):
    "Find rightmost value less than x"
    i = bisect.bisect_left(array, x)
    if i:
        return array[i-1]
    raise ValueError

def find_le(array, x):
    "Find rightmost value less than or equal to x"
    i = bisect.bisect_right(array, x)
    if i:
        return array[i-1]
    raise ValueError

def find_gt(array, x):
    "Find leftmost value greater than x"
    i = bisect.bisect_right(array, x)
    if i != len(array):
        return array[i]
    raise ValueError

def find_ge(array, x):
    "Find leftmost item greater than or equal to x"
    i = bisect.bisect_left(array, x)
    if i != len(array):
        return array[i]
    raise ValueError

def find_last_true(sorted_list, true_criterion):
    """
    [EN doc]
    suppose we have a list of item [item1, item2, ..., itemn]
    if we do a map:
        list of items -- tru_criterion --> [True, True, ... True, False, False, ... False]
                                                           (last true)
    this function returns the index of last true item.

    we do can do the map for all item, and run a binary search to find the index. But sometime
    the mapping function is expensive. so this function gives a way to minimize the time cost.

    [CN doc]
    假设有一组排序号了的元素, 从前往后假设前面的元素都满足某一条件, 而到了中间某处起就不再满足了。
    本函数返回满足这一条件的最后一个元素。

    例题:
        序号   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        真值表 [1, 1, 1, 1, 1, 1, 1, 0, 0, 0]
        我们要找到那个小于等于6的元素

    算法:
        我们检验一个序号ind, 如果为False, 那么则向前跳跃继续检验
        如果为True, 那么则检验ind+1, 如果为False, 说明找到了。如果ind+1也为真, 则向后跳跃。重复这一过程。

    例:
        第一次检查 int((0+9)/2.0) = 4, 为True,
        检查4+1=5, 也是True。 那么跳跃至 int((4+9)/2.0)=6。很显然, 我们找到了
    """

    # exam first item, if not true, then impossible to find result
    if not true_criterion(sorted_list[0]):
        raise ValueError

    # exam last item, if true, it is the one.
    if true_criterion(sorted_list[-1]):
        return sorted_list[-1]

    lower, upper = 0, len(sorted_list) - 1

    index = int((lower+upper)/2.0)
    while 1:
        if true_criterion(sorted_list[index]):
            if true_criterion(sorted_list[index+1]):
                lower = index
                index = int((index+upper)/2.0)
            else:
                return sorted_list[index]
        else:
            upper = index
            index = int((lower+index)/2.0)

def find_nearest(array, x):
    """find the nearest item of x from sorted array
    """
    if x <= array[0]:
        return array[0]
    elif x >= array[-1]:
        return array[-1]
    else:
        lower = find_le(array, x)
        upper = find_ge(array, x)
        if (x - lower) > (upper - x):
            return upper
        else:
            return lower

if __name__ == "__main__":
    from collections import OrderedDict
    import unittest
    import random
    import time

    class BiSearch():
        """A binary search class, doens't have better performance than original implementation
        """
        def fit(self, array):
            self.train_dict = OrderedDict()
            for ind, value in enumerate(array):
                self.train_dict[ind] = value
            self.train_array = array

        def find_le(self, x):
            "Find rightmost value less than or equal to x"
            i = bisect.bisect_right(self.train_array, x)
            if i != len(self.train_array):
                return self.train_dict[i-1]
            raise ValueError

        def find_ge(self, x):
            "Find leftmost item greater than or equal to x"
            i = bisect.bisect_left(self.train_array, x)
            if i != len(self.train_array):
                return self.train_dict[i]
            raise ValueError

    class FunctionsUnittest(unittest.TestCase):
        def setUp(self):
            self.sorted_array = list(range(1000))

        def test_index(self):
            self.assertEqual(find_index(self.sorted_array, 0), 0)
            self.assertEqual(find_index(self.sorted_array, 999), 999)
            self.assertEqual(find_index(self.sorted_array, 499), 499)
            self.assertRaises(ValueError, find_index, self.sorted_array, -1)
            self.assertRaises(ValueError, find_index, self.sorted_array, 1001)

        def test_find_nearest(self):
            self.assertEqual(find_nearest(self.sorted_array, 25), 25)
            self.assertEqual(find_nearest(self.sorted_array, 25.49), 25)
            self.assertEqual(find_nearest(self.sorted_array, 25.5), 25)
            self.assertEqual(find_nearest(self.sorted_array, 25.51), 26)

            self.assertEqual(find_nearest(self.sorted_array, -1), 0)
            self.assertEqual(find_nearest(self.sorted_array, 1000), 999)

    class PerformanceTest(unittest.TestCase):
        def setUp(self):
            self.sorted_array = list(range(1000*1000))
            self.bisearch = BiSearch()
            self.bisearch.fit(self.sorted_array)

        def test_speed(self):
            """because original recepi use list[index] to take item. I thought the speed can be
            improved if I use dict[index]. But failed.
            """
            st = time.clock()
            for _ in range(1000):
                find_le(self.sorted_array, 500*1000)
            original = time.clock() - st

            st = time.clock()
            for _ in range(1000):
                self.bisearch.find_le(500*1000)
            improved = time.clock() - st
            self.assertFalse(improved < original) # improved elapse not smaller than original

    class LastTrueTest(unittest.TestCase):
        def setUp(self):
            self.sorted_list = list({random.randint(1, 100000) for _ in range(1000)})
            self.sorted_list.sort()

        def true_criterion(self, item):
            return item <= 500

        def test(self):
            value = find_last_true(self.sorted_list, self.true_criterion)
            print("last True value is %s" % value)

    unittest.main()


from source.utils.dataload import loadData
from source.programming_languages.pl import PL

def mainfunc():
    # set coefs here
    modelSize = 250
    learnSize = 158
    pl = PL("./datasets/programming languages.csv", [modelSize, learnSize])
    curlang = 'Rust'
    pl.analyzeLanguage(curlang)

if __name__ == '__main__':
    mainfunc()


import cv2, os, random, colorsys, onnxruntime, string, time, argparse, uuid, logging
import numpy as np
from utils import Processing
from glob import glob
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt

parser = argparse.ArgumentParser("license")
parser.add_argument('-i',"--input", type = str, required = True, default = False, help = "path image ...")
logging.basicConfig(filename=f'log/ocr.log', filemode='w', format='%(asctime)s - %(message)s', level = logging.INFO, datefmt='%d-%b-%y %H:%M:%S')

class Detection(Processing):
    def __init__(self, path_model:str, path_classes:str, image_shape:list, padding:int):
        self.path_model   = path_model
        self.path_classes = path_classes
        self.session = onnxruntime.InferenceSession(self.path_model)
        self.class_labels, self.num_names = self.get_classes(self.path_classes)
        self.image_shape = image_shape
        self.font = ImageFont.truetype('weights/font.otf', 8)
        self.class_colors = self.colors(self.class_labels)

    def boxes_detection(self, image, size):
        ort_inputs = {self.session.get_inputs()[0].name:image, self.session.get_inputs()[1].name:size}
        box_out, scores_out, classes_out = self.session.run(None, ort_inputs)
        return box_out, scores_out, classes_out

    def draw_detection(self, image, boxes_out, scores_out, classes_out):
        image_pred = image.copy()
        for i, c in reversed(list(enumerate(classes_out))):
            draw = ImageDraw.Draw(image_pred)
            predicted_class = self.class_labels[c]
            box = boxes_out[i]
            score = scores_out[i]
            top, left, bottom, right = box
            top = max(0, np.floor(top + 0.5).astype('int32'))
            left = max(0, np.floor(left + 0.5).astype('int32'))
            bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))
            right = min(image.size[0], np.floor(right + 0.5).astype('int32'))
            label = '{}: {:.2f}%'.format(predicted_class, score*100)
            print(label)
            logging.info(f'{label}')
            label_size = draw.textsize(label, self.font)
            if top - label_size[1] >= 0:
            	text_origin = np.array([left, top - label_size[1]])
            else:
            	text_origin = np.array([left, top + 1])
            draw.rectangle([left, top, right, bottom], outline= tuple(self.class_colors[c]), width=1)
            draw.text(text_origin, label, fill = (255,255,0), font = self.font)
            del draw
        return np.array(image_pred)

    def __call__(self, input_image:str):
        image = Image.open(input_image)
        input_image_shape = np.expand_dims(np.array([image.size[1], image.size[0]], dtype='float32'), 0)
        image = self.cvtColor(image)
        image_data  = self.resize_image(image, (self.image_shape[1], self.image_shape[0]))
        image_data  = np.expand_dims(self.preprocess_input(np.array(image_data, dtype='float32')), 0)
        box_out, scores_out, classes_out = self.boxes_detection(image_data,input_image_shape)
        image_pred = self.draw_detection(image, box_out, scores_out, classes_out)
        return image_pred

if __name__ == '__main__':
	args = parser.parse_args()
	opt = {"path_model":"weights/yolo4.onnx","path_classes":"classes.txt","image_shape":[416,416],"padding":0}
	detector = Detection(**opt)
	image_pred = detector(args.input)
	image = cv2.cvtColor(image_pred, cv2.COLOR_BGR2RGB)
	cv2.imwrite("out.jpg", image)


from collections import defaultdict
from pathlib import Path
from typing import DefaultDict, List

from jubeatools import song
from jubeatools.formats.dump_tools import make_dumper_from_chart_file_dumper
from jubeatools.formats.filetypes import ChartFile
from jubeatools.utils import group_by

from .. import commons as konami
from ..commons import AnyNote
from ..dump_tools import make_events_from_chart
from . import construct

def _dump_jbsq(song: song.Song, **kwargs: dict) -> List[ChartFile]:
    res = []
    for dif, chart, timing, hakus in song.iter_charts():
        events = make_events_from_chart(chart.notes, timing, hakus)
        jbsq_chart = make_jbsq_chart(events, chart.notes)
        chart_bytes = construct.jbsq.build(jbsq_chart)
        res.append(ChartFile(chart_bytes, song, dif, chart))

    return res

dump_jbsq = make_dumper_from_chart_file_dumper(
    internal_dumper=_dump_jbsq, file_name_template=Path("seq_{difficulty:l}.jbsq")
)

def make_jbsq_chart(events: List[konami.Event], notes: List[AnyNote]) -> construct.JBSQ:
    jbsq_events = [convert_event_to_jbsq(e) for e in events]
    num_events = len(events)
    combo = compute_max_combo(notes)
    end_time = next(e for e in events if e.command == konami.Command.END).time
    first_note_time_in_beats = min((n.time for n in notes), default=0)
    starting_notes = [n for n in notes if n.time == first_note_time_in_beats]
    starting_buttons = sum(1 << n.position.index for n in starting_notes)
    first_note_time = min(
        (
            e.time
            for e in events
            if e.command in (konami.Command.PLAY, konami.Command.LONG)
        ),
        default=0,
    )
    densities = compute_density_graph(events, end_time)
    jbsq_chart = construct.JBSQ(
        num_events=num_events,
        combo=combo,
        end_time=end_time,
        starting_buttons=starting_buttons,
        start_time=first_note_time,
        density_graph=densities,
        events=jbsq_events,
    )
    jbsq_chart.magic = b"JBSQ"
    return jbsq_chart

def convert_event_to_jbsq(event: konami.Event) -> construct.Event:
    return construct.Event(
        type_=construct.EventType[event.command.name],
        time_in_ticks=event.time,
        value=event.value,
    )

def compute_max_combo(notes: List[AnyNote]) -> int:
    notes_by_type = group_by(notes, type)
    tap_notes = len(notes_by_type[song.TapNote])
    long_notes = len(notes_by_type[song.LongNote])
    return tap_notes + 2 * long_notes

def compute_density_graph(events: List[konami.Event], end_time: int) -> List[int]:
    events_by_type = group_by(events, lambda e: e.command)
    buckets: DefaultDict[int, int] = defaultdict(int)
    for tap in events_by_type[konami.Command.PLAY]:
        bucket = int((tap.time / end_time) * 120)
        buckets[bucket] += 1

    for long in events_by_type[konami.Command.LONG]:
        press_bucket = int((long.time / end_time) * 120)
        buckets[press_bucket] += 1
        duration = konami.EveLong.from_value(long.value).duration
        release_time = long.time + duration
        release_bucket = int((release_time / end_time) * 120)
        buckets[release_bucket] += 1

    res = []
    for i in range(0, 120, 2):
        # The jbsq density graph in a array of nibbles, the twist is that for
        # some obscure reason each pair of nibbles is swapped in the byte ...
        # little-endianness is a hell of a drug, don't do drugs kids ...
        first_nibble = min(buckets[i], 15)
        second_nibble = min(buckets[i + 1], 15)
        density_byte = (second_nibble << 4) + first_nibble
        res.append(density_byte)

    return res


import sys
import copy
from collections import deque

# Running script: given code can be run with the command:
# python file.py, ./path/to/init_state.txt ./output/output.txt

# Variable ordering heuristics: Most constrained variable + Most constraining variable
# Value ordering heuristics: Least constraining value
# Inference mechanisms: Arc consistency

class Sudoku(object):
    def __init__(self, puzzle):
        self.puzzle = puzzle # self.puzzle is a list of lists
        self.var_domain, self.var_constraints, self.var_unassigned = self.csp(puzzle)

    def csp(self, puzzle):
        var_domain = {}
        var_constraints = {}
        var_unassigned = 0

        for r in xrange(9):
            for c in xrange(9):
                var_domain[(r, c)] = None
                var_constraints[(r, c)] = set()

                if puzzle[r][c] == 0:
                   var_unassigned += 1

        possible_domain = set([1, 2, 3, 4, 5, 6, 7, 8, 9])

        for var in var_domain:
            row, column = var[0], var[1]
            assigned_val = set()
            puzzle_val = puzzle[row][column]

            for c in xrange(9):
                val = puzzle[row][c]
                var_constraints[var].add((row, c))

                if val != 0 and puzzle_val == 0:
                    assigned_val.add(val)

            for r in xrange(9):
                val = puzzle[r][column]
                var_constraints[var].add((r, column))

                if val != 0 and puzzle_val == 0:
                    assigned_val.add(val)

            subgrid_r = (row / 3) * 3
            subgrid_c = (column / 3) * 3

            for r in xrange(subgrid_r, subgrid_r + 3):
                for c in xrange(subgrid_c, subgrid_c + 3):
                    val = puzzle[r][c]
                    var_constraints[var].add((r, c))

                    if val != 0 and puzzle_val == 0:
                        assigned_val.add(val)

            var_constraints[var].remove(var)

            if puzzle_val == 0:
                var_domain[var] = possible_domain - assigned_val
            else:
                var_domain[var] = puzzle_val

        return var_domain, var_constraints, var_unassigned

    def is_complete(self, var_unassigned):
        return var_unassigned == 0

    def is_consistent(self, var, val, var_domain, var_constraints):
        return all(var_domain[constraint] != val for constraint in var_constraints[var])

    def select_unassigned_var(self, var_domain, var_constraints):
        most_constrained_var = set()
        fewest_legal_val = 9

        for var in var_domain:
            domain = var_domain[var]

            if isinstance(domain, set):
                legal_val = len(domain)

                if legal_val < fewest_legal_val:
                    most_constrained_var = set()
                    fewest_legal_val = legal_val

                if legal_val == fewest_legal_val:
                    most_constrained_var.add(var)

        most_constraining_var = None
        most_constraints = 0

        for var in most_constrained_var:
            num_constraints = 0

            for constraint in var_constraints[var]:
                if isinstance(var_domain[constraint], set):
                    num_constraints += 1

            if num_constraints >= most_constraints:
                most_constraining_var = var
                most_constraints = num_constraints

        # last var in most_constrained_var with largest num_constraints
        # may not be only var with that num_constraints
        return most_constraining_var

    def order_domain_val(self, var, var_domain, var_constraints):
        val_order = []

        for val in var_domain[var]:
            num_affected = 0

            for constraint in var_constraints[var]:
                if isinstance(var_domain[constraint], set):
                    if val in var_domain[constraint]:
                        num_affected += 1

            val_order.append((val, num_affected))

        val_order.sort(key = lambda c: c[1])

        return [v[0] for v in val_order]

    def revise(self, var_domain, x_i, x_j):
        revised = False
        domain_i = var_domain[x_i]
        delete = set()

        for val_x in domain_i:
            domain_j = var_domain[x_j]

            if isinstance(domain_j, set):
                if not any(val_y != val_x for val_y in domain_j):
                    delete.add(val_x)
                    revised = True
            else:
                if not domain_j != val_x:
                    delete.add(val_x)
                    revised = True

        var_domain[x_i] = domain_i - delete

        return revised

    def inference(self, var, var_domain, var_constraints):
        # queue of arcs (x_i, x_j) for all x_i which are unassigned. x_j is var.
        queue = deque()

        for constraint in var_constraints[var]:
            if isinstance(var_domain[constraint], set):
                queue.append((constraint, var))

        while queue:
            x_i, x_j = queue.popleft()

            if self.revise(var_domain, x_i, x_j):
                if len(var_domain[x_i]) == 0:
                    return False

                for x_k in var_constraints[x_i] - set([x_j]):
                    if isinstance(var_domain[x_k], set):
                        queue.append((x_k, x_i))

        return True

    def backtrack(self, var_domain, var_constraints, var_unassigned):

        if self.is_complete(var_unassigned):
            return var_domain

        var = self.select_unassigned_var(var_domain, var_constraints)

        for val in self.order_domain_val(var, var_domain, var_constraints):
            var_domain_prev = var_domain.copy()
            var_unassigned_prev = var_unassigned

            if self.is_consistent(var, val, var_domain, var_constraints):
                var_domain[var] = val
                var_unassigned -= 1
                inferences = self.inference(var, var_domain, var_constraints)

                if inferences != False:
                    result = self.backtrack(var_domain, var_constraints, var_unassigned)

                    if result != False:
                        return result

            var_domain = var_domain_prev
            var_unassigned = var_unassigned_prev

        return False

    def solve(self):
        complete_assignment = self.backtrack(self.var_domain, self.var_constraints, self.var_unassigned)

        for var in complete_assignment:
            r, c = var[0], var[1]
            self.puzzle[r][c] = complete_assignment[var]

        return self.puzzle

    # you may add more classes/functions if you think is useful
    # However, ensure all the classes/functions are in this file ONLY
    # Note that our evaluation scripts only call the solve method.
    # Any other methods that you write should be used within the solve() method.

if __name__ == "__main__":
    # STRICTLY do NOT modify the code in the main function here
    if len(sys.argv) != 3:
        print ("\nUsage: python CS3243_P2_Sudoku_XX.py input.txt output.txt\n")
        raise ValueError("Wrong number of arguments!")

    try:
        f = open(sys.argv[1], 'r')
    except IOError:
        print ("\nUsage: python CS3243_P2_Sudoku_XX.py input.txt output.txt\n")
        raise IOError("Input file not found!")

    puzzle = [[0 for i in range(9)] for j in range(9)]
    lines = f.readlines()

    i, j = 0, 0
    for line in lines:
        for number in line:
            if '0' <= number <= '9':
                puzzle[i][j] = int(number)
                j += 1
                if j == 9:
                    i += 1
                    j = 0

    sudoku = Sudoku(puzzle)
    ans = sudoku.solve()

    with open(sys.argv[2], 'a') as f:
        for i in range(9):
            for j in range(9):
                f.write(str(ans[i][j]) + " ")
            f.write("\n")


#!/usr/bin/env python

import re

import lib.analysis.analyse as a
import lib.analysis.component as a_comp
import lib.dynamic.component as comp
import lib.independence.fs as fs
import lib.settings as s
import lib.ui.menu as menu

# The greater purpose of (functions in) this file is to
# ask user what results are to be analysed

class AnalysisMenuHandler(object):
    '''Object to handle sequential submenu calls,
    and to provide selection filters'''

    # Constructor
    # resultpath is the path where all results are kept
    # components is a list of available methodcomponent
    def __init__(self, resultpath, components):
        self.current_path = resultpath
        self.components = components

    # Returns a list of dirs with datetime name, found in Meizodon/results
    def get_result_dirs(self):
        if not fs.isdir(self.current_path):
            return []
        return_list = fs.lsonlydir(self.current_path, full_paths=True)

        if fs.isdir(s.analyseddir):
            already_analysed = fs.lsonlydir(s.analyseddir)
        else:
            already_analysed = []
        regex = '[0-9]+-[0-9]{2}-[0-9]{2}\([0-9]{2}:[0-9]{2}:[0-9]{2}\)'
        pattern = re.compile(regex)

        for item in return_list:
            basename = fs.basename(item)
            if (not pattern.match(basename)) or (basename in already_analysed):
                return_list.remove(item)
        return return_list

    # Returns a list of dirs in Meizodon/results/<datetime>/,
    # with names corresponding to available methods
    def get_result_sub_dirs(self):
        return_list = fs.lsonlydir(self.current_path)
        component_names = [str(x) for x in self.components]

        for item in return_list:
            if not item in component_names:
                return_list.remove(item)
        return return_list

    # Takes a full path to a result, returns an AnalysisComponent
    # path like: results/<datetime>/DroidSafe/adsvr.soporteweb.es.apk
    def get_analysis_component(self, path):
        path_array = fs.split(path)
        datetime = path_array[-3]
        method_name = path_array[-2]
        apk_name = path_array[-1]

        method = comp.Component.get_component_for_name(self.components, method_name)
        results = fs.join(s.resultsdir,datetime,'results.csv')

        analysis_result_loc = fs.join(s.analyseddir,datetime,method_name,apk_name)
        return a_comp.AnalysisComponent(path, analysis_result_loc, method, results)

    # Takes list of full paths to a result, returns list of AnalysisComponents
    # path like: [results/<datetime>/DroidSafe/adsvr.soporteweb.es.apk, ...]
    def get_analysis_components(self, paths):
        analysiscomponents = []
        for path in paths:
            analysiscomponents.append(self.get_analysis_component(path))
        return analysiscomponents

    # Takes list of paths to methods, returns list of AnalysisComponents
    # path like: [results/<datetime>/DroidSafe, results/<datetime>/JN-SAF]
    def get_sub_all_analysis_components(self, paths):
        analysiscomponents = []
        for path in paths:
            contents = fs.lsonlydir(path, full_paths=True)
            analysiscomponents.extend(self.get_analysis_components(contents))
        return analysiscomponents

    # Takes list of path to execution results, returns list of AnalysisComponents
    # path like: [results/2019-04-14(13:59:55), results/2019-05-24(01:23:34)]
    def get_all_analysis_components(self, paths):
        analysiscomponents = []
        for path in paths:
            contents = fs.lsonlydir(path, full_paths=True)
            analysiscomponents.extend(self.get_sub_all_analysis_components(contents))
        return analysiscomponents

    # Perform analysis on one or more full execution results
    # path like: [results/2019-04-14(13:59:55), results/2019-05-24(01:23:34)]
    def analyse_all(self, paths):
        analysiscomponents = self.get_all_analysis_components(paths)
        a.analyse_all(analysiscomponents)

    # Perform analysis on one or more components from a execution results
    # path like: [results/<datetime>/DroidSafe, results/<datetime>/JN-SAF]
    def analyse_sub_all(self, paths):
        analysiscomponents = self.get_sub_all_analysis_components(paths)
        a.analyse_all(analysiscomponents)

    # Perform analysis on one or more apks from one component from one execution result
    # path like: [results/<datetime>/DroidSafe/adsvr.soporteweb.es.apk, ...]
    def analyse_sub_sub_all(self, paths):
        analysiscomponents = self.get_analysis_components(paths)
        a.analyse_all(analysiscomponents)

    # Perform analysis on exactly 1 apk's execution result for one component
    # path like: results/<datetime>/DroidSafe/adsvr.soporteweb.es.apk
    def analyse_sub_sub_single(self, path):
        analysiscomponent = self.get_analysis_component(path)
        a.analyse_all([analysiscomponent])

    # Shows user a menu to determine which analyse generated
    # result directories should be analysed
    def analysis_menu(self):
        if not fs.isdir(s.resultsdir) or not fs.ls(s.resultsdir):
            print('Nothing to analyse.')
            return

        while True:
            print('Results for which run do you want to analyse?')
            options = self.get_result_dirs()

            chosenopts, result = menu.standard_menu(options, lambda x: fs.basename(str(x)))
            if result == menu.MenuResults.CHOSEN:
                if len(chosenopts) == 1:
                    self.current_path = fs.join(self.current_path,chosenopts[0])
                    self.analysis_submenu()
                    return
                elif len(chosenopts) > 1:
                    self.analyse_all(chosenopts)
                    return
            elif result == menu.MenuResults.EVERYTHING:
                self.analyse_all(chosenopts)
                return
            elif result == menu.MenuResults.BACK:
                return

    # Shows user a menu to further decide which
    # execution results should be analysed
    def analysis_submenu(self):
        if not fs.ls(self.current_path):
            print('Nothing to analyse here')
            return

        while True:
            print('Results for which method do you want to analyse?')
            options = self.get_result_sub_dirs()

            chosenopts, result = menu.standard_menu(options, lambda x: str(x))
            if result == menu.MenuResults.CHOSEN:
                if len(chosenopts) == 1:
                    self.current_path = fs.join(self.current_path,chosenopts[0])
                    self.analysis_sub_submenu()
                    return
                elif len(chosenopts) > 1:
                    self.analyse_sub_all([fs.join(self.current_path,x) for x in chosenopts])
                    return
            elif result == menu.MenuResults.EVERYTHING:
                self.analyse_sub_all([fs.join(self.current_path,x) for x in chosenopts])
                return
            elif result == menu.MenuResults.BACK:
                self.current_path = fs.dirname(self.current_path)
                return

    # Shows user a menu to further decide which
    # execution results should be analysed
    def analysis_sub_submenu(self):
        if not fs.ls(self.current_path):
            print('Nothing to analyse here')
            return

        print('Results for which apk do you want to analyse?')
        options = fs.lsonlydir(self.current_path)

        chosenopts, result = menu.standard_menu(options, lambda x: str(x))
        if result == menu.MenuResults.CHOSEN:
            if len(chosenopts) == 1:
                self.current_path = fs.join(self.current_path,chosenopts[0])
                self.analyse_sub_sub_single(self.current_path)
            elif len(chosenopts) > 1:
                self.analyse_sub_sub_all([fs.join(self.current_path,x) for x in chosenopts])
        elif result == menu.MenuResults.EVERYTHING:
            self.analyse_sub_sub_all([fs.join(self.current_path,x) for x in chosenopts])
        elif result == menu.MenuResults.BACK:
            self.current_path = fs.dirname(self.current_path)

# Returns True if this window should be shown in the main menu
# Otherwise, it returns False
def should_show(components):
    handler = AnalysisMenuHandler(s.resultsdir, components)
    return len(handler.get_result_dirs()) > 0

# Main function of this menu. Creates a handler-object and executes it
def analysis_menu(components):
    handler = AnalysisMenuHandler(s.resultsdir, components)
    handler.analysis_menu()


# Pure Doubly Linked List
# My intention is to get familiar with Doubly Linked List before implementing the LRU cache algorithm.

class Node:
    def __init__(self, next = None, prev = None, data = None):
        self.next = next
        self.prev = prev
        self.data = data

class DoublyLinkedList:
    # Adding a node at the front of the list
    def __init__(self):
        self.head = None

    def push(self, new_data):
        # 1 & 2: Allocate the Node & Put in the data
        new_node = Node(data = new_data)

        # 3: Make next of the new node as head and previous as NULL
        new_node.next = self.head
        new_node.prev = None

        # 4. change prev of head node to new node
        if self.head is not None:
            self.head.prev = new_node

        # 5. move the head to point to the new node
        self.head = new_node

    def insertAfter(self, prev_node, new_data):
        # 1: check if prev_node is not NULL
        if prev_node == None:
            print("This node doesn't exist in DDL")
            return

        # 2: allocate node and 3: put in the data
        new_node = Node(data = new_data)

        # 4: Make next of new_node as next of next of prev_node
        new_node.next = prev_node.next

        # 5: Make the next of new_node as new_node
        prev_node.next = new_node

        # 6: Make the prev of new_node as prev_node
        new_node.prev = prev_node

        # 7: Change previous of new_node's next node
        if new_node.next != None:
            new_node.next.prev = new_node

    def append(self, new_data):
        # 1: allocate node and 2: put in the data
        new_node = Node(data = new_data)
        last = self.head

        # 3: This new_node is going to be the last node,
        # so make next of this node as NULL
        new_node.next = None

        # 4: If the DLL is empty, make prev of the new_node as NULL
        if self.head == None:
            new_node.prev = None
            self.head = new_node
            return

        # 5: traverse till the last node
        while last.next != None:
            last = last.next

        # 6: Make the next of last node as new_node
        last.next = new_node

        # 7: Make the previous of new_node as last
        new_node.prev = last

        return

dll = DoublyLinkedList()
dll.append(3)
dll.insertAfter(dll.head.next, 4)
print(dll)

# python3 cache.py


from flask import Flask,render_template,request
from pymongo import MongoClient
import subprocess as sp
import os

mongo_server_url="mongodb://127.0.0.1:27017"
client = MongoClient(mongo_server_url)

app = Flask("chat app")
#here i am going to defind database and collection name
db ="lw"
collection="flask"

#We have to specify that In which IP and port you want to run this web app
port=80
hostname="0.0.0.0"

@app.route('/')
def home():
    #Very Important steps
    file=open("names.yml" , "r+")
    file.truncate(0)
    file.close()
    file=open("mobiles.yml" , "r+")
    file.truncate(0)
    file.close()
    file=open("emails.yml" , "r+")
    file.truncate(0)
    file.close()
    return render_template("index.html")

@app.route('/sumbitted' , methods=['POST'])
def sumbitted():
    name=request.form.get("name")
    mobile=request.form.get("mobile")
    email=request.form.get("email")
    #inserting the data in mongodb server
    client[db][collection].insert({"name": name , "mobile": mobile , "email": email})
    #now i want to do some manupulation to store the name, mobile and email

    # file handling for "names.yml"
    f = open("names.yml" ,"a")
    var="moqaddas"
    f.write("name: ")
    f.write(name)
    f.close()

    # file handling for "mobiles.yml"
    f = open("mobiles.yml" ,"a")
    var="moqaddas"
    f.write("mobile: ")
    f.write(mobile)
    f.close()

    # file handling for "names.yml"
    f = open("emails.yml" ,"a")
    var="moqaddas"
    f.write("email: ")
    f.write(email)
    f.close()

    m=sp.getstatusoutput("ansible-playbook mail.yml  --vault-password-file password.txt")
    exit_code=m[0]
    output=m[1]
    if exit_code==0:

        return render_template("response.html")
    else: return render_template("err.html")

app.run(debug=True , port=port , host=hostname)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 22 20:10:01 2018

@author: Suveen
"""

from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
import re

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
html = urlopen(url, context=ctx).read()

# html.parser is the HTML parser included in the standard Python 3 library.
# information on other HTML parsers is here:
# http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser
soup = BeautifulSoup(html, "html.parser")

# Retrieve all of the anchor tags
tags = soup('span')
count = 0
com_sum = 0
numlist= list()
for tag in tags:
    # Look at the parts of a tag
    count= count+1
    str_tag= str(tag)
#    print('TAg : ',tag)
#    print('String', str_tag)
    stuff=re.findall('[0-9]+',str_tag)

    for k in range(len(stuff)):
        num = float(stuff[k])
        com_sum = com_sum+ num
#    print (num)
        numlist.append(num)
#print(numlist)

print('Count ',count)
print('Sum ', int(com_sum))


#Python - Partie 2 - Exercice 9
#Script qui affiche 8 carré à la suite.

#Importation des module
from turtle import *
from dessins_tortue import *

#Lecture de l'entrée
taille=int(input("Entrez la taille des carrés."))
couleur=input("Entrez la couleur des carrés. (en anglais)")

for i in range (8):
    down()
    carre(taille,couleur)
    up()
    goto (xcor()+taille+20,ycor())


import torch
import torch.nn.functional as F

def R_from_axis_angle(k: torch.tensor, theta: torch.tensor):
    if torch.norm(k) == 0.:
        return torch.eye(3)
    k = F.normalize(k, p=2., dim=0)
    kx, ky, kz = k[0], k[1], k[2]
    cos, sin = torch.cos(theta), torch.sin(theta)
    R = torch.zeros((3, 3)).to(k)
    R[0, 0] = cos + (kx**2) * (1 - cos)
    R[0, 1] = kx * ky * (1 - cos) - kz * sin
    R[0, 2] = kx * kz * (1 - cos) + ky * sin
    R[1, 0] = kx * ky * (1 - cos) + kz * sin
    R[1, 1] = cos + (ky**2) * (1 - cos)
    R[1, 2] = ky * kz * (1 - cos) - kx * sin
    R[2, 0] = kx * kz * (1 - cos) - ky * sin
    R[2, 1] = ky * kz * (1 - cos) + kx * sin
    R[2, 2] = cos + (kz**2) * (1 - cos)
    return R

def axis_angle_to_quaternions(axis: torch.tensor, angle: torch.tensor):
    a = F.normalize(axis, p=2., dim=0)
    half_angle = angle * 0.5
    sin_ = torch.sin(half_angle)
    cos_ = torch.cos(half_angle)
    r = cos_
    i = a[0] * sin_
    j = a[1] * sin_
    k = a[2] * sin_
    q = torch.tensor([r, i, j, k], dtype=torch.float32).to(axis)
    return q

def R_from_quaternions(quaternions: torch.tensor):
    quaternions = F.normalize(quaternions, p=2., dim=0)

    r, i, j, k = torch.unbind(quaternions, -1)
    two_s = 2.0 / (quaternions * quaternions).sum(-1)

    o = torch.stack(
        (
            1 - two_s * (j * j + k * k),
            two_s * (i * j - k * r),
            two_s * (i * k + j * r),
            two_s * (i * j + k * r),
            1 - two_s * (i * i + k * k),
            two_s * (j * k - i * r),
            two_s * (i * k - j * r),
            two_s * (j * k + i * r),
            1 - two_s * (i * i + j * j),
        ),
        -1,
    )
    return o.reshape(quaternions.shape[:-1] + (3, 3)).to(quaternions)

def _sqrt_positive_part(x: torch.Tensor) -> torch.Tensor:
    """
    Returns torch.sqrt(torch.max(0, x))
    but with a zero subgradient where x is 0.
    """
    ret = torch.zeros_like(x)
    positive_mask = x > 0
    ret[positive_mask] = torch.sqrt(x[positive_mask])
    return ret

def matrix_to_quaternion(matrix: torch.Tensor) -> torch.Tensor:
    """
    Convert rotations given as rotation matrices to quaternions.

    Args:
        matrix: Rotation matrices as tensor of shape (..., 3, 3).

    Returns:
        quaternions with real part first, as tensor of shape (..., 4).
    """
    if matrix.size(-1) != 3 or matrix.size(-2) != 3:
        raise ValueError(f"Invalid rotation matrix shape {matrix.shape}.")

    batch_dim = matrix.shape[:-2]
    m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind(
        matrix.reshape(batch_dim + (9,)), dim=-1
    )

    q_abs = _sqrt_positive_part(
        torch.stack(
            [
                1.0 + m00 + m11 + m22,
                1.0 + m00 - m11 - m22,
                1.0 - m00 + m11 - m22,
                1.0 - m00 - m11 + m22,
            ],
            dim=-1,
        )
    )

    # we produce the desired quaternion multiplied by each of r, i, j, k
    quat_by_rijk = torch.stack(
        [
            # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and
            #  `int`.
            torch.stack([q_abs[..., 0] ** 2, m21 - m12, m02 - m20, m10 - m01], dim=-1),
            # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and
            #  `int`.
            torch.stack([m21 - m12, q_abs[..., 1] ** 2, m10 + m01, m02 + m20], dim=-1),
            # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and
            #  `int`.
            torch.stack([m02 - m20, m10 + m01, q_abs[..., 2] ** 2, m12 + m21], dim=-1),
            # pyre-fixme[58]: `**` is not supported for operand types `Tensor` and
            #  `int`.
            torch.stack([m10 - m01, m20 + m02, m21 + m12, q_abs[..., 3] ** 2], dim=-1),
        ],
        dim=-2,
    )

    # We floor here at 0.1 but the exact level is not important; if q_abs is small,
    # the candidate won't be picked.
    flr = torch.tensor(0.1).to(dtype=q_abs.dtype, device=q_abs.device)
    quat_candidates = quat_by_rijk / (2.0 * q_abs[..., None].max(flr))

    # if not for numerical problems, quat_candidates[i] should be same (up to a sign),
    # forall i; we pick the best-conditioned one (with the largest denominator)

    return quat_candidates[
        F.one_hot(q_abs.argmax(dim=-1), num_classes=4) > 0.5, :
    ].reshape(batch_dim + (4,))

def R_from_6d(d6: torch.tensor):
    """
    Converts 6D rotation representation by Zhou et al. [1] to rotation matrix
    using Gram--Schmidt orthogonalization per Section B of [1].
    Args:
        d6: 6D rotation representation, of size (*, 6)

    Returns:
        batch of rotation matrices of size (*, 3, 3)

    [1] Zhou, Y., Barnes, C., Lu, J., Yang, J., & Li, H.
    On the Continuity of Rotation Representations in Neural Networks.
    IEEE Conference on Computer Vision and Pattern Recognition, 2019.
    Retrieved from http://arxiv.org/abs/1812.07035
    """

    a1, a2 = d6[..., :3], d6[..., 3:]
    b1 = F.normalize(a1, dim=-1)
    b2 = a2 - (b1 * a2).sum(-1, keepdim=True) * b1
    b2 = F.normalize(b2, dim=-1)
    b3 = torch.cross(b1, b2, dim=-1)
    return torch.stack((b1, b2, b3), dim=-2).to(d6)

def quaternion_to_axis_angle(quaternions: torch.Tensor) -> torch.Tensor:
    """
    Convert rotations given as quaternions to axis/angle.

    Args:
        quaternions: quaternions with real part first,
            as tensor of shape (..., 4).

    Returns:
        Rotations given as a vector in axis angle form, as a tensor
            of shape (..., 3), where the magnitude is the angle
            turned anticlockwise in radians around the vector's
            direction.
    """
    norms = torch.norm(quaternions[..., 1:], p=2, dim=-1, keepdim=True)
    half_angles = torch.atan2(norms, quaternions[..., :1])
    angles = 2 * half_angles
    eps = 1e-6
    small_angles = angles.abs() < eps
    sin_half_angles_over_angles = torch.empty_like(angles)
    sin_half_angles_over_angles[~small_angles] = (
        torch.sin(half_angles[~small_angles]) / angles[~small_angles]
    )
    # for x small, sin(x/2) is about x/2 - (x/2)^3/6
    # so sin(x/2)/x is about 1/2 - (x*x)/48
    sin_half_angles_over_angles[small_angles] = (
        0.5 - (angles[small_angles] * angles[small_angles]) / 48
    )
    axis = quaternions[..., 1:] / sin_half_angles_over_angles
    axis = F.normalize(axis, p=2., dim=0)
    return axis, angles

def axis_angle_from_6d(d6: torch.Tensor):
    R = R_from_6d(d6)
    q = matrix_to_quaternion(R)
    axis, angle = quaternion_to_axis_angle(q)
    return axis, angle

def matrix_to_axis_angle(R: torch.Tensor):
    return quaternion_to_axis_angle(matrix_to_quaternion(R))


import cv2,os,shutil
import numpy as np
import argparse

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required=True,help="directory of the cropped odonates")
ap.add_argument("-o", "--output", required=True,\
help="parent directory to which each one be stored")
args = vars(ap.parse_args())

input_dir=args['input']
out_dir=args['output']

for i in range(14):
    vars()["dir"+str(i+1)]=out_dir+ 'thumbi_%s/'%str(i+1)
try:
    for i in range(14):

        os.mkdir(out_dir+ 'thumbi_%s/'%str(i+1))
        print("directory %s created"%(i+1))
except FileExistsError :
    print("Directories already exists")

for fln in sorted(os.listdir(input_dir)):
    fname=fln.replace(".jpg"," ")
    img=cv2.imread(os.path.join(input_dir,fln))
    cv2.namedWindow(fname, cv2.WINDOW_NORMAL)
    cv2.setWindowProperty(fname, cv2.WND_PROP_FULLSCREEN,
                          cv2.WINDOW_FULLSCREEN)
    cv2.imshow(fname,img)
    while(1):
        k=cv2.waitKey(0) & 0xFF
        if k==ord("a"):
            cv2.destroyAllWindows()
            shutil.move(os.path.join(input_dir,fln),dir1)
            break
        if k==ord("b"):
            cv2.destroyAllWindows()
            shutil.move(os.path.join(input_dir,fln),dir2)
            break
        if k==ord("c"):
            cv2.destroyAllWindows()
            shutil.move(os.path.join(input_dir,fln),dir3)
            break
        if k==ord("d"):
            cv2.destroyAllWindows()
            shutil.move(os.path.join(input_dir,fln),dir4)
            break
        if k==ord("e"):
            cv2.destroyAllWindows()
            shutil.move(os.path.join(input_dir,fln),dir5)
            break
        if k==ord("f"):
            cv2.destroyAllWindows()
            shutil.move(os.path.join(input_dir,fln),dir6)
            break
        if k==ord("g"):
            cv2.destroyAllWindows()
            shutil.move(os.path.join(input_dir,fln),dir7)
            break
        if k==ord("h"):
            cv2.destroyAllWindows()
            shutil.move(os.path.join(input_dir,fln),dir8)
            break
        if k==ord("i"):
            cv2.destroyAllWindows()
            shutil.move(os.path.join(input_dir,fln),dir9)
            break
        if k==ord("j"):
            cv2.destroyAllWindows()
            shutil.move(os.path.join(input_dir,fln),dir10)
            break
        if k==ord("k"):
            cv2.destroyAllWindows()
            shutil.move(os.path.join(input_dir,fln),dir11)
            break
        if k==ord("l"):
            cv2.destroyAllWindows()
            shutil.move(os.path.join(input_dir,fln),dir12)
            break
        if k==ord("m"):
            cv2.destroyAllWindows()
            shutil.move(os.path.join(input_dir,fln),dir13)
            break
        if k==27:
            cv2.destroyAllWindows()
            shutil.move(os.path.join(input_dir,fln),dir14)
            break


from datetime import datetime
from pyquery import PyQuery as pquery

import urllib3
urllib3.disable_warnings()

import webbrowser

def timestamp():
    return datetime.now().strftime('%Y-%m-%d %H:%M:%S')

def main():
    active = 'https://webbtelescope.org/contents/media/images/2022/028/01G77Q8BTTSEB7ZSB2ZEY49HSQ'

    print(f'{timestamp()} Starting...')

    count=0
    while (active):
        py = pquery(active, verify=False)
        page_num = int([i.text() for i in py.find("div.controls").parent().find('li').items()][0])

        span = py.find("span")
        spans = [i.text() for i in span.items()]

        try:
            next_idx = spans.index("Next")
            next = 'https://webbtelescope.org' + [i.attr("href") for i in span.eq(next_idx).parent().items()][0]
        except ValueError:
            if page_num == 247:
                pass
            else:
                print(active)
                print(page_num)
                print(timestamp())
                raise

        downloads = py.find("div.media-library-links-list").find('a')

        imgs_text = [i.text() for i in downloads.items()]
        imgs_links = [i.attr('href') for i in downloads.items()]

        full_res_str = [i for i in imgs_text if i.startswith('Full') and 'TIF' not in i] # Full Res first
        if not full_res_str:
            full_res_str = [i for i in imgs_text if 'TIF' not in i] # Png next or first jpg
            if not full_res_str:
                full_res_str = [imgs_text[0]] # Whatever is left over

        full_res_idx = imgs_text.index(full_res_str[0])
        img_link = 'https:' + imgs_links[full_res_idx]

        webbrowser.open(img_link)

        count+=1
        if page_num < 247:
            active = next
        else:
            break

    print(f'{timestamp()} Done...')

if __name__ == "__main__":
    main()


import requests

url = "https://ngl.link/api/submit"

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36",
    "X-Requested-With": "XMLHttpRequest",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    "Origin": "https://ngl.link",
    "Referer": "https://ngl.link/z7hejan"
}

data = {
    "username": "TARGET HERE",
    "question": "UR QUESTION HERE",
    "deviceId": "cfd278d9-b21d-444d-8a6f-6e7494f84bf8",
    "gameSlug": "",
    "referrer": ""
}

# amount of the spamms
num_requests = 100

for i in range(num_requests):
    response = requests.post(url, headers=headers, data=data)
    print(f"Request {i+1}: {response.status_code}")


import csv
import shlex
import subprocess
from decimal import Decimal

ZERO = Decimal("0")

def execute(cmd):
    # TODO: check return code
    process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    return process.communicate()  # must be used instead of wait

def save_intervals(intervals, filename):
    with open(filename, encoding="utf8", mode="w") as fobj:
        writer = csv.writer(fobj)
        writer.writerow(["start", "end"])
        for interval in intervals:
            writer.writerow([interval["start"], interval["end"]])

def load_intervals(filename):
    with open(filename, encoding="utf8") as fobj:
        intervals = [{"start": Decimal(row["start"]), "end": Decimal(row["end"])} for row in csv.DictReader(fobj)]
    return intervals

def print_intervals(intervals):
    print("  start,end")
    for interval in intervals:
        start = interval["start"]
        end = interval["end"]
        print(f"  {start:10.5f},{end:10.5f}")

def video_length(filename):
    cmd = f'ffprobe -v quiet -of csv=p=0 -show_entries format=duration "{filename}"'
    stdout, stderr = execute(cmd)
    return Decimal(stdout.decode("utf8").strip())

def detect_silence_intervals(filename, noise_level, minimum_duration):
    command = (
        f'ffmpeg -i "{filename}" '
        f"-af silencedetect=noise={noise_level}dB:d={minimum_duration} "
        f"-f null -"
    )
    stdout, stderr = execute(command)
    result = stderr.decode("utf8")
    intervals = []
    start = None
    end = None
    for line in result.splitlines():
        if "silence_" not in line:
            continue
        data = line.split("silence_")[1].split(": ")
        if data[0] == "start":
            start = Decimal(data[1].strip())
        elif data[0] == "end":
            end = Decimal(data[1].split()[0].strip())
            this_duration = Decimal(line.split("silence_duration:")[1].strip())
            if start < 0:  # TODO: should really force this?
                start = ZERO
                this_duration = end
            row = {"start": start, "end": end, "duration": this_duration}
            intervals.append(row)
            start, end, this_duration = None, None, None

    return intervals

def extract_non_silence_from_silence(silence_intervals, threshold=ZERO):
    extract = []
    pairs = zip(silence_intervals, silence_intervals[1:])
    for index, (silence_1, silence_2) in enumerate(pairs, start=1):
        start = silence_1["end"] - threshold
        if start < 0:
            start = ZERO
        end = silence_2["start"] + threshold
        extract.append({"start": start, "end": end})

    return extract

def optimize_intervals(intervals, minimum_gap):
    finished = False
    while not finished:
        finished = True
        result = []
        last = len(intervals) - 1
        index = 0
        while index <= last:
            interval = intervals[index]
            if index < last:
                next_interval = intervals[index + 1]
                if next_interval["start"] - interval["end"] <= minimum_gap:
                    # merge these two intervals
                    finished = False
                    result.append({"start": interval["start"], "end": next_interval["end"]})
                    index += 1  # jump the next one
                else:
                    result.append(interval)

            else:  # last interval, just append
                result.append(interval)

            index += 1
        intervals = result

    return result


from django.urls import path

from . import views

urlpatterns = [
    # API routes
    path('', views.index, name='index'),
    path('library', views.library, name='library'),
    path('library/<int:song_id>', views.song, name='song'),
    path('setlists', views.setlists, name='setlists'),
    path('setlists/<int:id>', views.setlist, name='setlist'),
    path('search', views.search_genius, name='search'),
    path('search/<int:id>', views.search_genius_by_id, name='search_by_id'),
    path('profile/<int:userId>', views.profile_view, name='profile'),
    # Auth routes
    path('session', views.session_view, name='session'),
    path('csrf', views.get_csrf_token, name='csrf'),
    path('register', views.register, name='register'),
    path('login', views.login_view, name='login'),
    path('logout', views.logout_view, name='logout'),
]


##### for mounting drive on colab

# from google.colab import drive
# drive.mount('/content/drive')

#################################

import urllib.request
import os
import time
import tensorflow as tf
root_path = os.getcwd()

def download_images(link_file_images,output_directory,image_type):
  print("\nDownoading", image_type)

  with open(link_file_images,'r') as link_file:
    image_links = link_file.readlines()

  for idx, image_link in enumerate(image_links):
    image_path = output_directory + image_type  + "/image_%d.tiff" % (idx+1)
    urllib.request.urlretrieve(image_link, image_path)

if __name__ == '__main__':
    dataset_name = "MassachusettsRoads"
    link_file_images = (root_path+ "/src/Images.txt").format(dataset_name)
    link_file_targets = (root_path+ "/src/Targets.txt").format(dataset_name)
    output_directory = (root_path+ "/Data/").format(dataset_name)
    tf.io.gfile.mkdir(output_directory+ "Images")
    tf.io.gfile.mkdir(output_directory+ "Targets" )
    if not os.path.exists(output_directory):
        tf.io.gfile.mkdir(output_directory)

    start_time = time.time()
    download_images(link_file_images, output_directory, "Images")
    download_images(link_file_targets, output_directory, "Targets")
    print("TOTAL TIME: {} minutes".format(round((time.time() - start_time)/60, 2)))


from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from .models import Product, Inventory, OrderLine
from import_export import fields
from import_export.widgets import ForeignKeyWidget

class ProductResource(resources.ModelResource):
    class Meta:
        model = Product
        import_id_fields = ['product_code']

@admin.register(Product)
class ProductAdmin(ImportExportModelAdmin):
    resource_class = ProductResource
    import_export_options = {'update': True}

class InventoryResource(resources.ModelResource):
    product = fields.Field(
        column_name='product_code',
        attribute='product',
        widget=ForeignKeyWidget(Product, 'product_code')
    )

    class Meta:
        model = Inventory
        fields = ('id', 'product', 'current_stock')

@admin.register(Inventory)
class InventoryAdmin(ImportExportModelAdmin):
    resource_class = InventoryResource

class OrderLineResource(resources.ModelResource):
    product = fields.Field(
        column_name='product_code',
        attribute='product',
        widget=ForeignKeyWidget(Product, 'product_code')
    )

    class Meta:
        model = OrderLine
        fields = ('id', 'product', 'reorder_point')

@admin.register(OrderLine)
class OrderLineAdmin(ImportExportModelAdmin):
    resource_class = OrderLineResource


from collections import namedtuple
from enum import Enum

from dagster import check
from dagster.core.definitions import Materialization, SolidHandle
from dagster.core.definitions.events import EventMetadataEntry
from dagster.core.serdes import whitelist_for_serdes
from dagster.core.types.runtime_type import RuntimeType
from dagster.utils import merge_dicts
from dagster.utils.error import SerializableErrorInfo

@whitelist_for_serdes
class StepOutputHandle(namedtuple('_StepOutputHandle', 'step_key output_name')):
    @staticmethod
    def from_step(step, output_name='result'):
        check.inst_param(step, 'step', ExecutionStep)

        return StepOutputHandle(step.key, output_name)

    def __new__(cls, step_key, output_name='result'):
        return super(StepOutputHandle, cls).__new__(
            cls,
            step_key=check.str_param(step_key, 'step_key'),
            output_name=check.str_param(output_name, 'output_name'),
        )

@whitelist_for_serdes
class StepInputData(namedtuple('_StepInputData', 'input_name type_check_data')):
    def __new__(cls, input_name, type_check_data):
        return super(StepInputData, cls).__new__(
            cls,
            input_name=check.str_param(input_name, 'input_name'),
            type_check_data=check.opt_inst_param(type_check_data, 'type_check_data', TypeCheckData),
        )

@whitelist_for_serdes
class TypeCheckData(namedtuple('_TypeCheckData', 'success label description metadata_entries')):
    def __new__(cls, success, label, description=None, metadata_entries=None):
        return super(TypeCheckData, cls).__new__(
            cls,
            success=check.bool_param(success, 'success'),
            label=check.str_param(label, 'label'),
            description=check.opt_str_param(description, 'description'),
            metadata_entries=check.opt_list_param(
                metadata_entries, metadata_entries, of_type=EventMetadataEntry
            ),
        )

@whitelist_for_serdes
class UserFailureData(namedtuple('_UserFailureData', 'label description metadata_entries')):
    def __new__(cls, label, description=None, metadata_entries=None):
        return super(UserFailureData, cls).__new__(
            cls,
            label=check.str_param(label, 'label'),
            description=check.opt_str_param(description, 'description'),
            metadata_entries=check.opt_list_param(
                metadata_entries, metadata_entries, of_type=EventMetadataEntry
            ),
        )

@whitelist_for_serdes
class StepOutputData(
    namedtuple('_StepOutputData', 'step_output_handle intermediate_materialization type_check_data')
):
    def __new__(cls, step_output_handle, intermediate_materialization=None, type_check_data=None):
        return super(StepOutputData, cls).__new__(
            cls,
            step_output_handle=check.inst_param(
                step_output_handle, 'step_output_handle', StepOutputHandle
            ),
            intermediate_materialization=check.opt_inst_param(
                intermediate_materialization, 'intermediate_materialization', Materialization
            ),
            type_check_data=check.opt_inst_param(type_check_data, 'type_check_data', TypeCheckData),
        )

    @property
    def output_name(self):
        return self.step_output_handle.output_name

@whitelist_for_serdes
class StepFailureData(namedtuple('_StepFailureData', 'error user_failure_data')):
    def __new__(cls, error, user_failure_data):
        return super(StepFailureData, cls).__new__(
            cls,
            error=check.opt_inst_param(error, 'error', SerializableErrorInfo),
            user_failure_data=check.opt_inst_param(
                user_failure_data, 'user_failure_data', UserFailureData
            ),
        )

@whitelist_for_serdes
class StepSuccessData(namedtuple('_StepSuccessData', 'duration_ms')):
    def __new__(cls, duration_ms):
        return super(StepSuccessData, cls).__new__(
            cls, duration_ms=check.float_param(duration_ms, 'duration_ms')
        )

class StepKind(Enum):
    COMPUTE = 'COMPUTE'

class StepInputSourceType(Enum):
    SINGLE_OUTPUT = 'SINGLE_OUTPUT'
    MULTIPLE_OUTPUTS = 'MULTIPLE_OUTPUTS'
    CONFIG = 'CONFIG'

class StepInput(
    namedtuple('_StepInput', 'name runtime_type source_type source_handles config_data')
):
    def __new__(cls, name, runtime_type, source_type, source_handles=None, config_data=None):
        return super(StepInput, cls).__new__(
            cls,
            name=check.str_param(name, 'name'),
            runtime_type=check.inst_param(runtime_type, 'runtime_type', RuntimeType),
            source_type=check.inst_param(source_type, 'source_type', StepInputSourceType),
            source_handles=check.opt_list_param(
                source_handles, 'source_handles', of_type=StepOutputHandle
            ),
            config_data=config_data,  # can be any type
        )

    @property
    def is_from_output(self):
        return (
            self.source_type == StepInputSourceType.SINGLE_OUTPUT
            or self.source_type == StepInputSourceType.MULTIPLE_OUTPUTS
        )

    @property
    def is_from_single_output(self):
        return self.source_type == StepInputSourceType.SINGLE_OUTPUT

    @property
    def is_from_multiple_outputs(self):
        return self.source_type == StepInputSourceType.MULTIPLE_OUTPUTS

    @property
    def dependency_keys(self):
        return {handle.step_key for handle in self.source_handles}

class StepOutput(namedtuple('_StepOutput', 'name runtime_type optional')):
    def __new__(cls, name, runtime_type, optional):
        return super(StepOutput, cls).__new__(
            cls,
            name=check.str_param(name, 'name'),
            runtime_type=check.inst_param(runtime_type, 'runtime_type', RuntimeType),
            optional=check.bool_param(optional, 'optional'),
        )

class ExecutionStep(
    namedtuple(
        '_ExecutionStep',
        (
            'pipeline_name key_suffix step_inputs step_input_dict step_outputs step_output_dict '
            'compute_fn kind solid_handle logging_tags metadata'
        ),
    )
):
    def __new__(
        cls,
        pipeline_name,
        key_suffix,
        step_inputs,
        step_outputs,
        compute_fn,
        kind,
        solid_handle,
        logging_tags=None,
        metadata=None,
    ):
        return super(ExecutionStep, cls).__new__(
            cls,
            pipeline_name=check.str_param(pipeline_name, 'pipeline_name'),
            key_suffix=check.str_param(key_suffix, 'key_suffix'),
            step_inputs=check.list_param(step_inputs, 'step_inputs', of_type=StepInput),
            step_input_dict={si.name: si for si in step_inputs},
            step_outputs=check.list_param(step_outputs, 'step_outputs', of_type=StepOutput),
            step_output_dict={so.name: so for so in step_outputs},
            compute_fn=check.callable_param(compute_fn, 'compute_fn'),
            kind=check.inst_param(kind, 'kind', StepKind),
            solid_handle=check.inst_param(solid_handle, 'solid_handle', SolidHandle),
            logging_tags=merge_dicts(
                {
                    'step_key': str(solid_handle) + '.' + key_suffix,
                    'pipeline': pipeline_name,
                    'solid': solid_handle.name,
                    'solid_definition': solid_handle.definition_name,
                },
                check.opt_dict_param(logging_tags, 'logging_tags'),
            ),
            metadata=check.opt_dict_param(metadata, 'metadata', key_type=str),
        )

    @property
    def key(self):
        return str(self.solid_handle) + '.' + self.key_suffix

    @property
    def solid_name(self):
        return self.solid_handle.name

    @property
    def solid_definition_name(self):
        return self.solid_handle.definition_name

    def has_step_output(self, name):
        check.str_param(name, 'name')
        return name in self.step_output_dict

    def step_output_named(self, name):
        check.str_param(name, 'name')
        return self.step_output_dict[name]

    def has_step_input(self, name):
        check.str_param(name, 'name')
        return name in self.step_input_dict

    def step_input_named(self, name):
        check.str_param(name, 'name')
        return self.step_input_dict[name]


import base64
import json

import requests
from cassandra.cqlengine import connection
from flask import make_response
from flask_restful import Resource

from conf.config import CASSANDRA_HOSTS, FRIEND_KEYSPACE
from conf.service import USER_INFO_BULK_URL
from model.friend import FriendRelation
from service.common import get_user_id_from_jwt

class GetFriendList(Resource):
    def get(self):
        user_id = get_user_id_from_jwt()
        if not user_id:
            return make_response("You must send the userInfo into the header X-Endpoint-Api-Userinfo", 405)

        connection.setup(hosts=CASSANDRA_HOSTS, default_keyspace=FRIEND_KEYSPACE)

        friend_rows = FriendRelation.filter(user_id=user_id)

        friends = {}
        friend_ids = []

        for friend_row in friend_rows:
            friend = friend_row.to_object()
            friend_id = friend['user_id']
            friends[friend_id] = friend
            friend_ids.append(friend_id)

        user_info_list = self._get_user_info_bulk(friend_ids)

        for user in user_info_list:
            user_id = user['user_id']
            friends[user_id]['username'] = user['username']

        return {
            "results": len(friends),
            "friends": friends
        }

    @staticmethod
    def _get_user_info_bulk(user_ids):
        payload = json.dumps({"user_ids": user_ids})
        headers = {'Content-Type': 'application/json'}
        response = requests.post(USER_INFO_BULK_URL, data=payload, headers=headers)
        data = response.json()
        return data.get("users")