from models.movie import Movie as MovieModel
from config.database import session
from schemas.movie import Movie
from config.redis import getRedisConnection
import pickle

db = session()

class MovieService():

    def getMovies(self):
        connection = getRedisConnection()
        result = connection.get("movies")
        if result is None:  # If the cache does not contain the data
            # Get data from database
            result = db.query(MovieModel).all()

            # Store the data in the cache for future access,
            # first converting the data to bytes
            connection.set("movies", pickle.dumps(result))
        else:
            # If the cache contains the data, convert it back to Python objects
            result = pickle.loads(result)
        return result

    def getMovie(self, id):
        connection = getRedisConnection()
        key = "movies:" + str(id)
        result = connection.get(key)
        if result is None:  # If the cache does not contain the data
            # Get data from database
            result = db.query(MovieModel).filter(MovieModel.id == id).first()

            # Store the data in the cache for future access
            connection.set(key, pickle.dumps(result))
        else:
            # If the cache contains the data, convert it back to Python objects
            result = pickle.loads(result)

        return result

    def getMovieByCategory(self, category):
        connection = getRedisConnection()
        key = "movies:" + category
        # Try to get the data from the cache first
        result = connection.get(key)
        if result is None:  # If the cache does not contain the data
            # Get data from database
            result = db.query(MovieModel).filter(
                MovieModel.category == category).all()

            # Store the data in the cache for future access
            connection.set(key, pickle.dumps(result))
        else:
            # If the cache contains the data, convert it back to Python objects
            result = pickle.loads(result)

        return result

    def createMovie(self, movie: Movie):
        connection = getRedisConnection()
        try:
            newMovie = MovieModel(**dict(movie))
            db.add(newMovie)
            db.commit()
            # After successful creation, invalidate the 'movies' cache
            connection.delete("movies")

            # If the category list is cached, also invalidate that
            connection.delete("movies:" + newMovie.category)
            return True
        except Exception as e:
            return e

    def updateMovie(self, id: int, data: Movie):
        connection = getRedisConnection()
        result = db.query(MovieModel).filter(MovieModel.id == id).first()
        if not result:
            return False
        old_category = result.category

        result.title = data.title
        result.overview = data.overview
        result.year = data.year
        result.rating = data.rating
        result.category = data.category
        db.commit()
        # After successful update, invalidate the 'movies' cache
        connection.delete("movies")

        # If the old or new category lists are cached, invalidate them
        connection.delete("movies:" + old_category)
        connection.delete("movies:" + data.category)

        return True

    def deleteMovie(self, id):
        connection = getRedisConnection()
        result = db.query(MovieModel).filter(MovieModel.id == id).first()
        if not result:
            return False
        old_category = result.category
        db.delete(result)
        db.commit()
        # After successful deletion, invalidate the 'movies' cache
        connection.delete("movies")

        # If the category list is cached, invalidate that
        connection.delete("movies:" + old_category)
        connection.delete("movies:" + str(id))
        return True


#!/usr/bin/env python3

# 检查手机号码
def checkPhone(string):
    if len(string) != 11:
        return False

    for i in string:
        if i < "0" or i > "9":
            return False

    if string[0] != "1":
        return False
    elif int(string[1]) > 8:
        return False

    return True

print(checkPhone("13912345678"))
print(checkPhone("139123456781"))
print(checkPhone("139123r5678"))
print(checkPhone("19912345678"))


#!/usr/bin/python3
"""TestCases City module"""
import unittest
import os
import pep8
from models.city import City
from datetime import datetime

class TestCity(unittest.TestCase):
    """Test User class"""

    c1 = City()
    c2 = City()

    def test_pep8_FileStorage(self):
        """Tests pep8 style"""
        style = pep8.StyleGuide(quiet=True)
        p = style.check_files(['models/city.py'])
        self.assertEqual(p.total_errors, 0, "fix pep8")

    def test_docstring_module(self):
        """Check for the DocString"""

        self.assertGreater(len(City.__doc__), 1)

    def test_create(self):
        """Check for the objects"""

        self.assertTrue(self.c1)
        self.assertTrue(self.c2)

    def test_file(self):
        """Check for the file is create"""

        c3 = City()
        c3.save()
        with open('file.json', 'r') as f:
            self.assertIn(c3.id, f.read())

    def test_file_exists(self):
        """Check for the file Exists"""

        if os.path.exists('file.json'):
            os.remove('file.json')

    def test_attr_test(self):
        """Check for user data created attributes"""

        self.c1.name = "Barranquilla"
        self.c2.name = "Puerto Colombia"
        self.assertEqual(self.c1.name, "Barranquilla")
        self.assertEqual(self.c2.name, "Puerto Colombia")

    def test_update_name(self):
        """Check for update user name attributes"""

        self.c1.name = "Barranquilla"
        self.c2.name = "Puerto Colombia"
        self.c1.name = "Cartagena"
        self.assertEqual(self.c1.name, "Cartagena")
        self.assertEqual(self.c2.name, "Puerto Colombia")

    def test_created_at(self):
        """Check created_at is of the datetime"""

        self.assertEqual(datetime, type(City().created_at))
        self.assertEqual(datetime, type(self.c1.created_at))
        self.assertEqual(datetime, type(self.c2.created_at))

    def test_update_at(self):
        """check update_at is of the datetime"""

        self.assertEqual(datetime, type(City().updated_at))
        self.assertEqual(datetime, type(self.c1.updated_at))
        self.assertEqual(datetime, type(self.c2.updated_at))

if __name__ == '__main__':
    unittest.main()


import setuptools

with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()

setuptools.setup(
    name="bluevol",
    version="0.0.1",
    author="presidentarrow",
    author_email="piyush.galphat@gmail.com",
    description="manage volume of bluetooth headphones",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/presidentarrow/bluevol",
    project_urls={
        "Bug Tracker": "https://github.com/presidentarrow/bluevol/issues",
    },
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: Unix",
    ],
    package_dir={"": "src"},
    packages=setuptools.find_packages(where="src"),
    python_requires=">=3.6",
    include_package_data=True,
    package_data={'bluevol': ['/*.glade']},
    entry_points = {
        'console_scripts': ['bluevol=bluevol.index:main'],
    }
)


from django.db.models import QuerySet

from base.models import Player

def schedule_players_info(player: QuerySet[Player]):
    return "\n".join(
        (
            f"{i + 1}. {x['last_name']} {x['first_name']}"
            for i, x in enumerate(
                player.values("first_name", "last_name").order_by("last_name")
            )
        )
    )


import csv
import serial

SerialIn = serial.Serial("COM3",115200)

with open('record.csv', mode='a' , newline='') as am2320_file:
   am2320_writer = csv.writer(am2320_file, delimiter=',')
   line_count=0

   while True:

         while SerialIn.in_waiting:
               data_in = SerialIn.readline()
               data_raw = data_in.decode('utf-8')

               if line_count!=0:
                  temper = data_raw[:-2]

                  temper = temper.split(',')
                  for i in range(len(temper)):

                        temper[i] = int(temper[i])

                  cat = 10 #紀錄類別
                  temper.append(cat)
                  print("recording:",cat, line_count)
                  am2320_writer.writerow(temper)

               line_count = line_count + 1

   # except KeyboardInterrupt:
   #     SerialIn.close()


from typing import Set

import numpy as np

from .bezier_motion_planner import BezierMotionPlanner
from .controllers import ActionSpaceType
from .coordinates import Heading, Pose
from .provider import Provider, ProviderState
from .vehicle import VEHICLE_CONFIGS, VehicleState

class MotionPlannerProvider(Provider):
    def __init__(self):
        self._is_setup = False

    @property
    def action_spaces(self) -> Set[ActionSpaceType]:
        return {ActionSpaceType.TargetPose, ActionSpaceType.MultiTargetPose}

    def setup(self, scenario) -> ProviderState:
        self._motion_planner = BezierMotionPlanner()
        self._vehicle_id_to_index = {}
        self._vehicle_index_to_id = {}
        self._poses = np.empty(shape=(0, 3))  # [[x, y, heading]]; pose of vehicle
        self._is_setup = True

        return ProviderState()

    def teardown(self):
        self._is_setup = False

    def sync(self, provider_state):
        pass  # ... we ignore other sim state here

    def reset(self):
        pass

    def step(self, target_poses_at_t, dt, elapsed_sim_time) -> ProviderState:
        """Step through and update the vehicle poses

        Args:
            target_poses_at_t:
                {vehicle_id: [x, y, heading, seconds_into_future]}
                 pose we would like to have this many seconds into the future
            dt:
                sim time in seconds to advance into the future
        """
        assert self._is_setup
        self._update_membership(target_poses_at_t)

        target_poses_at_t = np.array(
            [
                self._normalize_target_pose(v_index, target_poses_at_t, dt)
                for v_index in self._vehicle_id_to_index.values()
            ],
        ).reshape(-1, 4)

        # vectorized cubic bezier computation
        indices = list(self._vehicle_id_to_index.values())
        first_point_of_traj = self._motion_planner.trajectory_batched(
            self._poses.take(indices, axis=0), target_poses_at_t, 1, dt
        ).reshape(-1, 4)
        speeds = first_point_of_traj[:, 3]
        poses = first_point_of_traj[:, :3]
        self._poses[indices] = poses
        vehicle_type = "passenger"  # TODO: allow for multiple vehicle types

        return ProviderState(
            vehicles=[
                VehicleState(
                    vehicle_id=v_id,
                    vehicle_type=vehicle_type,
                    pose=Pose.from_center(
                        [*poses[idx][:2], 0],
                        Heading(poses[idx][2]),
                    ),
                    dimensions=VEHICLE_CONFIGS[vehicle_type].dimensions,
                    speed=speeds[idx],
                    source="BEZIER",
                )
                for idx, v_id in enumerate(self._vehicle_id_to_index.keys())
            ],
        )

    def _normalize_target_pose(self, vehicle_index, target_poses, dt):
        # Vehicle index may or may not map to an active vehicle, it could be an
        # index of a vehicle we have not garbage collected yet

        vehicle_id = self._vehicle_index_to_id.get(vehicle_index, None)
        pose = target_poses.get(vehicle_id, None)
        if pose is None:
            # agent failed to produce a target pose, just use the previous pose
            prev_pose = self._poses[vehicle_index]
            return np.array([*prev_pose[:3], dt])
        return pose

    def _update_membership(self, active_agents):
        new_ids = {
            veh_id
            for veh_id in active_agents
            if veh_id not in self._vehicle_id_to_index
        }
        removed_ids = {
            veh_id
            for veh_id in self._vehicle_id_to_index
            if veh_id not in active_agents
        }

        assert (
            new_ids == set()
        ), f"{new_ids} should have been created ahead of time with self.create_vehicle(..)"

        for smarts_id in removed_ids:
            self._destroy_vehicle(smarts_id)

        # We should be synced up
        assert set(active_agents.keys()) == set(self._vehicle_id_to_index.keys())
        assert set(active_agents.keys()) == set(self._vehicle_index_to_id.values())

    def create_vehicle(self, provider_vehicle: VehicleState):
        assert self._is_setup

        vehicle_id = provider_vehicle.vehicle_id
        assert vehicle_id not in self._vehicle_id_to_index
        vehicle_index = self._alloc_index()

        self._vehicle_id_to_index[vehicle_id] = vehicle_index
        self._vehicle_index_to_id[vehicle_index] = vehicle_id

        position, heading = (
            provider_vehicle.pose.position,
            provider_vehicle.pose.heading,
        )
        self._poses = np.append(self._poses, [*position[:2], heading]).reshape(-1, 3)

    def _alloc_index(self) -> int:
        return len(self._poses)

    def _destroy_vehicle(self, vehicle_id):
        vehicle_index = self._vehicle_id_to_index.pop(vehicle_id)
        removed_vehicle_id = self._vehicle_index_to_id.pop(vehicle_index)
        assert removed_vehicle_id == vehicle_id

        # TODO: Currently we leak poses for the duration of the episode.
        #       This is probably fine for now since we tend to have fairly small scale sims.
        #       In the future we would like to have smarter index allocation (re-use destroyed vehicle indices)
        #       or perform periodic garbage collection to remove unused vehicle indices


def main(args=None):
    """Run simulators.
    """
    import argparse
    import logging

    from .instrument import SIMULATORS

    parser = argparse.ArgumentParser(description='Run Lantz simulators.',
                                     add_help=False)

    parser.add_argument('-h', '--help', action='store_true')
    parser.add_argument('simulator',
                        choices=list(SIMULATORS.keys()),
                        nargs='?')
    args, pending = parser.parse_known_args(args)

    if args.simulator is None:
        if args.help:
            parser.print_help()
        else:
            parser.print_usage()
    else:
        if args.help:
            pending += ['--help', ]

        print('Dispatching ' + args.simulator)

        logging.basicConfig(level=logging.DEBUG,
                            format='%(asctime)s %(message)s',
                            datefmt='%Y-%d-%m %H:%M:%S')

        SIMULATORS[args.simulator](pending)

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
import re
import sys

def programa(texto):
    # Implementar programa
    #paso el texto por el programa 1 para borrarle los comentarios
    texto=re.sub(r"( )*\*\*\*(.|\n)*\*\*\*\n",'', texto) #esto anda para varias lineas,  no pudimos usar \s puesto que incluye a \n
    texto=re.sub(r'( )*//(.)*\n', '', texto)

    i = len(re.findall(' si ', texto, flags=0))

    k = len(re.findall(' para cada ', texto, flags=0))

    j = len(re.findall(' para ', texto, flags=0))
    j = j-k #para descontar los "para cada"

    l = len(re.findall(' mientras ', texto, flags=0))

    texto = "si: " + str(i) + "\npara: " + str(j) + "\npara-cada: " + str(k) + "\nmientras: " + str(l)
    return texto

if __name__ == '__main__':
    archivo_entrada = sys.argv[1]
    archivo_salida = sys.argv[2]
    f = open(archivo_entrada, 'r')
    datos = f.read()
    f.close()
    salida = programa(datos)
    f = open(archivo_salida, 'w')
    f.write(salida)
    f.close()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('dnn', '0011_auto_20151231_1318'),
    ]

    operations = [
        migrations.AddField(
            model_name='weight',
            name='name',
            field=models.CharField(default=b'', max_length=200),
        ),
        migrations.AlterField(
            model_name='dataset',
            name='data_type',
            field=models.CharField(default=b'uint8', max_length=200, choices=[(b'uint8', b'integer BYTE'), (b'uint16', b'integer WORD'), (b'uint32', b'integer DWORD')]),
        ),
        migrations.AlterField(
            model_name='dataset',
            name='divide_num',
            field=models.IntegerField(default=256),
        ),
        migrations.AlterField(
            model_name='dataset',
            name='divide_type',
            field=models.CharField(default=b'float32', max_length=200, choices=[(b'float32', b'float DWORD')]),
        ),
    ]


from itertools import combinations
import torch
import numpy as np
from math import log
import scipy.sparse as sp

def make_window(sentences, window_size) :
    # In this case, sentences = train_data[][1]
    windows = []
    for sentence in sentences :
        sentence_length = len(sentence)
        if sentence_length <= window_size :
            windows.append(sentence)
        else :
            for j in range(sentence_length - window_size + 1) :
                window = sentence[j:j+window_size]
                windows.append(window)
    return windows

def count_word(windows, word) :
    count = 0
    for window in windows :
        if word in window :
            count += 1

    return count

def count_word_freq(vocab, windows) :
    word_freq = {}
    for word in vocab :
        if word not in word_freq :
            word_freq[word] = count_word(windows, word)

    return word_freq

def count_pair_freq(windows) :
    pair_freq = dict()
    for i, window in enumerate(windows) :
        combination = list(combinations(window, 2))
        for comb in combination :
            if (comb[0], comb[1]) in pair_freq :
                pair_freq[(comb[0], comb[1])] += 1
            elif (comb[1], comb[0]) in pair_freq :
                pair_freq[(comb[1], comb[0])] += 1
            else :
                pair_freq[(comb[0], comb[1])] = 1
    return pair_freq

def sparse_mx_to_torch_sparse_tensor(sparse_mx):
    """Convert a scipy sparse matrix to a torch sparse tensor."""
    sparse_mx = sparse_mx.tocoo().astype(np.float32)
    indices = torch.from_numpy(
        np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))
    values = torch.from_numpy(sparse_mx.data)
    shape = torch.Size(sparse_mx.shape)
    return torch.sparse.FloatTensor(indices, values, shape)

def accuracy(output, labels):
    preds = output.max(1)[1].type_as(labels)
    correct = preds.eq(labels).double()
    correct = correct.sum()
    return correct / len(labels)

def normalize(mx):
    """Row-normalize sparse matrix"""
    rowsum = np.array(mx.sum(1))
    r_inv = np.power(rowsum, -1).flatten()
    r_inv[np.isinf(r_inv)] = 0.
    r_mat_inv = sp.diags(r_inv)
    mx = r_mat_inv.dot(mx)
    return mx

class Graph_creation(object):

    def __init__(self):
        pass

    def build_vocab(self,sentences):

        # build vocab
        word_freq = {}
        word_set = set()
        for doc_words in sentences:
            words = doc_words.split()
            for word in words:
                word_set.add(word)
                if word in word_freq:
                    word_freq[word] += 1
                else:
                    word_freq[word] = 1

        vocab = list(word_set)
        vocab_size = len(vocab)
        word2int = {j : i for i,j in enumerate(vocab)}

        return {'vocab' : vocab,
                'vocab_size' : vocab_size,
                'word_freq' : word_freq,
                'word_2_int' : word2int}

    def normalize(self,mx):
        """Row-normalize sparse matrix"""
        rowsum = np.array(mx.sum(1))
        r_inv = np.power(rowsum, -1).flatten()
        r_inv[np.isinf(r_inv)] = 0.
        r_mat_inv = sp.diags(r_inv)
        mx = r_mat_inv.dot(mx)
        return mx

    def word_doc_freq(self,sentences):
        word_doc_list = {}
        for i in range(len(sentences)):
            doc_words = sentences[i]
            words = doc_words.split()
            appeared = set()
            for word in words:
                if word in appeared:
                    continue
                if word in word_doc_list:
                    doc_list = word_doc_list[word]
                    doc_list.append(i)
                    word_doc_list[word] = doc_list
                else:
                    word_doc_list[word] = [i]
                appeared.add(word)

        word_doc_freq = {}
        for word, doc_list in word_doc_list.items():
            word_doc_freq[word] = len(doc_list)
        return {'word_doc_list' : word_doc_list, 'word_doc_freq' : word_doc_freq}

    def word_windows(self, sentences, window_size):
        # word co-occurence with context windows
        windows = []

        for doc_words in sentences:
            words = doc_words.split()
            length = len(words)
            if length <= window_size:
                windows.append(words)
            else:
                # print(length, length - window_size + 1)
                for j in range(length - window_size + 1):
                    window = words[j: j + window_size]
                    windows.append(window)
                    # print(window)
        return windows

    def word_window_freq(self, windows):

        word_window_freq = {}
        for window in windows:
            appeared = set()
            for i in range(len(window)):
                if window[i] in appeared:
                    continue
                if window[i] in word_window_freq:
                    word_window_freq[window[i]] += 1
                else:
                    word_window_freq[window[i]] = 1
                appeared.add(window[i])

        return word_window_freq

    # In[ ]:

    def word_pair_count(self, word_window_list, word_id_map):
        word_pair_count = {}
        for window in word_window_list:
            for i in range(1, len(window)):
                for j in range(0, i):
                    word_i = window[i]
                    word_i_id = word_id_map[word_i]
                    word_j = window[j]
                    word_j_id = word_id_map[word_j]

                    if word_i_id == word_j_id:

                        continue
                    word_pair_str = str(word_i_id) + ',' + str(word_j_id)

                    if word_pair_str in word_pair_count:

                        word_pair_count[word_pair_str] += 1
                    else:
                        word_pair_count[word_pair_str] = 1
                    # two orders
                    word_pair_str = str(word_j_id) + ',' + str(word_i_id)
                    if word_pair_str in word_pair_count:
                        word_pair_count[word_pair_str] += 1
                    else:
                        word_pair_count[word_pair_str] = 1

        return word_pair_count

    def word_pair_count_demo(self, word_window_list, word_id_map):
        word_pair_count = {}
        for window in word_window_list:
            for i in range(1, len(window)):
                for j in range(0, i):
                    word_i = window[i]
                    word_i_id = word_id_map[word_i]
                    word_j = window[j]
                    word_j_id = word_id_map[word_j]

                    if word_i_id == word_j_id:

                        continue
                    word_pair_str = str(word_i) + ',' + str(word_j)

                    if word_pair_str in word_pair_count:

                        word_pair_count[word_pair_str] += 1
                    else:
                        word_pair_count[word_pair_str] = 1
                    # two orders
                    word_pair_str = str(word_j) + ',' + str(word_i)
                    if word_pair_str in word_pair_count:
                        word_pair_count[word_pair_str] += 1
                    else:
                        word_pair_count[word_pair_str] = 1

        return word_pair_count

    def calculate_pmi(self, word_windows, word_pair_count,
                      word_window_freq, vocab, train_size):
        row = []
        col = []
        weight = []

        # pmi as weights
        num_window = len(word_windows)

        for key in word_pair_count:
            temp = key.split(',')
            i = int(temp[0])
            j = int(temp[1])

            count = word_pair_count[key]

            word_freq_i = word_window_freq[vocab[i]]
            word_freq_j = word_window_freq[vocab[j]]

            pmi = log((1.0 * count / num_window) /
                      (1.0 * word_freq_i * word_freq_j/(num_window * num_window)))
            if pmi <= 0:
                continue

            row.append(train_size + i)
            col.append(train_size + j)
            weight.append(pmi)

        return {'row' : row, 'col' : col, 'weight' : weight }

    def heterogeneous_graph(self, sentences, word_id_map,
                            train_size, pmi,
                            vocab, test_size,word_doc_freq):

        vocab_size = len(vocab)
        row = pmi['row']
        col = pmi['col']
        weight = pmi['weight']

        # doc word frequency
        doc_word_freq = {}

        for doc_id in range(len(sentences)):
            doc_words = sentences[doc_id]
            words = doc_words.split()
            for word in words:
                word_id = word_id_map[word]
                doc_word_str = str(doc_id) + ',' + str(word_id)
                if doc_word_str in doc_word_freq:
                    doc_word_freq[doc_word_str] += 1
                else:
                    doc_word_freq[doc_word_str] = 1

        for i in range(len(sentences)):
            doc_words = sentences[i]
            words = doc_words.split()
            doc_word_set = set()
            for word in words:
                if word in doc_word_set:
                    continue
                j = word_id_map[word]
                key = str(i) + ',' + str(j)
                freq = doc_word_freq[key]
                if i < train_size:
                    row.append(i)
                else:
                    row.append(i + vocab_size)
                col.append(train_size + j)
                idf = log(1.0 * len(sentences) /
                          word_doc_freq[vocab[j]])
                weight.append(freq * idf)
                doc_word_set.add(word)

        node_size = train_size + vocab_size + test_size
        adj = sp.csr_matrix(
        (weight, (row, col)), shape=(node_size, node_size))
        adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)
        adj = normalize(adj + sp.eye(node_size))

        return adj


import os,sys,re, string, random
from pprint import pprint
import json

from autoprotocol import *
from autoprotocol.protocol import Protocol

#### custom protocol ####

def ul(microliters):
    """Unicode function name for creating microliter volumes"""
    return Unit(microliters,"microliter")

class CustomProtocol(Protocol):

    def __init__(self):
        #catalog inventory
        self.inv = {
            "water"       : "rs17gmh5wafm5p", # catalog; Autoclaved MilliQ H2O; ambient
            "DH5a"        : "rs16pbj944fnny", # catalog; Zymo DH5a; cold_80
            "Gibson Mix"  : "rs16pfatkggmk5", # catalog; Gibson Mix (2X); cold_20
            'NEBuilder_Master_Mix': 'rs18pc86ykcep6', # catalog; NEBuilder MasterMix
            "LB Miller"   : "rs17bafcbmyrmh", # catalog; LB Broth Miller; cold_4
            "Amp 100mgml" : "rs17msfk8ujkca", # catalog; Ampicillin 100mg/ml; cold_20
            "pUC19"       : "rs17tcqmncjfsh", # catalog; pUC19; cold_20
            "IPTG"          : "rs18vwgfgxq597", # catalog: 100mM
            "M13_F"                       : "rs17tcpqwqcaxe", # catalog; M13 Forward (-41); cold_20 (1ul = 100pmol)
            "M13_R"                       : "rs17tcph6e2qzh", # catalog; M13 Reverse (-48); cold_20 (1ul = 100pmol)
            "SensiFAST_SYBR_No-ROX"       : "rs17knkh7526ha", # catalog; SensiFAST SYBR for qPCR
            # kits (must be used differently)
            "lb-broth-100ug-ml-amp_6-flat" : "ki17sbb845ssx9", # catalog; ampicillin plates
            "noAB-amp_6-flat" : "ki17reefwqq3sq" # catalog; no antibiotic plates
        }

        super(CustomProtocol,self).__init__()

    def ref(self, name, id=None, cont_type=None, storage=None, discard=None):
        if discard:
            storage=None

        return super(CustomProtocol,self).ref(name, id=id, cont_type=cont_type,
                                              storage=storage, discard=discard)

    def transfer(self, source, dest, volume, one_source=False, one_tip=False,
                aspirate_speed=None, dispense_speed=None,
                aspirate_source=None, dispense_target=None,
                pre_buffer=None, disposal_vol=None,
                transit_vol=None, blowout_buffer=None,
                tip_type=None, new_group=False, **mix_kwargs):

        if type(volume) == list:
            min_volume = min(volume)
        else:
            min_volume = volume

        if min_volume < ul(10) and not mix_kwargs.get('mix_after') \
           and not mix_kwargs.get('ignore_mix_after_warning'):
            raise Exception('mix_after required for <10uL of solution to ensure complete transfer. \n'
                            'Ensure you have are pipetting into something big enough and set this')

        if 'ignore_mix_after_warning' in mix_kwargs:
            del mix_kwargs['ignore_mix_after_warning']

        super().transfer(source, dest, volume, one_source=one_source, one_tip=one_tip,
              aspirate_speed=aspirate_speed, dispense_speed=dispense_speed,
              aspirate_source=aspirate_source, dispense_target=dispense_target,
              pre_buffer=pre_buffer, disposal_vol=disposal_vol,
              transit_vol=transit_vol, blowout_buffer=blowout_buffer,
              tip_type=tip_type, new_group=new_group,**mix_kwargs)

    def distribute(self, source, dest, volume, allow_carryover=False,
                   mix_before=False, mix_after=False, mix_vol=None, repetitions=10,
                   flowrate="100:microliter/second", aspirate_speed=None,
                   aspirate_source=None, distribute_target=None,
                   pre_buffer=None, disposal_vol=None, transit_vol=None,
                   blowout_buffer=None, tip_type=None, new_group=False,
                   ignore_mix_after_warning=False):

        if volume < ul(10):
            for dest_well in dest:
                self.transfer(source,dest_well,volume,mix_before=mix_before,
                              mix_after=mix_after,mix_vol=mix_vol,
                              aspirate_speed=aspirate_speed,
                              aspirate_source=aspirate_source,
                              pre_buffer=pre_buffer, disposal_vol=disposal_vol,
                              transit_vol=transit_vol, blowout_buffer=blowout_buffer,
                              tip_type=tip_type, new_group=new_group,
                              ignore_mix_after_warning=ignore_mix_after_warning)
        else:
            super().distribute(source, dest, volume, allow_carryover=allow_carryover,
                               mix_before=mix_before, mix_vol=mix_vol, repetitions=repetitions,
                               flowrate=flowrate, aspirate_speed=aspirate_speed,
                               aspirate_source=aspirate_source, distribute_target=distribute_target,
                               pre_buffer=pre_buffer, disposal_vol=disposal_vol, transit_vol=transit_vol,
                               blowout_buffer=blowout_buffer, tip_type=tip_type, new_group=new_group)

#### conversion tables ####

#brick to transcriptic

b2t = { 'ecoli':'rs16pbj944fnny',
        "water"       : "rs17gmh5wafm5p", # catalog; Autoclaved MilliQ H2O; ambient
        "DH5a"        : "rs16pbj944fnny", # catalog; Zymo DH5a; cold_80
        "Gibson Mix"  : "rs16pfatkggmk5", # catalog; Gibson Mix (2X); cold_20
        'NEBuilder_Master_Mix': 'rs18pc86ykcep6', # catalog; NEBuilder MasterMix
        "LB Miller"   : "rs17bafcbmyrmh", # catalog; LB Broth Miller; cold_4
        "Amp 100mgml" : "rs17msfk8ujkca", # catalog; Ampicillin 100mg/ml; cold_20
        "pUC19"       : "rs17tcqmncjfsh", # catalog; pUC19; cold_20
        "IPTG"          : "rs18vwgfgxq597", # catalog: 100mM
        "M13_F"                       : "rs17tcpqwqcaxe", # catalog; M13 Forward (-41); cold_20 (1ul = 100pmol)
        "M13_R"                       : "rs17tcph6e2qzh", # catalog; M13 Reverse (-48); cold_20 (1ul = 100pmol)
        "SensiFAST_SYBR_No-ROX"       : "rs17knkh7526ha", # catalog; SensiFAST SYBR for qPCR
        # kits (must be used differently)
        "lb-broth-100ug-ml-amp_6-flat" : "ki17sbb845ssx9", # catalog; ampicillin plates
        "noAB-amp_6-flat" : "ki17reefwqq3sq", # catalog; no antibiotic plates
        "EcoRI":    "rs17ta8xftpdk6",   # catalog; EcoRI-HF; cold_20; 20 units/ul
        "hindiii":    "rs18nw6kpnp44v",   # catalog; hindiii-HF; cold_20; 20 units/ul
        "CutSmart": "rs17ta93g3y85t",   # catalog; CutSmart Buffer 10x; cold_20
        #"pUC19":    "rs17tcqmncjfsh",   # catalog; pUC19; cold_20
        'reagent_plate': '', #optional: only needed after the first run
        'NEBuilder_Master_Mix': 'rs18pc86ykcep6' # catalog; NEBuilder MasterMix
}

#### workflow switcher ####

#def workflowSwitch(n):

#### workflows ####

def dispense(protocol, species):
    plate=protocol.ref("growth_plate", id=None, cont_type="96-flat", storage="cold_4", discard=None)
    tube=protocol.ref("bacteria_tube", id=None, cont_type="micro-1.5", storage=None, discard=True)
    #species 2 tube
    s2t=protocol.provision(species, tube.well(0), "15:microliter")
    #medium 2 plate
    m2p=protocol.dispense(plate, "lb-broth-noAB", [{"column": 0, "volume": "175:microliter"}])
    return (plate,tube,s2t, m2p)

def gibsonAssembly(p, plasmid):

    def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
        return ''.join(random.choice(chars) for _ in range(size))

    experiment_name = id_generator()

    def ul(microliters):
        """Unicode function name for creating microliter volumes"""
        return Unit(microliters,"microliter")

    def expid(val,expt_name=experiment_name):
        """Generate a unique ID per experiment"""
        global experiment_name
        if not expt_name:
            assert experiment_name, "Must set experiment name"
            expt_name = experiment_name
        return "{}_{}".format(expt_name, val)

    plate_name = 're_reagents'
    number_of_experiments = 6

    ### step.1. provision ###

    dead_volume = ul(3)
    reagent_plate = p.ref(plate_name, cont_type="96-pcr", storage="cold_20")
    ecori_hindiii_well = reagent_plate.wells(["A1"])[0]

    #provisioning less than 10uL is dangerous due to pipetting mistakes (can't mix after)
    volume_per_experiment = ul(1)
    re_volume = max(ul(10),number_of_experiments*volume_per_experiment+dead_volume/2)
    p.provision(b2t["EcoRI"], ecori_hindiii_well, re_volume)
    p.provision(b2t["hindiii"], ecori_hindiii_well, re_volume)
    ecori_hindiii_well.name = 'EcoRI+hindiii'
    ecori_hindiii_well.properties = {'Unit Concentration':'10 units/ul'}

    #there is an extra negative control for every 2 experiments so we use 3/2*experiments
    cutsmart_well = reagent_plate.wells(["B1"])[0]
    volume_per_experiment = ul(5)
    p.provision(b2t["CutSmart"], cutsmart_well, number_of_experiments*3/2*volume_per_experiment+dead_volume)
    cutsmart_well.name = 'CutSmart 10x'

    pUC19_well = reagent_plate.wells(["H12"])[0]
    volume_per_experiment = ul(1)
    pUC19_volume = max(ul(10),number_of_experiments*volume_per_experiment+dead_volume)
    p.provision(plasmid, pUC19_well, pUC19_volume)
    pUC19_well.name = 'pUC19'
    pUC19_well.properties = {'Mass Concentration':'1 ug/ul'}

    ### step 02 linearize plasmid ###

    # Tubes and plates we use and then discard

    water_tube = p.ref("water_tube", cont_type="micro-1.5", discard=True).well(0)
    pcr_plate  = p.ref("pcr_plate",  cont_type="96-pcr", discard=True)

    # The result of the experiment, a pUC19 cut by EcoRI and HindIII, goes in this tube for storage
    puc19_cut_tube  = p.ref(expid("puc19_cut",experiment_name), cont_type="micro-1.5", storage="cold_20").well(0)

    # -------------------------------------------------------------
    # Provisioning and diluting.
    # Diluted EcoRI can be used more than once
    #
    p.provision(b2t["water"], water_tube, ul(500))

    # -------------------------------------------------------------
    # Restriction enzyme cutting pUC19
    # 3 experiments (1 without re)
    # 50ul total reaction volume for cutting 1ug of DNA:
    # 42uL water
    # 5ul CutSmart 10x
    # 1ul pUC19 1ml/ml or 1ug/ul (1ug of DNA)
    # 2ul EcoRI+hindiii (20 units each, >10 units per ug DNA)

    p.distribute(water_tube, pcr_plate.wells(["A1","B1","A2"]), ul(42))
    p.distribute(pUC19_well, pcr_plate.wells(["A1","B1","A2"]), ul(1),
                 mix_before=True, mix_after=True, mix_vol=ul(5))
    p.distribute(cutsmart_well, pcr_plate.wells(["A1","B1","A2"]), ul(5),
             mix_before=True, mix_after=True, mix_vol=ul(10))
    p.distribute(water_tube, pcr_plate.wells(["A2"]), ul(2),ignore_mix_after_warning=True)
    p.distribute(ecori_hindiii_well, pcr_plate.wells(["A1","B1"]), ul(2),
             mix_before=True, mix_after=True, mix_vol=ul(5))
    assert all(well.volume == ul(50) for well in pcr_plate.wells(["A1","B1","A2"]))

    p.mix(pcr_plate.wells(["A1","B1","A2"]), volume=ul(25), repetitions=10)

    # Incubation to induce cut, then heat inactivation of EcoRI+hindiii
    p.seal(pcr_plate)
    #NEB enzymes are time saver so they only need 15minutes
    p.incubate(pcr_plate, "warm_37", "15:minute", shaking=False)
    #inactivate RE's (see this site for thermal temps)
    #https://www.neb.com/tools-and-resources/usage-guidelines/heat-inactivation
    p.thermocycle(pcr_plate, [{"cycles":  1, "steps": [{"temperature": "80:celsius", "duration": "20:minute"}]}], volume=ul(50))

    # --------------------------------------------------------------
    # Gel electrophoresis, to ensure the cutting worked
    #
    p.unseal(pcr_plate)
    p.mix(pcr_plate.wells(["A1","B1","A2"]), volume=ul(25), repetitions=5)
    p.transfer(water_tube, pcr_plate.wells(["D1","E1","D2"]), ul(15))
    p.transfer(pcr_plate.wells(["A1","B1","A2"]), pcr_plate.wells(["D1","E1","D2"]), ul(8), mix_after=True, mix_vol=ul(10))
    assert all(well.volume == ul(20) + dead_volume for well in pcr_plate.wells(["D1","E1","D2"]))

    p.gel_separate(pcr_plate.wells(["D1","E1","D2"]), ul(20), "agarose(10,2%)", "ladder2", "15:minute", expid("gel",experiment_name))
    remaining_volumes = [well.volume - dead_volume for well in pcr_plate.wells(["A1","B1"])]
    # Then consolidate all cut plasmid to one tube (puc19_cut_tube).
    p.consolidate(pcr_plate.wells(["A1","B1"]), puc19_cut_tube, remaining_volumes, allow_carryover=True)

    #verify that we haven't gone below what can actually be pulled from tubes
    #assert_valid_volume([water_tube, ecori_hindiii_well, cutsmart_well, pUC19_well])

    ### step 03 full Gibson assembly and transformation protocol for sfGFP and pUC19 ###

    sfgfp_pcroe_amp_tube = p.ref("pfragment", cont_type="micro-1.5", storage="cold_20").well(0)
    clone_plate = p.ref(expid("clone"), cont_type="96-pcr", storage="cold_20")
    water_tube = p.ref("water", cont_type="micro-1.5", discard=True).well(0)

    ### 03.01 do transformate ###

    #
    # Combine all the Gibson reagents in one tube and thermocycle
    #

    p.provision(p.inv["NEBuilder_Master_Mix"], clone_plate.well(0), ul(10))
    p.transfer(water_tube, clone_plate.well(0), ul(3.5), mix_after=True, mix_vol=ul(6))
    p.transfer(puc19_cut_tube, clone_plate.well(0), ul(2.5), mix_after=True, mix_vol=ul(6))
    p.transfer(sfgfp_pcroe_amp_tube, clone_plate.well(0), ul(4), mix_after=True, mix_vol=ul(10))

    p.seal(clone_plate)
    p.thermocycle(clone_plate, [{"cycles":  1, "steps": [{"temperature": "50:celsius", "duration": "15:minute"}]}], \
                                                     volume=ul(20))
    #
    # Dilute assembled plasmid 4X according to the NEB Gibson assembly protocol (20ul->80ul)
    #
    p.unseal(clone_plate)
    p.transfer(water_tube, clone_plate.well(0), ul(60), mix_after=True, mix_vol=ul(40), repetitions=5)

data = json.load(sys.stdin)
data.sort(key=lambda x:x['id'])

(species, method) = (None,None)
p = CustomProtocol()

for item in data:
    if item['elementtype'] == 'organism' or item['elementtype'] == 'plasmid':
        brick = item['name']
        # lookup catalog for tsc reference
        if brick in b2t.keys():
            brick = b2t[brick]
    elif item['elementtype'] == 'bioprotocol':
        method = item['name']
    else:
        sys.exit(0)

    #trigger if brick and method
    if brick and method:
        exec("%s(%s,\"%s\")" % (method,"p",brick))
        #print("%s(%s,\"%s\")" % (method,"p",brick))
# Dump autoprotocol2JSON.
p2ap = json.dumps(p.as_dict(), indent=2)
print(p2ap)


import numpy as np
import matplotlib.pyplot as plt
print ("Enter Your Attendence in each subject seperated by a space")
Atten=input().split() # Attendence Array
Nt_Deb=[]             # Array of Debarred Subjects
Deb=[]                # Position of Debarred Subjects
X_Nt_Deb=[]           # Array of Not Debarred Subjects
X_Deb=[]              # Position of Not Debarred Subjects
for i in range(len(Atten)):
    Atten[i]=int(Atten[i])
    assert 0<=Atten[i]<=100
    if Atten[i]>=75:
        Nt_Deb.append(Atten[i])
        X_Nt_Deb.append(i)
    else:
        Deb.append(Atten[i])
        X_Deb.append(i)

plt.axis([0,len(Atten)+1,0,100])
H=["A","B","C"]
plt.bar(X_Nt_Deb,Nt_Deb,color='b',align='edge')
plt.bar(X_Deb,Deb,color='r',align='edge')
plt.show()


import requests
import json

registration_ids = "dZsqmpRIs0GCnSU1IXMlW8:APA91bHXtGJQW8AGSSAtdz0BOX12-xa6N1g-l-Ws7zZofr15YyDop_b16ix8A4XYhUTXbA9-Nb6IsitWLQHeITw1k7O0C5VzeVMFTOI0ybdt0ottH2MIWpAaW8JnqbthsKLxKY_xK13h"
message_title = "Hello You got"
message_desc = "Hello Testing"

def send_notification(registration_ids , message_title , message_desc , action , info_data):
    #fcm_api = "AAAAjG_ontY:APA91bG_pu05vhQm2IE4gGjOFjAC1mFtzZF0j_zsI_JQWl58u9LsLHnoEpjrLV5cIMNBPsVkFbf52zerKkhCc1Kj8wOEosMCKOtTG1_vE4Ji_pez9kKdxeA-9MLfItcnTrYWeN9grRw0"
    try:
        url = "https://fcm.googleapis.com/fcm/send"

        headers = {
            "Content-Type": "application/json",
            "Authorization": 'key=AAAAyREJETk:APA91bF_A0HV93gPZg2dw07h08E95i9rhZ9HZs6LhcGS46O2PU6pj7J8ao7uWn39iaHWLflJTBfXWX7fKavcA-0DlffGdw38mCzB_HjB3lMgmX0anlDdIJg7-FTf4nH4GD58KsqVPlPy',
        }

        payload = {
            "registration_ids" :registration_ids,
            "priority" : "high",
            "notification" : {
                "body" : message_desc,
                "title" : message_title,
                "image" : "https://shebirth.com/wp-content/uploads/2023/03/Untitled-design-30-1024x768.png",
                "icon": "https://shebirth.com/wp-content/uploads/2021/10/Shebirth-Final-Logo-new.png",
                "click_action" : action
            },
            "data" : info_data
        }

        print(payload)

        result = requests.post(url,  data=json.dumps(payload), headers=headers )
        print(result.text)

    except Exception as e:
        print(e)
        import sys, os
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print(exc_type, fname, exc_tb.tb_lineno)

#send_notification(registration_ids , message_title , message_desc ,action="criticality")


import os
from libqtile.config import Click, Drag, KeyChord, Key
from libqtile.command import lazy
from libqtile.lazy import lazy

mod = "mod4"
mod1 = "mod1"
mod2 = "control"
mod3  = "shift"
home = os.path.expanduser('~')
Term2 = "alacritty"
myTerm = "kitty"

# if qtile.core.name=='x11':
#     launcher="dmenu_run -i -h 25 -p 'RUN:'"
# elif qtile.core.name=='wayland':
    # launcher="bemenu-run -i -H 30 --fn 'Space mono for powerline 11' --nb '#2e3440' --nf '#ffffff' --hb '#aaeedd' --hf '#000000' --sb '#aaeedd' --sf '#000000' -p 'RUN:' --tb '#aaeedd' --tf '#000000' --fb '#000000' --ff '#aaeedd'"

# a=subprocess.Popen('echo $HOME', shell=True, stdout=subprocess.PIPE)
# user=a.communicate()[0].decode().strip()

@lazy.function
def window_to_prev_group(qtile):
    if qtile.currentWindow is not None:
        i = qtile.groups.index(qtile.currentGroup)
        qtile.currentWindow.togroup(qtile.groups[i - 1].name)

@lazy.function
def window_to_next_group(qtile):
    if qtile.currentWindow is not None:
        i = qtile.groups.index(qtile.currentGroup)
        qtile.currentWindow.togroup(qtile.groups[i + 1].name)

#############################################
############ SHORTCUTS ######################
#############################################

keys = [
    Key([], "F4", lazy.spawn("launcher")),
    Key([mod], "d", lazy.spawn("dmenu_run -i -h 25 -p 'RUN'")),

##################################################
################# MEDIA CONTROLS #################
##################################################

# INCREASE/DECREASE/MUTE VOLUME
    # Key([], "XF86AudioMute", lazy.spawn("amixer -q set Master toggle")),
    # Key([], "XF86AudioLowerVolume", lazy.spawn("amixer -q set Master 5%-")),
    # Key([], "XF86AudioRaiseVolume", lazy.spawn("amixer -q set Master 5%+")),

    Key([], "XF86AudioMute", lazy.spawn("pamixer -t")),
    Key([], "XF86AudioMicMute", lazy.spawn("mictoggle")),
    Key([], "XF86AudioLowerVolume", lazy.spawn("pamixer -d 5")),
    Key([], "XF86AudioRaiseVolume", lazy.spawn("pamixer -i 5")),

    Key([], "XF86AudioPlay", lazy.spawn("playerctl play-pause")),
    Key([], "XF86AudioNext", lazy.spawn("playerctl next")),
    Key([], "XF86AudioPrev", lazy.spawn("playerctl previous")),
    Key([], "XF86AudioStop", lazy.spawn("playerctl stop")),
    # Key([], "XF86MonBrightnessUp", lazy.spawn("light -A 5")),
    # Key([], "XF86MonBrightnessDown", lazy.spawn("light -U 5")),
    Key([], "XF86MonBrightnessUp", lazy.spawn("xbacklight -inc 5")),
    Key([], "XF86MonBrightnessDown", lazy.spawn("xbacklight -dec 5")),

    # Switch between windows in current stack pane
###################################################
################  SWITCH LAYOUT ###################
###################################################

# TOGGLE FLOATING LAYOUT
    Key([mod, "control"], "a", lazy.window.toggle_floating()),

    # CHANGE FOCUS
    Key([mod], "Up", lazy.layout.up()),
    Key([mod], "Down", lazy.layout.down()),
    Key([mod], "Left", lazy.layout.left()),
    Key([mod], "Right", lazy.layout.right()),
    Key([mod], "k", lazy.layout.up()),
    Key([mod], "j", lazy.layout.down()),
    Key([mod], "period",lazy.layout.grow(), lazy.layout.increase_nmaster()),
    Key([mod], "comma", lazy.layout.shrink(), lazy.layout.decrease_nmaster()),
    Key([mod], "n", lazy.layout.normalize()),
    Key([mod], "w", lazy.window.toggle_fullscreen()),
    Key([mod], "h", lazy.layout.decrease_ratio()),
    Key([mod], "l", lazy.layout.increase_ratio()),

# FLIP LAYOUT FOR MONADTALL/MONADWIDE
    Key([mod, "shift"], "f", lazy.layout.flip()),

# MOVE WINDOWS UP OR DOWN MONADTALL/MONADWIDE LAYOUT
    Key([mod, "shift"], "Up", lazy.layout.shuffle_up()),
    Key([mod, "shift"], "k", lazy.layout.shuffle_up()),
    Key([mod, "shift"], "j", lazy.layout.shuffle_down()),
    Key([mod, "shift"], "Down", lazy.layout.shuffle_down()),
    Key([mod, "shift"], "Left", lazy.layout.swap_left()),
    Key([mod, "shift"], "Right", lazy.layout.swap_right()),
    Key([mod], "s", lazy.layout.next()),

#########################################
############### BSPWM ###################
#########################################
    Key([mod], "Down", lazy.layout.down()),
    Key([mod], "Up", lazy.layout.up()),
    Key([mod], "Left", lazy.layout.left()),
    Key([mod], "Right", lazy.layout.right()),
    Key([mod, "shift"], "Down", lazy.layout.shuffle_down()),
    Key([mod, "shift"], "Up", lazy.layout.shuffle_up()),
    Key([mod, "shift"], "Left", lazy.layout.shuffle_left()),
    Key([mod, "shift"], "Right", lazy.layout.shuffle_right()),
    Key([mod, "mod1"], "Down", lazy.layout.flip_down()),
    Key([mod, "mod1"], "Up", lazy.layout.flip_up()),
    Key([mod, "mod1"], "Left", lazy.layout.flip_left()),
    Key([mod, "mod1"], "Right", lazy.layout.flip_right()),
    Key([mod, "control"], "Down", lazy.layout.grow_down()),
    Key([mod, "control"], "Up", lazy.layout.grow_up()),
    Key([mod, "shift"], "l", lazy.layout.grow_left()),
    Key([mod, "shift"], "m", lazy.layout.grow_right()),
    Key([mod, "shift"], "n", lazy.layout.normalize()),
    # Key([mod], "z", lazy.layout.toggle_split()),
    Key([mod], "z", lazy.spawn("killall zoom")),

    Key([mod], "b", lazy.hide_show_bar()),
    Key([mod], "Tab", lazy.next_layout()),
    Key([mod], "a", lazy.prev_layout()),
    Key([mod], "q", lazy.window.kill()),
    Key([mod, "shift"], "q", lazy.shutdown()),
    Key([mod], "c", lazy.restart()),
    Key([mod], "r", lazy.spawncmd()),
    Key([mod, "shift"], "x", lazy.spawn("poweroff")),
##############################################
############## SCREENSHOTS ###################
##############################################

    Key(["shift"], "Print", lazy.spawn("clip")),
    Key(["control"], "Print", lazy.spawn("vmcrop")),
    Key([mod], "Print", lazy.spawn("crop")),
    Key([], "Print", lazy.spawn("shot")),

#####################3#########################
############## APPLICATIONS ###################
###############################################

    Key([mod], "space", lazy.spawn(Term2)),
    Key([mod, "shift"], "a", lazy.spawn("i3lock -c 000000")),
    Key([mod], "KP_Subtract", lazy.spawn("i3lock -c 00000000")),
    Key([mod], "KP_Add", lazy.spawn("lock")),
    Key([mod], "Return", lazy.spawn(myTerm)),
    Key([mod], "KP_Enter", lazy.spawn(myTerm)),
    Key([mod], "z", lazy.spawn(myTerm+" -e fish")),
    Key([mod], "v", lazy.spawn("pavucontrol")),
    Key([], "F9", lazy.spawn("pavucontrol")),
    Key([mod, "shift"], 'd', lazy.spawn('dunstop')),

    KeyChord([mod], "i",[
        Key([], "f", lazy.spawn("firefox-bin")),
        Key([], "v", lazy.spawn("vivaldi-stable")),
        Key([], "b", lazy.spawn("brave-bin")),
        Key([], "l", lazy.spawn("librewolf")),
    ]),
### EDITORS
    KeyChord([mod], "e",[
        Key([], "e", lazy.spawn("emacs")),
        Key([], "v", lazy.spawn("vscodium")),
        Key([], "k", lazy.spawn("kitty -e nvim")),
    ]),
### XSS-LOCK
    KeyChord([mod], "t",[
        Key([], "x", lazy.spawn("killall xss-lock")),
        Key([], "r", lazy.spawn("xss-lock --transfer-sleep-lock -- i3lock -c 00000000 --nofork")),
            ]),
### DMSCRIPTS
    KeyChord([mod], "x",[
        Key([], "c", lazy.spawn("bash /home/karttikeya/dmscripts/dmconf")),
        Key([], "x", lazy.spawn("powermenu")),
        Key([], "p", lazy.spawn("bash /home/karttikeya/dmscripts/dmpy")),
        Key([], "f", lazy.spawn("bash /home/karttikeya/dmscripts/dmfeh")),
            ]),

### REDSHIFT
    KeyChord([mod], "r",[
        Key([], "1", lazy.spawn("redshift -O 6000")),
        Key([], "2", lazy.spawn("redshift -O 5000")),
        Key([], "3", lazy.spawn("redshift -O 4500")),
        Key([], "4", lazy.spawn("redshift -O 4250")),
        Key([], "5", lazy.spawn("redshift -O 4000")),
        Key([], "6", lazy.spawn("redshift -O 3500")),
        Key([], "x", lazy.spawn("redshift -x")),
            ]),
    ]

mouse = [
    Drag([mod], "Button1", lazy.window.set_position_floating(),
         start=lazy.window.get_position()),
    Drag([mod], "Button3", lazy.window.set_size_floating(),
         start=lazy.window.get_size()),
    Click([mod], "Button2", lazy.window.bring_to_front())
]


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
NOTE: __all__ affects the from <module> import * behavior only. Members that are not mentioned in __all__ are still accessible from outside the module and can be imported with from <module> import <member>.

__all__ = ["DATA_FILE",
            "EMAIL",
            "ERROR_HANDLE",
            "VERSION_CONTROL"]
"""

"""
import VERSION_CONTROL
import IMAGES
import EMAIL
"""
#print ("Primary EnneadTab Module")

import os
for module in os.listdir(os.path.dirname(__file__)):
    #print (module)
    if module == '__init__.py':
        continue
    if module in ["RHINO", "REVIT", "EXE", "FUN"]:
        __import__(module, locals(), globals())
        continue
    if module[-3:] != '.py':
        continue
    try:
        __import__(module[:-3], locals(), globals())
    except Exception as e:
        print (e)
        print ("Cannot import {}".format(module))
del module# delete this varible becaue it is refering to last item on the for loop


import sys
sys.stdin = open('sample_input.txt', 'r')

def DFS(idx):
    global sum, min
    # 최소값 구하기
    if idx == N:
        if sum < min:
            min = sum
        return
    # 가지치기
    if sum > min:
        return

    for j in range(0, N):
        if visited[j] == 0: # 접근한 적이 없다면
            sum += arr[idx][j]

            visited[j] = 1 # 접근한 것으로 바꾸기

            DFS(idx+1)

            visited[j] = 0 # 초기화
            sum -= arr[idx][j] # 최소값이 아닐 경우 더했던 값을 빼면서 합 초기화

T = int(input())

for tc in range(1, T+1):
    N = int(input())
    arr = [list(map(int, input().split())) for _ in range(N)]

    visited = [0] * N # 행의 중복을 막기 위함

    sum = 0
    min = 999999 # 최소값을 큰 값으로 설정해 비교

    DFS(0)

    print('#{} {}'.format(tc, min))


import io

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from flask import request, render_template, make_response, send_from_directory, send_file
from flask_restful import Resource
from marshmallow import INCLUDE

from libs.strings import gettext
from models.studentmodel import StudentModel
from schemas.student import StudentSchema

student_schema = StudentSchema(unknown=INCLUDE)

class Verification(Resource):

    @classmethod
    def post(cls):
        doc_id = request.form['doc_id']

        with open("publickey.cer", "rb") as key_file:
            public_key = serialization.load_pem_public_key(
                key_file.read(),
                backend=default_backend()
            )

        try:
            signature = open(f"signatures/signature-{doc_id}.txt", "rb").read()
            document = open(f'files/{doc_id}-file.pdf', 'rb').read()
        except FileNotFoundError:
            return {'message': 'doc not found'}, 404

        try:
            public_key.verify(
                signature,
                document,
                padding.PSS(
                    mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH
                ),
                hashes.SHA256()
            )

            student = StudentModel.find_by_docid(doc_id)
            if not student:
                return {'message': gettext("user_not_found")}, 404

            return student_schema.dump(student), 200
        except InvalidSignature:
            return {'message': 'invalid'}, 401

class StudentImage(Resource):

    @classmethod
    def get(cls, doc_id):
        filename = f'{doc_id}.png'
        return send_file(
            io.BytesIO(open(f'images/{filename}', 'rb').read()),
            attachment_filename=filename,
            mimetype='image/png'
        )


from django.urls import path
from .views import Favmanager,Favdisp,Account,Deletefav,Community,addfollowers,Recipe_submission,Shop
urlpatterns = [
    path('favoratie/',Favmanager,name='favoratie'),
    path('favdisp/',Favdisp,name='Fav'),
    path('account/',Account,name='Acc'),
    path('favoratie/del',Deletefav,name='Favdel'),
    path('community/',Community,name='community'),
    path('add_followers',addfollowers,name='add_followers'),
    path('submit/',Recipe_submission,name='Submit'),
    path('shop/',Shop,name='Shop'),
]


import numpy as np
import seaborn as sns
import pandas as pd
import pickle
from matplotlib import pyplot as plt
import matplotlib
import re
from mlxtend.plotting import plot_confusion_matrix
import scikitplot as skplt
from sklearn.metrics import classification_report, accuracy_score, confusion_matrix, roc_curve, auc, \
                            silhouette_score, recall_score, precision_score, make_scorer, \
                            roc_auc_score, f1_score, precision_recall_curve, fbeta_score, ConfusionMatrixDisplay

def dame_variables_categoricas(dataset=None):
    '''
    ----------------------------------------------------------------------------------------------------------
    Función dame_variables_categoricas:
    ----------------------------------------------------------------------------------------------------------
        -Descripción: Función que recibe un dataset y devuelve una lista con los nombres de las
        variables categóricas
        -Inputs:
            -- dataset: Pandas dataframe que contiene los datos
        -Return:
            -- lista_variables_categoricas: lista con los nombres de las variables categóricas del
            dataset de entrada con menos de 100 valores diferentes
            -- 1: la ejecución es incorrecta
    '''
    if dataset is None:
        print(u'\nFaltan argumentos por pasar a la función')
        return 1
    lista_variables_categoricas = []
    other = []
    for i in dataset.columns:
        if (dataset[i].dtype!=float) & (dataset[i].dtype!=int):
            unicos = int(len(np.unique(dataset[i].dropna(axis=0, how='all'))))
            if unicos < 9:
                lista_variables_categoricas.append(i)
            else:
                other.append(i)

    return lista_variables_categoricas, other

def get_deviation_of_mean_perc(pd_fraud, list_var_continuous, target, multiplier):
    """
    Devuelve el porcentaje de valores que exceden del intervalo de confianza
    :type series:
    :param multiplier:
    :return:
    """
    pd_final = pd.DataFrame()

    for i in list_var_continuous:

        series_mean = pd_fraud[i].mean()
        series_std = pd_fraud[i].std()
        std_amp = multiplier * series_std
        left = series_mean - std_amp
        right = series_mean + std_amp
        size_s = pd_fraud[i].size

        perc_goods = pd_fraud[i][(pd_fraud[i] >= left) & (pd_fraud[i] <= right)].size/size_s
        perc_excess = pd_fraud[i][(pd_fraud[i] < left) | (pd_fraud[i] > right)].size/size_s

        if perc_excess>0:
            pd_concat_percent = pd.DataFrame(pd_fraud[target][(pd_fraud[i] < left) | (pd_fraud[i] > right)]\
                                            .value_counts(normalize=True).reset_index()).T
            pd_concat_percent.columns = [pd_concat_percent.iloc[0,0],
                                         pd_concat_percent.iloc[0,1]]
            pd_concat_percent = pd_concat_percent.drop('index',axis=0)
            pd_concat_percent['variable'] = i
            pd_concat_percent['sum_outlier_values'] = pd_fraud[i][(pd_fraud[i] < left) | (pd_fraud[i] > right)].size
            pd_concat_percent['porcentaje_sum_null_values'] = perc_excess
            pd_final = pd.concat([pd_final, pd_concat_percent], axis=0).reset_index(drop=True)

    if pd_final.empty:
        print('No existen variables con valores nulos')

    return pd_final

def histogram(pd_fraud, col_name):
    sns.histplot(pd_fraud.loc[pd_fraud[col_name].notnull(), col_name], kde=False)

def box_plot(pd_fraud, col_name):
    sns.boxplot(x=col_name, y='isFraud', data=pd_fraud)

def get_corr_matrix(dataset = None, metodo='pearson', size_figure=[10,8]):
    # Para obtener la correlación de Spearman, sólo cambiar el metodo por 'spearman'

    if dataset is None:
        print(u'\nHace falta pasar argumentos a la función')
        return 1
    sns.set(style="white")
    # Compute the correlation matrix
    corr = dataset.corr(method=metodo)
    # Set self-correlation to zero to avoid distraction
    for i in range(corr.shape[0]):
        corr.iloc[i, i] = 0
    # Set up the matplotlib figure
    f, ax = plt.subplots(figsize=size_figure)
    # Draw the heatmap with the mask and correct aspect ratio
    sns.heatmap(corr, center=0,
                square=True, linewidths=.5,  cmap ='viridis' ) #cbar_kws={"shrink": .5}
    plt.show()

    return 0

def conf_matrix (model):
    titles_options = [("Confusion matrix, without normalization", None),
                  ("Normalized confusion matrix", 'true')]
    for title, normalize in titles_options:
        disp = plot_confusion_matrix(model, X_validation, y_validation,
                                 # display_labels=ytest,
                                 cmap=plt.cm.Blues)
                                 #normalize=normalize)
        disp.ax_.set_title(title)

        print(title)
        print(disp.confusion_matrix)
plt.show()

def plot_roc_curve (model):
    prob_predictions = model.predict_proba(X_validation)
    # keep probabilities for the positive outcome only
    yhat = prob_predictions[:, 1]
    # calculate roc curves
    fpr, tpr, thresholds = roc_curve(y_validation, yhat)
    # plot the roc curve for the model
    plt.plot([0,1], [0,1], linestyle='--', label='No Skill')
    plt.plot(fpr, tpr, marker='.', label='Random Forest')
    # axis labels
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.legend()
    # show the plot
    plt.show()

def evaluate_model(ytest, ypred, ypred_proba = None):
    if ypred_proba is not None:
        print('ROC-AUC score of the model: {}'.format(roc_auc_score(ytest, ypred_proba[:, 1])))
    print('Accuracy of the model: {}\n'.format(accuracy_score(ytest, ypred)))
    print('Classification report: \n{}\n'.format(classification_report(ytest, ypred)))
    print('Confusion matrix: \n{}\n'.format(confusion_matrix(ytest, ypred)))
    print('F2 Score: \n{}\n'.format(fbeta_score(ytest, ypred,beta=2,average="macro")))

def model_analysis(modelo, xtest, ytest):
    matplotlib.rcParams['figure.figsize'] = (9, 9)
    ypred = modelo.predict(xtest)
    ypred_proba = modelo.predict_proba(xtest)
    # keep probabilities for the positive outcome only
    yhat = ypred_proba[:, 1]
    # calculate roc curves
    fpr, tpr, thresholds = roc_curve(ytest, yhat)
    # plot the roc curve for the model
    plt.plot([0, 1], [0, 1], linestyle='--', label='No Skill')
    plt.plot(fpr, tpr, marker='.', label=re.findall('^[A-z]+', str(modelo)))
    # axis labels
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.legend()
    # show the plot
    plt.show()

    gmeans = np.sqrt(tpr * (1 - fpr))
    # locate the index of the largest g-mean
    ix = np.argmax(gmeans)

    # print('Best Threshold=%f, G-Mean=%.3f' % (thresholds[ix], gmeans[ix]))

    # plot the roc curve for the model
    plt.plot([0, 1], [0, 1], linestyle='--', label='No Skill')
    plt.plot(fpr, tpr, marker='.', label=re.findall('^[A-z]+', str(modelo)))
    plt.scatter(fpr[ix], tpr[ix], s=100, marker='o', color='black', label='Best')
    # axis labels
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.legend()
    # show the plot
    plt.show()
    ypred_new_threshold = (ypred_proba[:, 1] > thresholds[ix]).astype(int)

    # Plot non-normalized confusion matrix
    titles_options = [("Confusion matrix, without normalization", None),
                      ("Normalized confusion matrix", 'true')]

    for title, normalize in titles_options:
        fig, ax = plt.subplots(figsize=(10, 10))
        disp = ConfusionMatrixDisplay.from_predictions(ytest, ypred_new_threshold,
                                                       cmap=plt.cm.Greens,
                                                       normalize=normalize,
                                                       ax=ax)
        ax.set_title(title)

    evaluate_model(ytest, ypred_new_threshold, ypred_proba)

def load_model(path):
    return pickle.load(open(path, 'rb'))

def com_gain(y_test, prob_predictions):
    skplt.metrics.plot_cumulative_gain(y_test, prob_predictions)
    plt.show()

def lift_curve(ytest, prob_predictions):
    skplt.metrics.plot_lift_curve(ytest, prob_predictions)
    plt.show()

def model_analysis_op(modelo, xtest, ytest):
    matplotlib.rcParams['figure.figsize'] = (9, 9)
    ypred = modelo.predict(xtest)
    ypred_proba = modelo.predict_proba(xtest)
    # keep probabilities for the positive outcome only
    yhat = ypred_proba[:, 1]
    # calculate roc curves
    fpr, tpr, thresholds = roc_curve(ytest, yhat)
    # plot the roc curve for the model
    plt.plot([0, 1], [0, 1], linestyle='--', label='No Skill')
    plt.plot(fpr, tpr, marker='.', label=re.findall('^[A-z]+', str(modelo)))
    # axis labels
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.legend()
    # show the plot
    plt.show()

    gmeans = np.sqrt(tpr * (1 - fpr))
    # locate the index of the largest g-mean
    ix = np.argmax(gmeans)

    # print('Best Threshold=%f, G-Mean=%.3f' % (thresholds[ix], gmeans[ix]))

    # plot the roc curve for the model
    plt.plot([0, 1], [0, 1], linestyle='--', label='No Skill')
    plt.plot(fpr, tpr, marker='.', label=re.findall('^[A-z]+', str(modelo)))
    plt.scatter(fpr[ix], tpr[ix], s=100, marker='o', color='black', label='Best')
    # axis labels
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.legend()
    # show the plot
    plt.show()
    ypred_new_threshold = (ypred_proba[:, 1] > thresholds[ix]).astype(int)

    # Plot non-normalized confusion matrix
    titles_options = [("Confusion matrix, without normalization", None),
                      ("Normalized confusion matrix", 'true')]

    for title, normalize in titles_options:
        fig, ax = plt.subplots(figsize=(10, 10))
        disp = ConfusionMatrixDisplay.from_predictions(ytest, ypred_new_threshold,
                                                       cmap=plt.cm.Greens,
                                                       normalize=normalize,
                                                       ax=ax)
        ax.set_title(title)

    evaluate_model(ytest, ypred_new_threshold, ypred_proba)

    com_gain(ytest, ypred_proba)

    lift_curve(ytest, ypred_proba)


# pip install gensim
# Run this in the terminal

# pip install matplotlib
# Run this in the terminal to install matplotlib for drawing the barcharts (used for analysing the data)

#pip install huggingface_hub

# optional
# pip show gensim
# Use it to make sure that you have downloaded Gensim library properly

import gensim.downloader as api
import gensim
import json
import random
import os
import matplotlib.pyplot as plt
from gensim.models import KeyedVectors
from huggingface_hub import hf_hub_download

# MAKE REPORT FOLDER IF IT DOESN"T EXIST YET
folder_name = 'reports'
if not os.path.exists(folder_name):
    os.makedirs(folder_name)

# LOAD DATASET FROM .json FILE
with open('data_set/synonym.json', 'r') as file:
  data_set = json.load(file)

# MAKE analysis.csv FILE AND WRITE COLUMN NAMES
reports_file_path = os.path.join(folder_name, 'analysis.csv')
with open(reports_file_path, 'w') as file:
  file.write('Model Name,Size of Vocabulary,#Correct Labels,Model Accuracy\n')

# LOAD MODELS
models = {
    # TASK 1:
    "word2vec-google-news-300": None,

    # TASK 2:
    # "glove-wiki-gigaword-300": None,  # trained on Wikipedia + Gigaword.
    # "fasttext-wiki-news-subwords-300": None,  # trained on Common Crawl.
    "glove-twitter-50": None,  # trained on a dataset composed of tweets.
    "glove-twitter-25": None  # trained on a dataset composed of tweets.
}

for model_name in models.keys():
  models[model_name] = api.load(model_name)
  print(f'{model_name} has been successfylly downloaded')

# Load the nlpl_5 model, Nordic Language Processing Laboratory
# This model is trained on the English Wikipedia Dump of February 2017.
nlpl_5_model_path = hf_hub_download(repo_id="Word2vec/nlpl_5", filename="model.bin")
models['nlpl_5_model-300'] = KeyedVectors.load_word2vec_format(nlpl_5_model_path, binary=True)
print('nlpl_5_model-300 has been successfylly downloaded')

# Load the nlpl_222 model, Nordic Language Processing Laboratory
# This model is trained on the English Wikipedia Dump of November 2021.
nlpl_222_model_path = hf_hub_download(repo_id="Word2vec/nlpl_222", filename="model.bin")
models['nlpl_222_model-300'] = KeyedVectors.load_word2vec_format(nlpl_222_model_path, binary=True)
print('nlpl_222_model-300 has been successfylly downloaded')

# TASK 3
task3models = os.listdir('./task3models/')
try:
  for model_file in task3models:
    model_name = model_file.rsplit('.', 1)[0]
    model = gensim.models.Word2Vec.load('./task3models/' + model_file)
    models[model_name] = model.wv

except:
  print('\n -- task 3 models not trained yet..\n!! RUN task3.py FIRST !!\n')

print("\n********************\n")

model_stats = {}
for model_name, model in models.items():
  file_path = os.path.join(folder_name, f'{model_name}-details.csv')
  with open(file_path, 'w') as file:
    file.write("#,question_word,correct_answer_word,system_guess_word,label\n")
    i = 1
    correct_guesses_counter = 0
    wrong_guesses_counter = 0

    for entry in data_set:
      question_word = entry["question"]
      choices = entry["choices"]
      correct_answer_word = entry["answer"]

      label = "guess"
      similarities = {}

      # IF QUESTION WORD IN MODEL
      if question_word in model:
        for choice in choices:
          if choice in model:
            similarities[choice] = model.similarity(question_word, choice)
        # IF AT LEAST ONE CHOICE IN MODEL
        if  len(similarities) > 0:
          system_guess_word = max(similarities, key=similarities.get)
          if system_guess_word == correct_answer_word:
            label = 'correct'
            correct_guesses_counter += 1
          else:
            label = 'wrong'
            wrong_guesses_counter += 1
      # OTHERWISE, STILL A GUESS
      if label == 'guess':
        system_guess_word = random.choice(choices)

      # WRITE TO MODEL REPORT
      file.write(f"{i},{question_word},{correct_answer_word},{system_guess_word},{label}\n")
      i+=1

  print(f'{model_name}-details.csv has been sucessfully generated')

  vocab_size = len(model.key_to_index)
  model_accuracy = 0
  if (correct_guesses_counter + wrong_guesses_counter) > 0:
    model_accuracy = correct_guesses_counter / (correct_guesses_counter + wrong_guesses_counter)

  model_stats[model_name] = {"accuracy": model_accuracy, "total_correct_words": correct_guesses_counter, "total_model_guesses": correct_guesses_counter + wrong_guesses_counter} # for analyzing the data later

  # WRITE TO ANALYSIS FILE
  with open(reports_file_path, 'a') as file:
    file.write(f'{model_name},{vocab_size},{correct_guesses_counter},{model_accuracy*100:.1f}%\n')

print("\n********************\n")
print(f'The analysis.csv has been sucessfully generated')

# ANALYZE THE DATA
model_names = list(model_stats.keys())
accuracy = [model_stats[model]['accuracy'] for model in model_names]
total_correct_words = [model_stats[model]['total_correct_words'] for model in model_names]
total_model_guesses = [model_stats[model]['total_model_guesses'] for model in model_names]

plt.figure(figsize=(14, 6))

# Accuracy Bar Chart
plt.subplot(1, 3, 1)
plt.bar(model_names, accuracy, color='skyblue')
plt.title('Model Accuracy Comparison')
plt.xlabel('Model')
plt.ylabel('Accuracy')
plt.xticks(rotation=90)

# Adding a horizontal line for the Human Gold-Standard at 88.5%
plt.axhline(y=0.885, color='r', linestyle='-', label='Human Gold-Standard')
plt.legend()

# Adding a horizontal line for the Human Gold-Standard at 88.5%
plt.axhline(y=0.25, color='y', linestyle='-', label='Random Baseline')
plt.legend()

# Total Model Guesses Bar Chart
plt.subplot(1, 3, 2)
plt.bar(model_names, total_correct_words, color='lightgreen')
plt.title('Correct Model Predicted Answers')
plt.xlabel('Model')
plt.ylabel('Total Correct Words')
plt.xticks(rotation=90)

# Total Model Guesses Bar Chart
plt.subplot(1, 3,3)
plt.bar(model_names, total_model_guesses, color='salmon')
plt.title('Model Predicted Answers')
plt.xlabel('Model')
plt.ylabel('Total Model Valid Set')
plt.xticks(rotation=90)

plt.tight_layout()
plt.savefig('model_comparison_charts.png')
plt.show()


import trac
from trac.core import *
from trac.util.html import html
from trac.web import IRequestHandler
from trac.web.api import IRequestFilter
from trac.web.chrome import INavigationContributor
from trac.perm import IPermissionRequestor, IPermissionPolicy
import trac.wiki
import trac.wiki.api

class UserPagePlugin(Component):
	trac.core.implements(IRequestHandler, IRequestFilter)

	# IRequestFilter methods
	def pre_process_request(self, req, handler):
		root = self.config.get('userpage', 'root')
		if req.path_info.startswith(root):
			self.real_handler = handler
			return self
		return handler

	def post_process_request(self, req, template, content_type):
		return (template, content_type)

	# IRequestHandler methods
	def match_request(self, req):
		root = self.config.get('userpage', 'root')
		if req.path_info.startswith(root):
			return True
		return False

	def process_request(self, req):
		root = self.config.get('userpage', 'root')
		rpath = req.path_info[len(root):]
		elements = rpath.split('/')

		if elements[0] == req.authname:
			# If it's your own page, then render without further analysis
			return self.real_handler.process_request(req)

		if self.config.has_option('userpage', 'default'):
			mode = self.config.get('userpage', 'default')
		else:
			mode = 'public'

		if len(elements) > 1 and elements[1] in ('public', 'private'):
			mode = elements[1]

		if req.perm.has_permission('TRAC_ADMIN'):
			mode = 'public'

		if mode == 'public':
			return self.real_handler.process_request(req)
		else:
			return self.noaccess(req)

	# public methods
	def noaccess(self, req):
		wiki = trac.wiki.api.WikiSystem(self.env)
		error = self.config.get('userpage', 'error')
		req.redirect(req.href.wiki(error))
		#req.send_response(200)
		#req.send_header('Content-type', 'text/html')
		#req.end_headers()
		#req.write(wiki.format_page_name(error))
		return

		return self._render_view(trac.wiki.model.WikiPage(self.env, error))
		req.send_response(200)
		req.send_header('Content-type', 'text/html')
		req.end_headers()
		req.write(trac.wiki.wiki_to_html('no', self.env, req))
		return

		if self.config.has_option('mypage', 'url_prefix'):
			prefix = self.config.get('mypage', 'url_prefix')
			url = prefix + url
		req.send_response(307)
		req.send_header('Location', url)
		req.end_headers()
		return


# -*- coding: utf-8 -*-
# date: 2022/7/7
import xlwings

file = xlwings.books.active
shtnames = [i.name for i in file.sheets]
shtnames.sort(key=None)  # 可以用lamda函数按规则排序
for index, name in enumerate(shtnames):
    file.sheets[name].api.Move(After=file.sheets[shtnames[index - 1]].api)
# for i in range(1, len(shtnames)):
#     # .api后面的函数以及参数首字母需大写
#     file.sheets[shtnames[i]].api.Move(After=file.sheets[shtnames[i - 1]].api)

# 或者以下方式
# for name in shtnames:
#     # sheets.copy(before=***)等价于sheets.api.Copy(Before=***)
#     file.sheets[name].copy()
#     file.sheets[name].delete()
#     file.sheets[-1].name = name


import re
from pathlib import Path

import pytest
from boltons.iterutils import flatten

from ..platform import OS_DEFINITIONS
from .conftest import MANAGER_IDS

""" Test documentation. """

def test_changelog():
    changelog_path = Path(
        __file__).parent.parent.parent.joinpath('CHANGES.rst').resolve()
    with changelog_path.open() as doc:
        changelog = doc.read()

    assert changelog.startswith("Changelog\n=========\n")

    entry_pattern = re.compile(r"^\* \[(?P<category>[a-z,]+)\] (?P<entry>.+)")
    for line in changelog.splitlines():
        if line.startswith('*'):
            match = entry_pattern.match(line)
            assert match
            entry = match.groupdict()
            assert entry['category']
            assert set(entry['category'].split(',')).issubset(flatten([
                MANAGER_IDS, OS_DEFINITIONS.keys(), 'mpm', 'bitbar']))


import scrapy
from bs4 import BeautifulSoup
from scrapy import signals
from selenium.webdriver import Edge

class SeleniumTestSpider(scrapy.Spider):
    name = 'selenium_test'
    allowed_domains = ['www.guazi.com']
    start_urls = ['https://www.guazi.com/buy']

    @classmethod
    def from_crawler(cls, crawler, *args, **kwargs):

        #'SeleniumTestSpider' # 父类class名称
        spider = super(SeleniumTestSpider, cls).from_crawler(crawler, *args, **kwargs)

        # 创建webdriver对象 用户中间件调度
        spider.edge=Edge()

        # signals.spider_closed 当莫信号成立时 关闭spider
        crawler.signals.connect(spider.spider_closed, signal=signals.spider_closed)

        return spider

    def spider_closed(self, spider, reason):

        spider.edge.quit()
        print('爬虫结束')

    def parse(self, response):
        # print(response.url)

        soup = BeautifulSoup(str(response.text), "html.parser")
        pictures = soup.find_all('div', class_='car-card content-item')

        for picture in pictures:
            src = str(picture.find('img').get('data-src')).split('?')[0]  # 提取高清图
            name = picture.find('img').get('alt')
            print(src, name)


"""
comparators

== ----->  value equality
!= -----> not equal to
>  -----> greater than
<  -----> less than
>= -----> greater than equal to
<= -----> less than equal to
"""

a = 24==24

b = 24 != 38

c = 35 > 24

d = 48 < 189

e = 75 >= 75+15

f = 75 <= 75-5

print(a)

print(e)

print(f)


import http.client
import urllib.parse

class NetworkError(Exception):
    pass

def krnnt_response_lines(text):
    """
    Get KRNNT's analysis of text as a list of lines.
    """
    params = urllib.parse.urlencode({'text': text})
    headers = {'Content-type': 'application/x-www-form-urlencoded',
            'Accept': 'text/plain'}
    conn = http.client.HTTPConnection('localhost:9003') # where KRNNT resides
    conn.request('POST', '', params, headers)
    response = conn.getresponse()
    if response.status != 200:
        raise NetworkError('Cannot connect to KRNNT: {} {}, is the container running?'.format(
            response.status, response.reason))
    resp_html = response.read().decode('utf-8') # we get a HTML page and need to strip tags
    lines = resp_html[resp_html.index('<pre>')+len('<pre>')
            :resp_html.index('</pre>')].strip().split('\n')
    return lines

def tag_nkjp(text):
    """
    Tag text with NKJP tagset. Returns a list of sentences as lists of (form, lemma, interp).
    """
    lines = krnnt_response_lines(text)
    sents = [[]]
    current_token = None
    for line_n, line in enumerate(lines):
        # Next sentence.
        if len(line) == 0:
            sents.append([])
            continue
        # A form line - assign the form.
        if line_n % 2 == (0 if (len(sents) % 2 == 1) else 1):
            current_token = line.split('\t')[0]
        else:
            interp_data = line.split('\t')
            current_token = (current_token, interp_data[1], interp_data[2])
            sents[-1].append(current_token)
    sents = [sent for sent in sents if len(sent) > 0]
    return sents

def split_sents_krnnt(text, strip_sents=True):
    """
    Use KRNNT to split the text into a list of sentence strings.
    """
    lines = krnnt_response_lines(text)
    sents = ['']
    for line_n, line in enumerate(lines):
        # Next sentence.
        if len(line) == 0:
            sents.append('')
            continue
        # A form line - grow the sentence.
        if line_n % 2 == (0 if (len(sents) % 2 == 1) else 1):
            form_data = line.split('\t')
            form = form_data[0]
            if form_data[1] == 'space':
                preceding_sep = ' '
            elif form_data[1] == 'none':
                preceding_sep = ''
            elif form_data[1] == 'newline':
                preceding_sep = '\n'
            sents[-1] += preceding_sep + form
    if strip_sents:
        sents = [sent.strip() for sent in sents]
    sents = [sent for sent in sents if len(sent) > 0]
    return sents


__all__ = ['TrainerSimpleMeshLayers']

import logging
from typing import List

import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image

from lib.modules.cameras import CameraPytorch3d
from lib.modules.edge_filters.spatial_grad import SpatialGradient
from lib.modules.losses import PerceptualLoss, PSNRMetric, SSIM
from lib.utils.visualise import plot_square_grid
from .trainer_base import TrainerBase
from ..utils.base import min_max_scale

logger = logging.getLogger(__name__)

class TrainerSimpleMeshLayers(TrainerBase):
    def _unpack_data(self,
                     data: dict,
                     mode: str = 'eval',
                     ):
        assert list(data['initial']['image'].shape[1:3]) == [1, 1], f'Expected one image in one timestamp'
        source_images: torch.Tensor = data['initial']['image'].squeeze(1).squeeze(1).cuda()
        source_cameras = CameraPytorch3d(extrinsics=data['initial']['extrinsics'].squeeze(1).squeeze(1).cuda(),
                                         intrinsics=data['initial']['intrinsics'].squeeze(1).squeeze(1).cuda(),
                                         )

        novel_cameras = CameraPytorch3d(extrinsics=data['novel']['extrinsics'].squeeze(1).squeeze(1).cuda(),
                                        intrinsics=data['novel']['intrinsics'].squeeze(1).squeeze(1).cuda(),
                                        )

        if mode == 'train':
            novel_images: torch.Tensor = data['novel']['image'].squeeze(1).squeeze(1).cuda()
            return (
                source_images,
                novel_images,
                source_cameras,
                novel_cameras,
            )

        elif mode == 'eval':
            return (
                source_images,
                source_cameras,
                novel_cameras,
            )
        else:
            raise ValueError(f'Unknown mode: {mode}')

    def _init_auxiliary_modules(self):
        if self.params['weights']['generator'].get('perceptual', 0.) > 0:
            self.perceptual_loss = PerceptualLoss(
                feature_layers=(2, 7, 12, 21, 30),
                feature_weights=(1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0),
                use_avg_pool=False,
                use_input_norm=True,
                input_range='tanh').cuda()
        self.psnr = PSNRMetric(input_range='tanh').cuda()
        self.ssim = SSIM(input_range='tanh').cuda()
        self.spatial_grad = SpatialGradient()

    def update_step(self,
                    iteration,
                    a_images,
                    b_images,
                    a_cameras,
                    b_cameras
                    ):

        novel_image_b, novel_depth_b, depth_tuned_a, source_depth_a, novel_mask_b = self.gen(
            a_images,
            a_cameras,
            b_cameras,
        )

        novel_image_a, novel_depth_a, depth_tuned_b, source_depth_b, novel_mask_a = self.gen(
            b_images,
            b_cameras,
            a_cameras,
        )

        """
        GENERATOR UPDATE
        """
        self.losses['generator']['l1'] = 0
        self.losses['generator']['l1_depth'] = 0
        self.losses['generator']['depth_grad'] = 0

        """
        DEPTH LOSS
        """

        for predicted_depth, target_depth, frame_mask in [
            (novel_depth_b, source_depth_b, novel_mask_b),
            (novel_depth_a, source_depth_a, novel_mask_a),
        ]:
            self.losses['generator']['l1_depth'] += F.l1_loss(predicted_depth * frame_mask, target_depth * frame_mask)

        for predicted_depth, target_depth, frame_mask in [
            (novel_depth_b, source_depth_b, novel_mask_b),
            (novel_depth_a, source_depth_a, novel_mask_a),
        ]:
            self.losses['generator']['depth_grad'] += self.spatial_grad(predicted_depth).abs().mean()

        """
        IMAGE LOSS
        """

        for predicted_images, target_images, frame_mask in [
            (novel_image_b, b_images, novel_mask_b),
            (novel_image_a, a_images, novel_mask_a),
        ]:
            self.losses['generator']['l1'] += F.l1_loss(predicted_images * frame_mask,
                                                        target_images * frame_mask)

        self._aggregate_losses('generator')
        self.backward('generator')
        self.optimizers['generator'].step()

    def forward(self,
                source_images,
                source_cameras,
                novel_cameras
                ):

        novel_image, novel_depth, depth_tuned, depth_source, novel_mask = self.gen(
            source_images,
            source_cameras,
            novel_cameras,
        )

        out = {'images': novel_image,
               'depth': depth_tuned,
               'depth_novel': novel_depth,
               'depth_source': depth_source,
               'projection_mask': novel_mask,
               }

        return out

    @torch.no_grad()
    def inference(self, data):
        training_status = self.training
        self.eval()
        result = self.forward(*self._unpack_data(data, 'eval'))
        self.train(training_status)
        return result

    def _compute_visualisation(self, output: dict, data: dict) -> List[Image.Image]:

        novel_image = output['images'].data.add(1).div(2).to("cpu").numpy().transpose((0, 2, 3, 1))

        depth_output = output['depth'].data
        depth_output = min_max_scale(depth_output).to("cpu").numpy().transpose((0, 2, 3, 1))

        depth_novel = output['depth_novel'].data
        depth_novel = min_max_scale(depth_novel).to("cpu").numpy().transpose((0, 2, 3, 1))

        depth_source = output['depth_source'].data
        depth_source = min_max_scale(depth_source).to("cpu").numpy().transpose((0, 2, 3, 1))

        depth_grad = self.spatial_grad(output['depth_source']).abs().mean(2).data.to("cpu").numpy().transpose(
            (0, 2, 3, 1))

        projection_mask = output['projection_mask'].data.to("cpu").numpy().transpose((0, 2, 3, 1))

        mask_image = np.concatenate((projection_mask,
                                     1 - projection_mask,
                                     np.zeros_like(projection_mask)), axis=3)

        # TODO: this implementation contains squeezeing, suitable only for a single camera of each role per one scene
        images_target = data['novel']['image'].squeeze(1).squeeze(1).data.add(1).div(2).to("cpu").numpy().transpose(
            (0, 2, 3, 1))
        images_source = data['initial']['image'].squeeze(1).squeeze(1).data.add(1).div(2).to("cpu").numpy().transpose(
            (0, 2, 3, 1))

        depth_images = []
        for i in range(depth_output.shape[-1]):
            depth_images.append(np.repeat(depth_output[..., [i]], 3, axis=3))

        mse = np.power(novel_image - images_target, 2).sum(-1, keepdims=True)

        images_out = np.concatenate((images_source,
                                     images_target,
                                     np.repeat(mse, 3, axis=3),
                                     novel_image,
                                     np.repeat(depth_output, 3, axis=3),
                                     np.repeat(depth_source, 3, axis=3),
                                     np.repeat(depth_novel, 3, axis=3),
                                     mask_image,
                                     np.repeat(depth_grad, 3, axis=3),
                                     ),
                                    axis=2) * 255

        pil_output_images = []
        for image in images_out:
            image = np.clip(image, 0., 255.).astype(np.uint8)
            if image.shape[1] % 2 != 0:
                image = image[:, :-1]
            pil_output_images.append(Image.fromarray(image))

        return pil_output_images

    def _aggregate_visualisation(self, visualisations: List[Image.Image]) -> Image.Image:
        return plot_square_grid(visualisations, 1, len(visualisations), padding=5)

    def _compute_metrics(self, output: dict, data: dict) -> dict:
        images_output = output['images']

        images_target = data['novel']['image'].cuda()
        images_target = images_target.contiguous().view(-1, *images_target.shape[-3:])

        return {
            'ssim': self.ssim(images_output, images_target),
            'psnr': self.psnr(images_output, images_target),
            'batch_length': images_output.shape[0],
        }

    def _aggregate_metrics(self, metrics: List[dict]) -> dict:
        ssim, psnr, batch_length = [], [], []
        for metrics_per_batch in metrics:
            ssim.append(metrics_per_batch['ssim'].item())
            psnr.append(metrics_per_batch['psnr'].item())
            batch_length.append(metrics_per_batch['batch_length'])

        ssim, psnr, batch_length = np.array(ssim), np.array(psnr), np.array(batch_length)
        return {
            'psnr': np.sum(psnr * batch_length) / batch_length.sum(),
            'ssim': np.sum(ssim * batch_length) / batch_length.sum(),
        }


import webapp2
import logging
import csv

from google.appengine.ext import deferred

from db.model import *

class UpdateDB(webapp2.RequestHandler):
    def get(self):
#        deferred.defer(update)
        deferred.defer(update)
        self.response.out.write('postcodes.UpdateDB')

def update():
    logging.info("Updating Postcode data from local Council Data")
    n_pcs = 0
    invalid_postcodes = re.compile(
        r"((((South|West|East|North)\s)+Edinburgh)|(NN not supplied))",
        re.IGNORECASE)
    with open('data/natural-neighbourhoods-survey.csv', 'r') as f_in:
#        csv_in = csv.DictReader(f_in)
        f_in.readline()

        for row in f_in.readlines():
            row = row.split(',')
            try:
                if ((int(row[4]) != 0)
                    and (int(row[5]) != 0)):
                    # and (len(invalid_postcodes.findall(row["Allocated  NN"]))
                    #      == 0)):
                    pcString = row[3].strip().upper()

                    dbPostcode = Postcodes.query(
                        Postcodes.postcode == pcString).get()

                    if dbPostcode is None:
                        dbPostcode = Postcodes(
                            postcode = pcString,
                            grid_x = int(row[4]),
                            grid_y = int(row[5]),
                            districts = []
                        )
                    else:
                        continue

                    district_names = row[2].split('/')

                    for d in district_names:
                        dbDistrictKey = District.query(
                            District.name == d).get()
                        if dbDistrictKey is None:
                            dbDistrictKey = District(name = d).put()
                        else:
                            dbDistrictKey = dbDistrictKey.key

                        dbPostcode.districts.append(dbDistrictKey)

                    dbPostcode.put()
                    n_pcs += 1
            except ValueError as e:
                logging.warning("Exception: at %i (%s)"
                                % (n_pcs, ' '.join(e.args)))
    logging.info("Successfully read %i entries" % (n_pcs))
    logging.info("Testing pulling")


import os
import clarify
import model
import numpy as np

class predictor():
    def __init__(self,debug=False):

        # init vars
        self.debug=debug
        self.train_list = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")

        # load model
        _model = model.Model()
        self.model = _model.model
    def predict_image(self, path=None, image=None):
        # clarify the image first
        clf = clarify.clarify(img=image,path=path)
        clf.clarify_and_gray()
        image = clf.img / 255.0
        # add dimensions in order to fit it in model
        image = np.expand_dims(image, 2)
        image = np.expand_dims(image, 0)

        # get prediction from model
        prediction = self.model.predict(image)

        # models output is list of prob list. get maximum value of each list of prob list with stride=train_list_len
        prediction = np.reshape(prediction, (5,62))
        maxs = np.argmax(prediction, axis=1)
        probs = np.max(prediction, axis=1)
        locs = [self.train_list[max] for max in maxs]
        print(dict(zip(locs, probs)))
        # string list to one string
        return "".join(locs)

if __name__ == "__main__":
    predictor_=predictor(debug=True)
    print(predictor_.predict_image("test.png"))


from copy import deepcopy

import anndata as ad
import numpy as np
import scanpy as sc

class DeltaHVFMean:
    def __init__(self, calculate_deltamean: bool = True, log_transform: bool = False,
                 num_top_features: int = None, min_disp: float = 0.5,
                 min_mean: float = 0.0125, max_mean: float = 3):
        self.calculate_deltamean = calculate_deltamean
        self.log_transform = log_transform
        self.num_top_features = num_top_features
        self.min_disp = min_disp
        self.min_mean = min_mean
        self.max_mean = max_mean

    def fit_predict(self, X, y, control_class: int = 0, case_class: int = 1):
        num_features = X.shape[1]
        num_classes = len(np.unique(y))
        results = np.zeros((num_features))

        # Shift data
        min_value = X.min(0)
        if len(np.where(min_value < 0)[0]) > 0:
            X = X - min_value + 1

        adata = ad.AnnData(X=X)
        # Logarithm transformation
        if self.log_transform:
            sc.pp.log1p(adata)
            np.nan_to_num(adata.X, copy=False, nan=0.0, posinf=0.0, neginf=0.0)
        delta_vars = list()
        delta_means = list()
        X = deepcopy(adata.X)
        for i in range(num_classes):
            examples_i = np.where(y == i)[0]
            adata = ad.AnnData(X=X[examples_i])
            sc.pp.highly_variable_genes(adata, n_top_genes=self.num_top_features,
                                        min_disp=self.min_disp, min_mean=self.min_mean,
                                        max_mean=self.max_mean)
            features_idx = adata.var["highly_variable"]
            disp1 = adata.var[features_idx]["dispersions_norm"].to_numpy()
            mean1 = np.mean(X[examples_i], axis=0)
            for j in range(i + 1, num_classes):
                examples_j = np.where(y == j)[0]
                adata = ad.AnnData(X=X[examples_j])
                sc.pp.highly_variable_genes(adata, n_top_genes=self.num_top_features,
                                            min_disp=self.min_disp, min_mean=self.min_mean,
                                            max_mean=self.max_mean)
                features_idx = adata.var["highly_variable"]
                disp2 = adata.var[features_idx]["dispersions_norm"].to_numpy()
                mean2 = np.mean(X[examples_j], axis=0)
                delta_vars.append(np.abs(disp1 - disp2))
                delta_means.append(np.abs(mean1 - mean2))
        results = np.max(delta_vars, axis=0)
        if self.calculate_deltamean:
            results += np.max(delta_means, axis=0)
        np.nan_to_num(results, copy=False, nan=0.0, posinf=0.0, neginf=0.0)
        results = np.reshape(results, (results.shape[0], 1))
        return results


import re
from fake_useragent import UserAgent
from bs4 import BeautifulSoup
from urllib.request import urlopen
from xlwt import *

# function for Excel output with xlwt package
def outputExcel(urlList):
    urlIterator = iter(urlList)
    excelFile = Workbook(encoding = 'utf-8')
    excelTable = excelFile.add_sheet('Mazak')

    row = 0
    for i in urlIterator:

        htmlMachine = urlopen(i).read().decode('utf-8')
        soupMachine = BeautifulSoup(htmlMachine, 'lxml')

        excelTable.write(row, 0, str(soupMachine.h1)[14:][:-11]) #write machine name in 1. column

        div = soupMachine.find("tbody") # where the machine specs are
        specList = re.findall(r'<td>.*</td>', str(div)) # find all labels and specs and then divide them
        #print(str(div))
        #print(specList)
        specIterator = iter(specList)
        column = 1
        for i in specIterator:
            newstring = str(i)[4:][:-5]
            if ':' in newstring:
                #print("writing column: " + str(column) + ", row: " + str(row) + ", content: " + str(i)[4:][:-5]) # console output
                data = newstring.replace(':', '')
                if data is not None:
                    excelTable.write(row, column, data) # writing without useless chars
                    column = column + 1 # write data / label in next cell
                else:
                    continue
            else:
                if newstring is not None:
                    excelTable.write(row, column, newstring) # writing without useless chars
                    column = column + 1 # write data / label in next cell
                else:
                    continue

        row = row + 1 # change to next row

    excelFile.save('Mazak_MachineData2.xls')

# start of code
ua = UserAgent()
ua.chrome

mazakAllMachineHTML = []
urlList = []
mazakURL = "https://www.mazakeu.com"
htmlMazak = urlopen("https://www.mazakeu.com/machines").read().decode('utf-8')

# use bs4 to collect html information
soup = BeautifulSoup(htmlMazak, 'lxml')
mazakMachinesColumn = soup.find_all("div", {"class": "all-machines-column"}) # return a list of all machine columns
#print(len(mazakMachinesColumn))
#print(mazakMachinesColumn)

# create a iterator to merge machine columns in one list
columnIterator = iter(mazakMachinesColumn)
for i in columnIterator:
    mazakAllMachineHTML = mazakAllMachineHTML + i.find_all(r'li') # for 'li' see html code of Mazak

# create an iterator for every machine and append URL address to urlList
machineIterator = iter(mazakAllMachineHTML)
for i in machineIterator:
    #print(re.findall(r'".*"', str(i)))
    temp = mazakURL + str(re.findall(r'".*"', str(i)))[3:][:-3] # find URL and delete first & last four char
    urlList.append(temp)

# save URL list in an excel file
excelFile = Workbook(encoding='utf-8')
excelTable = excelFile.add_sheet('Mazak_URLList')
row = 0
excelIterator = iter(urlList)
for i in excelIterator:
    #print(str(i))
    excelTable.write(row, 0, str(i))
    row = row + 1
excelFile.save('Mazak_URLList.xls')

# finally output the data in CSV format
outputExcel(urlList)