#!/usr/bin/env python3
import argparse
import binascii
import datetime
import hashlib
import logging
import logging.handlers
import os
import sys
from base64 import b64encode
from dataclasses import dataclass
from typing import Mapping, Optional

import pkcs11
import requests
import yaml
from pkcs11 import Attribute, ObjectClass, KeyType, UserNotLoggedIn
from OpenSSL import crypto
from jose import jwk, jws, JWSError

_defaults = {'debug': False,
             'module': '/usr/lib/softhsm/libsofthsm2.so',
             'url': 'http://localhost:8000/',
             }

@dataclass
class P11Params(object):
    module: str
    pin: Optional[str]
    token_label: Optional[str]
    label: str
    id: int

# This global variable (sigh) will be filled with values after argument parsing.
# The P11Key class makes use of these values in the global variable (sigh) when
# the JOSE library instantiates them.
P11Key_params = P11Params(module='', pin=None, token_label=None, label='', id=None)

class P11Key(jwk.Key):

    def __init__(self, key, algorithm, p11: P11Params = P11Key_params):
        super().__init__(key, algorithm)
        #self._key = key
        self._algorithm = algorithm
        self._public_key = None
        self._private_key = None
        self._mechanism = None
        self.p11 = p11

        logger.debug(f'Initialising PKCS#11 module: {self.p11.module}')
        self.lib = pkcs11.lib(self.p11.module)
        for _slot in self.lib.get_slots():
            logger.debug(f'Slot: {_slot}')

        logger.debug(f'Looking for token {repr(self.p11.token_label)}')
        self.token = self.lib.get_token(token_label=self.p11.token_label)

        logger.debug(f'Loaded module {self.lib} (key {key}, alg {algorithm})')

    def _load_key(self, session) -> None:
        if self._public_key is not None and self._private_key is not None:
            return

        if self._private_key is None:
            self._load_key2(session, key_type=ObjectClass.PRIVATE_KEY,
                            cka_label=self.p11.label, cka_id=self.p11.id)

        if self._public_key is None:
            self._load_key2(session, key_type=ObjectClass.PUBLIC_KEY,
                            cka_label=self.p11.label, cka_id=self.p11.id)

    def _load_key2(self, session, key_type, cka_label: Optional[str] = None, cka_id: Optional[int] = None):
        #key = session.get_key(label=self.p11.label, key_type=pkcs11.ObjectClass.PRIVATE_KEY)
        attrs = {Attribute.KEY_TYPE: key_type,
                 #Attribute.LABEL: self.p11.label,
                 }
        if cka_label is not None:
            attrs[Attribute.LABEL] = cka_label
        if cka_id is not None:
            attrs[Attribute.ID] = cka_id
        logger.debug(f'Looking for key {attrs} in session {session}')
        # SoftHSM2 returns both private and public keys
        for this in session.get_objects(attrs):
            logger.debug(f'Object: {this}')
            if this.object_class == ObjectClass.PUBLIC_KEY:
                self._public_key = this
                p = this[Attribute.EC_POINT]
                logger.debug(f'Loaded EC_POINT {binascii.hexlify(p)}')
            elif this.object_class == ObjectClass.PRIVATE_KEY:
                self._private_key = this
            if this.key_type == KeyType.EC:
                # SoftHSM2 does not seem to support CKM_ECDSA_SHA256
                self._mechanism = pkcs11.Mechanism.ECDSA
                if this.object_class != ObjectClass.PUBLIC_KEY:
                    continue
            elif this.key_type == KeyType.RSA:
                self._mechanism = pkcs11.Mechanism.SHA256_RSA_PKCS_PSS

    def sign(self, msg: bytes) -> bytes:
        assert isinstance(self.token, pkcs11.Token)
        logger.info('Opening session with PIN')
        with self.token.open(user_pin=self.p11.pin) as session:
            logger.info(f'Session: {session}')
            self._load_key(session)

            if not self._private_key:
                raise RuntimeError('Could not load private key')

            logger.debug(f'Signing data: {msg}')
            if self._mechanism == pkcs11.Mechanism.ECDSA:
                msg = hashlib.sha256(msg).digest()
                logger.debug(f'SHA-256 hashed into new data: {binascii.hexlify(msg)}')
            logger.info(f'Signing using private key {self._private_key}')
            try:
                signature = self._private_key.sign(msg, mechanism=self._mechanism)
            except UserNotLoggedIn:
                logger.error("""

                Got UserNotLoggedIn from opensc. You need to add

                    app default {
                        framework pkcs15 {
                                pin_cache_ignore_user_consent = false;
                        }
                    }

                to /etc/opensc/opensc.conf, and not have a too old opensc (works with 0.20.0).
                """)
                return None
            logger.debug(f'Signature: {binascii.hexlify(signature)}')
        return signature

    def verify(self, msg: bytes, sig: bytes) -> bool:
        assert isinstance(self.token, pkcs11.Token)
        with self.token.open(user_pin=self.p11.pin) as session:
            self._load_key(session)

            if not self._public_key:
                raise RuntimeError('Could not load public key')

            logger.debug(f'Verifying signature, data: {msg}')
            logger.debug(f'Signature: {binascii.hexlify(sig)}')
            import pkcs11.util.ec
            logger.debug(f'Encoded signature: {binascii.hexlify(pkcs11.util.ec.encode_ecdsa_signature(sig))}')
            if self._mechanism == pkcs11.Mechanism.ECDSA:
                msg = hashlib.sha256(msg).digest()
                logger.debug(f'SHA-256 hashed into new data: {binascii.hexlify(msg)}')

            logger.debug(f'VERIFY msg {msg} SIG {sig} MECH {self._mechanism}')
            res = self._public_key.verify(msg, sig, mechanism=self._mechanism)
            logger.debug(f'Verify result: {res}')
            if not res:
                raise RuntimeError('Signature failed validation')
        return True

    def get_jwk_alg(self) -> str:
        with self.token.open(user_pin=self.p11.pin) as session:
            self._load_key(session)

            if not self._public_key:
                raise RuntimeError('Could not load public key')

            if self._public_key.key_type == KeyType.RSA:
                return 'RS256'
            elif self._public_key.key_type == KeyType.EC:
                return 'ES256'

def parse_args(defaults: Mapping):
    parser = argparse.ArgumentParser(description='ICI ACME pre-auth token generator',
                                     add_help=True,
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )

    # Positional arguments
    parser.add_argument('names', nargs='+',
                        metavar='FQDN',
                        help='Names to put in token',
    )

    # Required arguments
    parser.add_argument('--cert',
                        dest='cert',
                        type=str, required=True,
                        help='Certificate to sign token with',
    )
    parser.add_argument('--token_label',
                        dest='token',
                        type=str, required=True,
                        help='PKCS#11 token label where the key resides',
    )

    # Optional arguments
    parser.add_argument('--debug',
                        dest='debug',
                        action='store_true', default=defaults['debug'],
                        help='Enable debug operation',
    )
    parser.add_argument('--module',
                        dest='module',
                        type=str, default=defaults['module'],
                        help='PKCS#11 module',
    )
    parser.add_argument('--pin',
                        dest='pin',
                        type=str,
                        help='PKCS#11 user-pin to access key',
    )
    parser.add_argument('--url',
                        dest='url',
                        type=str, default=defaults['url'],
                        help='ACME server URL (to the directory endpoint)',
    )
    parser.add_argument('--label',
                        dest='cka_label',
                        type=str, default=None,
                        help='PKCS#11 CKA_LABEL of key to use to sign token',
    )
    parser.add_argument('--cka_id',
                        dest='cka_id',
                        type=int, default=None,
                        help='PKCS#11 CKA_ID of key to use to sign token',
    )
    parser.add_argument('--output_file',
                        dest='output_file',
                        type=str, default=None, metavar='YAMLFILE',
                        help='Write generated token to this file',
    )

    args = parser.parse_args()
    global P11Key_params
    P11Key_params.module = args.module
    P11Key_params.token_label = args.token
    P11Key_params.label = args.cka_label
    P11Key_params.id = args.cka_id
    P11Key_params.pin = args.pin

    return args

def main(args: argparse.Namespace, logger: logging.Logger):
    now = datetime.datetime.now(tz=datetime.timezone.utc)
    expire = now + datetime.timedelta(minutes=5)
    directory = get_acme_directory(args.url)

    logger.debug(f'Loading certificate from {args.cert}')
    with open(args.cert, 'rb') as fd:
        cert_pem = fd.read()

    certificate = crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem)
    logger.info(f'Including cert from file {args.cert}')
    logger.info(f'Requestor: {certificate.get_subject()} (serial {hex(certificate.get_serial_number())})')
    headers = {'x5c': [b64encode(crypto.dump_certificate(crypto.FILETYPE_ASN1, certificate)).decode('utf-8')],
               'url': directory['newAuthz'],
               }
    claims = {'names': args.names,
              'nonce': get_acme_nonce(directory),
              'aud': directory['newAuthz'],
              'iat': int(now.timestamp()),
              'exp': int(expire.timestamp()),
              'crit': ['exp'],
              }
    token = pkcs11_jws_sign(claims, args.cka_label, headers=headers)
    if not token:
        return False
    logger.debug(f'JWS: {token}')

    sig_verified = False

    try:
        # Verify token using PKCS#11. This step is not really necessary, but
        # the code seemed like it could be useful sometime somewhere so why not.
        verified = pkcs11_jws_verify(token)
        logger.debug(f'PKCS#11 verification result: {verified}')
        if verified:
            sig_verified = True
            logger.info('Signature validated by token using PKCS#11')
    except Exception:
        logger.exception('FAILED verifying signature using PKCS#11')

    # Verify the token by extracting the public key from the certificate, just like
    # the ICI ACME server this token will be passed to will do. This ensures the
    # certificate provided (in a file) matches the private key used (PKCS#11).
    pubkey_pem = crypto.dump_publickey(crypto.FILETYPE_PEM, certificate.get_pubkey())
    try:
        verified = jws.verify(token, pubkey_pem.decode('utf-8'), [jwk.ALGORITHMS.ES256, jwk.ALGORITHMS.RS256])
        logger.debug(f'Verification result: {verified}')
        if verified:
            sig_verified = True
            logger.info('Signature validated using software cryptography library')
    except Exception:
        logger.exception('FAILED verifying signature using cryptography')

    if not sig_verified:
        logger.error('The generated signature could not be validated')
        return False

    if args.output_file:
        # Write some extra info besides the token. The extra info should not be used
        # anywhere except by humans. All the extra info is already included in the
        # token, but then you have to parse the token to figure out the audience URL
        # for example.
        data = {'acme_url': args.url,
                'issue_ts': now,
                'expire_ts': expire,
                'token': token,
                'names': args.names,
                }
        with open(args.output_file, 'w') as fd:
            fd.write('---\n')
            yaml.safe_dump(data, fd)
        logger.info(f'Wrote ICI ACME token to file {args.output_file}')
    else:
        while token:
            print(token[:80])
            token = token[80:]
    return True

def get_acme_directory(url: str) -> dict:
    r = requests.get(url, json={})
    directory = r.json()
    if 'newNonce' not in directory:
        raise RuntimeError(f'No newNonce endpoint returned from ACME server at {url}')
    return r.json()

def get_acme_nonce(directory: Mapping) -> str:
    url = directory['newNonce']
    r = requests.head(url)
    nonce = r.headers.get('replay-nonce')
    if not nonce:
        raise RuntimeError(f'No nonce returned from newNonce endpoint at {url}')
    return nonce

def pkcs11_jws_sign(data, key=None, headers=None) -> str:
    """
    Perform JWS Sign with a key stored in an PKCS#11 token.

    This requires some trickery - temporary switch out the key class for the algorithm
    to P11Key before calling jws.sign. It is not possible to just register a new algorithm,
    say ECP11, because the algorithm is included in the JWT and the consumer of the JWT
    would expect ES256 (or similar) and not know how to handle ECP11.

    :return: A signed JWT
    """
    global P11Key_params
    _p11key = P11Key('', '', P11Key_params)
    _alg = _p11key.get_jwk_alg()

    orig_key = jwk.get_key(_alg)
    try:
        jwk.register_key(_alg, P11Key)
        res = jws.sign(data, key, algorithm=_alg, headers=headers)
    except:
        raise
    finally:
        jwk.register_key(_alg, orig_key)
    return res

def pkcs11_jws_verify(token: str) -> Optional[str]:
    """
    Perform JWS Sign with a key stored in an PKCS#11 token.

    This requires temporarily switching the key class for the algorithm in the token.
    See the documentation for pkcs11_jws_sign for more details.

    :return: The signed payload from the token, or None if verify is not supported
    """
    headers = jws.get_unverified_headers(token)
    _alg = headers['alg']

    # First, check if verify for this algorithm is supported by the token (current YubiKey can
    # sign with ECDSA, but not verify).
    # We have to do it in this hackish manner since the JOSE library will ignore any exceptions
    # from the verify method and just turn everything into an
    # JWSError('Signature verification failed.') exception.
    _p11key = P11Key('', _alg, P11Key_params)
    with _p11key.token.open(user_pin=_p11key.p11.pin) as session:
        _p11key._load_key(session)
        info = _p11key.token.slot.get_mechanism_info(_p11key._mechanism)
    logger.debug('Token mechanism info:\n{}'.format(info))
    if pkcs11.MechanismFlag.VERIFY not in info.flags:
        logger.info('Verify is not a supported operation for algorithm {} using the PKCS#11 token'.format(
            _p11key._algorithm))
        return None

    orig_key = jwk.get_key(_alg)
    try:
        # First check if verify is a supported operation using this al
        jwk.register_key(_alg, P11Key)
        res = jws.verify(token, '', algorithms=[jwk.ALGORITHMS.ES256, jwk.ALGORITHMS.RS256])
    except:
        raise
    finally:
        jwk.register_key(_alg, orig_key)
    return res

def _get_logger(args: argparse.Namespace, progname: str) -> logging.Logger:
    # This is the root log level
    level = logging.INFO
    if args.debug:
        level = logging.DEBUG
    logging.basicConfig(level=level, stream=sys.stderr,
                        format='%(asctime)s: %(name)s: %(levelname)s %(message)s')
    logger = logging.getLogger(progname)
    # If stderr is not a TTY, change the log level of the StreamHandler (stream = sys.stderr above) to WARNING
    if not sys.stderr.isatty() and not args.debug:
        for this_h in logging.getLogger('').handlers:
            this_h.setLevel(logging.WARNING)
    return logger

if __name__ == '__main__':
    try:
        # initialize various components
        progname = os.path.basename(sys.argv[0])
        args = parse_args(_defaults)
        logger = _get_logger(args, progname)

        res = main(args, logger)

        if res is True:
            sys.exit(0)
        if res is False:
            sys.exit(1)
        sys.exit(int(res))
    except KeyboardInterrupt:
        sys.exit(0)


from unified.core.auth import Auth
import requests
import json
from datetime import datetime, timezone

def get_access_token(context):
    """ Returns new access token """

    headers = context['headers']
    auth_info = {
        "client_id": headers["client_id"],
        "client_secret": headers["client_secret"],
        "token": headers["token"],
        "refresh_url": headers["refresh_url"],
    }
    token = Auth().get_oauth2_token(auth_info)

    return (json.loads(token))['access_token']

def rest(method, url, access_token, org_id, body=None, files=None):
    """ Send REST request and returns response  """

    headers = {
        "Accept": "*/*",
        "Content-Type": "application/json; charset=utf-8",
        "Authorization": f"Zoho-oauthtoken {access_token}"
    }

    if org_id:
        headers['orgId'] = org_id

    if files:
        del headers['Content-Type']
        response = requests.post(url, files=files, headers=headers)
        return response

    response = requests.request(method, url, headers=headers, json=body, files=files)

    return response

def epoch_to_format(epoch, format='%Y-%m-%dT%H:%M:%SZ'):
    """ Convert  epoch to given format """

    return datetime.fromtimestamp(int(epoch[:10]), tz=timezone.utc).strftime(format)

def get_url():
    """ Utility function for getting url """

    return "https://desk.zoho.in/api/v1/"


import re
import statistics
def read_words(fname):
    with open(fname) as f:
        content=f.readlines()
    words=[]
    for i in content:
        words.append(get_words_from_string(i))
    return words

def get_words_from_string(s):
    return (set(re.findall(r"\w+",s)))

def semordnilap(fname):
    a=read_words(fname)
    b = set()
    for i in a:
        for j in i:
            b.add(j)


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

"""Programmatic execution of notebooks."""

# pylint: disable=invalid-name

import argparse
import os
from datetime import datetime
from typing import Dict, List

import papermill as pm

PROJ_ROOT_DIR = os.getcwd()
data_dir = os.path.join(PROJ_ROOT_DIR, "data")
output_notebook_dir = os.path.join(PROJ_ROOT_DIR, "executed_notebooks")

raw_data_path = os.path.join(data_dir, "raw")

one_dict_nb_name = "1_create_aws_resources.ipynb"
two_dict_nb_name = "2_create_sagemaker_resources.ipynb"
three_dict_nb_name = "3_combine_raw_data.ipynb"
four_dict_nb_name = "4_data_processing.ipynb"
five_dict_nb_name = "5_delete_sagemaker_resources.ipynb"
six_dict_nb_name = "6_delete_aws_resources.ipynb"

s3_bucket_name = os.getenv("AWS_S3_BUCKET_NAME")
firehose_stream_name = "twitter_delivery_stream"
sg_group_name = "mysgname"
nb_instance_name = "mydemo"
ansible_host_vars_filepath = "inventories/production/host_vars/ec2host"

one_dict = dict(
    s3_bucket_name=s3_bucket_name,
    iam_role_path="/",
    iam_role_name="kinesis-firehose-role",
    iam_role_description="IAM Role to be assumed by Kinesis Firehose",
    iam_role_trust_policy={
        "Version": "2012-10-17",
        "Statement": [
            {
                "Sid": "",
                "Effect": "Allow",
                "Principal": {"Service": "firehose.amazonaws.com"},
                "Action": "sts:AssumeRole",
            }
        ],
    },
    iam_firehose_s3_policy_name="mypolicy",
    iam_firehose_s3_policy_description=(
        "IAM Policy Granting Firehose Access to S3"
    ),
    iam_firehose_s3_policy_tags=[
        {"Key": "Name", "Value": "firehose_access_s3"}
    ],
    stream_s3_destination_prefix="datasets/twitter/kinesis-demo/",
    firehose_stream_name="twitter_delivery_stream",
    cw_logs_group_name=f"kinesisfirehose_{firehose_stream_name}",
    sg_group_tags=[{"Key": "Name", "Value": "allow-inbound-ssh"}],
    key_fname="aws_ec2_key",
    keypair_name="ec2-key-pair",
    ec2_instance_image_id="ami-0cc00ed857256d2b4",
    ec2_instance_type="t2.micro",
    ec2_instance_tags_list=[{"Key": "Name", "Value": "my-ec2-instance"}],
    ansible_inventory_host_vars_fpath=ansible_host_vars_filepath,
)
two_dict = dict(
    s3_bucket_name="",
    iam_role_name="AmazonSageMaker-ExecutionRole-20211228T122046",
    sg_group_name="mysgname",
    sg_group_desc="My security group",
    sg_group_tags=[{"Key": "Name", "Value": sg_group_name}],
    nb_lifecycle_name="mynbconfig",
    nb_instance_name=nb_instance_name,
    nb_instance_type="ml.t3.xlarge",
    nb_instance_tags=[{"Key": "Name", "Value": nb_instance_name}],
    cw_log_group_name="/aws/sagemaker/NotebookInstances",
)
three_dict = dict(
    path_to_folder="/datasets/twitter/kinesis-demo/",
    sub_folders_list=[
        "csvs",
        "predictions",
        "athena-queries-outputs",
        "models",
    ],
    headers=[
        "id",
        "geo",
        "coordinates",
        "place",
        "contributors",
        "is_quote_status",
        "quote_count",
        "reply_count",
        "retweet_count",
        "favorite_count",
        "favorited",
        "retweeted",
        "created_at",
        "source",
        "in_reply_to_user_id",
        "in_reply_to_screen_name",
        "source_text",
        "place_id",
        "place_url",
        "place_place_type",
        "place_name",
        "place_full_name",
        "place_country_code",
        "place_country",
        "place_bounding_box_type",
        "place_bounding_box_coordinates",
        "place_attributes",
        "coords_type",
        "coords_lon",
        "coords_lat",
        "geo_type",
        "geo_lon",
        "geo_lat",
        "user_name",
        "user_screen_name",
        "user_followers",
        "user_friends",
        "user_listed",
        "user_favourites",
        "user_statuses",
        "user_protected",
        "user_verified",
        "user_contributors_enabled",
        "user_joined",
        "user_location",
        "retweeted_tweet",
        "tweet_text_urls",
        "tweet_text_hashtags",
        "tweet_text_usernames",
        "num_urls_in_tweet_text",
        "num_users_in_tweet_text",
        "num_hashtags_in_tweet_text",
        "text",
    ],
    cols_to_use=[
        "id",
        "contributors",
        "created_at",
        "source",
        "in_reply_to_screen_name",
        "source_text",
        "place_id",
        "place_url",
        "place_place_type",
        "place_country_code",
        "place_country",
        "user_name",
        "user_screen_name",
        "user_followers",
        "user_friends",
        "user_listed",
        "user_favourites",
        "user_statuses",
        "user_protected",
        "user_verified",
        "user_joined",
        "user_location",
        "retweeted_tweet",
        "text",
    ],
    unwanted_partial_strings_list=[
        "crypto",
        "token",
        "koistarter",
        "daostarter",
        "decentralized",
        "services",
        "pancakeswap",
        "eraxnft",
        "browsing",
        "kommunitas",
        "hosting",
        "internet",
        "exipofficial",
        "servers",
        "wallet",
        "liquidity",
        "rewards",
        "floki",
        "10000000000000linkstelegram",
        "dogecoin",
        "czbinance",
        "watch",
        "binance",
        "dogelonmars",
        "cryptocurrency",
        "hbomax",
        "money",
        "danheld",
        "cybersecurity",
        "prostitution",
        "nairobi",
        "musembe",
        "volcano detected",
        "block-2",
        "mo-greene",
        "running scared2012",
        "running scared 2012",
        "massacres",
        "eric ephriam chavez",
        "drugs",
        "tanzanite",
        "vvsorigin",
        "gemstonecarat",
        "bin laden",
        "saddam",
        "webuye",
        "bungoma",
        "perished",
        "popescu",
        "whore",
        "nasty",
        "ethereum",
        "pay someone",
        "gamejoin",
        "nft",
        "breeding",
        "seungkwan",
        "woozi",
        "hoshi",
        "bitcrush",
        "arcade",
        "homeworkpay",
        "homework",
        "photocards",
        "deta",
        "marketing",
        "dreamcast",
        "sega",
        "xbox",
        "wii",
        "ps4",
        "kasama",
        "nung",
        "lahat",
        "jinsoul",
        "brunisoul",
        "loona",
        "taas",
        "nung",
        "essay",
        "scriptures",
        "methusealah",
        "testament",
        "yahweh",
        "god",
        "mullah",
        "allah",
        "clergy",
        "mercy",
        "morality",
        "muslims,",
        "hindus",
        "buddhist",
        "catholics",
        "christians",
        "atheist",
        "nazist",
        "antifa",
        "proud boys",
    ],
)
four_dict = dict(
    path_to_folder="/datasets/twitter/kinesis-demo/",
    num_files_to_use=25,
    nrows=800_000,
    all_cols_to_process=[
        "document",
        "created_at",
        "user_joined",
        "in_reply_to_screen_name",
        "source_text",
        "place_country",
        "user_followers",
        "user_friends",
        "user_listed",
        "user_favourites",
        "user_statuses",
        "user_protected",
        "user_verified",
        "user_location",
        "reviewText",
    ],
    count_vectorizer_filename="count_vec_model",
    save_count_vectorizer=False,
    s3_models_subfolder="models",
    num_topics=4,
    num_top_terms_per_topic=15,
    num_top_docs_to_read=8,
    output_file_name="processed_with_predictions",
)
five_dict = dict(
    s3_bucket_name="",
    iam_role_name="AmazonSageMaker-ExecutionRole-20211228T122046",
    iam_policy_name="AmazonSageMaker-ExecutionPolicy-20211228T122046",
    delete_iam_resources="no",
    sg_group_name="mysgname",
    nb_lifecycle_name="mynbconfig",
    nb_instance_name="mydemo",
    nb_instance_tags=[{"Key": "Name", "Value": nb_instance_name}],
    cw_log_group_name="/aws/sagemaker/NotebookInstances",
)
six_dict = dict(
    s3_bucket_name=s3_bucket_name,
    iam_role_name="kinesis-firehose-role",
    iam_policy_name="mypolicy",
    firehose_stream_name=firehose_stream_name,
    cw_logs_group_name=f"kinesisfirehose_{firehose_stream_name}",
    sg_group_tags=[{"Key": "Name", "Value": "allow-inbound-ssh"}],
    key_fname="aws_ec2_key",
    keypair_name="ec2-key-pair",
    ec2_instance_tags_list=[{"Key": "Name", "Value": "my-ec2-instance"}],
    ansible_inventory_host_vars_fpath=ansible_host_vars_filepath,
)

def papermill_run_notebook(
    nb_dict: Dict, output_notebook_directory: str = "executed_notebooks"
) -> None:
    """Execute notebook with papermill"""
    for notebook, nb_params in nb_dict.items():
        now = datetime.now().strftime("%Y%m%d-%H%M%S")
        output_nb = os.path.basename(notebook).replace(
            ".ipynb", f"-{now}.ipynb"
        )
        print(
            f"\nInput notebook path: {notebook}",
            f"Output notebook path: {output_notebook_directory}/{output_nb} ",
            sep="\n",
        )
        for key, val in nb_params.items():
            print(key, val, sep=": ")
        pm.execute_notebook(
            input_path=notebook,
            output_path=f"{output_notebook_directory}/{output_nb}",
            parameters=nb_params,
        )

def run_notebooks(
    notebooks_list: List, output_notebook_directory: str = "executed_notebooks"
) -> None:
    """Execute notebooks from CLI.
    Parameters
    ----------
    nb_dict : List
        list of notebooks to be executed
    Usage
    -----
    > import os
    > PROJ_ROOT_DIR = os.path.abspath(os.getcwd())
    > one_dict_nb_name = "a.ipynb
    > one_dict = {"a": 1}
    > run_notebook(
          notebook_list=[
              {os.path.join(PROJ_ROOT_DIR, one_dict_nb_name): one_dict}
          ]
      )
    """
    for nb in notebooks_list:
        papermill_run_notebook(
            nb_dict=nb, output_notebook_directory=output_notebook_directory
        )

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--action",
        type=str,
        dest="action",
        default="create",
        help="whether to create or destroy AWS resources",
    )
    args = parser.parse_args()

    if args.action == "create":
        nb_dict_list, nb_name_list = [one_dict, one_dict_nb_name]
    elif args.action == "sagemaker-create":
        nb_dict_list, nb_name_list = [two_dict, two_dict_nb_name]
    elif args.action == "sagemaker-delete":
        nb_dict_list, nb_name_list = [five_dict, five_dict_nb_name]
    elif args.action == "delete":
        nb_dict_list, nb_name_list = [six_dict, six_dict_nb_name]

    notebook_list = [
        {os.path.join(PROJ_ROOT_DIR, nb_name): nb_dict}
        for nb_dict, nb_name in zip(nb_dict_list, nb_name_list)
    ]
    run_notebooks(
        notebooks_list=notebook_list,
        output_notebook_directory=output_notebook_dir,
    )


from rl_framework.agent import Agent
from rl_framework.environment import Environment
from stable_baselines3.common.base_class import BaseAlgorithm
from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.vec_env import DummyVecEnv
from stable_baselines3 import A2C, DDPG, DQN, HER, PPO, SAC, TD3
from typing import List, Text, Optional, Dict
from huggingface_sb3 import package_to_hub, load_from_hub
from functools import partial
from enum import Enum

class StableBaselinesAlgorithm(Enum):
    A2C = A2C
    DDPG = DDPG
    DQN = DQN
    HER = HER
    PPO = PPO
    SAC = SAC
    TD3 = TD3

class StableBaselinesAgent(Agent):
    @property
    def model(self):
        return self._model

    @model.setter
    def model(self, value):
        self._model = value

    def __init__(
        self,
        rl_algorithm: StableBaselinesAlgorithm = StableBaselinesAlgorithm.PPO,
        rl_algorithm_parameters: Dict = None,
        pretrained_model: Optional[BaseAlgorithm] = None,
    ):
        """
        Initialize an agent which will trained on one of Stable-Baselines3 algorithms.

        Args:
            rl_algorithm (StableBaselinesAlgorithm): Enum with values being SB3 RL Algorithm classes (Types).
                Specifies the algorithm for RL training.
                Defaults to PPO.
            rl_algorithm_parameters (Dict): Parameters / keyword arguments for the specified SB3 RL Algorithm class.
                See https://stable-baselines3.readthedocs.io/en/master/modules/base.html for details on common params.
                See individual docs (e.g., https://stable-baselines3.readthedocs.io/en/master/modules/ppo.html)
                for algorithm-specific params.
            pretrained_model (BaseAlgorithm): Pretrained SB3 model.
                This variable is mainly used for loading previously saved models.
        """

        self.sb3_algorithm = rl_algorithm.value
        self.model = pretrained_model

        if rl_algorithm_parameters is None:
            rl_algorithm_parameters = {
                "policy": "MlpPolicy",
                "learning_rate": 0.001,
            }

        self._model_builder = partial(
            self.sb3_algorithm,
            **rl_algorithm_parameters
        )

    def train(self, training_environments: List[Environment], total_timesteps: int = 100000, *args, **kwargs):
        """
        Train the instantiated agent on the environment.

        This training is done by using the agent-on-environment training method provided by Stable-baselines3.

        The model is changed in place, therefore the updated model can be accessed in the `.model` attribute
        after the agent has been trained.

        Args:
            training_environments (List[Environment): Environment on which the agent should be trained on.
                If n_environments is set above 1, multiple environments enables parallel training of an agent.
            total_timesteps (int): Amount of individual steps the agent should take before terminating the training.
        """

        environment_iterator = iter(training_environments)
        training_env = make_vec_env(
            lambda: next(environment_iterator), n_envs=len(training_environments)
        )

        self.model = self._model_builder(env=training_env)

        self.model.learn(total_timesteps=total_timesteps)

    def choose_action(self, observation: object, *args, **kwargs):
        """
        Chooses action which the agent will perform next, according to the observed environment.

        Args:
            observation (object): Observation of the environment

        Returns: action (int): Action to take according to policy.

        """

        action, _ = self.model.predict(observation)
        return action

    def save(self, file_path: Text):
        """
        Save the model of the agent to a zipped file.

        Args:
            file_path (Text): Path where the model should be saved to.
        """
        self.model.save(file_path)

    def upload_to_huggingface_hub(
        self,
        evaluation_environment: Environment,
        model_name: Text,
        model_architecture: Text,
        environment_name: Text,
        repository_id: Text,
        commit_message: Text
    ) -> None:
        """

        Args:
            evaluation_environment (Environment): Environment used for final evaluation and clip creation before upload.
            model_name (Text): Name of the model (uploaded model .zip will be named accordingly).
            model_architecture (Text): Name of the used model architecture (only used for model card and metadata).
            environment_name (Text): Name of the environment (only used for model card and metadata).
            repository_id (Text): Id of the model repository from the Hugging Face Hub.
            commit_message (Text): Commit message for the HuggingFace repository commit.

        NOTE: If after running the package_to_hub function, and it gives an issue of rebasing, please run the following code
            `cd <path_to_repo> && git add . && git commit -m "Add message" && git pull`
            And don't forget to do a `git push` at the end to push the change to the hub.

        """
        # Create a Stable-baselines3 vector environment (required for HuggingFace upload function)
        vectorized_evaluation_environment = DummyVecEnv(
            [lambda: evaluation_environment]
        )

        model = self.model
        package_to_hub(
            model=model,
            model_name=model_name,
            model_architecture=model_architecture,
            env_id=environment_name,
            eval_env=vectorized_evaluation_environment,
            repo_id=repository_id,
            commit_message=commit_message,
        )

    def download_from_huggingface_hub(
        self, repository_id: Text, filename: Text
    ):
        """
        Download a reinforcement learning model from the HuggingFace Hub and update the agent policy in-place.

        Args:
            repository_id (Text): Repository ID of the reinforcement learning model we want to download.
            filename (Text): The model filename (file ending with .zip) located in the hugging face repository.

        """

        # When the model was trained on Python 3.8 the pickle protocol is 5
        # But Python 3.6, 3.7 use protocol 4
        # In order to get compatibility we need to:
        # 1. Install pickle5
        # 2. Create a custom empty object we pass as parameter to PPO.load()
        custom_objects = {
            "learning_rate": 0.0,
            "lr_schedule": lambda _: 0.0,
            "clip_range": lambda _: 0.0,
        }

        checkpoint = load_from_hub(repository_id, filename)
        model = self.sb3_algorithm.load(
            checkpoint, custom_objects=custom_objects, print_system_info=True
        )
        self.model = model


from llama.program.util.run_ai import query_run_embedding

from tqdm import tqdm

import faiss
import json
import os
import numpy as np

import logging

logger = logging.getLogger(__name__)

class LaminiIndex:
    def __init__(self, loader=None):
        self.loader = loader

        if loader is not None:
            self.build_index()

    @staticmethod
    def load_index(path):
        lamini_index = LaminiIndex()

        faiss_path = os.path.join(path, "index.faiss")
        splits_path = os.path.join(path, "splits.json")

        # Load the index from a file
        lamini_index.index = faiss.read_index(faiss_path)

        # Load the splits from a file
        with open(splits_path, "r") as f:
            lamini_index.splits = json.load(f)

        return lamini_index

    def build_index(self):
        self.splits = []

        self.index = None

        # load a batch of splits from a generator
        for split_batch in tqdm(self.loader):
            embeddings = self.get_embeddings(split_batch)

            if self.index is None:
                # initialize the index
                logger.info(f"Creating index with dimension {len(embeddings[0])}")
                self.index = faiss.IndexFlatL2(len(embeddings[0]))

            # add the embeddings to the index
            self.index.add(embeddings)

            # save the splits
            self.splits.extend(split_batch)

    def get_embeddings(self, examples):
        embeddings = query_run_embedding(examples)

        embedding_list = [embedding[0] for embedding in embeddings]

        return np.array(embedding_list)

    def query(self, query, k=5):
        embedding = self.get_embeddings([query])[0]

        embedding_array = np.array([embedding])

        # get the k nearest neighbors
        distances, indices = self.index.search(embedding_array, k)

        return [self.splits[i] for i in indices[0]]

    def save_index(self, path):

        faiss_path = os.path.join(path, "index.faiss")
        splits_path = os.path.join(path, "splits.json")

        logger.debug("Saving index to %s", faiss_path)
        logger.debug("Saving splits to %s", splits_path)

        logger.debug("Index size: %d", self.index.ntotal)

        # Save the index to a file
        faiss.write_index(self.index, faiss_path)

        # Save the splits to a file
        with open(splits_path, "w") as f:
            json.dump(self.splits, f)


"""Faça um algoritimo para calcular a media de n numero informados pelo usuario. Para sair do calculo, o usuario deverá digitar um numero negativo  """

soma = 0
a = 1
cont = 1

while a > 0:
    n = int(input("Digite um número :"))
    if n > 0:
        soma = soma +n
        media = soma/ cont
        cont +=1
    else:
        a = -1

print(" A média dos numeros digitados foi de :", media)
print( "Fim do programa !")


#! /usr/bin/env python

import argparse
import re
import sys
import webbrowser
import requests
import logging

from gen_html import init_html, story_html, end_html, comment_html
from http.server import BaseHTTPRequestHandler, HTTPServer

logger = logging.getLogger(__name__)

class HandlerClass(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)

        logger.info("received new request")
        logger.info("path: " + self.path)

        if self.path == "/":
            logger.info("true")
            self.end_headers()
            out = get_top(1)
            self.wfile.write(bytes(out, "utf8"))

        if self.path == "/style.css":
            self.send_header('Content-type', "text/css")
            self.end_headers()
            with open("./style.css", "r") as file:
                self.wfile.write(bytes(file.read(), "utf8"))

def run(server: str, port: int, num_stories):
    httpd = HTTPServer((server, port), HandlerClass)
    httpd.serve_forever()

def open_web_browser(server: str, port: int):
    server_address = 'https://' + server + ':' + str(port)
    webbrowser.open_new(server_address)

def get_top(num_stories: int):
    i = 0
    res = [init_html()]
    top_story_list = requests.get(
        "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"
    )
    stories = top_story_list.text.split(", ")

    # TODO: use queue of threads for this
    # see https://docs.python.org/3/library/queue.html
    while i < num_stories:
        url = get_api_url(stories[i])
        story = requests.get(url).json()
        title = story.get("title")

        # TODO: create new css class, make title a link to post on HN
        #       HN url: https://news.ycombinator.com/item?id=<id>
        try:
            res.append(story_html(story.get("url"), story.get("title")))
        except TypeError:
            pass
        print_comments(story)
        # time.sleep(0.01) # to stay under rate limit
        i += 1

    res.append(end_html())
    # TODO lets not use print() here
    print("".join(res))
    return "".join(res)

def get_api_url(item):
    base_url = "https://hacker-news.firebaseio.com/v0/item/"
    postfix = ".json?print=pretty"
    item_number = trim_id(str(item))
    return base_url + item_number + postfix

def get_hn_url(item):
    base_url = "https://news.ycombinator.com/item?id="
    return base_url + item

def print_comments(story):
    res = []

    comments = story.get("kids")

    print(comments)

    try:
        for comment in comments:
            comment = requests.get(get_api_url(comment)).json()
            res.append(comment_html(comment.get("text")))
    except TypeError:
        pass

    print("".join(res))
    return "".join(res)

def trim_id(n: str):
    return re.sub(r"\D", "", n)

def process_args():
    """process arguments
# default server address
SERVER_ADDRESS = ("127.0.0.1", 8080)
    """
    parser = argparse.ArgumentParser()

    parser.add_argument('--num_stories',
                        type=int,
                        default=20,
                        help="number of stories to return")
    parser.add_argument('--server',
                        type=str,
                        default='127.0.0.1',
                        help="Address to serve page on.")
    parser.add_argument('--port',
                        type=int,
                        default=8080,
                        help="Port to use.")
    parser.add_argument('--verbose',
                        action='store_true',
                        help="Verbose logging")

    return parser.parse_args()

def init_logging(verbose):
    log_level = logging.ERROR if args.verbose else logging.INFO
    _log_handler = logging.StreamHandler(stream=sys.stdout)
    logger.addHandler(_log_handler)
    logger.setLevel(log_level)

if __name__ == "__main__":
    args = process_args()
    init_logging(args.verbose)
    open_web_browser(args.server, args.port)
    run(args.server, args.port, args.num_stories)


import sys
import math

n_1, n_2 = input().split()

n_3 = ""

for i in range(len(n_1)):
    if n_1[i] == "1" or n_2[i] == "1":
        n_3 += "1"
    else:
        n_3 += "0"

print(n_3)


import sys
import json

from dialogBoxes import MultipleInputDialog
from databaseManager import DBManager

from Resources.design import Ui_MainWindow
from PyQt5 import QtWidgets
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QTableWidgetItem
from PyQt5.QtWidgets import QMessageBox

class DebtCalculator(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.uiManager = Ui_MainWindow()
        self.uiManager.setupUi(self)

        # Attributes
        # *************
        with open("Data/texts.json") as file:
            self.textDict = json.load(file)
        self.user1Name = self.textDict["user1"]
        self.user2Name = self.textDict["user2"]
        # *************

        self.setWindowTitle("Debt Calculator")
        self.setWindowIcon(QIcon("Resources/iconDebt.png"))
        self.setFixedSize(self.width(), self.height())
        self.uiManager.tableUser1toUser2.hideColumn(0)
        self.uiManager.tableUser2toUser1.hideColumn(0)

        self.initTexts()
        self.calculateDebt("user1", 0)
        self.calculateDebt("user2", 0)
        self.initActions()

        self.loadTables()

    def initActions(self):
        self.uiManager.btnAddEntryUser1.clicked.connect(self.action_btnAddEntryUser1)
        self.uiManager.btnAddEntryUser2.clicked.connect(self.action_btnAddEntryUser2)

        self.uiManager.btnChangeUser1Name.clicked.connect(self.action_btnChangeUser1Name)
        self.uiManager.btnChangeUser2Name.clicked.connect(self.action_btnChangeUser2Name)

        self.uiManager.btnDeleteEntryUser1.clicked.connect(self.action_btnDeleteEntryUser1)
        self.uiManager.btnDeleteEntryUser2.clicked.connect(self.action_btnDeleteEntryUser2)

        self.uiManager.tableUser1toUser2.cellDoubleClicked.connect(self.action_tableUser1toUser2CellDoubleClicked)
        self.uiManager.tableUser2toUser1.cellDoubleClicked.connect(self.action_tableUser2toUser1CellDoubleClicked)

        self.uiManager.btnClearTable1.clicked.connect(self.action_btnClearTable1)
        self.uiManager.btnClearTable2.clicked.connect(self.action_btnClearTable2)

    def initTexts(self):
        self.user1Name = self.textDict["user1"]
        self.user2Name = self.textDict["user2"]

        self.uiManager.labelUser1_1.setText(self.user1Name)
        self.uiManager.labelUser2_1.setText(self.user2Name)
        self.uiManager.labelUser1_2.setText(self.user1Name)
        self.uiManager.labelUser2_2.setText(self.user2Name)

        self.uiManager.btnChangeUser1Name.setText("Rename '{}'".format(self.user1Name))
        self.uiManager.btnChangeUser2Name.setText("Rename '{}'".format(self.user2Name))

    def loadTables(self):
        dbManager = DBManager()
        dataList = dbManager.getRows("debtUser1toUser2")

        self.uiManager.tableUser1toUser2.setRowCount(len(dataList))
        for ix, data in enumerate(dataList):
            self.uiManager.tableUser1toUser2.setItem(ix, 0, QTableWidgetItem(str(data[0])))
            self.uiManager.tableUser1toUser2.setItem(ix, 1, QTableWidgetItem(data[1]))
            self.uiManager.tableUser1toUser2.setItem(ix, 2, QTableWidgetItem(str(data[2])))
            self.uiManager.tableUser1toUser2.setItem(ix, 3, QTableWidgetItem(data[3]))

        dataList = dbManager.getRows("debtUser2toUser1")

        self.uiManager.tableUser2toUser1.setRowCount(len(dataList))
        for ix, data in enumerate(dataList):
            self.uiManager.tableUser2toUser1.setItem(ix, 0, QTableWidgetItem(str(data[0])))
            self.uiManager.tableUser2toUser1.setItem(ix, 1, QTableWidgetItem(data[1]))
            self.uiManager.tableUser2toUser1.setItem(ix, 2, QTableWidgetItem(str(data[2])))
            self.uiManager.tableUser2toUser1.setItem(ix, 3, QTableWidgetItem(data[3]))

    def calculateDebt(self, whichUser: str, value: float):
        if whichUser == "user1":
            self.textDict["debtFromUser1ToUser2"] += value
            with open("Data/texts.json", "w") as file:
                json.dump(self.textDict, file)
            self.uiManager.labelTotalUser1.setText(f"Total: {self.textDict['debtFromUser1ToUser2']}")
        elif whichUser == "user2":
            self.textDict["debtFromUser2ToUser1"] += value
            with open("Data/texts.json", "w") as file:
                json.dump(self.textDict, file)
            self.uiManager.labelTotalUser2.setText(f"Total: {self.textDict['debtFromUser2ToUser1']}")
        self.netDebt()

    def netDebt(self):
        u1_to_u2 = self.textDict["debtFromUser1ToUser2"]
        u2_to_u1 = self.textDict["debtFromUser2ToUser1"]
        text = ""
        if u2_to_u1 == u1_to_u2:
            text = "Net debt is zero."
        elif u1_to_u2 > u2_to_u1:
            debt = u1_to_u2 - u2_to_u1
            if len(str(debt).split(".")[1]) > 3:
                debt = float(str(debt)[:-(len(str(debt).split(".")[1]) - 3)])
            text = f"{self.user1Name}\nowes {debt} to\n{self.user2Name}"
        elif u2_to_u1 > u1_to_u2:
            debt = u2_to_u1 - u1_to_u2
            if len(str(debt).split(".")[1]) > 3:
                debt = float(str(debt)[:-(len(str(debt).split(".")[1]) - 3)])
            text = f"{self.user2Name}\nowes {debt} to\n{self.user1Name}"
        self.uiManager.labelNetDebt.setText(text)

    def action_btnAddEntryUser1(self):
        inputBox = MultipleInputDialog(parent=self, windowTitle="New Entry", labelArr=["Name:", "Debt:", "Date:"])
        response = inputBox.exec()
        if response == 1:
            newEntryData = inputBox.getResult()
            if newEntryData[0] == '' or newEntryData[1] == '' or newEntryData[2] == '':
                msgBox = QMessageBox(parent=self)

                msgBox.setWindowTitle("Alert!")
                msgBox.setText("You must fill all the blanks.")
                msgBox.setStandardButtons(QMessageBox.Ok)

                msgBox.exec()
            else:
                name, debt, date = newEntryData
                try:
                    debt = float(debt)
                except Exception as err:
                    print("Error Message -> ", err)
                    msgBox = QMessageBox(parent=self)

                    msgBox.setWindowTitle("Alert!")
                    msgBox.setText("Debt must be numerical.")
                    msgBox.setStandardButtons(QMessageBox.Ok)

                    msgBox.exec()
                    return
                dbManager = DBManager()
                dbManager.addRow("debtUser1toUser2", name, debt, date)
                self.loadTables()
                self.calculateDebt("user1", debt)

    def action_btnAddEntryUser2(self):
        inputBox = MultipleInputDialog(parent=self, windowTitle="New Entry", labelArr=["Name:", "Debt:", "Date:"])
        response = inputBox.exec()
        if response == 1:
            newEntryData = inputBox.getResult()
            if newEntryData[0] == '' or newEntryData[1] == '' or newEntryData[2] == '':
                msgBox = QMessageBox(parent=self)

                msgBox.setWindowTitle("Alert!")
                msgBox.setText("You must fill all the blanks.")
                msgBox.setStandardButtons(QMessageBox.Ok)

                msgBox.exec()
            else:
                name, debt, date = newEntryData
                try:
                    debt = float(debt)
                except Exception as err:
                    print("Error Message -> ", err)
                    msgBox = QMessageBox(parent=self)

                    msgBox.setWindowTitle("Alert!")
                    msgBox.setText("Debt must be numerical.")
                    msgBox.setStandardButtons(QMessageBox.Ok)

                    msgBox.exec()
                    return
                dbManager = DBManager()
                dbManager.addRow("debtUser2toUser1", name, debt, date)
                self.loadTables()
                self.calculateDebt("user2", debt)

    def action_btnChangeUser1Name(self):
        oldName = self.user1Name
        inputBox = MultipleInputDialog(parent=self, windowTitle="Rename", labelArr=[f"Change {oldName} to "])
        inputBox.exec()
        newName = inputBox.getResult()
        if newName:
            self.textDict["user1"] = newName
            with open("Data/texts.json", "w") as file:
                json.dump(self.textDict, file)

            self.initTexts()
            self.netDebt()

    def action_btnChangeUser2Name(self):
        oldName = self.user2Name
        inputBox = MultipleInputDialog(parent=self, windowTitle="Rename", labelArr=[f"Change {oldName} to "])
        inputBox.exec()
        newName = inputBox.getResult()
        if newName:
            self.textDict["user2"] = newName
            with open("Data/texts.json", "w") as file:
                json.dump(self.textDict, file)

            self.initTexts()
            self.netDebt()

    def action_btnDeleteEntryUser1(self):
        table = self.uiManager.tableUser1toUser2
        selectedItems = table.selectedItems()
        if not selectedItems:
            alertBox = QMessageBox(parent=self)

            alertBox.setText("There is no selected item.")
            alertBox.setWindowTitle("Alert")
            alertBox.setStandardButtons(QMessageBox.Ok)

            alertBox.exec()
            return
        selectedItemRow = selectedItems[0].row()
        rowValues = [table.item(selectedItemRow, 0), table.item(selectedItemRow, 1), table.item(selectedItemRow, 2), table.item(selectedItemRow, 3)]

        messageBox = QMessageBox(parent=self)

        messageBox.setWindowTitle("Deleting Item")
        text = f"Are you sure want to delete this entry ?\nName: {rowValues[1].text()}\nDebt: {rowValues[2].text()}\nDate: {rowValues[3].text()}"
        messageBox.setText(text)
        messageBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)

        response = messageBox.exec()
        if response == QMessageBox.Yes:
            dbManager = DBManager()
            dbManager.deleteRow("debtUser1toUser2", rowValues[0].text())

            self.calculateDebt("user1", -float(rowValues[2].text()))
            self.uiManager.tableUser1toUser2.removeRow(selectedItemRow)

    def action_btnDeleteEntryUser2(self):
        table = self.uiManager.tableUser2toUser1
        selectedItems = table.selectedItems()
        if not selectedItems:
            alertBox = QMessageBox(parent=self)

            alertBox.setText("There is no selected item.")
            alertBox.setWindowTitle("Alert")
            alertBox.setStandardButtons(QMessageBox.Ok)

            alertBox.exec()
            return
        selectedItemRow = selectedItems[0].row()
        rowValues = [table.item(selectedItemRow, 0), table.item(selectedItemRow, 1), table.item(selectedItemRow, 2), table.item(selectedItemRow, 3)]

        messageBox = QMessageBox(parent=self)

        messageBox.setWindowTitle("Deleting Item")
        text = f"Are you sure want to delete this entry ?\nName: {rowValues[1].text()}\nDebt: {rowValues[2].text()}\nDate: {rowValues[3].text()}"
        messageBox.setText(text)
        messageBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)

        response = messageBox.exec()
        if response == QMessageBox.Yes:
            dbManager = DBManager()
            dbManager.deleteRow("debtUser2toUser1", rowValues[0].text())

            self.calculateDebt("user2", -float(rowValues[2].text()))
            self.uiManager.tableUser2toUser1.removeRow(selectedItemRow)

    def action_tableUser1toUser2CellDoubleClicked(self):
        table = self.uiManager.tableUser1toUser2
        selectedItems = table.selectedItems()
        selectedItemsRow = selectedItems[0].row()

        inputBox = MultipleInputDialog(parent=self, windowTitle="Editing an entry", labelArr=["Name:", "Debt:", "Date:"])
        inputBox.lineEdits[0].setText(selectedItems[0].text())
        inputBox.lineEdits[1].setText(selectedItems[1].text())
        inputBox.lineEdits[2].setText(selectedItems[2].text())
        inputBox.exec()
        response = inputBox.getResult()
        if len(response) == 3 and (response[0] == '' or response[1] == '' or response[2] == ''):
            msgBox = QMessageBox(parent=self)

            msgBox.setWindowTitle("Alert!")
            msgBox.setText("You must fill all the blanks.")
            msgBox.setStandardButtons(QMessageBox.Ok)

            msgBox.exec()
            return
        elif response:
            try:
                response[1] = float(response[1])
                response[1] = str(response[1])
            except Exception as err:
                print("Error Message -> ", err)
                msgBox = QMessageBox(parent=self)

                msgBox.setWindowTitle("Alert!")
                msgBox.setText("Debt must be numerical.")
                msgBox.setStandardButtons(QMessageBox.Ok)

                msgBox.exec()
                return
            ID = table.item(selectedItemsRow, 0).text()
            debtDiff = float(response[1]) - float(selectedItems[1].text())

            dbManager = DBManager()
            dbManager.editRow("debtUser1toUser2", ID, [response[0], response[1], response[2]])
            table.setItem(selectedItemsRow, 1, QTableWidgetItem(response[0]))
            table.setItem(selectedItemsRow, 2, QTableWidgetItem(response[1]))
            table.setItem(selectedItemsRow, 3, QTableWidgetItem(response[2]))
            self.calculateDebt("user1", debtDiff)

    def action_tableUser2toUser1CellDoubleClicked(self):
        table = self.uiManager.tableUser2toUser1
        selectedItems = table.selectedItems()
        selectedItemsRow = selectedItems[0].row()

        inputBox = MultipleInputDialog(parent=self, windowTitle="Editing an entry", labelArr=["Name:", "Debt:", "Date:"])
        inputBox.lineEdits[0].setText(selectedItems[0].text())
        inputBox.lineEdits[1].setText(selectedItems[1].text())
        inputBox.lineEdits[2].setText(selectedItems[2].text())
        inputBox.exec()
        response = inputBox.getResult()
        if len(response) == 3 and (response[0] == '' or response[1] == '' or response[2] == ''):
            msgBox = QMessageBox(parent=self)

            msgBox.setWindowTitle("Alert!")
            msgBox.setText("You must fill all the blanks.")
            msgBox.setStandardButtons(QMessageBox.Ok)

            msgBox.exec()
            return
        elif response:
            try:
                response[1] = float(response[1])
                response[1] = str(response[1])
            except Exception as err:
                print("Error Message -> ", err)
                msgBox = QMessageBox(parent=self)

                msgBox.setWindowTitle("Alert!")
                msgBox.setText("Debt must be numerical.")
                msgBox.setStandardButtons(QMessageBox.Ok)

                msgBox.exec()
                return
            ID = table.item(selectedItemsRow, 0).text()

            debtDiff = float(response[1]) - float(selectedItems[1].text())

            dbManager = DBManager()
            dbManager.editRow("debtUser2toUser1", ID, [response[0], response[1], response[2]])
            table.setItem(selectedItemsRow, 1, QTableWidgetItem(response[0]))
            table.setItem(selectedItemsRow, 2, QTableWidgetItem(response[1]))
            table.setItem(selectedItemsRow, 3, QTableWidgetItem(response[2]))
            self.calculateDebt("user2", debtDiff)

    def action_btnClearTable1(self):
        if self.uiManager.tableUser1toUser2.rowCount() == 0:
            QMessageBox.warning(
                self,
                "No Data to Clear",
                "There is no data to clear in table 1",
                QMessageBox.Ok,
                QMessageBox.Ok
            )
            return
        else:
            alertBox = QMessageBox.warning(
                self,
                "ALERT !!",
                "ARE YOU SURE TO DELETE ALL THE DATA FROM TABLE 1 ?",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            if alertBox == QMessageBox.Yes:
                dbManager = DBManager()
                dbManager.deleteRow("debtUser1ToUser2")
                self.loadTables()
                self.calculateDebt("user1", -(self.textDict["debtFromUser1ToUser2"]))

    def action_btnClearTable2(self):
        if self.uiManager.tableUser2toUser1.rowCount() == 0:
            QMessageBox.warning(
                self,
                "No Data to Clear",
                "There is no data to clear in table 2",
                QMessageBox.Ok,
                QMessageBox.Ok
            )
            return
        else:
            alertBox = QMessageBox.warning(
                self,
                "ALERT !!",
                "ARE YOU SURE TO DELETE ALL THE DATA FROM TABLE 2 ?",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            if alertBox == QMessageBox.Yes:
                dbManager = DBManager()
                dbManager.deleteRow("debtUser2ToUser1")
                self.loadTables()
                self.calculateDebt("user2", -(self.textDict["debtFromUser2ToUser1"]))

def runApp():
    myApp = QtWidgets.QApplication(sys.argv)
    myWindow = DebtCalculator()
    myWindow.show()
    myApp.exec()

runApp()


def cal(n, f):
   result = 0
   while (n >= f):
      n //= f
      result += n
   return result

n, m = map(int, input().split())
print(min(cal(n, 2) - cal(m, 2) - cal(n - m, 2),
   cal(n, 5) - cal(m, 5) - cal(n - m, 5)))


import pyautogui as pya
import pyperclip
import time
import keyboard
import webbrowser

lst = []

def copy_clipboard():
    pyperclip.copy("")
    pya.hotkey('ctrl','c')
    time.sleep(.1)
    return pyperclip.paste()

def double_click_copy():
    pya.doubleClick(pya.position())
    pya.click(pya.position())
    var=copy_clipboard()
    lst.append(var)
    print(lst)
    webbrowser.open('https://stackoverflow.com/')
    time.sleep(3)
    pya.hotkey('ctrl','v')
    pya.press('enter')

keyboard.add_hotkey('ctrl+f9',double_click_copy)
keyboard.wait()


#-*-coding:utf-8 -*-
__author__ = 'Jy2881'

import numpy as np

def polyFeatures(X, p):
    # zero initial
    X_poly = np.zeros([np.size(X), p])

    # start
    for i in range(0,p):
        X_poly[:,i] = X[:,0]**(i+1)

    return X_poly


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

import requests
import config

class Geocode:
    """ This class search the geolocation informations of a place """

    def __init__(self, place=""):
        self.api_key = config.GOOGLE_API_KEY
        self.url = "https://maps.googleapis.com/maps/api/geocode/json"
        self.geocode_params = {
            "address": place,
            "key": self.api_key,
        }
        self.get_place_infos()

    def get_place_infos(self):
        self.placeInfos = {}
        req = requests.get(self.url, self.geocode_params)
        if req.status_code >= 200 and req.status_code <= 400:
            data = req.json()
            self.placeInfos["status"] = data["status"]
            if self.placeInfos["status"] == "OK":
                self.placeInfos["address"] = data["results"][0]["formatted_address"]
                self.placeInfos["location"] = data["results"][0]["geometry"]["location"]
                self.placeInfos["place_id"] = data["results"][0]["place_id"]
            else:
                try:
                    self.placeInfos['error_message'] = data["error_message"]
                except KeyError:
                    pass
            return self.placeInfos
        else:
            self.placeInfos['status'] = "Erreur 404"
            self.placeInfos['error_message'] = "Page not found or error in URL"
            return self.placeInfos

    @property
    def infos(self):
        return self.placeInfos

    @property
    def status(self):
        return self.placeInfos["status"]

    @property
    def address(self):
        try:
            if self.placeInfos["address"]:
                return self.placeInfos["address"]
        except KeyError:
            return "'address' not found for this request"

    @property
    def location(self):
        try:
            if self.placeInfos["location"]:
                return self.placeInfos["location"]
        except KeyError:
            return "'location' not found for this request"

    @property
    def place_id(self):
        try:
            if self.placeInfos["place_id"]:
                return self.placeInfos["place_id"]
        except KeyError:
            return "'place_id' not found for this request"

    @property
    def message_error(self):
        try:
            if self.placeInfos["error_message"]:
                return self.placeInfos["error_message"]
        except KeyError:
            return "No message Error"

# if __name__=="__main__":
#     geo = Geocode("OpenClassrooms Paris")
#     print(geo.status)
#     print(geo.address)
#     print(geo.location)
#     print(geo.location['lat'])
#     print(geo.location['lng'])
#     print(geo.place_id)
#     print(geo.message_error)


from rest_framework import exceptions, serializers
from rest_framework.validators import UniqueValidator
from rest_framework.generics import get_object_or_404
from rest_framework_simplejwt.tokens import RefreshToken

from .models import User, Category, Genre, Title, Review, Comment

class CustomTokenObtainSerializer(serializers.Serializer):
    """Higher serializer for token obtaining."""

    username_field = User.USERNAME_FIELD

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields[self.username_field] = serializers.CharField()

        self.fields['confirmation_code'] = serializers.CharField()

    def validate(self, attrs):
        self.user = get_object_or_404(User, email=attrs[self.username_field])

        if not self.user:
            raise exceptions.AuthenticationFailed('The user is not valid.')

        return {}

class CustomTokenObtainPairSerializer(CustomTokenObtainSerializer):
    """Serializer for token obtaining."""
    @classmethod
    def get_token(cls, user):
        return RefreshToken.for_user(user)

    def validate(self, attrs):
        data = super(CustomTokenObtainPairSerializer, self).validate(attrs)

        refresh = self.get_token(self.user)

        data['refresh'] = str(refresh)
        data['access'] = str(refresh.access_token)

        return data

class CreateUserSerializer(serializers.ModelSerializer):
    """Serializer for user creation action."""

    class Meta:
        fields = ("email",)
        model = User

class UserSerializer(serializers.ModelSerializer):
    """Serializer for user endpoints with forbid role changes."""

    username = serializers.CharField(
        validators=[UniqueValidator(queryset=User.objects.all())],
        required=True,
    )
    email = serializers.EmailField(
        validators=[UniqueValidator(queryset=User.objects.all())],
        required=True,
    )

    class Meta:
        fields = (
            "id",
            "first_name",
            "last_name",
            "username",
            "bio",
            "email",
            "role",
        )
        model = User
        read_only_fields = ("email", "role")

class AdminSerializer(serializers.ModelSerializer):
    """Serializer for user endpoints with allowed role changes."""

    username = serializers.CharField(
        validators=[UniqueValidator(queryset=User.objects.all())],
        required=True,
    )
    email = serializers.EmailField(
        validators=[UniqueValidator(queryset=User.objects.all())],
        required=True,
    )

    class Meta:
        fields = (
            "id",
            "first_name",
            "last_name",
            "username",
            "bio",
            "email",
            "role",
        )
        model = User
        read_only_fields = ("email",)

class CategorySerializer(serializers.ModelSerializer):
    """Serializer for category endpoints."""

    name = serializers.CharField(required=True)

    class Meta:
        exclude = ("id",)
        model = Category

class GenreSerializer(serializers.ModelSerializer):
    """Serializer for genre endpoints."""

    name = serializers.CharField(required=True)

    class Meta:
        fields = ("name", "slug")
        model = Genre

class GetTitleSerializer(serializers.ModelSerializer):
    """Serializer for title GET endpoints."""

    name = serializers.CharField(required=True)
    genre = GenreSerializer(many=True, required=False)
    category = CategorySerializer(required=False)
    rating = serializers.IntegerField(read_only=True, default=None)

    class Meta:
        fields = "__all__"
        model = Title

class CreateTitleSerializer(serializers.ModelSerializer):
    """Serializer for title POST, PATCH, DELETE endpoints."""

    name = serializers.CharField(required=True)
    genre = serializers.SlugRelatedField(
        many=True,
        queryset=Genre.objects.all(),
        slug_field="slug",
        required=False,
    )
    category = serializers.SlugRelatedField(
        queryset=Category.objects.all(), slug_field="slug", required=False
    )
    rating = serializers.IntegerField(read_only=True, default=None)

    class Meta:
        fields = "__all__"
        model = Title

class CreateReviewSerializer(serializers.ModelSerializer):
    """Serializer for title POST endpoints."""

    text = serializers.CharField(required=True)
    score = serializers.ChoiceField(
        choices=[(i, i) for i in range(1, 11)], required=True
    )
    author = serializers.SlugRelatedField(
        slug_field="username",
        read_only=True,
        default=serializers.CurrentUserDefault(),
    )
    title = serializers.SlugRelatedField(
        required=False, slug_field="pk", queryset=Title.objects.all()
    )

    class Meta:
        fields = "__all__"
        model = Review

    def validate(self, data):
        """Check that authors review already exists."""
        title = self.context["view"].kwargs.get("title_id")
        author = self.context["request"].user
        message = "Authors review already exists"
        if Review.objects.filter(title=title, author=author).exists():
            raise serializers.ValidationError(message)
        return data

class ReviewSerializer(serializers.ModelSerializer):
    """Serializer for title GET, PATCH, DELETE endpoints."""

    text = serializers.CharField(required=True)
    score = serializers.ChoiceField(
        choices=[(i, i) for i in range(1, 11)], required=True
    )
    author = serializers.SlugRelatedField(
        slug_field="username",
        read_only=True,
        default=serializers.CurrentUserDefault(),
    )
    title = serializers.SlugRelatedField(
        required=False, slug_field="pk", queryset=Title.objects.all()
    )

    class Meta:
        fields = "__all__"
        model = Review

class CommentSerializer(serializers.ModelSerializer):
    """Serializer for comment endpoints."""

    text = serializers.CharField(required=True)
    author = serializers.SlugRelatedField(
        slug_field="username",
        read_only=True,
        default=serializers.CurrentUserDefault(),
    )
    title = serializers.SlugRelatedField(
        required=False, slug_field="pk", queryset=Title.objects.all()
    )
    review = serializers.SlugRelatedField(
        required=False, slug_field="pk", queryset=Review.objects.all()
    )

    class Meta:
        fields = "__all__"
        model = Comment


import configparser

from cpe_help import util

def get_configuration():
    config = configparser.RawConfigParser()
    config.read(util.path.CONFIG_PATH)
    return config

def get_acs_variables():
    """
    Return a dictionary mapping variable names to be queried into how
    these variables should be named locally.
    """
    config = get_configuration()
    default_keys = list(config['DEFAULT'])
    result = {k.upper(): v
              for k, v in config['ACS Variables'].items()
              if k not in default_keys}
    return result


import sys

from models import Location, User
from sqlalchemy import or_

from app import db, app

def send_user_notification(user_id):
    notification_text = "Não esqueça de levar seu guarda-chuvas!"
    print("sending notification to %s: %s" % (user_id, notification_text))

def load_forecasts():
    with app.app_context():
        for location in Location.query.all():
            location.load_forecasts()
            db.session.add(location)
            db.session.commit()

def notify_users():
    with app.app_context():
        locations = Location.query.filter(Location.hourly_forecast.contains("rain"))

        locations = {
            l.id: l for l in locations
        }

        user_list = db.session.query(User).filter(User.home_location_id.in_(locations.keys()))

        for user in user_list:
            notification_required = False
            if user.next_day_forecast_required():
                notification_required = True  # if next day is required any result is valid

            elif user.home_location_id in locations.keys() and 'rain' in \
                    locations[user.home_location_id].today_forecasts().values():
                notification_required = True
            elif user.work_location_id in locations.keys() and 'rain' in \
                    locations[user.work_location_id].today_forecasts().values():
                notification_required = True

            # send notification if required
            if notification_required:
                send_user_notification(user.id)

def main():
    action = sys.argv[0]
    if action == "load_forecasts":
        load_forecasts()
    elif action == "notify_users":
        notify_users()
    else:
        print("Invalid action")
        exit(1)

if __name__ == "__main__":
    main()


import logging

from flask import request
from flask_restplus import Resource, fields
from structlog import wrap_logger

from ras_backstage import party_api
from ras_backstage.controllers import party_controller

logger = wrap_logger(logging.getLogger(__name__))

respondent_details = party_api.model('RespondentDetails', {
    'first_name': fields.String(required=True),
    'last_name': fields.String(required=True),
    'telephone': fields.String(required=True),
    'email_address': fields.String(required=True),
    'new_email_address': fields.String(required=True)
})

@party_api.route('/update-respondent-details/<respondent_id>')
class UpdateRespondentDetails(Resource):
    @staticmethod
    @party_api.expect(respondent_details, validate=True)
    def put(respondent_id):
        logger.info('Retrieving updated respondent details', respondent_id=respondent_id)
        respondent_contact_details = request.get_json()
        party_controller.update_respondent_details(respondent_id, respondent_contact_details)
        logger.info('Successfully updated user details', respondent_id=respondent_id)
        return 200


#https://leetcode.com/problems/second-minimum-time-to-reach-destination/
#A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. The time taken to traverse any edge is time minutes.
#Each vertex has a traffic signal which changes its color from green to red and vice versa every change minutes. All signals change at the same time. You can enter a vertex at any time, but can leave a vertex only when the signal is green. You cannot wait at a vertex if the signal is green.
#The second minimum value is defined as the smallest value strictly larger than the minimum value.
#For example the second minimum value of [2, 3, 4] is 3, and the second minimum value of [2, 2, 4] is 4.
#Given n, edges, time, and change, return the second minimum time it will take to go from vertex 1 to vertex n.

class Solution(object):
    def secondMinimum(self, n, edges, time, change):
        """
        :type n: int
        :type edges: List[List[int]]
        :type time: int
        :type change: int
        :rtype: int
        """
        graph = collections.defaultdict(list)
        for u, v in edges:
            graph[u].append(v)
            graph[v].append(u)
        dist = [float('inf')] * (n+1)
        dist[1] = 0
        q = [(0, 1)]
        while q:
            d, u = heapq.heappop(q)
            if dist[u] < d:
                continue
            for v in graph[u]:
                if (d // change) % 2 == 0:
                    if dist[v] > d + time:
                        dist[v] = d + time
                        heapq.heappush(q, (dist[v], v))
                else:
                    if dist[v] > d + change - d % change + time:
                        dist[v] = d + change - d % change + time
                        heapq.heappush(q, (dist[v], v))
        return dist[-1]


from django.db import models
from authen.models import UserProfile, Content

# Create your models here.

class Forum(models.Model):
    creator = models.ForeignKey(UserProfile, on_delete=models.CASCADE) # Perlu kah?
    title = models.CharField(max_length = 255, unique=True)
    description = models.TextField()
    contents = models.ManyToManyField(Content)
    date_created = models.DateTimeField(auto_now_add=True)

class Members(models.Model):
    forum = models.OneToOneField(Forum, on_delete=models.CASCADE)
    subscriptor = models.ManyToManyField(UserProfile) # Mau make ginian?


print('===== DESAFIO 33 =====')
print('===== Qual é o maior? E o menor? =====')
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número: '))
n3 = int(input('Digite o terceiro número: '))
# definindo o maior
maior = n1
if n2 > n1 and n2 > n3:
    maior = n2
if n3 > n1 and n3 > n2:
    maior = n3
# definindo o menor
menor = n1
if n2 < n1 and n2 < n3:
    menor = n2
if n3 < n1 and n3 < n2:
    menor = n3
print('O maior número é {}!'.format(maior))
print('E o menor número é {}!'.format(menor))


from __future__ import absolute_import, division, print_function, unicode_literals

import os
import sys

# CONSTANTS

# categorization of a run result
CATEGORY_CORRECT = 'correct'
"""run result given by tool was correct"""

CATEGORY_WRONG   = 'wrong'
"""run result given by tool was wrong"""

CATEGORY_UNKNOWN = 'unknown'
"""run result given by tool was "unknown" (i.e., no answer)"""

CATEGORY_ERROR   = 'error'
"""tool failed, crashed, or hit a resource limit"""

CATEGORY_MISSING = 'missing'
"""BenchExec could not determine whether run result was correct or wrong
because no property was defined, and no other categories apply."""

# internal property names used in this module (should not contain spaces)
# previously used by SV-COMP (http://sv-comp.sosy-lab.org/2014/rules.php):
_PROP_LABEL =        'unreach-label'
# currently used by SV-COMP (http://sv-comp.sosy-lab.org/2016/rules.php):
_PROP_CALL =         'unreach-call'
_PROP_TERMINATION =  'termination'
_PROP_OVERFLOW =     'no-overflow'
_PROP_DEREF =        'valid-deref'
_PROP_FREE =         'valid-free'
_PROP_MEMTRACK =     'valid-memtrack'
# for Java verification:
_PROP_ASSERT =       'assert'
# specification given as an automaton:
_PROP_AUTOMATON =    'observer-automaton'
# for solvers:
_PROP_SAT =          'sat'

STR_FALSE = 'false' # only for special cases. STR_FALSE is no official result, because property is missing

# possible run results (output of a tool)
RESULT_UNKNOWN =            'unknown'
"""tool could not find out an answer due to incompleteness"""
RESULT_ERROR =              'ERROR' # or any other value not listed here
"""tool could not complete due to an error
(it is recommended to instead use a string with more details about the error)"""
RESULT_TRUE_PROP =          'true'
"""property holds"""
RESULT_FALSE_REACH =        STR_FALSE + '(reach)'
"""SV-COMP reachability property violated"""
RESULT_FALSE_TERMINATION =  STR_FALSE + '(' + _PROP_TERMINATION + ')'
"""SV-COMP termination property violated"""
RESULT_FALSE_OVERFLOW =     STR_FALSE + '(' + _PROP_OVERFLOW    + ')'
"""SV-COMP overflow property violated"""
RESULT_FALSE_DEREF =        STR_FALSE + '(' + _PROP_DEREF       + ')'
"""SV-COMP valid-deref property violated"""
RESULT_FALSE_FREE =         STR_FALSE + '(' + _PROP_FREE        + ')'
"""SV-COMP valid-free property violated"""
RESULT_FALSE_MEMTRACK =     STR_FALSE + '(' + _PROP_MEMTRACK    + ')'
"""SV-COMP valid-memtrack property violated"""
RESULT_WITNESS_CONFIRMED =  'witness confirmed'
"""SV-COMP property violated and witness confirmed"""
RESULT_SAT =                'sat'
"""task is satisfiable"""
RESULT_UNSAT =              'unsat'
"""task is unsatisfiable"""

# List of all possible results.
# If a result is not in this list, it is handled as RESULT_CLASS_ERROR.
RESULT_LIST = [RESULT_TRUE_PROP, RESULT_UNKNOWN,
               RESULT_FALSE_REACH, RESULT_FALSE_TERMINATION,
               RESULT_FALSE_DEREF, RESULT_FALSE_FREE, RESULT_FALSE_MEMTRACK,
               RESULT_WITNESS_CONFIRMED,
               RESULT_SAT, RESULT_UNSAT,
               RESULT_FALSE_OVERFLOW
               ]

# Classification of results
RESULT_CLASS_TRUE    = 'true'
RESULT_CLASS_FALSE   = 'false'
RESULT_CLASS_UNKNOWN = 'unknown'
RESULT_CLASS_ERROR   = 'error'

# This maps content of property files to property name.
_PROPERTY_NAMES = {'LTL(G ! label(':                    _PROP_LABEL,
                   'LTL(G ! call(__VERIFIER_error()))': _PROP_CALL,
                   'LTL(F end)':                        _PROP_TERMINATION,
                   'LTL(G valid-free)':                 _PROP_FREE,
                   'LTL(G valid-deref)':                _PROP_DEREF,
                   'LTL(G valid-memtrack)':             _PROP_MEMTRACK,
                   'OBSERVER AUTOMATON':                _PROP_AUTOMATON,
                   'SATISFIABLE':                       _PROP_SAT,
                   'LTL(G ! overflow)':                 _PROP_OVERFLOW,
                  }

# This maps a possible result substring of a file name
# to the expected result string of the tool and the set of properties
# for which this result is relevant.
_FILE_RESULTS = {
              '_true-unreach-label':   (RESULT_TRUE_PROP, {_PROP_LABEL}),
              '_true-unreach-call':    (RESULT_TRUE_PROP, {_PROP_CALL}),
              '_true_assert':          (RESULT_TRUE_PROP, {_PROP_ASSERT}),
              '_true-termination':     (RESULT_TRUE_PROP, {_PROP_TERMINATION}),
              '_true-valid-deref':     (RESULT_TRUE_PROP, {_PROP_DEREF}),
              '_true-valid-free':      (RESULT_TRUE_PROP, {_PROP_FREE}),
              '_true-valid-memtrack':  (RESULT_TRUE_PROP, {_PROP_MEMTRACK}),
              '_true-valid-memsafety': (RESULT_TRUE_PROP, {_PROP_DEREF, _PROP_FREE, _PROP_MEMTRACK}),
              '_true-no-overflow':     (RESULT_TRUE_PROP, {_PROP_OVERFLOW}),

              '_false-unreach-label':  (RESULT_FALSE_REACH,       {_PROP_LABEL}),
              '_false-unreach-call':   (RESULT_FALSE_REACH,       {_PROP_CALL}),
              '_false_assert':         (RESULT_FALSE_REACH,       {_PROP_ASSERT}),
              '_false-termination':    (RESULT_FALSE_TERMINATION, {_PROP_TERMINATION}),
              '_false-valid-deref':    (RESULT_FALSE_DEREF,       {_PROP_DEREF}),
              '_false-valid-free':     (RESULT_FALSE_FREE,        {_PROP_FREE}),
              '_false-valid-memtrack': (RESULT_FALSE_MEMTRACK,    {_PROP_MEMTRACK}),
              '_false-no-overflow':    (RESULT_FALSE_OVERFLOW,    {_PROP_OVERFLOW}),

              '_sat':                  (RESULT_SAT,   {_PROP_SAT}),
              '_unsat':                (RESULT_UNSAT, {_PROP_SAT}),
              }

# Map a property to all possible results for it.
_VALID_RESULTS_PER_PROPERTY = {
    _PROP_ASSERT:      {RESULT_TRUE_PROP, RESULT_FALSE_REACH},
    _PROP_LABEL:       {RESULT_TRUE_PROP, RESULT_FALSE_REACH},
    _PROP_CALL:        {RESULT_TRUE_PROP, RESULT_FALSE_REACH},
    _PROP_AUTOMATON:   {RESULT_TRUE_PROP, RESULT_FALSE_REACH},
    _PROP_DEREF:       {RESULT_TRUE_PROP, RESULT_FALSE_DEREF},
    _PROP_FREE:        {RESULT_TRUE_PROP, RESULT_FALSE_FREE},
    _PROP_MEMTRACK:    {RESULT_TRUE_PROP, RESULT_FALSE_MEMTRACK},
    _PROP_OVERFLOW:    {RESULT_TRUE_PROP, RESULT_FALSE_OVERFLOW},
    _PROP_TERMINATION: {RESULT_TRUE_PROP, RESULT_FALSE_TERMINATION},
    _PROP_SAT:         {RESULT_SAT, RESULT_UNSAT},
    }

# Score values taken from http://sv-comp.sosy-lab.org/
# If different scores should be used depending on the checked property,
# change score_for_task() appropriately
# (use values 0 to disable scores completely for a given property).
_SCORE_CORRECT_TRUE = 2
_SCORE_CORRECT_FALSE = 1
_SCORE_UNKNOWN = 0
_SCORE_WRONG_FALSE = -16
_SCORE_WRONG_TRUE = -32

def _expected_result(filename, checked_properties):
    results = []
    for (filename_part, (expected_result, for_properties)) in _FILE_RESULTS.items():
        if filename_part in filename \
                and for_properties.intersection(checked_properties):
            results.append(expected_result)
    if not results:
        # No expected result for any of the properties
        return None
    if len(results) > 1:
        # Multiple checked properties per file not supported
        return None
    return results[0]

def properties_of_file(propertyfile):
    """
    Return a list of property names that should be checked according to the given property file.
    @param propertyfile: None or a file name of a property file.
    @return: A possibly empty list of property names.
    """
    assert os.path.isfile(propertyfile)

    with open(propertyfile) as f:
        content = f.read().strip()
    if not( 'CHECK' in content
            or content == 'OBSERVER AUTOMATON'
            or content == 'SATISFIABLE'
            ):
        sys.exit('File "{0}" is not a valid property file.'.format(propertyfile))

    properties = []
    # TODO: should we switch to regex or line-based reading?
    for substring, status in _PROPERTY_NAMES.items():
        if substring in content:
            properties.append(status)

    if not properties:
        sys.exit('File "{0}" does not contain a known property.'.format(propertyfile))
    return properties

def satisfies_file_property(filename, properties):
    """
    Tell whether the given property is violated or satisfied in a given file.
    @param filename: The file name of the input file.
    @param properties: The list of properties to check (as returned by properties_of_file()).
    @return True if the property is satisfied; False if it is violated; None if it is unknown
    """
    expected_result = _expected_result(filename, properties)
    if not expected_result:
        return None
    expected_result_class = get_result_classification(expected_result)
    if expected_result_class == RESULT_CLASS_TRUE:
        return True
    if expected_result_class == RESULT_CLASS_FALSE:
        return False
    return None

def score_for_task(filename, properties, category, result):
    """
    Return the possible score of task, depending on whether the result is correct or not.
    Pass category=result.CATEGORY_CORRECT and result=None to calculate the maximum possible score.
    """
    if category != CATEGORY_CORRECT and category != CATEGORY_WRONG:
        return 0
    if _PROP_SAT in properties:
        return 0

    correct = (category == CATEGORY_CORRECT)
    expected = satisfies_file_property(filename, properties)
    if expected is None:
        return 0
    elif expected == True:
        # expected result is "true", result was "true" or "false"
        return _SCORE_CORRECT_TRUE if correct else _SCORE_WRONG_FALSE
    elif expected == False:
        if correct:
            # expected result is "false", result was "false" with correct property
            return _SCORE_CORRECT_FALSE
        else:
            assert result, "Cannot compute score without actual tool result"
            result_class = get_result_classification(result)
            if result_class == RESULT_CLASS_TRUE:
                # expected result is "false", result was "true"
                return _SCORE_WRONG_TRUE
            elif result_class == RESULT_CLASS_FALSE:
                # expected result is "false", result was "false" but with wrong property
                return _SCORE_WRONG_FALSE
            else:
                assert False, "unexpected result classification " + result_class + " for result " + result

        return _SCORE_CORRECT_FALSE if correct else _SCORE_WRONG_TRUE
    else:
        assert False, "unexpected return value from satisfies_file_property: " + expected

def _file_is_java(filename):
    # Java benchmarks have as filename their main class, so we cannot check for '.java'
    return '_assert' in filename

def get_result_classification(result):
    '''
    Classify the given result into "true" (property holds),
    "false" (property does not hold), "unknown", and "error".
    @param result: The result given by the tool (needs to be one of the RESULT_* strings to be recognized).
    @return One of RESULT_CLASS_* strings
    '''
    if result not in RESULT_LIST:
        return RESULT_CLASS_ERROR

    if result == RESULT_UNKNOWN:
        return RESULT_CLASS_UNKNOWN

    if result == RESULT_TRUE_PROP or result == RESULT_SAT:
        return RESULT_CLASS_TRUE
    else:
        return RESULT_CLASS_FALSE

def get_result_category(filename, result, properties):
    '''
    This function determines the relation between actual result and expected result
    for the given file and properties.
    @param filename: The file name of the input file.
    @param result: The result given by the tool (needs to be one of the RESULT_* strings to be recognized).
    @param properties: The list of properties to check (as returned by properties_of_file()).
    @return One of the CATEGORY_* strings.
    '''
    assert set(properties).issubset(_VALID_RESULTS_PER_PROPERTY.keys())

    if result not in RESULT_LIST:
        return CATEGORY_ERROR

    if result == RESULT_UNKNOWN:
        return CATEGORY_UNKNOWN

    if _file_is_java(filename) and not properties:
        # Currently, no property files for checking Java programs exist,
        # so we hard-code a check for _PROP_ASSERT for these
        properties = [_PROP_ASSERT]

    if not properties:
        # Without property we cannot return correct or wrong results.
        return CATEGORY_MISSING

    expected_result = _expected_result(filename, properties)
    if not expected_result:
        # filename gives no hint on the expected output
        return CATEGORY_MISSING

    for prop in properties:
        if result in _VALID_RESULTS_PER_PROPERTY[prop]:
            # tool returned an answer for this property
            return CATEGORY_CORRECT if expected_result == result else CATEGORY_WRONG

    # tool returned an answer that does not belong to any of the checked properties
    return CATEGORY_UNKNOWN


from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField, IntegerField
from wtforms.validators import DataRequired

from app.models import Menu

class OrderForm(FlaskForm):
    order_name = StringField('order_name', validators=[DataRequired()])
    phone = StringField('phone', validators=[DataRequired()])
    adress = StringField('adress', validators=[DataRequired()])
    dish1 = SelectField(default=1)
    dish2 = SelectField(default=1)
    dish3 = SelectField(default=1)
    dish4 = SelectField(default=1)
    dish5 = SelectField(default=1)
    amount = IntegerField()
    submit1 = SubmitField('Сделать заказ', validators=[DataRequired()])

    def __init__(self, *args, **kwargs):
        super(OrderForm, self).__init__(*args, **kwargs)
        self.dish1.choices = [(c.id, c.name) for c in Menu.query.all()]
        self.dish2.choices = [(c.id, c.name) for c in Menu.query.all()]
        self.dish3.choices = [(c.id, c.name) for c in Menu.query.all()]
        self.dish4.choices = [(c.id, c.name) for c in Menu.query.all()]
        self.dish5.choices = [(c.id, c.name) for c in Menu.query.all()]

class OrderSatus(FlaskForm):
    search = StringField('search')
    submit = SubmitField('Поиск', validators=[DataRequired()])

    def __init__(self, *args, **kwargs):
        super(OrderSatus, self).__init__(*args, **kwargs)


import sys
input = sys.stdin.readline
#########################################
t = int(input())

for _ in range(t):
    n, m = map(int, input().split())

    input_data = [list(map(int, input().split())) for __ in range(n)]

    # 행의 합과 열의 누적합을 저장하는 리스트
    sum_h = [0 for _ in range(n)]
    sum_v = [0 for _ in range(n)]

    # 행과 열의 누적합 저장
    for i in range(n):
        for j in range(n):
            sum_h[i] += input_data[j][i]
            sum_v[i] += input_data[i][j]

    # 연산 적용
    for ___ in range(m):
        r1, c1, r2, c2, v = map(int, input().split())

        # 행에 누적합 계산
        for i in range(r1-1, r2):
            sum_v[i] += v * (c2 - c1 + 1)

        # 열에 누적합 계산
        for i in range(c1-1, c2):
            sum_h[i] += v * (r2 - r1 + 1)

    # 값 출력
    for i in sum_v:
        print(i, end = " ")
    print()

    for i in sum_h:
        print(i, end = " ")
    print()


from project_management.clickup import util
from project_management.clickup.entities.clickup_folder import ClickupFolder
from project_management.clickup.entities.clikup_tasklist import ClickupTasklist
from project_management.clickup.entities.clickup_task import ClickupTask
import json

class ClickupApi:
    def folder(self, context, params):
        '''gets a folder'''

        url = f"https://api.clickup.com/api/v2/folder/{params['folder_id']}"

        response = util.rest("GET", url, context=context)

        folder_obj = json.loads(response.text)

        folder = ClickupFolder(
            space_id=folder_obj['space']['id'],
            folder_name=folder_obj['name'],
            folder_id=folder_obj['id'],
            is_archived=folder_obj['archived'],
            task_count=folder_obj['task_count'],
        )

        return folder.__dict__

    def tasklist(self, context, params):
        '''gets a tasklist'''

        url = f"https://api.clickup.com/api/v2/list/{params['tasklist_id']}"
        response = util.rest("GET", url, context=context)

        tasklist_obj = json.loads(response.text)

        tasklist = ClickupTasklist(
            folder_id=tasklist_obj['folder']['id'],
            priority=tasklist_obj['priority'],
            assignee_to=tasklist_obj['assignee'],
            due_date=tasklist_obj['due_date'],
            id=tasklist_obj['id'],
            name=tasklist_obj['name'],
        )

        return tasklist.__dict__

    def task(self, context, params):
        '''get a task'''

        url = f"https://api.clickup.com/api/v2/task/{params['task_id']}"
        response = util.rest("GET", url, context=context)

        task_obj = json.loads(response.text)
        task = ClickupTask(
            due_date=task_obj['due_date'],
            list_id=task_obj['list']['id'],
            tag=task_obj['tags'],
            id=task_obj['id'],
            name=task_obj['name'],
            description=task_obj['description'],
            task_id=task_obj['id'],
            assigned_to=task_obj['assignees'],
        )

        return task.__dict__

    def tasks(self, context, params):
        '''get list of task in list or team '''

        if params.get('list_id'):
            url = f"https://api.clickup.com/api/v2/list/{params['list_id']}/task"
        else:
            url = f"https://api.clickup.com/api/v2/team/{params['team_id']}/task"

        response = util.rest("GET", url, context=context)

        task_list = json.loads(response.text)['tasks']

        tasks = []

        for task_obj in task_list:
            task = ClickupTask(
                due_date=task_obj['due_date'],
                list_id=task_obj['list']['id'],
                tag=task_obj['tags'],
                id=task_obj['id'],
                name=task_obj['name'],
                description=task_obj['description'],
                task_id=task_obj['id'],
                assigned_to=task_obj['assignees'],
            )
            tasks.append(task.__dict__)

        return json.dumps(tasks)

    def profile(self, context, payload):
        url = "https://api.clickup.com/api/v2/user"
        response_data = util.rest("GET", url, context=context)
        response = response_data.json()['user']
        profile = {
            'id':response['id'],
            'email':response['email'],
            'name':response['username']
        }
        return profile, response_data.status_code

    def verify(self, context, payload):
        url = "https://api.clickup.com/api/v2/team"
        response_data = util.rest("GET", url, context=context)
        response = response_data.json()
        return response, response_data.status_code