from sqlalchemy.orm import Session

from . import models, schemas
from typing import Union

from datetime import date

def create_inventory(db: Session, inventory: schemas.InventoryCreate):
    db_inventory = models.Inventory(
        id=inventory.id,
        quantity=inventory.quantity,
        name=inventory.name if inventory.name else None
    )

    db.add(db_inventory)
    db.commit()
    db.refresh(db_inventory)
    return db_inventory

def create_future_inventory(db: Session, product: schemas.FutureInventoryCreate):
    db_inventory = models.FutureInventory(
        id=product.id,
        quantity=product.quantity,
        available_date=product.available_date,
        name=product.name if product.name else None
    )

    db.add(db_inventory)
    db.commit()
    db.refresh(db_inventory)
    return db_inventory

def create_inventory_reservation(db: Session, product: schemas.ReservationInventoryCreate, inventory_id: int):
    db_inventory = models.ReservationInventory(
        quantity=product.quantity,
        expiration_date=product.expiration_date,
        status=product.status,
        inventory_id=inventory_id,
    )

    db.add(db_inventory)
    db.commit()
    db.refresh(db_inventory)
    return db_inventory

def update_inventory_quantity(db: Session, inventory_id: int, new_quantity: int):
    db_inventory = db.query(models.Inventory).filter(models.Inventory.id == inventory_id).first()

    if db_inventory:
        db_inventory.quantity = new_quantity
        db.commit()
        db.refresh(db_inventory)
        return db_inventory

    return

def update_future_inventory(db: Session, inventory_id: int, product: schemas.FutureInventoryUpdate):
    db_inventory = db.query(models.FutureInventory).filter(models.FutureInventory.id == inventory_id).first()

    if db_inventory:
        db_inventory.quantity = product.quantity if product.quantity else db_inventory.quantity
        db_inventory.available_date = product.available_date if product.available_date else db_inventory.available_date
        db.commit()
        db.refresh(db_inventory)
        return db_inventory

    return

def get_inventory_by_id(db: Session, id: int):
    return db.query(models.Inventory).filter(models.Inventory.id == id).first()

def get_future_inventory_by_id(db: Session, id: int):
    return db.query(models.FutureInventory).filter(models.FutureInventory.id == id).first()

def get_reservation_inventory_by_id(db: Session, id: int):
    return db.query(models.ReservationInventory).filter(models.ReservationInventory.id == id).first()


import spotipy
import sys
import urllib.request
import csv
import sqlite3
import numpy as np

## SPOTIFY.DB
# 'album_name' = TEXT
# 'imageURL' = TEXT
# 'danceability' = TEXT
# 'energy' = TEXT
# 'speechiness' = TEXT
# 'acousticness' = TEXT
# 'liveness' = TEXT
# 'imageLoc' = TEXT
# 'instrumentalness' = TEXT
# 'tempo' = TEXT
##

def ave_feat(album_id):
    tracks = sp.album(album_id)['tracks']['items']
    ids = [x['id'] for x in tracks]
    af = sp.audio_features(ids)
    if af == None:
        return None, None, None, None, None, None, None
    d = get_ave_feat(af, 'danceability')
    e = get_ave_feat(af, 'energy')
    s = get_ave_feat(af, 'speechiness')
    a = get_ave_feat(af, 'acousticness')
    l = get_ave_feat(af, 'liveness')
    i = get_ave_feat(af, 'instrumentalness')
    t = get_ave_feat(af, 'tempo')
    return d, e, s, a, l, i, t

def get_ave_feat(features_list, feature):
    feat_lst = []
    for x in features_list:
        if x is not None:
            feat = x[feature]
            if feat is not None:
                feat_lst.append(feat)
    if not feat_lst:
        return None
    else:
        return np.average(feat_lst)

from spotipy.oauth2 import SpotifyClientCredentials
client_credentials_manager = SpotifyClientCredentials(client_id='INSERT ID', client_secret='INSERET SECRET')
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

database_dir = "C:/Users/Alex/Documents/PhD/spotify-dataset2"
conn = sqlite3.connect("C:/Users/Alex/Documents/PhD/spotify-dataset2/spotify.db")
c = conn.cursor()
num_songs_per_genre = 10000
genres = ['o', 'p', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
album_dict = {}
counter = 0
with open('dataset-links.tsv', 'w') as tsvfile:
    writer = csv.writer(tsvfile, delimiter='\t', lineterminator='\n')
    for genre in genres:
        print(genre)
        off = 0
        urls = {}
        more_albums = True
        while more_albums:
            try:
                results = sp.search(q=genre, type='track', limit=50, offset=off)['tracks']['items']
            except Exception as e:
                print(e)
                more_albums = False
            if more_albums:
                off += 50
                for item in results:
                    album = item['album']
                    a_name = album['name']
                    if a_name not in album_dict:
                        album_dict[a_name] = counter
                        d, e, s, a, l , i, t = ave_feat(album['id'])
                        if (d != None):
                            print(genre, counter)
                            counter += 1
                            image_indx = 2
                            if len(album['images']) < 2:
                                image_indx = 0
                            try:
                                url = album['images'][image_indx]['url']
                                loc = database_dir  + '/' + str(counter%10000) + '/' + a_name + '.jpg'
                                sqcomm = (a_name, url, d, e, s, a, l, loc, i, t)
                                c.execute("REPLACE INTO spotify VALUES (?, ?, ?, ?, ?, ?, ?, ? ,? ,?)", sqcomm)
                                conn.commit()
                            except Exception as e:
                                print(e)


from project_Players_Monsters.hero import Hero
from project_Players_Monsters.elf import Elf

hero = Hero("H", 4)
print(hero.username)
print(hero.level)
print(str(hero))
print(hero.__class__.__bases__[0].__name__)
elf = Elf("E", 4)
print(str(elf))
print(elf.__class__.__bases__[0].__name__)
print(elf.username)
print(elf.level)
muse_elf = Elf("ME", 2)
print(str(muse_elf))
print(muse_elf.__class__.__bases__[0].__name__)
print(muse_elf.username)
print(muse_elf.level)

# zero test
from project_Players_Monsters.hero import Hero
from project_Players_Monsters.elf import Elf
import unittest

class Tests(unittest.TestCase):
   def test(self):
      hero = Hero("H", 4)
      self.assertEqual(hero.username, "H")
      self.assertEqual(hero.level, 4)
      self.assertEqual(str(hero), "H of type Hero has level 4")
      elf = Elf("E", 4)
      self.assertEqual(str(elf), "E of type Elf has level 4")
      self.assertEqual(elf.__class__.__bases__[0].__name__, "Hero")
      self.assertEqual(elf.username, "E")
      self.assertEqual(elf.level, 4)

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


"""Create index for get_depends_query.

Revision ID: 79e1d320db3d
Revises: 8231fee9a210
Create Date: 2019-11-29 16:59:44.869319+00:00

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = "79e1d320db3d"
down_revision = "8231fee9a210"
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_index("depends_on_version_id_idx", "depends_on", ["version_id"], unique=False)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index("depends_on_version_id_idx", table_name="depends_on")
    # ### end Alembic commands ###


# > curl -i https://controltower.ea.com/api/v1/breaches > breach_api.txt
# replace true -> True, false -> False

import collections

with open("breach_api.txt", 'r') as input:

	source = input.readlines()[16]
	source_list = eval(source)

	metric_dict = collections.defaultdict(list)
	for d in source_list:
		metric_dict[d["metric_name"]].append(d)

	print(metric_dict.keys())

# conclusion:
## the metrics used by control tower so far are:
## ['AWS_USERS_CURRENTLY_CONNECTED', 'PSU']

# reference:
## https://apis.controltower.ea.com/apidocs/, BREACHES:
## breaches metrics: {PSU, LATENCY, TPM, OUTAGES, CRASHES, EPM_INTERNAL_SERVER_ERROR, EPM_400, CE ...}


# ---------- IMPORT ------------
import logging
import datetime
from datetime import date, timedelta
import json
import numpy as np
import pandas as pd
from rdd import rdd
# ------------------------------

# ---------- INPUT -------------
path_source = "..."
path_source_genderdata = "/home/lmoldon/data/users_gender.json"
path_source_merge = "/home/lmoldon/data/merge.json"
# ------------------------------

# ---------- OUTPUT ------------

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

# ---------- CONFIG ------------
observed_start = date(2016, 4, 18) # this must be a monday and the same input of getWeekendActivity.py
observed_end = date(2016, 6, 19) # this must be a sunday and the same input of getWeekendActivity.py
userlevel = True # True: datapoint represents single user per day, False: represents avg of all users per day
# IMPORTANT: in the paper bandwidth means full observed time interval, here it means bandwidth +/- around cut (2x for bandwidth length)
bandwidth = 3 # maximum: (observed_end - observed_start).weeks() / 2
country = "" # restrict rdd on users from a specific country, if empty - disable feature (ONLY FOR USERLEVEL = TRUE)
gender = "" # restrict rdd on female/male users, if empty streak - feature (ONLY FOR USERLEVEL = TRUE)

# real changedate MONDAY is date(2016,5,16) - change this MONDAY date for placebo test!
changedate = date(2016,5,16)
# ------------------------------

# ---------- INITIAL -----------
logging.basicConfig(format='%(asctime)s [%(levelname)s] - %(message)s', datefmt='%d-%m-%y %H:%M:%S', level=logging.INFO)
datetimeFormat = "%Y-%m-%d"
x = []
y = []
if userlevel:
    path_source = "/home/lmoldon/results/weekends/weekendActivity_userlevel.json"
else:
    path_source = "/home/lmoldon/results/weekendActivity.json"
# ------------------------------

def daterange(observedtime_start, observedtime_end):
        for n in range(int((observedtime_end - observedtime_start).days + 1)):
                yield observedtime_start + timedelta(n)

log_starttime = datetime.datetime.now()

with open(path_source, "r") as fp:
    weekdata = json.load(fp)

with open(path_source_genderdata, "r") as fp:
    genderdata = json.load(fp)

with open(path_source_merge, "r") as fp:
    merge = json.load(fp)

if country != "" or gender != "":
    for userID in genderdata:
        if genderdata[userID]["country"] in merge:
            genderdata[userID]["country"] = merge[genderdata[userID]["country"]]

    delIDs = set()
    for day in daterange(observed_start, observed_end):
        if str(day) in weekdata:
            for userID in weekdata[str(day)]:
                if userID not in genderdata:
                    delIDs.add(userID)

    for userID in delIDs:
        for day in daterange(observed_start, observed_end):
            if str(day) in weekdata:
                if userID in weekdata[str(day)]:
                    del weekdata[str(day)][userID]

cnt = 1 # index of current week
if not userlevel:
    for day in daterange(observed_start, observed_end):
        if str(day) in weekdata and str(day) != str(changedate):
            x.append(cnt)
            y.append(weekdata[str(day)]["RW"])
            if day > changedate and change_cnt == -1:
                change_cnt = cnt
            cnt += 1
        if str(day) in weekdata and str(day) == str(changedate):
            change_cnt = cnt
            print()
            print(str(change_cnt) + ": " + str(day) + " (excluded week as cut point for treatment)")
            cnt += 1
else:
    for day in daterange(observed_start, observed_end):
        if str(day) in weekdata and str(day) != str(changedate):
            for userID in weekdata[str(day)]:
                if country == "" or genderdata[userID]["country"] == country:
                    if gender == "" or genderdata[userID]["gender"] == gender:
                        x.append(cnt)
                        y.append(weekdata[str(day)][userID]["RW"])
            cnt += 1
        if str(day) in weekdata and str(day) == str(changedate):
            change_cnt = cnt
            print()
            print(str(change_cnt) + ": " + str(day) + " (excluded week as cut point for treatment)")
            cnt += 1

data = pd.DataFrame({'y': y, 'x': x})

#bandwidth_opt = rdd.optimal_bandwidth(data['y'], data['x'], cut=change_cnt)
#logging.info("Optimal bandwidth:" + str(bandwidth_opt))

data_rdd = rdd.truncated_data(data, 'x', bandwidth, cut=change_cnt)

print()
print("Number of observations per week in this model: ")
print(data_rdd["x"].value_counts())
print()
print()
model = rdd.rdd(data_rdd, 'x', 'y', cut=change_cnt)
print()
print(model.fit().summary())
print()
log_endtime = datetime.datetime.now()
log_runtime = (log_endtime - log_starttime)
logging.info("Total runtime: " + str(log_runtime))


from tkinter import *
import traceback
from tkinter.scrolledtext import ScrolledText

CODEC = 'utf8'

# XXX This should import the "markov" module.
# XXX All changes made here should be copied.

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

class MarkovDemo:

    def __init__(self, master):
        self.prompt_size = Label(master, anchor=W, text='Encode Word Size')
        self.prompt_size.pack(side=TOP, fill=X)

        self.size_entry = Entry(master)
        self.size_entry.insert(0, '8')
        self.size_entry.pack(fill=X)

        self.prompt_plain = Label(master, anchor=W, text='Plaintext Characters')
        self.prompt_plain.pack(side=TOP, fill=X)

        self.plain_entry = Entry(master)
        self.plain_entry.insert(0, '""')
        self.plain_entry.pack(fill=X)

        self.showframe = Frame(master)
        self.showframe.pack(fill=X, anchor=W)

        self.showvar = StringVar(master)
        self.showvar.set("encode")

        self.showfirstradio = Radiobutton(self.showframe,
                                          text="Encode Plaintext",
                                          variable=self.showvar,
                                          value="encode",
                                          command=self.reevaluate)
        self.showfirstradio.pack(side=LEFT)

        self.showallradio = Radiobutton(self.showframe,
                                        text="Decode Cyphertext",
                                        variable=self.showvar,
                                        value="decode",
                                        command=self.reevaluate)
        self.showallradio.pack(side=LEFT)

        self.inputbox = ScrolledText(master, width=60, height=10, wrap=WORD)
        self.inputbox.pack(fill=BOTH, expand=1)

        self.dynamic_var = IntVar()
        self.dynamic_box = Checkbutton(master, variable=self.dynamic_var,
                                       text='Dynamic Evaluation',
                                       offvalue=False, onvalue=True,
                                       command=self.reevaluate)
        self.dynamic_box.pack()

        self.output = Label(master, anchor=W, text="This is your output:")
        self.output.pack(fill=X)

        self.outbox = ScrolledText(master, width=60, height=10, wrap=WORD)
        self.outbox.pack(fill=BOTH, expand=1)

        self.inputbox.bind('<Key>', self.reevaluate)

        def select_all(event=None):
            event.widget.tag_add(SEL, 1.0, 'end-1c')
            event.widget.mark_set(INSERT, 1.0)
            event.widget.see(INSERT)
            return 'break'
        self.inputbox.bind('<Control-Key-a>', select_all)
        self.outbox.bind('<Control-Key-a>', select_all)
        self.inputbox.bind('<Control-Key-/>', lambda event: 'break')
        self.outbox.bind('<Control-Key-/>', lambda event: 'break')
        self.outbox.config(state=DISABLED)

    def reevaluate(self, event=None):
        if event is not None:
            if event.char == '':
                return
        if self.dynamic_var.get():
            text = self.inputbox.get(1.0, END)[:-1]
            if len(text) < 10:
                return
            text = text.replace('\n \n', '\n\n')
            mode = self.showvar.get()
            assert mode in ('decode', 'encode'), 'Bad mode!'
            if mode == 'encode':
                # Encode Plaintext
                try:
                    # Evaluate the plaintext characters
                    plain = self.plain_entry.get()
                    if plain:
                        PC = eval(self.plain_entry.get())
                    else:
                        PC = ''
                        self.plain_entry.delete(0, END)
                        self.plain_entry.insert(0, '""')
                    # Evaluate the word size
                    size = self.size_entry.get()
                    if size:
                        XD = int(size)
                        while grid_size(text, XD, PC) > 1 << 20:
                            XD -= 1
                    else:
                        XD = 0
                        grid = 0
                        while grid <= 1 << 20:
                            grid = grid_size(text, XD, PC)
                            XD += 1
                        XD -= 1
                    # Correct the size and encode
                    self.size_entry.delete(0, END)
                    self.size_entry.insert(0, str(XD))
                    cyphertext, key, prime = encrypt_str(text, XD, PC)
                except:
                    traceback.print_exc()
                else:
                    buffer = ''
                    for block in key:
                        buffer += repr(block)[2:-1] + '\n'
                    buffer += repr(prime)[2:-1] + '\n\n' + cyphertext
                    self.outbox.config(state=NORMAL)
                    self.outbox.delete(1.0, END)
                    self.outbox.insert(END, buffer)
                    self.outbox.config(state=DISABLED)
            else:
                # Decode Cyphertext
                try:
                    header, cypher = text.split('\n\n', 1)
                    lines = header.split('\n')
                    for index, item in enumerate(lines):
                        try:
                            lines[index] = eval('b"' + item + '"')
                        except:
                            lines[index] = eval("b'" + item + "'")
                    plain = decrypt_str(cypher, tuple(lines[:-1]), lines[-1])
                except:
                    traceback.print_exc()
                else:
                    self.outbox.config(state=NORMAL)
                    self.outbox.delete(1.0, END)
                    self.outbox.insert(END, plain)
                    self.outbox.config(state=DISABLED)
        else:
            text = self.inputbox.get(1.0, END)[:-1]
            text = text.replace('\n \n', '\n\n')
            mode = self.showvar.get()
            assert mode in ('decode', 'encode'), 'Bad mode!'
            if mode == 'encode':
                try:
                    XD = int(self.size_entry.get())
                    PC = eval(self.plain_entry.get())
                    size = grid_size(text, XD, PC)
                    assert size
                except:
                    pass
                else:
                    buffer = 'Grid size will be:\n' + convert(size)
                    self.outbox.config(state=NORMAL)
                    self.outbox.delete(1.0, END)
                    self.outbox.insert(END, buffer)
                    self.outbox.config(state=DISABLED)

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

import random
CRYPT = random.SystemRandom()

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

# This section includes functions that
# can test the required key and bootstrap.

# sudoko_key
#  - should be a proper "markov" key
def _check_sudoku_key(sudoku_key):
    # Ensure key is a tuple with more than one item.
    assert isinstance(sudoku_key, tuple), '"sudoku_key" must be a tuple'
    assert len(sudoku_key) > 1, '"sudoku_key" must have more than one item'
    # Test first item.
    item = sudoku_key[0]
    assert isinstance(item, bytes), 'first item must be an instance of bytes'
    assert len(item) > 1, 'first item must have more than one byte'
    assert len(item) == len(set(item)), 'first item must have unique bytes'
    # Test the rest of the key.
    for obj in sudoku_key[1:]:
        assert isinstance(obj, bytes), 'remaining items must be of bytes'
        assert len(obj) == len(item), 'all items must have the same length'
        assert len(obj) == len(set(obj)), \
               'remaining items must have unique bytes'
        assert len(set(item)) == len(set(item).union(set(obj))), \
               'all items must have the same bytes'

# boot_strap
#  - should be a proper "markov" bootstrap
#  - we will call this a "primer"
# sudoko_key
#  - should be a proper "markov" key
def _check_boot_strap(boot_strap, sudoku_key):
    assert isinstance(boot_strap, bytes), '"boot_strap" must be a bytes object'
    assert len(boot_strap) == len(sudoku_key) - 1, \
           '"boot_strap" length must be one less than "sudoku_key" length'
    item = sudoku_key[0]
    assert len(set(item)) == len(set(item).union(set(boot_strap))), \
           '"boot_strap" may only have bytes found in "sudoku_key"'

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

# This section includes functions capable
# of creating the required key and bootstrap.

# bytes_set should be any collection of bytes
#  - it should be possible to create a set from them
#  - these should be the bytes on which encryption will follow
# word_size
#  - this will be the size of the "markov" chains program uses
#  - this will be the number of dimensions the "grid" will have
#  - one less character will make up bootstrap (or primer)
def make_sudoku_key(bytes_set, word_size):
    key_set = set(bytes_set)
    blocks = []
    for block in range(word_size):
        blocks.append(bytes(CRYPT.sample(key_set, len(key_set))))
    return tuple(blocks)

# sudoko_key
#  - should be a proper "markov" key
def make_boot_strap(sudoku_key):
    block = sudoku_key[0]
    return bytes(CRYPT.choice(block) for byte in range(len(sudoku_key) - 1))

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

# This section contains functions needed to
# create the multidimensional encryption grid.

# sudoko_key
#  - should be a proper "markov" key
def make_grid(sudoku_key):
    grid = expand_array(sudoku_key[0], sudoku_key[1])
    for block in sudoku_key[2:]:
        grid = expand_array(grid, block)
    return grid

# grid
#  - should be an X dimensional grid from make_grid
# block_size
#  - comes from length of one block in a sudoku_key
def make_decode_grid(grid, block_size):
    cache = []
    for part in range(0, len(grid), block_size):
        old = grid[part:part+block_size]
        new = [None] * block_size
        key = sorted(old)
        for index, byte in enumerate(old):
            new[key.index(byte)] = key[index]
        cache.append(bytes(new))
    return b''.join(cache)

# grid
#  - should be an X dimensional grid from make_grid
# block
#  - should be a block from a sudoku_key
#  - should have same unique bytes as the expanding grid
def expand_array(grid, block):
    cache = []
    grid_size = len(grid)
    block_size = len(block)
    for byte in block:
        index = grid.index(bytes([byte]))
        for part in range(0, grid_size, block_size):
            cache.append(grid[part+index:part+block_size])
            cache.append(grid[part:part+index])
    return b''.join(cache)

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

# The first three functions can be used to check an encryption
# grid. The eval_index function is used to evaluate a grid cell.

# grid
#  - grid object to be checked
#  - grid should come from the make_grid function
#  - must have unique bytes along each axis
# block_size
#  - comes from length of one block in a sudoku_key
#  - this is the length of one edge along the grid
#  - each axis is this many unit long exactly
# word_size
#  - this is the number of blocks in a sudoku_key
#  - this is the number of dimensions in a grid
#  - this is the length needed to create a needed markon chain
def check_grid(grid, block_size, word_size):
    build_index(grid, block_size, word_size, [])

# create an index to access the grid with
def build_index(grid, block_size, word_size, index):
    for number in range(block_size):
        index.append(number)
        if len(index) == word_size:
            check_cell(grid, block_size, word_size, index)
        else:
            build_index(grid, block_size, word_size, index)
        index.pop()

# compares the contents of a cell along each grid axis
def check_cell(grid, block_size, word_size, index):
    master = eval_index(grid, block_size, index)
    for axis in range(word_size):
        for value in range(block_size):
            if index[axis] != value:
                copy = list(index)
                copy[axis] = value
                slave = eval_index(grid, block_size, copy)
                assert slave != master, 'Cell not unique along axis!'

# grid
#  - grid object to be accessed and evaluated
#  - grid should come from the make_grid function
#  - must have unique bytes along each axis
# block_size
#  - comes from length of one block in a sudoku_key
#  - this is the length of one edge along the grid
#  - each axis is this many unit long exactly
# index
#  - list of coordinates to access the grid
#  - should be of length word_size
#  - should be of length equal to number of dimensions in the grid
def eval_index(grid, block_size, index):
    offset = 0
    for power, value in enumerate(reversed(index)):
        offset += value * block_size ** power
    return grid[int(offset)]

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

# The following functions act as a suite that can ultimately
# encrpyt strings, though other functions can be built from them.

# bytes_obj
#  - the bytes to encode
# byte_map
#  - byte tranform map for inserting into the index
# grid
#  - X dimensional grid used to evaluate markov chains
# index
#  - list that starts the index for accessing grid (primer)
#  - it should be of length word_size - 1
# block_size
#  - length of each edge in a grid
def _encode(bytes_obj, byte_map, grid, index, block_size):
    cache = bytes()
    index = [0] + index
    for byte in bytes_obj:
        if byte in byte_map:
            index.append(byte_map[byte])
            index = index[1:]
            cache += bytes([eval_index(grid, block_size, index)])
        else:
            cache += bytes([byte])
    return cache, index[1:]

# bytes_obj
#  - the bytes to encode
# sudoko_key
#  - should be a proper "markov" key
#  - this key will be automatically checked for correctness
# boot_strap
#  - should be a proper "markov" bootstrap
def encrypt(bytes_obj, sudoku_key, boot_strap):
    _check_sudoku_key(sudoku_key)
    _check_boot_strap(boot_strap, sudoku_key)
    # make byte_map
    array = sorted(sudoku_key[0])
    byte_map = dict((byte, value) for value, byte in enumerate(array))
    # create two more arguments for encode
    grid = make_grid(sudoku_key)
    index = list(map(byte_map.__getitem__, boot_strap))
    # run the actual encoding algorithm and create reversed map
    code, index = _encode(bytes_obj, byte_map, grid, index, len(sudoku_key[0]))
    rev_map = dict(reversed(item) for item in byte_map.items())
    # fix the boot_strap and return the results
    boot_strap = bytes(rev_map[number] for number in index)
    return code, boot_strap

# string
#  - should be the string that you want encoded
# word_size
#  - length you want the markov chains to be of
# plain_chars
#  - characters that you do not want to encrypt
def encrypt_str(string, word_size, plain_chars=''):
    byte_obj = string.encode(CODEC, 'ignore')
    encode_on = set(byte_obj).difference(set(plain_chars.encode()))
    sudoku_key = make_sudoku_key(encode_on, word_size)
    boot_strap = make_boot_strap(sudoku_key)
    cyphertext = encrypt(byte_obj, sudoku_key, boot_strap)[0]
    # return encrypted string, key, and original bootstrap
    return cyphertext.decode(CODEC, 'ignore'), sudoku_key, boot_strap

def grid_size(string, word_size, plain_chars):
    encode_on = set(string.encode()).difference(set(plain_chars.encode()))
    return len(encode_on) ** word_size

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

# The following functions act as a suite that can ultimately
# decrpyt strings, though other functions can be built from them.

# bytes_obj
#  - the bytes to encode
# byte_map
#  - byte tranform map for inserting into the index
# grid
#  - X dimensional grid used to evaluate markov chains
# index
#  - list that starts the index for accessing grid (primer)
#  - it should be of length word_size - 1
# block_size
#  - length of each edge in a grid
def _decode(bytes_obj, byte_map, grid, index, block_size):
    cache = bytes()
    index = [0] + index
    for byte in bytes_obj:
        if byte in byte_map:
            index.append(byte_map[byte])
            index = index[1:]
            decoded = eval_index(grid, block_size, index)
            index[-1] = byte_map[decoded]
            cache += bytes([decoded])
        else:
            cache += bytes([byte])
    return cache, index[1:]

# bytes_obj
#  - the bytes to decode
# sudoko_key
#  - should be a proper "markov" key
#  - this key will be automatically checked for correctness
# boot_strap
#  - should be a proper "markov" bootstrap
def decrypt(bytes_obj, sudoku_key, boot_strap):
    _check_sudoku_key(sudoku_key)
    _check_boot_strap(boot_strap, sudoku_key)
    # make byte_map
    array = sorted(sudoku_key[0])
    byte_map = dict((byte, value) for value, byte in enumerate(array))
    # create two more arguments for decode
    grid = make_grid(sudoku_key)
    grid = make_decode_grid(grid, len(sudoku_key[0]))
    index = list(map(byte_map.__getitem__, boot_strap))
    # run the actual decoding algorithm and create reversed map
    code, index = _decode(bytes_obj, byte_map, grid, index, len(sudoku_key[0]))
    rev_map = dict(reversed(item) for item in byte_map.items())
    # fix the boot_strap and return the results
    boot_strap = bytes(rev_map[number] for number in index)
    return code, boot_strap

# string
#  - should be the string that you want decoded
# word_size
#  - length you want the markov chains to be of
# plain_chars
#  - characters that you do not want to encrypt
def decrypt_str(string, sudoku_key, boot_strap):
    byte_obj = string.encode(CODEC, 'ignore')
    plaintext = decrypt(byte_obj, sudoku_key, boot_strap)[0]
    # return encrypted string, key, and original bootstrap
    return plaintext.decode(CODEC, 'ignore')

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

def convert(number):
    "Convert bytes into human-readable representation."
    assert 0 < number < 1 << 110, 'Number Out Of Range'
    ordered = reversed(tuple(format_bytes(partition_number(number, 1 << 10))))
    cleaned = ', '.join(item for item in ordered if item[0] != '0')
    return cleaned

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

def partition_number(number, base):
    "Continually divide number by base until zero."
    div, mod = divmod(number, base)
    yield mod
    while div:
        div, mod = divmod(div, base)
        yield mod

def format_bytes(parts):
    "Format partitioned bytes into human-readable strings."
    for power, number in enumerate(parts):
        yield '{} {}'.format(number, format_suffix(power, number))

def format_suffix(power, number):
    "Compute the suffix for a certain power of bytes."
    return (PREFIX[power] + 'byte').capitalize() + ('s' if number != 1 else '')

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

PREFIX = ' kilo mega giga tera peta exa zetta yotta bronto geop'.split(' ')

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

if __name__ == '__main__':
    root = Tk()
    root.title('Markov Demo 1')
    demo = MarkovDemo(root)
    root.mainloop()


from knapsack_data_abstract import *

"""
Brute force algorithm to explore all possible combinations of items in order to
pick the most optimal solution.
Here we have a search tree implamentation whereby nodes represent the knapsack
with different combinations of items.

* 1.The tree is built top down starting with the root and the first element is
    selected from the items_to_be_considered.
* 2.The left child denotes the consequences of taking an item the right
    explores not taking that item.
* 3.We then recursively reapply the process to the non left childern.
* 4.We than evaluate and choose the node with the higest value within the set
    constraints.

*****************************NOTE*********************************************
We do not actually build the search tree instead the local variable result
records the best solution so far.
"""
def max_value(items_to_consider, available_weight):
    if items_to_consider == [] or available_weight == 0:
        result = (0, ())
    elif items_to_consider[0].get_weight() > available_weight:
        #Explore right branch only
        result = max_value(items_to_consider[1:], available_weight)
    else:
        next_item = items_to_consider[0]
        #Explore left branch
        with_value, with_to_take = max_value(items_to_consider[1:],
                                     available_weight - next_item.get_weight())
        with_value += next_item.get_value()
        #Explore right branch
        without_value, without_to_take = max_value(items_to_consider[1:],
                                                   available_weight)
        #Choose better branch
        if with_value > without_value:
            result = (with_value, with_to_take + (next_item,))
        else:
            result = (without_value, without_to_take)
    return result

"""
Modification of max_value function to add memoization for problem sets with
overlapping subproblems.
"""

def fast_max_value(items_to_consider, available_weight, memo = {}):
    # len(items_to_consider) => this is a compact way of representing the items
    # left to be considered as items are removed from the front and so by
    # knowing the lenght we by default know the items remaining.
    if (len(items_to_consider), available_weight) in memo:
        result = memo[(len(items_to_consider), available_weight)]
    elif items_to_consider == [] or available_weight == 0:
        result = (0, ())
    elif items_to_consider[0].get_weight() > available_weight:
        #Explore right branch only
        result = fast_max_value(items_to_consider[1:], available_weight, memo)
    else:
        next_item = items_to_consider[0]
        #Explore left branch
        with_value, with_to_take = fast_max_value(items_to_consider[1:],
                                     available_weight - next_item.get_weight(),
                                            memo)
        with_value += next_item.get_value()
        #Explore right branch
        without_value, without_to_take = fast_max_value(items_to_consider[1:],
                                                   available_weight, memo)
        #Choose better branch
        if with_value > without_value:
            result = (with_value, with_to_take + (next_item,))
        else:
            result = (without_value, without_to_take)
    memo[(len(items_to_consider), available_weight)] = result
    return result

"""
************************************TEST UNIT ******************************************
"""

def test(items, constraint, algorithm, print_items=True):
    value, taken = algorithm(items, constraint)
    if print_items:
        print(f'Total value of items take is {value}')
        for item in taken:
            print(f'{item}')

if __name__ == '__main__':
    items = ['ball', 'watch', 'hat', 'bat', 'TV', 'couch', 'jacket']
    values = [10, 100, 10, 15, 450, 500, 125]
    weights = [100, 100, 200, 300, 1230, 1000, 100]
    collection = build_items(items, values, weights)
    test(collection, 750, max_value)
    test(collection, 750, fast_max_value)


import time
from umodbus.tcp import TCP as ModbusTCPMaster
import network

# ===============================================
# connect to a network
station = network.WLAN(network.STA_IF)
if station.active() and station.isconnected():
    station.disconnect()
    time.sleep(1)
station.active(False)
time.sleep(1)
station.active(True)

# station.connect('SSID', 'PASSWORD')
station.connect('Fusion Automate', 'Fusion_Automate')
time.sleep(1)

while True:
    print('Waiting for WiFi connection...')
    if station.isconnected():
        print(f'Connected to WiFi, Pico W IP : {station.ifconfig()[0]}')
        break
    time.sleep(2)
# ===============================================

# TCP Slave setup
port = 502            # port to listen to
slave_addr = 1        # bus address of modbus_client
starting_addr = 0     # starting addres of register
register_qty = 5      # number of regsiter to read

# IP Address of Modbus TCP Server
ip = '192.168.29.221'

# Setup Modbus TCP Client
modbus_client = ModbusTCPMaster(slave_ip=ip,slave_port=port,timeout=5)
print(f'Requesting data from Modbus TCP Server at {ip}:{port}')

# READ HREGS
register_value = modbus_client.read_holding_registers(slave_addr=slave_addr,starting_addr=starting_addr,register_qty=register_qty)
print('Status of HREG from {} to {} : {}'.format(starting_addr,starting_addr + register_qty, register_value))


import os

print(os.getcwd())
os.chdir(
    "c:\\Users\\sigur\\OneDrive - Imperial College London\\[01] MEng project\\[03] Computer calculators"
)
print(os.getcwd())
import numpy as np

testArray = np.array([[2, 1], [3, 4]])

import os

print(os.getcwd())

from tc_python import *
import numpy as np
from matplotlib import pyplot as plt
import datetime

batch_2_alloys = [
    {"Ti": 38.0, "V": 15.0, "Nb": 23.0, "Hf": 24.0},
    {"Ti": 25.0, "V": 25.0, "Nb": 25.0, "Hf": 25.0},
    {"Ti": 12.0, "V": 13.0, "Nb": 16.0, "Mo": 24.0, "Ta": 20.0, "W": 15.0},
    {"Ti": 16.7, "V": 16.7, "Nb": 16.7, "Mo": 16.7, "Ta": 16.7, "W": 16.7},
    {"V": 23.0, "Cr": 31.0, "Mo": 17.0, "Hf": 29.0},
    {"V": 25.0, "Cr": 25.0, "Mo": 25.0, "Hf": 25.0},
    {"Ti": 11.0, "Zr": 40.0, "Hf": 49.0},
    {"Ti": 33.0, "Zr": 33.0, "Hf": 33.0},
    {"Ti": 50.0, "V": 20.0, "Nb": 30.0},
    {"Ti": 33.0, "V": 33.0, "Nb": 33.0},
    {"Ti": 49.0, "V": 19.0, "Hf": 32.0},
    {"Ti": 33.0, "V": 33.0, "Hf": 33.0},
]

def DictionaryToAlloyShorthand(AlloyDict):
    AlloyDictKeys = list(AlloyDict.keys())

    shorthand = ""
    for key in AlloyDictKeys:
        shorthand += str(key) + str(AlloyDict[key])

    return shorthand

def estimate_liquidus_solidus(alloys, Databases=["TCHEA2"]):
    alloysShorthand = []

    LiquidusTempK = []
    SolidusTempK = []
    deltaT = []

    with TCPython() as session:
        for Database in Databases:
            for alloy in alloys:
                alloyKeys = list(alloy.keys())
                print(alloyKeys)
                system = session.select_database_and_elements(
                    Database, alloyKeys
                ).get_system()

                calc = system.with_property_model_calculation(
                    "Liquidus and Solidus Temperature"
                )

                for i in range(len(alloyKeys) - 1):
                    calc.set_composition(alloyKeys[i], alloy[alloyKeys[i]])

                result = calc.calculate()

                LiquidusTempK.append(result.get_value_of("Liquidus temperature"))
                SolidusTempK.append(result.get_value_of("Solidus temperature"))
                alloysShorthand.append(DictionaryToAlloyShorthand(alloy))

            LiquidusTempC = np.array(LiquidusTempK) - 273.14
            SolidusTempC = np.array(SolidusTempK) - 273.14
            deltaT = LiquidusTempC - SolidusTempC

            solidus_liquidus_array = np.array(
                [
                    alloysShorthand,
                    LiquidusTempK,
                    LiquidusTempC,
                    SolidusTempK,
                    SolidusTempC,
                    deltaT,
                ]
            )

    return np.save(
        f"Solidus Liquidus Data{alloys}_{Databases}_17oct23.npy", solidus_liquidus_array
    )

estimate_liquidus_solidus(batch_2_alloys)


import argparse
import os

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm

from dataset import UNetDataset
from model import UNet, DiceLoss

# set environment parser
Parser = argparse.ArgumentParser()
Parser.add_argument("-b", "--batch_size", default=10, type=int, help="batch size")
Parser.add_argument("-d", "--device", default="cpu", type=str, help="device")
Parser.add_argument("-e", "--epochs", default=100, type=int, help="training epochs")
Parser.add_argument("-l", "--lr", default=0.0005, type=float, help="learning rate")
Parser.add_argument("-s", "--save_path", default="runs", type=str, help="save path")
Parser.add_argument("-w", "--num_workers", default=8, type=int, help="number of workers")

# general train process
def train(model, dataloader, criterion, optimizer, device, train):
    if train:
        model.train()
        print("training model")
    else:
        model.eval()
        print("testing model")
    running_loss = 0
    process_bar = tqdm(enumerate(dataloader), total=len(dataloader))

    for batch_idx, (data, labels) in process_bar:
        data, labels = data.to(device), labels.to(device)
        if train:
            optimizer.zero_grad()
        outputs = model(data)
        loss = criterion(outputs, labels)
        if train:
            loss.backward()
            optimizer.step()
        running_loss += loss.item()

    epoch_loss = running_loss / len(dataloader)

    return epoch_loss

if __name__ == "__main__":
    args = Parser.parse_args()

    train_dataset = UNetDataset(40, '2d', True)
    test_dataset = UNetDataset(10, '2d', False)

    # Define the sizes of the training, validation, and test sets

    train_dataloader = DataLoader(dataset=train_dataset, batch_size=args.batch_size,
                                  num_workers=args.num_workers)
    test_dataloader = DataLoader(dataset=test_dataset, batch_size=args.batch_size,
                                  num_workers=args.num_workers)

    device = args.device
    if device == "cuda" and not torch.cuda.is_available():
        device = "cpu"
    elif device == "cuda":
        device = "cuda:0"

    model = UNet(1)
    model.to(device)

    criterion = DiceLoss()
    optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=0.001)
    writer = SummaryWriter()

    best = 100
    best_epoch = -1
    for epoch in range(args.epochs):
        loss = train(model, train_dataloader, criterion, optimizer, device, True)
        test_loss = train(model, test_dataloader, criterion, optimizer,
                                         device, False)

        writer.add_scalar("Training Loss", loss, epoch)
        writer.add_scalar("Test Loss", test_loss, epoch)

        print(f"Epoch: {args.epochs}/{epoch + 1}, Train_loss: {loss}, Test_loss: {test_loss}")
        save_root = args.save_path
        if best > test_loss:
            best_epoch = epoch
            best = test_loss
            torch.save(model.state_dict(), os.path.join(save_root, "best.pth"))
            print(f"best epoch: {epoch + 1}")

        writer.close()

    print(f"best_loss: {test_loss}, best epoch: {best_epoch + 1}")


from django.urls import path
from . import views

urlpatterns = [
    path('html/', views.employeeDataView),
    path('json/', views.employeeDataJsonView),
    path('django/', views.employeeDataDjangoJsonView),
    path('class/', views.JSONdata.as_view(), name="class_based_view"),
    path('mixins/', views.JsonDataWithMixinView.as_view(), name="using_mixins"),
]


"""Base GRR module class. GRR modules should extend it."""
import abc
import tempfile
import time

from grr_api_client import api as grr_api
from grr_api_client import errors as grr_errors

from dftimewolf.lib import module

class GRRBaseModule(module.BaseModule):
  """Base module for GRR hunt and flow modules.

  Attributes:
    output_path (str): path to store collected artifacts.
    grr_api: GRR HTTP API client.
    grr_url: GRR HTTP URL.
    reason (str): justification for GRR access.
    approvers: list of GRR approval recipients.
  """

  _CHECK_APPROVAL_INTERVAL_SEC = 10

  def __init__(self, state, name=None, critical=False):
    """Initializes a GRR hunt or flow module.

    Args:
      state (DFTimewolfState): recipe state.
      name (Optional[str]): The module's runtime name.
      critical (Optional[bool]): True if the module is critical, which causes
          the entire recipe to fail if the module encounters an error.
    """
    super(GRRBaseModule, self).__init__(state, name=name, critical=critical)
    self.reason = None
    self.grr_api = None
    self.grr_url = None
    self.approvers = None
    self.output_path = None

  # pylint: disable=arguments-differ
  def SetUp(
      self, reason, grr_server_url, grr_username, grr_password, approvers=None,
      verify=True):
    """Initializes a GRR hunt result collector.

    Args:
      reason (str): justification for GRR access.
      grr_server_url (str): GRR server URL.
      grr_username (str): GRR username.
      grr_password (str): GRR password.
      approvers (Optional[str]): comma-separated GRR approval recipients.
      verify (Optional[bool]): True to indicate GRR server's x509 certificate
          should be verified.
    """
    grr_auth = (grr_username, grr_password)
    self.approvers = []
    if approvers:
      self.approvers = [item.strip() for item in approvers.split(',')]
    self.grr_api = grr_api.InitHttp(api_endpoint=grr_server_url,
                                    auth=grr_auth,
                                    verify=verify)
    self.grr_url = grr_server_url
    self.output_path = tempfile.mkdtemp()
    self.reason = reason

  # TODO: change object to more specific GRR type information.
  def _WrapGRRRequestWithApproval(
      self, grr_object, grr_function, *args, **kwargs):
    """Wraps a GRR request with approval.

    This method will request the approval if not yet granted.

    Args:
      grr_object (object): GRR object to create the eventual approval on.
      grr_function (function): GRR function requiring approval.
      args (list[object]): Positional arguments that are to be passed
          to `grr_function`.
      kwargs (dict[str, object]): keyword arguments that are to be passed
          to `grr_function`.

    Returns:
      object: return value of the execution of grr_function(*args, **kwargs).
    """
    approval_sent = False
    approval_url = None

    while True:
      try:
        return grr_function(*args, **kwargs)

      except grr_errors.AccessForbiddenError as exception:
        self.logger.info('No valid approval found: {0!s}'.format(exception))
        # If approval was already sent, just wait a bit more.
        if approval_sent:
          self.logger.info('Approval not yet granted, waiting {0:d}s'.format(
              self._CHECK_APPROVAL_INTERVAL_SEC))
          self.logger.info(approval_url)
          time.sleep(self._CHECK_APPROVAL_INTERVAL_SEC)
          continue

        # If no approvers were specified, abort.
        if not self.approvers:
          message = ('GRR needs approval but no approvers specified '
                     '(hint: use --approvers)')
          self.ModuleError(message, critical=True)

        # Otherwise, send a request for approval
        approval = grr_object.CreateApproval(
            reason=self.reason, notified_users=self.approvers)
        approval_sent = True
        approval_url = ('{0:s}/#/users/{1:s}/approvals/client/{2:s}/{3:s}'.
                        format(self.grr_url, approval.username,
                               approval.client_id,
                               approval.approval_id))
        self.logger.info(
            '{0!s}: approval request sent to: {1!s} (reason: {2:s})'.format(
                grr_object, self.approvers, self.reason))

  @abc.abstractmethod
  def Process(self):
    """Processes input and builds the module's output attribute.

    Modules take input information and process it into output information,
    which can in turn be ingested as input information by other modules.
    """


from typing import Callable
from utils.solution import Solution

def part1(input: list[str]) -> int:
    rotated = list(zip(*input[::-1]))
    width = len(rotated[0])
    height = len(rotated)
    gamma = ['0'] * height
    epsilon = ['0'] * height

    for i in range(height):
        bits = rotated[i]
        if bits.count('1') > (width / 2):
            gamma[i] = '1'
            epsilon[i] = '0'
        else:
            gamma[i] = '0'
            epsilon[i] = '1'

    gamma = int(''.join(gamma), 2)
    epsilon = int(''.join(epsilon), 2)
    return gamma * epsilon

def part2(input: list[str]) -> int:
    rotated = list(zip(*input[::-1]))
    width = len(rotated[0])
    height = len(rotated)
    oxygen_indices = range(width)
    co2_indices = range(width)

    def filter_rating(bits: tuple, indices: list[int], get_match_bit: Callable) -> list[int]:
        match_bit = get_match_bit([c for j, c in enumerate(bits) if j in indices])
        return [j for j in indices if input[j][i] == match_bit]

    for i in range(height):
        if len(oxygen_indices) > 1:
            oxygen_indices = filter_rating(reversed(rotated[i]), oxygen_indices,
                lambda filtered_bits: '1' if filtered_bits.count('1') >= (len(filtered_bits) / 2) else '0')
        if len(co2_indices) > 1:
            co2_indices = filter_rating(reversed(rotated[i]), co2_indices,
                lambda filtered_bits: '0' if filtered_bits.count('0') <= (len(filtered_bits) / 2) else '1')

    oxygen_generator_rating = int(input[oxygen_indices[0]], 2)
    co2_scrubber_rating = int(input[co2_indices[0]], 2)

    return oxygen_generator_rating * co2_scrubber_rating

solution = Solution(3, part1, part2, (198, 230))
solution.run()


import maya.cmds as cmds

def CreateSpiral(height, degreeStep, NrOffBalls, radius):
    '''
    CreateSpiral(float height, float degreeStep, int NrOffBalls, float radius)
    creates a spiral of balls
    '''
    degrees = 0
    h = height/NrOffBalls
    for i in range(NrOffBalls):
        thisName = "SpiralSphere_%s" % i
        parts = cmds.sphere(name=thisName, pivot=[radius, h*i, 0])
        transform = parts[0]
        rotY = transform + ".rotateY"
        cmds.setAttr(rotY, degrees)
        degrees += degreeStep
        degrees = degrees%360

def CreateSpiralWindow():
    '''
    creates window for creating spiral, with ui to change variables
    '''
    window = cmds.window( title="Create Spiral", widthHeight=(200, 300))
    cmds.columnLayout( columnAttach=('both', 5), rowSpacing=5,adjustableColumn=True)
    height = cmds.floatFieldGrp( numberOfFields=1, label='height', value1=10.0)
    degreeStep = cmds.floatFieldGrp( numberOfFields=1, label='degreeStep', value1=30.0)
    NrOffBalls = cmds.intFieldGrp( numberOfFields=1, label='NrOffBalls', value1=20)
    radius = cmds.floatFieldGrp( numberOfFields=1, label='radius', value1=3)

    def click(value):
        doCreateSpiral(height, degreeStep, NrOffBalls, radius)

    cmds.button( label='Create Spiral!', command=click )

    closeCmd = 'cmds.deleteUI("%s", window=True)' % window
    cmds.button( label='Close', command=closeCmd )

    cmds.showWindow( window )

def doCreateSpiral(height, degreeStep, NrOffBalls, radius):

    heightVal = cmds.floatFieldGrp(height, query=True, value1=True)
    degreeStepVal = cmds.floatFieldGrp(degreeStep, query=True, value1=True)
    NrOffBallsVal = cmds.intFieldGrp(NrOffBalls, query=True, value1=True)
    radiusVal = cmds.floatFieldGrp(radius, query=True, value1=True)

    CreateSpiral(heightVal, degreeStepVal, NrOffBallsVal, radiusVal)


# -*- encoding: utf-8 -*-
import os, sys
import ycm_core

#SCRIPT_FILE = os.path.abspath(__file___)
#SCRIPT_DIR = os.path.dirname(SCRIPT_FILE)
SCRIPT_DIR = os.getcwd()

# These are the compilation flags that will be used in case there's no
# compilation database set (by default, one is not set).
# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.

include_dirs = [
    'src',
    'lua/src',
    'boost-process',
]

if sys.platform.startswith('win32'):
    include_dirs.extend([
        'c:/Python34/Include',
        "c:\\mingw\\x32-4.8.1-posix-dwarf-rev5\\mingw32\\lib\\gcc\\i686-w64-mingw32\\4.8.1\\include\\c++\\i686-w64-mingw32",
        "c:\\mingw\\x32-4.8.1-posix-dwarf-rev5\\mingw32\\lib\\gcc\\i686-w64-mingw32\\4.8.1\\include\\c++",
        "c:\\mingw\\x32-4.8.1-posix-dwarf-rev5\\mingw32\\lib\\gcc\\i686-w64-mingw32\\4.8.1\\include",
        "c:\\mingw\\x32-4.8.1-posix-dwarf-rev5\\mingw32\\i686-w64-mingw32\\include",
        "c:\\LLVM-3.4.svn\\lib\\clang\\3.4\\include",
    ])
elif sys.platform.startswith('darwin'):
    include_dirs.extend([
        '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1',
        '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/5.0/include',
        '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include',
        '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include',
        '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/System/Library/Frameworks',
        '/Users/hotgloupi/local/lib/c++/v1',
        '/usr/lib/c++/v1',
        '/usr/local/include'
    ])
elif sys.platform.startswith('linux'):
    for gcc_version in ['4.8', '4.7']:
        include_dirs.extend([
            '/usr/include/c++/%s' % gcc_version,
            '/usr/include/i386-linux-gnu/c++/%s' % gcc_version,
            '/usr/include/c++/%s/backward' % gcc_version,
            '/usr/lib/gcc/i686-linux-gnu/%s/include' % gcc_version,
            '/usr/local/include',
            '/usr/lib/gcc/i686-linux-gnu/%s/include-fixed' % gcc_version,
            '/usr/include/i386-linux-gnu',
            '/usr/include'
        ])

flags = [
    '-Wall',
    '-Wextra',
    '-std=c++11',
    '-x', 'c++',
    '-include', 'boost/test/unit_test.hpp'
]

print(include_dirs)
for d in include_dirs:
    flags.append('-I')
    flags.append(d)

if sys.platform.startswith('darwin'):
    flags.append('-stdlib=libc++')

# Set this to the absolute path to the folder (NOT the file!) containing the
# compile_commands.json file to use that instead of 'flags'. See here for
# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html
#
# Most projects will NOT need to set this to anything; you can just change the
# 'flags' list of compilation flags. Notice that YCM itself uses that approach.
compilation_database_folder = ''

if compilation_database_folder:
  database = ycm_core.CompilationDatabase( compilation_database_folder )
else:
  database = None

def DirectoryOfThisScript():
  return os.path.dirname( os.path.abspath( __file__ ) )

def MakeRelativePathsInFlagsAbsolute( flags, working_directory ):
  if not working_directory:
    return list( flags )
  new_flags = []
  make_next_absolute = False
  path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]
  for flag in flags:
    new_flag = flag

    if make_next_absolute:
      make_next_absolute = False
      if not flag.startswith( '/' ):
        new_flag = os.path.join( working_directory, flag )

    for path_flag in path_flags:
      if flag == path_flag:
        make_next_absolute = True
        break

      if flag.startswith( path_flag ):
        path = flag[ len( path_flag ): ]
        new_flag = path_flag + os.path.join( working_directory, path )
        break

    if new_flag:
      new_flags.append( new_flag )
  return new_flags

def FlagsForFile( filename, **kw):
  if database:
    # Bear in mind that compilation_info.compiler_flags_ does NOT return a
    # python list, but a "list-like" StringVec object
    compilation_info = database.GetCompilationInfoForFile( filename )
    final_flags = MakeRelativePathsInFlagsAbsolute(
      compilation_info.compiler_flags_,
      compilation_info.compiler_working_dir_ )

    # NOTE: This is just for YouCompleteMe; it's highly likely that your project
    # does NOT need to remove the stdlib flag. DO NOT USE THIS IN YOUR
    # ycm_extra_conf IF YOU'RE NOT 100% YOU NEED IT.
    try:
      final_flags.remove( '-stdlib=libc++' )
    except ValueError:
      pass
  else:
    relative_to = DirectoryOfThisScript()
    final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to )

  return {
    'flags': final_flags,
    'do_cache': True
  }


"""
Hanwei Wang
Time: 24-2-2020 8:27
Contact: hanwei_wang_94@outlook.com
Naming standard:
    name of a class: AbcdAbcd
    name of a method/function: abcdabcd
    name of a variable: abcd_abcd
    name of a instantiation: abcd_abcd
    # in English is the comments
"""

from Webapp import create_app

if __name__== '__main__':
    app = create_app()
    print(app.root_path)
    app.run(debug = False, port=800)


def test12():
    print("test12 begins")
    print("test12 ends")
    return 3
def test34():
    print("test34 begins")
    print("test34 ends")
    return 1
def test56():
    print("test56 begins")
    print("test56 ends")
    return 2
def test78(x):
    x.append(1)
    return 1
def main():
    i = 227 % 27
    if i % 4 == 1:
        test12()
    elif i % 4 == 2:
        test34()
    elif i % 4 == 3:
        test56()
    else:
        test12()
    # testing exec order
    x = []
    if test78(x) > 1:
        print(1)
    elif test78(x) > 2:
        print(2)
    elif len(x) > 1:
        print(3)

main()


from tokenize import Double

a = int(input("Введите чило a:"))
b = int(input("Введите число b:"))
arg1 = a%b
arg2 = a//b # не стал приводить к float, т.к. целочисленное деление
print(f"Остаток от деления = {arg1} \n Целочисленное деление = {arg2}")


import requests
import time
import os

os.system('cls')

filename = "urllist.txt"
output_file = "output.txt"
aranacak_yazi = "wp-submit"

with open(filename, 'r') as file, open(output_file, 'w') as out:
    lines = file.readlines()
    for line in lines:
        url = line.strip()
        try: # YANLIIIIIIIIIIIIIIIŞ
            r = requests.get(url+"/wp-login.php")
            if r.status_code == 200:

                if aranacak_yazi in r.content.decode('latin-1'):
                    out.write("{}\n".format(url.split("wp")[0])) # SİLMEEEEEEEEEEEZ
                    print("Belirtilen yazı {} adresinde mevcut: {}".format(url, aranacak_yazi))
                else:
                    print("Belirtilen yazı {} adresinde mevcut değil: {}".format(url, aranacak_yazi))
            else:
                print("URL {} ziyaret edilemedi".format(url))
        except:
            print("Can't Connect The Server !")


import dns.resolver

from spiderfoot import SpiderFootEvent, SpiderFootPlugin

class sfp_yandexdns(SpiderFootPlugin):

    meta = {
        'name': "Yandex DNS",
        'summary': "Check if a host would be blocked by Yandex DNS",
        'flags': [""],
        'useCases': ["Investigate", "Passive"],
        'categories': ["Reputation Systems"],
        'dataSource': {
            'website': "https://yandex.com/",
            'model': "FREE_NOAUTH_UNLIMITED",
            'references': [
                "https://tech.yandex.com/"
            ],
            'favIcon': "https://yastatic.net/iconostasis/_/tToKamh-mh5XlViKpgiJRQgjz1Q.png",
            'logo': "https://yastatic.net/iconostasis/_/tToKamh-mh5XlViKpgiJRQgjz1Q.png",
            'description': "Yandex is a technology company that builds intelligent products and services powered by machine learning. "
            "Our goal is to help consumers and businesses better navigate the online and offline world. "
            "Since 1997, we have delivered world-class, locally relevant search and information services.",
        }
    }

    # Default options
    opts = {
    }

    # Option descriptions
    optdescs = {
    }

    results = None

    def setup(self, sfc, userOpts=dict()):
        self.sf = sfc
        self.results = self.tempStorage()

        for opt in list(userOpts.keys()):
            self.opts[opt] = userOpts[opt]

    # What events is this module interested in for input
    def watchedEvents(self):
        return ["INTERNET_NAME", "AFFILIATE_INTERNET_NAME", "CO_HOSTED_SITE"]

    # What events this module produces
    # This is to support the end user in selecting modules based on events
    # produced.
    def producedEvents(self):
        return ["MALICIOUS_INTERNET_NAME", "MALICIOUS_AFFILIATE_INTERNET_NAME",
                "MALICIOUS_COHOST"]

    # Query Yandex DNS "safe" servers
    # https://dns.yandex.com/advanced/
    def queryAddr(self, qaddr):
        res = dns.resolver.Resolver()
        res.nameservers = ["77.88.8.88", "77.88.8.2"]

        try:
            addrs = res.resolve(qaddr)
            self.sf.debug(f"Addresses returned: {addrs}")
        except Exception:
            self.sf.debug(f"Unable to resolve {qaddr}")
            return False

        if addrs:
            return True
        return False

    # Handle events sent to this module
    def handleEvent(self, event):
        eventName = event.eventType
        srcModuleName = event.module
        eventData = event.data
        parentEvent = event
        resolved = False

        self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")

        if eventData in self.results:
            return

        self.results[eventData] = True

        # Check that it resolves first, as it becomes a valid
        # malicious host only if NOT resolved by Yandex.
        try:
            if self.sf.resolveHost(eventData):
                resolved = True
        except Exception:
            self.sf.debug(f"Unable to resolve {eventData}")
            return

        if not resolved:
            return

        found = self.queryAddr(eventData)

        if found:
            return

        if eventName == "CO_HOSTED_SITE":
            typ = "MALICIOUS_COHOST"
        else:
            typ = "MALICIOUS_" + eventName

        evt = SpiderFootEvent(typ, "Blocked by Yandex [" + eventData + "]",
                              self.__name__, parentEvent)
        self.notifyListeners(evt)

# End of sfp_yandexdns class


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

# In[3]:

import cv2
import mediapipe as mp
import time
import TrackingModule as tm
import numpy as np

def thumb_closed():

    p4=np.array((lmList[4][1],lmList[4][2]))
    p5=np.array((lmList[5][1],lmList[5][2]))
    p0=np.array((lmList[0][1],lmList[0][2]))

    dist1 = np.linalg.norm(p4-p0)
    dist2 = np.linalg.norm(p5-p0)

    if dist1<dist2:
#         cv2.putText(img, "Thumb Closed", (400, 200), cv2.FONT_HERSHEY_PLAIN, 2,
#                 (0, 0, 255), 2)
        return True

def index_closed():

    p8=np.array((lmList[8][1],lmList[8][2]))
    p6=np.array((lmList[6][1],lmList[6][2]))
    p0=np.array((lmList[0][1],lmList[0][2]))

    dist1 = np.linalg.norm(p8-p0)
    dist2 = np.linalg.norm(p6-p0)

    if dist1<dist2:
#         cv2.putText(img, "Index Closed", (400, 400), cv2.FONT_HERSHEY_PLAIN, 2,
#                 (0, 0, 255), 2)
        return True

def middle_closed():

    p12=np.array((lmList[12][1],lmList[12][2]))
    p10=np.array((lmList[10][1],lmList[10][2]))
    p0=np.array((lmList[0][1],lmList[0][2]))

    dist1 = np.linalg.norm(p12-p0)
    dist2 = np.linalg.norm(p10-p0)

    if dist1<dist2:
#         cv2.putText(img, "Middle Closed", (400, 350), cv2.FONT_HERSHEY_PLAIN, 2,
#                 (0, 0, 255), 2)
        return True

def ring_closed():

    p16=np.array((lmList[16][1],lmList[16][2]))
    p14=np.array((lmList[14][1],lmList[14][2]))
    p0=np.array((lmList[0][1],lmList[0][2]))

    dist1 = np.linalg.norm(p16-p0)
    dist2 = np.linalg.norm(p14-p0)

    if dist1<dist2:
#         cv2.putText(img, "Ring Closed", (400, 300), cv2.FONT_HERSHEY_PLAIN, 2,
#                 (0, 0, 255), 2)
        return True

def pinky_closed():

    p20=np.array((lmList[20][1],lmList[20][2]))
    p18=np.array((lmList[18][1],lmList[18][2]))
    p0=np.array((lmList[0][1],lmList[0][2]))

    dist1 = np.linalg.norm(p20-p0)
    dist2 = np.linalg.norm(p18-p0)

    if dist1<dist2:
#         cv2.putText(img, "Pinky Closed", (400, 250), cv2.FONT_HERSHEY_PLAIN, 2,
#                 (0, 0, 255), 2)
        return True

pTime = 0
cTime = 0
cap = cv2.VideoCapture(0)
detector = tm.handDetector()
while True:
    success, img = cap.read()
    img = detector.findHands(img, draw=False)
    lmList = detector.findPosition(img, draw=False)
    if len(lmList) != 0:

        if index_closed() and middle_closed() and ring_closed() and pinky_closed() and not thumb_closed():
            if lmList[4][2] < lmList[0][2]:
                cv2.putText(img, "Thumbs Up", (450, 200), cv2.FONT_HERSHEY_PLAIN, 2,
                    (0, 0, 255), 2)
            else :
                cv2.putText(img, "Thumbs Down", (400, 200), cv2.FONT_HERSHEY_PLAIN, 2,
                    (0, 0, 255), 2)

        if not(index_closed()) and not(middle_closed()) and ring_closed() and pinky_closed() and thumb_closed():
            cv2.putText(img, "V", (450, 200), cv2.FONT_HERSHEY_PLAIN, 4,
                (0, 0, 255), 2)
        if index_closed() and not(middle_closed()) and not ring_closed() and not pinky_closed() and thumb_closed():
            cv2.putText(img, "Okay", (450, 200), cv2.FONT_HERSHEY_PLAIN, 2,
                (0, 0, 255), 2)

    cTime = time.time()
    fps = 1 / (cTime - pTime)
    pTime = cTime

    cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3,
                (255, 0, 255), 3)

    cv2.imshow("Image", img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
            break

# After the loop release the cap object
cap.release()
# Destroy all the windows
cv2.destroyAllWindows()

# In[ ]:


import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
import sys

with open('../confusions/confusion-densenet121-19042018.txt','rb') as f:
    m = np.loadtxt(f)

# Constants used
img_width, img_height = 224, 224
test_data_dir = '../places205-subset27\\test'

validation_datagen = ImageDataGenerator(rescale = 1./255)
validation_generator = validation_datagen.flow_from_directory(
    test_data_dir,
    target_size=(img_width, img_height),
    batch_size=25)

classes = len(validation_generator.class_indices)
categories = classes * ['']

for key, value in validation_generator.class_indices.items():
    categories[value] = key

for x in range(0, 27):
    for y in range(0, 27):
        m[x,y] = int(float("{0:.2f}".format(m[x,y]/399 *100)))

m = m.astype(int)
df_cm = pd.DataFrame(m, categories, categories)
sn.set(font_scale=0.9)#for label size
sn.heatmap(df_cm, cmap="BuPu", annot=True, annot_kws={"size": 14})# font size

plt.show()


from django.urls import path, include
from rest_framework.routers import DefaultRouter

from fobbage.quizes.views import (
    SessionViewSet, FobbitViewSet,
    AnswerViewSet, QuizViewSet, ActiveFobbitViewSet, BluffViewSet,
    GuessViewSet, QuestionViewSet,
)

router = DefaultRouter()
router.register(r'quizes', QuizViewSet, basename='quiz')
router.register(r'questions', QuestionViewSet, basename='question')
router.register(r'fobbits', FobbitViewSet, basename='fobbit')
router.register(r'sessions', SessionViewSet, basename='session')
router.register(r'bluffs', BluffViewSet, basename='bluff')
router.register(r'guesses', GuessViewSet, basename='guess')
router.register(r'answers', AnswerViewSet, basename='answer')
router.register(
    r'active_fobbits', ActiveFobbitViewSet, basename='active_fobbit')

urlpatterns = [
    path('', include(router.urls)),
]


import names
import random
import string

DB_NAME = 'Wydawnictwo'

class Autor(object):
    TABLE = 'Autor'
    DEGREE = ['B.Sc', 'M.Sc', 'Ph.D', 'Prof']
    BIOGRAPHY = ['BIOGRAFIA NUMER 1', 'BIOGRAFIA NUMER 2', 'BIOGRAFIA NUMER 3', 'BIOGRAFIA NUMER 4', 'BIOGRAFIA NUMER 5']

    def __init__(self, db, cursor):
        self.db = db
        self.cursor = cursor

    def addQuotes(self, val):
        return "'" + str(val) + "'"

    def randomString(self, stringLength=10):
        """Generate a random string of fixed length """
        letters = string.ascii_lowercase
        return ''.join(random.choice(letters) for i in range(stringLength))

    def getMaxIntVal(self, table, column):
        self.cursor.execute("SELECT MAX(" + column + ") FROM " + DB_NAME + '.' + table)
        result = self.cursor.fetchall()
        for i in result:
            if(i[0] == None):
                return 0
            maxIntVal = (int)(i[0])
        return maxIntVal

    def genSqlInsertAutor(self):
        id = self.getMaxIntVal(self.TABLE, 'idAutor') + 1
        val = []
        sql = "INSERT INTO `Wydawnictwo`.`Autor` (`idAutor`, `Nazwisko`, `Imie`, `Stopień`, `Biografia`) VALUES (%s, %s, %s, %s, %s)";
        name = names.get_first_name()
        surname = names.get_last_name()
        val.append(id)
        val.append(self.addQuotes(surname))
        val.append(self.addQuotes(name))
        val.append(self.addQuotes(random.choice(self.DEGREE)))
        val.append(self.addQuotes(random.choice(self.BIOGRAPHY)))
        sql = sql % tuple(val)
        return sql

    def insertAutor(self, number):
        for i in range(number):
            self.cursor.execute(self.genSqlInsertAutor())
            self.db.commit()

    def deleteAllValues(self):
        self.cursor.execute("DELETE FROM " + DB_NAME + "." + self.TABLE)
        self.db.commit()


import time

from behave import *
from Utilities import configReader
from features.pageobjects.CollaboratorPartnerView import CollaboratorPartnerView
from features.pageobjects.CommonFunctions import CommonFunctions
from features.pageobjects.CustomersPage import CustomersPage
from features.pageobjects.DashboardPage import DashboardPage
from features.pageobjects.LoginPage import LoginPage
from features.pageobjects.Navbar import Navbar
from features.pageobjects.PartnersPage import PartnersPage
from features.pageobjects.ProjectsPage import ProjectsPage
from features.pageobjects.SettingPage import SettingsPage

@when("I click new partner button")
def iClickNewPartnerButton(context):
    PartnersPage(context.driver).iClickNewPartnersButton()
    PartnersPage(context.driver).waitNewPartnerModalVisible()

@when("I click from partner page history of shipments navigation button")
def iCLickFromParnetPageHistoryOfShipmentsNavigationButton(context):
    PartnersPage(context.driver).iClickShipmentsHistoryButton()
    PartnersPage(context.driver).waitShipmentsHistoryPageDisplayed()

@when("I click from partner page view partners navigation button")
def iCLickFromParnetPageViewPartnersNavigationButton(context):
    PartnersPage(context.driver).iClickViewPartnersButton()
    PartnersPage(context.driver).waitViewPartnersPageDisplayed()

@when("Verify from shipments history row '{row}' and column '{column}' holds the value: '{value}'")
def iCLickFromParnetPageHistoryOfShipmentsNavigationButton(context, row, column, value):
    actualCell = PartnersPage(context.driver).getFromShipmentHistoryNumberElementCellNumber(row, column)
    actualCell = actualCell.replace("\n", " ")
    # value=value+context.token
    assert actualCell == value

@when("I choose in view partner page the partner with name '{name}'")
def iCLickFromParnetPageHistoryOfShipmentsNavigationButton(context,name):
    PartnersPage(context.driver).choosePartnerWithName(name)
    CollaboratorPartnerView(context.driver).waitPageVisible()

@when("I fill new partners form with the following details")
def iFillNewPartnersFormWithTheFollowingDetails(context):
    PartnersPage(context.driver).iSetNewPartnerNameToBe(context.table[0]['Value'])
    if context.table[1]['Value'] == 'click':
        PartnersPage(context.driver).iSetNewPartnerAddressFromMapClick()
    else:
        PartnersPage(context.driver).iSetNewPartnerAddressTobe(context.table[1]['Value'])
    if context.table[2]['Value'] == 'random':
        email=CommonFunctions(context.driver).get_random_string(10) + "@gmail.com"
    else:
        email=context.table[2]['Value']
    context.email=email

    PartnersPage(context.driver).iSetNewPartnerEmailAddressTobe(email)
    PartnersPage(context.driver).iSetNewPartnerTaxIDToBe(context.table[3]['Value'])
    PartnersPage(context.driver).iSetNewPartnerTaxOfficeToBe(context.table[4]['Value'])

@when("I set in new partner modal new partner name to be '{name}'")
def iSetInNewpartnerModalNewPartnerNameToBe(context, name):
    PartnersPage(context.driver).iSetNewPartnerNameToBe(name)

@when("I set in new partner modal new partner address to be '{address}'")
def iSetInNewpartnerModalNewPartnerAddressToBe(context, address):
    PartnersPage(context.driver).iSetNewPartnerAddressTobe(address)

@when("I set in new partner modal new email address to be '{address}'")
def iSetInNewpartnerModalNewPartnerAddressToBe(context, address):
    PartnersPage(context.driver).iSetNewPartnerEmailAddressTobe(address)

@when("I set in new partner modal new partner tax id to be '{address}'")
def iSetInNewpartnerModalNewPartnerTaxIDToBe(context, address):
    PartnersPage(context.driver).iSetNewPartnerTaxIDToBe(address)

@when("I set in new partner modal new partner tax office to be '{address}'")
def iSetInNewpartnerModalNewPartnerTaxOfficeToBe(context, address):
    PartnersPage(context.driver).iSetNewPartnerTaxOfficeToBe(address)

@when("I click new partner modal submit button")
def iClickNewPartnerModalSubmitButton(context):
    PartnersPage(context.driver).iClickNewPartnerSubmitButton()
    PartnersPage(context.driver).waitNewPartnerModalNOTVisible()


# -*- coding: utf-8 -*-
"""
Created on Tue Jul 23 15:20:02 2019

@author: slw
"""
import numpy as np
import xlrd
import xlwt

def excel2m(path):
    data = xlrd.open_workbook(path)
    table = data.sheets()[0]
    nrows = table.nrows  # 行数
    ncols = table.ncols  # 列数
    datamatrix = np.zeros((nrows, ncols))
    for x in range(ncols):
        cols = table.col_values(x)
        cols1 = np.matrix(cols)  # 把list转换为矩阵进行矩阵操作
        datamatrix[:, x] = cols1 # 把数据进行存储
    return datamatrix

def save(data,path):
    f = xlwt.Workbook()  # 创建工作簿
    sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True)  # 创建sheet
    [h, l] = data.shape  # h为行数，l为列数
    for i in range(h):
        for j in range(l):
            sheet1.write(i, j, data[i, j])
    f.save(path)

#计算5点3阶SG算子的系数矩阵----------------------------------------------
A=np.mat([[1,-2,4,-8],[1,-1,1,-1],[1,0,0,0],[1,1,1,1],[1,2,4,8]])
B=(A*(A.T*A).I)*A.T

#读取并裁剪光谱数据----------------------------------------------------
data=excel2m('C:/Users/slw/Desktop/pyth test/data.xls')
linenum=data.shape[0]
rownum=data.shape[1]
wavenum=data[:,0]
wavenummin=0
wavenummax=0
for i in range(0,linenum):
    if wavenum[i]<800:
        wavenummin=wavenummin+1

for i in range(0,linenum):
    if wavenum[i]<=1800:
        wavenummax=wavenummax+1
newdata=data[wavenummin:wavenummax+1,0:rownum]

#计算新光谱------------------------------------------------------------
new_linenum=newdata.shape[0]
new_rownum=newdata.shape[1]
new_spectra=np.zeros([1001,new_rownum])
for j in range(1,rownum):
    new_spectra[0,j]=B[0]*newdata[0:5,j:j+1]
    new_spectra[1,j]=B[1]*newdata[0:5,j:j+1]
    new_spectra[999,j]=B[3]*newdata[new_linenum-5:new_linenum,j:j+1]
    new_spectra[1000,j]=B[4]*newdata[new_linenum-5:new_linenum,j:j+1]
    for i in range(2,999):
        error=np.zeros([new_linenum,1])
        for p in range(0,new_linenum):
            error[p]=abs(newdata[p,0]-i-800)
        min_error=min(error)
        for q in range(0,new_linenum):
            if (error[q]==min_error):
                min_num=q
        factor=[newdata[min_num-2,j],newdata[min_num-1,j],newdata[min_num,j],newdata[min_num+1,j],newdata[min_num+2,j]]
        factor=(np.matrix(factor)).T
        new_spectra[i,j]=B[2]*factor;

a=np.matrix(np.linspace(800,1800,1001)).T
for i in range(0,a.shape[0]) :
    new_spectra[i,0]=a[i,0]

#归一化光谱--------------------------------------------
for j in range(1,rownum):
    min_data=min(new_spectra[:,j])
    max_data=max(new_spectra[:,j])
    for i in range(0,1001):
        new_spectra[i,j]=(new_spectra[i,j]-min_data)/(max_data-min_data)

save(new_spectra,'C:/Users/slw/Desktop/pyth test/result.xls')


# Perform necessary imports
from bokeh.io import curdoc
from bokeh.plotting import figure

##|----------------
##| Create Plot
##|----------------

# Create a new plot: plot
plot = figure()

# Add a line to the plot
plot.line(x = [1,2,3,4,5], y = [2,5,4,6,7])

# Add the plot to the current document
curdoc().add_root(plot)

##|----------------
##| Create Sliders
##|----------------

# Perform necessary imports
from bokeh.layouts import widgetbox
from bokeh.models import Slider

# Create first slider: slider1
slider1 = Slider(
    title = 'slider1',
    start = 0,
    end = 10,
    step = 0.1,
    value = 2)

# Create second slider: slider2
slider2 = Slider(
    title = 'slider2',
    start = 10,
    end = 100,
    step = 1,
    value = 20)

# Add slider1 and slider2 to a widgetbox
layout = widgetbox(slider1, slider2)

# Add the layout to the current document
curdoc().add_root(layout)


import dpkt
import sys
import struct

def pcap_parser(fname):

    f = open(fname, "rb")
    pcap = dpkt.pcap.Reader(f)
    index = 0

    for _, buf in pcap:
        index = index + 1
        eth = dpkt.ethernet.Ethernet(buf)
        if eth.type == dpkt.ethernet.ETH_TYPE_IP or eth.type == dpkt.ethernet.ETH_TYPE_IP6:
            ip = eth.data

            if eth.type == dpkt.ethernet.ETH_TYPE_IP and ip.p != dpkt.ip.IP_PROTO_RSVP:
                continue
            if eth.type == dpkt.ethernet.ETH_TYPE_IP6 and ip.nxt != dpkt.ip.IP_PROTO_RSVP:
                continue

            data = ip.data  # RSVP object

            # RSVP header is 8 bytes, skip over it
            offset = 8

            # does the INTEGRITY object always follows the RSVP Header?
            length = struct.unpack(">H", data[offset:offset+2])[0]

            # "Object class" is at offset 3 within the "INTEGRITY" object
            object_class = ord(data[offset + 2])

            if object_class != 4:
                continue

            # hash is at offset 20 within the "INTEGRITY" object
            hash_length = length - 20
            h = data[offset+20:][:hash_length]
            if hash_length == 16:
                algo_type = 1
            else:
                algo_type = 2

            # zero-out the hash during hash calculation
            salt = data.replace(h, "\x00" * len(h))
            sys.stdout.write("%s:$rsvp$%d$%s$%s\n" % (index, algo_type, salt.encode("hex"), h.encode("hex")))

    f.close()

if __name__ == "__main__":
    if len(sys.argv) < 2:
        sys.stderr.write("Usage: %s [.pcap files]\n" % sys.argv[0])
        sys.exit(-1)

    for i in range(1, len(sys.argv)):
        pcap_parser(sys.argv[i])


from google.cloud import dialogflow

def detect_intent_texts(project_id, session_id, texts, language_code):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversation."""

    session_client = dialogflow.SessionsClient()
    session_path = session_client.session_path(project_id, session_id)
    conversation_items = []

    for text in texts:
        text_input = dialogflow.TextInput(
            text=text, language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)

        query_result = session_client.detect_intent(
            request={"session": session_path, "query_input": query_input}
        ).query_result

        conversation_items.append(
            {
                'query_text': query_result.query_text,
                'detected_intent': query_result.intent.display_name,
                'confidence': query_result.intent_detection_confidence,
                'fulfillment_text': query_result.fulfillment_text,
            }
        )

    return {
        'session_path': session_path,
        'conversation_items': conversation_items,
        'is_fallback': query_result.intent.is_fallback,
    }


from configparser import ConfigParser
from threading import Thread, Lock
import zmq
import time
import json

class lv(Thread):

    def __init__(self, fileName, port):
        Thread.__init__(self)
        configObj = ConfigParser()
        configObj.read(fileName)

        #Create launch vehicle based on the config file
        lvInfo = configObj["LAUNCH_INFO"]
        self.name = lvInfo["name"]
        self.orbit = int(lvInfo["orbit"])
        self.telemetry = {}

        #Set initial telemetry data
        self.telemetry["altitude"] = 0
        self.telemetry["latitude"] = 0
        self.telemetry["longitude"] = 0
        self.telemetryMutex = Lock()
        self.telemetry["temperature"] = 300
        self.telemetry["timeToOrbit"] = self.orbit/3600 + 10
        self.isLaunched = False
        self.isSending = False
        self.latitudeStep = True
        self.isDeployable = False
        self.isDeOrbited = False
        self.port = port
        self.payload = lvInfo["payloadConfig"]

    #Thread that sends and receives transmissions to and from dsn
    def run(self):
        context = zmq.Context()
        socket = context.socket(zmq.PAIR)
        string = "tcp://localhost:" + str(self.port)
        socket.connect(string)
        while True:
            try:
                #receive signal from DSN
                message = (socket.recv(flags=zmq.NOBLOCK)).decode("utf-8")
            except zmq.Again as e:
                message = ""

            # Initiate launch
            if(message == "Launch"):
                self.isLaunched = True

            #Start sending telemetry data
            if(message == "StartT"):
                self.isSending = True

            #Stop sending telemetry data
            if(message == "StopT"):
                self.isSending = False

            #De orbit the launch vehicle
            if(message == "DeOrbit"):
                self.isDeOrbited = True
                self.isSending = True

            #If launch vehicle is in sending mode
            if self.isSending:
                self.telemetryMutex.acquire()
                try:
                    #Send telemetry data to dsn
                    data = json.dumps(self.telemetry)
                    socket.send_json(data)
                finally:
                    self.telemetryMutex.release()

            #Update telemetry data
            self.updateTelemetry()

            if(self.isLaunched and self.telemetry["timeToOrbit"] == 0):
                self.isDeployable = True

            #Repeat loop every second (so telemetry data is sent every second)
            time.sleep(1)
            if self.isDeOrbited:
                break

    #This function updates telemetry data every second so that it can be sent to dsn
    def updateTelemetry(self):
        if self.isLaunched:
            # print(self.name + ": in here")
            self.telemetryMutex.acquire()
            try:
                self.telemetry["altitude"] += 60
                if(self.telemetry["altitude"] > self.orbit):
                    self.telemetry["altitude"] = self.orbit

                self.telemetry["timeToOrbit"] -= 1
                if(self.telemetry["timeToOrbit"] < 0):
                    self.telemetry["timeToOrbit"] = 0

                if(self.latitudeStep == True):
                    self.telemetry["latitude"] += 1.5
                else:
                    self.telemetry["latitude"] -= 1.5
                if(self.telemetry["latitude"] > 90):
                    self.telemetry["latitude"] = 90
                    self.latitudeStep = not self.latitudeStep
                if(self.telemetry["latitude"] < -90):
                    self.telemetry["latitude"] = -90
                    self.latitudeStep = not self.latitudeStep

                self.telemetry["longitude"] += 1.5
                if(self.telemetry["longitude"] >= 180):
                    self.telemetry["longitude"] = -180

                if(self.telemetry["altitude"] < 300):
                    self.telemetry["temperature"] -= 20
                elif(self.telemetry["altitude"] > 300 and self.telemetry["altitude"] < 1000):
                    self.telemetry["temperature"] = (self.telemetry["altitude"] - 300) * 100 / 60
                else:
                    self.telemetry["temperature"] -= 50

                if(self.telemetry["temperature"] < 5):
                    self.telemetry["temperature"] = 5

            finally:
                self.telemetryMutex.release()


from envs import GraphSamplingEnv
from agents import BaseAgent

def train_test_agent():
  M = 10
  env = GraphSamplingEnv(max_samples=M)

  num_train_graphs = 10

  agent = BaseAgent(env=env)
  agent.learn(num_train_graphs)
  agent.test()

if __name__ == "__main__":
  train_test_agent()


import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import argparse
from model import NFNet
from optim import SGD_AGC

# Hyper-parameters
parser = argparse.ArgumentParser(description='NFNet Training')
parser.add_argument('--variant', default='F0', type=str, choices=['F0', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7'], help='NFNet variants')
parser.add_argument('--lr', default=0.1, type=float, help='the learning rate')
parser.add_argument('--num_epochs', default=200, type=int, help='the number of the epochs')
parser.add_argument('--batch_size', default=128, type=int, help='batch sizes')
args = parser.parse_args()

# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
best_acc = 0

# Image preprocessing modules
transform_train = transforms.Compose([
            transforms.Pad(4),
            transforms.RandomHorizontalFlip(),
            transforms.RandomCrop(32),
            transforms.ToTensor(),
            transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))])

transform_test = transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))])

# CIFAR-10 dataset
train_dataset = torchvision.datasets.CIFAR10(root='./data/', train=True, transform=transform_train, download=True)

test_dataset = torchvision.datasets.CIFAR10(root='./data/', train=False, transform=transform_test)

# Data loader
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=args.batch_size, shuffle=True, num_workers=2)

test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=args.batch_size, shuffle=False, num_workers=2)

# Model
model = NFNet(num_classes=10, variant=args.variant, stochdepth_rate=0.25, alpha=0.2, se_ratio=0.5, activation='gelu').to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = SGD_AGC(named_params=model.named_parameters(), lr=args.lr, momentum=0.9, clipping=0.1, weight_decay=5e-4, nesterov=True)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=200)

# Train the model
def train(epoch):
    model.train()
    for i, (images, labels) in enumerate(train_loader):
        images, labels = images.to(device), labels.to(device)

        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)

        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i + 1) % 100 == 0:
            print ("Epoch [{}/{}], Step [{}/{}] Loss: {:.4f}".format(epoch+1, args.num_epochs, i+1, len(train_loader), loss.item()))

# Test the model
def test(epoch):
    global best_acc
    model.eval()
    with torch.no_grad():
        correct = 0
        total = 0
        for images, labels in test_loader:
            images, labels = images.to(device), labels.to(device)
            outputs = model(images)
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
        print('Epoch [{}/{}], Accuracy of the model on the test images: {} %'.format(epoch+1, args.num_epochs, 100 * correct / total))

    acc = 100 * correct / total
    if acc > best_acc:
        # Save the model checkpoint
        torch.save(model.state_dict(), 'nfnet.ckpt')
        best_acc = acc
        print('Best Accuracy : {} %'.format(best_acc))

for epoch in range(args.num_epochs):
    train(epoch)
    test(epoch)
    scheduler.step()


''' Faça um programa que leia o comprimento do cateto oposto e do cateto adjacenter de um triângulo retângulo e mostre o comprimento da hipotenusa.'''

co = float(input('Digite o valor do cateto oposto: '))
ca = float(input(' Digite o valor do cateto adjacente: '))

'''hipotenusa faz cateto oposto ao ² que é ** 2 x cateto adjacente ² que é ** 2, tudo na raiz quadrada que é ** 1/2'''
hi = (co ** 2 + ca ** 2) ** (1/2)

print('A hipotenusa vai medir {:.2f}'. format(hi))


def saludar():
    """
    (none) -> str
    Saluda al usuario luego de preguntar el nombre

    :return: el nombre ingresado por el usuario
    """
    return input("¿Cual es tu nombre?\n")

#Tres formas de definir str
# comillas simples fugan automaticamente las comillas dobles
cadena_1 = 'Hola "comillas dobles" '
#comillas dobles fugan automaticamente las comillas simples
cadena_2 = "Hola 'comillas simples' "
#comillas triples fugan automaticamente los saltos de linea
cadena_3 = '''Hola
mundo'''#las comillas triples permiten escribir multiples lineas

#note la diferencia en lo que se imprime
print(cadena_1, cadena_2, cadena_3)

#Podemos concatenar cadenas usando el operador +
cadena_concatenada = cadena_1 + cadena_2
print("La cadena concatenada es:",cadena_concatenada)

#Podemos multiplicar nuestras cadenas utilizando el operador *
cadena_multiplicada = cadena_1 * 3
print("la cadena multiplicada es:",cadena_multiplicada)

#Podemos averiguar la longitud de una cadena utlizando la función
#len(str)
longitud = len(cadena_multiplicada)
print("La longitud de la cadena es",longitud)

#Podemos fugar usando \
cadena_de_fugas = "\n\t\"\'\\"
print("La cadena de fugas es:",cadena_de_fugas)

#Podemos preguntar si algo esta en la cadena
esta_h = "h" in cadena_1
print("Esta \"h\" en cadena_1:",esta_h)

esta_Ho = "Ho" in cadena_1
print("Esta \"Ho\" en cadena_1:",esta_Ho)

def saludar_2():
    '''
    (none) -> str

    Solicita el nombre, luego el apellido y retorna una cadena con
    los dos separados por un espacio

    :return: el nombre completo
    '''

    #strip() elimina los espacios al comienzo y al final de mi cadena
    nombre = input("¿Cual es su Nombre?\n").strip().lower()

    #lower() convierte la cadena en minusculas
    apellido = input("¿Cual es su Apellido\n").strip().lower()
    return nombre + " " + apellido

#probamos nuestra función saludar
#print("Hola" , saludar())

#probamos nuestra función saludar 2 y escribimos como un titulo
#print("Hola" , saludar_2().title())

#podemos convertir de numeros a cadenas
#print("Hola " + str(2) + "da vez")

print(int("234"))


"""
This file contains constants used by other scripts
"""

# Buttons captions
START = 'Start'
HIT = 'Hit'
STAND = 'Stand'
QUIT = 'Quit'
CREATE_TABLE = 'Create table'

# Keys of data passing between modules
HIT_CARD = 'hit_card'
IMAGE = 'image'
SWITCHER = 'switcher'
CARD = 'card'
SPOT = 'spot'
PLAYER_NUM = 'player_num'
SHOW_MSG = 'show_message'
MSG = 'message'
IS_OVER = 'is_over'
DEALER_CARDS = 'dealer_cards'
DEALER_SPOTS = 'dealer_spots'
PLAYERS_CARDS = 'players_cards'
PLAYERS_SPOTS = 'players_spots'
PLAYERS = 'players'
NEW_GAME = 'new_game'
NEW_GAME_MSG = 'new_game_message'
BOOL = 'boolean'
NUM_PLAYERS = 'num_of_players'
NUM_DECKS = 'num_of_decks'
ERROR = 'error'

# View
SERVER_TITLE = 'Blackjack Server'
TITLE = 'Blackjack-1.0'
DEALER = 'Dealer'
PLAYER = 'Player'
GREEN = 'green'
BLUE = 'blue'
RED = 'red'
BLACK = 'black'
LOST = 'Lost'
TIE = 'Tie'
WON = 'Won'
SCORES = 'Scores'
STATE = 'state'
NOTIFICATIONS = 'Notifications'
ICN_PLUS_PATH = r'images\icons\icn_plus.png'
ICN_MINUS_PATH = r'images\icons\icn_minus.png'

# Client/Server
HEADER = 64
FORMAT = 'utf-8'
DISCONNECT_MSG = '!DISCONNECT!'
DISCONNECTING = 'disconnecting'
MIN_PLAYERS = 1
MAX_PLAYERS = 3
MAX_CLIENTS = 3
MIN_USERNAME_LEN = 4

MAX_CARDS = 5
MIN_BET = 5.0
MAX_BET = 100.0
DEALER_TURN = 'dealer_turn'
GET_RESULTS = 'get_results'
RESULTS = 'results'
PRIZE = 'prize'
BET = 'bet'

# Card's attributes
SUIT = 'suit'
VALUE = 'value'
TEXT = 'text'
REAL_VALUE = 'real_value'
PATH = 'path'
HIGH_VALUE = 'high_value'

# card suits
DIAMONDS = 'diamonds'
CLUBS = 'clubs'
HEARTS = 'hearts'
SPADES = 'spades'

# User
USERNAME = 'username'
USER_MONEY = 'user_money'
STARTER_MONEY_AMOUNT = 1000.0

# guides
GUIDE = 'guide'
SERVER_GUIDE_TEXT = """This is a blackjack server.
Please enter your username,
and select how many players and decks are in the game.
If this is your first time playing,
just choose any username and start to play."""
CLIENT_GUIDE_TEXT = f"""This is a blackjack client.
Press [{START}] * - To start a new game.
Press [{HIT}] ** - To get another card from the dealer (You can get up to {MAX_CARDS} cards).
Press [{STAND}] ** - To finish current player's turn.
Press [{QUIT}] * - To exit from the game.

*   Cannot be clicked during a game!
**  Can be clicked (only) during a game!"""


import json
import os
from pathlib import Path
from dataclasses import asdict, dataclass

@dataclass
class Config:
    SETTINGS_REL_PATH = ".vscode/settings.json"
    SQLTOOLS_KEY = "sqltools.connections"
    SQLTOOLS_USERNAME_KEY = "username"
    USERNAME_ENV_KEY = "NIB_USERNAME"

@dataclass
class SnowflakeConnectionConfig:
    authenticator: str = "externalbrowser"
    warehouse: str = "group_general"
    database: str = "build_prod"
    role: str = "nib_dwh"
    account: str = "ly01550.ap-southeast-2"
    ocsp_fail_open: bool = True
    sqltools_connection_config = [
        {
            "authenticator": authenticator,
            "ocspOptions": {"ocspFailOpen": ocsp_fail_open},
            "snowflakeOptions": {
                "clientSessionKeepAlive": True,
                "clientSessionKeepAliveHeartbeatFrequency": 3600,
                "role": role,
            },
            "previewLimit": 50,
            "driver": "Snowflake",
            "username": "",
            "name": database,
            "database": database,
            "account": account,
            "warehouse": warehouse,
        }
    ]

class VSCodeSettings:
    def __init__(self) -> None:
        self._config = Config()

        # find the settings file
        test_path = Path(".").absolute()
        self._settings_path = None
        if test_path.joinpath(self._config.SETTINGS_REL_PATH).is_file():
            self._settings_path = test_path.joinpath(self._config.SETTINGS_REL_PATH)
        else:
            while test_path != test_path.parent:
                test_path = test_path.parent
                if test_path.joinpath(self._config.SETTINGS_REL_PATH).is_file():
                    self._settings_path = test_path.joinpath(
                        self._config.SETTINGS_REL_PATH
                    )

        # load settings
        if self._settings_path is None:
            raise FileNotFoundError(
                f"Could not find {self._config.SETTINGS_REL_PATH} in any parent directory."
            )
        else:
            with open(self._settings_path, "r") as settings_file:
                self._settings = json.load(settings_file)

        # get the username
        self._username = self._get_sfuser_from_env()
        if self._username is None:
            self._username = self._get_sfuser_from_settings()
        if self._username is None:
            raise RuntimeError(
                "Could not find user name from environment var or settings.json"
            )

    def set_sqltools_username(self, username: str = None) -> None:
        username = self._username if username is None else username

        for connection in self._settings[self._config.SQLTOOLS_KEY]:
            connection[self._config.SQLTOOLS_USERNAME_KEY] = username

    def sqltools_config_exists(self) -> bool:
        return self._settings.get(self._config.SQLTOOLS_KEY) is not None

    def set_sqltools_default(self) -> None:
        self._settings[
            self._config.SQLTOOLS_KEY
        ] = SnowflakeConnectionConfig().sqltools_connection_config

    def save(self) -> None:
        with open(self._settings_path, "w") as settings_file:
            json.dump(self._settings, settings_file, indent=4)

    def _get_sfuser_from_env(self) -> str:
        return os.environ.get(self._config.USERNAME_ENV_KEY)

    def _get_sfuser_from_settings(self) -> str:
        """get the username from the first snowfloke connection in settings.json

        returns: (str) the full nib username or None if no connection config exists
        """
        sfuser = None
        connectionss_config = self._settings.get(self._config.SQLTOOLS_KEY)
        if connectionss_config and (len(connectionss_config) >= 1):
            sfuser = connectionss_config[0].get(self._config.SQLTOOLS_USERNAME_KEY)

        return sfuser

    def get_snowflake_connection_config(
        self, database: str = None, schema: str = None
    ) -> dict:
        connection_config = asdict(SnowflakeConnectionConfig())
        connection_config["user"] = self._username
        if database is not None:
            connection_config["database"] = database
        if schema is not None:
            connection_config["schema"] = schema

        return connection_config