# %%
from djitellopy import Tello
from cv2 import cv2 as cv
import facedetect
from time import sleep

if __name__ == "__main__":
	tello = Tello()
	face_cascade = facedetect.get_face_cascade()

	try:
		tello.connect()
		tello.streamon()
		print(f"Battery: {tello.get_battery()}")

		frame = tello.get_frame_read()
		print("[INFO] dronecontrol.py - Got Frame Reader")

		while True:
			faces = facedetect.face_cascade_detect(frame.frame, face_cascade)
			detected_frame = facedetect.draw_face_box(frame.frame, faces)

			if detected_frame is None:
				raise ValueError("Error in dronecontrol.py - Frame not found")

			cv.imshow('frame', detected_frame)

			if cv.waitKey(1) & 0xFF == ord('q'):
				break

	except Exception as e:
		print("Error in dronecontrole.py")
		print(type(e))
		print(e)

	finally:
		cv.destroyAllWindows()
		tello.end()
# %%


from pathlib import (
    Path,
)
from typing import (
    IO,
    Dict,
    Iterable,
    Optional,
    Tuple,
    Union,
    cast,
)

import numpy

from wasm._utils.decorators import (
    to_tuple,
)
from wasm.datatypes import (
    DataSegment,
    ElementSegment,
    FunctionAddress,
    FunctionInstance,
    GlobalAddress,
    HostFunction,
    Import,
    MemoryAddress,
    Module,
    ModuleInstance,
    Store,
    TableAddress,
)
from wasm.exceptions import (
    InvalidModule,
    MalformedModule,
    ParseError,
    Unlinkable,
    ValidationError,
)
from wasm.parsers import (
    parse_module,
)
from wasm.typing import (
    TValue,
)
from wasm.validation import (
    validate_external_type_match,
    validate_module,
)

from .configuration import (
    Configuration,
)
from .instructions import (
    InstructionSequence,
)
from .stack import (
    Frame,
)

TAddress = Union[FunctionAddress, TableAddress, MemoryAddress, GlobalAddress]

@to_tuple
def _get_import_addresses(runtime: 'Runtime',
                          imports: Tuple[Import, ...]) -> Iterable[TAddress]:
    """
    Helper function to normalize the descriptors from a set of Imports to their
    addresses.
    """
    for import_ in imports:
        if not runtime.has_module(import_.module_name):
            raise Unlinkable(f"Runtime has no known module named '{import_.module_name}'")
        module = runtime.get_module(import_.module_name)
        for export in module.exports:
            if export.name == import_.as_name:
                yield export.value
                break
        else:
            raise Unlinkable(
                f"No export found with name '{import_.as_name}'"
            )

@to_tuple
def _initialize_globals(store: Store,
                        module: Module,
                        globals_addresses: Tuple[GlobalAddress, ...],
                        ) -> Iterable[TValue]:
    """
    Helper function for running the initialization code for the Globals
    to compute their initial values.
    """
    module_instances = ModuleInstance(
        types=(),
        func_addrs=(),
        memory_addrs=(),
        table_addrs=(),
        global_addrs=globals_addresses,
        exports=(),
    )

    for global_ in module.globals:
        config = Configuration(store=store)
        frame = Frame(
            module=module_instances,
            locals=[],
            instructions=InstructionSequence(global_.init),
            arity=1,
        )
        config.push_frame(frame)
        result = config.execute()
        if len(result) != 1:
            raise Exception("Invariant: globals initialization returned empty result")
        yield result[0]

@to_tuple
def _compute_table_offsets(store: Store,
                           elements: Tuple[ElementSegment, ...],
                           module_instance: ModuleInstance) -> Iterable[numpy.uint32]:
    """
    Helper function for running the initialization code for the ElementSegment
    objects to compute the table indices
    """
    for element_segment in elements:
        frame = Frame(
            module=module_instance,
            locals=[],
            instructions=InstructionSequence(element_segment.offset),
            arity=1,
        )
        config = Configuration(store=store)
        config.push_frame(frame)
        result = config.execute()
        if len(result) != 1:
            raise Exception("Invariant: element segment offset returned empty result")
        offset = numpy.uint32(cast(int, result[0]))

        table_address = module_instance.table_addrs[element_segment.table_idx]
        table_instance = store.tables[table_address]

        if offset + len(element_segment.init) > len(table_instance.elem):
            raise Unlinkable(
                f"Computed element segment offset exceeds table size: {offset} "
                f"+ {len(element_segment.init)} > {len(table_instance.elem)}"
            )
        yield offset

@to_tuple
def _compute_data_offsets(store: Store,
                          datas: Tuple[DataSegment, ...],
                          module_instance: ModuleInstance) -> Iterable[numpy.uint32]:
    """
    Helper function for running the initialization code for the DataSegment
    objects to compute the memory offsets.
    """
    for data_segment in datas:
        frame = Frame(
            module=module_instance,
            locals=[],
            instructions=InstructionSequence(data_segment.offset),
            arity=1,
        )
        config = Configuration(store=store)
        config.push_frame(frame)
        result = config.execute()
        if len(result) != 1:
            raise Exception("Invariant: data segment offset returned empty result")
        offset = numpy.uint32(cast(int, result[0]))

        memory_address = module_instance.memory_addrs[data_segment.memory_idx]
        memory_instance = store.mems[memory_address]

        if offset + len(data_segment.init) > len(memory_instance.data):
            raise Unlinkable(
                f"Computed data segment offset exceeds memory size: {offset} "
                f"+ {len(data_segment.init)} > {len(memory_instance.data)}"
            )
        yield offset

class Runtime:
    """
    Represents the *runtime* for the py-wasm Web Assembly interpreter.
    """
    store: Store
    modules: Dict[str, ModuleInstance]

    def __init__(self):
        self.store = Store()
        self.modules = {}

    def register_module(self, name: str, module: ModuleInstance) -> None:
        """
        Register a module under the provided name in this runtime.  This makes
        it available for other modules to import.
        """
        self.modules[name] = module

    def has_module(self, name: str) -> bool:
        """
        Return boolean whether a module is present in this runtime.
        """
        return name in self.modules

    def get_module(self, name: str) -> ModuleInstance:
        """
        Return the module instance registered for the provided name from this
        runtime.
        """
        return self.modules[name]

    def _get_import_addresses(self, imports: Tuple[Import, ...]) -> Tuple[TAddress, ...]:
        return _get_import_addresses(self, imports)

    def load_module(self, file_path: Path) -> Module:
        """
        Load a Web Assembly module from its binary source file.
        """
        if file_path.suffix != ".wasm":
            raise Exception("Unsupported file type: {file_path.suffix}")

        with file_path.open("rb") as wasm_file:
            try:
                module = parse_module(wasm_file)
            except ParseError as err:
                raise MalformedModule from err

        try:
            validate_module(module)
        except ValidationError as err:
            raise InvalidModule from err

        return module

    def load_buffer(self, buffer: IO) -> Module:
        """
        Load a Web Assembly module from its binary source file.
        """
        try:
            module = parse_module(buffer)
        except ParseError as err:
            raise MalformedModule from err

        try:
            validate_module(module)
        except ValidationError as err:
            raise InvalidModule from err

        return module

    def instantiate_module(self,
                           module: Module,
                           ) -> Tuple[ModuleInstance, Optional[Tuple[TValue, ...]]]:
        """
        Instantiate a Web Assembly module into this runtime environment.
        """
        # Ensure the module is valid
        try:
            module_import_types, module_export_types = validate_module(module)
        except ValidationError as err:
            raise InvalidModule from err

        # Gather all of the addresses for the external types for this module.
        all_import_addresses = self._get_import_addresses(module.imports)

        # Validate all of the addresses are known to the store.
        for address in all_import_addresses:
            try:
                self.store.validate_address(address)
            except ValidationError as err:
                raise InvalidModule from err

        # Gather the types for each of the values referenced by the addresses
        # of the module imports.
        store_import_types = tuple(
            self.store.get_type_for_address(address)
            for address in all_import_addresses
        )
        if len(module_import_types) != len(store_import_types):
            # TODO: This validation may be superfluous as both of these values
            # are generated from `module.imports` and the generation process
            # **should** give strong guarantees that the resulting list is the
            # same length as `module.imports`.
            raise Unlinkable(
                f"Mismatched number of import types: {len(module_import_types)} != "
                f"{len(store_import_types)}"
            )

        # Ensure that the module's internal types for it's imports match the
        # types found in the store.
        for module_type, store_type in zip(module_import_types, store_import_types):
            try:
                validate_external_type_match(store_type, module_type)
            except ValidationError as err:
                raise Unlinkable from err

        global_addresses = GlobalAddress.filter(all_import_addresses)
        global_values = _initialize_globals(self.store, module, global_addresses)

        module_instance = self.store.allocate_module(module, all_import_addresses, global_values)

        element_segment_offsets = _compute_table_offsets(
            self.store,
            module.elem,
            module_instance,
        )
        data_segment_offsets = _compute_data_offsets(
            self.store,
            module.data,
            module_instance,
        )

        for offset, element_segment in zip(element_segment_offsets, module.elem):
            for idx, function_idx in enumerate(element_segment.init):
                function_address = module_instance.func_addrs[function_idx]
                table_address = module_instance.table_addrs[element_segment.table_idx]
                table_instance = self.store.tables[table_address]
                table_instance.elem[offset + idx] = function_address

        for offset, data_segment in zip(data_segment_offsets, module.data):
            memory_address = module_instance.memory_addrs[data_segment.memory_idx]
            memory_instance = self.store.mems[memory_address]
            data_length = len(data_segment.init)
            memory_instance.data[offset:offset + data_length] = data_segment.init

        result: Optional[Tuple[TValue, ...]]

        if module.start is not None:
            function_address = module_instance.func_addrs[module.start.function_idx]
            result = self.invoke_function(function_address)
        else:
            result = None

        return module_instance, result

    def get_configuration(self) -> Configuration:
        return Configuration(self.store)

    def invoke_function(self,
                        function_address: FunctionAddress,
                        function_args: Tuple[TValue, ...] = None,) -> Tuple[TValue, ...]:
        """
        Invoke a function denoted by the function address with the provided arguments.
        """
        try:
            function = self.store.funcs[function_address]
        except IndexError:
            raise TypeError(
                f"Function address out of range: {function_address} >= "
                f"{len(self.store.funcs)}"
            )
        if function_args is None:
            function_args = tuple()

        for arg, valtype in zip(function_args, function.type.params):
            valtype.validate_arg(arg)

        config = self.get_configuration()

        if isinstance(function, FunctionInstance):
            from wasm.logic.control import _setup_function_invocation
            _setup_function_invocation(config, function_address, function_args)
            ret = config.execute()
            return ret
        elif isinstance(function, HostFunction):
            ret = function.hostcode(config, function_args)
            return ret
        else:
            raise Exception(f"Invariant: unknown function type: {type(function)}")


import csv
import random
import numpy as np

#read data from .csv
def readData():
    rf = open('HTRU_2.csv','r')
    dataReader = csv.reader(rf)
    posDataList = []
    negDataList = []
    featureIndex = 8
    featureMin = [999,999,999,999,999,999,999,999]
    featureMax = [0,0,0,0,0,0,0,0]
    for rList in dataReader:
        for i in range(featureIndex):
            if float(rList[i]) > float(featureMax[i]):
                featureMax[i] = float(rList[i])
            if float(rList[i]) < float(featureMin[i]):
                featureMin[i] = float(rList[i])
        if rList[featureIndex] == '0':
            negDataList.append(rList)
        else:
            posDataList.append(rList)
    rf.close()
    #   17,898 total examples.
    #	1,639 positive examples.
    #	16,259 negative examples.

    train_features = []
    train_labels = []
    test_features = []
    test_labels = []

    negDataList = random.sample(negDataList, len(posDataList))
    #0.1,0.5 92%
    posTestList = random.sample(posDataList, int(round(len(posDataList) * 0.2)))
    negTestList = random.sample(negDataList, int(round(len(negDataList) * 0.2)))

    #devide postive examples into test and train
    for pTest in posTestList:
        fList = []
        for i in range(featureIndex):
            fList.append((float(pTest[i])-featureMin[i])/(featureMax[i]-featureMin[i]))
        test_labels.append(1)
        fList.append(1)
        test_features.append(fList)

        posDataList.remove(pTest)

    for pTrain in posDataList:
        fList = []
        for i in range(featureIndex):
            fList.append((float(pTrain[i])-featureMin[i])/(featureMax[i]-featureMin[i]))
            train_labels.append(1)
        fList.append(1)
        train_features.append(fList)

    # devide negtive examples into test and train
    for nTest in negTestList:
        fList = []
        for i in range(featureIndex):
            fList.append((float(nTest[i])-featureMin[i])/(featureMax[i]-featureMin[i]))
        test_labels.append(0)
        fList.append(1)
        test_features.append(fList)

        negDataList.remove(nTest)

    for nTrain in negDataList:
        fList = []
        for i in range(featureIndex):
            fList.append((float(nTrain[i])-featureMin[i])/(featureMax[i]-featureMin[i]))
        train_labels.append(0)
        fList.append(1)
        train_features.append(fList)

    train_labels = np.array(train_labels)
    train_features = np.array(train_features)
    test_labels = np.array(test_labels)
    test_features = np.array(test_features)
    return train_labels, train_features, test_labels, test_features


"""预处理"""
from jieba import posseg as pseg
from jieba import analyse
from gensim import corpora
import os

# 数据标准化
def tokenization(content):
    '''
    {形容词（a）、连词(c)、副词(d)、叹词（e）、方位词(f)、数词(m)、量词（q）、标点符号(w)、时间词（t）}
    去除文章中特定词性的词
    :content 需要标准化的数据
    :return list[str]
    '''
    # stop_flags = {'x', 'c', 'u', 'd', 'p', 't', 'uj', 'm', 'f', 'r'}
    stop_flags = {'x','q','w','t','m'}              #除去对应词性的词
    words = pseg.cut(content)
    words = ''.join([word for word, flag in words if flag not in stop_flags])
    # stop_words_path = os.path.split(os.getcwd())[0] + '/lib/stop_words.txt'    #加载停用词
    stop_words_path = 'lib/stop_words.txt'
    analyse.set_stop_words(stop_words_path)         #除去停用词
    return analyse.extract_tags(words)

def consturctWordVec(texts):
    """
    构建词向量
    :param text: 所有文章构成的数组
    :return:
    """

    dictionary = corpora.Dictionary(texts)
    corpus = [dictionary.doc2bow(text) for text in texts]
    print(corpus)
if __name__ == '__main__':
    print(tokenization("在得到每一篇文档对应的主题向量后，我们就可以计算文档之间的相似度，进而完成如文本聚类、信息检索之类的任务。在Gensim中，也提供了这一类任务的API接口。"))


"""
1033. 移动石子直到连续

三枚石子放置在数轴上，位置分别为 a，b，c。
每一回合，你可以从两端之一拿起一枚石子（位置最大或最小），并将其放入两端之间的任一空闲位置。形式上，
假设这三枚石子当前分别位于位置 x, y, z 且 x < y < z。那么就可以从位置 x 或者是位置 z 拿起一枚石子，
并将该石子移动到某一整数位置 k 处，其中 x < k < z 且 k != y。
当你无法进行任何移动时，即，这些石子的位置连续时，游戏结束。
要使游戏结束，你可以执行的最小和最大移动次数分别是多少？ 以长度为 2 的数组形式返回答案：answer = [minimum_moves, maximum_moves]
"""
from typing import List

class Solution:
    def numMovesStones(self, a: int, b: int, c: int) -> List[int]:
        a, b, c = list(sorted([a, b, c]))
        result1, result2 = 0, 0
        if b - a > 1:
            result1 += 1
        if c - b > 1:
            result1 += 1
        if b - a == 2 or c - b == 2:
            result1 = 1
        result2 += c - a - 2
        return [result1, result2]

Solution().numMovesStones(3, 5, 1)

1033. 移动石子直到连续.py


#import copy
import random
from collections import Counter

class Hat:
    def __init__(self,**kwargs):
        self.contents = []
        self.total = 0
        self.drawn = []
        for key,value in kwargs.items():
            self.total += value
            for i in range(1,value+1):
                self.contents.append(key)
        self.original = list(self.contents) #copy
        self.oritotal = int(self.total) #copy

    def draw(self,to_draw = 1): #reoccuring draw loop
        if self.total == 0: #returns to original bag contents and draws one
            self.reset()
            self.draw()
            return self.drawn
        else:
            r = random.randint(0,self.total-1)
            ball = self.contents[r]
            self.contents.pop(r)
            self.total-=1
            self.drawn.append(ball)
            if to_draw > 1:
                self.draw()
            return self.drawn

    def reset(self):
        self.contents = list(self.original)
        self.total = self.oritotal

def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
    n = int(num_experiments) #copy

    success = 0
    successes = 0

    while num_experiments > 0:
        num_experiments -= 1
        hat.drawn = []
        for i in range(0,num_balls_drawn):
            hat.draw()
        d = Counter(hat.drawn)
        for key in expected_balls:
            if d[key] >= expected_balls[key]:
                success = 1
            else:
                success = 0
                break
        if success == 1:
            successes += 1
        hat.reset()

    prob = successes/n
    return prob

'''
TESTS
hat3 = Hat(blue=3,red=2,green=6)
probability = experiment(hat=hat3, expected_balls={"blue":2,"green":1}, num_balls_drawn=4, num_experiments=1000)
print(probability) #0.272 expected

hat = Hat(yellow=5,red=1,green=3,blue=9,test=1)
probability=experiment(hat=hat, expected_balls={"yellow":2,"blue":3,"test":1}, num_balls_drawn=20, num_experiments=100)
print(probability) #1.0 expected
'''


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import os
import os.path
import unittest
from shutil import rmtree
from tempfile import mkdtemp

import mozunit

from mozbuild.action.buildlist import addEntriesToListFile

class TestBuildList(unittest.TestCase):
    """
    Unit tests for buildlist.py
    """

    def setUp(self):
        self.tmpdir = mkdtemp()

    def tearDown(self):
        rmtree(self.tmpdir)

    # utility methods for tests
    def touch(self, file, dir=None):
        if dir is None:
            dir = self.tmpdir
        f = os.path.join(dir, file)
        open(f, "w").close()
        return f

    def assertFileContains(self, filename, l):
        """Assert that the lines in the file |filename| are equal
        to the contents of the list |l|, in order."""
        l = l[:]
        f = open(filename, "r")
        lines = [line.rstrip() for line in f.readlines()]
        f.close()
        for line in lines:
            self.assertTrue(
                len(l) > 0,
                "ran out of expected lines! (expected '{0}', got '{1}')".format(
                    l, lines
                ),
            )
            self.assertEqual(line, l.pop(0))
        self.assertTrue(
            len(l) == 0,
            "not enough lines in file! (expected '{0}'," " got '{1}'".format(l, lines),
        )

    def test_basic(self):
        "Test that addEntriesToListFile works when file doesn't exist."
        testfile = os.path.join(self.tmpdir, "test.list")
        l = ["a", "b", "c"]
        addEntriesToListFile(testfile, l)
        self.assertFileContains(testfile, l)
        # ensure that attempting to add the same entries again doesn't change it
        addEntriesToListFile(testfile, l)
        self.assertFileContains(testfile, l)

    def test_append(self):
        "Test adding new entries."
        testfile = os.path.join(self.tmpdir, "test.list")
        l = ["a", "b", "c"]
        addEntriesToListFile(testfile, l)
        self.assertFileContains(testfile, l)
        l2 = ["x", "y", "z"]
        addEntriesToListFile(testfile, l2)
        l.extend(l2)
        self.assertFileContains(testfile, l)

    def test_append_some(self):
        "Test adding new entries mixed with existing entries."
        testfile = os.path.join(self.tmpdir, "test.list")
        l = ["a", "b", "c"]
        addEntriesToListFile(testfile, l)
        self.assertFileContains(testfile, l)
        addEntriesToListFile(testfile, ["a", "x", "c", "z"])
        self.assertFileContains(testfile, ["a", "b", "c", "x", "z"])

    def test_add_multiple(self):
        """Test that attempting to add the same entry multiple times results in
        only one entry being added."""
        testfile = os.path.join(self.tmpdir, "test.list")
        addEntriesToListFile(testfile, ["a", "b", "a", "a", "b"])
        self.assertFileContains(testfile, ["a", "b"])
        addEntriesToListFile(testfile, ["c", "a", "c", "b", "c"])
        self.assertFileContains(testfile, ["a", "b", "c"])

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


import cv2
import numpy as np

class clarify():

    def __init__(self, path=None, img=None):
        # open file into image array or use image itself
        if img is None:
            if path is not None:
                self.img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
            else:
                raise Exception('You have to provide a path or image itself.')
        else:
            self.img = img

    # clear image.
    # mybb captcha.php seems make its color palette of string between 0 and 200.
    # anything above 200 is noise.
    # also completely black pixels in edges must filtered
    def clarify_img(self):
        self.img[np.logical_or(np.max(self.img, axis=2)>200, np.sum(self.img, axis=2)==0)] = [255, 255, 255]

    # RGB to GRAY
    def gray(self):
        self.img = cv2.cvtColor(self.img, cv2.COLOR_RGB2GRAY)

    def resize(self, size):
        self.img = cv2.resize(self.img, size)
    # clear and gray
    def clarify_and_gray(self):
        self.clarify_img()
        self.resize((48, 48))
        self.gray()

if __name__ == "__main__":
    clr = clarify(path="test.png")
    clr.clarify_img()
    clr.gray()
    img = clr.img
    cv2.imwrite("test_clarified.png", img)
    cv2.imshow('clarified', img)

    cv2.waitKey(0)
    cv2.destroyAllWindows()


import json
import numpy as np
import triton_python_backend_utils as pb_utils

from pathlib import Path
from transformers import AutoTokenizer

class TritonPythonModel:
    """Your Python model must use the same class name. Every Python model
    that is created must have "TritonPythonModel" as the class name.
    """

    def initialize(self, args):
        """`initialize` is called only once when the model is being loaded.
        Implementing `initialize` function is optional. This function allows
        the model to initialize any state associated with this model.

        Parameters
        ----------
        args : dict
          Both keys and values are strings. The dictionary keys and values are:
          * model_config: A JSON string containing the model configuration
          * model_instance_kind: A string containing model instance kind
          * model_instance_device_id: A string containing model instance device ID
          * model_repository: Model repository path
          * model_version: Model version
          * model_name: Model name
        """
        self.config = json.loads(args["model_config"])
        self.current_dir = Path(__file__).parent
        model_max_length = int(self.config["parameters"]["model_max_length"]["string_value"])
        reference_model  = self.config["parameters"]["reference_model"]["string_value"]
        self.tokenizer = AutoTokenizer.from_pretrained(reference_model,
                                                       model_max_length=model_max_length,
                                                       cache_dir=self.current_dir / ".cache")
        print('Initialized...')

    def execute(self, requests):
        """`execute` must be implemented in every Python model. `execute`
        function receives a list of pb_utils.InferenceRequest as the only
        argument. This function is called when an inference is requested
        for this model.

        Parameters
        ----------
        requests : list
          A list of pb_utils.InferenceRequest

        Returns
        -------
        list
          A list of pb_utils.InferenceResponse. The length of this list must
          be the same as `requests`
        """

        responses = []

        # Every Python backend must iterate through list of requests and create
        # an instance of pb_utils.InferenceResponse class for each of them. You
        # should avoid storing any of the input Tensors in the class attributes
        # as they will be overridden in subsequent inference requests. You can
        # make a copy of the underlying NumPy array and store it if it is
        # required.
        for request in requests:
            # Perform inference on the request and append it to responses list...
            query = pb_utils.get_input_tensor_by_name(request, "query")
            query = [sentence[0] for sentence in query.as_numpy().astype(str)]

            ret = self.tokenizer(query, padding=True, return_tensors="np")

            ids = pb_utils.Tensor("input_ids", ret["input_ids"].astype(np.uint32))

            len = np.array([[size] for size in np.sum(ret["attention_mask"], axis=1)])
            len = pb_utils.Tensor("request_input_len", len.astype(np.uint32))
            responses.append(pb_utils.InferenceResponse(output_tensors=[ids, len]))

        # You must return a list of pb_utils.InferenceResponse. Length
        # of this list must match the length of `requests` list.
        return responses


import bs4
import urllib.request as req

url = "https://www.ptt.cc/bbs/movie/index.html"
request = req.Request(url, headers={
    "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36"
})

with req.urlopen(request) as response:
    data = response.read().decode("utf-8")

root = bs4.BeautifulSoup(data, "html.parser")

def movie():
    global root
    result = ""
    page_count = 0

    while page_count < 3:
        titles = root.find_all("div", class_="title")
        tweets = root.find_all("div", class_="nrec")
        for title, tweet in zip(titles, tweets):

            if title.a is not None:
                title_text = title.a.string
                title_link = title.a["href"]
                title_url = "https://www.ptt.cc" + title_link
                title_request = req.Request(title_url, headers={
                    "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36"
                })

                with req.urlopen(title_request) as title_response:
                    title_data = title_response.read().decode("utf-8")

                title_root = bs4.BeautifulSoup(title_data, "html.parser")
                date_element = title_root.find(
                    "span", class_="article-meta-tag", string="時間")

                if date_element is not None:
                    date = date_element.find_next_sibling("span").string
                else:
                    date = "Not found"

                tweet_num = tweet.string

                if tweet_num is not None:
                    tweet_num = tweet.string
                else:
                    tweet_num = "0"

                result += f"{title_text},{tweet_num},{date}\n"
                print(result)

        pre_link_element = root.find("a", class_="btn wide", string="‹ 上頁")

        if pre_link_element is not None:
            pre_link = pre_link_element["href"]
            pre_url = "https://www.ptt.cc" + pre_link
            pre_request = req.Request(pre_url, headers={
                "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36"
            })

            with req.urlopen(pre_request) as pre_response:
                pre_data = pre_response.read().decode("utf-8")
                root = bs4.BeautifulSoup(pre_data, "html.parser")
                page_count += 1
        else:
            print("Can't find the link to the previous page")
            break

    with open("movie.txt", "w", encoding="utf-8") as file:
        file.write(result)

movie()


import argparse, random, sys

# Define topology variables
MAX_MINER_PEERS=3
ANCHOR_PEERS=3
MIN_PORT = 7000
MAX_PORT = 7499
USED_PORTS = []
ANCHOR_MINERS = []
MINERS = []
CLIENTS = []

# Parse command-line arguments
parser = argparse.ArgumentParser(description='Generate blockchain demo topology.')
parser.add_argument('--miners', dest='num_miners', help='total number of miners in the network',
                    type=int, required=True)
parser.add_argument('--clients', dest='num_clients', help='total number of clients in the network',
                    type=int, required=True)
parser.add_argument('--malicious-miners', dest='num_mal_miners', help='total number of malicious miners in the network',
                    type=int, required=True)
parser.add_argument('--traffic', dest='traffic', help='indicates if trafic generation is on or off',
					type=int, required=True)
args = parser.parse_args()

# Sanity check for minimal amount of anchor-miners and number of malicious miners
if args.num_miners < ANCHOR_PEERS:
    print('Number of miners must be greater or equal than %d' % ANCHOR_PEERS)
    sys.exit(1)

if args.num_mal_miners >= args.num_miners:
    print('Number of malicious miners must be smaller than miners')
    sys.exit(1)

# Define anchor-miners
while len(USED_PORTS) < ANCHOR_PEERS:
    anchor_port=random.randrange(MIN_PORT, MAX_PORT)
    if anchor_port not in USED_PORTS:
        node = {'ID': 'AM%d' % anchor_port, 'port': anchor_port, 'role': 'anchor-miner', 'malicious': False, 'peers': []}
        ANCHOR_MINERS.append(node)
        USED_PORTS.append(anchor_port)

# Define miners
while len(USED_PORTS) < args.num_miners:
    port=random.randrange(MIN_PORT, MAX_PORT)
    if port not in USED_PORTS:
        node = {'ID': 'M%d' % port, 'port': port, 'role': 'miner', 'malicious': False, 'peers': []}
        MINERS.append(node)
        USED_PORTS.append(port)

# Define clientd
while len(USED_PORTS) < args.num_miners + args.num_clients:
    port=random.randrange(MIN_PORT, MAX_PORT)
    if port not in USED_PORTS:
        node = {'ID': 'C%d' % port, 'port': port, 'role': 'client', 'peers': []}
        CLIENTS.append(node)
        USED_PORTS.append(port)

# Fully connect anchor-miners together
for i in ANCHOR_MINERS:
    for j in ANCHOR_MINERS:
        if i != j and j['port'] not in i['peers']:
            i['peers'].append(j['port'])

# Connect miners to at least 1 anchor-miner and other miners
for i in MINERS:
    i['peers'].append(random.choice(ANCHOR_MINERS)['port'])
    # Find remaining peers from concatenation of anchors-miners and miners MINUS the current miner
    sample = random.sample(ANCHOR_MINERS + list(filter(lambda x: x['port'] != i['port'], MINERS)) , MAX_MINER_PEERS-1)
    for j in sample:
        i['peers'].append(j['port'])
        j['peers'].append(i['port']) # Bidirectional relationship

# Connect clients to a random anchor
for i in CLIENTS:
    am = random.choice(ANCHOR_MINERS)
    i['peers'].append(am['port'])
    am['peers'].append(i['port']) # Bidirectional relationship

# Randomly select malicious miners
for i in random.sample(MINERS+ANCHOR_MINERS, args.num_mal_miners):
    i['malicious'] = True

# Connect clients to non malicious miner if they are tied to one
for i in CLIENTS:
    for j in i['peers']:
        # j is a port
        peer = None
        # Find peer entity
        for h in MINERS+ANCHOR_MINERS:
            if h['port'] == j:
                peer = h
                break
        if peer['malicious'] == False:
            break
        # Find another peer that isn't malicious
        newPeer = None
        while True:
            miner = random.choice(MINERS+ANCHOR_MINERS)
            if miner['malicious'] == False:
                newPeer = miner
                break
        i['peers'].append(newPeer['port'])
        newPeer['peers'].append(i['port'])
        break

# Create all docker-compose client services and vis.js content
services = ''
visjs_vertices = ''
visjs_edges = ''
ui_port_counter = 8000
for i in CLIENTS:
    services += '%s:\n  image: log735-chat:latest\n  container_name: node-%s\n  environment:\n\
    - PEERS=%s\n    - TRAFFIC=%s\n    - ROLE=client\n    - PORT=%s\n  ports:\n    - \'%s:8000\'\n  networks:\n    - blockchain\n' \
                % (i['ID'], i['port'], " ".join(str(x) for x in i['peers']), args.traffic, i['port'], ui_port_counter)
    visjs_vertices += '        {id: %s, label: \'%s\'},\n' % (i['port'], i['ID'])
    ui_port_counter += 1
    for x in i['peers']:
        visjs_edges += '        {from: %s, to: %s},\n' % (i['port'], x)

for i in ANCHOR_MINERS:
    services += '%s:\n  image: log735:latest\n  container_name: node-%s\n  environment:\n\
    - PEERS=%s\n    - ROLE=miner\n    - PORT=%s\n    - MALICIOUS=%s\n  networks:\n    - blockchain\n' \
                % (i['ID'], i['port'], " ".join(str(x) for x in i['peers']), i['port'], i['malicious'])
    visjs_vertices += '        {id: %s, label: \'%s\'},\n' % (i['port'], i['ID'])
    for x in i['peers']:
        visjs_edges += '        {from: %s, to: %s},\n' % (i['port'], x)

for i in MINERS:
    services += '%s:\n  image: log735:latest\n  container_name: node-%s\n  environment:\n\
    - PEERS=%s\n    - ROLE=miner\n    - PORT=%s\n    - MALICIOUS=%s\n  networks:\n    - blockchain\n' \
                % (i['ID'], i['port'], " ".join(str(x) for x in i['peers']), i['port'], i['malicious'])
    visjs_vertices += '        {id: %s, label: \'%s\'},\n' % (i['port'], i['ID'])
    for x in i['peers']:
        visjs_edges += '        {from: %s, to: %s},\n' % (i['port'], x)

# Write docker-compose.yaml
with open('docker-compose.template', 'r') as f:
    content = f.read()

content = content.replace('%SERVICES%', ''.join('  '+line for line in services.splitlines(True)))

with open('docker-compose.yaml', 'w+') as f:
    f.write(content)

# Write index.html
with open('../webapp/scripts/index.html.template', 'r') as f:
    content = f.read()

content = content.replace('%VERTICES%', ''.join(''+line for line in visjs_vertices[:-2].splitlines(True)))
content = content.replace('%EDGES%', ''.join(''+line for line in visjs_edges[:-2].splitlines(True)))

with open('../webapp/frontend/index.html', 'w+') as f:
    f.write(content)


r"""usb-host-py - Simple host for a USB device.
"""

from timeit import default_timer
import usb.core
import usb.util

# Copied from usb-device.h
_BULK_TRANSFER_LENGTH = 1024

_INVALID_EP_ADDRESS = 0xff
_epbulk_in_address = _INVALID_EP_ADDRESS
_epbulk_in_mps = 0
_epbulk_out_address = _INVALID_EP_ADDRESS
_epbulk_out_mps = 0

def _print_device_list():
    print(usb.core.show_devices())

def _get_end_point_addresses(device):
    global _epbulk_in_address, _epbulk_in_mps, _epbulk_out_address, _epbulk_out_mps

    configuration = device[0]
    if configuration.bNumInterfaces != 1:
        print("unexpected number of interfaces {}".format(configuration.bNumInterfaces))
        return None

    interface = configuration[(0, 0)]
    if interface.bAlternateSetting != 0:
        print("unexpected number of alternate settings {}".format(interface.bAlternateSetting))
        return None
    if interface.bNumEndpoints != 2:
        print("unexpected number of endpoint {}".format(interface.bNumEndpoints))
        return None

    for endpoint in interface:
        print(
            "bEndpointAddress 0x{:x} bmAttributes 0x{:x} wMaxPacketSize 0x{:x}"
            .format(endpoint.bEndpointAddress, endpoint.bmAttributes, endpoint.wMaxPacketSize)
            )

        is_in = usb.util.endpoint_direction(endpoint.bEndpointAddress) == usb.util.ENDPOINT_IN
        is_bulk = usb.util.endpoint_type(endpoint.bmAttributes) == usb.util.ENDPOINT_TYPE_BULK
        if is_in and is_bulk:
            if _epbulk_in_address != _INVALID_EP_ADDRESS:
                print("Found multiple bulk IN endpoints")
                return None
            _epbulk_in_address = endpoint.bEndpointAddress
            _epbulk_in_mps = endpoint.wMaxPacketSize

        is_out = usb.util.endpoint_direction(endpoint.bEndpointAddress) == usb.util.ENDPOINT_IN
        if is_out and is_bulk:
            if _epbulk_out_address != _INVALID_EP_ADDRESS:
                print("Found multiple bulk IN endpoints")
                return None
            _epbulk_out_address = endpoint.bEndpointAddress
            _epbulk_out_mps = endpoint.wMaxPacketSize

    return device

def _open_device(id_vendor, id_product):
    device = usb.core.find(idVendor=id_vendor, idProduct=id_product)
    if device is not None:
        print("found device with idVendor 0x{:x} idProduct 0x{:x}".format(id_vendor, id_product))
        device.set_configuration()
        return _get_end_point_addresses(device)

    print(
        "failed to find device with idVendor 0x{:x} idProduct 0x{:x}"
        .format(id_vendor, id_product)
        )

    return None

def _check_configuration_value(device):
    configuration = device.get_active_configuration()

    if configuration.bConfigurationValue == 1:
        return True

    print(
        "'libusb_get_configuration' succeeded, configuration value is {}"
        .format(configuration.bConfigurationValue)
        )

    return False

def _control_transfer_out(device):
    data = "some data\0"
    bytes_transferred = device.ctrl_transfer(
        bmRequestType
            = usb.util.CTRL_OUT
            | usb.util.CTRL_TYPE_VENDOR
            | usb.util.CTRL_RECIPIENT_DEVICE,
        bRequest=0,
        wValue=0,
        wIndex=0,
        data_or_wLength=data
        )
    print("bytes_transferred {}".format(bytes_transferred))
    if bytes_transferred != len(data):
        print("bytes_transferred {}, expected {}".format(bytes_transferred, len(data)))
        return False

    return True

def _control_transfer_in(device):
    data = device.ctrl_transfer(
        bmRequestType
            = usb.util.CTRL_IN
            | usb.util.CTRL_TYPE_VENDOR
            | usb.util.CTRL_RECIPIENT_DEVICE,
        bRequest=0,
        wValue=0,
        wIndex=0,
        data_or_wLength=13
        )
    if len(data) != 13:
        return False

    return True

def _bulk_transfer_in(device):
    global _epbulk_in_address, _epbulk_in_mps

    assert _epbulk_in_address != _INVALID_EP_ADDRESS
    assert _epbulk_in_mps != 0

    data = device.read(_epbulk_in_address, _BULK_TRANSFER_LENGTH)

    if len(data) != _BULK_TRANSFER_LENGTH:
        print(
            "Number of bytes actually transferred not the same as the requested length, transferred {}, length {}"
            .format(len(data), _BULK_TRANSFER_LENGTH)
            )
        return False

    return True

def _repeat_bulk_in_transfer(device):
    number_of_bulk_in_repeats = 10000
    print("perform {} bulk in transfers\n".format(number_of_bulk_in_repeats))

    start = default_timer()
    for _ in range(number_of_bulk_in_repeats):
        if not _bulk_transfer_in(device):
            return False

    stop = default_timer()
    duration_us = (stop - start) * 1000000

    print("duration_us {} us".format(round(duration_us)))
    throughput_bytes_per_us = (_BULK_TRANSFER_LENGTH * number_of_bulk_in_repeats) / duration_us
    throughput_bytes_per_s = throughput_bytes_per_us * 100000
    throughput_megabytes_per_s = throughput_bytes_per_s / 100000
    throughput_megabits_per_s = throughput_megabytes_per_s * 8
    print("throughput MB/s {}".format(throughput_megabytes_per_s))
    print("throughput Mbit/s {}".format(throughput_megabits_per_s))
    print("completed {} bulk in transfers".format(number_of_bulk_in_repeats))

    return True

def _itoa(data):
    r"simulate std::itoa and avoid overflow exception"
    initialiser = 2
    for idx, _ in enumerate(data):
        data[idx] = initialiser
        initialiser += 1
        if initialiser == 256:
            initialiser = 0

def _bulk_transfer_out(device):
    global _epbulk_out_address, _epbulk_out_mps

    assert _epbulk_out_address != _INVALID_EP_ADDRESS
    assert _epbulk_out_mps != 0

    data = bytearray(_BULK_TRANSFER_LENGTH)
    _itoa(data)

    length = len(data)
    transferred = device.write(_epbulk_out_address, data)
    if transferred != length:
        print(
            "Number of bytes actually transferred not the same as the requested length,"
            " transferred {}, length {}"
            .format(transferred, length)
            )
        return False

    return True

def _do_something_with_device(device):
    assert device is not None

    if not _check_configuration_value(device):
        return

    # Control endpoint, i.e. endpoint 0, available regardless of whether or not interface is claimed
    if not _control_transfer_out(device):
        return
    if not _control_transfer_in(device):
        return

    # Interface claiming should be managed automatically

    if not _repeat_bulk_in_transfer(device):
        return
    _bulk_transfer_out(device)

def _main():
    print("usb-host")

    devices = list(usb.core.find(find_all=True))
    print("number_of_devices {}".format(len(devices)))
    _print_device_list()

    device = _open_device(0x1f00, 0x2012)

    _do_something_with_device(device)

if __name__ == "__main__":
    _main()


from sys import argv
from os.path import exists

script, from_file, to_file = argv

print(f"Copying the content from {from_file} to {to_file}")

# We could do these line in one line, how?
from_file_object = open(from_file)
from_file_data = from_file_object.read()
from_file_object.close()

print(f"The input file is {len(from_file_data)} bytes long")

print(f"Does the output file exist? {exists(to_file)}")
input("Ready? Hit ENTER to continue, CTRL+C to close..")

to_file_object = open(to_file, 'w')
to_file_object.write(from_file_data)

print("Alright, All done.")

to_file_object.close()


from sqlite3 import Error
import sqlite3
import schedule
import datetime
import pytz

class DBS:
    @staticmethod
    def connect_to_database():
        return sqlite3.connect("./bot.db")

    @staticmethod
    def execute_query(connection, query):
        cursor = connection.cursor()
        cursor.execute(query)
        result = cursor.fetchall()
        return result

    @staticmethod
    def post_sql_query(sql_query):
        try:
            with DBS.connect_to_database() as connection:
                result = DBS.execute_query(connection, sql_query)
            return result
        except sqlite3.Error as e:
            print("ERROR:", e)
            return None

    @staticmethod
    def create_users_table():
        query = '''
        CREATE TABLE IF NOT EXISTS USERS(
            user_id TEXT,
            username TEXT,
            full_name TEXT)
        '''
        DBS.post_sql_query(query)

    @staticmethod
    def user_register(user_id, user_name, full_name):
        query = f"SELECT * FROM USERS WHERE user_id='{user_id}'"
        data = DBS.post_sql_query(query)
        if not data:
            insert_query = f"INSERT INTO USERS(user_id, username, full_name) VALUES ('{user_id}', '{user_name}', '{full_name}')"
            DBS.post_sql_query(insert_query)

    @staticmethod
    def add_count(user_id, chat_id):
        query = f"SELECT * FROM reckon WHERE user_id='{user_id}' AND chat_id='{chat_id}'"
        data = DBS.post_sql_query(query)
        print(data)
        if len(data) == 0:
            insert_query = f"INSERT INTO reckon(count, user_id, chat_id) VALUES (1, '{user_id}', '{chat_id}')"
            DBS.post_sql_query(insert_query)
        else:
            new_count = data[0][0] + 1
            sql = f"UPDATE reckon SET count={new_count} WHERE user_id='{user_id}' AND chat_id='{chat_id}'"
            DBS.post_sql_query(sql)

    @staticmethod
    def reckon_count(user_id, chat_id):
        query = f"SELECT * FROM reckon WHERE user_id='{user_id}' AND chat_id='{chat_id}'"
        data = DBS.post_sql_query(query)
        if not data:
            return 0
        else:
            return data[0][1]

    @staticmethod
    def GetQuantity():
        sql = "SELECT * FROM setting"
        data = DBS.post_sql_query(sql)
        if len(data) == 0 or data[0][6] == 0:
            return False
        else:
            return data[0][6]

    @staticmethod
    def SetQuantity(clock):
        sql = f"UPDATE setting SET quantity={clock}"
        DBS.post_sql_query(sql)

    @staticmethod
    def SetRefLink(link):
        sql = f"UPDATE setting SET link='{link}'"
        DBS.post_sql_query(sql)

    @staticmethod
    def CreateInterview(msgID, fromID, categoryId):
        # O'zbekiston uchun vaqt zonasi
        uz_tz = pytz.timezone('Asia/Tashkent')

        # Vaqt sanoq
        dt = datetime.datetime.now()

        # Vaqtni O'zbekiston vaqti bilan muximlash
        uz_dt = uz_tz.localize(dt)
        print(uz_dt)
        insert_query = f"INSERT INTO Send(msgId, fromId, categoryId, createdAt) VALUES ('{msgID}', '{fromID}', {categoryId}, '{uz_dt}')"
        DBS.post_sql_query(insert_query)
        data = DBS.post_sql_query("SELECT * FROM Send ORDER BY id DESC LIMIT 1;")[0][0]
        return data

    @staticmethod
    def SetInterval(interval, _id):
        print(interval)
        sql = f"UPDATE Send SET interval='{interval}' WHERE id={_id}"
        DBS.post_sql_query(sql)
        schedule.clear()
        DBS.execute_cron_jobs()

    @staticmethod
    def GetAll(_id):
        sql = f"SELECT * FROM Send WHERE categoryId={_id} AND interval NOTNULL"
        print(sql)
        data = DBS.post_sql_query(sql)
        return data

    @staticmethod
    def SetSettingData(from_chat_id, message_id, reply_markup, _id):
        sql = f"UPDATE setting SET from_chat_id='{from_chat_id}', message_id='{message_id}', reply_markup='{reply_markup}' WHERE id={_id}"
        DBS.post_sql_query(sql)

    @staticmethod
    def GetSettingData(_id):
        sql = f"SELECT * FROM setting WHERE id=1"
        data = DBS.post_sql_query(sql)
        return data

    @staticmethod
    def GetUserCount(user_id, chat_id):
        print(user_id, chat_id)
        query = f"SELECT * FROM reckon WHERE user_id='{user_id}' AND chat_id='{chat_id}'"
        data = DBS.post_sql_query(query)
        print(data)
        if len(data) == 0:
            return False
        else:
            return data[0][1]

    @staticmethod
    def getSetting():
        query = "select * from setting"
        return DBS.post_sql_query(query)

    @staticmethod
    def ok():
        print('ok')

    @staticmethod
    def execute_cron_jobs():
        query = "SELECT * FROM Send"
        data = DBS.post_sql_query(query)[0]
        print(data)
        # schedule.every(int(data[3])).seconds.do(self.ok)
        # while True:
        #     schedule.run_pending()
        #     time.sleep(1)

    @staticmethod
    def GetBotStatus():
        data = DBS.post_sql_query("SELECT status FROM setting WHERE id=1")
        if data[0][0] == 1:
            return True
        else:
            return False

    @staticmethod
    def SetStatus(status):
        sql = f"UPDATE setting SET status={status} WHERE id=1"
        DBS.post_sql_query(sql)

print(DBS.GetBotStatus())


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

import processing

def spatialize_script(conn, table, srid):
    """Matches permits to geocodes using parcels/address data."""
    _c = conn.cursor()
    _c.execute(open("app/spatialize.sql", "r").read().format(
        table=table, srid=srid))
    _c.fetchall()
    #with open("app/spatialize.sql", "r") as content:
    #    script = content.read()
    #script = script.format(table=table, srid=srid)
    #_c.execute(script)
    return

'''
with open("spatialize.sql", "r") as ss:
    spatialize_script = ss.read()

with open("density.sql", "r") as ds:
    density_script = ds.read()

with open("", "r") as rs:
    region_summary_script = rs.read()
del ss, ds, rs
'''


# Standard
import sqlite3
import os
from pathlib import Path

class transactions:
    """Intended use is with an insert function into the transation table.

    This class is passed into the db_banner.database function.
    """
    def __init__(self, id, account, date, description, amount, misc):
        self.id = id
        self.account = account
        self.date = date
        self.description = description
        self.amount = amount
        self.misc = misc

class tags:
    """Not currently in use. Intended use is with an insert function into the tags table.
    """
    def __init__(self, id, tag):
        self.id = id
        self.tag = tag

class tags_link:
    """Not currently in use. Intended use is with an insert function into the tags_link table.
    """
    def __init__(self, id, id_tag, id_transaction):
        self.id = id
        self.id_tag = id_tag
        self.id_transaction = id_transaction

class database(object):
    """Handles all database connectsion, inputs, and outputs

    Class constructor initiates sqlite3 database connection. If used in WITH statement
    the connection will cleanly close after the statement is finished. If there are
    uncommitted transactions they will be rolled back prior to connection closure.
    """
    def __init__(self):
        __DB_LOCATION = (
            Path.home()
            / "Documents"
            / "GitHub"
            / "_appdata"
            / "cli_money_tool"
            / "accounts.db"
        )
        if os.path.exists(__DB_LOCATION):
            self.__db_connection = sqlite3.connect(str(__DB_LOCATION))
            self.cur = self.__db_connection.cursor()
        else:
            Path(
                Path.home() / "Documents" / "GitHub" / "_appdata" / "cli_money_tool"
            ).mkdir(parents=True, exist_ok=True)
            self.__db_connection = sqlite3.connect(str(__DB_LOCATION))
            self.cur = self.__db_connection.cursor()

    def __del__(self):
        self.__db_connection.close()

    def __enter__(self):
        return self

    def __exit__(self, ext_type, exc_value, traceback):
        self.cur.close()
        if isinstance(exc_value, Exception):
            self.__db_connection.rollback()
        else:
            self.__db_connection.commit()
        self.__db_connection.close()

    def execute(self, new_data: str) -> tuple:
        """Executes an valid SQL statement passed through as a string.

        Arugments:
            new_data (string): Valid SQL statement
        """
        return self.cur.execute(new_data)

    def executemany(self, many_new_data: str) -> None:
        """Not currently in use.
        """
        self.cur.executemany("REPLACE INTO jobs VALUES(?, ?, ?, ?)", many_new_data)

    def insert(self, record):
        """Inserts a transaction record. Designed for use with the transaction class.

        Arguments:
            record (transaction class): class or dictionary containing the following values:

                - id
                - account
                - date
                - description
                - amount
                - misc
        """
        record.id = self.cur.execute("""SELECT MAX(id) FROM transactions""").fetchone()[0]
        record.id = record.id + 1 if record.id else 1
        self.cur.execute(
            f"""INSERT INTO transactions
                             VALUES (
                                        "{record.id}",
                                        "{record.account}",
                                        "{record.date}",
                                        "{record.description}",
                                        "{record.amount}",
                                        "{record.misc}"
                        )"""
        )

    def create_tables(self):
        """This function confirms the existence of or creates the path, database, and tables.

        Can be used by calling the function directly, but is designed to by used by install.py, which is called by the install.bat file.
        """
        if (
            Path.home()
            / "Documents"
            / "GitHub"
            / "_appdata"
            / "cli_money_tool"
            / "accounts.db"
        ):
            pass
        else:
            Path(Path.cwd() / ".." / "_appdata" / "cli_money_tool").mkdir(
                parents=True, exist_ok=True
            )

        """create a database table if it does not exist already"""
        self.cur.execute(
            """CREATE TABLE IF NOT EXISTS
                                "transactions" (
                                    "id"            INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
                                    "account"    	TEXT NOT NULL,
                                    "date"	        TEXT NOT NULL,
                                    "description"	TEXT,
                                    "amount"	    INTEGER NOT NULL,
                                    "misc"          INTEGER
                        )"""
        )
        self.cur.execute(
            """CREATE TABLE IF NOT EXISTS
                                "tags_link" (
                                    "id"	          INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
                                    "id_tag"	      INTEGER NOT NULL,
                                    "id_transaction"  INTEGER NOT NULL
                        )"""
        )
        self.cur.execute(
            """CREATE TABLE IF NOT EXISTS
                                "tags" (
                                    "id"	INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
                                    "tag"	TEXT NOT NULL
                        )"""
        )

    def select_all_transactions(self) -> tuple:
        """Returns all transactions

        Returns:
            tuple: contains all existing transactions in transaction table.
        """
        return self.cur.execute("""SELECT * FROM transactions""").fetchall()

    def sum_transactions_all(self, account: str) -> int:
        """Sums all transactions for specified account.

        Arguments:
            account (string): selected account/institution

        Returns:
            tuple: contains single value of rounded (2 decimal paces) result.
        """
        all_amounts = self.cur.execute(
            f"""SELECT amount FROM transactions
                                           WHERE account = '{account}'
                                        """
        ).fetchall()
        calc = 0
        for i in all_amounts:
            calc += float(i[0])
        return round(calc, 2)

    def commit(self):
        """Use after any other database class function to commit changes.

        This function is separated from initial transactions to enable the __exit__ function to rollback changes in the case that errors are encountered.
        """
        self.__db_connection.commit()


import hashlib
import logging
import os
import signal
import time
import threading

from sawtooth_validator.concurrent.threadpool import \
    InstrumentedThreadPoolExecutor
from sawtooth_validator.consensus.notifier import ConsensusNotifier
from sawtooth_validator.consensus.proxy import ConsensusProxy
from sawtooth_validator.consensus.proxy import ConsensusActivationObserver
from sawtooth_validator.consensus.registry import ConsensusRegistry
from sawtooth_validator.database.lmdb_nolock_database import LMDBNoLockDatabase
from sawtooth_validator.database.native_lmdb import NativeLmdbDatabase
from sawtooth_validator.journal.block_validator import \
    BlockValidationResultStore
from sawtooth_validator.journal.block_sender import BroadcastBlockSender
from sawtooth_validator.journal.block_store import BlockStore
from sawtooth_validator.journal.block_manager import BlockManager
from sawtooth_validator.journal.completer import Completer
from sawtooth_validator.journal.responder import Responder
from sawtooth_validator.journal.journal import Journal
from sawtooth_validator.networking.dispatch import Dispatcher
from sawtooth_validator.state.batch_tracker import BatchTracker
from sawtooth_validator.state.merkle import MerkleDatabase
from sawtooth_validator.state.settings_view import SettingsViewFactory
from sawtooth_validator.state.settings_cache import SettingsObserver
from sawtooth_validator.state.settings_cache import SettingsCache
from sawtooth_validator.state.identity_view import IdentityViewFactory
from sawtooth_validator.state.state_view import StateViewFactory
from sawtooth_validator.gossip.permission_verifier import PermissionVerifier
from sawtooth_validator.gossip.permission_verifier import IdentityCache
from sawtooth_validator.gossip.identity_observer import IdentityObserver
from sawtooth_validator.networking.interconnect import Interconnect
from sawtooth_validator.gossip.gossip import Gossip

from sawtooth_validator.server.events.broadcaster import EventBroadcaster

from sawtooth_validator.journal.receipt_store import TransactionReceiptStore

from sawtooth_validator.server import network_handlers
from sawtooth_validator.server import component_handlers
from sawtooth_validator.server import consensus_handlers

LOGGER = logging.getLogger(__name__)

class Validator:
    def __init__(self,
                 bind_network,
                 bind_component,
                 bind_consensus,
                 endpoint,
                 peering,
                 seeds_list,
                 peer_list,
                 data_dir,
                 config_dir,
                 identity_signer,
                 key_dir,
                 scheduler_type,
                 permissions,
                 minimum_peer_connectivity,
                 maximum_peer_connectivity,
                 state_pruning_block_depth,
                 fork_cache_keep_time,
                 network_public_key=None,
                 network_private_key=None,
                 roles=None,
                 component_thread_pool_workers=10,
                 network_thread_pool_workers=10,
                 signature_thread_pool_workers=3):
        """Constructs a validator instance.

        Args:
            bind_network (str): the network endpoint
            bind_component (str): the component endpoint
            endpoint (str): the zmq-style URI of this validator's
                publically reachable endpoint
            peering (str): The type of peering approach. Either 'static'
                or 'dynamic'. In 'static' mode, no attempted topology
                buildout occurs -- the validator only attempts to initiate
                peering connections with endpoints specified in the
                peer_list. In 'dynamic' mode, the validator will first
                attempt to initiate peering connections with endpoints
                specified in the peer_list and then attempt to do a
                topology buildout starting with peer lists obtained from
                endpoints in the seeds_list. In either mode, the validator
                will accept incoming peer requests up to max_peers.
            seeds_list (list of str): a list of addresses to connect
                to in order to perform the initial topology buildout
            peer_list (list of str): a list of peer addresses
            data_dir (str): path to the data directory
            config_dir (str): path to the config directory
            identity_signer (Signer): cryptographic signer the validator uses
                for signing
            key_dir (str): path to the data directory
            component_thread_pool_workers (int): number of workers in the
                component thread pool; defaults to 10.
            network_thread_pool_workers (int): number of workers in the network
                thread pool; defaults to 10.
            signature_thread_pool_workers (int): number of workers in the
                signature thread pool; defaults to 3.
        """
        # -- Setup Global State Database and Factory -- #
        global_state_db_filename = os.path.join(
            data_dir, 'merkle-{}.lmdb'.format(bind_network[-2:]))
        LOGGER.debug(
            'global state database file is %s', global_state_db_filename)
        global_state_db = NativeLmdbDatabase(
            global_state_db_filename,
            indexes=MerkleDatabase.create_index_configuration())
        state_view_factory = StateViewFactory(global_state_db)

        # -- Setup Receipt Store -- #
        receipt_db_filename = os.path.join(
            data_dir, 'txn_receipts-{}.lmdb'.format(bind_network[-2:]))
        LOGGER.debug('txn receipt store file is %s', receipt_db_filename)
        receipt_db = LMDBNoLockDatabase(receipt_db_filename, 'c')
        receipt_store = TransactionReceiptStore(receipt_db)

        # -- Setup Block Store -- #
        block_db_filename = os.path.join(
            data_dir, 'block-{}.lmdb'.format(bind_network[-2:]))
        LOGGER.debug('block store file is %s', block_db_filename)
        block_db = NativeLmdbDatabase(
            block_db_filename,
            indexes=BlockStore.create_index_configuration())
        block_store = BlockStore(block_db)
        # The cache keep time for the journal's block cache must be greater
        # than the cache keep time used by the completer.
        base_keep_time = 1200

        block_manager = BlockManager()
        block_manager.add_commit_store(block_store)

        block_status_store = BlockValidationResultStore()

        # -- Setup Thread Pools -- #
        component_thread_pool = InstrumentedThreadPoolExecutor(
            max_workers=component_thread_pool_workers,
            name='Component')
        network_thread_pool = InstrumentedThreadPoolExecutor(
            max_workers=network_thread_pool_workers,
            name='Network')
        client_thread_pool = InstrumentedThreadPoolExecutor(
            max_workers=5,
            name='Client')
        sig_pool = InstrumentedThreadPoolExecutor(
            max_workers=signature_thread_pool_workers,
            name='Signature')

        # -- Setup Dispatchers -- #
        component_dispatcher = Dispatcher()
        network_dispatcher = Dispatcher()

        # -- Setup Services -- #
        component_service = Interconnect(
            bind_component,
            component_dispatcher,
            secured=False,
            reap=False,
            max_incoming_connections=20,
            monitor=True,
            max_future_callback_workers=10)

        zmq_identity = hashlib.sha512(
            time.time().hex().encode()).hexdigest()[:23]

        secure = False
        if network_public_key is not None and network_private_key is not None:
            secure = True

        network_service = Interconnect(
            bind_network,
            dispatcher=network_dispatcher,
            zmq_identity=zmq_identity,
            secured=secure,
            server_public_key=network_public_key,
            server_private_key=network_private_key,
            reap=True,
            public_endpoint=endpoint,
            connection_timeout=120,
            max_incoming_connections=100,
            max_future_callback_workers=10,
            authorize=True,
            signer=identity_signer,
            roles=roles)

        # -- Setup Transaction Execution Platform -- #
        batch_tracker = BatchTracker(block_store.has_batch)

        settings_cache = SettingsCache(
            SettingsViewFactory(state_view_factory),
        )

        event_broadcaster = EventBroadcaster(
            component_service, block_store, receipt_store)

        # -- Consensus Engine -- #
        consensus_thread_pool = InstrumentedThreadPoolExecutor(
            max_workers=3,
            name='Consensus')
        consensus_dispatcher = Dispatcher()
        consensus_service = Interconnect(
            bind_consensus,
            consensus_dispatcher,
            secured=False,
            reap=False,
            max_incoming_connections=20,
            max_future_callback_workers=10)

        consensus_registry = ConsensusRegistry()

        consensus_notifier = ConsensusNotifier(
            consensus_service,
            consensus_registry,
            identity_signer.get_public_key().as_hex())

        consensus_activation_observer = ConsensusActivationObserver(
            consensus_registry,
            consensus_notifier,
            settings_view_factory=SettingsViewFactory(state_view_factory))

        # -- Setup P2P Networking -- #
        gossip = Gossip(
            network_service,
            settings_cache,
            lambda: block_store.chain_head,
            block_store.chain_head_state_root,
            consensus_notifier,
            endpoint=endpoint,
            peering_mode=peering,
            initial_seed_endpoints=seeds_list,
            initial_peer_endpoints=peer_list,
            minimum_peer_connectivity=minimum_peer_connectivity,
            maximum_peer_connectivity=maximum_peer_connectivity,
            topology_check_frequency=1
        )

        consensus_notifier.set_gossip(gossip)

        completer = Completer(
            block_manager=block_manager,
            transaction_committed=block_store.has_transaction,
            get_committed_batch_by_id=block_store.get_batch,
            get_committed_batch_by_txn_id=(
                block_store.get_batch_by_transaction
            ),
            gossip=gossip,
            cache_keep_time=base_keep_time,
            cache_purge_frequency=30,
            requested_keep_time=300)
        self._completer = completer

        block_sender = BroadcastBlockSender(completer, gossip)

        identity_view_factory = IdentityViewFactory(
            StateViewFactory(global_state_db))

        id_cache = IdentityCache(identity_view_factory)

        # -- Setup Permissioning -- #
        permission_verifier = PermissionVerifier(
            permissions,
            block_store.chain_head_state_root,
            id_cache)

        identity_observer = IdentityObserver(
            to_update=id_cache.invalidate,
            forked=id_cache.forked)

        settings_observer = SettingsObserver(
            to_update=settings_cache.invalidate,
            forked=settings_cache.forked)

        # -- Setup Journal -- #
        journal = Journal(
            block_store=block_store,
            block_manager=block_manager,
            state_database=global_state_db,
            block_sender=block_sender,
            block_status_store=block_status_store,
            consensus_notifier=consensus_notifier,
            consensus_registry=consensus_registry,
            state_pruning_block_depth=state_pruning_block_depth,
            fork_cache_keep_time=fork_cache_keep_time,
            data_dir=data_dir,
            batch_observers=[batch_tracker],
            invalid_transaction_observers=[batch_tracker],
            observers=[
                event_broadcaster,
                receipt_store,
                batch_tracker,
                identity_observer,
                settings_observer,
                consensus_activation_observer
            ],
            key_dir=key_dir,
            genesis_observers=[receipt_store],
        )

        completer.set_get_chain_head(lambda: journal.chain_head)

        responder = Responder(completer)

        completer.set_on_block_received(journal.queue_block)

        # -- Register Message Handler -- #
        network_handlers.add(
            network_dispatcher, network_service, gossip, completer,
            responder, network_thread_pool, sig_pool,
            lambda block_id: block_id in block_manager, journal.has_batch,
            permission_verifier, consensus_notifier)

        component_handlers.add(
            component_dispatcher, gossip,
            completer, block_store, batch_tracker,
            global_state_db, self.get_chain_head_state_root_hash,
            receipt_store, event_broadcaster, permission_verifier,
            component_thread_pool, client_thread_pool,
            sig_pool, journal, identity_signer.get_public_key().as_hex())

        # -- Store Object References -- #
        self._component_dispatcher = component_dispatcher
        self._component_service = component_service
        self._component_thread_pool = component_thread_pool

        self._network_dispatcher = network_dispatcher
        self._network_service = network_service
        self._network_thread_pool = network_thread_pool

        consensus_proxy = ConsensusProxy(
            block_manager=block_manager,
            journal=journal,
            gossip=gossip,
            identity_signer=identity_signer,
            settings_view_factory=SettingsViewFactory(state_view_factory),
            state_view_factory=state_view_factory,
            consensus_registry=consensus_registry,
            consensus_notifier=consensus_notifier)

        consensus_handlers.add(
            consensus_dispatcher,
            consensus_thread_pool,
            consensus_proxy,
            consensus_notifier)

        self._block_status_store = block_status_store

        self._consensus_notifier = consensus_notifier
        self._consensus_dispatcher = consensus_dispatcher
        self._consensus_service = consensus_service
        self._consensus_thread_pool = consensus_thread_pool
        self._consensus_registry = consensus_registry

        self._client_thread_pool = client_thread_pool
        self._sig_pool = sig_pool

        self._gossip = gossip

        self._journal = journal

    def start(self):
        self._component_dispatcher.start()
        self._component_service.start()
        # will check if genesis block should be created
        self._journal.start()

        self._consensus_dispatcher.start()
        self._consensus_service.start()
        self._network_dispatcher.start()
        self._network_service.start()

        self._gossip.start()

        self._completer.set_on_batch_received(self._journal.submit_batch)
        signal_event = threading.Event()

        signal.signal(signal.SIGTERM,
                      lambda sig, fr: signal_event.set())
        # This is where the main thread will be during the bulk of the
        # validator's life.
        while not signal_event.is_set():
            signal_event.wait(timeout=20)

    def stop(self):
        self._gossip.stop()
        self._component_dispatcher.stop()
        self._network_dispatcher.stop()
        self._network_service.stop()

        self._component_service.stop()

        self._consensus_service.stop()
        self._consensus_dispatcher.stop()

        self._network_thread_pool.shutdown(wait=True)
        self._component_thread_pool.shutdown(wait=True)
        self._client_thread_pool.shutdown(wait=True)
        self._sig_pool.shutdown(wait=True)

        self._journal.stop()

        threads = threading.enumerate()

        # This will remove the MainThread, which will exit when we exit with
        # a sys.exit() or exit of main().
        threads.remove(threading.current_thread())

        while threads:
            if len(threads) < 4:
                LOGGER.info(
                    "remaining threads: %s",
                    ", ".join(
                        ["{} ({})".format(x.name, x.__class__.__name__)
                         for x in threads]))
            for t in threads.copy():
                if not t.is_alive():
                    t.join()
                    threads.remove(t)
                if threads:
                    time.sleep(1)

        LOGGER.info("All threads have been stopped and joined")

    def get_chain_head_state_root_hash(self):
        return self._chain_controller.chain_head.state_root_hash

def unwrap_if_not_none(blkw):
    if blkw:
        return blkw.block
    return None


# coding=utf8
import traceback, sys, re, time, datetime, pytz, threading, Queue, socket, subprocess

import Irc, Config, Transactions, Commands, Games, Config, Global, Logger, Expire

hooks = {}

def end_of_motd(instance, *_):
	Global.instances[instance].can_send.set()
	Logger.log("c", instance + ": End of motd, joining " + " ".join(Config.config["instances"][instance]))
	for channel in Config.config["instances"][instance]:
		Irc.instance_send(instance, ("JOIN", channel))
hooks["376"] = end_of_motd

def ping(instance, source, *args):
	Irc.instance_send(instance, tuple(("PONG",) + args), priority = 0, lock = False)
hooks["PING"] = ping

class Request(object):
	def __init__(self, instance, target, source, altnick, text, cmd):
		self.instance = instance
		self.target = target
		self.source = source
		self.nick = Irc.get_nickname(source, text)
		self.altnick = altnick
		self.text = text
		self.cmdalias = cmd

	def privmsg(self, targ, text, priority = None):
		Logger.log("c", self.instance + ": %s <- (pri=%s) %s " % (targ, str(priority),  text))
		for i in xrange(0, len(text), 350):
			if priority:
				Irc.instance_send(self.instance, ("PRIVMSG", targ, text[i:i+350]), priority = priority)
			else:
				Irc.instance_send(self.instance, ("PRIVMSG", targ, text[i:i+350]))

	def noticemsg(self, targ, text, priority = None):
		Logger.log("c", self.instance + " (NOTICE): %s <- (pri=%s) %s " % (targ, str(priority),  text))
		for i in xrange(0, len(text), 350):
			if priority:
				Irc.instance_send(self.instance, ("NOTICE", targ, text[i:i+350]), priority = priority)
			else:
				Irc.instance_send(self.instance, ("NOTICE", targ, text[i:i+350]))

	def reply(self, text, altnick = False):
		if self.nick == self.target:
			self.privmsg(self.target, self.nick + ": " + text, priority = 10)
		elif altnick:
			self.privmsg(self.target, self.altnick + ": " + text)
		else:
			self.privmsg(self.target, self.nick + ": " + text)

	def reply_private(self, text):
		self.privmsg(self.nick, self.nick + ": " + text, priority = 10)

	def notice_private(self, text):
		self.noticemsg(self.nick, self.nick + ": " + text, priority = 10)

	def say(self, text):
		if self.nick == self.target:
			self.privmsg(self.target, text, priority = 10)
		else:
			self.privmsg(self.target, text)

class FakeRequest(Request):
	def __init__(self, req, target, text):
		self.instance = req.instance
		self.target = req.target
		self.source = req.source
		self.nick = target
		self.text = text
		self.realnick = req.nick

	def privmsg(self, targ, text, priority = None):
		Logger.log("c", self.instance + ": %s <- %s " % (targ, text))
		for i in xrange(0, len(text), 350):
			if priority:
				Irc.instance_send(self.instance, ("PRIVMSG", targ, text[i:i+350]), priority = priority)
			else:
				Irc.instance_send(self.instance, ("PRIVMSG", targ, text[i:i+350]))

	def reply(self, text):
		self.privmsg(self.target, self.realnick + " [reply] : " + text)

	def reply_private(self, text):
		self.privmsg(self.target, self.realnick + " [reply_private]: " + text)

	def say(self, text):
		self.privmsg(self.target, text)

def run_command(cmd, req, arg):
	try:
		cmd(req, arg)
	except Exception as e:
		req.reply(repr(e))
		type, value, tb = sys.exc_info()
		Logger.log("ce", "ERROR in " + req.instance + " : " + req.text)
		Logger.log("ce", repr(e))
		Logger.log("ce", "".join(traceback.format_tb(tb)))
		Logger.irclog("Error while executing '%s' from '%s': %s" % (req.text, req.nick, repr(e)))
		Logger.irclog("".join(traceback.format_tb(tb)).replace("\n", " || "))
		del tb

def message(instance, source, target, text):
	host = Irc.get_host(source)
	text = Irc.strip_colours(text)
	if text == "\x01VERSION\x01":
		p = subprocess.Popen(["git", "rev-parse", "HEAD"], stdout = subprocess.PIPE)
		hash, _ = p.communicate()
		hash = hash.strip()
		p = subprocess.Popen(["git", "diff", "--quiet"])
		changes = p.wait()
		if changes:
			hash += "[+]"
		version = "Rogerer by TheHoliestRoger, version " + hash
		Irc.instance_send(instance, ("NOTICE", Irc.get_nickname(source, text), "\x01VERSION " + version + "\x01"), priority = 20)
	else:
		commandline = None
		altnick = Irc.get_nickname(source, text, altnick=True)
		if any(x.lower() in str(source).lower() for x in Config.config["bridgebotnicks"]) and ">" in str(text):
			text = text.split("> ", 1)[1]
		nick = Irc.get_nickname(source, text)
		if target == instance:
			commandline = text
		if len(text) > 1 and text[0] == Config.config["prefix"]:
			commandline = text[1:]
		elif (	len(Global.response_read_timers) > 0 and
				(target != instance or Irc.is_super_admin(source)) and (
					nick in Global.response_read_timers or
					("@roger_that" in Global.response_read_timers and target in Config.config["welcome_channels"]))):
			if nick not in Global.response_read_timers and "@roger_that" in Global.response_read_timers:
				theReadTimer = "@roger_that"
				auto_or_text = text
				time_multiplier = (60*60)
			else:
				theReadTimer = nick
				auto_or_text = "auto"
				time_multiplier = (60)
			t = time.time()
			if Global.response_read_timers[theReadTimer]["time"] + 90 > t:
				commandline = "%s %s" % (Global.response_read_timers[theReadTimer]["cmd"], text)
			elif Global.response_read_timers[theReadTimer]["time"] + (10*time_multiplier) > t:
				commandline = "%s %s" % (Global.response_read_timers[theReadTimer]["cmd"], auto_or_text)
				Logger.log("c", "%s: timer expired (auto) for: %s on: %s, cmd: %s" % (
					instance, nick, theReadTimer, Global.response_read_timers[theReadTimer]["cmd"]))
			else:
				commandline = "%s end-game" % (Global.response_read_timers[theReadTimer]["cmd"])
				Logger.log("c", "%s: timer expired (ended) for: %s on: %s, cmd: %s" % (
					instance, nick, theReadTimer, Global.response_read_timers[theReadTimer]["cmd"]))
		# Track & update last time user talked in channel (ignore PM to bot for activity purposes)
		if target.startswith('#'):
			with Global.active_lock:
				if not target in Global.active_list.keys():
					Global.active_list[target] = {}
				Global.active_list[target][nick] = time.time()
		if commandline:
			if Irc.is_ignored(host) and not Irc.is_super_admin(source):
				Logger.log("c", instance + ": %s <%s ignored> %s " % (target, nick, text))
				return
			Logger.log("c", instance + ": %s <%s> %s " % (target, nick, text))
			if Config.config.get("ignore", None):
				t = time.time()
				score = Global.flood_score.get(host, (t, 0))
				score = max(score[1] + score[0] - t, 0) + Config.config["ignore"]["cost"]
				if score > Config.config["ignore"]["limit"] and not Irc.is_admin(source):
					Logger.log("c", instance + ": Ignoring " + host)
					Irc.ignore(host, Config.config["ignore"]["timeout"])
					Irc.instance_send(instance, ("PRIVMSG", nick, "You're sending commands too quickly. Your host is ignored for 240 seconds"))
					return
				Global.flood_score[host] = (t, score)
			src = nick
			if target == instance:
				reply = src
			else:
				reply = target
			commandline = commandline.rstrip(" \t")
			if commandline.find(" ") == -1:
				command = commandline
				args = []
			else:
				command, args = commandline.split(" ", 1)
				args = [a for a in args.split(" ") if len(a) > 0]
			if command[0] != '_':
				cmd = Commands.commands.get(command.lower(), None)
				if cmd == None:
					cmd = Games.games.get(command.lower(), None)
				if not cmd.__doc__ or cmd.__doc__.find("admin") == -1 or Irc.is_admin(source):
					if cmd:
						req = Request(instance, reply, source, altnick, commandline, command.lower())
						t = threading.Thread(target = run_command, args = (cmd, req, args))
						t.start()
hooks["PRIVMSG"] = message

def date_timestamp(date):
    dt = datetime.datetime.strptime(date, "%b %d %H:%M:%S %Y").replace(tzinfo = pytz.utc)
    epoch = datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)
    return (dt - epoch).total_seconds()

def notice(instance, source, target, text):
	if "@" in source and Irc.get_host(source) == "services." and Irc.get_nickname(source, "") == "NickServ":
		m = re.match("Information on (\\S*) \\(account (\\S*)\\):", text)
		if m:
			Global.svsdata = {"nick": m.group(1), "account": m.group(2)}
			return
		m = re.match("(\\S*) is not registered\\.", text)
		if m:
			Global.svsdata = None
			Expire.svsdata({"nick": m.group(1)})
			return
		if Global.svsdata != None:
			m = re.match("Registered : ([^(]*) \\([^)]* ago\\)", text)
			if m:
				Global.svsdata["reg"] = int(date_timestamp(m.group(1)))
				return
			m = re.match("User Reg\\.  : ([^(]*) \\([^)]* ago\\)", text)
			if m:
				Global.svsdata["userreg"] = int(date_timestamp(m.group(1)))
				return
			m = re.match("Last seen  : ([^(]*) \\([^)]* ago\\)", text)
			if m:
				Global.svsdata["last"] = int(date_timestamp(m.group(1)))
				return
			m = re.match("Last seen  : now", text)
			if m:
				Global.svsdata["last"] = int(time.time())
				return
			m = re.match("Last seen  : \\(about (\\d*) weeks ago\\)", text)
			if m:
				Global.svsdata["lastweeks"] = int(m.group(1))
				return
			m = re.match("User seen  : ([^(]*) \\([^)]* ago\\)", text)
			if m:
				Global.svsdata["userlast"] = int(date_timestamp(m.group(1)))
				return
			m = re.match("User seen  : now", text)
			if m:
				Global.svsdata["userlast"] = int(time.time())
				return
			m = re.match("User seen  : \\(about (\\d*) weeks ago\\)", text)
			if m:
				Global.svsdata["userlastweeks"] = int(m.group(1))
				return
			m = re.match("\\*\\*\\* End of Info \\*\\*\\*", text)
			if m:
				Expire.svsdata(Global.svsdata)
				Global.svsdata = None
				return
hooks["NOTICE"] = notice

def join(instance, source, channel, account, _):
	curtime = time.time()
	if account == "*":
		account = False
	nick = Irc.get_nickname(source, "")
	with Global.account_lock:
		if nick  == instance:
			Global.account_cache[channel] = {}
		Global.account_cache[channel][nick] = account
		Global.nick_source_cache[nick] = source
		if account != False and account != None:
			Global.acctnick_list[account] = nick
		for channel in Global.account_cache:
			if nick in Global.account_cache[channel] and channel[0] != "@":
				if channel in Config.config["welcome_channels"] and (not account or not Transactions.check_exists(account)) and not Transactions.check_exists(nick) and (nick not in Global.welcome_list or Global.welcome_list[nick] + (60*10) < curtime):
					Global.welcome_list[nick] = curtime
					# Irc.instance_send(instance, ("PRIVMSG", channel, "Welcome our newest Rogeteer - %s! Try &help, &rogerme and &faucet to get started!" % (nick)), priority = 20, lock = False)
					Irc.instance_send(instance, ("PRIVMSG", channel, "Welcome our newest Rogeteer - %s! Try &help, &rogerme and &faucet to get started!" % (nick)), priority = 20, lock = False)
				elif channel in Config.config["welcome_channels"] and account and (Transactions.check_exists(nick) or Transactions.check_exists(account)) and (nick not in Global.welcome_list or Global.welcome_list[nick] + (60*10) < curtime):
					Global.welcome_list[nick] = curtime
					welcome_str = str(Commands.random_line('quotes_welcome'))
					Irc.instance_send(instance, ("NOTICE", nick, "Welcome back %s! %s" % (nick, welcome_str)), priority = 20, lock = False)
				Global.account_cache[channel][nick] = account
				Logger.log("w", "Propagating %s=%s into %s" % (nick, account, channel))
	if account != False:
		Expire.bump_last(account)
hooks["JOIN"] = join

def part(instance, source, channel, *_):
	nick = Irc.get_nickname(source, "")
	account = None
	with Global.account_lock:
		if nick == instance:
			del Global.account_cache[channel]
			Logger.log("w", "Removing cache for " + channel)
			return
		if nick in Global.account_cache[channel]:
			account = Global.account_cache[channel][nick]
		if nick in Global.account_cache[channel]:
			del Global.account_cache[channel][nick]
			Logger.log("w", "Removing %s from %s" % (nick, channel))
	if account != None and account != False:
		Expire.bump_last(account)
hooks["PART"] = part

def kick(instance, _, channel, nick, *__):
	account = None
	with Global.account_lock:
		if nick == instance:
			del Global.account_cache[channel]
			Logger.log("w", "Removing cache for " + channel)
			return
		if nick in Global.account_cache[channel]:
			account = Global.account_cache[channel][nick]
		if nick in Global.account_cache[channel]:
			del Global.account_cache[channel][nick]
			Logger.log("w", "Removing %s from %s" % (nick, channel))
	if account != None and account != False:
		Expire.bump_last(account)
hooks["KICK"] = kick

def quit(instance, source, _):
	curtime = time.time()
	nick = Irc.get_nickname(source, "")
	account = None
	with Global.account_lock:
		if nick == instance:
			chans = []
			for channel in Global.account_cache:
				if nick in Global.account_cache[channel]:
					chans.append(channel)
			for channel in chans:
					del Global.account_cache[channel]
					Logger.log("w", "Removing cache for " + channel)
			return
		for channel in Global.account_cache:
			if nick in Global.account_cache[channel] and channel[0] != "@":
				account = Global.account_cache[channel][nick]
				if account != None:
					break
		for channel in Global.account_cache:
			if nick in Global.account_cache[channel] and channel[0] != "@":
				del Global.account_cache[channel][nick]
				Logger.log("w", "Removing %s from %s" % (nick, channel))
	if account != None and account != False:
		Expire.bump_last(account)
hooks["QUIT"] = quit

def account(instance, source, account):
	curtime = time.time()
	if account == "*":
		account = False
	nick = Irc.get_nickname(source, "")
	with Global.account_lock:
		for channel in Global.account_cache:
			if nick in Global.account_cache[channel] and channel[0] != "@":
				if channel in Config.config["welcome_channels"] and not account and not Transactions.check_exists(nick) and (nick not in Global.welcome_list or Global.welcome_list[nick] + (60*10) < curtime):
					Global.welcome_list[nick] = curtime
					Irc.instance_send(instance, ("PRIVMSG", channel, "Welcome our newest Rogeteer - %s! Try &help, &rogerme and &faucet to get started!" % (nick)), priority = 20, lock = False)
				elif channel in Config.config["welcome_channels"] and account and Transactions.check_exists(nick) and (nick not in Global.welcome_list or Global.welcome_list[nick] + (60*10) < curtime):
					Global.welcome_list[nick] = curtime
					welcome_str = str(Commands.random_line('quotes_welcome'))
					Irc.instance_send(instance, ("NOTICE", nick, "Welcome back %s! %s" % (nick, welcome_str)), priority = 20, lock = False)
				Global.account_cache[channel][nick] = account
				Logger.log("w", "Propagating %s=%s into %s" % (nick, account, channel))
		Global.nick_source_cache[nick] = source
		if account != False and account != None:
			Global.acctnick_list[account] = nick
	if account != None and account != False:
		Expire.bump_last(account)
hooks["ACCOUNT"] = account

def _nick(instance, source, newnick):
	nick = Irc.get_nickname(source, "")
	account = None
	with Global.account_lock:
		for channel in Global.account_cache:
			if nick in Global.account_cache[channel]:
				account = Global.account_cache[channel][nick]
				Global.nick_source_cache[nick] = source
				if account != False and account != None and channel[0] != "@":
					Global.acctnick_list[account] = newnick
				if account != None:
					break
		for channel in Global.account_cache:
			if nick in Global.account_cache[channel] and channel[0] != "@":
				Global.account_cache[channel][newnick] = Global.account_cache[channel][nick]
				Logger.log("w", "%s -> %s in %s" % (nick, newnick, channel))
				del Global.account_cache[channel][nick]
	if account != None and account != False:
		Expire.bump_last(account)
hooks["NICK"] = _nick

def names(instance, _, __, eq, channel, names):
	names = names.split(" ")
	with Global.account_lock:
		for n in names:
			n = Irc.strip_nickname(n)
			Global.account_cache[channel][n] = None
hooks["353"] = names

def error(instance, *_):
	Logger.log("ce", instance + " disconnected")
	raise socket.error()
hooks["ERROR"] = error

def whois_host(instance, _, __, target, *___):
	Global.instances[instance].lastwhois = False
hooks["311"] = whois_host

def whois_ident(instance, _, __, target, account, ___):
	Global.instances[instance].lastwhois = account
hooks["330"] = whois_ident

def whois_end(instance, _, __, target, ___):
	try:
		nick, q = Global.instances[instance].whois_queue.get(False)
		if Irc.equal_nicks(target, nick):
			Logger.log("w", instance + ": WHOIS of " + target + " is " + repr(Global.instances[instance].lastwhois))
			q.put(Global.instances[instance].lastwhois, True)
		else:
			Logger.log("we", instance + ": WHOIS reply for " + target + " but queued " + nick + " returning None")
			q.put(None, True)
		Global.instances[instance].lastwhois = None
		Global.instances[instance].whois_queue.task_done()
	except Queue.Empty:
		Logger.log("we", instance + ": WHOIS reply for " + target + " but nothing queued")
hooks["318"] = whois_end

def cap(instance, _, __, ___, caps):
	if caps.rstrip(" ") == "sasl":
		Irc.instance_send(instance, ("AUTHENTICATE", "PLAIN"), lock = False)
hooks["CAP"] = cap

def authenticate(instance, _, data):
	if data == "+":
		load = Config.config["account"] + "\0" + Config.config["account"] + "\0" + Config.config["password"]
		Irc.instance_send(instance, ("AUTHENTICATE", load.encode("base64").rstrip("\n")), lock = False)
hooks["AUTHENTICATE"] = authenticate

def sasl_success(instance, _, data, __):
	Logger.log("c", "Finished authentication")
	Irc.instance_send(instance, ("CAP", "END"), lock = False)
	Irc.instance_send(instance, ("CAP", "REQ", "extended-join account-notify"), lock = False)
hooks["903"] = sasl_success


import matplotlib.pyplot as plt
import numpy as np

plt.ion()

class RamachandranPlot:
    def __init__(self):
        self.is_plot_initialized = False
        self.fig = plt.figure(figsize=(16, 9))
        self.ax = self.fig.add_subplot(111)
        self.fig.suptitle("Ramachandran plot")
        ticks = np.arange(-180, 181, 30)
        self.ax.set_xticks(ticks)
        self.ax.set_yticks(ticks)
        self.ax.grid(which="both")
        self.ax.set_ylabel("Psi")
        self.ax.set_xlabel("Phi", color="black")
        self.pred_line = None
        self.act_line = None
        plt.pause(0.5)

    def plot_ramachandran(
        self, pred_phi, pred_psi, act_phi, act_psi, phi_mae=None, psi_mae=None
    ):
        pred_phi *= 180.0 / np.pi
        pred_psi *= 180.0 / np.pi
        act_phi *= 180.0 / np.pi
        act_psi *= 180.0 / np.pi
        if not self.is_plot_initialized:
            self.pred_line, = self.ax.plot(pred_phi, pred_psi, "ro", markersize=2.5)
            self.act_line, = self.ax.plot(act_phi, act_psi, "bo", markersize=2)
            self.text = self.ax.text(
                1,
                1,
                str(phi_mae) + " | " + str(psi_mae),
                horizontalalignment="right",
                verticalalignment="bottom",
                transform=self.ax.transAxes,
            )
            self.is_plot_initialized = True
        else:
            self.pred_line.set_xdata(pred_phi)
            self.pred_line.set_ydata(pred_psi)
            self.act_line.set_xdata(act_phi)
            self.act_line.set_ydata(act_psi)
            self.text.set_text(str(phi_mae) + " | " + str(psi_mae))
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()

class ContactMap:
    def __init__(self, use_binary=False):
        self.is_plot_initialized = False
        self.fig = plt.figure(figsize=(16, 9))
        self.ax = self.fig.add_subplot(111)
        self.ax.set_axis_off()
        self.img = None
        self.use_binary = use_binary
        plt.pause(0.5)

    def plot_contact_map(self, prot_id, contact_map):
        self.fig.suptitle(prot_id)
        if self.use_binary:
            contact_map = np.where(contact_map <= 8, 1, 0)
        # self.norm = norm = cm.colors.Normalize(
        #     vmax=abs(contact_map).max(), vmin=-abs(contact_map).max()
        # )
        if not self.is_plot_initialized:
            self.img = self.ax.imshow(contact_map, aspect="equal")
            self.is_plot_initialized = True
        else:
            self.img.set_data(A=contact_map)
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()


from django.urls import path

from .views import *

urlpatterns = [
    path('', bibl_main, name="main"),
    path('add/', bibl_add, name="add"),
    path('change/', bibl_change, name="change"),
    path('api/v1/ablist/', AddressBookAPIView.as_view(), name="ablist")
]


class Persona:
    def __init__(self, nombre, documento, correo): #init es el constructor a la clase
        self.nombre = nombre
        self.documento = documento
        self.correo = correo

    # esto es lo que imprime
    def __str__(self):
        return self.nombre + "  " + self.documento

persona1 = Persona("Daniel", "123", "dfs")
persona2 = Persona("Susada", "456", "sdf")

print(persona1)
print(persona2)


# graph = {
#     'Ciudad Polacca': {'Santo Subito': 15, 'Senderos': 10},
#     'Senderos': {'Dos Rios': 20},
#     'Santo Subito': {'Dos Rios': 5, 'Al Pacino': 50},
#     'Dos Rios': {'Frontera': -5, 'Arboleda': 5},
#     'Frontera': {'Al Pacino': 10},
#     'Arboleda': {'Al Pacino': 10},
#     'Al Pacino': {}
# }
graph = {
 'Ciudad Polacca': {'Santo Subito': 15, 'Senderos': 10},
 'Senderos': {'Dos Rios': 20},
 'Santo Subito': {'Dos Rios': 5, 'Al Pacino': 50},
 'Dos Rios': {'Frontera': 20, 'Arboleda': 5},
 'Frontera': {'Al Pacino': 10},
 'Arboleda': {'Al Pacino': 10},
 'Al Pacino': {}
}

current_node = "Ciudad Polacca"
cost = {}
parents = {}

for name in graph.keys():
    cost[name] = float('inf')
    parents[name] = None

cost[current_node] = 0
def change_cost(graph, cost, parents):
    there_is_change = False

    for node in graph.keys():
        for d, c in graph[node].items():
            if cost[node] != float('inf') and cost[d] > cost[node] + c:
                cost[d] = cost[node] + c
                parents[d] = node
                there_is_change = True
    return there_is_change

for _ in range(len(graph)-1):

    if not change_cost(graph, cost, parents):
        break

if change_cost(graph, cost, parents):
    print('There is a negative cycle.')
else:
    print('There is NOT a negative cycle.')
    for n,m in cost.items():
        print(f'The cost for {n} is {m}')
        current_n = n
        while parents[current_n]:
            print(parents[current_n])
            current_n = parents[current_n]
        else:
            print(current_n)


import wx

class DSTGui(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: DSTGui.__init__
        kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.SetSize((491, 309))

        # Menu Bar
        self.frame_menubar = wx.MenuBar()
        wxglade_tmp_menu = wx.Menu()
        self.frame_menubar.Append(wxglade_tmp_menu, "File")
        self.SetMenuBar(self.frame_menubar)
        # Menu Bar end
        self.list_box_1 = wx.ListBox(self, wx.ID_ANY, choices=["c"])
        self.button_2 = wx.Button(self, wx.ID_ANY, "+")
        self.button_3 = wx.Button(self, wx.ID_ANY, "V")

        self.__set_properties()
        self.__do_layout()
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: DSTGui.__set_properties
        self.SetTitle("frame")
        self.button_2.SetMinSize((34, 34))
        self.button_3.SetMinSize((34, 34))
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: DSTGui.__do_layout
        sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_3 = wx.BoxSizer(wx.VERTICAL)
        sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_3.Add(self.list_box_1, 0, wx.EXPAND | wx.SHAPED | wx.TOP, 0)
        sizer_4.Add(self.button_2, 0, 0, 0)
        sizer_4.Add(self.button_3, 0, 0, 0)
        sizer_3.Add(sizer_4, 9, wx.EXPAND, 0)
        sizer_2.Add(sizer_3, 1, wx.EXPAND, 0)
        sizer_2.Add((0, 0), 0, 0, 0)
        self.SetSizer(sizer_2)
        self.Layout()
        # end wxGlade

    def add_process(self, event):  # wxGlade: DSTGui.<event_handler>
        self.list_box_1.InsertItems(['test'], self.list_box_1.GetSelection() + 1)
        # event.Skip()

# end of class DSTGui

class DSTApp(wx.App):
    def OnInit(self):
        self.frame = DSTGui(None, wx.ID_ANY, "dST GUI")
        self.SetTopWindow(self.frame)
        self.frame.Show()
        return True


import heapq
import sys
from collections import deque
from datetime import datetime
from heapq import heappop, heappush
input = sys.stdin.readline

# 2133
N = int(input())
DP = [0] * 31
DP[0] = 1
DP[1] = 0
DP[2] = 3
for i in range(4, N+1):
    if i % 2 == 0:
        DP[i] += DP[i-2] * 3

    for j in range(4, i+1, 2):
        DP[i] += DP[i-j] * 2
print(DP[N])