import os

def getCurrentPath():
    script_dir = os.path.dirname(__file__)
    dirs = script_dir.split('\\');
    return '/'.join(dirs[:len(dirs)-1])

def read_characters(lang):
    path = getCurrentPath()
    rel_path = "data/characters/" + lang + '.txt'
    abs_file_path = os.path.join(path, rel_path)
    with open(abs_file_path, encoding="utf-8") as f:
        characters = f.read().splitlines()
        f.close()
    return characters

def read_words_file(lang, category):
    path = getCurrentPath()
    rel_path = 'data/categories/' + lang + '/' + category + '.txt'
    abs_file_path = os.path.join(path, rel_path)
    with open(abs_file_path, encoding="utf-8") as f:
        dictionary = f.read().splitlines()
        f.close()
    return dictionary

def read_input_file(file):
    with open(file, encoding="utf-8") as f:
        dictionary = f.read().upper().splitlines()
        f.close()
    return dictionary


import stack

def syntaxChecker(string):
    stack_sy = stack.stack()
    # 注意这里的 opens、closes 变量的设置，顺序均为 小括号、中括号、大括号，
    # 定义为顺序一致是为了方便的通过 下标 判断括号是否配对
    opens = "([{"
    closes = ")]}"
    balanced = True
    # 循环遍历字符串
    for i in string:
        # 如果是左括号，直接入栈
        if i in opens:
            stack_sy.push(i)
        # 如果是右括号，进入判断
        elif i in closes:
            # 判断1：栈是否为空，为空则 false
            if stack_sy.is_Empty():
                balanced = False
                break
            # 判断2：栈不为空，则取出栈顶左括号
            else:
                j = stack_sy.pop()
                # 判断3：在初始化变量 opens、closes 中查找左括号和右括号的下标，如果下标不同则说明不匹配
                if opens.find(j) != closes.find(i):
                    balanced = False
                    break
    # 遍历结束，如果栈不为空，说明左侧有多余左括号，false
    if not stack_sy.is_Empty():
        balanced = False
    return balanced

if __name__ == "__main__":
    syntax = "{{()}}{[]}("
    print("括号字符串 {} 合法校验：{}".format(syntax,syntaxChecker(syntax)))


#age = int(input("ป้อนอายุของคุณ: "))

# if age>=15:
#     print("คำนำหน้าเป็น นาย/นางสาว")
#     print("จบโปรแกรมด้านใน if")

# print("จบโปรแกรม")

# if age>=15 or age <=20:
#     print("วัยรุ่น")
# elif age>=20 or age<=29:
#     print("วัยทำงาน")
# else:
#     print("วันเด็ก")
# print("จบโปรแกรม")

# Ternary Operator
# print("วัยรุ่น") if age>=15 else print("วันเด็ก")

# if ซ้อน if
# if age<=15:
#     if age==15:
#         print("ม.3")
#     elif age==14:
#         print("ม.2")
#     elif age==13:
#         print("ม.1")
#     else:
#         print("ประถม")
# else:
#     print("มัธยม")

# print("จบโปรแกรม")

# เขียนโปรแกรมหาตัวเลข มาก / น้อย
# a=int(input("ป้อนตัวเลขที่ 1:"))
# b=int(input("ป้อนตัวเลขที่ 2:"))

# if a>b:
#     print(a," มากกว่า ",b)
# else:
#     print(b," มากกว่า ",a)

# หาเลขคู่ / คี่
# number = int(input("ป้อนตัวเลขของคุณ: "))
# # ถ้าหาร 2 ลงตัว => คู่
# if number %2 == 0:
#     print("เป็นเลขคู่")
# else:
#     print("เป็นเลขคี่")

# แลกแบงค์ธนาคาร
# number = int(input("เงินของคุณ: "))

# if number>=1000:
#     print("1000 bath = ",number//1000,"ใบ")
#     number%=1000

# if number>=500:
#     print("500 bath = ",number//500,"ใบ")
#     number%=500

# if number>=100:
#     print("100 bath = ",number//100,"ใบ")
#     number%=100

# if number>=50:
#     print("50 bath = ",number//50,"ใบ")
#     number%=50

# if number>=20:
#     print("20 bath = ",number//20,"ใบ")
#     number%=20

# แปลง ค.ศ. เป็น พ.ศ. +543
# แปลง พ.ศ. เป็น ค.ศ. -543
# number = int(input("ป้อนปี พ.ศ.: "))
# number=number-543
# print("เป็น ค.ศ. = ",number)

# BMI
weight = int(input("ป้อนน้ำหนักของคุณ (Kg): "))
high = int(input("ป้อนส่วนสูงของคุณ (cm): "))/100
bmi = weight/(high**2)

if bmi>=0 and bmi<18.0:
    result="ผอม"
elif bmi>=18.5 and bmi<=22.9:
    result="สมส่วน"
elif bmi>=23.0 and bmi<=24.9:
    result="น้ำหนักเกิน"
elif bmi>=25.0 and bmi<=29.9:
    result="โรคอ้วนระดับ1"
elif bmi>30:
    result="โรคอ้วนระดับอันตราย"
else:
    result="ไม่ทราบค่าที่ชัดเจน"

print(result)


# -*- coding: utf-8 -*-
import multiprocessing
import threading
import time

import redis
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings

from sports.spiders.bti_basketball import BtiBasketballSpider
from sports.spiders.bti_football import BtiFootballSpider
from sports.spiders.fb_basketball import FbBasketballSpider
from sports.spiders.fb_football import FbFootballSpider
from sports.spiders.vd_basketball import VdBasketballSpider
from sports.spiders.vd_football import VdFootballSpider

class RunSpider:
    spider_class_list = [
        BtiFootballSpider, FbFootballSpider, VdFootballSpider,
        BtiBasketballSpider, FbBasketballSpider, VdBasketballSpider
    ]
    ball_time_list = ["live", "today", "tomorrow"]

    def __init__(self):
        redis_config = get_project_settings().get("REDIS_CONFIG", {})
        self.redis_client = redis.StrictRedis(**redis_config, decode_responses=True)

    @classmethod
    # 定义运行爬虫的函数
    def run_spider(cls, spider_class, ball_time, detail_requests):
        settings = get_project_settings()
        process = CrawlerProcess(settings=settings)
        process.crawl(spider_class, ball_time=ball_time, detail_requests=detail_requests)
        process.start()

    def process_function(self, spider_class, ball_time, detail_requests):

        if not detail_requests:
            ball_time_delay = {"live": 0.2, "today": 20, "tomorrow": 40}
        else:
            ball_time_delay = {"live": 0.2, "today": 2, "tomorrow": 20}
        delay = ball_time_delay[ball_time]

        while True:
            p1 = multiprocessing.Process(target=self.run_spider, args=(spider_class, ball_time, detail_requests))
            p1.start()
            p1.join()
            time.sleep(delay)

    def run(self):
        threads = []
        for i in self.spider_class_list:
            for ball_time in self.ball_time_list:
                detail_list = [False, True]
                for detail in detail_list:
                    if ball_time == "tomorrow" and detail is True:
                        continue
                    t = threading.Thread(target=self.process_function, args=(i, ball_time, detail))
                    threads.append(t)
        for i in threads:
            i.start()
        for i in threads:
            i.join()

if __name__ == "__main__":
    RunSpider().run()


import sys

N,S = map(int,sys.stdin.readline().rstrip().split())

array = list(map(int,sys.stdin.readline().rstrip().split()))

def BS(start,end):
    while start<=end:
        mid = (start+end)//2
        if array[mid] == S:
            return mid
        if array[mid] > S:
            end = mid-1
            continue
        if array[mid] < S:
            start = mid+1
            continue

    return False
array.sort()
result = BS(0,N-1)
if result == False:
    print('찾는 원소 없음')
else:
    print(result+1)


import socket as sc
from time import sleep

HOST_1 = '192.168.137.219' # 클라이언트
HOST_2 = '0.0.0.0' # 서버
PORT_1 = 1004
PORT_2 = 31004

socket_1 = sc.socket(sc.AF_INET, sc.SOCK_STREAM)
socket_2 = sc.socket(sc.AF_INET, sc.SOCK_STREAM)
socket_2.setsockopt(sc.SOL_SOCKET, sc.SO_REUSEADDR, 1)

socket_1.connect((HOST_1, PORT_1))

socket_2.bind((HOST_2, PORT_2))
socket_2.listen()

client, addr = socket_2.accept()

while True:
    signal = socket_1.recv(8)

    if signal.decode() == 'add':
        client.sendall(signal)

        name = socket_1.recv(64)
        print(len(name.decode('utf-8')))
        client.sendall(name);sleep(0.01)

        data = socket_1.recv(4096)
        print(len(data.decode()))
        client.sendall(data)

    # caution 시그널은 라즈베리파이 모터 속도 늦춤
    elif signal.decode() == 'caution':
        # 라즈베리파이로 시그널 전송
        client.sendall(signal)

    # danger 시그널은 라즈베리파이 모터 멈춤
    elif signal.decode() == 'intrusion':
        # 라즈베리파이에 시그널 전송
        client.sendall(signal)


import arcade
from arcade import View, Window
from arcade.gui import UIImageButton
from arcade.gui.layouts.box import UIBoxLayout
from arcade.gui.layouts.manager import UILayoutManager

BUTTON_NORMAL = arcade.load_texture(":resources:gui_basic_assets/red_button_normal.png")
HOVERED_TEXTURE = arcade.load_texture(
    ":resources:gui_basic_assets/red_button_hover.png"
)
PRESSED_TEXTURE = arcade.load_texture(
    ":resources:gui_basic_assets/red_button_press.png"
)

class MenuButton(UIImageButton):
    def __init__(self, text):
        super().__init__(
            text=text,
            normal_texture=BUTTON_NORMAL,
            hover_texture=HOVERED_TEXTURE,
            press_texture=PRESSED_TEXTURE,
        )

class MyView(View):
    def __init__(self, window=None):
        super().__init__(window=window)
        self.ui_manager = UILayoutManager(window=window)

    def on_show_view(self):
        arcade.set_background_color(arcade.color.WHITE)
        self.ui_manager.enable()

        # Add BoxLayout centered on screen
        menu = self.ui_manager.pack(UIBoxLayout(), center_x=0, center_y=0)

        # add button to menu
        start_button = menu.pack(MenuButton("Start Game"))
        start_button.on_click = self.start_game

        # same code but different syntax
        menu.pack(MenuButton("Settings"), space=20).on_click = self.open_settings

        # Add exit button
        menu.pack(MenuButton("Exit"), space=20).on_click = self.exit_game

        # manually call `do_layout()`, so everything is ready on the first `on_draw()` call
        self.ui_manager.do_layout()

    def start_game(self):
        print("Open GameView")
        # self.window.show_view(GameView())

    def open_settings(self):
        print("Open SettingsView")
        # self.window.show_view(SettingsView())

    def exit_game(self):
        print("Exit game")
        self.window.close()

    def on_draw(self):
        arcade.start_render()
        self.ui_manager.on_draw()

def main():
    window = Window(resizable=True)
    window.show_view(MyView())
    arcade.run()

if __name__ == "__main__":
    main()


# -*- coding: utf-8; py-indent-offset:4 -*-
from __future__ import absolute_import, division, print_function, unicode_literals

import datetime

import backtrader as bt
import backtrader.feeds as btfeed
from btplotting import BacktraderPlotting

class firstStrategy(bt.Strategy):
    params = (('maperiod', 5),)

    def log(self, txt, dt=None, doprint=False):
        '''日志函数，用于统一输出日志格式'''
        if doprint:
            dt = dt or self.datas[0].datetime.date(0)
            print('%s, %s' % (dt.isoformat(), txt))

    def __init__(self):
        self.dataclose = self.datas[0].close

        self.order = None
        self.buyprice = None
        self.buycomm = None

        # 五日移动平均线
        self.sma5 = bt.indicators.SimpleMovingAverage(self.datas[0], period=5)
        # 十日移动平均线
        self.sma10 = bt.indicators.SimpleMovingAverage(self.datas[0], period=10)
        self.sma30 = bt.indicators.SimpleMovingAverage(self.datas[0], period=30)

    def notify_order(self, order):
        """
        订单状态处理

        Arguments:
            order {object} -- 订单状态
        """
        if order.status in [order.Submitted, order.Accepted]:
            # 如订单已被处理，则不用做任何事情
            return

        # 检查订单是否完成
        if order.status in [order.Completed]:
            if order.isbuy():
                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm
            self.bar_executed = len(self)

        # 订单因为缺少资金之类的原因被拒绝执行
        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('Order Canceled/Margin/Rejected')

        # 订单状态处理完成，设为空
        self.order = None

    def notify_trade(self, trade):
        """
        交易成果

        Arguments:
            trade {object} -- 交易状态
        """
        if not trade.isclosed:
            return

        # 显示交易的毛利率和净利润
        self.log(
            'OPERATION PROFIT, GROSS %.2f, NET %.2f' % (trade.pnl, trade.pnlcomm),
            doprint=True,
        )

    def next(self):
        '''下一次执行'''

        # 记录收盘价
        self.log('Close, %.2f' % self.dataclose[0])

        # 是否正在下单，如果是的话不能提交第二次订单
        if self.order:
            return

        # 是否已经买入
        if not self.position:
            # 还没买，如果 MA5 > MA10 说明涨势，买入
            if self.sma5[0] > self.sma10[0]:
                self.order = self.buy()
        else:
            # 已经买了，如果 MA5 < MA10，说明跌势，卖出
            if self.sma5[0] < self.sma10[0]:
                self.order = self.sell()

    def stop(self):
        self.log(
            u'(金叉死叉有用吗) Ending Value %.2f' % (self.broker.getvalue()), doprint=True
        )

class BSCSVData(btfeed.GenericCSVData):
    params = (
        ("fromdate", datetime.datetime(2020, 1, 1)),
        ("todate", datetime.datetime(2022, 12, 31)),
        ('dtformat', ('%Y-%m-%d')),
        ('openinterest', -1),
    )

if __name__ == '__main__':
    cerebro = bt.Cerebro()
    cerebro.addstrategy(firstStrategy)
    cerebro.broker.setcash(1000000.0)
    cerebro.broker.setcommission(commission=0.001)

    data = BSCSVData(dataname="../../datas/baostock/{0}".format('bs_sh.000905.csv'))
    cerebro.adddata(data)
    cerebro.addsizer(bt.sizers.FixedSize, stake=100)

    cash_1 = cerebro.broker.getvalue()
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    cerebro.run()
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    cash_2 = cerebro.broker.getvalue()

    # 计算总回报率和年度回报率
    return_all = cerebro.broker.getvalue() / 1000000.0
    print(
        'Total ROI: {0}%, Annual ROI{1}%, comm: {2}'.format(
            round((return_all - 1.0) * 100, 2),
            round((pow(return_all, 1.0 / 10) - 1.0) * 100, 2),
            cash_2 - cash_1,
        )
    )

    p = BacktraderPlotting(
        style='bar',
    )
    cerebro.plot(p)


# Python's random module could be helpful for pseudorandom decisions
# https://docs.python.org/3/library/random.html

import os
import random
import re
import sys

DAMPING = 0.85
SAMPLES = 10000

# main expects command line argument (name of directory containing web pages)
def main():
    if len(sys.argv) != 2:
        sys.exit("Usage: python pagerank.py corpus")
    corpus = crawl(sys.argv[1])

    # estimate PageRank of each page by sampling -> arguments: corpus of pages generated by crawl above and damping number and sample size
    ranks = sample_pagerank(corpus, DAMPING, SAMPLES)
    print(f"PageRank Results from Sampling (n = {SAMPLES})")
    for page in sorted(ranks):
        # keys in that dictionary represent pages (e.g., "2.html"), and the values of the dictionary are a set of all of the pages linked to by the key (e.g. {"1.html", "3.html"}). -> return dictionary with page names as keys and respective PageRank per page (number between 0 and 1)
        print(f"  {page}: {ranks[page]:.4f}")

        # calls iterate_pagerank which will calculate PR for each page using the iterative formula instead of sampling
    ranks = iterate_pagerank(corpus, DAMPING)
    print(f"PageRank Results from Iteration")
    for page in sorted(ranks):
        print(f"  {page}: {ranks[page]:.4f}")

def crawl(directory):
    """
    Parse a directory of HTML pages and check for links to other pages.
    Return a dictionary where each key is a page, and values are
    a list of all other pages in the corpus that are linked to by the page.

    """
    pages = dict()

    # Extract all links from HTML files
    for filename in os.listdir(directory):
        if not filename.endswith(".html"):
            continue
        with open(os.path.join(directory, filename)) as f:
            contents = f.read()
            links = re.findall(r"<a\s+(?:[^>]*?)href=\"([^\"]*)\"", contents)
            pages[filename] = set(links) - {filename}

    # Only include links to other pages in the corpus
    for filename in pages:
        pages[filename] = set(
            link for link in pages[filename]
            if link in pages
        )

    return pages

def transition_model(corpus, page, damping_factor):
    """
    Return a probability distribution over which page to visit next,
    given a current page.

    With probability `damping_factor`, choose a link at random
    linked to by `page`. With probability `1 - damping_factor`, choose
    a link at random chosen from all pages in the corpus.
    """
    raise NotImplementedError

def sample_pagerank(corpus, damping_factor, n):
    """
    Return PageRank values for each page by sampling `n` pages
    according to transition model, starting with a page at random.

    Return a dictionary where keys are page names, and values are
    their estimated PageRank value (a value between 0 and 1). All
    PageRank values should sum to 1.
    """
    raise NotImplementedError

def iterate_pagerank(corpus, damping_factor):
    """
    Return PageRank values for each page by iteratively updating
    PageRank values until convergence.

    Return a dictionary where keys are page names, and values are
    their estimated PageRank value (a value between 0 and 1). All
    PageRank values should sum to 1.
    """
    raise NotImplementedError

if __name__ == "__main__":
    main()


from datetime import date
from django import forms
from django.forms.widgets import Select, RadioSelect
from django.conf import settings

from baseapp.modelspackage.animals import Animal
from baseapp.modelspackage.colours import Colour
from browse.modelspackage.sites import SiteManager, Site

from itertools import chain

# This tuple is defined elsewhere but I am not comfortable
# using that tuple unless they are all unified in one place
# otherwise we have too strong a coupling between the applications
GENDER_CHOICES = (('male', 'Male'), ('female', 'Female'))

EDUCATION_LEVEL_CHOICES = ((None, 'Unknown'),
							('primary to junior high', 'Primary to Junior High'),
							('school certificate', 'School Certificate'),
							('Bachelor Degree','Bachelor Degree' ),
							('higher school certificate', 'Higher School Certificate'),
							('Diploma', 'Diploma'),
							('Graduate Certificate', 'Graduate Certificate'),
							('Advanced Diploma', 'Advanced Diploma'),
							('Masters Degree', 'Masters Degree'),
							('Vocational Graduate Certificate','Vocational Graduate Certificate'),
							('Vocational Graduate Diploma', 'Vocational Graduate Diploma'),
							('Doctoral Degree', 'Doctoral Degree'),
							('Associate Degree', 'Associate Degree'),
							('TAFE Certificate', 'TAFE Certificate'),
							('Graduate Diploma', 'Graduate Diploma')
						)

def get_years():
  current_year = date.today().year
  return ((i, i) for i in range(current_year - 100, current_year - 18))

def get_sites():
	siteManager = SiteManager(client_json=settings.PPCLIENT)
	sites =  siteManager.all()
	choices = []
	for site in sites:
		choices.append((site.label,site.name))
	return choices

class LoginForm(forms.Form):

  animal      = forms.ModelChoiceField(queryset = Animal.objects.order_by('name'), initial = 1, widget = Select(attrs={'class':'form-control'}))
  colour      = forms.ModelChoiceField(queryset = Colour.objects.all(), initial = 1, widget = Select(attrs={'class':'form-control'}))
  birth_year  = forms.ChoiceField(choices = get_years(), widget = Select(attrs={'class':'form-control'}))
  gender = forms.ChoiceField(choices = GENDER_CHOICES, widget = RadioSelect, initial = 'male')

#class Password_Reset_Form(forms.Form):
class ColourAnimalHelperForm(forms.Form):
	pwd_site = forms.ChoiceField(choices = get_sites(), widget= Select(attrs={'class':'form-control'}))
	pwd_highest_qual = forms.ChoiceField(choices = sorted(EDUCATION_LEVEL_CHOICES), widget=Select(attrs={'class':'form-control'}), required=False)
	pwd_father_highest_qual = forms.ChoiceField(choices = sorted(EDUCATION_LEVEL_CHOICES), widget=Select(attrs={'class':'form-control'}), required=False)
	pwd_mother_highest_qual = forms.ChoiceField(choices = sorted(EDUCATION_LEVEL_CHOICES), widget=Select(attrs={'class':'form-control'}), required=False)


# blender --background --python 08_animation.py --render-anim -- </path/to/output/directory>/<name> <resolution_percentage> <num_samples>
# ffmpeg -r 24 -i </path/to/output/directory>/<name>%04d.png -pix_fmt yuv420p out.mp4

import bpy
import sys
import math
import os

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import utils
import external.cc0assetsloader as loader

def set_scene_objects():
    loader.build_pbr_textured_nodes_from_name("Metal07")
    loader.build_pbr_textured_nodes_from_name("Marble01")

    current_object = utils.create_smooth_monkey(location=(0.0, 0.0, 1.0), rotation=(0.0, 0.0, -math.pi * 60.0 / 180.0))
    current_object.data.materials.append(bpy.data.materials["Metal07"])

    # Keyframes
    current_object.location = (0.0, 0.0, 0.2)
    current_object.scale = (0.0, 0.0, 0.0)
    current_object.rotation_euler = (0.0, 0.0, -math.pi * (360.0 * 3.0 + 60.0) / 180.0)
    current_object.keyframe_insert(data_path='location', frame=4)
    current_object.keyframe_insert(data_path='scale', frame=4)
    current_object.keyframe_insert(data_path='rotation_euler', frame=4)
    current_object.location = (0.0, 0.0, 1.0)
    current_object.scale = (1.0, 1.0, 1.0)
    current_object.rotation_euler = (0.0, 0.0, -math.pi * 60.0 / 180.0)
    current_object.keyframe_insert(data_path='location', frame=42)
    current_object.keyframe_insert(data_path='scale', frame=42)
    current_object.keyframe_insert(data_path='rotation_euler', frame=42)

    current_object = utils.create_plane(size=12.0, name="Floor")
    current_object.data.materials.append(bpy.data.materials["Marble01"])

    bpy.ops.object.empty_add(location=(0.0, -0.70, 1.0))
    focus_target = bpy.context.object
    return focus_target

# Args
output_file_path = str(sys.argv[sys.argv.index('--') + 1])
resolution_percentage = int(sys.argv[sys.argv.index('--') + 2])
num_samples = int(sys.argv[sys.argv.index('--') + 3])

# Parameters
hdri_path = "./assets/HDRIs/green_point_park_2k.hdr"

# Scene Building
scene = bpy.data.scenes["Scene"]
world = scene.world

## Reset
utils.clean_objects()

## Suzannes
focus_target = set_scene_objects()

## Camera
bpy.ops.object.camera_add(location=(0.0, -16.0, 2.0))
camera_object = bpy.context.object

utils.add_track_to_constraint(camera_object, focus_target)
utils.set_camera_params(camera_object.data, focus_target, lens=85, fstop=0.5)

## Lights
utils.build_environment_texture_background(world, hdri_path)

## Composition
utils.build_scene_composition(scene)

# Animation Setting
utils.set_animation(scene, fps=24, frame_start=1, frame_end=48)

# Render Setting
utils.set_output_properties(scene, resolution_percentage, output_file_path)
utils.set_cycles_renderer(scene, camera_object, num_samples, use_motion_blur=True)


import FreeCADGui
import FreeCAD
import Path.Op.Adaptive as PathAdaptive
import Path.Op.Gui.Base as PathOpGui
import Path.Op.Gui.FeatureExtension as PathFeatureExtensionsGui
from PySide import QtCore

import Path.Base.Gui.Util as PathGuiUtil

class TaskPanelOpPage(PathOpGui.TaskPanelPage):
    def getForm(self):
        """getForm() ... return UI"""

        form = FreeCADGui.PySideUic.loadUi(":/panels/PageOpAdaptiveEdit.ui")
        comboToPropertyMap = [("Side", "Side"), ("OperationType", "OperationType")]

        enumTups = PathAdaptive.PathAdaptive.propertyEnumerations(dataType="raw")

        self.populateCombobox(form, enumTups, comboToPropertyMap)
        return form

    def initPage(self, obj):
        self.form.LiftDistance.setProperty(
            "unit", obj.LiftDistance.getUserPreferred()[2]
        )
        self.form.HelixDiameterLimit.setProperty(
            "unit", obj.HelixDiameterLimit.getUserPreferred()[2]
        )
        self.form.KeepToolDownRatio.setProperty(
            "unit", obj.KeepToolDownRatio.getUserPreferred()[2]
        )
        self.form.StockToLeave.setProperty(
            "unit", obj.StockToLeave.getUserPreferred()[2]
        )

    def getSignalsForUpdate(self, obj):
        """getSignalsForUpdate(obj) ... return list of signals for updating obj"""
        signals = []
        signals.append(self.form.Side.currentIndexChanged)
        signals.append(self.form.OperationType.currentIndexChanged)
        signals.append(self.form.ToolController.currentIndexChanged)
        signals.append(self.form.stepOverPercent.valueChanged)
        signals.append(self.form.Tolerance.valueChanged)
        signals.append(self.form.HelixAngle.valueChanged)
        signals.append(self.form.HelixConeAngle.valueChanged)
        signals.append(self.form.HelixDiameterLimit.valueChanged)
        signals.append(self.form.LiftDistance.valueChanged)
        signals.append(self.form.KeepToolDownRatio.valueChanged)
        signals.append(self.form.StockToLeave.valueChanged)
        signals.append(self.form.coolantController.currentIndexChanged)
        signals.append(self.form.ForceInsideOut.stateChanged)
        signals.append(self.form.FinishingProfile.stateChanged)
        signals.append(self.form.useOutline.stateChanged)
        signals.append(self.form.StopButton.toggled)
        return signals

    def setFields(self, obj):
        self.selectInComboBox(obj.Side, self.form.Side)
        self.selectInComboBox(obj.OperationType, self.form.OperationType)
        self.form.stepOverPercent.setValue(obj.StepOver)
        self.form.Tolerance.setValue(int(obj.Tolerance * 100))

        self.form.HelixAngle.setText(
            FreeCAD.Units.Quantity(obj.HelixAngle, FreeCAD.Units.Angle).UserString
        )

        self.form.HelixConeAngle.setText(
            FreeCAD.Units.Quantity(obj.HelixConeAngle, FreeCAD.Units.Angle).UserString
        )

        self.form.HelixDiameterLimit.setProperty(
            "rawValue", obj.HelixDiameterLimit.Value
        )

        self.form.LiftDistance.setProperty("rawValue", obj.LiftDistance.Value)

        if hasattr(obj, "KeepToolDownRatio"):
            self.form.KeepToolDownRatio.setProperty(
                "rawValue", obj.KeepToolDownRatio.Value
            )
            # self.form.KeepToolDownRatio.setValue(obj.KeepToolDownRatio)

        if hasattr(obj, "StockToLeave"):
            self.form.StockToLeave.setProperty("rawValue", obj.StockToLeave.Value)

        self.form.ForceInsideOut.setChecked(obj.ForceInsideOut)
        self.form.FinishingProfile.setChecked(obj.FinishingProfile)
        self.form.useOutline.setChecked(obj.UseOutline)
        self.setupToolController(obj, self.form.ToolController)
        self.setupCoolant(obj, self.form.coolantController)
        self.form.StopButton.setChecked(obj.Stopped)
        obj.setEditorMode("AdaptiveInputState", 2)  # hide this property
        obj.setEditorMode("AdaptiveOutputState", 2)  # hide this property
        obj.setEditorMode("StopProcessing", 2)  # hide this property
        obj.setEditorMode("Stopped", 2)  # hide this property

    def getFields(self, obj):
        if obj.Side != str(self.form.Side.currentData()):
            obj.Side = str(self.form.Side.currentData())

        if obj.OperationType != str(self.form.OperationType.currentData()):
            obj.OperationType = str(self.form.OperationType.currentData())

        if obj.StepOver != self.form.stepOverPercent.value():
            obj.StepOver = self.form.stepOverPercent.value()

        obj.Tolerance = 1.0 * self.form.Tolerance.value() / 100.0
        PathGuiUtil.updateInputField(obj, "HelixAngle", self.form.HelixAngle)
        PathGuiUtil.updateInputField(obj, "HelixConeAngle", self.form.HelixConeAngle)
        PathGuiUtil.updateInputField(
            obj, "HelixDiameterLimit", self.form.HelixDiameterLimit
        )
        PathGuiUtil.updateInputField(obj, "LiftDistance", self.form.LiftDistance)

        if hasattr(obj, "KeepToolDownRatio"):
            PathGuiUtil.updateInputField(
                obj, "KeepToolDownRatio", self.form.KeepToolDownRatio
            )

        if hasattr(obj, "StockToLeave"):
            PathGuiUtil.updateInputField(obj, "StockToLeave", self.form.StockToLeave)

        obj.ForceInsideOut = self.form.ForceInsideOut.isChecked()
        obj.FinishingProfile = self.form.FinishingProfile.isChecked()
        obj.UseOutline = self.form.useOutline.isChecked()
        obj.Stopped = self.form.StopButton.isChecked()
        if obj.Stopped:
            self.form.StopButton.setChecked(False)  # reset the button
            obj.StopProcessing = True

        self.updateToolController(obj, self.form.ToolController)
        self.updateCoolant(obj, self.form.coolantController)
        obj.setEditorMode("AdaptiveInputState", 2)  # hide this property
        obj.setEditorMode("AdaptiveOutputState", 2)  # hide this property
        obj.setEditorMode("StopProcessing", 2)  # hide this property
        obj.setEditorMode("Stopped", 2)  # hide this property

    def taskPanelBaseLocationPage(self, obj, features):
        if not hasattr(self, "extensionsPanel"):
            self.extensionsPanel = PathFeatureExtensionsGui.TaskPanelExtensionPage(
                obj, features
            )
        return self.extensionsPanel

Command = PathOpGui.SetupOperation(
    "Adaptive",
    PathAdaptive.Create,
    TaskPanelOpPage,
    "Path_Adaptive",
    QtCore.QT_TRANSLATE_NOOP("Path_Adaptive", "Adaptive"),
    QtCore.QT_TRANSLATE_NOOP("Path_Adaptive", "Adaptive clearing and profiling"),
    PathAdaptive.SetupProperties,
)


from django.core.urlresolvers import reverse

from rest_framework import serializers

from ..models import PostLike

__all__ = [
    'PostLikeSerializer',
]

class PostLikeSerializer(serializers.ModelSerializer):
    user_id = serializers.SerializerMethodField()
    username = serializers.SerializerMethodField()

    url = serializers.SerializerMethodField()

    class Meta:
        model = PostLike
        fields = (
            'id',
            'liked_on',

            'user_id',
            'username',

            'url',
        )

    def get_user_id(self, obj):
        return obj['user_id']

    def get_username(self, obj):
        return obj['user_name']

    def get_url(self, obj):
        if obj['user_id']:
            return reverse('misago:user', kwargs={
                'slug': obj['user_slug'],
                'pk': obj['user_id'],
            })
        else:
            return None


import pandas as pd
import numpy as np
import datetime

import advent_of_code as aoc

## Read in input
num = 6
#lines = aoc.input_readlines(num,test=True) # read in test data
lines = aoc.input_readlines(num)
lines = [line.strip('\n') for line in lines]
verbose = True

## Functions ##################################################
def incr_one_day(state):
    ''' state is a numpy array
    '''

    state = state - 1
    find_neg_ones = np.where(state == -1)[0]

    ## WHY DOESN'T np array have an extend in place??
    if find_neg_ones.size > 0:
        state_list = state.tolist()
        state_list.extend(find_neg_ones.size*[8])
        state = np.array(state_list)
    state[find_neg_ones] = 6

    return state

## PART 1  ##################################################
init = [int(fish) for fish in lines[0].split(',')]
state = np.array(init)

#ndays = 18
ndays = 80
for iday in range(ndays):
    state = incr_one_day(state)
    if verbose:
        print(state)

print(f'Answer: {state.size}')

## PART 2  ##################################################

## Way of doing PART 1 waaaaay too slow, redid to optimize
init_time = datetime.datetime.now()
init = [int(fish) for fish in lines[0].split(',')]
ndays = 256

## Go through initial set of fish
## Track new fish in nfish_dict
## nfish_dict key = day new fish spawned
## nfish_dict value = number of new fish spawned that day
total_fish = len(init)
nfish_dict = {}
nfish_dict_total = {} ## for troubleshooting only
nitems  = 0 ## for curiousity
for ifish in init:

    if ifish < ndays % 7:
        spawned = int(np.ceil(ndays/7))
    else:
        spawned = int(np.floor(ndays/7))

    for i in range(spawned):
        born_day = i*(7)+ifish+1
        str_born_day = str(born_day)
        if str_born_day in nfish_dict:
            nfish_dict[str_born_day] += 1
            nfish_dict_total[str_born_day] += 1
        else:
            nfish_dict[str_born_day] = 1
            nfish_dict_total[str_born_day] = 1
            nitems += 1
    total_fish += spawned

## Go through each iteration of new fish
## Track new fish in nfish_dict
## nfish_dict key = day new fish spawned
## nfish_dict value = number of new fish spawned that day
## Track newest round of fish in new_nfish_dict (which will be set to nfish_dict at end of while)

stop_while = 0
#counter = 30 ## for troubleshooting while loop
while (stop_while == 0):

    if verbose:
        print(f'Number of iterations in for loop this time: {nitems}')

    ## Go through new batch of spawned fish
    nitems = 0
    new_nfish_dict = {}
    for ifish_key,ifish_val in nfish_dict.items():
        ifish = int(ifish_key)

        ## New fish will spawn 9 days after it spawned
        ## Keep track of fish spawned, handling first spawn differently
        first_spawn_day = ifish + 9
        spawned = []
        if first_spawn_day <= ndays:
            ## CASE: fish will spawn before ndays is over, need to include and track
            spawned.append(first_spawn_day)

            ## After initial spawning, a fish will produce a new fish every 7 days
            spawned_after_first = int(np.floor((ndays - first_spawn_day) / 7))
            if spawned_after_first > 0:
                ## CASE: fish will spawn more after first spawn, need to include and track
                spawned.extend([i*(7)+first_spawn_day
                                for i in range(1,spawned_after_first + 1)])

            ## For each new fish, add to new_nfish_dict
            ##  this will become the next dictionary to iterate over (the next nfish_dict)
            for born_day in spawned:
                str_born_day = str(born_day)
                if str_born_day in new_nfish_dict:
                    new_nfish_dict[str_born_day] += ifish_val
                else:
                    new_nfish_dict[str_born_day] = ifish_val
                    nitems += 1

                ## For troubleshooting only
                if str_born_day in nfish_dict_total:
                    nfish_dict_total[str_born_day] += 1
                else:
                    nfish_dict_total[str_born_day] = 1

    ## Track how many fish spawned this time
    total_fish += sum(new_nfish_dict.values())
    if verbose:
        print(f'Total fish: {total_fish}')

    ## If no new fish spawned this time, break while loop
    nfish_dict = new_nfish_dict
    if nfish_dict == {}:
        stop_while = 1

    #counter -= 1
    #if counter == 0:
    #    stop_while = 1

stop_time = datetime.datetime.now()
print(f'Answer: {total_fish}')
print(f'Computation time: {stop_time - init_time}')


# 요세푸스 문제와 동일
# 메모리 제한 128MB

# N과 K가 주어지면, 마지막으로 남는 사람의 번호를 구하는 프로그램을 작성하시오.

# 예제 입력 1
# 7 3

# 예제 출력 1
# 4

# 1. 메모리 초과
import sys
from collections import deque

n, k = map(int, sys.stdin.readline().split())
dq = list(range(1, n+1))
dq = deque(dq)

while dq:
    for _ in range(k-1):
        cur = dq.popleft()
        dq.append(cur)
    dq.popleft()
    if len(dq) == 1:
        print(dq[0])
        break

1178_마지막요세푸스문제.py


def prints(num, res):
    if num != 0:
        return prints(num-1, " " + str(num) + res)
    else:
        return res[1:]+" "

NumOfEg = int(input())
result = []
for i in range(NumOfEg):
    num = int(input())
    res = ""
    res = prints(num, res)
    result.append(res)
for k in result:
    print(k)


import pygame
import random as rd
import os
import time
import tkinter as tk

rd.seed()
pygame.init()

# different mouseclicks
LEFT = 1
RIGHT = 3

# leben
leben = 1

# temp variable to check for first playthrough
first_t_start = True

# temp variable
temp = True
temp2 = True

# fieldsize
fgröse = 14

# percent of bombs
bomb_perc = 20

# how many bombs
bomb_anz = round((bomb_perc*(fgröse**2))//100)

# masks for different playstyles

Standard = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,0), (0,1), (1,-1), (1,0), (1,1)]
Kreuz = [(-1,0),(0,-1),(0,0),(0,1),(1,0)]

masklist = {"Default":Standard, "Cross":Kreuz}

# window to choose the playstyle
main = tk.Tk("Minesweeper")

# variable for index of playstyle
var = tk.IntVar()
var.set(0)

# button function
def quit_loop():
    global selection
    selection = var.get()
    main.destroy()

tk.Label(main, text="Choose playstyle", font=("Default", 15)).grid(row=0)

for masksnum in range(len(masklist)):

    # create a radiobutton for every element in masklist
    tk.Radiobutton(main, text=list(masklist.keys())[masksnum], variable=var, value=masksnum, font=("Default", 15)).grid(row=masksnum+1)

# start button
button = tk.Button(main, text="Start", command=quit_loop, font=("Default", 15)).grid(row=len(masklist)+1)

main.mainloop()

try:
    mask = list(masklist.values())[selection]
except:
    os._exit(1)

# for fields that have 0 bombs around them
nkl = []

# list for counting bombs on start of the game
cl = []

# all correctly clicked fields
rfelder = set()

# generating field
field = [["O" for i in range(fgröse)] for i in range(fgröse)]

color = 1

# colors
grün = (50,205,50)
weis = (255, 255, 255)
rot = (255, 0, 0)
grau = (238,232,170)
orange = (255,165,0)
schwarz = (0,0,0)

# colors for the board
colors = [(50,205,50), (152,251,152)]

# how much fields you have to click to win (Changes as soon as game starts)
rn = 1

x = 1
y = 1
z = 0
s = 0

gröse = 50

def add_bombs(field, mx, my):

    # list of start coordinates
    startcords = []

    for tup_mask in mask:

                # tupel
                addx, addy = tup_mask

                # add tupel coords to clicked coords
                addedx, addedy = addx + mx, addy + my

                if addedx >= 0 and addedy >= 0 and addedx < fgröse and addedy < fgröse:

                    # add startcoords to startcords list
                    startcords.append((addedx, addedy))

    # generate bombs
    global bomben
    bomben = set()

    while len(bomben) != bomb_anz:
        bombe = (rd.randint(0,fgröse-1), rd.randint(0,fgröse-1))

        if bombe not in startcords:

            bomben.add(bombe)

    # add bombs
    for i in bomben:
            b_höhe, b_breite = i
            field[b_höhe][b_breite] = "+"

for a in range(len(field)):
    for b in range(len(field[a])):

        # check if not a bomb
        if field[a][b] != "+":

            for tup_mask in mask:

                # tupel
                addx, addy = tup_mask
                # add tupel coords to clicked coords
                addedx, addedy = addx + a, addy + b

                if addedx >= 0 and addedy >= 0 and addedx < fgröse and addedy < fgröse:

                    # add fields to cl to count them
                    cl.append(field[addedx][addedy])

            bomb_count = cl.count("+")
            field[a][b] = str(bomb_count)
            cl = []

width = fgröse * gröse + (fgröse - 1) * 1
height = fgröse * gröse + (fgröse - 1) * 1

game_over = False

screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Minesweeper")

while True:

    if len(rfelder) >= rn and temp2:
        print("You have won!")

        for bombs in bomben:

            # tupel
            bx, by = bombs

            # show every bomb on field with red color
            pygame.draw.rect(screen, grün, (bx*gröse+(bx*1)+1, by*gröse+(by*1)+1, gröse, gröse))

        game_over = True
        temp2 = False

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            os._exit(1)

        if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT and game_over == False:

            pos = pygame.mouse.get_pos()
            mx, my = pos
            mx = int((mx-(int(mx/gröse)*1))/gröse)
            my = int((my-(int(my/gröse)*1))/gröse)

            if first_t_start:
                add_bombs(field, mx, my)

                for a in range(len(field)):
                    for b in range(len(field[a])):

                        # check if not a bomb
                        if field[a][b] != "+":

                            for tup_mask in mask:

                                # tupel
                                addx, addy = tup_mask

                                # add tupel coords to clicked coords
                                addedx, addedy = addx + a, addy + b

                                if addedx >= 0 and addedy >= 0 and addedx < fgröse and addedy < fgröse:

                                    # add fields to cl to count them
                                    cl.append(field[addedx][addedy])

                            bomb_count = cl.count("+")
                            field[a][b] = str(bomb_count)
                            cl = []

                # how much fields to win
                rn = int(fgröse**2-len(bomben))
                print("Correct needed:", rn)
                first_t_start = False

            if field[mx][my] != "+" and pygame.Surface.get_at(screen, pos) != grau and pygame.Surface.get_at(screen, pos) != schwarz and field[mx][my] != "0":
                pygame.draw.rect(screen, grau, (mx*gröse+(mx*1)+1, my*gröse+(my*1)+1, gröse, gröse))
                myfont = pygame.font.SysFont('Comic Sans MS', int(gröse/2.5))
                textsurface = myfont.render(field[mx][my], False, (0, 0, 0))
                screen.blit(textsurface,(mx*gröse+(mx*1)+gröse/2.3, my*gröse+(my*1)+gröse/3.7))

                # add correct field to rfelder
                rfelder.add((mx,my))
                print("Correct:", len(rfelder))

            elif field[mx][my] == "+":

                pygame.draw.rect(screen, rot, (mx*gröse+(mx*1)+1, my*gröse+(my*1)+1, gröse, gröse))
                pygame.display.update()

                # give the player time to process what they have done
                time.sleep(0.5)

                game_over = True

            elif field[mx][my] == "0" and pygame.Surface.get_at(screen, pos) != grau and pygame.Surface.get_at(screen, pos) != schwarz:

                # add first coords
                nkl.append((mx,my))

                # loop as long all fields are checked
                while len(nkl) != 0:

                    # take mx, my from the list
                    mx, my = nkl[0]

                    for tup_mask in mask:

                        # tupel
                        addx, addy = tup_mask

                        # add tupel coords to clicked coords
                        addedx, addedy = addx + mx, addy + my

                        # try/except because of bug in last row
                        try:
                            if addedx >= 0 and addedy >= 0 and addedx <= fgröse-1 and addedy <= fgröse-1:

                                # make field yellow/grey
                                pygame.draw.rect(screen, grau, (addedx*gröse+(addedx*1)+1, addedy*gröse+(addedy*1)+1, gröse, gröse))

                                # show numbers
                                myfont = pygame.font.SysFont('Comic Sans MS', int(gröse/2.5))
                                textsurface = myfont.render(field[addedx][addedy], False, (0, 0, 0))
                                screen.blit(textsurface,(addedx*gröse+(addedx*1)+gröse/2.3, addedy*gröse+(addedy*1)+gröse/3.7))

                                # add field to nkl if not in rfelder
                                if field[addedx][addedy] == "0" and field[addedx][addedy] != "+" and (addedx,addedy) not in rfelder:

                                    nkl.append((addedx, addedy))

                                # add field to rfelder
                                rfelder.add((addedx,addedy))

                        except IndexError:
                            continue

                    # pop first element
                    nkl.pop(0)

                print("Correct:", len(rfelder))

        # still bugy
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == RIGHT and not game_over:
            pos = pygame.mouse.get_pos()
            mx, my = pos
            mx = int((mx-(int(mx/gröse)*1))/gröse)
            my = int((my-(int(my/gröse)*1))/gröse)

            if pygame.Surface.get_at(screen, pos) == colors[0] or pygame.Surface.get_at(screen, pos) == colors[1]:
                cc = pygame.Surface.get_at(screen, pos)
                pygame.draw.rect(screen, orange, (mx*gröse+(mx*1)+1, my*gröse+(my*1)+1, gröse, gröse))
            elif pygame.Surface.get_at(screen, pos) == orange:
                pygame.draw.rect(screen, cc, (mx*gröse+(mx*1)+1, my*gröse+(my*1)+1, gröse, gröse))

    # show all bombs if lost
    if game_over and temp and temp2:

        # iterate over all bombs
        for bombs in bomben:

            # tupel
            bx, by = bombs

            # show all bombs red
            pygame.draw.rect(screen, rot, (bx*gröse+(bx*1)+1, by*gröse+(by*1)+1, gröse, gröse))

        # so it doesnt draw the screen everytime some event happens
        temp = False

    # drawing the board
    while z != fgröse - 1 and s != fgröse - 1:

        #choose random color
        colo = rd.randint(0,1)

        for z in range(len(field)):

            # switch color every row if fgröse is even
            colo = (colo + 1) % 2 if fgröse % 2 == 0 else colo

            for s in range(len(field[z])):

                colo = (colo + 1) % 2

                pygame.draw.rect(screen, colors[colo], (x, y, gröse, gröse))

                # assign x, y coords
                y = y+gröse+1 if s == fgröse-1 else y
                x = x+gröse+1 if s != fgröse-1 else 1

    try:
        pygame.display.update()
    except:
        break


from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from core.models.user import UserAddon
from core.models.register import RegisterToken
from api.serializers.tokens import RegisterTokenSerializer
from django.http import Http404

class RegisterTokenAPIView(APIView):
    def get(self, request, token=None, *args, **kargs):
        # try:
        #     user = UserAddon.objects.get(token=token).user
        # except:
        #     return Response(status=status.HTTP_401_UNAUTHORIZED)
        # if user.is_staff()
        if token:
            try:
                tokens = RegisterToken.objects.get(id=token)
            except:
                return Response(status=status.HTTP_400_BAD_REQUEST)
            serializers = RegisterTokenSerializer(tokens, many=True)
        else:
            tokens = RegisterToken.objects.filter(use=False)
            serializers = RegisterTokenSerializer(tokens, many=True)
        return Response(serializers.data, status=status.HTTP_200_OK)
        # else:
        #     return Response(status=status.HTTP_401_UNAUTHORIZED)

    def post(self, request, *args, **kargs):
        re = RegisterToken()
        re.save()
        return Response(status=status.HTTP_201_CREATED)

class RegisterTokenDetail(APIView):
    """
    Retrieve, update or delete a snippet instance.
    """
    def get_object(self, pk):
        try:
            return RegisterToken.objects.get(pk=pk)
        except RegisterToken.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        rt = self.get_object(pk)
        serializer = RegisterTokenSerializer(rt)
        return Response(serializer.data)


#!/usr/bin/python3

import os
import signal
import sys
import syslog

from lockfile import FileLock, LockTimeout, AlreadyLocked
from twisted.internet import reactor, defer
from twisted.python import usage

from jasmin.protocols.smpp.configs import SMPPServerPBClientConfig
from jasmin.protocols.smpp.proxies import SMPPServerPBProxy
from jasmin.queues.configs import AmqpConfig
from jasmin.queues.factory import AmqpFactory
from jasmin.routing.configs import DLRThrowerConfig
from jasmin.routing.throwers import DLRThrower
from jasmin.config import ROOT_PATH
from jasmin.bin import BaseDaemon

CONFIG_PATH = os.getenv('CONFIG_PATH', '%s/etc/jasmin/' % ROOT_PATH)

class Options(usage.Options):
    optParameters = [
        ['config', 'c', '%s/dlr.cfg' % CONFIG_PATH,
         'Jasmin dlrd configuration file'],
        ['id', 'i', 'master',
         'Daemon id, need to be different for each dlrd daemon'],
    ]

    optFlags = [
    ]

class DlrDaemon(BaseDaemon):
    def startAMQPBrokerService(self):
        """Start AMQP Broker"""

        AMQPServiceConfigInstance = AmqpConfig(self.options['config'])
        self.components['amqp-broker-factory'] = AmqpFactory(AMQPServiceConfigInstance)
        self.components['amqp-broker-factory'].preConnect()

        # Add service
        self.components['amqp-broker-client'] = reactor.connectTCP(
            AMQPServiceConfigInstance.host,
            AMQPServiceConfigInstance.port,
            self.components['amqp-broker-factory'])

    def stopAMQPBrokerService(self):
        """Stop AMQP Broker"""

        return self.components['amqp-broker-client'].disconnect()

    def startSMPPServerPBClient(self):
        """Start SMPPServerPB client"""

        SMPPServerPBClientConfigInstance = SMPPServerPBClientConfig(self.options['config'])
        self.components['smpps-pb-client'] = SMPPServerPBProxy()

        return self.components['smpps-pb-client'].connect(
            SMPPServerPBClientConfigInstance.host,
            SMPPServerPBClientConfigInstance.port,
            SMPPServerPBClientConfigInstance.username,
            SMPPServerPBClientConfigInstance.password,
            retry=True)

    def stopSMPPServerPBClient(self):
        """Stop SMPPServerPB client"""

        if self.components['smpps-pb-client'].isConnected:
            return self.components['smpps-pb-client'].disconnect()

    def startDLRThrowerService(self):
        """Start DLRThrower"""

        DLRThrowerConfigInstance = DLRThrowerConfig(self.options['config'])
        self.components['dlr-thrower'] = DLRThrower(DLRThrowerConfigInstance)
        self.components['dlr-thrower'].addSmpps(self.components['smpps-pb-client'])

        # AMQP Broker is used to listen to DLRThrower queue
        return self.components['dlr-thrower'].addAmqpBroker(self.components['amqp-broker-factory'])

    def stopDLRThrowerService(self):
        """Stop DLRThrower"""
        return self.components['dlr-thrower'].stopService()

    @defer.inlineCallbacks
    def start(self):
        """Start Dlrd daemon"""
        syslog.syslog(syslog.LOG_INFO, "Starting Dlr Daemon ...")

        ########################################################
        # Start AMQP Broker
        try:
            self.startAMQPBrokerService()
            yield self.components['amqp-broker-factory'].getChannelReadyDeferred()
        except Exception as e:
            syslog.syslog(syslog.LOG_ERR, "  Cannot start AMQP Broker: %s" % e)
        else:
            syslog.syslog(syslog.LOG_INFO, "  AMQP Broker Started.")

        ########################################################
        try:
            # Start SMPPServerPB Client
            yield self.startSMPPServerPBClient()
        except Exception as e:
            syslog.syslog(syslog.LOG_ERR, "  Cannot start SMPPServerPBClient: %s" % e)
        else:
            syslog.syslog(syslog.LOG_INFO, "  SMPPServerPBClientStarted.")

        ########################################################
        try:
            # Start DLRThrower
            yield self.startDLRThrowerService()
        except Exception as e:
            syslog.syslog(syslog.LOG_ERR, "  Cannot start DLRThrower: %s" % e)
        else:
            syslog.syslog(syslog.LOG_INFO, "  DLRThrower Started.")

    @defer.inlineCallbacks
    def stop(self):
        """Stop Dlrd daemon"""
        syslog.syslog(syslog.LOG_INFO, "Stopping Dlr Daemon ...")

        if 'smpps-pb-client' in self.components:
            yield self.stopSMPPServerPBClient()
            syslog.syslog(syslog.LOG_INFO, "  SMPPServerPBClient stopped.")

        if 'dlr-thrower' in self.components:
            yield self.stopDLRThrowerService()
            syslog.syslog(syslog.LOG_INFO, "  DLRThrower stopped.")

        if 'amqp-broker-client' in self.components:
            yield self.stopAMQPBrokerService()
            syslog.syslog(syslog.LOG_INFO, "  AMQP Broker disconnected.")

        reactor.stop()

    def sighandler_stop(self, signum, frame):
        """Handle stop signal cleanly"""
        syslog.syslog(syslog.LOG_INFO, "Received signal to stop Dlr Daemon")

        return self.stop()

if __name__ == '__main__':
    lock = None
    try:
        options = Options()
        options.parseOptions()

        # Must not be executed simultaneously (c.f. #265)
        lock = FileLock("/tmp/dlrd-%s" % options['id'])

        # Ensure there are no paralell runs of this script
        lock.acquire(timeout=2)

        # Prepare to start
        dlr_d = DlrDaemon(options)
        # Setup signal handlers
        signal.signal(signal.SIGINT, dlr_d.sighandler_stop)
        signal.signal(signal.SIGTERM, dlr_d.sighandler_stop)
        # Start DlrDaemon
        dlr_d.start()

        reactor.run()
    except usage.UsageError as errortext:
        print('%s: %s' % (sys.argv[0], errortext))
        print('%s: Try --help for usage details.' % (sys.argv[0]))
    except LockTimeout:
        print("Lock not acquired ! exiting")
    except AlreadyLocked:
        print("There's another instance on dlrd running, exiting.")
    finally:
        # Release the lock
        if lock is not None and lock.i_am_locking():
            lock.release()


import pandas as pd
import numpy as np
#import math
#import matplotlib
#import matplotlib.pyplot as plt
#from IPython import get_ipython
#get_ipython().run_line_magic('matplotlib', 'inline')
#from sklearn import datasets, linear_model, preprocessing, model_selection
#import numpy.polynomial.polynomial as poly
#import scipy.io
#import sklearn
#import random
#import pickle

def iso_generator():
    #x = pd.read_csv('isoletx 1.csv', header=None).values
    #y = pd.read_csv('isolety.csv', header=None).values
    x = pd.read_csv('aloix.csv', header=None).values
    y = pd.read_csv('aloiy.csv', header=None).values
    data_size = len(y)
    shuffle = np.random.permutation(data_size)
    x = x[shuffle]
    y = y[shuffle]
    del shuffle
    #normalize
    #x = x-np.reshape(np.mean(x, axis=1), (data_size, 1))
    x = x/np.expand_dims(np.std(x, axis=1), axis=1)
    x[np.isinf(x)] = 0
    x = x - np.mean(x)
    for i in range(data_size):
        yield (x[i], y[i])

def mnist_generator():

    #load mnist
    from sklearn.datasets import fetch_mldata
    dataset = fetch_mldata("MNIST original")
    data_size = dataset.target.shape[0]
    #permutation
    shuffle = np.random.permutation(data_size)
    data = dataset.data[shuffle]
    label = dataset.target[shuffle]
    del shuffle, dataset

    #normalize
    #data = data-np.reshape(np.mean(data, axis=1), (data_size, 1))
    data = data/np.reshape(np.std(data, axis=1), (data_size, 1))
    data = data-np.mean(data)
    '''
    #resize 784 to 28*28
    data2 = np.zeros((data_size, 28, 28))
    for i in range (data_size):
    data2[i, ] = np.reshape(data[i, ], (28, 28))
    data = data2
    del data2
    '''
    for i in range(data_size):
        yield (data[i], label[i])

class fc_with_sigmoid(object):

    def __init__(self):
        self.w = .000001*(np.random.rand(128)-.5)
        self.b0 = .000001*(np.random.random()-.5)

    def test(self, x):
        y_hat = self.w.dot(x) + self.b0
        #print('y_hat =', y_hat)
        return 1/(1+np.exp(-y_hat))

    def train(self, x, c, lr=.05):
        y_hat = self.w.dot(x) + self.b0
        c_hat = 1/(1+np.exp(-y_hat))
        #print('w_before =', self.w[:5])
        temp = lr*(c_hat - c)/(np.exp(-y_hat)+1)/(np.exp(y_hat)+1)
        self.w = self.w - temp*x
        #print('w_after =', self.w[:5])
        #print('b0_before =', self.b0)
        self.b0 = self.b0 -temp
        #print('b0_after =', self.b0)

class node(object):

    def __init__(self, node_index):
        self.left = None
        self.right = None
        self.parent = None
        self.n_all = 0
        self.e_all = 0
        self.n = []
        self.e = []
        self.class_name = []
        self.ex = []
        self.c_his = []
        self.suspend_n = []
        self.suspend_e = []
        self.suspend_class_name = []
        self.node_index = node_index
        self.model = fc_with_sigmoid()

    def setLeft(self, node):
        self.left = node

    def setRight(self, node):
        self.right = node

    def setParent(self, node):
        self.parent = node

    def testModel(self, x):
        return self.model.test(x)

    def trainModel(self, x, c):
        self.model.train(x, c)

    def addClass(self, class_name):
        if class_name not in self.suspend_class_name:
            self.n.append(0)
            self.e.append(0)
            self.class_name.append(class_name)
            self.ex.append(0)
            self.c_his.append(int(0))
        else:
            index_in_suspend_class_name = self.suspend_class_name.index(class_name)
            self.n.append(self.suspend_n.pop(index_in_suspend_class_name))
            self.e.append(self.suspend_e.pop(index_in_suspend_class_name))
            self.class_name.append(self.suspend_class_name.pop(index_in_suspend_class_name))
            self.ex.append(0)
            self.c_his.append(int(0))

    def suspendClassInNode(self, class_name):
        class_index_in_node = self.class_name.index(class_name)
        self.suspend_n.append(self.n.pop(class_index_in_node))
        self.suspend_e.append(self.e.pop(class_index_in_node))
        self.suspend_class_name.append(self.class_name.pop(class_index_in_node))
        del self.ex[class_index_in_node]
        del self.c_his[class_index_in_node]

    def updateExpectation(self, c, class_index_in_node):
        self.n_all = self.n_all + 1
        self.e_all = self.e_all + c
        self.n[class_index_in_node] = self.n[class_index_in_node] + 1
        self.e[class_index_in_node] = self.e[class_index_in_node] + c
        self.ex[class_index_in_node] = self.e[class_index_in_node]/self.n[class_index_in_node]

    def findExceptionAll(self):
        if self.n_all == 0:
            return 0
        else:
            #mean
            #return self.e_all/self.n_all
            #medium
            #return np.median(np.array([self.findExceptionOneClass(i) for i in range(len(self.class_name))]))
            return np.median(self.ex)

    def findExceptionOneClass(self, class_index_in_node):
        if self.n[class_index_in_node] == 0:
            return 0
        else:
            return self.e[class_index_in_node]/self.n[class_index_in_node]

    def judgeInTrain(self, class_index_in_node):
        #c == 0: left, c == 1: right
        return int(self.findExceptionAll() <= self.findExceptionOneClass(class_index_in_node))

        #just assign the classes, to make sure tree is balanced
        #return class_index_in_node%2

    def judgeInTest(self, x):
        return int(self.findExceptionAll() <= self.testModel(x))

class tree(object):

    def __init__(self):
        self.nodes = []
        self.current_node_index = 0
        self.root = node(self.current_node_index)
        self.nodes.append(self.root)
        self.current_node_index = self.current_node_index + 1

    def giveBirth(self, node_index):
        #node_index is index of node in self.nodes, who is going to give birth to left and right
        #two new born nodes would be appended at the end of self.nodes
        self.nodes.append(node(self.current_node_index))
        self.current_node_index = self.current_node_index + 1
        self.nodes[node_index].setLeft(self.nodes[-1])
        self.nodes[-1].setParent(self.nodes[node_index])

        self.nodes.append(node(self.current_node_index))
        self.current_node_index = self.current_node_index + 1
        self.nodes[node_index].setRight(self.nodes[-1])
        self.nodes[-1].setParent(self.nodes[node_index])

    def deleteChilds(self, node):
        delete_index = node.left.node_index
        del self.nodes[delete_index]
        self.current_node_index = self.current_node_index - 1
        for i in range(delete_index, self.current_node_index):
            self.nodes[i].node_index = i

        delete_index = node.right.node_index
        del self.nodes[delete_index]
        self.current_node_index = self.current_node_index - 1
        for i in range(delete_index, self.current_node_index):
            self.nodes[i].node_index = i

        node.left = None
        node.right = None

    def suspendClass(self, class_name, node):
        node.suspendClassInNode(class_name)
        if len(node.class_name) == 1:
            #if this node loses(suspends) its last 2nd class, delete both its childs
            self.deleteChilds(node)
        elif len(node.class_name) == 0:
            #attention that, if this node loses its last class, it will NOT be deleted, and nothing special will be done
            #this will lead to a special temporary status: this node includes no class, its parent and sibling have the same classes
            #this temporary status will not last long, unless expection of samples arrives at its parent keep increase monotonically, which is unlikely for a pre-normalized dataset
            #this temporary status may cause problem for testing, because a leaf of the decision tree might cannot even give out a single class, and it is fixed in onlineTest function
            pass
        else:
            #recursive down
            if class_name in node.left.class_name:
                self.suspendClass(class_name, node.left)
            elif class_name in node.right.class_name:
                self.suspendClass(class_name, node.right)
            else:
                print('suspendClass fail in node: ', node)

    def onlineTrain(self, xy, node):
        x, y = xy
        #print('node_index =', node.node_index)

        #1:register if y is new in this node
        if_register = (y not in node.class_name)
        if if_register:
            node.addClass(y)

        #2:judge (if current h(x) is above average)
        class_index_in_node = node.class_name.index(y)
        #print('class_index_in_node =', class_index_in_node)
        #c == 0: left, c == 1: right
        c = node.judgeInTrain(class_index_in_node)
        #print('c =', c)

        #3:train
        node.trainModel(x, c)

        #4:update e, n
        c_hat = node.testModel(x)
        node.updateExpectation(c_hat, class_index_in_node)

        #5:give birth if second class arrives at this node
        if if_register and len(node.class_name) == 2:
            self.giveBirth(node.node_index)
            #the only previous class should be arranged to other child
            #though it cannot be trained in an online algorithm
            [node.left, node.right][1-c].addClass(node.class_name[0])

        #6:suspend a class recursively if this class no longer go to a child of this node
        if not if_register and node.c_his[class_index_in_node] == 1-c and node.left != None and y in [node.left, node.right][1-c].class_name:#this class's c changes
            self.suspendClass(y, [node.left, node.right][1-c])
        node.c_his[class_index_in_node] = c

        #7:a sample trains recursively down all the way to a leaf
        del x, y, if_register, class_index_in_node, c_hat
        if node.left != None:#if a node have child, then it must have exactly two childs
            self.onlineTrain(xy, [node.left, node.right][c])

    def startOnlineTrain(self, xy):
        self.onlineTrain(xy, self.root)

    def onlineTest(self, x, node):
        if len(node.class_name) == 1:
            return node.class_name[0]
        else:
            try:
                return self.onlineTest(x, [node.left, node.right][node.judgeInTest(x)])
                return self.onlineTest(x, [node.left, node.right][1-node.judgeInTest(x)])
                print('onlineTest return fail at node: ', node)
            except:
                pass

    def startOnlineTest(self, x):
        return self.onlineTest(x, self.root)

if __name__ == "__main__":

    #build
    #my_generator = mnist_generator()
    my_generator = iso_generator()
    my_tree = tree()

    #train
    for i in range(90000):
        if i%500 == 0:
            print('index of sample i =', i)
        my_tree.startOnlineTrain(next(my_generator))

    #test
    test_result = []
    for i in range(10000):
        x, y = next(my_generator)
        test_result.append(int(y == my_tree.startOnlineTest(x)))
    accurancy = np.mean(test_result)
    print('accurancy =', accurancy)


import idc
import idautils
import idaapi

import winsound
from datetime import datetime
import time
import string
from textwrap import wrap

#
# #
# # #
# # # # Entitlement Finder
# # #
# #
#

# global variables (in python u dont really need to declare them, but just for clarifying)

# user input

verbose = False
sound = False

FirstSegment_VirtualAddress = 0x00000000

SecondSegment_VirtualAddress = 0x00000000

# program input

EntitlementLength = 32

# program variables (shouldn't be changed in most cases)

BytesLength = 2
SizesLength = 8
AddressesLength = 8

successes = 0
success_text = None

failures = 0
failure_text = None

heads = None
heads_amount = None
heads_index = None
previous_head = None
current_head = None
next_head = None

cmd = None
cmd_length = None
cmd_fixed = None
cmd_fixed_length = None
cmd_fixed_splitted = None
cmd_fixed_splitted_amount = None
cmd_fixed_splitted_index = None
cmd_fixed_splitted_cell = None
cmd_fixed_splitted_cell_length = None
cmd_fixed_splitted_cell_index = None

position = None

entitlement_bytes_amount = EntitlementLength / 2

entitlement_allowed_characters = None
entitlement_allowed_characters_matches = 0

suggested_entitlement_allowed_characters = None
suggested_entitlement_allowed_characters_matches = 0

suggested_hardcore_entitlement_allowed_characters_matches = 0

sequence_bytes = None
sequence_bytes_address = None
sequence_bytes_original_amount = None
sequence_bytes_amount = None
sequence_bytes_offset = None
sequence_bytes_index = None
sequence_byte = None

def CheckHexText(source, length, add_0x):  # returns the hex text
    source_hex = str(hex(source)[2:])
    source_hex_length = len(source_hex)
    source_hex_index = None
    source_hex_cell = None

    for source_hex_index in range(0, source_hex_length):
        source_hex_cell = source_hex[source_hex_index]

        if (source_hex_cell in string.hexdigits) is False:
            source_hex = source_hex[:source_hex_index]

            break

    result = str(source_hex.zfill(length))

    if add_0x is True:
        result = "0x" + result

    return result

def WaitForInitialAutoanalysis():
    idc.auto_wait()

def CompletionSound():
    frequencies = [420, 430, 440]
    frequency = None

    duration = 500

    for frequency in frequencies:
        winsound.Beep(frequency, duration)
        time.sleep(duration / 1000)

def CheckHeads(start_address, end_address):  # returns the heads in the range
    result = None

    current_result = []

    heads = idautils.Heads(start_address, end_address)

    for head in heads:
        current_result.append(int(head))

    result = current_result

    return result

def CheckCommand(address):  # returns the command
    result = str(idc.GetDisasm(address))

    return result

def CheckByte(address):  # returns the byte from the address
    result = int(idc.GetOriginalByte(address))

    return result

def CheckSequenceBytesAmount(sequence_bytes_address):  # returns the sequence bytes amount
    result = None

    current_result = int(idc.ItemSize(sequence_bytes_address))

    if current_result <= 0:
        current_result = 1

    result = current_result

    return result

def CreateSequence(address, amount):  # returns True if succeed to create the sequence, False if didn't
    # if the amount is None then checking the sequence amount using the CheckSequenceBytesAmount function

    result = None

    # Global Variables

    # global verbose
    # global sound

    # global FirstSegment_VirtualAddress

    # global SecondSegment_VirtualAddress

    # global EntitlementLength

    global BytesLength
    global SizesLength
    global AddressesLength

    # global successes
    # global success_text

    # global failures
    # global failure_text

    # global heads
    # global heads_amount
    # global heads_index
    # global previous_head
    # global current_head
    # global next_head

    # global cmd
    # global cmd_length
    # global cmd_fixed
    # global cmd_fixed_length
    # global cmd_fixed_splitted
    # global cmd_fixed_splitted_amount
    # global cmd_fixed_splitted_index
    # global cmd_fixed_splitted_cell
    # global cmd_fixed_splitted_cell_length
    # global cmd_fixed_splitted_cell_index

    # global position

    # global entitlement_bytes_amount

    # global entitlement_allowed_characters
    # global entitlement_allowed_characters_matches

    # global suggested_entitlement_allowed_characters
    # global suggested_entitlement_allowed_characters_matches

    # global suggested_hardcore_entitlement_allowed_characters_matches

    global sequence_bytes
    global sequence_bytes_address
    global sequence_bytes_original_amount
    global sequence_bytes_amount
    global sequence_bytes_offset
    global sequence_bytes_index
    global sequence_byte

    # Function Variables

    method_found = False

    # Start

    if sequence_bytes_address == address and sequence_bytes_original_amount == amount:
        method_found = True
    else:
        sequence_bytes_original_amount = amount

        sequence_bytes = None
        sequence_bytes_address = address
        sequence_bytes_amount = None
        sequence_bytes_offset = None
        sequence_bytes_index = None
        sequence_byte = None

        if sequence_bytes_original_amount is not None:
            sequence_bytes_amount = sequence_bytes_original_amount
        else:
            sequence_bytes_amount = CheckSequenceBytesAmount(sequence_bytes_address)

        # print(str(sequence_bytes_amount))

        if sequence_bytes_amount is not None and sequence_bytes_amount > 0:
            sequence_bytes = []

            for sequence_bytes_index in range(0, sequence_bytes_amount):
                sequence_byte = None

                sequence_bytes.append(sequence_byte)

            method_found = True

    result = method_found

    return result

def CheckSequenceByte(offset):  # offset from start (0 goes for first cell, 1 for second, etc), returns the sequence byte
    result = None

    # Global Variables

    # global verbose
    # global sound

    # global FirstSegment_VirtualAddress

    # global SecondSegment_VirtualAddress

    # global EntitlementLength

    global BytesLength
    global SizesLength
    global AddressesLength

    # global successes
    # global success_text

    # global failures
    # global failure_text

    # global heads
    # global heads_amount
    # global heads_index
    # global previous_head
    # global current_head
    # global next_head

    # global cmd
    # global cmd_length
    # global cmd_fixed
    # global cmd_fixed_length
    # global cmd_fixed_splitted
    # global cmd_fixed_splitted_amount
    # global cmd_fixed_splitted_index
    # global cmd_fixed_splitted_cell
    # global cmd_fixed_splitted_cell_length
    # global cmd_fixed_splitted_cell_index

    # global position

    # global entitlement_bytes_amount

    # global entitlement_allowed_characters
    # global entitlement_allowed_characters_matches

    # global suggested_entitlement_allowed_characters
    # global suggested_entitlement_allowed_characters_matches

    # global suggested_hardcore_entitlement_allowed_characters_matches

    global sequence_bytes
    global sequence_bytes_address
    # global sequence_bytes_original_amount
    global sequence_bytes_amount
    # global sequence_bytes_offset
    # global sequence_bytes_index
    # global sequence_byte

    # Function Variables

    current_result = None

    # Start

    if offset >= 0 and offset < sequence_bytes_amount:
        if sequence_bytes[offset] is not None:
            current_result = sequence_bytes[offset]
        else:
            current_result = CheckByte(sequence_bytes_address + offset)

            sequence_bytes[offset] = current_result

    result = current_result

    return result

def CheckSequenceBytesText(direction):  # returns the sequence bytes text, None in case of not finding any
    # gets direction, True goes for first to last byte, False goes for last to first byte

    result = None

    # Global Variables

    # global verbose
    # global sound

    # global FirstSegment_VirtualAddress

    # global SecondSegment_VirtualAddress

    # global EntitlementLength

    global BytesLength
    global SizesLength
    global AddressesLength

    # global successes
    # global success_text

    # global failures
    # global failure_text

    # global heads
    # global heads_amount
    # global heads_index
    # global previous_head
    # global current_head
    # global next_head

    # global cmd
    # global cmd_length
    # global cmd_fixed
    # global cmd_fixed_length
    # global cmd_fixed_splitted
    # global cmd_fixed_splitted_amount
    # global cmd_fixed_splitted_index
    # global cmd_fixed_splitted_cell
    # global cmd_fixed_splitted_cell_length
    # global cmd_fixed_splitted_cell_index

    # global position

    # global entitlement_bytes_amount

    # global entitlement_allowed_characters
    # global entitlement_allowed_characters_matches

    # global suggested_entitlement_allowed_characters
    # global suggested_entitlement_allowed_characters_matches

    # global suggested_hardcore_entitlement_allowed_characters_matches

    # global sequence_bytes
    # global sequence_bytes_address
    # global sequence_bytes_original_amount
    global sequence_bytes_amount
    # global sequence_bytes_offset
    global sequence_bytes_index
    global sequence_byte

    # Function Variables

    current_result = None

    # Start

    if sequence_bytes_amount > 0:
        if direction is True:
            sequence_bytes_index = 0
        else:
            sequence_bytes_index = sequence_bytes_amount - 1

        while (
            direction is True and sequence_bytes_index < sequence_bytes_amount
            or direction is False and sequence_bytes_index >= 0
        ):
            sequence_byte = CheckSequenceByte(sequence_bytes_index)

            if sequence_byte is not None:
                if current_result is None:
                    current_result = ""

                current_result += CheckHexText(sequence_byte, BytesLength, (current_result == ""))
            else:
                break

            if direction is True:
                sequence_bytes_index += 1
            else:
                sequence_bytes_index -= 1

    result = current_result

    return result

def check_entitlement_allowed_characters():
    # Global Variables

    # global verbose
    # global sound

    # global FirstSegment_VirtualAddress

    # global SecondSegment_VirtualAddress

    # global EntitlementLength

    global BytesLength
    global SizesLength
    global AddressesLength

    # global successes
    # global success_text

    # global failures
    # global failure_text

    # global heads
    # global heads_amount
    # global heads_index
    # global previous_head
    # global current_head
    # global next_head

    # global cmd
    # global cmd_length
    # global cmd_fixed
    # global cmd_fixed_length
    # global cmd_fixed_splitted
    # global cmd_fixed_splitted_amount
    # global cmd_fixed_splitted_index
    # global cmd_fixed_splitted_cell
    # global cmd_fixed_splitted_cell_length
    # global cmd_fixed_splitted_cell_index

    # global position

    # global entitlement_bytes_amount

    global entitlement_allowed_characters
    # global entitlement_allowed_characters_matches

    global suggested_entitlement_allowed_characters
    # global suggested_entitlement_allowed_characters_matches

    # global suggested_hardcore_entitlement_allowed_characters_matches

    # global sequence_bytes
    # global sequence_bytes_address
    # global sequence_bytes_original_amount
    # global sequence_bytes_amount
    # global sequence_bytes_offset
    # global sequence_bytes_index
    # global sequence_byte

    # Start

    entitlement_allowed_characters = (
        [
            '0'
            , '1'
            , '2'
            , '3'
            , '4'
            , '5'
            , '6'
            , '7'
            , '8'
            , '9'
            , 'A'
            , 'B'
            , 'C'
            , 'D'
            , 'E'
            , 'F'
            , 'G'
            , 'H'
            , 'I'
            , 'J'
            , 'K'
            , 'L'
            , 'M'
            , 'N'
            , 'O'
            , 'P'
            , 'Q'
            , 'R'
            , 'S'
            , 'T'
            , 'U'
            , 'V'
            , 'W'
            , 'X'
            , 'Y'
            , 'Z'
            , 'a'
            , 'b'
            , 'c'
            , 'd'
            , 'e'
            , 'f'
            , 'g'
            , 'h'
            , 'i'
            , 'j'
            , 'k'
            , 'l'
            , 'm'
            , 'n'
            , 'o'
            , 'p'
            , 'q'
            , 'r'
            , 's'
            , 't'
            , 'u'
            , 'v'
            , 'w'
            , 'x'
            , 'y'
            , 'z'
        ]
    )

    suggested_entitlement_allowed_characters = (
        [
            '\n'
            , '\r'
            , '\t'
            , ' '
            , '!'
            , '"'
            , '#'
            , '$'
            , '%'
            , '&'
            , '\''
            , '('
            , ')'
            , '*'
            , '+'
            , ','
            , '-'
            , '.'
            , '/'
            , ':'
            , ';'
            , '<'
            , '='
            , '>'
            , '?'
            , '@'
            , '['
            , '\\'
            , ']'
            , '^'
            , '_'
            , '`'
            , '{'
            , '|'
            , '}'
            , '~'
        ]
    )

def check_entitlement():  # returns -1 in case of failure, 0 in case of not finding a match, and 1 in case of success
    result = None

    # Global Variables

    global verbose
    # global sound

    # global FirstSegment_VirtualAddress

    # global SecondSegment_VirtualAddress

    global EntitlementLength

    global BytesLength
    global SizesLength
    global AddressesLength

    global successes
    global success_text

    # global failures
    global failure_text

    # global heads
    # global heads_amount
    # global heads_index
    # global previous_head
    global current_head
    # global next_head

    # global cmd
    # global cmd_length
    # global cmd_fixed
    # global cmd_fixed_length
    global cmd_fixed_splitted
    global cmd_fixed_splitted_amount
    # global cmd_fixed_splitted_index
    global cmd_fixed_splitted_cell
    global cmd_fixed_splitted_cell_length
    # global cmd_fixed_splitted_cell_index

    global position

    global entitlement_bytes_amount

    global entitlement_allowed_characters
    global entitlement_allowed_characters_matches

    global suggested_entitlement_allowed_characters
    global suggested_entitlement_allowed_characters_matches

    global suggested_hardcore_entitlement_allowed_characters_matches

    # global sequence_bytes
    global sequence_bytes_address
    # global sequence_bytes_original_amount
    global sequence_bytes_amount
    global sequence_bytes_offset
    # global sequence_bytes_index
    # global sequence_byte

    # Function Variables

    SequenceBytesText = None

    wrapped_entitlement = None
    wrapped_entitlement_cell = None
    wrapped_entitlement_cell_character = None

    possible_entitlement = None
    possible_entitlement_level = None
    possible_entitlement_text = None
    possible_entitlement_hex_text = None

    method_found = False
    error_found = False

    # Start

    if cmd_fixed_splitted_amount == 2:
        command = cmd_fixed_splitted[0]

        if command == "xmmword":
            if cmd_fixed_splitted_cell_length - 1 == EntitlementLength:
                for cmd_fixed_splitted_cell_index in range(0, cmd_fixed_splitted_cell_length):
                    if cmd_fixed_splitted_cell[cmd_fixed_splitted_cell_index] in string.hexdigits:
                        continue
                    elif cmd_fixed_splitted_cell[cmd_fixed_splitted_cell_index] == 'h':
                        if cmd_fixed_splitted_cell_index > 0:
                            if cmd_fixed_splitted_cell_index == cmd_fixed_splitted_cell_length - 1:
                                method_found = True

                        break
                    else:
                        break

                if method_found is True:
                    method_found = False

                    CreateSequence(current_head, None)  # no need to check for the result, assuming it is True

                    if sequence_bytes_amount != entitlement_bytes_amount:
                        failure_text = (
                            "the sequence bytes amount"
                            + ' ' + str(sequence_bytes_amount)
                            + ' ' + "isn't the same as the entitlement bytes amount"
                            + ' ' + str(entitlement_bytes_amount)
                        )

                        error_found = True
                    else:
                        SequenceBytesText = CheckSequenceBytesText(True)

                        if SequenceBytesText is None:
                            failure_text = ("the sequence bytes text is empty")

                            error_found = True
                        else:
                            wrapped_entitlement = (
                                wrap(
                                    cmd_fixed_splitted_cell[0:cmd_fixed_splitted_cell_length - 1]  # the hex number as a string without the 'h' at the end
                                    , 2
                                )  # converting the string to a string list with each cell having 2 number characters
                            )

                            possible_entitlement_level = 0
                            possible_entitlement_text = ""

                            for wrapped_entitlement_cell in wrapped_entitlement:
                                wrapped_entitlement_cell_character = chr(int(wrapped_entitlement_cell, 16))

                                if (wrapped_entitlement_cell_character in entitlement_allowed_characters) is True:
                                    possible_entitlement_text += wrapped_entitlement_cell_character
                                else:
                                    if (wrapped_entitlement_cell_character in suggested_entitlement_allowed_characters) is True:
                                        possible_entitlement_text += wrapped_entitlement_cell_character

                                        if possible_entitlement_level == 0:
                                            possible_entitlement_level = 1
                                    else:
                                        if possible_entitlement_level <= 1:
                                            possible_entitlement_level = 2

                            possible_entitlement = (
                                int(
                                    "".join(
                                        wrapped_entitlement[::-1]  # reversing the list
                                    )  # converting the list to a string
                                    , 16
                                )  # converting the string as a hex number to int
                            )

                            possible_entitlement_text = possible_entitlement_text[::-1]
                            possible_entitlement_hex_text = CheckHexText(possible_entitlement, EntitlementLength, True)

                            if possible_entitlement_hex_text != SequenceBytesText:
                                failure_text = (
                                    "the sequence bytes text"
                                    + ' ' + str(SequenceBytesText)
                                    + ' ' + "isn't the same as the possible entitlement bytes hex text"
                                    + ' ' + str(possible_entitlement_hex_text)
                                )

                                error_found = True
                            else:
                                success_text = "Found possible entitlement"

                                success_text += (
                                    '\t' + "level:" + ' '
                                    + (
                                        "entitlement allowed characters"
                                        if possible_entitlement_level == 0
                                        else (
                                            "suggested entitlement allowed characters"
                                            if possible_entitlement_level == 1
                                            else "suggested hardcore entitlement allowed characters"
                                        )
                                    )
                                )

                                success_text += '\t' + "address:" + ' ' + CheckHexText(sequence_bytes_address, AddressesLength, True)

                                if verbose is True:
                                    success_text += (
                                        '\t' + "command:" + ' ' + '\t'.join(cmd_fixed_splitted)
                                        + '\t' + "position:" + ' ' + str(position) + ' ' + "out of:" + ' ' + str(cmd_fixed_splitted_amount)
                                    )

                                success_text += (
                                    '\t' + "possible entitlement:" + ' ' + possible_entitlement_hex_text
                                    + '\t' + "possible entitlement text:" + ' ' + possible_entitlement_text
                                )

                                if verbose is True:
                                    success_text += (('\t' + "sequence bytes:" + ' ' + SequenceBytesText) if SequenceBytesText is not None else "")

                                print(success_text)

                                if possible_entitlement_level == 0:
                                    entitlement_allowed_characters_matches += 1
                                elif possible_entitlement_level == 1:
                                    suggested_entitlement_allowed_characters_matches += 1
                                else:
                                    suggested_hardcore_entitlement_allowed_characters_matches += 1

                                successes += 1

                                method_found = True

    if method_found is True:
        result = 1
    elif error_found is True:
        result = -1
    else:
        result = 0

    return result

def fix_addresses():
    # Global Variables

    # global verbose
    # global sound

    global FirstSegment_VirtualAddress

    global SecondSegment_VirtualAddress

    # global EntitlementLength

    global BytesLength
    global SizesLength
    global AddressesLength

    # global successes
    # global success_text

    global failures
    global failure_text

    global heads
    global heads_amount
    global heads_index
    global previous_head
    global current_head
    global next_head

    global cmd
    global cmd_length
    global cmd_fixed
    global cmd_fixed_length
    global cmd_fixed_splitted
    global cmd_fixed_splitted_amount
    global cmd_fixed_splitted_index
    global cmd_fixed_splitted_cell
    global cmd_fixed_splitted_cell_length
    global cmd_fixed_splitted_cell_index

    global position

    # global entitlement_bytes_amount

    # global entitlement_allowed_characters
    # global entitlement_allowed_characters_matches

    # global suggested_entitlement_allowed_characters
    # global suggested_entitlement_allowed_characters_matches

    # global suggested_hardcore_entitlement_allowed_characters_matches

    # global sequence_bytes
    # global sequence_bytes_address
    # global sequence_bytes_original_amount
    # global sequence_bytes_amount
    # global sequence_bytes_offset
    # global sequence_bytes_index
    # global sequence_byte

    # Function Variables

    check_entitlement_result = None

    SequenceBytesText = None

    error_message = None

    method_found = False
    error_found = False

    # Start

    #
    # #
    # # # going through all of the functions/commands in all of the addresses from the first segment virtual address
    # # # to the segment after the mem hole mapped virtual address + its file size (not including the last one since it's an address of the next segment)
    # #
    #

    # going through all of the heads from first segment virtual address
    # to the segment before mem hole virtual address (not including the last one since it's an address of the next segment)

    print("")
    print("parsing addresses between the first segment to the segment before the memory hole")

    heads = CheckHeads(FirstSegment_VirtualAddress, SecondSegment_VirtualAddress - 1)
    heads_amount = len(heads)

    # heads_amount = 0

    check_entitlement_allowed_characters()

    for heads_index in range(0, heads_amount):
        previous_head = None
        current_head = None
        next_head = None

        if heads_index > 0:
            previous_head = heads[heads_index - 1]

        current_head = heads[heads_index]

        if heads_index < heads_amount - 1:
            next_head = heads[heads_index + 1]

        # print(CheckHexText(previous_head, AddressesLength, True))
        # print(CheckHexText(current_head, AddressesLength, True))
        # print(CheckHexText(next_head, AddressesLength, True))

        cmd = CheckCommand(current_head)

        if cmd is not None:
            cmd_length = len(cmd)

            if cmd_length > 0:
                # print(cmd)

                failure_text = None

                cmd_fixed = None
                cmd_fixed_length = None
                cmd_fixed_splitted = None
                cmd_fixed_splitted_amount = None
                cmd_fixed_splitted_index = None
                cmd_fixed_splitted_cell = None
                cmd_fixed_splitted_cell_length = None
                cmd_fixed_splitted_cell_index = None

                position = None

                try:
                    cmd_fixed = cmd.split(';')[0].replace(',', ' ')

                    if cmd_fixed is not None:
                        cmd_fixed_length = len(cmd_fixed)

                        if cmd_fixed_length > 0:
                            cmd_fixed_splitted = filter(None, cmd_fixed.split(' '))

                            if cmd_fixed_splitted is not None:
                                cmd_fixed_splitted_amount = len(cmd_fixed_splitted)

                                if cmd_fixed_splitted_amount > 0:
                                    cmd_fixed_splitted_index = cmd_fixed_splitted_amount - 1

                                    while cmd_fixed_splitted_index >= 1:
                                        # 1 because the first 2 are always a command and either a type or a variable (register)
                                        # , and we don't need to check the command cell

                                        cmd_fixed_splitted_cell = cmd_fixed_splitted[cmd_fixed_splitted_index]
                                        cmd_fixed_splitted_cell_length = len(cmd_fixed_splitted_cell)

                                        position = cmd_fixed_splitted_index + 1

                                        if cmd_fixed_splitted_cell_length > 0:
                                            check_entitlement_result = check_entitlement()

                                            if check_entitlement_result == 1:
                                                method_found = True
                                            elif check_entitlement_result == -1:
                                                error_found = True

                                            if method_found is True:
                                                method_found = False

                                                break
                                            elif error_found is True:
                                                error_found = False

                                                raise Exception(None)

                                        cmd_fixed_splitted_index -= 1
                except Exception:
                    error_message = []

                    error_message.append("can't parse.")

                    if failure_text is not None:
                        error_message.append("reason:" + ' ' + failure_text)

                    error_message.append("address:" + ' ' + CheckHexText(current_head, AddressesLength, True))

                    if cmd_fixed_splitted is not None:
                        error_message.append("command:" + ' ' + '\t'.join(cmd_fixed_splitted))

                    if position is not None:
                        error_message.append("position:" + ' ' + str(position) + ' ' + "out of:" + ' ' + str(cmd_fixed_splitted_amount))

                    if CreateSequence(current_head, None) is True:
                        SequenceBytesText = CheckSequenceBytesText(True)

                        if SequenceBytesText is not None:
                            error_message.append("sequence bytes:" + ' ' + SequenceBytesText)

                    print('\t'.join(error_message))

                    failures += 1

    print("")
    print("finished parsing addresses between first segment to the segment before the memory hole")

    # going through all of the addresses from segment before mem hole virtual address
    # to the segment after the mem hole mapped virtual address + its file size (not including the last one since it's an address of the next segment)

    # print("")
    # print("parsing addresses between the segment before the memory hole to the segment after the memory hole and its file size")

    # print("")
    # print("finished parsing addresses between the segment before the memory hole to the segment after the memory hole and its file size")

def main():
    # Global Variables

    global verbose
    global sound

    global FirstSegment_VirtualAddress

    global SecondSegment_VirtualAddress

    global EntitlementLength

    global BytesLength
    global SizesLength
    global AddressesLength

    global successes
    # global success_text

    global failures
    # global failure_text

    # global heads
    # global heads_amount
    # global heads_index
    # global previous_head
    # global current_head
    # global next_head

    # global cmd
    # global cmd_length
    # global cmd_fixed
    # global cmd_fixed_length
    # global cmd_fixed_splitted
    # global cmd_fixed_splitted_amount
    # global cmd_fixed_splitted_index
    # global cmd_fixed_splitted_cell
    # global cmd_fixed_splitted_cell_length
    # global cmd_fixed_splitted_cell_index

    # global position

    # global entitlement_bytes_amount

    # global entitlement_allowed_characters
    global entitlement_allowed_characters_matches

    # global suggested_entitlement_allowed_characters
    global suggested_entitlement_allowed_characters_matches

    global suggested_hardcore_entitlement_allowed_characters_matches

    # global sequence_bytes
    # global sequence_bytes_address
    # global sequence_bytes_original_amount
    # global sequence_bytes_amount
    # global sequence_bytes_offset
    # global sequence_bytes_index
    # global sequence_byte

    # Function Variables

    start_time = None
    end_time = None

    elapsedTime = None

    elapsedMinutes = None
    elapsedSeconds = None

    # Start

    # WaitForInitialAutoanalysis()

    start_time = datetime.now().time().strftime('%H:%M:%S')

    print("")
    print("User Input:")
    print(
        "Verbose:" + ' ' + ("True" if verbose is True else "False") + "\n"
        + "First Segment Virtual Address:" + ' ' + CheckHexText(FirstSegment_VirtualAddress, AddressesLength, True) + "\n"
        + "Second Segment Virtual Address:" + ' ' + CheckHexText(SecondSegment_VirtualAddress, AddressesLength, True)
    )

    print("")
    print("Program Input:")
    print(
        "Entitlement Length:" + ' ' + str(EntitlementLength)
    )

    fix_addresses()

    end_time = datetime.now().time().strftime('%H:%M:%S')

    elapsedTime = datetime.strptime(end_time, '%H:%M:%S') - datetime.strptime(start_time, '%H:%M:%S')

    elapsedMinutes = int(elapsedTime.total_seconds() / 60)
    elapsedSeconds = int(elapsedTime.total_seconds() - elapsedMinutes * 60)

    print("")
    print("successes:" + ' ' + str(successes))
    print("failures:" + ' ' + str(failures))

    print("")
    print("matches between first segment to the second segment:")
    print("entitlement allowed characters matches:" + ' ' + str(entitlement_allowed_characters_matches))
    print("suggested entitlement allowed characters matches:" + ' ' + str(suggested_entitlement_allowed_characters_matches))
    print("suggested hardcore entitlement allowed characters matches:" + ' ' + str(suggested_hardcore_entitlement_allowed_characters_matches))

    print("")
    print("elapsed time:" + ' ' + str(elapsedMinutes).zfill(2) + ':' + str(elapsedSeconds).zfill(2))

    if sound is True:
        CompletionSound()

    print("")
    print("done")

main()