import os
import sys
import docx2python

# Program to convert MS-Word pastes into a less
# annoying text file layout.

# Certain unicode symbols can be annoying to work with.
TRANSLATION_TABLE = [
    ("“", "\""), ("”", "\""), ("„", "\""),
    ("’", "'"), ("–", "-"), ("…", "..."),
    ("•", "*"),
]

def write_output(lines: list, out_file_name: str) -> None:
    with open(out_file_name, "w") as f:
        was_whitespace = False
        in_preformatted_block = False

        for line in lines:
            # Handle HTML <pre> blocks
            if "<pre>" in line or in_preformatted_block:
                in_preformatted_block = True

            if in_preformatted_block:
                f.write(line)
                if "</pre>" in line:
                    in_preformatted_block = False
                    was_whitespace = False

                continue

            # Convert unicode symbols
            for sym, rep in TRANSLATION_TABLE:
                line = line.replace(sym, rep)

            # Header
            if line.startswith("#"):
                was_whitespace = False
                f.write(line + "\n")

            # Whitespace
            elif not line.strip():
                if not was_whitespace:
                    was_whitespace = True
                    f.write("\n")

            # Normal text
            else:
                # Docx extraction artifact
                if line.strip() == "*-":
                    line = "---"

                was_whitespace = False
                buffer = str()
                for word in line.split():
                    if len(buffer) + len(word) + 1 < 80:
                        buffer += (" " + word if buffer else word)

                    else:
                        f.write(buffer + "\n")
                        buffer = word

                f.write(buffer + "\n\n")

        print("OK")

def process_md_file(input_name: str, out_file_name: str) -> None:
    print(f"Reading .md file: \"{input_name}\"... ", end="")
    with open(input_name, "r", encoding="utf-8", errors="replace") as f:
        lines = [e.strip() for e in f.readlines()]

    text = str()
    new_line = True
    for line in lines:
        if not line or any([line.startswith(c) for c in "*#"]):
            new_line = True
            text += "\n\n"

        if line:
            if new_line:
                new_line = False
            else:
                text += " "
            text += line

    print("OK")
    with open(out_file_name, "w", encoding="utf-8", errors="replace") as f:
        f.write(text)

def verify_file_does_not_exist_and_get_output_name(input_file_name: str, extension: str) -> str:
    output_name = input_file_name.rsplit(".", 1)[0] + extension
    if os.path.exists(output_name):
        print("Output file already exists!")
        sys.exit(-1)

    return output_name

def process_file(input_name: str) -> None:
    lower_file_name = input_name.lower().strip().rsplit(os.path.sep, 1)[-1]

    if lower_file_name.endswith(".txt"):
        output_name = verify_file_does_not_exist_and_get_output_name(input_name, ".md")
        print(f"Reading .txt file: \"{input_name}\"... ", end="")
        with open(input_name, "r", encoding="utf-8") as f:
            lines = f.readlines()
            write_output(lines, output_name)

    # docx files need some more handling
    elif lower_file_name.endswith(".docx") and not lower_file_name.startswith("~$"):
        output_name = verify_file_does_not_exist_and_get_output_name(input_name, ".md")
        print(f"Reading .docx file: \"{input_name}\"... ", end="")
        text = docx2python.docx2python(input_name).text.replace("--", "*")
        lines = [e + "\n" for e in text.splitlines() if e]
        write_output(lines, output_name)

    # convert .md files back to a format paste-able into Word
    elif lower_file_name.endswith(".md"):
        output_name = verify_file_does_not_exist_and_get_output_name(input_name, ".txt")
        process_md_file(input_name, output_name)

def process(input_name: str) -> None:
    if not os.path.exists(input_name):
        print(f"No file with name \"{input_name}\"!")
        return

    if os.path.isdir(input_name):
        print(f"Converting directory \"{input_name}\"...")
        entries = os.listdir(input_name)
        files = filter(lambda e: e.endswith(".docx") or e.endswith(".txt"), entries)

        for file in files:
            path = os.path.join(input_name, file)
            process_file(path)

    else:
        process_file(input_name)

def main() -> None:
    print("Flesh-Network Blog Post Indenting Tool (2021)")
    print("-> Convert .txt and .docx files into properly formatted blog posts!\n")
    if len(sys.argv) != 2:
        print("Please supply a file name!")
        sys.exit(-1)

    input_name = sys.argv[1]
    process(input_name)

if __name__ == "__main__":
    main()


import argparse
from pickle import NONE
import random
from wordfreq import zipf_frequency
from constants import *

def get_difficulty_to_words_map(difficulty=None):
    difficulty_to_words_map = {}
    for word in WORDS:
        difficulty = get_word_difficulty(word)
        if difficulty not in difficulty_to_words_map:
            difficulty_to_words_map[difficulty] = set(word)
        else:
            difficulty_to_words_map[difficulty].add(word)
    return difficulty_to_words_map if difficulty is None else difficulty_to_words_map[difficulty]

def get_word_difficulty(word):
    """
    Returns the difficulty of the word
    """
    frequency = zipf_frequency(word, 'en')
    if frequency >  2.63:
        return 1
    elif frequency > 1.7:
        return 2
    return 3

def get_word(length=None, difficulty=None):
    """
    Returns a random word from the dictionary of words
    """
    word_of_difficulty = get_difficulty_to_words_map(difficulty=difficulty)
    if length == 1:
        return random.choice(list(word_of_difficulty))

    word = NONE
    WORD_SEARCH_LIMIT = 1000
    for _ in range(WORD_SEARCH_LIMIT):
        word = random.choice(list(word_of_difficulty))
        if len(word) != length:
            continue

    if word == NONE:
        raise Exception("Could'nt find a word of length {}, try again with a different length!".format(length))

    return word

def validate_args(args):
    print("Validating arguments...")
    if not args.word:
        args.word = get_word(args.length, args.difficulty)
    args.word = args.word.lower()
    if args.word not in WORDS:
        raise ValueError("Word not in dictionary")
    if args.difficulty not in DIFFICULTY_CHOICES:
        raise ValueError(
            "Difficulty must be one of {}".format(DIFFICULTY_CHOICES))
    if args.length < MIN_WORD_LENGTH or args.length > MAX_WORD_LENGTH:
        raise ValueError("Word length must be between {} and {}".format(
            MIN_WORD_LENGTH, MAX_WORD_LENGTH))
    if args.guesses < MIN_GUESSES or args.guesses > MAX_GUESSES:
        raise ValueError("Number of guesses must be between {} and {}".format(
            MIN_GUESSES, MAX_GUESSES))
    print("Arguments validated successfully!")
    return args

def fetch_arguments_parser():
    parser = argparse.ArgumentParser(description='Worlde bot')
    parser.add_argument('-w', '--word', type=str,
                        help='Word to solve', default=None, required=False)
    parser.add_argument('-l', '--length', type=int,
                        help='Length of the word', default=DEFAULT_WORD_LENGTH, required=False)
    parser.add_argument('-d', '--difficulty', type=str,
                        help='Difficulty of the word', default=DEFAULT_DIFFICULTY, required=False)
    parser.add_argument('-g', '--guesses', type=str,
                        help='Number of gussess allowed', default=DEFAULT_NUM_GUESSES, required=False)
    parser.add_argument('-s', '--slow', type=str,
                        help='Wait for user input after every guess', default=None,
                        required=False)
    return parser


import unittest
import sys
import importlib
from math import sqrt
import BaseTypes
import model

class TestChromosome(unittest.TestCase):
    def setUp(self):
        self.naturalNumberN = model.Nucleotide(domain=BaseTypes.IntInterval(0,9))
        self.lessThan100N = model.Nucleotide(domain=BaseTypes.IntInterval(0,99))
        self.distanceG = model.Gene((self.naturalNumberN, self.lessThan100N),
                                    lambda nucleos: \
                                    nucleos[0].value + nucleos[1].value/100.0)
        self.fenotype = lambda genotype: sqrt(genotype[0].fenotype()**2 + \
                                              genotype[1].fenotype()**2)
        self.positionC = model.Chromosome((self.distanceG, self.distanceG),
                                          self.fenotype)

    def test_get_genes(self):
        genes = self.positionC.genes
        map(lambda gene: self.assertEqual(gene, self.distanceG), genes)

    def test_get_fenotypeFun(self):
        fenotype = self.positionC.fenotypeFun
        self.assertEqual(fenotype, self.fenotype)

    def test_fenotype(self):
        self.assertEqual(self.positionC.fenotype(),
                         self.fenotype(self.positionC.genes))

if __name__=='__main__':
    try:
        file_name = sys.argv[1]
        model = importlib.import_module(file_name)
    except IndexError:
        unittest.main()
        end()
    except ImportError:
        if sys.argv[1].startswith('-'):
            unittest.main()
            end()
        else:
            raise

    loader = unittest.defaultTestLoader.loadTestsFromTestCase(TestChromosome)
    unittest.TextTestRunner().run(loader)


import pytest

from .. import *

# this is not necessary but mypy complains if it's not included
from .. import CompileOptions

options = CompileOptions()

def test_cond_one_pred():
    expr = Cond([Int(1), Int(2)])
    assert expr.type_of() == TealType.uint64

    cond1, _ = Int(1).__teal__(options)
    pred1, _ = Int(2).__teal__(options)
    cond1Branch = TealConditionalBlock([])
    cond1.setNextBlock(cond1Branch)
    cond1Branch.setTrueBlock(pred1)
    cond1Branch.setFalseBlock(Err().__teal__(options)[0])
    pred1.setNextBlock(TealSimpleBlock([]))
    expected = cond1

    actual, _ = expr.__teal__(options)

    with TealComponent.Context.ignoreExprEquality():
        assert actual == expected

def test_cond_two_pred():
    expr = Cond([Int(1), Bytes("one")], [Int(0), Bytes("zero")])
    assert expr.type_of() == TealType.bytes

    cond1, _ = Int(1).__teal__(options)
    pred1, _ = Bytes("one").__teal__(options)
    cond1Branch = TealConditionalBlock([])
    cond2, _ = Int(0).__teal__(options)
    pred2, _ = Bytes("zero").__teal__(options)
    cond2Branch = TealConditionalBlock([])
    end = TealSimpleBlock([])

    cond1.setNextBlock(cond1Branch)
    cond1Branch.setTrueBlock(pred1)
    cond1Branch.setFalseBlock(cond2)
    pred1.setNextBlock(end)

    cond2.setNextBlock(cond2Branch)
    cond2Branch.setTrueBlock(pred2)
    cond2Branch.setFalseBlock(Err().__teal__(options)[0])
    pred2.setNextBlock(end)

    expected = cond1

    actual, _ = expr.__teal__(options)

    with TealComponent.Context.ignoreExprEquality():
        assert actual == expected

def test_cond_three_pred():
    expr = Cond([Int(1), Int(2)], [Int(3), Int(4)], [Int(5), Int(6)])
    assert expr.type_of() == TealType.uint64

    cond1, _ = Int(1).__teal__(options)
    pred1, _ = Int(2).__teal__(options)
    cond1Branch = TealConditionalBlock([])
    cond2, _ = Int(3).__teal__(options)
    pred2, _ = Int(4).__teal__(options)
    cond2Branch = TealConditionalBlock([])
    cond3, _ = Int(5).__teal__(options)
    pred3, _ = Int(6).__teal__(options)
    cond3Branch = TealConditionalBlock([])
    end = TealSimpleBlock([])

    cond1.setNextBlock(cond1Branch)
    cond1Branch.setTrueBlock(pred1)
    cond1Branch.setFalseBlock(cond2)
    pred1.setNextBlock(end)

    cond2.setNextBlock(cond2Branch)
    cond2Branch.setTrueBlock(pred2)
    cond2Branch.setFalseBlock(cond3)
    pred2.setNextBlock(end)

    cond3.setNextBlock(cond3Branch)
    cond3Branch.setTrueBlock(pred3)
    cond3Branch.setFalseBlock(Err().__teal__(options)[0])
    pred3.setNextBlock(end)

    expected = cond1

    actual, _ = expr.__teal__(options)

    with TealComponent.Context.ignoreExprEquality():
        assert actual == expected

def test_cond_has_return():
    exprWithReturn = Cond([Int(1), Return(Int(1))], [Int(0), Return(Int(0))])
    assert exprWithReturn.has_return()

    exprWithoutReturn = Cond([Int(1), Bytes("one")], [Int(0), Bytes("zero")])
    assert not exprWithoutReturn.has_return()

    exprSemiReturn = Cond(
        [Int(1), Return(Int(1))], [Int(0), App.globalPut(Bytes("key"), Bytes("value"))]
    )
    assert not exprSemiReturn.has_return()

def test_cond_invalid():
    with pytest.raises(TealInputError):
        Cond()

    with pytest.raises(TealInputError):
        Cond([])

    with pytest.raises(TealTypeError):
        Cond([Int(1), Int(2)], [Int(2), Txn.receiver()])

    with pytest.raises(TealTypeError):
        Cond([Arg(0), Int(2)])


# Qus:https://leetcode.com/problems/next-greater-element-i/

class Solution(object):
    def nextGreaterElement(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """

        stack = []
        d = {}

        for num in nums2:
            if(stack==[]):
                stack.append(num)
            else:

                while(stack!=[] and stack[-1]<num):
                    d[stack.pop()] = num
                stack.append(num)

        ans = []
        for num in nums1:
            ans.append(d.get(num,-1))
        return ans

leetcoding qus/Next Greater Element I.py


# Import the image data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

from tensorflow.contrib.session_bundle import exporter

import tensorflow as tf

# Start a session
sess = tf.InteractiveSession()

# Input Data
x = tf.placeholder(tf.float32, [None, 784])

# Actual Results
y_ = tf.placeholder(tf.float32, [None, 10])

# Begin Model
# Setup Weights
W = tf.Variable(tf.zeros([784, 10]))
# Wx will give a 1x10

# Setup biases
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x, W) + b)
# End Model

# Mean of the sum of y*log(y)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

# Optimize for the lowest cross entropy
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

# Define initial variables
init = tf.global_variables_initializer()
sess.run(init)

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))


import os

from . import exceptions
from .master import CURRENT as MASTER

def task(prefix, parsed_args, **kwargs):
    return [x["id"] for x in MASTER.tasks(prefix)]

def slave(prefix, parsed_args, **kwargs):
    return [s["id"] for s in MASTER.slaves(prefix)]

def file(prefix, parsed_args, **kwargs):
    files = set([])
    split = prefix.rsplit("/", 1)
    base = ""
    if len(split) == 2:
        base = split[0]
    pattern = split[-1]

    for task in MASTER.tasks(parsed_args.task):
        # It is possible for the master to have completed tasks that no longer
        # have files and/or executors
        try:
            for file_meta in task.file_list(base):
                rel = os.path.relpath(file_meta["path"], task.directory)
                if rel.rsplit("/", 1)[-1].startswith(pattern):
                    if file_meta["mode"].startswith("d"):
                        rel += "/"
                    files.add(rel)
        except exceptions.MissingExecutor:
            pass
    return files


from __future__ import annotations

# IMPORTS
# =======>

# noinspection PyUnresolvedReferences
import typing
from util.formatter.TextColor import *
from util.formatter.TextEffects import *
from dataclasses import dataclass, field
from copy import deepcopy

# EXPORTS
# =======>

__all__ = [
    'FormatString'
]

# MAIN CONTENT
# ============>

@dataclass
class FormatString:
    """
    A class that represents a format string.

    Attributes
    ----------
    string: typing.Any
        The string.
    color: TextColor
        The color.
    bold: bool
        Whether the string is bold.
    underline: bool
        Whether the string is underlined.
    italic: bool
        Whether the string is italicized.
    strikethrough: bool
        Whether the string is strikethrough.
    minlength: int or None
        The minimum length of the string.
    maxlength: int or None
        The maximum length of the string.

    Notes
    -----
    Color is an BASH escape sequence.

    References
    ----------
    [1] https://misc.flogisoft.com/bash/tip_colors_and_formatting
    """
    string: typing.Any = field(default='')
    color: TextColor | typing.Iterable[TextColor] = field(default=TextColor.RESET)
    bold: bool = field(default=False)
    underline: bool = field(default=False)
    italic: bool = field(default=False)
    strikethrough: bool = field(default=False)
    minlength: typing.Optional[int] = field(default=None)
    maxlength: typing.Optional[int] = field(default=None)

    _strings: typing.List[str] = field(init=False)
    _colors: typing.List[TextColor] = field(init=False)
    _bolds: typing.List[bool] = field(init=False)
    _underlines: typing.List[bool] = field(init=False)
    _italics: typing.List[bool] = field(init=False)
    _strikethroughs: typing.List[bool] = field(init=False)

    def __post_init__(self):
        """
        Initializes the format string.
        """
        self.string = str(self.string)
        self.string = self.string.ljust(self.minlength) if self.minlength is not None else self.string
        self.string = self.string[:self.maxlength - 1] + '…' \
            if self.maxlength is not None and len(self.string) > self.maxlength else self.string
        self._strings = []
        self._colors = []
        self._bolds = []
        self._underlines = []
        self._italics = []
        self._strikethroughs = []
        self._strings.append(self.string)
        self._colors.append(self.color)
        self._bolds.append(self.bold)
        self._underlines.append(self.underline)
        self._italics.append(self.italic)
        self._strikethroughs.append(self.strikethrough)

    def __str__(self) -> str:
        """
        Returns the string representation of the format string.

        Returns
        -------
        str
            The string representation of the format string.
        """
        string = ''
        for i in range(len(self._strings)):
            if isinstance(self._colors[i], TextColor):
                string += self._colors[i].value
            else:
                string += ''.join(map(lambda x: x.value, self._colors[i]))
            if self._bolds[i]:
                string += TextEffects.BOLD.value
            if self._underlines[i]:
                string += TextEffects.UNDERLINE.value
            if self._italics[i]:
                string += TextEffects.ITALIC.value
            if self._strikethroughs[i]:
                string += TextEffects.STRIKETHROUGH.value
            string += self._strings[i] + TextColor.RESET.value
        return string

    def __repr__(self) -> str:
        """
        Returns the string representation of the format string.

        Returns
        -------
        str
            The string representation of the format string.
        """
        return self.__str__()

    def indent(self, indent=4) -> FormatString:
        """
        Indents the format string.

        Parameters
        ----------
        indent: int
            The number of spaces to indent by.

        Returns
        -------
        FormatString
            The indented format string.
        """
        buffer = FormatString(' ' * indent)
        for index, string in enumerate(self._strings):
            lines = list(map(lambda x: FormatString(
                string=x, color=self._colors[index], bold=self._bolds[index], underline=self._underlines[index],
                italic=self._italics[index], strikethrough=self._strikethroughs[index]
            ), string.split('\n')))
            buffer += lines[0]
            for line in lines[1:]:
                buffer += FormatString('\n' + ' ' * indent) + line
        return buffer

    def join(self, strings: typing.Iterable[FormatString | str]) -> FormatString:
        """
        Joins the format strings.

        Parameters
        ----------
        strings: typing.List[FormatString]
            The format strings to join.

        Returns
        -------
        FormatString
            The joined format string.
        """
        buffer = FormatString()
        for index, string in enumerate(strings):
            if index > 0:
                buffer += self
            buffer += string
        return buffer

    def __add__(self, other: FormatString | str) -> FormatString:
        """
        Returns the concatenation of the format strings.

        Parameters
        ----------
        other: FormatString
            The other format string.

        Returns
        -------
        FormatString
            The concatenation of the format strings.
        """
        cself = deepcopy(self)
        other = deepcopy(other)
        if isinstance(other, str):
            other = FormatString(other)
        cself._strings += other._strings
        cself._colors += other._colors
        cself._bolds += other._bolds
        cself._underlines += other._underlines
        cself._italics += other._italics
        cself._strikethroughs += other._strikethroughs
        return cself

    def toRawString(self) -> str:
        """
        Returns the raw string representation of the format string.

        Returns
        -------
        str
            String without any formatting, but with all BASH escape sequences.

        Examples
        --------
        >>> print(FormatString('foo', TextColor.RED).toRawString())
        \033[31mfoo\033[0m

        Notes
        -----
        This method is used for testing.
        """
        string = self.__str__()
        for color, code in TextColor.RawCodes().items():
            string = string.replace(color.value, code)
        for effect, code in TextEffects.RawCodes().items():
            string = string.replace(effect.value, code)
        return string


import time, datetime
from screener import Screener
import os, yaml

def log(msg):
    print(f"[{datetime.datetime.now()}] - {msg}")

config = yaml.safe_load(open("config.yaml","r"))
folder_left = config['folder_left']
folder_substats = config['folder_substats']
sec_between_screenshot = config['sec_between_screenshot']

# make dirs
for folder in [folder_left, folder_substats]:
    try:
        os.makedirs(folder)
    except:
        pass

if __name__ == '__main__':
    bot = Screener(folder_left, folder_substats)
    log('Calibrate screen left')
    bot.run_calibration_left()
    time.sleep(1)
    log('Calibrate screen substats')
    bot.run_calibration_substats()
    log('Calibration is done, starting screenshoting...')
    print()
    while True:
        log(f'taking screenshot n°{bot.index}...')
        bot.screenshot(f"{bot.index}.png")
        bot.delete_screenshot_if_redonant()
        log('done.')
        print()
        time.sleep(sec_between_screenshot)


import sqlite3 as sq
from others import funcs as f

def sql_start():
    global base, cur
    base = sq.connect('bd_crypto_users.db')
    cur = base.cursor()
    if base:
        print('BD connected')
    base.execute('CREATE TABLE IF NOT EXISTS {}(id PRIMARY KEY, USDT,BTC,ETH)'.format('data'))
    base.commit()

def sql_add_start(user_id, usdt):
    cur.execute('INSERT INTO data VALUES (?,?,?,?)', (user_id, str(usdt), str(0), str(0)))
    base.commit()

def sql_reset_balance(user_id, usdt):
    cur.execute('UPDATE data SET BTC == 0, ETH == 0 WHERE id == ' +
                str(user_id))
    base.commit()
    cur.execute('UPDATE data SET USDT == ' + str(usdt) +
                ' WHERE id == ' + str(user_id))
    base.commit()

def sql_get_dep(user_id):
    r = cur.execute('SELECT USDT FROM data WHERE id LIKE \'%' +
                    str(user_id) + '%\'').fetchone()
    return r[0]

def sql_get_crypto(user_id):
    r = cur.execute('SELECT BTC, ETH FROM data WHERE id LIKE \'%' +
                    str(user_id) + '%\'').fetchone()
    return r

def sql_buy_crypto(user_id, coin, usdt):
    i = f.check_crypto_name(coin)
    amount_of_crypto = float(f.change_coins_amount(usdt, coin)).__round__(7)
    cur.execute('UPDATE data SET ' + coin + ' == ' +
                str((float(sql_get_crypto(user_id)[i]).__round__(7) +
                     amount_of_crypto)) +
                ' WHERE id == ' + str(user_id))
    base.commit()
    amount_of_usdts = (float(sql_get_dep(user_id)) - float(usdt)).__round__(2)
    if amount_of_usdts == 0.0:
        amount_of_usdts = 0
    cur.execute('UPDATE data SET USDT == ' + str(amount_of_usdts) +
                ' WHERE id == ' + str(user_id))
    base.commit()
    return str(amount_of_crypto)

def sql_sell_crypto(user_id, coin, crypto_amount):
    i = f.check_crypto_name(coin)
    crypto_balance = (float(sql_get_crypto(user_id)[i]) - float(crypto_amount)).__round__(7)
    if crypto_balance == 0.0:
        crypto_balance = 0
    cur.execute('UPDATE data SET ' + coin + ' == ' + str(crypto_balance) +
                ' WHERE id == ' + str(user_id))
    base.commit()
    usdt_amount = float(f.change_usdt_amount(crypto_amount, coin)).__round__(2)
    cur.execute('UPDATE data SET USDT == ' + str(
        (float(sql_get_dep(user_id)).__round__(2) +
         usdt_amount)) + ' WHERE id == ' + str(user_id))
    base.commit()
    return str(usdt_amount)

def sql_delete_acc(user_id):
    cur.execute('DELETE FROM data WHERE id == ' +
                str(user_id))
    base.commit()

def sql_read_id(user_id):
    try:
        r = cur.execute('SELECT id FROM data WHERE id LIKE \'%' +
                        str(user_id) + '%\'').fetchone()
        return r[0]
    except:
        return 0


# 수집할 정보에 대응하는 CSS선택자를 각각 문자열 하나로 만들고, 이들을 딕셔너리 객체에 모아서 BeautifulSoup select함수와 사용하는 기법
# Content는 \
import requests
from bs4 import BeautifulSoup
class Content:
    '''
    글/페이지 전체에 사용할 기반 클래스
    '''

    def __init__(self, url, title, body):
        self.url = url
        self.title = title
        self.body = body

    def print(self):
        '''
        출력 결과를 원하는 대로 바꿀 수 있는 함수
        '''
        print('URL: {}'.format(self.url))
        print('TITLE: {}'.format(self.title))
        print('BPDY: {}'.format(self.body))

# Website 클래스는 각 페이지에서 수집한 정보를 저장하는 것이 아니라, 해당 데이터를 수집하는 방법에 대한 지침을 저장합니다.
class Website:
    '''
    웹사이트 구조에 관한 정보를 저장할 클래스
    '''

    def __init__(self, name, url, titleTag, bodyTag):
        self.name = name
        self.url = url
        self.titleTag = titleTag
        self.bodyTag = bodyTag

# -----

class Crawler:

    def getPage(self, url):
        try:
            req = requests.get(url)
        except requests.exceptions.RequestException:
            return None
        return BeautifulSoup(req.text, 'html.parser')
    def safeGet(self, pageObj, selector):
        '''
        BeautifulSoup객체와 선택자를 받아 콘텐츠 문자열을 추출하는 함수
        주어진 선택자로 검색된 결과가 없다면 빈 문자열을 반환합니다.
        '''
        selectedElems = pageObj.select(selector)
        if selectedElems is not None and len(selectedElems) > 0:
            return '\n'.join([elem.get_text() for elem in selectedElems])
        return ''
    def parse(self, site, url):
        '''
        URL을 받아 콘텐츠를 추출합니다.
        '''
        bs = self.getPage(url)
        if bs is not None:
            title = self.safeGet(bs, site.titleTag)
            body = self.safeGet(bs, site.bodyTag)
            if title != '' and body != '':
                content = Content(url, title, body)
                content.print()

crawler = Crawler()
siteData = [
    ['O\'Reilly Media', 'http://oreilly.com', 'h1', 'section#product-description'],
    ['Reuters', 'http://reuters.com', 'h1', 'div.StandardArticleBody_body_1gnLA'],
    ['Brookings', 'http://www.brookings.edu', 'h1', 'div.post-body']
]
websites = []
urls = [
    'http://shop.oreiily.com/product/0636920028154.do',
    'http://www.reuters.com/article/us-usa-epa-pruitt-idUSKBN19W2D0',
    'https://www.brookings.edu/blog/techtank/2016/03/01/idea-to-retire-old-methods-of-policy-education/'
]
for row in siteData:
    websites.append(Website(row[0], row[1], row[2], row[3]))

crawler.parse(websites[0], urls[0])
crawler.parse(websites[1], urls[1])
crawler.parse(websites[2], urls[2])


from requests.adapters import BaseAdapter
from requests.compat import urlparse, unquote
from requests import Response, codes
import errno
import os
import stat
import locale
import io

from six import BytesIO

class FileAdapter(BaseAdapter):
    def __init__(self, set_content_length=True):
        super(FileAdapter, self).__init__()
        self._set_content_length = set_content_length

    def send(self, request, **kwargs):
        """ Wraps a file, described in request, in a Response object.

            :param request: The PreparedRequest` being "sent".
            :returns: a Response object containing the file
        """

        # Check that the method makes sense. Only support GET
        if request.method not in ("GET", "HEAD"):
            raise ValueError("Invalid request method %s" % request.method)

        # Parse the URL
        url_parts = urlparse(request.url)

        # Reject URLs with a hostname component
        if url_parts.netloc and url_parts.netloc != "localhost":
            raise ValueError("file: URLs with hostname components are not permitted")

        resp = Response()

        # Open the file, translate certain errors into HTTP responses
        # Use urllib's unquote to translate percent escapes into whatever
        # they actually need to be
        try:
            # Split the path on / (the URL directory separator) and decode any
            # % escapes in the parts
            path_parts = [unquote(p) for p in url_parts.path.split("/")]

            # Strip out the leading empty parts created from the leading /'s
            while path_parts and not path_parts[0]:
                path_parts.pop(0)

            # If os.sep is in any of the parts, someone fed us some shenanigans.
            # Treat is like a missing file.
            if any(os.sep in p for p in path_parts):
                raise IOError(errno.ENOENT, os.strerror(errno.ENOENT))

            # Look for a drive component. If one is present, store it separately
            # so that a directory separator can correctly be added to the real
            # path, and remove any empty path parts between the drive and the path.
            # Assume that a part ending with : or | (legacy) is a drive.
            if path_parts and (
                path_parts[0].endswith("|") or path_parts[0].endswith(":")
            ):
                path_drive = path_parts.pop(0)
                if path_drive.endswith("|"):
                    path_drive = path_drive[:-1] + ":"

                while path_parts and not path_parts[0]:
                    path_parts.pop(0)
            else:
                path_drive = ""

            # Try to put the path back together
            # Join the drive back in, and stick os.sep in front of the path to
            # make it absolute.
            path = path_drive + os.sep + os.path.join(*path_parts)

            # Check if the drive assumptions above were correct. If path_drive
            # is set, and os.path.splitdrive does not return a drive, it wasn't
            # reall a drive. Put the path together again treating path_drive
            # as a normal path component.
            if path_drive and not os.path.splitdrive(path):
                path = os.sep + os.path.join(path_drive, *path_parts)

            # Use io.open since we need to add a release_conn method, and
            # methods can't be added to file objects in python 2.
            resp.raw = io.open(path, "rb")
            resp.raw.release_conn = resp.raw.close
        except IOError as e:
            if e.errno == errno.EACCES:
                resp.status_code = codes.forbidden
            elif e.errno == errno.ENOENT:
                resp.status_code = codes.not_found
            else:
                resp.status_code = codes.bad_request

            # Wrap the error message in a file-like object
            # The error message will be localized, try to convert the string
            # representation of the exception into a byte stream
            resp_str = str(e).encode(locale.getpreferredencoding(False))
            resp.raw = BytesIO(resp_str)
            if self._set_content_length:
                resp.headers["Content-Length"] = len(resp_str)

            # Add release_conn to the BytesIO object
            resp.raw.release_conn = resp.raw.close
        else:
            resp.status_code = codes.ok
            resp.url = request.url

            # If it's a regular file, set the Content-Length
            resp_stat = os.fstat(resp.raw.fileno())
            if stat.S_ISREG(resp_stat.st_mode) and self._set_content_length:
                resp.headers["Content-Length"] = resp_stat.st_size

        return resp

    def close(self):
        pass


import telebot
import re
import pymongo
from datetime import datetime
from telebot import types
from bson.objectid import ObjectId
from config import *

bot = telebot.TeleBot(TOKEN)

db = pymongo.MongoClient('mongodb://localhost:27017/').kunyn_team

working_obj = {}
for player in db.players.find():
    working_obj[player['telegram_id']] = {
        'name': player['name']
    }

choose_game_msg = 'Тут останні твої ігри'
choose_player_msg = 'Вибери гравця'
choose_rest_player_msg = 'Є! Тобі залишилось оцініти ще їх:'
choose_score_msg = 'Тепер вибери оцінку або введи значення'

show_game_scores = 'Вибери гру, щоб побачити рейтинг гравців за неї'

CREATING_GAME = {
    'name': False,
    'date': False,
}

@bot.message_handler(commands=['start'])
def start_handler(message):
    bot.send_message(message.chat.id, 'Бот для статистики гравців футзальної команди *Кунин*. Тисни /join')

@bot.message_handler(commands=['help'])
def init_handler(message):
    bot.send_message(message.chat.id, 'Список доступних опцій:\n'
                                      '/join - приєднатися до команди\n'
                                      '/games - список 3-х останніх ігор\n'
                                      '/all_games - список всіх ігор\n'
                                      '/rating - рейтинг гравців за всі ігри\n'
                                      '/games_rating - список ігор, щоб подивитись рейтинг')

@bot.message_handler(commands=['join'])
def join_handler(message):
    from_user = message.from_user
    send_msg = 'Ви прийняті і можете оцінювати інших гравців'
    if_exist = db.players.find_one({'telegram_id': from_user.id}) is not None

    if if_exist:
        send_msg = 'Ви вже були додані до команди раніше'
    else:
        db.players.insert_one({
            'telegram_id': from_user.id,
            'name': from_user.first_name
        })

        working_obj[from_user.id] = {
            'name': from_user.first_name
        }

    keyboard = types.ReplyKeyboardMarkup()
    keyboard.row(types.KeyboardButton('/rating'), types.KeyboardButton('/help'))
    keyboard.row(types.KeyboardButton('/games'), types.KeyboardButton('/games_rating'))

    bot.send_message(message.chat.id, send_msg, reply_markup=keyboard)

@bot.message_handler(commands=['games', 'all_games', 'games_rating'])
def handler(message):
    msg = show_game_scores if message.text == '/games_rating' else choose_game_msg
    limit = 3 if message.text == '/games' else 0
    games = db.games.find({'date': {'$lt': datetime.now()}}).sort('date', pymongo.DESCENDING).limit(limit)

    keyboard = types.InlineKeyboardMarkup()
    for game in games:
        keyboard.row(types.InlineKeyboardButton(game['name'], callback_data=str(game['_id'])))

    bot.send_message(message.chat.id, msg, reply_markup=keyboard)

@bot.message_handler(commands=['add_game'])
def handler(message):
    CREATING_GAME['name'] = True
    bot.send_message(message.chat.id, 'Введи назву гри')

@bot.message_handler(func=lambda _: CREATING_GAME['name'])
def handler(message):
    game_name = message.text
    msg = 'Коли вона була?'
    is_valid = re.search(r"^(\w+('\w+)?)(\s\w+|-\d|\s\(\w+\))?(\s-\s)(\w+('\w+)?)(\s\w+|-\d|\s\(\w+\))?$", game_name) is not None

    if is_valid:
        CREATING_GAME['name'] = False
        is_exist = db.games.find_one({'name': game_name}) is not None

        if is_exist:
            msg = f'Гра {game_name} вже існує.\nПодивитись список /all_games\nДодати іншу /add_game'
        else:
            inserted_game = db.games.insert_one({
                'name': game_name,
                'scores': []
            })

            CREATING_GAME['date'] = True
            CREATING_GAME['id'] = inserted_game.inserted_id
    else:
        msg = 'Введи валідну назву гри.\nПриклад: Команда-1 - Команда-2'

    bot.send_message(message.chat.id, msg, parse_mode='html')

@bot.message_handler(func=lambda _: CREATING_GAME['date'])
def handler(message):
    target_game = {'_id': ObjectId(CREATING_GAME['id'])}
    game = db.games.find_one(target_game)
    msg = f'Гру *{game["name"]}* створено. Обирай її у списку /games'

    try:
        date = datetime.strptime(message.text, '%Y-%m-%d %H:%M')

        db.games.update_one(target_game, {'$set': {
            'date': date
        }})
        CREATING_GAME['date'] = False
        CREATING_GAME['id'] = None
    except ValueError:
        msg = 'Невірний формат! Приклад валідної дати: _2020-01-12 02:20_'

    bot.send_message(message.chat.id, msg, parse_mode='markdown')

def get_rating_msg(game_id=None):
    target_game = {'_id': game_id} if game_id is not None else {'date': {'$lt': datetime.now()}}

    games = db.games.find(target_game)

    rating = {tg_id: [] for tg_id in working_obj}

    for game in games:
        for s in game['scores']:
            rating[s['to']].append(s['score'])

    for tg_id, scores in rating.items():
        try:
            rating[tg_id] = sum(scores) / len(scores)
        except ZeroDivisionError:
            rating[tg_id] = 0

    sorted_players = {k: v for k, v in sorted(rating.items(), key=lambda item: item[1], reverse=True)}

    result_msg = ''
    for tg_id, score, n in zip(sorted_players, sorted_players.values(), range(len(sorted_players))):
        result_msg += f'{n + 1}. {working_obj[tg_id]["name"]}  {round(score, 2)}\n'

    return result_msg

def get_players_to_score(game, user_id):
    scores = game['scores']
    scores_by_current_user = filter(lambda score: score['by'] == user_id, scores)
    users_with_score = list(map(lambda s: s['to'], scores_by_current_user))
    users_with_score.append(user_id)

    all_users_ids = working_obj.keys()
    ids_to_score = set(all_users_ids) - set(users_with_score)

    return ids_to_score

def get_keyboard_with_players(players):
    keyboard = types.InlineKeyboardMarkup()
    for id in players:
        keyboard.row(types.InlineKeyboardButton(working_obj[id]['name'], callback_data=id))

    return keyboard

@bot.message_handler(commands=['rating'])
def handler(message):
    bot.send_message(message.chat.id, get_rating_msg())

@bot.callback_query_handler(func=lambda call: call.message.text == show_game_scores)
def handler(query):
    bot.send_message(query.message.chat.id, get_rating_msg(ObjectId(query.data)))

@bot.callback_query_handler(func=lambda call: call.message.text == choose_game_msg)
def handler(query):
    # When choose game
    game = db.games.find_one({'_id': ObjectId(query.data)})

    if not game:
        bot.send_message(query.message.chat.id, 'Спочатку виберу гру. Тисни /games')
        return

    working_obj[query.from_user.id]['game_id'] = ObjectId(query.data)

    players_to_score = get_players_to_score(game, query.from_user.id)

    if len(players_to_score) > 0:
        keyboard = get_keyboard_with_players(players_to_score)

        bot.send_message(query.message.chat.id, choose_player_msg, reply_markup=keyboard)
    else:
        bot.send_message(query.message.chat.id, f'За гру *{game["name"]}* ти вже поставив оцінки всім гравцям',
                         parse_mode='markdown')

@bot.callback_query_handler(func=lambda call: call.message.text in [choose_player_msg, choose_rest_player_msg])
def handler(query):
    # When choose player for the game

    if not working_obj[query.from_user.id].get('game_id'):
        bot.send_message(query.message.chat.id, 'Ти не обрав гру! Тисни /games')
        return

    working_obj[query.from_user.id]['to_id'] = int(query.data)

    keyboard = types.InlineKeyboardMarkup()
    for r in range(2):
        keyboard.row(
            types.InlineKeyboardButton(r * 5 + 1, callback_data=r * 5 + 1),
            types.InlineKeyboardButton(r * 5 + 2, callback_data=r * 5 + 2),
            types.InlineKeyboardButton(r * 5 + 3, callback_data=r * 5 + 3),
            types.InlineKeyboardButton(r * 5 + 4, callback_data=r * 5 + 4),
            types.InlineKeyboardButton(r * 5 + 5, callback_data=r * 5 + 5),
        )

    bot.send_message(query.message.chat.id, choose_score_msg, reply_markup=keyboard)

def set_score(score, from_id, chat_id):
    if not working_obj[from_id].get('game_id'):
        bot.send_message(chat_id, 'Ти не обрав гру! Тисни /games')
        return

    to_id = working_obj[from_id].get('to_id')
    if not to_id:
        bot.send_message(chat_id, 'Ти не обрав гравця, для якого хочеш поставити оцінку!')
        return

    if score < 1 or score > 10:
        bot.send_message(chat_id, 'Оцінка може бути в діапазоні *[1, 10]*', parse_mode='markdown')
        return

    target_game = {'_id': working_obj[from_id]['game_id']}

    game = db.games.find_one(target_game)

    if any(map(lambda s: s['by'] == from_id and s['to'] == to_id, game['scores'])):
        bot.send_message(chat_id, f'Ти вже ставив оцінку грацю *{working_obj[to_id]["name"]}* за гру *{game["name"]}*',
                         parse_mode='markdown')
        return

    new_score = {
        'by': from_id,
        'score': score,
        'to': to_id
    }

    db.games.update_one(target_game, {'$push': {'scores': new_score}})

    game['scores'].append(new_score)

    rest_players = get_players_to_score(game, from_id)
    if len(rest_players) > 0:
        keyboard = get_keyboard_with_players(rest_players)

        bot.send_message(chat_id, choose_rest_player_msg, reply_markup=keyboard)
    else:
        bot.send_message(chat_id, f'Круто! За гру *{game["name"]}* ти вже поставив оцінки всім гравцям',
                         parse_mode='markdown')

@bot.callback_query_handler(func=lambda call: call.message.text == choose_score_msg)
def score_handler(query):
    # When choose score for player
    set_score(int(query.data), query.from_user.id, query.message.chat.id)

@bot.message_handler(func=lambda _: True)
def handler(message):
    try:
        score = float(message.text)
        set_score(score, message.from_user.id, message.chat.id)
    except ValueError:
        msg = "Невірний формат оцінки! Можливо спробуй через крапку.\nПриклади: '7', '8.5', 6.75"

        if not working_obj[message.from_user.id].get('game_id'):
            msg = 'Ти не обрав гру! Тисни /games'
        elif not working_obj[message.from_user.id].get('to_id'):
            msg = 'Ти не обрав гравця, для якого хочеш поставити оцінку!'

        bot.send_message(message.chat.id, msg)

if __name__ == '__main__':
    bot.polling(none_stop=True)


#
# @lc app=leetcode id=324 lang=python3
#
# [324] Wiggle Sort II
#
# https://leetcode.com/problems/wiggle-sort-ii/description/
#
# algorithms
# Medium (30.59%)
# Likes:    1341
# Dislikes: 654
# Total Accepted:    96.8K
# Total Submissions: 314.6K
# Testcase Example:  '[1,5,1,1,6,4]'
#
# Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2]
# < nums[3]....
#
# You may assume the input array always has a valid answer.
#
#
# Example 1:
#
#
# Input: nums = [1,5,1,1,6,4]
# Output: [1,6,1,5,1,4]
# Explanation: [1,4,1,5,1,6] is also accepted.
#
#
# Example 2:
#
#
# Input: nums = [1,3,2,2,3,1]
# Output: [2,3,1,3,1,2]
#
#
#
# Constraints:
#
#
# 1 <= nums.length <= 5 * 10^4
# 0 <= nums[i] <= 5000
# It is guaranteed that there will be an answer for the given input nums.
#
#
#
# Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space?
#

# @lc code=start
class Solution:
    def wiggleSort(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        nums.sort()
        res = []
        n = len(nums)
        flag = 0
        smaller = (n - 1) // 2
        larger = n - 1

        for _ in range(n):
            if flag == 0:
                res.append(nums[smaller])
                smaller -= 1
            else:
                res.append(nums[larger])
                larger -= 1

            flag = 1 - flag

        for i in range(n):
            nums[i] = res[i]
# @lc code=end


#本范例会用list、if及wheil技巧，以传入list及目标参数，找出list中，最接近目标参数的值
def fun1(list,ss) :
    max=len(list)
    i=1
    rult=ss
    while i<max:
        if list[i]>ss:
            print('%s %d'%(list[i],rult)) #print多参数
            if list[i] >rult or list[i]>ss:
               if rult>ss and rult<list[i]:
                    rult=rult
               else :
                    rult=list[i]
            i+=1
        else:
            i+=1
    return rult
litAA=[0,5,2,4,6,7,8,10]
AA=str(fun1(litAA,3))
print('找出list中，最接近目标参数的值:'+AA)


import os
import glob
import subprocess
import pandas as pd
from PIL import Image
import datetime

datetime.timedelta.min
def get_date_taken(path):
    return Image.open(path)._getexif()[36867]

#enter in the directory of your images in the line below
os.chdir('D:/mgickdemo/images')
cwd = os.getcwd()
#unfortunately you have to use jpg for the exif data to come through. yes, this is dumb.
files = glob.glob('*.jpg')

for i in range(len(files)):
    files[i] = files[i].split(".", 1)[0]

#If you're on a nix based system this needs to be changed from 'magick' to 'convert'
str1 = "magick "
str2 = ".jpg -crop 1728x1152 +repage "
str3 = "_%d.jpg"

for i in range(len(files)):
    tfiles = str1 + files[i] + str2 + files[i] + str3
    subprocess.run(tfiles, shell=True)

subfiles = glob.glob('*_[0-9].jpg')
subfiles = sorted(subfiles)
str4 = " -fuzz 15% -fill black +opaque \"rgb(210,210,20)\" -fuzz 15% -fill white -opaque \"rgb(210,210,20)\" -print \"%[fx:w*h*mean]\" "
#the above line probably needs to be adjusted to capture an appropriate 'green'. Ive been doing this by using the colour picker in photoshop to get RGB
#colourspace values for just one image of the set. both instances of the rgb(x,x,x) need to be changed

      #" -fuzz 11% -fill black +opaque \"rgb(162,159,10)\" -fuzz 11% -fill white -opaque \"rgb(162,159,10)\" -print \"%[fx:w*h*mean]\" "

tl = ["t"] * len(subfiles)
namestamps = ["t"] * len(subfiles)
potnumber = ["t"] * len(subfiles)

col_names = ['Timestamp', 'Pixels']
my_df = pd.DataFrame(columns = col_names)
my_df

#get the first time to subtract from subsequent ones using time delta

for i in range(len(subfiles)):
    tsfiles = str1 + subfiles[i] + str4 + "res" + subfiles[i]
    print(tsfiles)
    tl[i] = subprocess.run(tsfiles, shell=True, capture_output=True).stdout
    tl[i] = tl[i].decode('utf-8')
    namestamps[i] = get_date_taken(subfiles[i])
    temp = get_date_taken(subfiles[i])
    potnumber[i] = subfiles[i].split("_")[2].split(".")[0]

out = pd.DataFrame(list(zip(tl, namestamps, potnumber)))
out.to_csv("out.csv")
print(tl)
print(namestamps)
print(potnumber)
print(out)


#!/usr/bin/python3

import numpy as np
import pickle
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
from mpl_toolkits.mplot3d import axes3d

# defining the class for later 3D arrow plots
class Arrow3D(FancyArrowPatch):
    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
        FancyArrowPatch.draw(self, renderer)

def plot_energies():
    infile = open('Data/energy_plot_values.pkl', 'r+b')
    energy_plot_values = pickle.load(infile)
    infile.close()
    dt = energy_plot_values[0]
    vmax = energy_plot_values[1]
    grid_size = energy_plot_values[2]
    thermostat = energy_plot_values[3]
    steps = energy_plot_values[4]

    infile = open('Data/E_kin.pkl', 'r+b')
    E_kin = pickle.load(infile)
    infile.close()

    infile = open('Data/E_pot.pkl', 'r+b')
    E_pot = pickle.load(infile)
    infile.close()

    infile = open('Data/E_tot.pkl', 'r+b')
    E_tot = pickle.load(infile)
    infile.close()

    t = np.arange(steps)
    fig2 = plt.figure()
    axe2 = fig2.add_subplot(111)
    axe2.set_ylabel('E')
    axe2.set_xlabel('n$_{steps}$')
    axe2.set_title('Energies for v$_{max}$ = %5.1f, n$_{steps}$= %5.0f, $\Delta$t=%5.3f' %(vmax, steps, dt))
    axe2.plot(t, E_kin, label='$E_{kin}$')
    axe2.plot(t, E_pot, label='$E_{pot}$')
    axe2.plot(t, E_tot, label='$E_{tot}')
    axe2.legend(loc=0)
    fig2.savefig('Graphs/Energies_grid'+str(grid_size)+'_vmax'+str(vmax)+'_thermo'+str(thermostat)+'.png')

def plot_RDF():
    infile = open('Data/RDF_plot_values.pkl', 'r+b')
    RDF_plot_values = pickle.load(infile)
    infile.close()
    dt = RDF_plot_values[0]
    vmax = RDF_plot_values[1]
    grid_size = RDF_plot_values[2]
    thermostat = RDF_plot_values[3]
    steps = RDF_plot_values[4]

    infile = open('Data/RDF.pkl', 'r+b')
    RDF = np.array(pickle.load(infile), dtype=np.float_)
    infile.close()

    RDF /= np.sum(RDF)

    infile = open('Data/bins.pkl', 'r+b')
    bins = pickle.load(infile)
    infile.close()

    width = 0.7*(bins[1]-bins[0])
    left = bins[:-1]

    fig3 = plt.figure()
    axe3 = fig3.add_subplot(111)
    axe3.bar(left, RDF, width=width)
    axe3.set_title('RDF for v$_{max}$ = %5.1f, n$_{steps}$= %5.0f, $\Delta$t=%5.3f, thermostat: %r' %(vmax, steps, dt, thermostat))
    axe3.set_xlim(xmax = float(grid_size)/2)
    axe3.set_xlabel('Distance r')
    axe3.set_ylabel('Propability P')
    fig3.savefig('Graphs/RDF_grid'+str(grid_size)+'_vmax'+str(vmax)+'_thermo'+str(thermostat)+'.png')

# plot_positions plots all positions in a 3D plot and saves it as a png
def plot_positions():
  infile = open('Data/RDF_plot_values.pkl', 'r+b')
  RDF_plot_values = pickle.load(infile)
  infile.close()
  dt = RDF_plot_values[0]
  vmax = RDF_plot_values[1]
  grid_size = RDF_plot_values[2]
  thermostat = RDF_plot_values[3]
  steps = RDF_plot_values[4]

  for n in range(int(steps)):
    infile = open('Data/x'+str(n)+'.pkl', 'r+b')
    x = np.array(pickle.load(infile))
    infile.close()

    plt.ioff()
    fig = plt.figure()
    axe = fig.add_subplot(111, projection='3d')
    xs, ys, zs = np.zeros(len(x)), np.zeros(len(x)), np.zeros(len(x))
    for i,el in enumerate(x):
      xs[i] = el[0]
      ys[i] = el[1]
      zs[i] = el[2]
    axe.scatter(xs,ys,zs, s=500)
    '''
    for i, acc in enumerate(a):
      acc /= 10
      acc += x[i]
      axe.add_artist(Arrow3D(*zip(x[i],acc), mutation_scale=20, lw=1, arrowstyle="-|>", color="k"))
    '''
    axe.set_xlim(0, grid_size)
    axe.set_ylim(0, grid_size)
    axe.set_zlim(0, grid_size)
    axe.set_title('Step %5.0f' %n)
    fig.savefig('Movie/step'+str(n)+'.png')
    plt.close('all')


import csv
import os
import datetime
from datetime import date, datetime, timedelta
import matplotlib.pyplot as plt
from rich.console import Console

console = Console()

current_date = date.today().strftime("%d/%m/%Y")

# Generates unique ID for each new line in each csv file
def generate_id(file_name):
    with open(file_name, "r") as file:
        csvReader = csv.reader(file)
        lines = []
        for line in csvReader:
            if line != []:
                lines.append(line)

        if len(lines) == 1:
            id_number = f"0{str(1)}"
            return id_number
        else:
            last_added = lines[-1]
            id_number = str(int(last_added[0]) + 1)
            if len(id_number) < 2:
                id_number = f"0{str(id_number)}"

    # Getting rid of blank lines
    f = open(file_name, "w+")
    f.truncate()
    f.close()
    with open(file_name, "w", newline="") as newfile:
        write = csv.writer(newfile)
        write.writerows(lines)

    return id_number

# Returns total available stock of a product in inventory
def get_total_stock(product):
    with open("data/inventory.csv", "r") as file:
        total_count = 0
        for line in file.readlines():
            if product in line:
                product_line = line.split(",")
                quantity = int(product_line[5])
                total_count += quantity
    return total_count

# Adds new product to inventory file
def buy_product(name, price, exp_date, quantity):
    id = generate_id("data/inventory.csv")
    new_product = [id, name, current_date, price, exp_date, quantity]
    with open("data/inventory.csv", "a", newline="") as file:
        writer = csv.writer(file)
        writer.writerow(new_product)
        console.print(f"{quantity} pieces of {name} are added to the inventory.", style="#96fdca")

# Updates sold.csv and expired.csv files
def update_csv_file(product, sold_quantity, sell_price, sell_date, file_name):
    id = generate_id(file_name)
    product = {
        "id": id,
        "product_name": product["product_name"],
        "buy_id": product["id"],
        "buy_price": product["buy_price"],
        "buy_date": product["buy_date"],
        "exp_date": product["exp_date"],
        "stock_quantity": product["quantity"],
        "sell_date": sell_date,
        "sell_price": sell_price,
        "sold_quantity": sold_quantity
    }
    with open(file_name, "a+", newline="") as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=[
                                "id","product_name","buy_id","buy_price","buy_date",
                                "exp_date","stock_quantity","sell_date",
                                "sell_price","sold_quantity"])
        writer.writerow(product)

# Updates inventory.csv file
def update_inventory_file(inventory_dict):
    csv_header = inventory_dict[0].keys()
    updated_csv_file = "data/new_inventory.csv"
    with open(updated_csv_file, "w") as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=csv_header)
        writer.writeheader()
        for product in inventory_dict[1:]:
            writer.writerow(product)
    old_csv_file = "data/inventory.csv"
    if (os.path.exists(old_csv_file) and os.path.isfile(old_csv_file)):
        os.remove(old_csv_file)
        os.rename(updated_csv_file, old_csv_file)

# When a product is sold, this function checks if there is enough stock is available for selling
# by checking quantities and expiration dates.
# It automatically removes sold and/or expired stock.
def check_and_update_stock(product_name, sold_quantity, sell_price):
    products_in_stock = []
    with open("data/inventory.csv", "r") as csvfile:
        readCSV = csv.reader(csvfile,delimiter=",")

        for row in readCSV:
            product = dict(id=row[0], product_name=row[1], buy_date=row[2], buy_price=row[3], exp_date=row[4], quantity=row[5])
            products_in_stock.append(product)

        updated_stock = 0
        for product in products_in_stock[1:]:

            if product["product_name"] == product_name:
                exp = datetime.strptime(product["exp_date"], "%d/%m/%Y")
                cur = datetime.strptime(current_date, "%d/%m/%Y")

                if cur < exp:
                    stock = int(product["quantity"])

                    if stock >= sold_quantity and cur < exp:
                        stock = stock + updated_stock
                        stock = stock - sold_quantity
                        product["quantity"] = str(stock)
                        update_csv_file(product, sold_quantity, sell_price, current_date, "data/sold.csv")
                        if stock <= 0: products_in_stock.remove(product)
                        console.print(f"{sold_quantity} pieces of {product_name} are removed from inventory.", style="#FBDBDF")
                        return products_in_stock
                    elif stock < sold_quantity and cur < exp:
                        stock = stock + updated_stock
                        updated_stock = stock - sold_quantity
                        sold_quantity = 0
                        product["quantity"] = str(updated_stock)
                        if updated_stock <= 0: products_in_stock.remove(product)

                elif cur >= exp and int(product["quantity"]) < get_total_stock(product["product_name"]):
                    products_in_stock.remove(product)
                    update_csv_file(product, 0, 0, "--", "data/expired.csv")
                    continue
                else:
                    console.print(f"Unfortunately your {product_name} stock is expired ðŸ¤", style="#fd9796")
                    sold_quantity = 0
                    sell_price = 0
                    sell_date = "--"
                    products_in_stock.remove(product)
                    update_csv_file(product, sold_quantity, sell_price, sell_date, "data/expired.csv")
                    return products_in_stock

# Removes products from inventory.
def sell_product(sold_product_name, sold_quantity, sell_price):
    total_stock = get_total_stock(sold_product_name)

    if total_stock >= sold_quantity:
        update_inventory_file(check_and_update_stock(sold_product_name, sold_quantity, sell_price))

    elif total_stock > 0:
        return console.print(f"You do not have enough stock, you can sell a maximum of {total_stock} ðŸ˜…", style="#fdca96")
    else:
        return console.print(f"You do not have any {sold_product_name} in stock ðŸ˜Ÿ", style="#fd9796")


import yaml
from airflow.models import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.operators.bash_operator import BashOperator

def run(script):
    execFile('/root/airflow/runtime/{}'.format(script))

def create_python_task(task, dag):
    if 'executor_config' in task:
        t = PythonOperator(task, python_callable=run, op_args=[task['script']],dag=dag,
        executor_config={'KubernetesExecutor': task['executor_config']})
    else:
        t = PythonOperator(task, python_callable=run, op_args=[task['script']],dag=dag)

def create_bash_task(task, dag):
    if 'executor_config' in task:
        t = BashOperator(task, bash_command=task['bash_command'],dag=dag,
        executor_config={'KubernetesExecutor': task['executor_config']})
    else:
        t = BashOperator(task, bash_command=task['bash_command'],dag=dag)

def parse(stream):
    content = yaml.load(stream)
    args = {'owner': content['owner'], 'start_date': content['start_date']}
    dag_id = content['dag_id']
    dag = DAG(dag_id, schedule_interval=content['schedule_interval'], default_args = args)
    tasks = content['tasks']
    t = {}
    operator_map = {"python": create_python_task, "bash": create_bash_task}
    for task in tasks:
        t[task] = operator_map[task['operator']](task, dag)
        if 'upstream' in task:
            t[task].set_upstream(t[task['upstream']])
    globals()[dag_id] = dag

if __name__ == '__main__':
    from sys import argv
    input_file = argv[1]
    with open(input_file, 'r') as fin:
        parse(fin)


import matplotlib.pyplot as plt

from random_walk import RandomWalk

"""make a random walk and plot points as long as the program is active"""
while True:
    rw = RandomWalk()
    rw.fill_walk()

    """set size of plot window"""
    plt.figure(figsize=(10, 6))
    point_numbers = list(range(rw.num_points))
    plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolors='none', s=1)

    """highlight start and end points"""
    plt.scatter(0, 0, c='purple', edgecolors='none', s=100)
    plt.scatter(rw.x_values[-1], rw.y_values[-1], c='yellow', edgecolors='none', s=100)

    """remove axes"""
    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)

    plt.show()

    keep_running = input("Would you like to make another walk? y/n: ")
    if keep_running == 'n':
        break


# The name that the server expects to be referred to by.
chocolate_server_name = "ca.theobroma.info"

# Where is a form located through which payments can be submitted
# if required by policy? (note: this address should expect to be
# called followed by a slash and then the 64 hex digit session ID)
payment_uri = "https://ca.theobroma.info/payment.py"

# Where are on-line error messages about failures located?
error_uri = "https://ca.theobroma.info/failures/"

# The shortest length in bits of an acceptable RSA modulus.
min_keysize = 2048

# The number of bits of hashcash that a client must provide with
# a new request.
difficulty = 23

# The number of seconds that the server asks the client to wait, at
# a time, when a request is still being processed.
polldelay = 4

# The maximum number of subject names in a request.
max_names = 20

# The maximum size in bytes of a CSR.
max_csr_size = 20480

# The expiry times of sessions, challenges, and hashcash, in seconds.
maximum_session_age = 100
maximum_challenge_age = 600
hashcash_expiry = 60*60

# Extra names that the CA refuses to issue for, apart from those in
# the blacklist table in the database.
extra_name_blacklist = ["eff.org", "www.eff.org"]

# Name of file containing cert chain
cert_chain_file = "demoCA/cacert.pem"
debug = True


#server
import os
import tkinter as tk
import sqlite3
import random
from tkinter import ttk
from tkinter import messagebox as mbox
import PIL
from PIL import Image
from tkinter import *
from PIL import Image, ImageTk
from PIL import ImageGrab
import socket
#from gtts import gTTS
#import pyttsx3
from functools import partial
from datetime import datetime
from datetime import date
import time
cu = datetime.now()

def start():

     def end(a):
          a.destroy()

     def request():
          lr = Label(root1, text="Client requested for chatting", fg="maroon", bg="peachpuff", font=("Lucida console", 15))
          lr.place(x=120,y=200)

     def receive(a):
          host='localhost'
          port=8500
          s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
          s.bind((host,port))
          s.listen(1)
          c,addr=s.accept()
          mess1=c.recv(1024)
          mess1=mess1.decode()
          e0.insert(0,mess1)
          c.close()

     def send(a):
          host='localhost'
          port=9000
          s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
          s.connect((host,port))
          mess1=e1.get()
          s.send(mess1.encode())
          e1.delete(0,END)
          e0.delete(0,END)
          s.close()

          receive(a)

     def undo(a):
          e1.delete(0,END)

     root1 = Tk()
     root1.title("Chat Server")
     root1.configure(bg="peachpuff")
     root1.geometry('800x700')

     f = Frame(root1, bg="peachpuff", borderwidth=20, relief=SUNKEN)
     f.pack()

     l = Label(f, text="Server", fg="maroon", bg="white", font=("Lucida console", 30), width=60,height=2)
     l.pack()

     pic = PIL.Image.open("chat.jpg").convert("RGB")
     pic = pic.resize((100,100))
     pic1 = ImageTk.PhotoImage(pic)
     img_label1 = Label(root1, image=pic1)
     img_label1.image=pic1
     img_label1.place(x=330,y=240)
     img_label1.pack_propagate(0)

     ls = Label(root1, text="Gray button indicates waiting for client..", fg="maroon", bg="peachpuff", font=("Lucida console", 15))
     ls.place(x=170,y=200)

     l1 = Label(root1, text="From client:", fg="maroon", bg="peachpuff", font=("Lucida console", 15))
     l1.place(x=120,y=400)

     l2 = Label(root1, text="To client:", fg="maroon", bg="peachpuff", font=("Lucida console", 15))
     l2.place(x=120,y=500)

     e0 = Entry(root1, font=("Candara", 18), width=25)
     e0.place(x=300, y=400)

     e1 = Entry(root1, font=("Candara", 18), width=25)
     e1.place(x=300, y=500)

     b1 = Button(root1, text=">>", bg="green", fg="black",width=3, overrelief=SUNKEN, font=("Calibri",15),borderwidth=2,command=partial(send,root1))
     b1.place(x=650, y=500)

     b2 = Button(root1, text="Undo", bg="maroon", fg="black",width=5, overrelief=SUNKEN, font=("Calibri",15),borderwidth=2,command=partial(undo,root1))
     b2.place(x=480, y=570)

     b3 = Button(root1, text="Accept request from client", bg="green", fg="black",width=30, overrelief=SUNKEN, font=("Calibri",15),command=partial(receive,root1))
     b3.place(x=220,y=150)

     root1.mainloop()

start()


import discord
from discord.ext import commands

from cogs.errors import WegbotException

@commands.command(hidden=False, name="pin", brief="Pin a message.", rest_is_raw=True)
@commands.guild_only()
async def pin_that(self, ctx, message_id: int, *, addition=None):
    """ Pins the message with the given ID.

    You may also provide additional text that will appear at the front of the pinned message. """

    self.bot.logger.info(f'{ctx.author} request pin {message_id} in #{ctx.channel}')
    await ctx.trigger_typing()

    try:

        message = await ctx.channel.get_message(message_id)
        if message.pinned is True:
            raise WegbotException("That message is already pinned")

        embedded = discord.Embed(title=f"Message from {message.author}", description=addition)
        embedded.add_field(name="Original Message", value=message.content, inline=False)

        sent = await ctx.send(embed=embedded)
        await sent.pin()

    except WegbotException as ex:
        self.bot.logger.warning(f'wegbot exception while pinning {message_id}: {ex.message}')
        await ctx.send(f"{ex.message}, {ctx.author.mention}.")

    except discord.errors.NotFound:
        self.bot.logger.warning(f'attempted to pin message {message_id}, not found')
        await ctx.send(f"Couldn't find a message with that ID, {ctx.author.mention}.")

    except Exception as ex:
        self.bot.logger.exception(f'unable to pin message {message_id}: {ex}')
        await ctx.send(f"Couldn't pin that, {ctx.author.mention}. Have @ChaoticWeg check the logs.")


import string

import requests

from fudge import __version__
from fudge.utils import FudgeException

def get_repository_name(repo_url):
    repo_url = repo_url.rstrip('/')
    repo_name = repo_url.split('/')[-1].rstrip('.git')

    whitelist = set([char for char in string.ascii_letters + string.digits + '-_'])
    if not all(char in whitelist for char in repo_name):
        raise FudgeException('invalid repository name')

    return repo_name

def discover_refs(repo_url, service):
    url = '{}/info/refs'.format(repo_url)
    headers = {
        'User-Agent': 'fudge/{}'.format(__version__),
    }
    params = {
        'service': service,
    }
    response = requests.get(url, headers=headers, params=params)
    if response.status_code not in (200, 304):
        raise FudgeException('repository {} does not exist'.format(repo_url))

    content_type = response.headers.get('Content-Type')
    if content_type != 'application/x-{}-advertisement'.format(service):
        raise FudgeException('invalid Content-Type: {}'.format(content_type))

    lines = iter(response.text.split('\n'))

    service_line = parse_pkt_line(next(lines))
    if service_line != '# service={}'.format(service):
        raise FudgeException('invalid service line')

    info = parse_pkt_line(next(lines))
    head, capabilities = info.split('\0')
    head_object_id = head.split()[0]
    capabilities = capabilities.split()

    refs = {}
    while True:
        ref_line = parse_pkt_line(next(lines))
        if len(ref_line) == 0:
            break

        object_id, ref = ref_line.split()
        refs[ref] = object_id

    return head_object_id

def upload_pack(repo_url):
    repo_url = repo_url.rstrip('/')
    service = 'git-upload-pack'

    head_object_id = discover_refs(repo_url, service)

    command = 'want {}'.format(head_object_id)
    request = pkt_line(command)
    request += pkt_line()
    request += pkt_line('done')

    url = '{}/{}'.format(repo_url, service)
    headers = {
        'Content-Type': 'application/x-{}-request'.format(service),
        'User-Agent': 'fudge/{}'.format(__version__)
    }
    response = requests.post(url, headers=headers, data=request)
    if response.status_code not in (200, 304):
        raise FudgeException('repository {} does not exist'.format(repo_url))

    content_type = response.headers.get('Content-Type')
    if content_type != 'application/x-{}-result'.format(service):
        raise FudgeException('invalid response Content-Type: {}'.format(content_type))

    lines = iter(response.content.split(b'\n', 1))
    status = parse_pkt_line(next(lines))
    if status != b'NAK':
        raise FudgeException('could not retrieve the requested pack file')

    pack = next(lines)

    return pack, head_object_id

def pkt_line(command=None):
    if not command:
        return '0000'

    length = '{:04x}'.format(len(command) + 5)
    return '{}{}\n'.format(length, command)

def parse_pkt_line(line):
    """Parse a pkt-line."""
    length, data = line[:4], line[4:]
    length = int(length, 16)

    # Skip flush-pkts
    if length == 0 and len(data) > 0:
        length, data = data[:4], data[4:]
        length = int(length, 16)

    return data


# Implementation of Selenium WebDriver with Python using PyTest
import pytest
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import sys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from time import sleep
import random
from faker import Faker     #   for random data input
fake = Faker()
test_users = [
    "SELENIUM_TEST",
    "Lois_Lane",
    "Clark_Kent",
    "Jenny_Flex",
]
DELAY = 2

def signin(driver, username, password):
    try:
        driver.find_element(by=By.XPATH, value='//a[@href="'+ "/home/signin/" +'"]').click()
        driver.find_element(by=By.XPATH, value='//input[@name="'+ "username" +'"]').send_keys(username)
        driver.find_element(by=By.XPATH, value='//input[@name="'+ "password" +'"]').send_keys(password)
        driver.find_element(by=By.XPATH, value='//button[@type="'+ "submit" +'"]').submit()
    except Exception as e:
        print('\n\n\
            Feature: {}\n\
            Given conditions: {}\n\
            When: {}\n\
            Then: {}'\
            .format(
            'https://rateer.pythonanywhere.com/home/signin/',
            'Attempting to input',
            'Clicking submit',
            'Test Failed! Details:'+str(e)))

def find_friend(driver, username):
    # Find friend
    try:
        driver.find_element(by=By.XPATH, value='//a[@href="'+ "/friends/search/" +'"]').click()
        driver.find_element(by=By.XPATH, value='//input[@name="'+ "queryname" +'"]').send_keys(username)
        driver.find_element(by=By.XPATH, value='//button[@type="'+ "submit" +'"]').submit()
        try:
            ui_res = driver.find_element(by=By.XPATH, value='//b[contains(text(), \'' + username + '\')]').text
        except Exception as e:
            print('\n\n\
            Feature: {}\n\
            Given conditions: {}\n\
            When: {}'\
            .format(
            'https://rateer.pythonanywhere.com/friends/find/',
            'Attempting to Find Friends',
            'Clicking submit'))
            print('\
            Then: Test Failed -- User Not Found-- {}\n'\
            .format(
            str(e)))
    except Exception as e:
        print('\n\n\
            Feature: {}\n\
            Given conditions: {}\n\
            When: {}\n\
            Then: {}'\
            .format(
            'https://rateer.pythonanywhere.com/friends/find/',
            'Attempting to input data',
            'Clicking submit',
            'Test Failed! Details:' + str(e)))

def view_profile(driver, username):
    try:
        msg = fake.sentence()
        element = driver.find_element(by=By.XPATH, value='//a[@href="'+ "/friends/" + username +'/"]')
        driver.execute_script("arguments[0].click();", element)
    except Exception as e:
        print('\n\n\
            Feature: {}\n\
            Given conditions: {}\n\
            When: {}\n\
            Then: {}'\
            .format(
            'https://rateer.pythonanywhere.com/friends/' + username + '/',
            'Attempting to find friend',
            'Clicking submit',
            'Test Failed! Details:' + str(e)))

def rate(driver, username, rating):
    try:
        element = driver.find_element(by=By.XPATH, value='//a[@href="'+ "/friends/rate/" + username + '/' + str(rating) + '/"]')
        driver.execute_script("arguments[0].click();", element)

        print('\n\n\
            Feature: {}\n\
            Given conditions: {}\n\
            When: {}\n\
            Then: Test Passed\n'\
            .format(
            '/friends/rate/' + username + '/' + str(rating) + '/',
            'Attempting to rate friend',
            'Clicking submit',))

    except Exception as e:
        print('\n\n\
            Feature: {}\n\
            Given conditions: {}\n\
            When: {}\n\
            Then: {}'\
            .format(
            '/friends/rate/' + username + '/' + str(rating) + '/',
            'Attempting to rate friend',
            'Clicking submit',
            'Test Failed! Details:' + str(e)))

if __name__ == '__main__':
    try:
        driver = webdriver.Chrome(ChromeDriverManager().install())
        driver.get('https://rateer.pythonanywhere.com/')
        driver.maximize_window()
    except Exception as e:
        print(str(e))
        exit(1)

    print("Starting test [Rate]")
    signin(driver, test_users[0], test_users[0])
    find_friend(driver, "Jenny_Flex")
    view_profile(driver, "Jenny_Flex")
    rate(driver, "Jenny_Flex", 4)
    print("Finished test [Rate]")
    sleep(DELAY)


import argparse
import subprocess
import os

# Create argument parser
parser = argparse.ArgumentParser(description='Create and build base UFS case')
parser.add_argument("--project", default=None, help='Project to charge', required=True)
parser.add_argument("--tag", default=None, help='Model tag', required=True)
parser.add_argument("--dates", default=None, nargs="+", help='List of start dates', required=True)
parser.add_argument("--compset", default="UFS_S2S", help='Model compset')
parser.add_argument("--res", default="C384_t025", help='Model resolution')
parser.add_argument("--driver", default="nuopc", help='Model driver')
parser.add_argument("--options", default='--run-unsupported', help='Other options')

# Get case variables
args = parser.parse_args()
tag = args.tag
dates = args.dates
compset = args.compset
res = args.res
driver = args.driver
project = args.project
options = args.options

# Fixed values
home=os.environ.get("HOME")
wallclock = "00:30:00"
rlen="1"

# Create list of cases
caselist={init:"ufs.s2s."+res+"."+init+"."+tag for init in dates}

# Parse initial dates to create reference dates
reflist={init:init[0:4]+"-"+init[4:6]+"-"+init[6:8] for init in dates}
print(reflist)

for init in dates:

# Go to cime/scripts directory in UFSCOMP
   os.chdir(home+"/UFSCOMP."+tag+"/cime/scripts")

# Clone the base build into  new cases
   options = '--keepexe'
   rc = subprocess.run(["./create_clone",
                        "--case", caselist[init],
                        "--clone", "build_base",
                        options])
   os.chdir(home+"/UFSCOMP."+tag+"/cime/scripts/"+caselist[init])
   rc = subprocess.run(["./case.setup"])

# Define xmlchanges
   xmlchanges = ["RUN_REFDATE="+reflist[init],
                 "RUN_STARTDATE="+reflist[init],
                 "JOB_WALLCLOCK_TIME="+wallclock,
                 "DOUT_S=FALSE",
                 "STOP_OPTION=nhours",
                 "STOP_N="+rlen]
   rc = [subprocess.run([os.getcwd()+"/xmlchange", xmlchange]) for xmlchange in xmlchanges]

# Set path to case ICs
   with open(os.getcwd()+"/env_mach_specific.xml", 'r') as f:
     filedata = f.read()
   filedata = filedata.replace("20120101",init)

   with open(os.getcwd()+"/env_mach_specific.xml", 'w') as f:
     f.write(filedata)

# Set cice IC
   with open(os.getcwd()+"/user_nl_cice", "a") as f:
     f.write("ice_ic = \"$ENV{UGCSINPUTPATH}/cice5_model.res_"+init+"00.nc\"\n")

# Set output options
   with open(os.getcwd()+"/user_nl_fv3gfs", "a") as f:
     f.write("nfhout = 6\n")
     f.write("nfhmax_hf = 0\n")
     f.write("nfhout_hf = 0\n")
     f.write("fhzero = 6.0\n")
     f.write("fdiag = 6.0\n")
     f.write("fhout = 6.0\n")

# Submit run
   #rc = subprocess.run([os.getcwd()+"/case.submit"])


"""	Author:	 Daniel J. Sawtelle
***	Purpose: Bombard the given URL with randomized form return data
***
***	Source: https://www.youtube.com/watch?v=UtNYzv8gLbs
"""
import os
import random
import string
import json
import time
import requests

""" Function - Return a string object of a date formatted as specified
***		start:	First date possible to select
***		end:	Last date possible to select
***		format:	Structure of the date string being returned
***		prop:	Proportion of the distance to jump into the specified date range
***
*** 	Source: https://stackoverflow.com/questions/553303/generate-a-random-date-between-two-other-dates
"""
def str_time_prop(start, end, format, prop):
    #Retrieve the start and end dates as a time object
    stime = time.mktime(time.strptime(start, format))
    etime = time.mktime(time.strptime(end, format))

    #Evaluate the proportion of the date range to jump to
    ptime = stime + prop * (etime - stime)

    #Return a string object of the date tracked
    return time.strftime(format, time.localtime(ptime))

#Seed the random instance for generating data for the bombardment
random.seed = (os.urandom(1024))
#URL of the address to spam with data
url = 'AddressOfScammerGoesHere'

"""---------------- Main Function : Bombard the URL with randomized data ----------------"""
#Get an object of the list of names (first and last), streets, and companies to use for data spamming
fNames = json.loads(open('FirstNames.json').read())
lNames = json.loads(open('LastNames.json').read())
street = json.loads(open('StreetNames.json').read())
company = json.loads(open('CompanyNames.json').read())
country = json.loads(open('USVariations.json').read())
na = json.loads(open('NAVariations.json').read())

#Track the number of data bombardments done during this script call
dataCount = 1
while True:
	#Generate a random city/state pairing
	state = random.choice(json.loads(open('StateAbbreviations.json').read()))
	city = random.choice(json.loads(open('StateCities\\'+ state + 'Cities.json').read()))

	#Person Information
	PName = random.choice(fNames) + ' ' + random.choice(lNames)
	PAppartmentNumber = str(random.randint(1, 999))
	if random.choice([True, False]):
		PAppartmentNumber =  random.choice(na)
	PAddress = str(random.randint(1, 10000)) + ' ' + random.choice(street)
	PCity = city
	PState = state
	PZip = ''.join(random.choice(string.digits) for i in range(5))
	PCountry = random.choice(country)
	PPhoneNumber = '(' + ''.join(random.choice(string.digits) for i in range(3)) + ') ' + ''.join(random.choice(string.digits) for i in range(3)) + '-' + ''.join(random.choice(string.digits) for i in range(4))

	#Employer Information
	EName = random.choice(company)
	EEIN = ''.join(random.choice(string.digits) for i in range(2))
	if random.choice([True, False]):
		EEIN = ''.join(random.choice(string.ascii_letters)) + EEIN
	if random.choice([True, False]):
		EEIN = EEIN + '-'
	EEIN = EEIN + ''.join(random.choice(string.digits) for i in range(7))
	if random.choice([True, False]):
		EEIN = EEIN + ''.join(random.choice(string.digits))
	EAddress = ''.join(random.choice(string.digits) for i in range(4)) + ' ' + random.choice(street)
	ECity = city
	EState = state
	EZip = PZip[:3] + ''.join(random.choice(string.digits) for i in range(2))
	ECountry = random.choice(country)
	EPhoneNumber = '(' + ''.join(random.choice(string.digits) for i in range(3)) + ') ' + ''.join(random.choice(string.digits) for i in range(3)) + '-' + ''.join(random.choice(string.digits) for i in range(4))

	#Government/Financial Information
	EDOB = str_time_prop('01/01/1970', '12/31/2011', '%m/%d/%Y', random.random())
	ESSN = ''.join(random.choice(string.digits) for i in range(3)) + '-' + ''.join(random.choice(string.digits) for i in range(2)) + '-' +''.join(random.choice(string.digits) for i in range(4))
	EDLNumber = 'D' + ''.join(random.choice(string.digits) for i in range(8))
	EState = state
	EDLIssueDate = str_time_prop('01/01/1970', '12/31/1970', '%m/%d/%Y', random.random())[:-4] + str(int(EDOB[-4:]) + random.randrange(16, 35))
	EDLExpireDate = EDOB[:-4] + str(int(EDOB[-4:]) + 6)
	if state == 'AZ':
		EDLExpireDate = EDOB[:-4] + str(int(EDOB[-4:]) + 65)
	AGI = ''.join(str(random.randint(1, 99))) + ',' + ''.join(random.choice(string.digits) for i in range(3)) + '.' + ''.join(random.choice(string.digits) for i in range(2))
	if random.choice([True, False]):
		AGI = '$' + AGI
	if random.choice([True, False]):
		AGI = str(random.randint(0, 87986)) + '.' + ''.join(random.choice(string.digits) for i in range(2))
	if random.choice([True, True, False, False, False]):
		notApp = random.choice(na)
		EName = notApp
		EEIN = notApp
		EAddress = random.choice(na)
		ECity = notApp
		EState = notApp
		EZip = notApp
		ECountry = notApp
		AGI = random.choice([notApp, "0"])
		if random.choice([True, False, False, False]):
			EName = random.choice(["Self", "Self Employed", "self empl.", "self employed"])
			AGI = ''.join(str(random.randint(1, 4))) + ',' + ''.join(random.choice(string.digits) for i in range(3)) + '.' + ''.join(random.choice(string.digits) for i in range(2))
			if random.choice([True, False]):
				AGI = '$' + AGI
			if random.choice([True, False]):
				AGI = str(random.randint(0, 4999)) + '.' + ''.join(random.choice(string.digits) for i in range(2))

	#Send the data bombardment to the URL
	requests.post(url, allow_redirects=False, data={
		'textfield'  : PName,
		'textfield2' : PAppartmentNumber,
		'textfield3' : PAddress,
		'textfield4' : PCity,
		'textfield5' : PState,
		'textfield6' : PZip,
		'textfield7' : PCountry,
		'textfield8' : PPhoneNumber,
		'textfield9' : EName,
		'textfield18': EEIN,
		'textfield10': EAddress,
		'textfield11': ECity,
		'textfield12': EState,
		'textfield13': EZip,
		'textfield14': ECountry,
		'textfield15': EPhoneNumber,
		'textfield16': EDOB,
		'textfield17': ESSN,
		'textfield19': EDLNumber,
		'textfield20': EState,
		'textfield22': EDLIssueDate,
		'textfield23': EDLExpireDate,
		'textfield21': AGI,
		'Submit': 'UAccess - CARES Fund'
	})

	#Display general random bombardment information sent this generation
	print(str(dataCount) + ' Sending Data - ')
	print('    Name     : ' + PName)
	print('    Apartment: ' + PAppartmentNumber)
	print('    Address  : ' + PAddress)
	print('    City     : ' + PCity)
	print('    State    : ' + PState)
	print('    Zip Code : ' + PZip)
	print('    Country  : ' + PCountry)
	print('    Phone    : ' + PPhoneNumber)
	print('    Employer : ' + EName)
	print('    EIN      : ' + EEIN)
	print('    Address  : ' + EAddress)
	print('    City     : ' + ECity)
	print('    State    : ' + EState)
	print('    Zip      : ' + EZip)
	print('    Country  : ' + ECountry)
	print('    Phone    : ' + EPhoneNumber)
	print('    DOB      : ' + EDOB)
	print('    SSN      : ' + ESSN)
	print('    DL Number: ' + EDLNumber)
	print('    DL Issued: ' + EDLIssueDate)
	print('    DL Expire: ' + EDLExpireDate)
	print('    AGI      : ' + AGI)

	#Increment the Bombardment Count
	dataCount = dataCount + 1


import json

from odata import ODataHandler

def test_service_endpoint(service, endpoint="", urlparams={}, sap_client = '100', print_result=False):
    """Simple test function for odata service"""
    odatahandler = ODataHandler()
    slash = "" if endpoint == "" else "/"
    service_endpoint = "/%s%s%s" % (service, slash, endpoint)

    urlparams0 = { 'sap-client': sap_client }
    for p in urlparams:
        urlparams0[p] = urlparams[p]

    resp = odatahandler.http_get(service_endpoint, urlparams=urlparams0)
    #print('status: %d' % resp.status_code)
    jsonobj = json.loads(resp.content)
    if print_result:
        print(json.dumps(jsonobj,indent=2))
    return jsonobj;

if __name__ == '__main__':

    # some example calls:

    # get endpoints for robcoewm service
    test_service_endpoint("zewm_robco_srv");

    # get all open warehouse tasks
    test_service_endpoint("zewm_robco_srv", "OpenWarehouseTaskSet")

    # get all storage bins
    test_service_endpoint("zewm_robco_srv", "StorageBinSet", print_result = False)

    # get endpoint for the md_product_op_srv service
    test_service_endpoint("md_product_op_srv", print_result = False)

    # get information about products
    test_service_endpoint("md_product_op_srv", "C_Product",
                          urlparams = {
                              "$top" : 10,
                          }, print_result = False)

    test_service_endpoint("billofmaterialv2_srv","I_Material",
                          urlparams = {
                              "$top": 10,
                          }, print_result = True)


import torch
import os
import logging
import datetime
import argparse
import json

import pandas as pd
import numpy as np

from tqdm import tqdm

from generative_utils import load_model, load_context, process_outputs

def inference(model, tokenizer, question, context, no_ans_threshold, ans_threshold, max_length=4096, stride=128, device="cuda", max_answer_length=64):
    """ This function performs inference on a given question and context.
    """
    inputs = tokenizer.encode(context, question, max_length=max_length, truncation="only_first", stride=stride, padding=False, return_overflowing_tokens=True)
    answers = []

    for input in tqdm(inputs):
        input_ids = torch.tensor(input, device=device).unsqueeze(0)

        #generate answer
        with torch.no_grad():
            outputs = model.generate(input_ids,
                                        do_sample=False,
                                        num_beams=20,
                                        max_new_tokens=max_answer_length,
                                        num_return_sequences=10,
                                        eos_token_id=tokenizer.eos_token_id,
                                        pad_token_id=tokenizer.pad_token_id,
                                        return_dict_in_generate=True,
                                        output_scores=True
                                )
            #Process outputs
            selected_sentence, sequence_score, no_answer_logit = process_outputs(outputs, input_ids, tokenizer, model, device)
            selected_sentence = selected_sentence.squeeze(0)

            answers.append((selected_sentence[input_ids.shape[1]:], sequence_score, no_answer_logit))
            del outputs

    for i, (answer, score, no_answer_logit) in enumerate(answers):
        answers[i] = (tokenizer.decode(answer.squeeze(0), skip_special_tokens=True), score, no_answer_logit)
    answers = [answer for answer in answers if (answer[2][0]) < no_ans_threshold and answer[1][0] > ans_threshold]
    answers.sort(key=lambda x: x[1][0], reverse=True)
    if len(answers) == 0:
        return {"text": "No answer found", "logit_score": "0", "no_answer_score": "0"}
    return {"text": answers[0][0], "logit_score": answers[0][1][0], "no_answer_score": answers[0][2][0]}

if __name__ == "__main__":
    #Parse arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('--config', default='../configs/config.json')
    args = parser.parse_args()
    config = json.load(open(args.config, 'r'))

    #Gather all hyperparameters
    experiment_name = config['experiment_name']
    model_id = config['model_id']
    tokenizer_id = config['tokenizer_id']
    device = config['device']
    no_ans_threshold = config['no_ans_threshold']
    ans_threshold = config['ans_threshold']
    stride = config['stride']
    Qlora = config['Qlora']
    max_length = config['max_length']
    max_answer_length = config['max_answer_length']
    seed = config['seed']

    #Set seed and create output directory
    torch.manual_seed(seed)
    np.random.seed(seed)
    output_dir = "../outputs/" + experiment_name
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    else:
        for file in os.listdir(output_dir):
            os.remove(output_dir + "/" + file)

    #Set up logging
    log_file = os.path.join(output_dir, "inference_log_" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + ".log")
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    fh = logging.FileHandler(log_file)
    fh.setLevel(logging.INFO)
    logger.addHandler(fh)
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)

    logger.info("Starting evaluation for experiment: " + experiment_name)
    logger.info("Model: " + model_id)
    logger.info("Tokenizer: " + tokenizer_id)
    logger.info("Device: " + device)
    logger.info("No answer threshold: " + str(no_ans_threshold))
    logger.info("Answer threshold: " + str(ans_threshold))
    logger.info("Qlora: " + str(Qlora))
    logger.info("Stride: " + str(stride))
    logger.info("Max length: " + str(max_length))
    logger.info("Max answer length: " + str(max_answer_length))
    logger.info("Seed: " + str(seed))

    #Load contexts
    sinch_node_red = load_context("mmd/sinch_doc_node_red.mmd")
    sinch_webhook = load_context("mmd/sinch_doc_how_to_webhook.mmd")
    sinch_overview = load_context("mmd/sinch_doc_overview.mmd")
    nougat_context = load_context("mmd/nougat.mmd")

    #Load model and hyperparameters
    model, tokenizer = load_model(model_id, Qlora=Qlora,  device=device)

    no_ans_threshold = no_ans_threshold
    ans_threshold = ans_threshold
    max_length = max_length

    #Inference
    df = pd.DataFrame(columns=['question', 'answer', 'logit_score', 'no_answer_probability'])

    question = "What is Node RED ? "
    answer = inference(model, tokenizer, question, sinch_node_red, no_ans_threshold=no_ans_threshold, ans_threshold=ans_threshold, device=device, stride=stride, max_length=max_length, max_answer_length=max_answer_length)
    logger.info(question + " " + str(answer))
    df = pd.concat([df, pd.DataFrame([[question, answer["text"], answer["logit_score"], answer["no_answer_score"]]], columns=['question', 'answer', 'logit_score', 'no_answer_probability'])])

    """question = "In few words, What is Node RED ? "
    answer = inference(model, tokenizer, question, sinch_node_red,  no_ans_threshold=no_ans_threshold, ans_threshold=ans_threshold, device=device, stride=stride, max_length=max_length, max_answer_length=max_answer_length)
    logger.info(question + " " + str(answer))
    df = pd.concat([df, pd.DataFrame([[question, answer["text"], answer["logit_score"], answer["no_answer_score"]]], columns=['question', 'answer', 'logit_score', 'no_answer_probability'])])

    question = "What are the supported channels of Node RED ? "
    answer = inference(model, tokenizer, question, sinch_node_red,  no_ans_threshold=no_ans_threshold, ans_threshold=ans_threshold, device=device, stride=stride, max_length=max_length, max_answer_length=max_answer_length)
    logger.info(question + " " + str(answer))
    df = pd.concat([df, pd.DataFrame([[question, answer["text"], answer["logit_score"], answer["no_answer_score"]]], columns=['question', 'answer', 'logit_score', 'no_answer_probability'])])

    question = "In which cases can I use Node RED ? "
    answer = inference(model, tokenizer, question, sinch_node_red,  no_ans_threshold=no_ans_threshold, ans_threshold=ans_threshold, device=device, stride=stride, max_length=max_length, max_answer_length=max_answer_length)
    logger.info(question + " " + str(answer))
    df = pd.concat([df, pd.DataFrame([[question, answer["text"], answer["logit_score"], answer["no_answer_score"]]], columns=['question', 'answer', 'logit_score', 'no_answer_probability'])])

    question = "What are the differents nodes of Sinch Messaging ? "
    answer = inference(model, tokenizer, question, sinch_node_red,  no_ans_threshold=no_ans_threshold, ans_threshold=ans_threshold, device=device, stride=stride, max_length=max_length, max_answer_length=max_answer_length)
    logger.info(question + " " + str(answer))
    df = pd.concat([df, pd.DataFrame([[question, answer["text"], answer["logit_score"], answer["no_answer_score"]]], columns=['question', 'answer', 'logit_score', 'no_answer_probability'])])

    question = "When was Node RED released ? "
    answer = inference(model, tokenizer, question, sinch_node_red,  no_ans_threshold=no_ans_threshold, ans_threshold=ans_threshold, device=device, stride=stride, max_length=max_length, max_answer_length=max_answer_length)
    logger.info(question + " " + str(answer))
    df = pd.concat([df, pd.DataFrame([[question, answer["text"], answer["logit_score"], answer["no_answer_score"]]], columns=['question', 'answer', 'logit_score', 'no_answer_probability'])])

    question = "Give me the different steps to add a webhook to my app ? "
    answer = inference(model, tokenizer, question, sinch_webhook,  no_ans_threshold=no_ans_threshold, ans_threshold=ans_threshold, device=device, stride=stride, max_length=max_length, max_answer_length=max_answer_length)
    logger.info(question + " " + str(answer))
    df = pd.concat([df, pd.DataFrame([[question, answer["text"], answer["logit_score"], answer["no_answer_score"]]], columns=['question', 'answer', 'logit_score', 'no_answer_probability'])])

    question = "What is the Sinch Conversation API ?"
    answer = inference(model, tokenizer, question, sinch_overview,  no_ans_threshold=no_ans_threshold, ans_threshold=ans_threshold, device=device, stride=stride, max_length=max_length, max_answer_length=max_answer_length)
    logger.info(question + " " + str(answer))
    df = pd.concat([df, pd.DataFrame([[question, answer["text"], answer["logit_score"], answer["no_answer_score"]]], columns=['question', 'answer', 'logit_score', 'no_answer_probability'])])

    question = "Can I use the Sinch Conversation API with Viber Business ? "
    answer = inference(model, tokenizer, question, sinch_overview,  no_ans_threshold=no_ans_threshold, ans_threshold=ans_threshold, device=device, stride=stride, max_length=max_length, max_answer_length=max_answer_length)
    logger.info(question + " " + str(answer))
    df = pd.concat([df, pd.DataFrame([[question, answer["text"], answer["logit_score"], answer["no_answer_score"]]], columns=['question', 'answer', 'logit_score', 'no_answer_probability'])])

    question = "Can I use the Sinch Conversation API with Outlook ? "
    answer = inference(model, tokenizer, question, sinch_overview,  no_ans_threshold=no_ans_threshold, ans_threshold=ans_threshold, device=device, stride=stride, max_length=max_length, max_answer_length=max_answer_length)
    logger.info(question + " " + str(answer))
    df = pd.concat([df, pd.DataFrame([[question, answer["text"], answer["logit_score"], answer["no_answer_score"]]], columns=['question', 'answer', 'logit_score', 'no_answer_probability'])])

    question = "Where are the hosting locations for the Conversation API ? "
    answer = inference(model, tokenizer, question, sinch_overview,  no_ans_threshold=no_ans_threshold, ans_threshold=ans_threshold, device=device, stride=stride, max_length=max_length, max_answer_length=max_answer_length)
    logger.info(question + " " + str(answer))
    df = pd.concat([df, pd.DataFrame([[question, answer["text"], answer["logit_score"], answer["no_answer_score"]]], columns=['question', 'answer', 'logit_score', 'no_answer_probability'])])

    question = "What are the specific pricing details for using the Sinch Conversation API ? "
    answer = inference(model, tokenizer, question, sinch_overview,  no_ans_threshold=no_ans_threshold, ans_threshold=ans_threshold, device=device, stride=stride, max_length=max_length, max_answer_length=max_answer_length)
    logger.info(question + " " + str(answer))
    df = pd.concat([df, pd.DataFrame([[question, answer["text"], answer["logit_score"], answer["no_answer_score"]]], columns=['question', 'answer', 'logit_score', 'no_answer_probability'])])

    question = "How does the Sinch Conversation API handle multimedia content like images and videos ? "
    answer = inference(model, tokenizer, question, sinch_overview,  no_ans_threshold=no_ans_threshold, ans_threshold=ans_threshold, device=device, stride=stride, max_length=max_length, max_answer_length=max_answer_length)
    logger.info(question + " " + str(answer))
    df = pd.concat([df, pd.DataFrame([[question, answer["text"], answer["logit_score"], answer["no_answer_score"]]], columns=['question', 'answer', 'logit_score', 'no_answer_probability'])])
"""
    #Save results
    df = df.drop(['logit_score', 'no_answer_probability'], axis=1)
    latex_code = df.to_latex(index=False, column_format="|p{5cm}|p{10cm}|", float_format=(lambda x: "%.3f" % x))
    latex_code = latex_code.replace('\\toprule', '\hline')
    latex_code = latex_code.replace('\\bottomrule', '\hline')
    latex_code = latex_code.replace('\\\n', '\\ \hline\n')

    latex_file_name = "/generative_qa_mistral_dpo.tex"
    with open(output_dir + latex_file_name, 'w') as file:
        file.write(latex_code)


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def generateTrees(self, n: int) -> List[Optional[TreeNode]]:

        def recursion(start, end):
            subtrees = []
            for root in range(start, end + 1):
                for left in recursion(start, root - 1):
                    for right in recursion(root + 1, end):
                        node = TreeNode(root)
                        node.left = left
                        node.right = right
                        subtrees.append(node)
            return subtrees if subtrees else [None]

        return recursion(1, n)