#!/usr/bin/env python
import bitcoinlib
import gmpy2
import argparse

from fastecdsa.ecdsa import verify
from fastecdsa.point import Point
from fastecdsa.curve import secp256k1
from fastecdsa.point import Point
from concurrent.futures import ProcessPoolExecutor
from concurrent.futures import as_completed

signs = [(-1, -1), (-1, 1), (1, -1), (1, 1)]
mask_msb = (1 << 256) - 1
mask_lsb = (1 << 128) - 1

def compute_k(d, r, s, h):
    k = (gmpy2.invert(s, secp256k1.q) * (h + r*d)) % secp256k1.q
    return k

def recover_key_lsb(h, s, r):
    s_inv = [gmpy2.invert(s_i, secp256k1.q) for s_i in s]

    # Original attack
    h1_msb = h[0] >> 128
    h2_msb = h[1] >> 128

    # Test all the 4 sign possibilities for nonces.
    try:
        a_inv = gmpy2.invert(r[0]*s_inv[0] - r[1]*s_inv[1], secp256k1.q)
    except ZeroDivisionError:
        return None
    b = h[0]*s_inv[0] - h[1]*s_inv[1]
    for sign in signs:
        c = (sign[0] * h1_msb - sign[1] * h2_msb) << 128
        d = ((c-b) * a_inv) % secp256k1.q
        k = (sign[0] * s_inv[0] * (h[0] + r[0]*d)) % secp256k1.q
        if k >> 128 == h1_msb:
            print(hex(k))
            print(hex(h1_msb))
            break
        else:
            d = None
    return d

# Recover the key when it was used as the msb of the nonce
def recover_key_msb(h, s, r):
    s_inv = [gmpy2.invert(s_i, secp256k1.q) for s_i in s]
    h1_lsb = h[0] >> 128
    h2_lsb = h[1] >> 128

    # Test all the 4 sign possibilities for nonces.
    try:
        a_inv = gmpy2.invert(r[0]*s_inv[0] - r[1]*s_inv[1], secp256k1.q)
    except ZeroDivisionError:
        return None
    b = h[0]*s_inv[0] - h[1]*s_inv[1]
    for sign in signs:
        c = (sign[0] * h1_lsb - sign[1] * h2_lsb)
        d = ((c-b) * a_inv) % secp256k1.q
        k = (sign[0] * s_inv[0] * (h[0] + r[0]*d)) % secp256k1.q
        if k & mask_lsb == h1_lsb:
            print(hex(k))
            print(hex(h1_lsb))
            break
        else:
            d = None
    return d

def process_batch(file, begin, end):
    results = []
    h_list = []
    s_list = []
    r_list = []
    last_pubkey = None

    with open(args.file, "rb") as blockchain:
        position = begin
        blockchain.seek(begin)
        while position != end:
            l = blockchain.readline()
            if len(l) == 0:
                break
            position += len(l)
            line = l.strip()
            fields = line.split(b";")
            addr, r, s, pubkey_c, txid, message_hash, block_timestamp = fields
            r = int(r, 16)
            s = int(s, 16)
            h = int(message_hash, 16)

            if last_pubkey == pubkey_c:
                s_list.append(s)
                r_list.append(r)
                h_list.append(h)
                dd = recover_key_lsb(h_list, s_list, r_list)
                if dd != None:
                    pubkey = bitcoinlib.keys.Key(pubkey_c.decode(), is_private=False)
                    x = pubkey.public_point()[0]
                    y = pubkey.public_point()[1]
                    Q = Point(x, y, curve=secp256k1)
                    #print(verify((r,s), unhexlify(message_hash) , Q, secp256k1, prehashed=True))
                    print(hex(dd))
                    print(f"Found private key {hex(dd)} for: {fields}")
                    print(int(dd) * secp256k1.G == Q)
                    k1 = compute_k(dd, r_list[0], s_list[0], h_list[0])
                    k2 = compute_k(dd, r_list[1], s_list[1], h_list[1])
                    outline = f"{pubkey_c.decode()},{dd:x},{txid.decode()},{k1:x},{k2:x}\n"
                    results.append(outline)

            h_list = [h]
            s_list = [s]
            r_list = [r]
            last_pubkey = pubkey_c
    return results

if __name__ == "__main__":
    last_pubkey = None
    begin = 0
    end = 0
    transactions = 0
    futures = []
    executor = ProcessPoolExecutor()

    parser = argparse.ArgumentParser()
    parser.add_argument('file', type=str, help='blockchain file')
    parser.add_argument('-o', '--output', type=str, help='output file')
    parser.add_argument('-b', '--batch', type=int, \
					help='batch size')

    args = parser.parse_args()
    results_file = open(args.output, "w")

    with open(args.file, "rb") as blockchain:
        with executor as ex:
            eof = False
            while not eof:
                for i in range(args.batch):
                    l = blockchain.readline()
                    if len(l) == 0:
                        eof = True
                        break

                if not eof:
                    line = l.strip()
                    fields = line.split(b";")
                    addr, r, s, pubkey_c, txid, message_hash, block_timestamp = fields
                    last_pubkey = pubkey_c
                else:
                    break
                # Keep the same keys in the same batch.
                while last_pubkey == pubkey_c and not eof:
                    last_line = blockchain.tell()
                    l = blockchain.readline()
                    if len(l) == 0:
                        eof = True
                        break
                    line = l.strip()
                    fields = line.split(b";")
                    addr, r, s, pubkey_c, txid, message_hash, block_timestamp = fields
                    if last_pubkey != pubkey_c:
                        blockchain.seek(last_line)
                        break

                end = blockchain.tell()
                #results = process_batch(current_batch)
                future = ex.submit(process_batch, args.file, begin, end)
                futures.append(future)
                print(f"The batch submitted {begin}-{end}.")
                begin = end

        for future in as_completed(futures):
            # retrieve the results
            for l in future.result():
                results_file.write(l)

    print(f"Finished {transactions} transactions")
    results_file.close()


import os
import subprocess
import colorama
from colorama import Fore

if os.geteuid() != 0:
    exit(Fore.RED+ "You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting.")
print("")
print(Fore.RED + '''
  ___                 __      __  __   _   ___
 / __|_ __  ___  ___ / _|_  _|  \/  | /_\ / __|
 \__ \ '_ \/ _ \/ _ \  _| || | |\/| |/ _ \ (__
 |___/ .__/\___/\___/_|  \_, |_|  |_/_/ \_\___|
     |_|                 |__/
                              ''' + Fore.GREEN + '''Simple MAC address changer by R00tDev1l''')

print(Fore.WHITE + "")
os.system('ifconfig')
print("")
print(Fore.RED + "These interfaces are currently availabe in your system please pick one of them.")
try:
    print("")
    interface = input(Fore.GREEN + "Please type the interface=>")
    print("")
    new_mac = input(Fore.GREEN + "Please type a new MAC address here=>")
    print("")

    print(Fore.RED + "Changeing MAC address for " + interface + " to " + new_mac)
    print(Fore.WHITE + "")

    subprocess.call("ifconfig " + interface + " down", shell=True)
    subprocess.call("ifconfig " + interface + " hw ether" + new_mac, shell=True)
    subprocess.call("ifconfig " + interface + " up", shell=True)

    print("")
    print(Fore.GREEN + "MAC address for "+ Fore.RED + interface + Fore.GREEN + " has been changed to "+ Fore.RED + new_mac + Fore.GREEN + " successfully.")
except KeyboardInterrupt:
    os.system('exit')


#!/usr/bin/env python

import time

import rospy
import rospkg #for get_path
from gazebo_msgs.srv import SpawnModel
from gazebo_msgs.msg import ModelStates
from std_msgs.msg import Empty
from geometry_msgs.msg import Pose

import signal
import sys

def signal_handler(signal, frame): # ctrl + c -> exit program
        print('You pressed Ctrl+C!')
        sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)

class mason_spawner():
    def __init__(self):
        rospy.init_node('mason_spawner', anonymous=True)
        self.gt_subscriber = rospy.Subscriber('/gazebo/model_states', ModelStates, self.gt_cb)
        self.msg_subscriber = rospy.Subscriber('/spawning_model', Empty, self.msg_cb)
        self.spawner = rospy.ServiceProxy('/gazebo/spawn_sdf_model', SpawnModel)
        self.rate = rospy.Rate(1)

        self.if_cam_spawned=False
        self.if_gz_on=False

    def gt_cb(self, msg):
        if not self.if_gz_on:
            rp = rospkg.RosPack()
            package_path = rp.get_path("khnp_competition")
            f = open(package_path+"/../gazebo_map_for_khnp/common/third_camera/model.sdf",'r')

            self.model_name = rospy.get_param("/third_cam_name", 'third_camera')
            self.model_xml = f.read()
            self.initial_pose = Pose()
            self.initial_pose.orientation.w=1.0
            f.close()
            self.if_gz_on=True

    def msg_cb(self, msg):
        if not self.if_cam_spawned and self.if_gz_on:
            response=self.spawner(self.model_name, self.model_xml, "", self.initial_pose, "world")
            print(response.success)
            print(response.status_message)
            if response.success:
                self.if_cam_spawned=True
                print("Cam spawned!!")

if __name__=='__main__':
    mas = mason_spawner()
    time.sleep(2)
    while True:
        try:
            mas.rate.sleep()
        except (rospy.ROSInterruptException, SystemExit, KeyboardInterrupt):
            sys.exit(0)
        finally:
            if mas.if_cam_spawned:
                break
    sys.exit(0)


import logging
import os
from django.utils.log import DEFAULT_LOGGING

from randevu.conf.boilerplate import BASE_DIR

# log_path = os.path.join(BASE_DIR, 'logs')
# isExist = os.path.exists(log_path)
# if not isExist:
#     os.makedirs(log_path)

logger = logging.getLogger(__name__)

LOG_LEVEL = "INFO"

logging.config.dictConfig({
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "console": {
            "format": "%(asctime)s %(name)-12s %(levelname)-8s %(message)s"
        },
        # "file": {
        #     "format": "%(asctime)s %(name)-12s %(levelname)-8s %(message)s"
        # },
        "django.server": DEFAULT_LOGGING["formatters"]["django.server"]
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "console"
        },
        # "file": {
        #     "level": "INFO",
        #     "class": "logging.handlers.TimedRotatingFileHandler",
        #     "formatter": "file",
        #     "filename": os.path.join(BASE_DIR, "logs/randevu-admin.log"),
        #     'when': 'midnight',
        #     'backupCount': 10,
        # },
        "django.server": DEFAULT_LOGGING["handlers"]["django.server"]
    },
    "loggers": {
        "": {
            "level": "INFO",
            "handlers": [
                "console",
                # "file"
            ],
            "propagate": False
        },
        "apps": {
            "level": "INFO",
            "handlers": [
                "console"
            ],
            "propagate": False
        },
        "django.server": DEFAULT_LOGGING["loggers"]["django.server"]
    }
})


"""
A custom Python format is a subclass of Formatter, with the logic split into
OutputFormatter for outputting to a format, and FormatExtractor for reading
from a format

The parameters it expects are specified in the format.json file.

Note: the name of the class itself is not relevant.

"""

from dataiku.customformat import Formatter, OutputFormatter, FormatExtractor

import base64
import datetime
import json
import logging
import os
import pandas

from tableau_table_reader import TableauTableReader

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format='Plugin: Tableau Hyper API | %(levelname)s - %(message)s')

class MyFormatter(Formatter):

    def __init__(self, config, plugin_config):
        """
        The configuration parameters set up by the user for the formatter instance
        are passed as a json object 'config' to the constructor.
        The static configuration parameters set up by the developer in the optional
        file settings.json at the root of the plugin directory are passed as a json
        object 'plugin_config' to the constructor
        """
        Formatter.__init__(self, config, plugin_config)

    def get_output_formatter(self, stream, schema):
        """
        Return a OutputFormatter for this format
        :param stream: the stream to write the formatted data to
        :param schema: the schema of the rows that will be formatted (never None)
        """
        return MyOutputFormatter(stream, schema)

    def get_format_extractor(self, stream, schema=None):
        """
        Return a FormatExtractor for this format
        :param stream: the stream to read the formatted data from
        :param schema: the schema of the rows that will be extracted. None when the extractor is used to detect the format.
        """
        table_name = self.config['table_name']
        schema_name = self.config['schema_name']
        return MyFormatExtractor(stream, schema, table_name=table_name, schema_name=schema_name)

class MyOutputFormatter(OutputFormatter):
    """
    Writes a stream of rows to a stream in a format. The calls will be:

    * write_header()
    * write_row(row_1)
      ...
    * write_row(row_N)
    * write_footer()

    """

    def __init__(self, stream, schema):
        """
        Initialize the formatter
        :param stream: the stream to write the formatted data to
        """
        OutputFormatter.__init__(self, stream)
        self.schema = schema

    def write_header(self):
        """
        Write the header of the format (if any)
        """
        if self.schema is not None:
            self.stream.write(' ' + base64.b64encode(json.dumps(self.schema['columns'])) + '\n')

    def write_row(self, row):
        """
        Write a row in the format
        :param row: array of strings, with one value per column in the schema
        """
        clean_row = []
        for column_value in row:
            if isinstance(column_value, datetime.datetime):
                clean_row.append(column_value.isoformat())
            elif isinstance(column_value, pandas.Timestamp):
                clean_row.append(column_value.isoformat())
            else:
                clean_row.append(column_value)
        self.stream.write(base64.b64encode(json.dumps(clean_row)) + '\n')

    def write_footer(self):
        """
        Write the footer of the format (if any)
        """
        pass

class MyFormatExtractor(FormatExtractor):
    """
    Read the input format
    """

    def __init__(self, stream, schema, table_name=None, schema_name=None):
        """
        Initialize the extractor
        :param stream: the stream to read the formatted data from
        """
        FormatExtractor.__init__(self, stream)
        self.tableau_reader = TableauTableReader(table_name=table_name, schema_name=schema_name)
        self.tableau_reader.create_tmp_hyper_file()
        self.tableau_reader.read_buffer(stream)
        self.tableau_reader.open_connection()
        self.tableau_reader.read_hyper_columns()

    def read_schema(self):
        """
        Get the schema of the data in the stream, if the schema can be known upfront.
        """
        return self.tableau_reader.read_schema()

    def read_row(self):
        """
        Read one row from the formatted stream
        :returns: a dict of the data (name, value), or None if reading is finished
        """
        return self.tableau_reader.read_row()


import discord
from discord.ext import commands
import os
import json
import pyrebase
from decouple import config

firebase = pyrebase.initialize_app(json.loads(config("FIREBASE")))
db=firebase.database()

class Message_Events(commands.Cog):
    def __init__(self,bot):
        self.bot = bot

    def afk_exists(self,uid):
        try:
            return uid in db.child("AFK").get().val()
        except Exception as e:
            pass

    def remove_afk(self,uid):
        if self.afk_exists(uid):
            db.child("AFK").child(uid).remove()

    def set_afk(self,uid,data):
        db.child("AFK").child(uid).set(data)

    def get_info(self,uid):
        if self.afk_exists(uid):
            d=db.child("AFK").child(uid).get().val()
            return d
        else: return [-1,"error"]

    @commands.Cog.listener()
    async def on_message(self,msg):
        if msg.author.bot:return
        ms=msg.content
        if not ms.lower().startswith('v!afk'):
            guild_id=str(msg.guild.id)
            user_id=str(msg.author.id)
            tag=guild_id+user_id
            if self.afk_exists(tag):
                data=self.get_info(tag)
                self.remove_afk(tag)
                no_more_afk=f"welcome back {msg.author.mention}.\n**{data[1]}**.\nYou were pinged **{data[0]}** times."
                await msg.channel.send(no_more_afk)
                # remove afk here
        for ping in msg.mentions:
            guild_id=str(msg.guild.id)
            user_id=str(ping.id)
            tag=guild_id+user_id
            if self.afk_exists(tag):
                data=self.get_info(tag)
                data[0]+=1
                self.set_afk(tag,data)
                msg_afk=f"**{ping.display_name}** is AFK\n\n{data[1]}"
                await msg.channel.send(msg_afk)
        user=str(msg.author.id)
        prefixes = self.get_prefix(user)
        for pfix in prefixes:
            if msg.content.startswith(pfix):
                msg.content = msg.content.replace(pfix,'v!').replace('v! ','v!')
                await self.bot.process_commands(msg)

    def get_prefix(self,uid):
        pfxs=db.child("PREFIX").child(uid).get().val()
        if pfxs==None:pfxs=[]
        return list(pfxs)

    def add_prefix(self,uid,pf):
        pfxs=db.child("PREFIX").child(uid).get().val()
        if pfxs==None:pfxs=[]
        pfxs.append(pf)
        db.child("PREFIX").child(uid).set(pfxs)

    def remove_prefix(self,uid,pf):
        pfxs=db.child("PREFIX").child(uid).get().val()
        if pfxs==None:pfxs=[]
        else:del pfxs[pfxs.index(pf)]
        db.child("PREFIX").child(uid).set(pfxs)

    @commands.command()
    async def prefix(self,ctx,do='',prfx=''):
        user=str(ctx.author.id)

        if do=='add' and prfx!='':
            self.add_prefix(user,prfx)
            await ctx.send(f"> added custom prefix - {prfx}")
        elif do=='remove' and prfx!='':
            self.remove_prefix(user,prfx)
            await ctx.send(f"> removed custom prefix - {prfx}")
        else:
            e=discord.Embed(title="CUSTOM PREFIX",description=f"add : add a custom prefix\nremove : remove a custom prefix",color=0xFF0055)
            ypfx = ""
            all_pfx=self.get_prefix(str(ctx.author.id))
            if all_pfx==[]: ypfx = "<no prefix set>"
            for each in all_pfx:
                ypfx+=each+"\n"
            e.add_field(name="your prefixes",value=ypfx)
            await ctx.send(embed=e)

    @commands.command()
    async def afk(self,ctx,*,status=' '):
        guild_id=str(ctx.guild.id)
        user=str(ctx.author.id)
        tag=guild_id+user
        data=[0,status]
        self.set_afk(tag,data)
        #e=discord.Embed(title="AFK SET",description=f"{ctx.author.mention} is AFK\n{status}",color=0xFF0055)
        #await ctx.send(embed=e)
        msg=f"{ctx.author.mention} is AFK\n{status}"
        await ctx.send(msg)

def setup(bot):
    bot.add_cog(Message_Events(bot))
    print('---> MESSAGE EVENTS LOADED')


from django.shortcuts import render, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.views.generic import (
    ListView,
    DetailView,
    CreateView,
    UpdateView,
    DeleteView
)
from django.shortcuts import redirect
from .models import Post, Comment
from .forms import CommentForm, PostForm
from django.urls import reverse, reverse_lazy
from django import forms
from pagedown.widgets import PagedownWidget
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from taggit.models import Tag
from django.template.defaultfilters import slugify
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic.dates import MonthArchiveView
import datetime

def is_valid_queryparam(param):
    return param != '' and param is not None

def home(request):
    posts = Post.objects.all()
    tag_search = request.GET.get('tag_search')
    common_tags = Post.tags.most_common()[:4]

    if is_valid_queryparam(tag_search):
        posts = posts.filter(tags__slug=tag_search)

    posts = posts[::-1]
    recent_posts = posts[:4]

    page = request.GET.get('page', 1)

    paginator = Paginator(posts, 3)
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    context = {
        'posts': posts,
        'common_tags': common_tags,
        'recent_posts': recent_posts,
    }
    return render(request, 'blog/home.html', context)

class PostListView2(ListView):
    model = Post
    template_name = 'blog/home.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 4

class PostListView(ListView):
    model = Post
    template_name = 'blog/home2.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 3

    def get_queryset(self):
        return Post.objects.filter(tags__slug=self.kwargs.get('slug'))

class UserPostListView(ListView):
    model = Post
    template_name = 'blog/user_posts.html'  # <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    paginate_by = 5

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user).order_by('-date_posted')

'''
class PostDetailView(DetailView):
    model = Post
'''

def post_detail(request, pk):
    object = get_object_or_404(Post, pk=pk)
    comments = object.comments.filter(Parent__isnull=True)
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            Parent_obj = None
            try:
                Parent_id = int(request.POST.get('Parent_id'))
            except:
                Parent_id = None
            if Parent_id:
                Parent_obj = Comment.objects.get(id=Parent_id)
                if Parent_obj:
                    reply_comment = comment_form.save(commit=False)
                    reply_comment.Parent = Parent_obj
            new_comment = comment_form.save(commit=False)
            new_comment.post = object
            new_comment.author = request.user
            new_comment.save()
            return redirect('blog:post-detail', object.id)

    else:
        comment_form = CommentForm()

    return render(request, 'blog/post_detail.html', {'object': object, 'comments': comments, 'comment_form': comment_form})

'''
class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['title', 'content']
    success_url = reverse_lazy('blog:home')

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)
'''

@login_required
def post_create(request):
    form = PostForm(request.POST or None, request.FILES or None)
    common_tags = Post.tags.most_common()[:4]
    if form.is_valid():
        instance = form.save(commit=False)
        instance.author = request.user
        instance.save()
        form.save_m2m()
        # message success
        #messages.success(request, "Successfully Created")
        return redirect('blog:home')
    context = {
        "form": form,
        "common_tags": common_tags,
    }
    return render(request, "blog/post_form.html", context)

def tagged(request, slug):
    tag = get_object_or_404(Tag, slug=slug)
    # Filter posts by tag name
    posts = Post.objects.filter(tags=tag)
    context = {
        'tag':tag,
        'posts':posts,
    }
    return render(request, "blog/home.html", context)

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    fields = ['title', 'content']
    success_url = reverse_lazy('blog:home')

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

'''
class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Post
    success_url = reverse_lazy('blog:home')

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False
'''

@login_required
def post_delete(request, pk):
    post = get_object_or_404(Post, pk=pk)
    post.delete()
    return redirect('blog:home')


import torch
from .extension import _assert_has_ops

Tensor = torch.Tensor

def lsq(x: Tensor, scale: Tensor, shift: Tensor,
        quant_min: int = 0,
        quant_max: int = 255,
        type_min: int = None,
        type_max: int = None,
        axis: int = 1,
        use_grad_scaling: bool = True,
        grad_scaler: float = 1.,
        is_affine: bool = True,
        is_perchannel: bool = False,
        eval_mode: bool = False,
        init_mode: bool = False) -> Tensor:
    '''
        Pytorch FakeQuantizer Observer with Learned Step Size Quantization(LSQ+) (https://arxiv.org/abs/2004.09576)

        Theory:
            The Pytorch quantization scheme is x_q = round(clamp(x/scale + zero_point,quant_min,quant_max);
                where zero_point is integer and have same type as x_q.

            In the article, however, used another approach: x_q = round(clamp((x - shift)/scale,quant_min,quant_max);
                shift - have float type here. We adapt such scheme via implicit conversion of shift to zero_point

            Following article, LSQ+ emulate the quantization and dequantization of input treating `scale` and `shift` as learnable parameters.

            Forward pass(quantize->dequantize):
               1) Emualate zero_point behaviour zero_point = clamp(-shift/scale, type_min, type_max); where type_min(type_max) is min(max) of quantized type (i.e int8/uint8)
               2) Quantized: x_q = round(clamp(x/scale + zero_point, quant_min, quant_max)
               3) Dequantized: x_r = x_q * scale + shift

            Backward pass:
                Consider, 1) zero_point = clamp(-shift/scale, type_min, type_max);
                          2) x_q = round(clamp(x/scale + zero_point, quant_min, quant_max));

                w.r.t input: 1,  if ((quant_min < x_q) && (x_q < quant_max))
                             0,  otherwise

                w.r.t scale: (x_r - x)/scale, if ((quant_min < x_q) && (x_q < quant_max))
                             quant_min - zero_point,    if x_q <= quant_min
                             quant_max - zero_point,    if x_q >= quant_max

                w.r.t shfit:  0,  if ((quant_min < x_q) && x_q < quant_max))
                              1,  otherwise

        Note! By default in 8-bit assymetric quantization will used: `quant_min` = 0, `quant_max` = 255

        By default the affine quantization is used (defined by `is_affine` flag)
        In case of symmetric(`is_affine`=False), the shift forcible treat as 0 both during backward pass

        Implementation natively support per_tensor(default) and per_channel schemes via `is_perchannel` flag.

        We support parameters initialization mode via `init_mode` flag.
            In original article the authors propose to init `scale` and `shift` for affine case by minimizing: ||x_r-x||F^2
            Instead of using it as additional loss, we incorporate this natively inside code,
            due to this function supposed to be work inside Pytorch Observer class.
        When `init_mode`=True only 'scale' and 'shift' will be updated treating ||x_r-x||F^2 as main loss function.

        Based on article we support scaling of derivatives on `scale` and `shift` on 1/sqrt(n_elements(x)*quant_max)
        (See https://arxiv.org/abs/1902.08153 for details)

        Note! type_min/type_max is stands for numerical limits of used quantized type.
              For Pytorch e.g. quint8 and qint8. They may corresponds to quant_min/quant_max,
              but is not always true, for example for unsigned 7-bit the quant_min == type_min, but quant_min < type_max.

        Arguments:
            x(torch.tensor) - input tensor
            scale(torch.tensor) - what the name said, 1D tensor(dim==1), even in per_tensor case.
            shift(torch.tensor) - what the name said, 1D tensor(dim==1), even in per_tensor case.
            quant_min(int) - lower bound of quantized range. Default: 0 (for assymetric quantization)
            quant_max(int) - upper bound of quantized range. Default: 255.
            type_min(int) - lower bound of quantized type. Default: None (= quant_min)
            type_max(int) - upper bound of quantized type. Default: None (= quant_max)
            axis(int) - dimension for per channel quantization scheme. Default: 1.
            use_grad_scaling(bool) - Apply scale to scale and zero_point gradient. Default: True.
            grad_scaler(float) - additional grad scaler, helps to compensate the learning rate. Default: 1.
            is_affine(bool) - Control assymmetric(true) or symmetric(false) quantization type. Default: true(assymmetric).
            is_perchannel(bool) - Control quantization scheme: per_channel(true) and per_tensor(false). Default: false(per_tensor)
            eval_mode(bool) - Force LSQ work like PyTorch FakeQuantizer(only fake quant) if enabled. Default: false.
            init_mode(bool) - Control parameters initialization(see description above). Default: false(not used)
    '''
    _assert_has_ops()
    if not is_affine:
        assert quant_min <= 0 <= quant_max, 'quantization range must be covered 0 in symmetric quantization'
    type_min = quant_min if type_min is None else type_min
    type_max = quant_max if type_max is None else type_max

    return torch.ops.torchlsq.lsq(x, scale, shift, quant_min, quant_max, type_min, type_max,
                                     axis, use_grad_scaling, grad_scaler, is_affine, is_perchannel,
                                     eval_mode, init_mode)


from builtins import tuple

import requests
import pprint
import json
import time
from flask import Flask, render_template, request
import sqlite3

app = Flask(__name__)

def get_vac(search='ml', per_page=20):
    url = 'https://api.hh.ru/vacancies'
    # search = 'ml'
    # per_page = 20
    lst_vac_for_html = []
    lst = []
    con = sqlite3.connect("hh.sqlite")
    cursor = con.cursor()
    params = {'page': 1,
              'per_page': per_page,
              'text': search,
              'area': 113,
              'only_with_salary': True}
    response = requests.get(url, params=params)
    print(f'Статус ({search}): {response.status_code}')
    result = response.json()
    list_vac = result['items']
    # pprint.pprint(response.json())

    # print(result['items'][0]['url'])
    skills = {'Python': 0, 'Spark': 0, 'Hadoop': 0, 'Docker': 0, 'Linux': 0, 'Git': 0, 'SQL': 0, 'PyTorch': 0,
              'Keras': 0,
              'Sklearn': 0, 'Pandas': 0, 'Scipy': 0, 'Numpy': 0, 'XGBoost': 0, 'CatBoost': 0, 'LightGBM': 0,
              'Matplotlib': 0, 'REST': 0, 'FastApi': 0, 'JSON': 0, 'Django': 0, 'Flask': 0, 'Redis': 0, 'Cassandra': 0,
              'ClickHouse': 0}
    key_skills = []
    salary = 0
    for i in range(len(list_vac)):
        cursor.execute("insert or ignore into city (name) VALUES (?)", (list_vac[i]['area']['name'],))
        cursor.execute("select * from city where name=?", (list_vac[i]['area']['name'],))
        city_values = cursor.fetchone()
        # print(city_values)
        cursor.execute("insert or ignore into currency (name) VALUES (?)", (list_vac[i]['salary']['currency'],))
        cursor.execute("select * from currency where name=?", (list_vac[i]['salary']['currency'],))
        currency_values = cursor.fetchone()
        # print(currency_values)
        cursor.execute("insert into vacancy (name, city_id, salary_from, salary_to, currency_id) VALUES (?,?,?,?,?)",
                       (list_vac[i]['name'], city_values[0], list_vac[i]['salary']['from'],
                        list_vac[i]['salary']['to'], currency_values[0]))
        dct = {'name': list_vac[i]['name'], 'city': list_vac[i]['area']['name'], 'salary': list_vac[i]['salary']}
        lst_vac_for_html.append(dct)
        # print(list_vac[i]['url'])
        # vacancy_url = list_vac[i]['url']
        # if list_vac[i]['salary']['from'] is None:
        #     sal = list_vac[i]['salary']['to']
        # else:
        #     sal = list_vac[i]['salary']['from']
        # if list_vac[i]['salary']['currency'] == 'USD':
        #     salary += sal * 80
        # elif list_vac[i]['salary']['currency'] == 'EUR':
        #     salary += sal * 90
        # else:
        #     salary += sal
        # time.sleep(1)
        # response = requests.get(vacancy_url)
        # print(f'Статус {i + 1}: {response.status_code}')
        # result = response.json()
        # # print(result)
        # desc = result['description']
        # key_sc = result['key_skills']
        # for key in skills.keys():
        #     if key.lower() in desc.lower():
        #         skills[key] += 1
        # if key_sc is not None:
        #     for key in key_sc:
        #         if key['name'] not in key_skills:
        #             key_skills.append(key['name'])

    # pprint.pprint(skills)
    # lst_2 = []
    # for key, value in skills.items():
    #     lst_2.append({'name': key, 'count': value, 'persent': round(value / len(list_vac) * 100, 1)})
    # lst.append({'keywords': search, 'salary_mean': round(salary / len(list_vac)), 'count': len(list_vac),
    #             'requirements': lst_2})
    #
    # pprint.pprint(lst)
    # pprint.pprint(key_skills)
    # with open(f"{search}.json", "w") as f:
    #     json.dump(lst, f)
    cursor.execute("select * from vacancy")
    print(cursor.fetchall())
    con.commit()
    return lst_vac_for_html

@app.route('/')
def index():
    return render_template('index.html', name='ПАРСЕР HH')

@app.route('/services/', methods=['POST', 'GET'])
def services():
    if request.method == 'POST':
        lst = get_vac(request.form['search'], int(request.form['per_page']))
        return render_template('services.html', lst=lst, methods='POST')
    else:
        return render_template('services.html', methods='GET')

@app.route('/contact/')
def contact():
    return render_template('contact.html')

if __name__ == "__main__":
    app.run(debug=True)


from enum import Enum
import numpy as np
from pyqtgraph import AxisItem
from time import strftime, localtime
import time
import datetime
import os

import openQCM
from openQCM.common.architecture import Architecture,OSType

###############################################################################
# Enum for the types of sources. Indices MUST match app_sources constant
###############################################################################
class SourceType(Enum):
    serial = 0
    calibration = 1
    SocketClient = 2

###############################################################################
# Specifies the minimal Python version required
###############################################################################
class MinimalPython:
    major = 3
    minor = 2
    release = 0

###############################################################################
# Common constants and parameters for the application.
###############################################################################
class Constants:

    ##########################
    # Application Parameters #
    ##########################
    app_title = "Real-Time openQCM GUI"
    app_version = openQCM.__version__
    app_sources = ["Measurement openQCM Q-1 Device", "Calibration openQCM Q-1 Device"]#, "Socket Client"]
    app_encoding = "utf-8"

    ###################
    # PLOT parameters #
    ###################
    plot_update_ms = 200#16
    plot_colors = ['#ff0000', '#0072bd', '#00ffff', '#edb120', '#7e2f8e', '#77ac30', '#4dbeee', '#a2142f']
    plot_max_lines = len(plot_colors)

    ####################
    #  SAMPLES NUMBER  #
    ####################
    argument_default_samples = 501#1001

    ####################################
    # FILTERING and FITTING parameters #
    ####################################
    # Notes:
    # left and right frequencies in the area of the resonance frequency
    # Savitzky-Golay size of the data window
    # Savitzky-Golay order of the polynomial fit
    # Number of spline points: same as the frequency band +1 (es.5001)
    # Spline smoothing factor

    # Savitzky-Golay order of the polynomial fit (common for all)
    SG_order = 3

    #--------------
    # 5MHz
    #--------------
    # left and right frequencies
    L5_fundamental = 5500
    R5_fundamental = 2500
    # Savitzky-Golay size of the data window
    SG_window_size5_fundamental = 9
    # Spline smoothing factor
    Spline_factor5_fundamental = 0.05
    # left and right frequencies
    L5_3th_overtone = 7500
    R5_3th_overtone = 2500
    # Savitzky-Golay size of the data window
    SG_window_size5_3th_overtone = 11
    # Spline smoothing factor
    Spline_factor5_3th_overtone = 0.01

    # left and right frequencies
    L5_5th_overtone = 10000
    R5_5th_overtone = 2500
    # Savitzky-Golay size of the data window
    SG_window_size5_5th_overtone = 11
    # Spline smoothing factor
    Spline_factor5_5th_overtone = 0.01

    # left and right frequencies
    L5_7th_overtone = 50000
    R5_7th_overtone = 2500
    # Savitzky-Golay size of the data window
    SG_window_size5_7th_overtone = 33
    # Spline smoothing factor
    Spline_factor5_7th_overtone = 0.01

    # TODO
    # left and right frequencies
    L5_9th_overtone = 5000000
    R5_9th_overtone = 100000
    # Savitzky-Golay size of the data window
    SG_window_size5_9th_overtone = 5
    # Spline smoothing factor
    Spline_factor5_9th_overtone = 0.5

    #--------------
    # 10MHz
    #--------------
    # left and right frequencies
    L10_fundamental = 7500
    R10_fundamental = 2500
    # Savitzky-Golay size of the data window
    SG_window_size10_fundamental = 11
    # Spline smoothing factor
    Spline_factor10_fundamental = 0.01

    # left and right frequencies
    L10_3th_overtone = 13500
    R10_3th_overtone = 2500
    # Savitzky-Golay size of the data window
    SG_window_size10_3th_overtone = 11
    # Spline smoothing factor
    Spline_factor10_3th_overtone = 0.01

    # left and right frequencies
    L10_5th_overtone = 23000
    R10_5th_overtone = 3000
    # Savitzky-Golay size of the data window
    SG_window_size10_5th_overtone = 19
    # Spline smoothing factor
    Spline_factor10_5th_overtone = 0.01

    ##########################
    # SERIAL PORT Parameters #
    ##########################
    serial_default_speed = 115200
    serial_default_overtone = None
    serial_default_QCS = "@10MHz"
    serial_writetimeout_ms = 0
    serial_timeout_ms = None#0.01

    ######################
    # Process parameters #
    ######################
    process_join_timeout_ms = 2000
    simulator_default_speed = 0.1 # not used
    parser_timeout_ms = 0.005

    ##################
    # Log parameters #
    ##################
    log_export_path = "logged_data"
    log_filename = "{}.log".format(app_title)
    log_max_bytes = 5120
    log_default_level = 1
    log_default_console_log = False

    ######################################
    # File parameters for exporting data #
    ######################################
    # sets the slash depending on the OS types
    if Architecture.get_os() in [OSType.macosx, OSType.linux]:
       slash="/"
    else:
       slash="\\"

    csv_delimiter = "," # for splitting data of the serial port and CSV file storage
    csv_default_prefix = "%Y-%b-%d_%H-%M-%S"#"%H-%M-%S-%d-%b-%Y" # Hour-Minute-Second-month-day-Year
    csv_extension = "csv"
    txt_extension = "txt"
    csv_export_path = "logged_data"
    csv_filename = (strftime(csv_default_prefix, localtime()))#+'_DataLog')
    csv_sweeps_export_path = "{}{}{}".format(csv_export_path,slash,csv_filename)
    csv_sweeps_filename = "sweep"

    # Calibration: scan (WRITE for @5MHz and @10MHz QCS) path: 'common\'
    csv_calibration_filename    = "Calibration_5MHz"
    csv_calibration_filename10  = "Calibration_10MHz"
    csv_calibration_export_path = os.path.dirname(openQCM.__file__) #"common"

    ##################
    # Calibration: baseline correction (READ for @5MHz and @10MHz QCS) path: 'common\'
    csv_calibration_path   = "{}{}{}.{}".format(csv_calibration_export_path,slash,csv_calibration_filename,txt_extension)
    csv_calibration_path10 = "{}{}{}.{}".format(csv_calibration_export_path,slash,csv_calibration_filename10,txt_extension)

    # Frequencies: Fundamental and overtones (READ and WRITE for @5MHz and @10MHz QCS)
    csv_peakfrequencies_filename   = "PeakFrequencies"
    #csv_peakfrequencies_filename   = "PeakFrequencies_5MHz"
    #csv_peakfrequencies_filename10 = "PeakFrequencies_10MHz"
    cvs_peakfrequencies_path    = "{}{}{}.{}".format(csv_calibration_export_path,slash,csv_peakfrequencies_filename,txt_extension)
    #cvs_peakfrequencies_path10 = "{}{}{}.{}".format(csv_calibration_export_path,slash,csv_peakfrequencies_filename10,txt_extension)
    #########################
    '''
    # Calibration: baseline correction (READ for @5MHz and @10MHz QCS) path: 'common\'
    csv_calibration_path   = "{}\{}.{}".format(csv_calibration_export_path,csv_calibration_filename,txt_extension)
    csv_calibration_path10 = "{}\{}.{}".format(csv_calibration_export_path,csv_calibration_filename10,txt_extension)

    # Frequencies: Fundamental and overtones (READ and WRITE for @5MHz and @10MHz QCS)
    csv_peakfrequencies_filename   = "PeakFrequencies"
    #csv_peakfrequencies_filename   = "PeakFrequencies_5MHz"
    #csv_peakfrequencies_filename10 = "PeakFrequencies_10MHz"
    cvs_peakfrequencies_path    = "{}\{}.{}".format(csv_calibration_export_path,csv_peakfrequencies_filename,txt_extension)
    #cvs_peakfrequencies_path10 = "{}\{}.{}".format(csv_calibration_export_path,csv_peakfrequencies_filename10,txt_extension)
    '''

    ##########################
    # CALIBRATION PARAMETERS #
    ##########################

    # Peak Detection - distance in samples between neighbouring peaks
    dist5  =  8000 # for @5MHz
    dist10 =  10000 # for @10MHz
    calibration_default_samples = 50001
    calibration_frequency_start =  1000000
    calibration_frequency_stop  = 51000000
    calibration_fStep = (calibration_frequency_stop - calibration_frequency_start) / (calibration_default_samples-1)
    calibration_readFREQ  = np.arange(calibration_default_samples) * (calibration_fStep) + calibration_frequency_start
    #-------------------
    calib_fStep = 1000
    calib_fRange = 5000000 #
    calib_samples = 5001
    calib_sections = 10

    ###########################
    # Ring Buffers Parameters #
    ###########################
    ring_buffer_samples = 16363

    ##############################
    # Parameters for the average #
    ##############################
    environment = 50 #######################################################################################################
    SG_order_environment = 1
    SG_window_environment = 3

    ###################
    class SocketClient: #unused
        timeout = 0.01
        host_default = "localhost"
        port_default = [5555, 8080, 9090]
        buffer_recv_size = 1024
    ###################

'''
###############################################################################
#  Provides a date-time aware axis
###############################################################################
class DateAxis(AxisItem):

    """
    A tool that provides a date-time aware axis. It is implemented as an AxisItem
    that interprets positions as UNIX timestamps (i.e. seconds since 1970).
    The labels and the tick positions are dynamically adjusted depending on the range.
    """

    def __init__(self, *args, **kwargs):
        AxisItem.__init__(self, *args, **kwargs)
        self._oldAxis = None

    def tickStrings(self, values, scale, spacing):
        ret = []
        ep = datetime.datetime(1970,1,1,0,0,0)
        tonow = (datetime.datetime.utcnow()- ep).total_seconds()
        if not values:
            return []
        if spacing >= 31622400:  #366days
            fmt = "%Y"
        elif spacing >= 2678400: #31days
            fmt = "%Y %b"
        elif spacing >= 86400:   #1day
            fmt = "%b/%d"
        elif spacing >= 3600:    #1h
            fmt = "%b/%d-%Hh"
        elif spacing >= 60:      #1m
            fmt = "%H:%M"
        elif spacing >= 1:       #1s
            fmt = "%H:%M:%S"
        else: # less than 2s (show microseconds)
            #fmt = "%S.%f"""
            fmt = '[+%fms]'  # explicitly relative to last second
        for x in values:
            try:
                ret.append(time.strftime(fmt, time.localtime(x*.1+tonow))) #time.localtime(x*.1+tonow)
            except ValueError:  # Windows can't handle dates before 1970
                ret.append('')
            except:
                ret.append('')
        return ret
'''
###############################################################################
#  Provides a date-time aware axis
###############################################################################
class DateAxis(AxisItem):
    def __init__(self, *args, **kwargs):
        super(DateAxis, self).__init__(*args, **kwargs)

    def tickStrings(self, values, scale, spacing):
        TS_MULT_us = 1e6
        try:
            z= [(datetime.datetime.utcfromtimestamp(float(value)/TS_MULT_us)).strftime("%b-%d %H:%M:%S") for value in values]
        except:
            z= ''
        return z
        #return [(datetime.datetime.utcfromtimestamp(float(value)/TS_MULT_us)).strftime("%b-%d %H:%M:%S") for value in values]

###############################################################################
#  Provides a non scientific axis notation
###############################################################################
class NonScientificAxis(AxisItem):
    def __init__(self, *args, **kwargs):
        super(NonScientificAxis, self).__init__(*args, **kwargs)

    def tickStrings(self, values, scale, spacing):
        return [int(value*1) for value in values]


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

##################################################################
#Polytech Sorbonne - année 2018/2019
#Réalisé par : Fatine Bentires Alj et Alexia Zounias-Sirabella
#Cours d'apprentissage statistique de Patrick Gallinari
##################################################################

from .Annexe import *
from .Lecture import *
import pandas
import numpy as np
import matplotlib.pyplot as plt

############################## Etape 1 : manipulation des données ##################################

class Manipulation_donnees:
	#calcule les valeurs moyennes pour les données quantitatives uniquement
	def moyenne(data):
		nombre_lignes=Annexe.nombre_de_lignes(data)
		somme = 0
		moy = [0,0,0,0,0,0,0,0,0,0]

		for lignes in data.values:
			for i in range(0,10): #pour les variables quantitatives
				moy[i]+=int(lignes[i])

		for i in range(0,10):
			moy[i]/=nombre_lignes #pour diviser par le nombre de lignes

		print("La moyenne des éléments quantitatifs obtenue à la main est : ", moy)

	#donne la probabilité d'appartenance à chaque classe de forêt
	def type_foret(data):
		classe = [0,0,0,0,0,0,0,0]
		nombre_lignes = Annexe.nombre_de_lignes(data)
		somme_proba = 0

		for arbre in data.values:
			if(int(arbre[54])==1): #si l'élément vaut 1 alors on le met dans classe 1
				classe[1]+=1
			elif(int(arbre[54])==2): #si l'élément vaut 2 alors on le met dans classe 2
				classe[2]+=1
			elif(int(arbre[54])==3): #si l'élément vaut 3 alors on le met dans classe 3
				classe[3]+=1
			elif(int(arbre[54])==4): #si l'élément vaut 4 alors on le met dans classe 4
				classe[4]+=1
			elif(int(arbre[54])==5): #si l'élément vaut 5 alors on le met dans classe 5
				classe[5]+=1
			elif(int(arbre[54])==6): #si l'élément vaut 6 alors on le met dans classe 6
				classe[6]+=1
			elif(int(arbre[54])==7): #si l'élément vaut 7 alors on le met dans classe 7
				classe[7]+=1
			else:
				print("Pas de classe. Problème.")

		proba = np.zeros(7)
		proba[0] = classe[1]/nombre_lignes
		proba[1] = classe[2]/nombre_lignes
		proba[2] = classe[3]/nombre_lignes
		proba[3] = classe[4]/nombre_lignes
		proba[4] = classe[5]/nombre_lignes
		proba[5] = classe[6]/nombre_lignes
		proba[6] = classe[7]/nombre_lignes
		somme_proba = np.sum(proba)

		plt.bar(range(7),proba)
		plt.xlabel('Type de couverture')
		plt.ylabel('Probabilité')
		plt.show()

		print("Nombre de lignes : ",nombre_lignes, "\nExample : nombre d'arbres appartenant à la classe 1 : ",classe[1],"\nExample : probabilité d'appartenir à la classe 1 : ",proba[0],"\nSomme des probas = 1 ? : ",somme_proba)


import quandl
from omar_utils.data.files import File  # https://github.com/Omega97/omar_utils

def load_data(path, name):
    try:
        # try to load data locally
        return File(path=path)()
    except FileNotFoundError:
        # download data from web
        df = quandl.get(name)
        f = File()
        f.load_var(df)
        f.save(path)
        return df

if __name__ == '__main__':

    # load data
    Df = load_data(path='datasets/GOOGL', name='WIKI/GOOGL')
    print(Df)

    # clean data
    print(Df['Open'])


import tkinter as tk
from tkinter import ttk
from tkinter import messagebox as msg
from tkinter import simpledialog
import random
import numpy as np
from scipy.stats import maxwell

#상수 또는 처음에 결정하는 값
delta_t=0.01 #(시뮬레이션 기준)스텝 사이 시간 간격(s)
M=0.01       #실제 분자량(kg/mol)
R=8.314      #기체 상수(J/mol K)

modestr=''
class simboard:
    def __init__(self, frame):
        self.c1=tk.Canvas(frame, relief='solid', bg='white')
        self.c1.pack_propagate(False)
        self.c1.pack(fill='both', expand=tk.YES)
        self.c1['width']=600
        self.c1['height']=300

    def unpack(self, frame):
        frame.pack_forget()

    def const_vol_sim(self):    #T,P,W를 표시함
        self.num=particle_num.get()
        self.V=amountvolume.get()
        self.size=particle_size.get()
        self.n=self.num/100
        Mol.set(self.n)
        #화면에 표시하는 값
        temper_value.set(2*amountheat.get()/(3*self.n*R))#온도(K)
        pressure_value.set(0)          #압력(atm)
        work_value.set(0)          #기체가 한 일(J) (등적 과정이므로 항상 0)

        #프로그램 내부에서 사용하는 값
        self.v_rms=np.sqrt(3*R*temper_value.get()/M) #분자의 rms 속력
        self.m=self.n*M/self.num   #입자 질량(kg)
        #각 입자의 위치, 속도 저장
        self.p=[]
        self.pad=5
        self.c_width ,self.c_height=600, 300
        self.v_width, self.v_height=self.c_width/10*self.V, self.c_height
        self.c1.create_rectangle(self.v_width, 0, self.v_width+15, self.v_height, fill='black')
        self.c1.create_rectangle(self.v_width+15, self.v_height/2-7.5, 2000, self.v_height/2+7.5, fill='black')
        for i in range(self.num):
            #x1,y1은 입자의 왼쪽 위 좌표, x2,y2는 입자의 오른쪽 아래 좌표
            x1,y1=self.v_width*(random.random()*0.8+0.1),self.v_height*(random.random()*0.8+0.1)
            x2,y2=x1+self.size,y1+self.size
            r1=self.c1.create_oval(x1,y1,x2,y2,fill='black')
            #속도 벡터의 구면 좌표(theta, phi)
            theta=random.random()*np.pi
            phi=random.random()*2*np.pi
            #실제 속도, m/s단위
            vel=maxwell.rvs()/np.sqrt(3)*self.v_rms
            vel_x=vel *np.sin(theta) *np.cos(phi)
            vel_y=vel *np.cos(theta)
            #delta_t(1스텝)동안 이동하는 pixel 수  #1m = 2339.214pixel
            v_x=vel_x*2339.214/1000/100
            v_y=vel_y*2339.214/1000/100
            self.p.append([x1,y1,x2,y2,r1,v_x,v_y])
        self.press=[]
        def particleMove():
            temper_value.set(2*amountheat.get()/(3*self.n*R))#온도(K)
            self.v_rms=np.sqrt(3*R*temper_value.get()/M) #분자의 rms 속력
            for i in range(self.num):
                #실제 속도, m/s단위
                vel=maxwell.rvs()/np.sqrt(3)*self.v_rms
                vel_x=vel *np.sin(theta) *np.cos(phi)
                vel_y=vel *np.cos(theta)
                #delta_t(1스텝)동안 이동하는 pixel 수  #1m = 2339.214pixel
                v_x=vel_x*2339.214/1000/100
                v_y=vel_y*2339.214/1000/100
                self.p[i][5]=self.p[i][5]/abs(self.p[i][5])*v_x
                self.p[i][6]=self.p[i][6]/abs(self.p[i][6])*v_y
            imp=0
            for i in range(self.num):
                #x1 범위 제한, 왼쪽 벽과 탄성 충돌
                if self.p[i][0]<=self.p[i][5]+self.pad:
                    self.p[i][5]=abs(self.p[i][5])
                #x2 범위 제한, 오른쪽 벽(피스톤)과 탄성 충돌
                if self.p[i][2]>=self.v_width-self.p[i][5]+self.pad:
                    self.p[i][5]=-abs(self.p[i][5])
                    #피스톤에 가해지는 충격량(kg m/s)
                    imp+=self.m*2*abs(self.p[i][5])/(2339.214/1000/100)
                #y1 범위 제한, 위쪽 벽과 탄성 충돌
                if self.p[i][1]<=self.p[i][6]+self.pad:
                    self.p[i][6]=abs(self.p[i][6])
                #y2 범위 제한, 아래쪽 벽과 탄성 충돌
                if self.p[i][3]>=self.v_height-self.p[i][6]+self.pad:
                    self.p[i][6]=-abs(self.p[i][6])
                self.c1.move(self.p[i][4], self.p[i][5], self.p[i][6])
                self.p[i][0]+=self.p[i][5]
                self.p[i][2]+=self.p[i][5]
                self.p[i][1]+=self.p[i][6]
                self.p[i][3]+=self.p[i][6]
                #피스톤을 뚫고 나간 입자(버그)는 다시 안으로 집어넣음
                if self.p[i][0]>=self.v_width+10 or self.p[i][0]<=-20:
                    x_new=self.v_width*(random.random()*0.8+0.1)
                    self.c1.move(self.p[i][4], x_new-self.p[i][0], 0)
                    self.p[i][0]=x_new
                    self.p[i][2]=self.p[i][0]+self.size
            self.press.append(imp)
            imp=0
            if len(self.press)==100:
                #충격량과 압력 사이 비례 상수
                k=0.02924018*0.01*0.001*101325 /1.5 #0.02924018 = 피스톤 단면적(m^2)
                #압력 계산(10스텝 평균 압력)
                pressure_value.set(sum(self.press)/100/k)
                self.press=[]
            self.c1.after(int(delta_t*1000), particleMove)
        particleMove()

    def const_tmp_sim(self):    #V,W를 표시함
        self.V=amountvolume.get()
        self.T=temper_value.get()
        self.num=particle_num.get()
        self.size=particle_size.get()
        self.n=self.num/100
        Mol.set(self.n)

        #화면에 표시하는 값
        amountvolume.set(0)          #부피(L)
        work_value.set(0)          #기체가 한 일(J)

        #프로그램 내부에서 사용하는 값
        self.v_rms=np.sqrt(3*R*self.T/M) #분자의 rms 속력
        m=self.n*M/self.num   #입자 질량(kg)
        self.pad=5
        self.c_width ,self.c_height=600, 300
        self.v_width, self.v_height=self.c_width/10*self.V, self.c_height
        self.piston=self.c1.create_rectangle(self.v_width, 0, self.v_width+15, self.v_height, fill='black')
        self.rod=self.c1.create_rectangle(self.v_width+15, self.v_height/2-7.5, 2000, self.v_height/2+7.5, fill='black')
        #각 입자의 위치, 속도 저장
        self.p=[]
        for i in range(self.num):
            #x1,y1은 입자의 왼쪽 위 좌표, x2,y2는 입자의 오른쪽 아래 좌표
            x1,y1=self.v_width*(random.random()*0.8+0.1),self.v_height*(random.random()*0.8+0.1)
            x2,y2=x1+self.size,y1+self.size
            r1=self.c1.create_oval(x1,y1,x2,y2,fill='black')
            #속도 벡터의 구면 좌표(theta, phi)
            theta=random.random()*np.pi
            phi=random.random()*2*np.pi
            #실제 속도, m/s단위
            vel=maxwell.rvs()/np.sqrt(3)*self.v_rms
            vel_x=vel *np.sin(theta) *np.cos(phi)
            vel_y=vel *np.cos(theta)
            #delta_t(1스텝)동안 이동하는 pixel 수  #1m = 2339.214pixel
            v_x=vel_x*2339.214/1000/100
            v_y=vel_y*2339.214/1000/100
            self.p.append([x1,y1,x2,y2,r1,v_x,v_y])

        #충격량과 압력 사이 비례 상수
        k=0.02924018*0.01*0.001*101325  #0.02924018 = 피스톤 단면적(m^2)

        def pistonMove(imp):
            delta_x=(imp-pressure_value.get()*k)*5
            self.v_width+=delta_x
            if delta_x<0:
                work_value.set(work_value.get()+pressure_value.get()*(delta_x/800*10)*101.325)
            else:
                work_value.set(work_value.get()+(imp/k-pressure_value.get())*(delta_x/800*10)*101.325)
            self.c1.move(self.piston, delta_x, 0)
            self.c1.move(self.rod, delta_x, 0)

        def particleMove():
            imp=0
            for i in range(self.num):
                #x1 범위 제한, 왼쪽 벽과 탄성 충돌
                if self.p[i][0]<=self.p[i][5]+self.pad:
                    self.p[i][5]=abs(self.p[i][5])
                #x2 범위 제한, 오른쪽 벽(피스톤)과 탄성 충돌
                if self.p[i][2]>=self.v_width-self.p[i][5]+self.pad:
                    self.p[i][5]=-abs(self.p[i][5])
                    #피스톤에 가해지는 충격량(kg m/s)
                    imp+=m*2*abs(self.p[i][5])/(2339.214/1000/100)
                #y1 범위 제한, 위쪽 벽과 탄성 충돌
                if self.p[i][1]<=self.p[i][6]+self.pad:
                    self.p[i][6]=abs(self.p[i][6])
                #y2 범위 제한, 아래쪽 벽과 탄성 충돌
                if self.p[i][3]>=self.v_height-self.p[i][6]+self.pad:
                    self.p[i][6]=-abs(self.p[i][6])
                self.c1.move(self.p[i][4], self.p[i][5], self.p[i][6])
                self.p[i][0]+=self.p[i][5]
                self.p[i][2]+=self.p[i][5]
                self.p[i][1]+=self.p[i][6]
                self.p[i][3]+=self.p[i][6]
                #피스톤을 뚫고 나간 입자(버그)는 다시 안으로 집어넣음
                if self.p[i][0]>=self.v_width+10 or self.p[i][0]<=-20:
                    x_new=self.v_width*(random.random()*0.8+0.1)
                    self.c1.move(self.p[i][4], x_new-self.p[i][0], 0)
                    self.p[i][0]=x_new
                    self.p[i][2]=self.p[i][0]+self.size

            self.c1.after(int(delta_t*1000), particleMove)
            amountvolume.set(self.v_width/800*10)   #기체의 부피(L)계산
            pistonMove(imp)
        particleMove()

    def const_pressure_sim(self):
        self.num=particle_num.get()
        self.P=pressure_value.get()
        self.size=particle_size.get()
        self.n=self.num/100
        Mol.set(self.n)

        #화면에 표시하는 값
        temper_value.set(2*amountheat.get()/(5*self.n*R))#온도(K)
        work_value.set(0)          #기체가 한 일(J) (등적 과정이므로 항상 0)
        self.P=pressure_value.get()
        pressure_label.configure(text='부피')
        pressure_entry.configure(textvariable=amountvolume)
        pressure_label2.configure(text='L')

        #프로그램 내부에서 사용하는 값
        self.v_rms=np.sqrt(3*R*temper_value.get()/M) #분자의 rms 속력
        self.m=self.n*M/self.num   #입자 질량(kg)

        self.my_w = tk.Tk()
        self.my_w.title('등압 과정')
        self.c_width,self.c_height=600,300
        self.v_width,self.v_height=self.c_width-100,self.c_height
        self.piston = self.c1.create_rectangle(self.v_width, 0, self.v_width+15, self.v_height, fill='black')
        self.rod = self.c1.create_rectangle(self.v_width+15, self.v_height/2-7.5, 2000, self.v_height/2+7.5, fill='black')

        #각 입자의 위치, 속도 저장
        self.p=[]
        self.pad=5
        for i in range(self.num):
            #x1,y1은 입자의 왼쪽 위 좌표, x2,y2는 입자의 오른쪽 아래 좌표
            x1,y1=self.v_width*(random.random()*0.8+0.1),self.v_height*(random.random()*0.8+0.1)
            x2,y2=x1+self.size,y1+self.size
            r1=self.c1.create_oval(x1,y1,x2,y2,fill='black')
            #속도 벡터의 구면 좌표(theta, phi)
            theta=random.random()*np.pi
            phi=random.random()*2*np.pi
            #실제 속도, m/s단위
            vel=maxwell.rvs()/np.sqrt(3)*self.v_rms
            vel_x=vel *np.sin(theta) *np.cos(phi)
            vel_y=vel *np.cos(theta)
            #delta_t(1스텝)동안 이동하는 pixel 수  #1m = 2339.214pixel
            v_x=vel_x*2339.214/1000/100
            v_y=vel_y*2339.214/1000/100
            self.p.append([x1,y1,x2,y2,r1,v_x,v_y])

        #충격량과 압력 사이 비례 상수
        k=0.02924018*0.01*0.001*101325 #0.02924018 = 피스톤 단면적(m^2)

        def pistonMove(imp):
            delta_x=(imp-self.P*k)*10
            self.v_width+=delta_x
            work_value.set(work_value.get()+self.P*(delta_x/800*10)*101.325)
            self.c1.move(self.piston, delta_x, 0)
            self.c1.move(self.rod, delta_x, 0)

        def particleMove():
            temper_value.set(2*amountheat.get()/(5*self.n*R))#온도(K)
            self.v_rms=np.sqrt(3*R*temper_value.get()/M) #분자의 rms 속력
            for i in range(self.num):
                #실제 속도, m/s단위
                vel=maxwell.rvs()/np.sqrt(3)*self.v_rms
                vel_x=vel *np.sin(theta) *np.cos(phi)
                vel_y=vel *np.cos(theta)
                #delta_t(1스텝)동안 이동하는 pixel 수  #1m = 2339.214pixel
                v_x=vel_x*2339.214/1000/100
                v_y=vel_y*2339.214/1000/100
                self.p[i][5]=self.p[i][5]/abs(self.p[i][5])*v_x
                self.p[i][6]=self.p[i][6]/abs(self.p[i][6])*v_y
            imp=0
            for i in range(self.num):
                #x1 범위 제한, 왼쪽 벽과 탄성 충돌
                if self.p[i][0]<=self.p[i][5]+self.pad:
                    self.p[i][5]=abs(self.p[i][5])
                #x2 범위 제한, 오른쪽 벽(피스톤)과 탄성 충돌
                if self.p[i][2]>=self.v_width-self.p[i][5]+self.pad:
                    self.p[i][5]=-abs(self.p[i][5])
                    #피스톤에 가해지는 충격량(kg m/s)
                    imp+=self.m*2*abs(self.p[i][5])/(2339.214/1000/100)
                #y1 범위 제한, 위쪽 벽과 탄성 충돌
                if self.p[i][1]<=self.p[i][6]+self.pad:
                    self.p[i][6]=abs(self.p[i][6])
                #y2 범위 제한, 아래쪽 벽과 탄성 충돌
                if self.p[i][3]>=self.v_height-self.p[i][6]+self.pad:
                    self.p[i][6]=-abs(self.p[i][6])
                self.c1.move(self.p[i][4], self.p[i][5], self.p[i][6])
                self.p[i][0]+=self.p[i][5]
                self.p[i][2]+=self.p[i][5]
                self.p[i][1]+=self.p[i][6]
                self.p[i][3]+=self.p[i][6]
                #피스톤을 뚫고 나간 입자(버그)는 다시 안으로 집어넣음
                if self.p[i][0]>=self.v_width+10 or self.p[i][0]<=-20:
                    x_new=self.v_width*(random.random()*0.8+0.1)
                    self.c1.move(self.p[i][4], x_new-self.p[i][0], 0)
                    self.p[i][0]=x_new
                    self.p[i][2]=self.p[i][0]+self.size
            self.c1.after(int(delta_t*1000), particleMove)
            amountvolume.set(self.v_width/800*10)
            pistonMove(imp)

        particleMove()

    def simulation_start(self):
        global modestr
        #mode: 0: 등적, 1: 등압, 2: 등온, 3: 단열
        mode=simtype.get()
        if mode==0:
            modestr='등적과정(부피 일정)'
            amountvolume.set(const_volume.get())
            self.const_vol_sim()
            amountvolume_slider['state']='disabled'
        if mode==1:
            modestr='등압과정(압력 일정)'
            pressure_value.set(const_pressure.get())
            self.const_pressure_sim()
        if mode==2:
            temper_value.set(const_temp.get())
            modestr='등온과정(온도 일정, 압력 조절)'
            self.const_tmp_sim()
            amountheat_slider['state']='disabled'
        whatmodeisit.set(modestr)

def simulation_type():
    if sim is not None:
        sim.disabled = True
    menuwindow.deiconify()       # 새 게임 대화상자를 화면에 표시, 게임판 비활성화

sim=None

def quitmenu():
    if sim is not None:
        sim.disabled = False
    menuwindow.withdraw()

def quitmain():
    if msg.askokcancel('열역학 시뮬레이터', '프로그램을 종료하시겠습니까?'):
        mainwindow.destroy()        # 게임종료 대화상자를 표시, 게임종료

def simuStart(frame):
    num=simpledialog.askinteger("particle_num", "입자의 개수를 입력하세요")
    particle_num.set(num)
    ss=simpledialog.askinteger("particle_size", "입자의 크기를 입력하세요(5~30)")
    particle_size.set(ss)
    menuwindow.withdraw()
    global sim
    if sim is not None:
        sim.unpack(mainFrame)
    sim= simboard(frame)
    sim.disabled = False
    sim.simulation_start()

# root
mainwindow = tk.Tk()
# mainwindow.geometry('430x200')
mainwindow.title('main')
mainwindow.geometry('1000x500+100+100')

menuwindow=tk.Toplevel(mainwindow)
menuwindow.wm_attributes("-topmost", 1)      # 새 게임 대화상자 윈도우를 생성, 초기설정
menuwindow.geometry('+100+100')
menuwindow.protocol("WM_DELETE_WINDOW", quitmenu)       # 창 닫기 버튼 클릭 시 quitGame 함수 호출

# 열역학 과정 선택 대화상자의 GUI 구성
title_frm=tk.Frame(menuwindow)
title_frm.grid(row=0, column=0, columnspan=4)
levelLabel = tk.Label(title_frm, text='열역학 과정의 종류를 선택해주세요!')
levelLabel.pack(fill='both')

# 라디오 버튼 생성
radio_frame=tk.Frame(menuwindow)
radio_frame.grid(row=1, column=0)
simtype = tk.IntVar()
isovolumetric = tk.Radiobutton(radio_frame, text='등적과정', variable=simtype, value=0)
isobaric = tk.Radiobutton(radio_frame, text='등압과정', variable=simtype, value=1)
isothermal = tk.Radiobutton(radio_frame, text='등온과정', variable=simtype, value=2)

# 라디오 버튼 배치
isovolumetric.grid(row=0, padx=15)
isobaric.grid(row=1, padx=15)
isothermal.grid(row=2, padx=15)

const_frm=tk.Frame(menuwindow)
const_frm.grid(row=1, column=1, columnspan=3)
# 위젯 클릭시 등장할 entry
const_volume=tk.IntVar(const_frm)
isovolumetric_label1=tk.Label(const_frm, text='부피:')
isovolumetric_label1.grid(row=0, column=0)
isovolumetric_entry=tk.Entry(const_frm, textvariable=const_volume)
isovolumetric_entry.grid(row=0, column=1)
isovolumetric_label2=tk.Label(const_frm, text='L')
isovolumetric_label2.grid(row=0, column=2)

const_pressure=tk.IntVar()
isobaric_label1=tk.Label(const_frm, text='압력:')
isobaric_label1.grid(row=1, column=0)
isobaric_entry=tk.Entry(const_frm, textvariable=const_pressure)
isobaric_entry.grid(row=1, column=1)
isobaric_label2=tk.Label(const_frm, text='atm')
isobaric_label2.grid(row=1, column=2)

const_temp=tk.IntVar()
isothermal_label1=tk.Label(const_frm, text='온도:')
isothermal_label1.grid(row=2, column=0)
isothermal_entry=tk.Entry(const_frm, textvariable=const_temp)
isothermal_entry.grid(row=2, column=1)
isothermal_label2=tk.Label(const_frm, text='K')
isothermal_label2.grid(row=2, column=2)
bin_label=tk.Label(const_frm)
bin_label.grid(row=3, column=0, columnspan=3)

btn_frame=tk.Frame(menuwindow)
btn_frame.grid(row=2, column=0, columnspan=4)
mainFrame=tk.Frame(mainwindow)
startBtn = tk.Button(btn_frame, text='확인', command=(lambda: simuStart(frm_canvas)))
startBtn.pack(fill='both')

#mainwindow 위젯 배치

mainFrame.grid_propagate(False)     # 게임이 들어갈 mainFrame 생성
whatmodeisit=tk.StringVar()
particle_num=tk.IntVar()
particle_size=tk.IntVar()
particle_size.set(20)
amountheat=tk.IntVar()
amountheat.set(6000)
amountvolume=tk.IntVar()
temper_value=tk.IntVar()
pressure_value=tk.IntVar()
work_value=tk.IntVar()
Mol=tk.IntVar()
#Mol.set(mol)

frm1=tk.Frame(mainwindow)
frm2=tk.Frame(mainwindow)
frm3=tk.Frame(mainwindow)
frm4=tk.Frame(mainwindow)
frm5=tk.Frame(mainwindow)
frm6=tk.Frame(mainwindow)
frm_canvas=tk.Frame(mainwindow)
frm1.grid(row=0, column=0, rowspan=2, columnspan=2)
frm2.grid(row=0, column=2, rowspan=2, columnspan=2)
frm3.grid(row=0, column=4, rowspan=2, columnspan=3)
frm4.grid(row=3, column=0, rowspan=1, columnspan=7)
frm5.grid(row=4, column=0, rowspan=1, columnspan=5)
frm6.grid(row=4, column=5, rowspan=7, columnspan=3)
frm_canvas.grid(row=5, column=0, rowspan=6, columnspan=4)

#frm1
particle_num_label=tk.Label(frm1, text='입자 수: ')
particle_num_entry=tk.Entry(frm1, textvariable=particle_num)
particle_num_label.grid(row=0, column=0)
particle_num_entry.grid(row=0, column=1)
whatmode=tk.Label(frm1, textvariable=whatmodeisit)
whatmode.grid(row=1, column=0, columnspan=2)

#frm2
particle_size_label=tk.Label(frm2, text='입자 크기: ')
particle_size_slider = ttk.Scale(frm2, from_=10, to=50, orient='horizontal', variable=particle_size, length=100, state='disabled') ####################
newSimBtn=tk.Button(frm2, text='새로운 시뮬레이션', command=simulation_type)
particle_size_label.grid(row=0, column=0)
particle_size_slider.grid(row=0, column=1)
newSimBtn.grid(row=1, column=0, columnspan=2)

#frm3
def resetwork():
    work_value.set(0)
actual_mol_label=tk.Label(frm3, text='실제 몰 수: ')
actual_mol_entry=tk.Entry(frm3, textvariable=Mol)
actual_mol_label2=tk.Label(frm3, text='mol')
resetwork_button=tk.Button(frm3, text='기체가 한 일 초기화', command=resetwork)
quitGameBtn = tk.Button(frm3, text=' X ', command=quitmain, foreground='red')
actual_mol_label.grid(row=0, column=0)
actual_mol_entry.grid(row=0, column=1)
actual_mol_label2.grid(row=0, column=3)
resetwork_button.grid(row=1, column=0, columnspan=2)
quitGameBtn.grid(row=1, column=3)

#frm4
amountheat_label=tk.Label(frm4, text='가한 열')
amountheat_slider = ttk.Scale(frm4, from_=100, to=30000, orient='horizontal', variable=amountheat, length=500) ####################
amountheat_label.grid(row=0, column=0)
amountheat_slider.grid(row=0, column=1)

#frm5
amountvolume_label=tk.Label(frm5, text='부피')
amountvolume_slider = ttk.Scale(frm5, from_=1, to=10, orient='horizontal', variable=amountvolume, length=300) ####################
amountvolume_label.grid(row=0, column=0, sticky='w')
amountvolume_slider.grid(row=0, column=1, sticky='w')

#frm6
temper_label=tk.Label(frm6, text='온도:')
temper_entry=tk.Entry(frm6, textvariable=temper_value)
temper_label2=tk.Label(frm6, text='K')
pressure_label=tk.Label(frm6, text='압력:')
pressure_entry=tk.Entry(frm6, textvariable=pressure_value)
pressure_label2=tk.Label(frm6, text='atm')
work_label=tk.Label(frm6, text='한 일:')
work_entry=tk.Entry(frm6, textvariable=work_value)
work_label2=tk.Label(frm6, text='J')
temper_label.grid(row=0,column=0)
temper_entry.grid(row=0,column=1)
temper_label2.grid(row=0,column=2)
pressure_label.grid(row=1,column=0)
pressure_entry.grid(row=1,column=1)
pressure_label2.grid(row=1,column=2)
work_label.grid(row=2,column=0)
work_entry.grid(row=2,column=1)
work_label2.grid(row=2,column=2)

mainwindow.mainloop()


from flask import Flask, request,make_response
from flask_cors import CORS
import json
import traceback

app = Flask(__name__)
CORS(app)

@app.route("/", methods=['GET'])
def hello():
    return ({
        "service": "product"
    })

@app.route("/file", methods=['POST'])
def getFile():
    try:
        response = make_response(request.get_data())
        customHeader = {}
        for key, value in request.headers:
            customHeader[key] = request.headers.get(key)
        response.headers = customHeader
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response
    except Exception as err:
        print(err)
        traceback.print_exc()
        return ({ 'err': str(err)})

@app.route("/lists", methods=['GET'])
def show_list():
    return ({
        "lists": ['Amazon', 'Flipkart']
    })

if __name__ == "__main__":
    app.run(debug=True, port=5000, host='0.0.0.0')


#!/usr/bin/env python3
"""
+================================+
| Script Name: CVE-List.py           |
| Author: Sandro Kocher          |
| Version: 1.0                   |
| Funktion: Compare Relases and CVE's                     |
| Bemerkung:                     |
+================================+
"""

import json
from natsort import natsorted

# realeases.txt mit "Read" Berechtigungen öffnen und in Variable speichern
releaseFile = open("./Data/releases.txt", "r")
"""
for line in releaseFile.readlines():
    print(line)
"""

#CVE File Laden und in Variable füllen
cvesFile = open("./Data/cves.json", "r")
cvesData = json.load(cvesFile)

#Dependencies File Laden und in Variable füllen
dependenciesFile = open("./Data/dependencies.json", "r")
dependenciesData = json.load(dependenciesFile)

# Vorbereiten Output file mit "Write" Berechtigungen
vulnerableFile = open("./Data/Output/vulnerable.txt", "w")

#test = {"key1": ["test1", "test2"], "Key2": "Blabla", "Key3": {"ukey1": ["utest1", "utest2"]}}

def main():
    """
{
  "ansible": [  ==> programm
    {
      "affects": [
        "1.17.2",
        "2.4.9",
        "2.0.7",
        "3.0.2",
        "1.5.7",
        "1.17.4",
        "1.20.5",
        "2.19.0",
        "1.5.4",
        "1.17.0",
        "2.2.7",
        "2.5.10",
        "1.4.3",
        "1.16.0"
      ],
      "cves": [
        "CVE-2014-4967"
      ],
      "advisory": "ansible 1.6.7 contains two security fixes:\r\n  * Strip lookup calls out of inventory variables and clean unsafe data\r\n    returned from lookup plugins (CVE-2014-4966)\r\n  * Make sure vars don't insert extra parameters into module args and prevent\r\n    duplicate params from superseding previous params (CVE-2014-4967)"
    },
    """
    cveList = {} #erstellt die Variabe cveList für die Speicherung der CVEs mit den entsprechenden Versionen {'Programm == Version': {'CVEs'}
    for programm in cvesData: #Nimmt den Key aus dem ersten Absatz
        #print(programm)
        for item in cvesData[programm]: #geht durch jedes Item (Key + Value) pro Key(von programm Oben)
            #print(item)
            for cves in item["cves"]: #geht durch alle Subkeys aus dem programm und sucht nach dem key "cves"
                #print(cves)
                for affectVersion in item["affects"]: #itreation durch alle "affects" Einträge pro Programm und listed diese unter den CVEs auf
                    #print(affectVersion)
                    affectString = '{}=={}'.format(programm, affectVersion) #Erstellt die Formatierung für
                    #print(affectString)
                    if (affectString not in cveList): #Wenn Programm==Version nicht in der Liste cveList sind
                        cveList[affectString] = set() #erstelle einen neuen Key mit Programm==Version
                    cveList[affectString].add(str(cves)) #Ergänze den String "cves" als Value unter dem Key Programm==Version
                    #print(cveList)

    for line in releaseFile.readlines(): #Liest jede Zeile aus dem Release File
        lineparts = line.split("\t") #Trennt die Strings beim Tabstop: ['Release 1.3.10', '["sqlalchemy==3.20.6", "flask==3.2.2", "urllib3==3.16.4", "certifi==3.18.10", "pyyaml==5.15.2", "pickle==4.17.19", "ansible==3.0.2"]']
        #print(lineparts)
        release = lineparts[0] #Setzt den Release aus dem ersten Teil
        swCsv = lineparts[1].replace('[', '').replace(']', '').replace(' ', '').replace('"', '').replace('\n', '') #Ersetzt die Zeichen '[',']',' ','"' und '\n' mit nichts (löscht diese). sqlalchemy==3.20.6,flask==3.2.2,urllib3==3.16.4,certifi==3.18.10,pyyaml==5.15.2,pickle==4.17.19,ansible==3.0.2
        #print(swCsv)
        swList = swCsv.split(',') #teilt den String in die einzelnen Versionen auf ['sqlalchemy==3.20.6', 'flask==3.2.2', 'urllib3==3.16.4', 'certifi==3.18.10', 'pyyaml==5.15.2', 'pickle==4.17.19', 'ansible==3.0.2']
        #print(swList)

        releasecve = set()
        for swItem in swList: #Für jeden Eintrag in der der Softwareliste ['sqlalchemy==3.20.6', 'flask==3.2.2', 'urllib3==3.16.4', 'certifi==3.18.10', 'pyyaml==5.15.2', 'pickle==4.17.19', 'ansible==3.0.2']
            if (swItem in cveList): #Wenn Eintrag in Softwareliste in der CVE-Liste auftaucht
                for Element in cveList[swItem]: #Dann für jedes Element in der CVE-Liste {'ansible==1.17.2': {'CVE-2014-4967', 'CVE-2016-3096'} mit dem Key aus der Softwareliste "ansible==1.17.2"
                    #print(Element)
                    releasecve.add(Element) #ergänze die Liste releasecve mit dem Element "CVE"

            for dependency in dependenciesData[swItem]: #Für jeden Software-Eintrag in der dependencies-Liste {'sqlalchemy==1.3.11': ['pycapnp-async==0.5.2', 'drf-jwt==1.15.1', 'pymisp==2.4.56'], usw.}
                #print(swItem)
                #print(dependency) #ansible==3.0.2 (swItem), errbot==1.3.2(dependency), ansible==3.0.2(swItem) katka-core==0.11.2(dependency) ansible==3.0.2(swItem) smeagol==0.1.1(dependency)
                if(dependency in cveList): #Wenn Eintrag in Dependency-Liste in der CVE-Liste auftaucht
                    for Eintrag in cveList[dependency]: #Dann für jedes Element in der CVE-Liste {'ansible==1.17.2': {'CVE-2014-4967', 'CVE-2016-3096'} mit dem Key aus der Softwareliste "ansible==1.17.2"
                        releasecve.add(Eintrag) #ergänze die Liste releasecve mit dem Eeintrag "CVE"

        # Immer noch in der Iteration der Releases Liste
        """
        vulnerableFile.write(release + "\t" + ', '.join((releasecve)) + "\n") #schreibe in das File "vulnerableFile" Release + Auflistung der CVEs
        print(release + "\t" + ', '.join((releasecve)))
        """

        vulnerableFile.write(release + "\t" + ', '.join(natsorted(releasecve)) + "\n")
        print(release + "\t" + ', '.join(natsorted(releasecve)))

if __name__ == '__main__':
    main()


from typing import List

class Solution:
    def firstMissingPositive_1(self, nums: List[int]) -> int:
        # Good. Running time is n with only constant storage.
        # Rearrange the nums array. Swap the element that points positions
        # within the range of the array.
        for i in range(len(nums)):
            if 0 < nums[i] <= len(nums):
                # Important to have nums[i] != nums[nums[i] - 1] in while,
                # in case there will be infinite loop during swap.
                while 0 < nums[i] <= len(nums) and nums[i] != nums[nums[i] - 1]:
                    idx = nums[i] - 1# The index that nums[i] points to.
                    nums[i], nums[idx] = nums[idx], nums[i]
        print(nums)
        for i in range(1, len(nums) + 1):
            if i != nums[i-1]:
                return i
        return len(nums) + 1

    def firstMissingPositive_2(self, nums: List[int]) -> int:
        # We are looking range [1, n] inclusive from both ends
        # Exclude all numbers that are either non-positive, or larger than n
        n = len(nums)
        for i in range(n):
            if nums[i] <= 0 or nums[i] > n:
                nums[i] = n + 1
        for i in range(n):
            if abs(nums[i]) != n + 1:
                # Set the number that nums[i] (already in range [1, n]) points
                # to (abs(nums[i]) - 1) as negative.
                nums[abs(nums[i]) - 1] = -abs(nums[abs(nums[i]) - 1])
        for i in range(n):
            if nums[i] > 0:
                return i + 1
        return n + 1

    def firstMissingPositive_sort(nums: List[int]) -> int:#nlogn
        # Not qualified since running time is nlogn
        nums.sort()
        start = 1
        for n in nums:
            if start == n:
                start += 1
        return start

    def firstMissingPositive_set(nums: List[int]) -> int:#n + n storage
        # Not qualified since using n storage
        numSet = set(nums)
        start = 1
        while start in numSet:
            start += 1
        return start

if __name__ == '__main__':
    print(Solution.firstMissingPositive_set(nums=[1,2,0]))
    print(Solution.firstMissingPositive_set(nums=[3,4,-1,1]))
    print(Solution.firstMissingPositive_set(nums=[7,8,9,11,12]))


import os
import pathlib
import warnings

import skimage.io
from multiprocess import Pool
from functools import partial
import _pickle

import numpy as np
from pycocotools.coco import COCO
import shapely.geometry

from tqdm import tqdm

import torch

from lydorn_utils import print_utils
from lydorn_utils import python_utils

from torch_lydorn.torch.utils.data import Dataset as LydornDataset, makedirs, files_exist, __repr__

from torch_lydorn.torchvision.datasets import utils

class MappingChallenge(LydornDataset):
    def __init__(self, root, transform=None, pre_transform=None, fold="train", small=False, pool_size=1):
        assert fold in ["train", "val", "test_images"], "Input fold={} should be in [\"train\", \"val\", \"test_images\"]".format(fold)
        if fold == "test_images":
            print_utils.print_error("ERROR: fold {} not yet implemented!".format(fold))
            exit()
        self.root = root
        self.fold = fold
        makedirs(self.processed_dir)
        self.small = small
        if self.small:
            print_utils.print_info("INFO: Using small version of the Mapping challenge dataset.")
        self.pool_size = pool_size

        self.coco = None
        self.image_id_list = self.load_image_ids()
        self.stats_filepath = os.path.join(self.processed_dir, "stats.pt")
        self.stats = None
        if os.path.exists(self.stats_filepath):
            self.stats = torch.load(self.stats_filepath)
        self.processed_flag_filepath = os.path.join(self.processed_dir, "processed-flag-small" if self.small else "processed-flag")

        super(MappingChallenge, self).__init__(root, transform, pre_transform)

    def load_image_ids(self):
        image_id_list_filepath = os.path.join(self.processed_dir, "image_id_list-small.json" if self.small else "image_id_list.json")
        if os.path.exists(image_id_list_filepath):
            image_id_list = python_utils.load_json(image_id_list_filepath)
        else:
            coco = self.get_coco()
            image_id_list = coco.getImgIds(catIds=coco.getCatIds())
        # Save for later so that the whole coco object doesn't have to be instantiated when just reading processed samples with multiple workers:
        python_utils.save_json(image_id_list_filepath, image_id_list)
        return image_id_list

    def get_coco(self):
        if self.coco is None:
            annotation_filename = "annotation-small.json" if self.small else "annotation.json"
            annotations_filepath = os.path.join(self.raw_dir, self.fold, annotation_filename)
            self.coco = COCO(annotations_filepath)
        return self.coco

    @property
    def processed_dir(self):
        return os.path.join(self.root, 'processed', self.fold)

    @property
    def processed_file_names(self):
        l = []
        for image_id in self.image_id_list:
            l.append(os.path.join("data_{:012d}.pt".format(image_id)))
        return l

    def __len__(self):
        return len(self.image_id_list)

    def _download(self):
        pass

    def download(self):
        pass

    def _process(self):
        f = os.path.join(self.processed_dir, 'pre_transform.pt')
        if os.path.exists(f) and torch.load(f) != __repr__(self.pre_transform):
            warnings.warn(
                'The `pre_transform` argument differs from the one used in '
                'the pre-processed version of this dataset. If you really '
                'want to make use of another pre-processing technique, make '
                'sure to delete `{}` first.'.format(self.processed_dir))
        f = os.path.join(self.processed_dir, 'pre_filter.pt')
        if os.path.exists(f) and torch.load(f) != __repr__(self.pre_filter):
            warnings.warn(
                'The `pre_filter` argument differs from the one used in the '
                'pre-processed version of this dataset. If you really want to '
                'make use of another pre-fitering technique, make sure to '
                'delete `{}` first.'.format(self.processed_dir))

        if os.path.exists(self.processed_flag_filepath):
            return

        print('Processing...')

        makedirs(self.processed_dir)
        self.process()

        path = os.path.join(self.processed_dir, 'pre_transform.pt')
        torch.save(__repr__(self.pre_transform), path)
        path = os.path.join(self.processed_dir, 'pre_filter.pt')
        torch.save(__repr__(self.pre_filter), path)

        print('Done!')

    def process(self):
        images_relative_dirpath = os.path.join("raw", self.fold, "images")

        image_info_list = []
        coco = self.get_coco()
        for image_id in self.image_id_list:
            filename = coco.loadImgs(image_id)[0]["file_name"]
            annotation_ids = coco.getAnnIds(imgIds=image_id)
            annotation_list = coco.loadAnns(annotation_ids)
            image_info = {
                "image_id": image_id,
                "image_filepath": os.path.join(self.root, images_relative_dirpath, filename),
                "image_relative_filepath": os.path.join(images_relative_dirpath, filename),
                "annotation_list": annotation_list
            }
            image_info_list.append(image_info)

        partial_preprocess_one = partial(preprocess_one, pre_filter=self.pre_filter, pre_transform=self.pre_transform,
                                         processed_dir=self.processed_dir)
        with Pool(self.pool_size) as p:
            sample_stats_list = list(tqdm(p.imap(partial_preprocess_one, image_info_list), total=len(image_info_list)))

        # Aggregate sample_stats_list
        image_s0_list, image_s1_list, image_s2_list, class_freq_list = zip(*sample_stats_list)
        image_s0_array = np.stack(image_s0_list, axis=0)
        image_s1_array = np.stack(image_s1_list, axis=0)
        image_s2_array = np.stack(image_s2_list, axis=0)
        class_freq_array = np.stack(class_freq_list, axis=0)

        image_s0_total = np.sum(image_s0_array, axis=0)
        image_s1_total = np.sum(image_s1_array, axis=0)
        image_s2_total = np.sum(image_s2_array, axis=0)

        image_mean = image_s1_total / image_s0_total
        image_std = np.sqrt(image_s2_total/image_s0_total - np.power(image_mean, 2))
        class_freq = np.sum(class_freq_array*image_s0_array[:, None], axis=0) / image_s0_total

        # Save aggregated stats
        self.stats = {
            "image_mean": image_mean,
            "image_std": image_std,
            "class_freq": class_freq,
        }
        torch.save(self.stats, self.stats_filepath)

        # Indicates that processing has been performed:
        pathlib.Path(self.processed_flag_filepath).touch()

    def get(self, idx):
        image_id = self.image_id_list[idx]
        data = torch.load(os.path.join(self.processed_dir, "data_{:012d}.pt".format(image_id)))
        data["image_mean"] = self.stats["image_mean"]
        data["image_std"] = self.stats["image_std"]
        data["class_freq"] = self.stats["class_freq"]
        return data

def preprocess_one(image_info, pre_filter, pre_transform, processed_dir):
    out_filepath = os.path.join(processed_dir, "data_{:012d}.pt".format(image_info["image_id"]))
    data = None
    if os.path.exists(out_filepath):
        # Load already-processed sample
        try:
            data = torch.load(out_filepath)
        except (EOFError, _pickle.UnpicklingError):
            pass
    if data is None:
        # Process sample:
        image = skimage.io.imread(image_info["image_filepath"])
        gt_polygons = []
        for annotation in image_info["annotation_list"]:
            flattened_segmentation_list = annotation["segmentation"]
            if len(flattened_segmentation_list) != 1:
                print("WHAT!?!, len(flattened_segmentation_list = {}".format(len(flattened_segmentation_list)))
                print("To implement: if more than one segmentation in flattened_segmentation_list (MS COCO format), does it mean it is a MultiPolygon or a Polygon with holes?")
                raise NotImplementedError
            flattened_arrays = np.array(flattened_segmentation_list)
            coords = np.reshape(flattened_arrays, (-1, 2))
            polygon = shapely.geometry.Polygon(coords)

            # Filter out degenerate polygons (area is lower than 2.0)
            if 2.0 < polygon.area:
                gt_polygons.append(polygon)

        data = {
            "image": image,
            "gt_polygons": gt_polygons,
            "image_relative_filepath": image_info["image_relative_filepath"],
            "name": os.path.splitext(os.path.basename(image_info["image_relative_filepath"]))[0],
            "image_id": image_info["image_id"]
        }

        if pre_filter is not None and not pre_filter(data):
            return

        if pre_transform is not None:
            data = pre_transform(data)

        # masked_angles = data["gt_crossfield_angle"].astype(np.float) * data["gt_polygons_image"][:, :, 1].astype(np.float)
        # skimage.io.imsave("gt_crossfield_angle.png", data["gt_crossfield_angle"])
        # skimage.io.imsave("masked_angles.png", masked_angles)
        # exit()

        torch.save(data, out_filepath)

    # Compute stats for later aggregation for the whole dataset
    normed_image = data["image"] / 255
    image_s0 = data["image"].shape[0] * data["image"].shape[1]  # Number of pixels
    image_s1 = np.sum(normed_image, axis=(0, 1))  # Sum of pixel normalized values
    image_s2 = np.sum(np.power(normed_image, 2), axis=(0, 1))
    class_freq = np.mean(data["gt_polygons_image"], axis=(0, 1)) / 255

    return image_s0, image_s1, image_s2, class_freq

def main():
    # Test using transforms from the frame_field_learning project:
    from frame_field_learning import data_transforms

    config = {
        "data_dir_candidates": [
                "/data/titane/user/nigirard/data",
                "~/data",
                "/data"
        ],
        "dataset_params": {
            "small": True,
            "root_dirname": "mapping_challenge_dataset",
            "seed": 0,
            "train_fraction": 0.75
        },
        "num_workers": 8,
        "data_aug_params": {
            "enable": False,
            "vflip": True,
            "affine": True,
            "color_jitter": True,
            "device": "cuda"
        }
    }

    # Find data_dir
    data_dir = python_utils.choose_first_existing_path(config["data_dir_candidates"])
    if data_dir is None:
        print_utils.print_error("ERROR: Data directory not found!")
        exit()
    else:
        print_utils.print_info("Using data from {}".format(data_dir))
    root_dir = os.path.join(data_dir, config["dataset_params"]["root_dirname"])

    # --- Transforms: --- #
    # --- pre-processing transform (done once then saved on disk):
    # --- Online transform done on the host (CPU):
    train_online_cpu_transform = data_transforms.get_online_cpu_transform(config,
                                                                          augmentations=config["data_aug_params"][
                                                                              "enable"])
    test_online_cpu_transform = data_transforms.get_eval_online_cpu_transform()

    train_online_cuda_transform = data_transforms.get_online_cuda_transform(config,
                                                                            augmentations=config["data_aug_params"][
                                                                                "enable"])
    # --- --- #

    dataset = MappingChallenge(root_dir,
                               transform=test_online_cpu_transform,
                               pre_transform=data_transforms.get_offline_transform_patch(),
                               fold="train",
                               small=config["dataset_params"]["small"],
                               pool_size=config["num_workers"])

    print("# --- Sample 0 --- #")
    sample = dataset[0]
    print(sample.keys())

    for key, item in sample.items():
        print("{}: {}".format(key, type(item)))

    print(sample["image"].shape)
    print(len(sample["gt_polygons_image"]))
    print("# --- Samples --- #")
    # for data in tqdm(dataset):
    #     pass

    data_loader = torch.utils.data.DataLoader(dataset, batch_size=10, shuffle=True, num_workers=config["num_workers"])
    print("# --- Batches --- #")
    for batch in tqdm(data_loader):
        print("Images:")
        print(batch["image_relative_filepath"])
        print(batch["image"].shape)
        print(batch["gt_polygons_image"].shape)

        print("Apply online tranform:")
        batch = utils.batch_to_cuda(batch)
        batch = train_online_cuda_transform(batch)
        batch = utils.batch_to_cpu(batch)

        print(batch["image"].shape)
        print(batch["gt_polygons_image"].shape)

        # Save output to visualize
        seg = np.array(batch["gt_polygons_image"][0])
        seg = np.moveaxis(seg, 0, -1)
        seg_display = utils.get_seg_display(seg)
        seg_display = (seg_display * 255).astype(np.uint8)
        skimage.io.imsave("gt_seg.png", seg_display)
        skimage.io.imsave("gt_seg_edge.png", seg[:, :, 1])

        im = np.array(batch["image"][0])
        im = np.moveaxis(im, 0, -1)
        skimage.io.imsave('im.png', im)

        gt_crossfield_angle = np.array(batch["gt_crossfield_angle"][0])
        gt_crossfield_angle = np.moveaxis(gt_crossfield_angle, 0, -1)
        skimage.io.imsave('gt_crossfield_angle.png', gt_crossfield_angle)

        distances = np.array(batch["distances"][0])
        distances = np.moveaxis(distances, 0, -1)
        skimage.io.imsave('distances.png', distances)

        sizes = np.array(batch["sizes"][0])
        sizes = np.moveaxis(sizes, 0, -1)
        skimage.io.imsave('sizes.png', sizes)

        # valid_mask = np.array(batch["valid_mask"][0])
        # valid_mask = np.moveaxis(valid_mask, 0, -1)
        # skimage.io.imsave('valid_mask.png', valid_mask)

        input("Press enter to continue...")

if __name__ == '__main__':
    main()


from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.generics import get_object_or_404, ListAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework_simplejwt.authentication import JWTAuthentication
from .serializers import *

# Create your views here.
class CompanyViewSet(viewsets.ViewSet):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def list(self, request):
        company = Company.objects.all()
        serializer = CompanySerializer(company, many=True, context={"request":request})
        response_dict = {"error": False, "message": "All companies data", "data": serializer.data}
        return Response(response_dict)

    def create(self, request):
        try:
            serializer = CompanySerializer(data=request.data, context={"request": request})
            serializer.is_valid(raise_exception=True)
            serializer.save()
            dict_response={
                "error":False,
                "message":"Company data added successfully!"
                }
        except:
            dict_response = {
                "error": True,
                "message": "Couldnt add the data",
            }
        return Response(dict_response)

    def update(self, request, pk=None):
        try:
            queryset = Company.objects.all()
            company = get_object_or_404(queryset, pk=pk)
            serializer = CompanySerializer(company, data=request.data, context={"request":request})
            serializer.is_valid(raise_exception=True)
            serializer.save()
            dict_response = {
                "error": False,
                "message": "Company data updated successfully!",
            }
        except:
            dict_response = {
                "error": True,
                "message": "Couldnt add the data",
            }
        return Response(dict_response)

class CompanyBankViewSet(viewsets.ViewSet):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def create(self, request):
        try:
            serializer = CompanyBankSerializer(
                data=request.data,
                context={"request":request}
                )
            serializer.is_valid(raise_exception=True)
            serializer.save()
            dict_response = {
                "error": False,
                "message": "Bank Details created!"
            }
        except:
            dict_response = {
                "error": True,
                "message": "Unable to create Bank details!"
            }
        return Response(dict_response)

    def list(self, request):
        company_bank = CompanyBank.objects.all()
        serializer = CompanyBankSerializer(company_bank, many=True, context={"request":request})
        dict_response = {
            "error": False,
            "message": "All company bank details",
            "data": serializer.data
        }

        return Response(dict_response)

    def retrieve(self, request, pk=None):
        queryset = CompanyBank.objects.all()
        company_bank = get_object_or_404(queryset, pk=pk)
        serializer = CompanyBankSerializer(company_bank, context={"request": request})
        dict_response = {
            "error": False,
            "message": "Single company Bank details!",
            "data": serializer.data
        }

        return Response(dict_response)

    def update(self, request, pk=None):
        try:
            queryset = CompanyBank.objects.all()
            company_bank = get_object_or_404(queryset, pk=pk)
            serializer = CompanyBankSerializer(
                company_bank,
                data=request.data,
                context={"request": request}
                )
            serializer.is_valid(raise_exception=True)
            serializer.save()
            dict_response = {
                "error": False,
                "message": "Details updated successfully!"
            }
        except:
            dict_response = {
                "error": True,
                "message": "Unable to update!"
            }

        return Response(dict_response)

class CompanyNameViewSet(ListAPIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]
    serializer_class = CompanySerializer

    def get_queryset(self):
        name=self.kwargs['name']
        return Company.objects.filter(name=name)

company_list = CompanyViewSet.as_view({"get":"list"})
company_create = CompanyViewSet.as_view({"post": "create"})
company_update = CompanyViewSet.as_view({"put": "update"})


import os
import arcade

from src.main import Game

def main():
    curr_dir = os.path.dirname(os.path.abspath(__file__))
    window = Game(curr_dir)
    window.setup()
    arcade.run()

if __name__ == "__main__":
    main()