import socket
import time

from io import BytesIO
from helpers import *
from random import randint
from block import Block
from tx import Tx

TX_DATA_TYPE = 1
BLOCK_DATA_TYPE = 2
FILTERED_BLOCK_DATA_TYPE = 3
COMPACT_BLOCK_DATA_TYPE = 4

NETWORK_MAGIC = b'\xf9\xbe\xb4\xd9'
TESTNET_NETWORK_MAGIC = b'\x0b\x11\x09\x07'

class NetworkEnvelope:
    def __init__(self, command, payload, testnet=False):
        self.command = command
        self.payload = payload
        if testnet:
            self.magic = TESTNET_NETWORK_MAGIC
        else:
            self.magic = NETWORK_MAGIC

    def __repr__(self):
        return '{}: {}'.format(self.command.decode('ascii'), self.payload.hex())

    @classmethod
    def parse(cls, s, testnet=False):

        #this is the point where code is halted as long there's nothing to read
        magic = s.read(4)
        if magic == b'':
            raise RuntimeError('Connection reset!')
        if testnet:
            expected_magic = TESTNET_NETWORK_MAGIC
        else:
            expected_magic = NETWORK_MAGIC
        if magic != expected_magic:
            raise RuntimeError('magic is not right {} vs {}'.format(magic.hex(), expected_magic.hex()))

        cmd = s.read(12)
        cmd = cmd.decode('utf-8').rstrip('\x00').encode()
        p_length = little_endian_to_int(s.read(4))
        checksum = s.read(4)
        payload = s.read(p_length)

        # verify checksum
        if not hash256(payload)[0:4] == checksum:
            raise RuntimeError('Bad Checksum!')

        return cls(cmd, payload)

    def serialize(self):
        '''Returns the byte serialization of the entire network message'''
        # add the network magic
        result = self.magic
        result += self.command + (12 - len(self.command)) * b'\x00'
        result += int_to_little_endian(len(self.payload), 4)
        result += hash256(self.payload)[0:4]
        result += self.payload

        return result

    def stream(self):
        return BytesIO(self.payload)

class VersionMessage:
    command = b'version'

    def __init__(self, version=70015, services=0, timestamp=None,
                 receiver_services=0,
                 receiver_ip=b'\x00\x00\x00\x00', receiver_port=8333,
                 sender_services=0,
                 sender_ip=b'\x00\x00\x00\x00', sender_port=8333,
                 nonce=None, user_agent=b'/bitcoingraffiti:0.1/',
                 latest_block=0, relay=False):
        self.version = version
        self.services = services
        if timestamp is None:
            self.timestamp = int(time.time())
        else:
            self.timestamp = timestamp
        self.receiver_services = receiver_services
        self.receiver_ip = receiver_ip
        self.receiver_port = receiver_port
        self.sender_services = sender_services
        self.sender_ip = sender_ip
        self.sender_port = sender_port
        if nonce is None:
            self.nonce = int_to_little_endian(randint(0, 2**64), 8)
        else:
            self.nonce = nonce
        self.user_agent = user_agent
        self.latest_block = latest_block
        self.relay = relay

    @classmethod
    def parse(cls, s):
        version = little_endian_to_int(s.read(4))
        services = little_endian_to_int(s.read(8))
        timestamp = little_endian_to_int(s.read(8))
        receiver_services = little_endian_to_int(s.read(8))
        receiver_ip = s.read(16)
        receiver_port = s.read(2)
        sender_services = little_endian_to_int(s.read(8))
        sender_ip = s.read(16)
        sender_port = s.read(2)
        nonce = s.read(8)
        user_agent_length = read_varint(s)
        user_agent = s.read(user_agent_length)
        latest_block = little_endian_to_int(s.read(4))
        relay = True if s.read(1) == b'\x01' else False

        print('Peer Version:', version, 'Services', services, bin(services))

        return cls(version, services, timestamp,
                 receiver_services,
                 receiver_ip, receiver_port,
                 sender_services,
                 sender_ip, sender_port,
                 nonce, user_agent,
                 latest_block, relay)

    def serialize(self):
        '''Serialize this message to send over the network'''
        ipv4 = 10 * b'\x00' + 2* b'\xff'

        result = int_to_little_endian(self.version, 4)
        result += int_to_little_endian(self.services, 8)
        result += int_to_little_endian(self.timestamp, 8)
        result += int_to_little_endian(self.receiver_services, 8)
        result += ipv4 + self.receiver_ip
        result += self.receiver_port.to_bytes(2, 'big')
        result += int_to_little_endian(self.sender_services, 8)
        result += ipv4 + self.sender_ip
        result += self.sender_port.to_bytes(2, 'big')
        result += self.nonce + (8 - len(self.nonce)) * b'\x00'
        result += encode_varint(len(self.user_agent))
        result += self.user_agent
        result += int_to_little_endian(self.latest_block, 4)

        '''relay is necessary for letting peer know to send only bloomfilter messages'''
        if self.relay:
            result += b'x\01'
        else:
            result += b'\x00'
        return result

class VerAckMessage:
    command = b'verack'

    def __init__(self):
        pass

    @classmethod
    def parse(cls, s):
        return cls()

    def serialize(self):
        return b''

class PingMessage:
    command = b'ping'

    def __init__(self, nonce):
        self.nonce = nonce

    @classmethod
    def parse(cls, s):
        nonce = s.read(8)
        return cls(nonce)

    def serialize(self):
        return self.nonce

class PongMessage:
    command = b'pong'

    def __init__(self, nonce):
        self.nonce = nonce

    def parse(cls, s):
        nonce = s.read(8)
        return cls(nonce)

    def serialize(self):
        return self.nonce

class GetAddressMessage:
    command = b'getaddr'

    def __init__(self):
        pass

    @classmethod
    def parse(cls, s):
        return cls()

    def serialize(self):
        return b''

class AddressMessage:
    command = b'addr'

    def __init__(self, count, addr_list):
        self.count = count
        self.addr_list = addr_list

    def __repr__(self):
        return 'Number of addresses: {}\n {}'.format(self.count, self.addr_list)

    @classmethod
    def parse(cls, s):
        count = read_varint(s)
        addr_list = []

        for addr in range(count):
          addr_list.append(NetAddress.parse(s))
          #

        return cls(count, addr_list)

    def serialize(self):
        raise NotImplementedError('Serialization not yet implemented!')

class GetHeadersMessage:
    '''Request Headers'''
    '''To request more headers, you can insert the last hash as a new startblock and repeat
        as startblock is not included in the search'''
    command = b'getheaders'

    def __init__(self, version=70015, num_hashes=1,
        start_block=None, end_block=None):
        self.version = version
        self.num_hashes = num_hashes
        if start_block is None:
            raise RuntimeError('a start block is required')
        self.start_block = start_block
        if end_block is None:
            self.end_block = b'\x00' * 32
        else:
            self.end_block = end_block

    def serialize(self):
        '''Serialize this message to send over the network'''
        result = int_to_little_endian(self.version, 4)
        result += encode_varint(self.num_hashes)
        result += self.start_block[::-1]
        result += self.end_block[::-1]
        return result

class HeadersMessage:
    '''Receive Headers'''
    command = b'headers'

    def __init__(self, blocks):
        self.blocks = blocks

    @classmethod
    def parse(cls, stream):
        num_headers = read_varint(stream)
        blocks = []
        for _ in range(num_headers):
            blocks.append(Block.parse(stream))
            num_txs = read_varint(stream)
            if num_txs != 0:
                raise RuntimeError('number of txs not 0')
        return cls(blocks)

class FeefilterMessage:
    '''Receive Feefilter'''
    '''This is the minimum fee per sats/1kb'''
    command = b'feefilter'

    def __init__(self, fee):
        self.fee = fee

    @classmethod
    def parse(cls, s):
        fee = little_endian_to_int(s.read(8))
        print('Feefilter: minimum fee is:', fee, 'satoshis')
        return cls(fee)

class MempoolMessage:
    '''Request mempool transactions hashes'''
    '''Response is an inv message'''
    command = b'mempool'

    def __init__(self):
        pass

    def serialize(self):
        return b''

class CmpctMessage:
    '''Request mempool transactions hashes'''
    '''Response is an inv message'''
    command = b'sendcmpct'

    def __init__(self, announce, version):
        self.announce = announce
        self.version = version

    def __repr__(self):
        return '\nAnnounce: {}\nVersion: {}\n'.format(self.announce, self.version)

    @classmethod
    def parse(cls, s):
        announce = little_endian_to_int(s.read(1))
        version = little_endian_to_int(s.read(8))

        return cls(announce, version)

    def serialize(self):
        raise NotImplementedError()

class GetDataMessage:
    command = b'getdata'

    def __init__(self):
        self.data = []

    def add_data(self, data_type, identifier):
        self.data.append((data_type, identifier))

    def serialize(self):
        result = encode_varint(len(self.data))
        # loop through each tuple (data_type, identifier) in self.data
        for data_type, identifier in self.data:
            # data type is 4 bytes Little-Endian
            result += int_to_little_endian(data_type, 4)
            # identifier needs to be in Little-Endian
            result += identifier[::-1]
        return result

class InvMessage:
    '''Receive Inv'''
    '''Inventory Vectors with data'''
    command = b'inv'

    def __init__(self, count, inventory):
        self.count = count
        self.inventory = inventory

    def __repr__(self):
        return '\nCount: {}\n{}'.format(self.count, self.inventory)

    @classmethod
    def parse(cls, s):
        count = read_varint(s)
        inventory = []

        for _ in range(count):
            inventory.append(InventoryVector.parse(s))

        return cls(count, inventory)

    def serialize(self):
        raise NotImplementedError('Serialization not yet implemented!')

class RejectMessage:
    '''Receive Inv'''
    '''Inventory Vectors with data'''
    command = b'reject'

    def __init__(self, message, ccode, reason, data):
        self.message = message
        self.ccode = ccode
        self.reason = reason
        self.data = data

    def __repr__(self):
        return '\nCode: {}\nMessage: {}\nReason: {}\n'.format(self.ccode, self.message, self.reason)

    @classmethod
    def parse(cls, s):
        message_length = read_varint(s)
        message = s.read(message_length)
        ccode = REJECT_CODE_NAMES[little_endian_to_int(s.read(1))]
        reason_length = read_varint(s)
        reason = s.read(reason_length)
        data = None #perhaps able to parse this out

        return cls(message, ccode, reason, data)

    def serialize(self):
        raise NotImplementedError('Serialization not yet implemented!')

class GenericMessage:
    def __init__(self, command, payload):
        self.command = command
        self.payload = payload

    def serialize(self):
        return self.payload

class SimpleNode:

    def __init__(self, host, port=None, testnet=False, logging=False):
        if port is None:
            if testnet:
                port = 18333
            else:
                port = 8333
        self.testnet = testnet
        self.logging = logging
        # connect to socket
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect((host, port))
        # create a stream that we can use with the rest of the library
        self.stream = self.socket.makefile('rb', None)

    def handshake(self):
        '''Do a handshake with the other node.
        Handshake is sending a version message and getting a verack back.'''
        version = VersionMessage()
        self.send(version)
        self.wait_for(VerAckMessage, VersionMessage)

    def getAddressesFromHost(self):
        ''' Get peers from host'''
        getaddress = GetAddressMessage()
        self.send(getaddress)
        address = self.wait_for(AddressMessage)
        print(address.addr_list)

    def getHeadersFromBlock(self, sb, eb=None):
        '''gets headers from start block till current block'''
        headers = []

        while len(headers) % 2000 == 0:
            self.send(GetHeadersMessage(start_block=sb, end_block=eb))
            headers += self.wait_for(HeadersMessage).blocks
            sb = headers[-1].hash()

        if (self.logging):
            print('Headers retrieved:', len(headers))

        return headers

    def send(self, message):
        '''Send a message to the connected node'''
        envelope = NetworkEnvelope(message.command, message.serialize(), testnet=self.testnet)

        if self.logging:
            print('sending: {}'.format(envelope))

        if message.command == b'tx':
            print('txID:', message.id())

        self.socket.sendall(envelope.serialize())

    def read(self):
        '''Read a message from the socket'''
        envelope = NetworkEnvelope.parse(self.stream, testnet=self.testnet)
        if self.logging:
            print('receiving: {}'.format(envelope))
        return envelope

    def wait_for(self, *message_classes):
        '''Wait for one of the messages in the list'''
        # initialize the command we have, which should be None
        command = None
        command_to_class = {m.command: m for m in message_classes}
        # loop until the command is in the commands we want
        while command not in command_to_class.keys():

            # get the next network message
            # this is also a halt on the code!!!
            envelope = self.read()

            # set the command to be evaluated
            command = envelope.command
            # we know how to respond to version and ping, handle that here
            if command == VersionMessage.command:
                # send verack
                self.send(VerAckMessage())
            elif command == PingMessage.command:
                # send pong
                self.send(PongMessage(envelope.payload))
            elif command == FeefilterMessage.command:
                pass
                # send pong
        # return the envelope parsed as a member of the right message class
        return command_to_class[command].parse(envelope.stream())

## Other Classes ##
class NetAddress:
    def __init__(self, time, services, ipv, port):
      self.time = time
      self.services = services
      self.ipv = ipv
      self.port = port

    def __repr__(self):
        return '\nTime: {}\nServices: {}\nipv: {}\nport: {}\n'.format(
          self.time, self.services, bytes_to_ip(self.ipv[-4:]), int.from_bytes(self.port, 'big')
        )

    @classmethod
    def parse(cls, s):
        time = little_endian_to_int(s.read(4))
        services = little_endian_to_int(s.read(8))
        ipv = s.read(16)
        port = s.read(2)

        return cls(time, services, ipv, port)

    def serialize(self):
        raise NotImplementedError('Serialization not yet implemented!')

class InventoryVector:
    def __init__(self, obj_type, obj_hash):
      self.obj_type = obj_type
      self.obj_hash = obj_hash

    def __repr__(self):
        return '\n{}: {}'.format(self.type_lookup(), self.obj_hash)

    @classmethod
    def parse(cls, s):
        obj_type = little_endian_to_int(s.read(4))
        obj_hash = s.read(32)[::-1].hex()

        return cls(obj_type, obj_hash)

    def serialize(self):
        raise NotImplementedError('Serialization not yet implemented!')

    def type_lookup(self):
        if self.obj_type == 0:
            return 'ERROR'
        elif self.obj_type == 1:
            return 'MSG_TX'
        elif self.obj_type == 2:
            return 'MSG_BLOCK'
        elif self.obj_type == 3:
            return 'MSG_FILTERED_BLOCK'
        elif self.obj_type == 4:
            return 'MSG_CMPCT_BLOCK'
        elif self.obj_type == 0x40000001:
            return 'MSG_WITNESS_TX'
        elif self.obj_type == 0x40000002:
            return 'MSG_WITNESS_BLOCK'
        elif self.obj_type == 0x40000003:
            return 'MSG_FILTERED_WITNESS_BLOCK'
        else:
            raise ValueError('Unknown InventoryVector data type')

REJECT_CODE_NAMES = {
    0x01: 'REJECT_MALFORMED',
    0x10: 'REJECT_INVALID',
    0x11: 'OBSOLETE',
    0x12: 'REJECT_DUPLICATE',
    0x40: 'REJECT_NONSTANDARD',
    0x41: 'REJECT_DUST',
    0x42: 'REJECT_INSUFFICIENT_FEE',
    0x43: 'REJECT_CHECKPOINT',
}


import argparse
import h5py
import neuropacks as packs
import numpy as np

def main(args):
    # Tag for the experiment
    tag = args.tag
    # Folder containing the model fits
    fit_folder = args.fit_folder
    # Folder containing the batch scripts
    batch_folder = args.batch_folder
    # Folder containing the outputs
    output_folder = args.output_folder
    # Folder containing the outputs
    script_path = args.script_path
    # Path to neural data
    data_path = args.data_path
    dataset = args.dataset

    # NERSC parameters
    n_nodes = args.n_nodes
    n_tasks = args.n_tasks
    n_batch_scripts = args.n_batch_scripts
    time = args.time
    qos = args.qos

    # Experiment configuration
    model_fit = args.model_fit
    # Create hyperparameters for CV fitting
    n_coupling_lambdas = args.n_coupling_lambdas
    coupling_lambdas = np.logspace(args.coupling_lambda_lower,
                                   args.coupling_lambda_upper,
                                   num=n_coupling_lambdas)
    n_tuning_lambdas = args.n_tuning_lambdas
    tuning_lambdas = np.logspace(args.tuning_lambda_lower,
                                 args.tuning_lambda_upper,
                                 num=n_tuning_lambdas)
    Ks = np.arange(args.max_K) + 1

    # Handle dataset
    if dataset == 'pvc11':
        pack = packs.PVC11(data_path=data_path)
        # Get design matrix and stimuli
        X = pack.get_design_matrix(form='cosine2')
        Y = pack.get_response_matrix(transform='square_root')
    elif dataset == 'ecog':
        raise NotImplementedError()

    # Get number of jobs and batch scripts
    n_jobs = Y.shape[1]
    n_jobs_per_batch = int(np.ceil(n_jobs / n_batch_scripts))

    # Header of batch script
    def batch_header(out):
        return (
            "#!/bin/bash\n"
            f"#SBATCH -N {n_nodes}\n"
            "#SBATCH -C haswell\n"
            f"#SBATCH -q {qos}\n"
            "#SBATCH -J nb\n"
            f"#SBATCH --output={output_folder}/{out}_out.o\n"
            f"#SBATCH --error={output_folder}/{out}_error.o\n"
            "#SBATCH --mail-user=pratik.sachdeva@berkeley.edu\n"
            "#SBATCH --mail-type=ALL\n"
            f"#SBATCH -t {time}\n"
            f"#SBATCH --image=docker:pssachdeva/neuro:latest\n\n"
            "export OMP_NUM_THREADS=1\n\n")

    job_counter = 0
    batch_counter = 0

    for job in range(n_jobs):
        # Save path for current experiment
        save_path = f"{fit_folder}/{tag}_{dataset}_{job}.h5"
        # Load the model configuration
        with h5py.File(save_path, 'w') as params:
            params['X'] = X
            params['Y'] = np.delete(Y, job, axis=1)
            params['y'] = Y[:, job][..., np.newaxis]
            # Training hyperparameters
            params['Ks'] = Ks
            params['coupling_lambdas'] = coupling_lambdas
            params['tuning_lambdas'] = tuning_lambdas
            # Training settings
            params.attrs['cv'] = args.cv
            params.attrs['fine_sweep_frac'] = args.fine_sweep_frac
            params.attrs['solver'] = args.solver
            params.attrs['initialization'] = args.initialization
            params.attrs['max_iter'] = args.max_iter
            params.attrs['tol'] = args.tol
        # Create SBATCH command
        command = (
            f"srun -n {n_tasks} -c $OMP_NUM_THREADS shifter python "
            f"{script_path} --file_path={save_path} "
            f"--model_fit={model_fit} &\n"
        )

        # If we have reset the job counter, create a new batch script
        if job_counter == 0:
            batch_script = batch_header(f"{tag}_{batch_counter}")
            batch_path = f"{batch_folder}/{tag}_{batch_counter}.sh"
            batch_counter += 1

        batch_script += command
        job_counter += 1
        if job_counter % args.n_simultaneous:
            command += "wait\n"
        # If we're at the last counter, write file
        if job_counter == n_jobs_per_batch:
            with open(batch_path, 'w') as batch:
                batch.write(batch_script)
            # Reset job counter
            job_counter = 0

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Run CV solver on triangular model.')
    # Required arguments
    parser.add_argument('--tag', type=str)
    parser.add_argument('--fit_folder', type=str)
    parser.add_argument('--batch_folder', type=str)
    parser.add_argument('--output_folder', type=str)
    parser.add_argument('--script_path', type=str)
    parser.add_argument('--data_path', type=str)
    # NERSC arguments
    parser.add_argument('--n_nodes', type=int, default=64)
    parser.add_argument('--n_tasks', type=int, default=32)
    parser.add_argument('--n_batch_scripts', type=int, default=100)
    parser.add_argument('--n_simultaneous', type=int, default=50)
    parser.add_argument('--time', type=str, default='00:30:00')
    parser.add_argument('--qos', type=str, default='debug')
    # Fixed model hyperparameters
    parser.add_argument('--model_fit', type=str, default='em')
    # CV fitting hyperparameters
    parser.add_argument('--n_coupling_lambdas', type=int, default=25)
    parser.add_argument('--coupling_lambda_lower', type=float, default=-7)
    parser.add_argument('--coupling_lambda_upper', type=float, default=-2)
    parser.add_argument('--n_tuning_lambdas', type=int, default=25)
    parser.add_argument('--tuning_lambda_lower', type=float, default=-7)
    parser.add_argument('--tuning_lambda_upper', type=float, default=-2)
    parser.add_argument('--fine_sweep_frac', type=float, default=0.1)
    parser.add_argument('--max_K', type=int, default=1)
    parser.add_argument('--cv', type=int, default=3)
    # Fitter arguments
    parser.add_argument('--solver', default='ow_lbfgs')
    parser.add_argument('--initialization', default='fits')
    parser.add_argument('--max_iter', type=int, default=500)
    parser.add_argument('--tol', type=float, default=1e-8)
    # Random seeds
    parser.add_argument('--fitter_rng', type=int, default=-1)
    args = parser.parse_args()

    main(args)


from tech_news.database import search_news
from datetime import datetime

# Requisito 6
def search_by_title(title):
    titles = []
    title_url = search_news({"title": {"$regex": title, "$options": "i"}})

    for itens in title_url:
        titles.append((itens["title"], itens["url"]))

    return titles

# Requisito 7
def search_by_date(date):
    news_by_date = []
    try:
        date_str = datetime.strptime(date, "%Y-%m-%d").strftime("%d/%m/%Y")
        results = search_news({"timestamp": date_str})
    except ValueError:
        raise ValueError("Data inválida")
    else:
        for itens in results:
            news_by_date.append((itens["title"], itens["url"]))
        return news_by_date

# Requisito 8
def search_by_tag(tag):
    tags = []
    results = search_news({"tags": {"$regex": tag, "$options": "i"}})
    for itens in results:
        tags.append((itens["title"], itens["url"]))

    return tags

# Requisito 9
def search_by_category(category):
    categories = []
    results = search_news({"category": {"$regex": category, "$options": "i"}})
    for itens in results:
        categories.append((itens["title"], itens["url"]))
    return categories


"""
Classification Functions

Peter Turney, October 10, 2020
"""
import golly as g
import numpy as np
import random as rand
import csv
import math
import classification_parameters as cparams
#
# define a function for geometric mean of x and 1-x
#
def geo_mean(x):
  """
  We assume x is a number between 0 and 1, representing
  a probability. The goal here is to reward a probability
  near 0.5 and punish a probability near 0.0 or 1.0. To do
  this, we calculate the geometric mean of x and 1-x.
  """
  assert isinstance(x, float)
  assert x >= 0.0
  assert x <= 1.0
  return math.sqrt(x * (1.0 - x))
#
# define a function for the complexity of a rule
#
def complexity(rule):
  """
  We assume the rule is a semi-totalistic (outer-totalistic) rule,
  such as "B3/S23". Every rule must contain "B", "S", and "/". Note
  that numbers are not required in all rules. For example, "B2/S"
  means every living cell dies every generation. We subtract 2 from
  the length of the rule, because the "B" and "S" are not strictly
  required to specify the rule. However, we need "/", for example,
  to distinguish "2/3" from "23/".
  """
  #
  # for rules of the form "B0..."
  #
  # B0 rules are more complex than BZ rules, although this
  # is not apparent from their length
  #
  complexity_BZ = cparams.complexity_BZ
  #
  # for rules of the form "BN..." where N > 0
  #
  complexity_BN = cparams.complexity_BN
  #
  assert isinstance(rule, str)
  #
  if (rule[1] == "0"):
    complexity = float(len(rule) + complexity_BZ)
  else:
    complexity = float(len(rule) + complexity_BN)
  #
  return complexity
#
# all_BS_rules() -- returns a list of all possible B/S rules (born/survive)
#
def all_BS_rules():
  """
  Make a list of all possible B/S rules (born/survive)
  - https://www.conwaylife.com/wiki/Rulestring#B.2FS_notation
  - there are 2^18 = 262,144 possible B/S rules
  - the Game of Life is "B3/S23" (born if 3 live neighbours / survive if 2 or 3)
  - the null rule "B/S" is legal, as is "B1/S" or "B/S1"
  - Golly supports all 262,144 of these rules
  """
  #
  num_rules = 2 ** 18
  rule_list = []
  #
  for rule_num in range(num_rules):
    # convert rule_num to a binary string with 18 characters
    # e.g. 14 --> '000000000000001110'
    binary_string = format(rule_num, '018b')
    # the binary string '111111111111111111' yields the rule
    # 'B012345678/S012345678' -- if there are any 0 values
    # in the binary string, then we delete the corresponding
    # number from the rule 'B012345678/S012345678'
    born = binary_string[0:9] # first 9 bits in binary_string
    survive = binary_string[9:18] # last 9 bits in binary_string
    # born
    rule = "B"
    for pos in range(9):
      if (born[pos] == '1'):
        rule = rule + str(pos)
    # survive
    rule = rule + "/S"
    for pos in range(9):
      if (survive[pos] == '1'):
        rule = rule + str(pos)
    # append the new rule to rule_list
    rule_list.append(rule)
  #
  return rule_list
#
# tsv_BS_rules(rule_file_name) -- load B/S rules from a tsv file
#
def tsv_BS_rules(rule_file_name):
  """
  Load a list of B/S rules from a file. We assume the file is a
  tab-separated value (tsv) file with the B/S rule in the second
  column (column number 1, starting from 0).
  """
  #
  rule_list = []
  #
  with open(rule_file_name) as tsvfile:
    reader = csv.reader(tsvfile, delimiter = '\t')
    for row in reader:
      rule = row[1] # extract second column from row
      rule_list.append(rule)
  #
  return rule_list
#
# tsv_BS_rule_cpu(rule_file_name, current_cpu_id)
# -- load B/S rules with associated CPUs
#
def tsv_BS_rule_cpu(rule_file_name, current_cpu_id):
  """
  Load a list of B/S rules from a file. We assume the file is a
  tab-separated value (tsv) file with the B/S rule in the first
  column and a CPU number in the second column: "B3/S368\tCPU5"
  """
  #
  rule_list = []
  #
  with open(rule_file_name) as tsvfile:
    reader = csv.reader(tsvfile, delimiter = '\t')
    for row in reader:
      rule = row[0]
      cpu = row[1]
      if (("CPU" + str(current_cpu_id)) == cpu):
        rule_list.append(rule)
  #
  return rule_list
#
# txt_BS_rules(rule_file_name) -- load B/S rules from a txt file
#
def txt_BS_rules(rule_file_name):
  """
  Load a list of B/S rules from a file. We assume the file is a
  plain text file with one B/S rule in each line.
  """
  #
  rule_list = []
  rule_handle = open(rule_file_name, "r")
  #
  for rule in rule_handle:
    rule_list.append(rule.strip()) # strip() removes newline character
  #
  return rule_list
#
# show_parameters() -- returns a list of parameters and values
#
def show_parameters():
  """
  Make a list of the parameters in cparams and show
  the value of each parameter.
  """
  parameter_names = sorted(dir(cparams))
  display_list = []
  #
  for name in parameter_names:
    # skip over system names
    # - system names have the form "__file__"
    if (name[0] != "_"):
      value = str(getattr(cparams, name))
      display_list.append(name + " = " + value)
  #
  return display_list
#
# random_sample(rule_list, sample_size) -- returns sample_list
#
def random_sample(rule_list, sample_size):
  """
  Get a random sample of sample_size rules from the rule list.
  """
  #
  # To avoid duplicates in the sample, randomize the order of the
  # rule list and then take the first sample_size rules
  # from the randomized list.
  #
  total_size = len(rule_list)
  assert total_size > sample_size
  assert sample_size > 0
  # attach a random number to each rule in the rule list
  randomized_rule_list = []
  for i in range(total_size):
    # item = [random real number between 0 and 1, the i-th rule]
    item = [rand.uniform(0, 1), rule_list[i]]
    randomized_rule_list.append(item)
  # sort randomized_rule_list in order of the attached random numbers
  randomized_rule_list.sort(key = lambda x: x[0]) # sort by random number
  # take the top sample_size items from randomized_rule_list and
  # remove their attached random numbers
  sample_list = []
  for i in range(sample_size):
    sample_list.append(randomized_rule_list[i][1]) # drop random number
  # return the cleaned-up list of sample_size rules
  return sample_list
#
#
#


import sys

def readDrive(filename: str) -> list:
    readList = list()
    with open(filename, 'r') as readFile:
        stringOfFile = readFile.read().replace('\n', '')
        readList = stringOfFile.split(' ')
    returnList = list()

    for el in readList:
        if el != '-1':
            returnList.append(el)
        else:
            break

    return returnList

def readWholeFile(filename: str) -> list:
    readList = list
    with open(filename, 'r') as readFile:
        stringOfFile = readFile.read().replace('\n', '')
        readList = stringOfFile.split(' ')
    return readList

def modifyEndOfFileList(fileList: list, listToAppend: list) -> list:
    newList = list()
    i = 0
    for l in fileList:
        if l == -1:
            break
        else:
            newList.append(l)

    for element in listToAppend:
        if element != '':
            newList.append(element)

    if len(newList) > 5000:
        return None
    else:
        return newList

def writeDrive(listToWrite: list) -> None:
    print(listToWrite)
    with open("drive", "w+") as driveFile:
        freeMem = 5000
        for i in listToWrite:
            driveFile.write(i + " ")
            freeMem = freeMem - 1
        freeMem = freeMem - 1
        for j in range(freeMem):
            driveFile.write("-1 ")

if __name__ == "__main__":
    argIter = iter(sys.argv)
    next(argIter)
    filenames = list()
    for filename in argIter:
        filenames.append(filename)

    listToAppend = list()

    for f in filenames:
        filenameEncoded = list(filename)
        filenameOrd = ""
        for fencoded in filenameEncoded:
            filenameOrd = filenameOrd + str(ord(fencoded)) + " "

        filenameOrd = filenameOrd + "0 "

        listToAppend.append('1454')
        listToAppend.append(str(len(f) + 1))
        for ford in filenameOrd.split(' '):
            if ford != '':
                listToAppend.append(ford)
        listToAppend.append(str(len(readWholeFile(f))))
        for fileEntry in readWholeFile(f):
            if fileEntry != '':
                listToAppend.append(fileEntry)
        listToAppend.append('-2')

    fileData = readDrive("drive")

    fileData = modifyEndOfFileList(fileData, listToAppend)

    writeDrive(fileData)


import cv2
import numpy as np

# taken from https://stackoverflow.com/a/44659589
def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
    dim = None
    (h, w) = image.shape[:2]

    r = 1

    if not (width or height):
        return image, r

    if height:
        if h <= height:
            return image, r

        r = height / float(h)
        dim = (int(w * r), height)

    else:
        if w <= width:
            return image, r

        r = width / float(w)
        dim = (width, int(h * r))

    resized = cv2.resize(image, dim, interpolation = inter)

    return resized, r

def _read_image(image, max_width, max_height):
    image = cv2.imread(image)
    image, scale = image_resize(image, width=max_width, height=max_height)

    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    image = image.astype('float32')
    mean = np.array([0.485, 0.456, 0.406])
    variance = np.array([0.229, 0.224, 0.225])

    image -= mean * 255
    image /= variance * 255
    return image, scale

def _pad_image_bottom_right(cv2_image, bottom, right, color=[0, 0, 0]):
    return cv2.copyMakeBorder(cv2_image, 0, bottom, 0, right, cv2.BORDER_CONSTANT, value = color)

def read_images(images, max_width, max_height=None):
    images = [_read_image(image, max_width, max_height) for image in images]
    scales = [i[1] for i in images]
    images = [i[0] for i in images]

    shapes = [image.shape for image in images]

    if len(set(shapes)) > 1:
        max_height = max(shapes, key=lambda x: x[0])[0]
        max_width = max(shapes, key=lambda x: x[1])[1]

        images = [_pad_image_bottom_right(image, bottom=max_height - shapes[i][0], right=max_width - shapes[i][1]) for i, image in enumerate(images)]

    images = np.asarray(images)

    return images, scales, shapes

def keras_pred_to_boxes(y_pred, detection_threshold=0.7, text_threshold=0.4, link_threshold=0.4, size_threshold=10, shapes=None, scales=None):
    box_groups = []
    for pred_i, y_pred_cur in enumerate(y_pred):
        # Prepare data
        textmap = y_pred_cur[..., 0].copy()
        linkmap = y_pred_cur[..., 1].copy()

        scale = 1
        if scales:
            scale = scales[pred_i]

        if shapes:
            img_h, img_w = shapes[pred_i][:2]
        else:
            img_h, img_w = textmap.shape

        _, text_score = cv2.threshold(textmap,
                                      thresh=text_threshold,
                                      maxval=1,
                                      type=cv2.THRESH_BINARY)
        _, link_score = cv2.threshold(linkmap,
                                      thresh=link_threshold,
                                      maxval=1,
                                      type=cv2.THRESH_BINARY)
        n_components, labels, stats, _ = cv2.connectedComponentsWithStats(np.clip(
            text_score + link_score, 0, 1).astype('uint8'),
                                                                          connectivity=4)
        boxes = []
        for component_id in range(1, n_components):
            # Filter by size
            size = stats[component_id, cv2.CC_STAT_AREA]

            if size < size_threshold:
                continue

            # If the maximum value within this connected component is less than
            # text threshold, we skip it.
            if np.max(textmap[labels == component_id]) < detection_threshold:
                continue

            # Make segmentation map. It is 255 where we find text, 0 otherwise.
            segmap = np.zeros_like(textmap)
            segmap[labels == component_id] = 255
            segmap[np.logical_and(link_score, text_score)] = 0
            x, y, w, h = [
                stats[component_id, key] for key in
                [cv2.CC_STAT_LEFT, cv2.CC_STAT_TOP, cv2.CC_STAT_WIDTH, cv2.CC_STAT_HEIGHT]
            ]

            # Expand the elements of the segmentation map
            niter = int(np.sqrt(size * min(w, h) / (w * h)) * 2)
            sx, sy = max(x - niter, 0), max(y - niter, 0)
            ex, ey = min(x + w + niter + 1, img_w), min(y + h + niter + 1, img_h)
            segmap[sy:ey, sx:ex] = cv2.dilate(
                segmap[sy:ey, sx:ex],
                cv2.getStructuringElement(cv2.MORPH_RECT, (1 + niter, 1 + niter)))

            # Make rotated box from contour
            contours = cv2.findContours(segmap.astype('uint8'),
                                        mode=cv2.RETR_TREE,
                                        method=cv2.CHAIN_APPROX_SIMPLE)[-2]
            contour = contours[0]
            box = cv2.boxPoints(cv2.minAreaRect(contour))

            # Check to see if we have a diamond
            w, h = np.linalg.norm(box[0] - box[1]), np.linalg.norm(box[1] - box[2])
            box_ratio = max(w, h) / (min(w, h) + 1e-5)

            if abs(1 - box_ratio) <= 0.1:
                l, r = contour[:, 0, 0].min(), contour[:, 0, 0].max()
                t, b = contour[:, 0, 1].min(), contour[:, 0, 1].max()
                box = np.array([[l, t], [r, t], [r, b], [l, b]], dtype=np.float32)
            else:
                # Make clock-wise order
                box = np.array(np.roll(box, 4 - box.sum(axis=1).argmin(), 0))

            boxes.append(2 * box  * (1/scale))

        box_groups.append(boxes)

    return box_groups

def draw_boxes_on_image(image_path, boxes, out_path=None, color=(255, 0, 0), thickness=5):
    if not out_path:
        image_type = image_path.split('.')[-1]
        out_path = '.'.join(image_path.split('.')[:-1]) + '.craft.' + image_type

    image = cv2.imread(image_path)

    for box in boxes:
        cv2.polylines(img=image, pts=box[np.newaxis].astype('int32'), color=color, thickness=thickness, isClosed=True)

    cv2.imwrite(out_path, image)

    return out_path


import pathlib
import subprocess
from textwrap import dedent
from unittest import mock
from unittest.mock import call

import pytest

from snapcraft_legacy.internal.meta.package_repository import (
    PackageRepositoryApt,
    PackageRepositoryAptPpa,
)
from snapcraft_legacy.internal.repo import apt_ppa, apt_sources_manager, errors

@pytest.fixture(autouse=True)
def mock_apt_ppa_get_signing_key():
    with mock.patch(
        "snapcraft_legacy.internal.repo.apt_ppa.get_launchpad_ppa_key_id",
        spec=apt_ppa.get_launchpad_ppa_key_id,
        return_value="FAKE-PPA-SIGNING-KEY",
    ) as m:
        yield m

@pytest.fixture(autouse=True)
def mock_environ_copy():
    with mock.patch("os.environ.copy") as m:
        yield m

@pytest.fixture(autouse=True)
def mock_host_arch():
    with mock.patch(
        "snapcraft_legacy.internal.repo.apt_sources_manager.ProjectOptions"
    ) as m:
        m.return_value.deb_arch = "FAKE-HOST-ARCH"
        yield m

@pytest.fixture(autouse=True)
def mock_run():
    with mock.patch("subprocess.run") as m:
        yield m

@pytest.fixture()
def mock_sudo_write():
    def write_file(*, dst_path: pathlib.Path, content: bytes) -> None:
        dst_path.write_bytes(content)

    with mock.patch(
        "snapcraft_legacy.internal.repo.apt_sources_manager._sudo_write_file"
    ) as m:
        m.side_effect = write_file
        yield m

@pytest.fixture(autouse=True)
def mock_version_codename():
    with mock.patch(
        "snapcraft_legacy.internal.os_release.OsRelease.version_codename",
        return_value="FAKE-CODENAME",
    ) as m:
        yield m

@pytest.fixture
def apt_sources_mgr(tmp_path):
    sources_list_d = tmp_path / "sources.list.d"
    sources_list_d.mkdir(parents=True)

    yield apt_sources_manager.AptSourcesManager(
        sources_list_d=sources_list_d,
    )

@mock.patch("tempfile.NamedTemporaryFile")
@mock.patch("os.unlink")
def test_sudo_write_file(mock_unlink, mock_tempfile, mock_run, tmp_path):
    mock_tempfile.return_value.__enter__.return_value.name = "/tmp/foobar"

    apt_sources_manager._sudo_write_file(dst_path="/foo/bar", content=b"some-content")

    assert mock_tempfile.mock_calls == [
        call(delete=False),
        call().__enter__(),
        call().__enter__().write(b"some-content"),
        call().__enter__().flush(),
        call().__exit__(None, None, None),
    ]
    assert mock_run.mock_calls == [
        call(
            [
                "sudo",
                "install",
                "--owner=root",
                "--group=root",
                "--mode=0644",
                "/tmp/foobar",
                "/foo/bar",
            ],
            check=True,
        )
    ]
    assert mock_unlink.mock_calls == [call("/tmp/foobar")]

def test_sudo_write_file_fails(mock_run):
    mock_run.side_effect = subprocess.CalledProcessError(
        cmd=["sudo"], returncode=1, output=b"some error"
    )

    with pytest.raises(RuntimeError) as error:
        apt_sources_manager._sudo_write_file(
            dst_path="/foo/bar", content=b"some-content"
        )

    assert (
        str(error.value).startswith(
            "Failed to install repository config with: ['sudo', 'install'"
        )
        is True
    )

@pytest.mark.parametrize(
    "package_repo,name,content",
    [
        (
            PackageRepositoryApt(
                architectures=["amd64", "arm64"],
                components=["test-component"],
                formats=["deb", "deb-src"],
                key_id="A" * 40,
                suites=["test-suite1", "test-suite2"],
                url="http://test.url/ubuntu",
            ),
            "snapcraft-http_test_url_ubuntu.sources",
            dedent(
                """\
                Types: deb deb-src
                URIs: http://test.url/ubuntu
                Suites: test-suite1 test-suite2
                Components: test-component
                Architectures: amd64 arm64
                """
            ).encode(),
        ),
        (
            PackageRepositoryApt(
                architectures=["amd64", "arm64"],
                components=["test-component"],
                key_id="A" * 40,
                name="NO-FORMAT",
                suites=["test-suite1", "test-suite2"],
                url="http://test.url/ubuntu",
            ),
            "snapcraft-NO-FORMAT.sources",
            dedent(
                """\
                Types: deb
                URIs: http://test.url/ubuntu
                Suites: test-suite1 test-suite2
                Components: test-component
                Architectures: amd64 arm64
                """
            ).encode(),
        ),
        (
            PackageRepositoryApt(
                key_id="A" * 40,
                name="WITH-PATH",
                path="some-path",
                url="http://test.url/ubuntu",
            ),
            "snapcraft-WITH-PATH.sources",
            dedent(
                """\
                Types: deb
                URIs: http://test.url/ubuntu
                Suites: some-path/
                Architectures: FAKE-HOST-ARCH
                """
            ).encode(),
        ),
        (
            PackageRepositoryApt(
                key_id="A" * 40,
                name="IMPLIED-PATH",
                url="http://test.url/ubuntu",
            ),
            "snapcraft-IMPLIED-PATH.sources",
            dedent(
                """\
                Types: deb
                URIs: http://test.url/ubuntu
                Suites: /
                Architectures: FAKE-HOST-ARCH
                """
            ).encode(),
        ),
        (
            PackageRepositoryAptPpa(ppa="test/ppa"),
            "snapcraft-ppa-test_ppa.sources",
            dedent(
                """\
                Types: deb
                URIs: http://ppa.launchpad.net/test/ppa/ubuntu
                Suites: FAKE-CODENAME
                Components: main
                Architectures: FAKE-HOST-ARCH
                """
            ).encode(),
        ),
    ],
)
def test_install(package_repo, name, content, apt_sources_mgr, mock_sudo_write):
    sources_path = apt_sources_mgr._sources_list_d / name

    changed = apt_sources_mgr.install_package_repository_sources(
        package_repo=package_repo
    )

    assert changed is True
    assert sources_path.read_bytes() == content
    assert mock_sudo_write.mock_calls == [
        call(
            content=content,
            dst_path=sources_path,
        )
    ]

    # Verify a second-run does not incur any changes.
    mock_sudo_write.reset_mock()

    changed = apt_sources_mgr.install_package_repository_sources(
        package_repo=package_repo
    )

    assert changed is False
    assert sources_path.read_bytes() == content
    assert mock_sudo_write.mock_calls == []

def test_install_ppa_invalid(apt_sources_mgr):
    repo = PackageRepositoryAptPpa(ppa="ppa-missing-slash")

    with pytest.raises(errors.AptPPAInstallError) as exc_info:
        apt_sources_mgr.install_package_repository_sources(package_repo=repo)

    assert exc_info.value._ppa == "ppa-missing-slash"


#!/usr/bin/env python3

import unittest
import time
import psutil
from vpp_papi.vpp_stats import VPPStats

from framework import VppTestCase, VppTestRunner

class StatsClientTestCase(VppTestCase):
    """Test Stats Client"""

    @classmethod
    def setUpClass(cls):
        super(StatsClientTestCase, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        super(StatsClientTestCase, cls).tearDownClass()

    def test_set_errors(self):
        """Test set errors"""
        self.assertEqual(self.statistics.set_errors(), {})
        self.assertEqual(self.statistics.get_counter('/err/ethernet-input/no'),
                         [0])

    def test_client_fd_leak(self):
        """Test file descriptor count - VPP-1486"""

        cls = self.__class__
        p = psutil.Process()
        initial_fds = p.num_fds()

        for _ in range(100):
            stats = VPPStats(socketname=cls.stats_sock)
            stats.disconnect()

        ending_fds = p.num_fds()
        self.assertEqual(initial_fds, ending_fds,
                         "initial client side file descriptor count: %s "
                         "is not equal to "
                         "ending client side file descriptor count: %s" % (
                             initial_fds, ending_fds))

    @unittest.skip("Manual only")
    def test_mem_leak(self):
        def loop():
            print('Running loop')
            for i in range(50):
                rv = self.vapi.papi.tap_create_v2(id=i, use_random_mac=1)
                self.assertEqual(rv.retval, 0)
                rv = self.vapi.papi.tap_delete_v2(sw_if_index=rv.sw_if_index)
                self.assertEqual(rv.retval, 0)

        before = self.statistics.get_counter('/mem/statseg/used')
        loop()
        self.vapi.cli("memory-trace on stats-segment")
        for j in range(100):
            loop()
        print(self.vapi.cli("show memory stats-segment verbose"))
        print('AFTER', before,
              self.statistics.get_counter('/mem/statseg/used'))

if __name__ == '__main__':
    unittest.main(testRunner=VppTestRunner)


import boto3

def create_dax_table(dyn_resource=None):
    """
    Creates a DynamoDB table.

    :param dyn_resource: Either a Boto3 or DAX resource.
    :return: The newly created table.
    """
    if dyn_resource is None:
        dyn_resource = boto3.resource('dynamodb')

    table_name = 'TryDaxTable'
    params = {
        'TableName': table_name,
        'KeySchema': [
            {'AttributeName': 'partition_key', 'KeyType': 'HASH'},
            {'AttributeName': 'sort_key', 'KeyType': 'RANGE'}
        ],
        'AttributeDefinitions': [
            {'AttributeName': 'partition_key', 'AttributeType': 'N'},
            {'AttributeName': 'sort_key', 'AttributeType': 'N'}
        ],
        'ProvisionedThroughput': {
            'ReadCapacityUnits': 10,
            'WriteCapacityUnits': 10
        }
    }
    table = dyn_resource.create_table(**params)
    print(f"Creating {table_name}...")
    table.wait_until_exists()
    return table

if __name__ == '__main__':
    dax_table = create_dax_table()
    print(f"Created table.")


import pygame
import math
import time
import hamilton
import common

pixel_per_meter = 10
width = 800
height = 600
v_inf = 1e4
width_m = width/pixel_per_meter
hegiht_m = height/pixel_per_meter
mass0 = 1

def main():
    dims = (width, height)
    background = (32, 32, 32)
    screen = pygame.display.set_mode(dims)
    pygame.display.set_caption("h")
    screen.fill((0, 0, 0))

    particles = []

    running = True
    currtime = time.time()

    dt = 0.001
    N = len(particles)

    while running:
        if time.time() - currtime >= dt:
            currtime = time.time()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
            screen.fill(background)


#!/usr/bin/env python3

# pop, peek, push, isEmpty

def stack_sort(s1):
    s2 = []
    fs = []
    l = len(s1)

    while len(fs) < l:
        g = None
        # search for greatest in s1 / s2
        for i in range(len(s1)):
            temp = s1.pop()
            s2.append(temp)
            if g is None:
                g = temp
            else:
                if temp < g:
                    g = temp

        # now we know the greatest, let's move it to fs
        for i in range(len(s2)):
            temp = s2.pop()
            if temp == g:
                fs.append(temp)
            else:
                s1.append(temp)

    return fs

if __name__ == '__main__':
    assert stack_sort([4, 5, 3, 8]) == [3, 4, 5, 8], 'error1'


#
# @lc app=leetcode id=438 lang=python3
#
# [438] Find All Anagrams in a String
#

# @lc code=start
import collections

class Solution:
    def findAnagrams(self, s: str, p: str):
        if len(s) < len(p) or not s or not p:
            return []
        rg = len(p)
        pd = collections.Counter(p)
        # initialize
        sd = collections.Counter(s[:rg])
        ans = []
        if pd == sd:
            ans = [0]
        for pos in range(1, len(s) - rg + 1):
            if sd[s[pos - 1]] == 1:
                sd.pop(s[pos - 1])
            else:
                sd[s[pos - 1]] -= 1
            if s[pos + rg - 1] not in sd:
                sd[s[pos + rg - 1]] = 1
            else:
                sd[s[pos + rg - 1]] += 1
            if pd == sd:
                ans.append(pos)
            pos += 1
        return ans

if __name__ == '__main__':
    a = Solution()
    b = a.findAnagrams("abab", "ab")
    print(b)

# @lc code=end


import sys
import parseEQU
import numpy as np

def parseNud(inpath,Nep,Equ):
    maincast = []
    allcount = []
    maxminute = 0
    for i in range(Nep):
        actorid = []
        counts = {}
        intext = inpath.split('*')[0]+"{:02}".format(i+1)+inpath.split('*')[1]
        lines = open(intext).readlines()
        for line in lines:
            if line.split(':')[0]=='Dialogue'\
            and len(line.split()[1].split(','))>=5:
                actor = line.split()[1].split(',')[4]
                actorid += actor,
                mints = int(line.split()[1].split(',')[1].split(':')[1])
                if mints>maxminute:
                    maxminute = mints
        counts = dict((x, actorid.count(x)) for x in actorid)
        allcount += actorid
        actorid = list(set(actorid))
    counts = dict((x, allcount.count(x)) for x in allcount)
    actorid = sorted(counts.keys(), key=lambda x: counts[x],reverse=True)
    #print len(actorid),actorid

    actoreq={}
    i=0
    for ls in Equ:
        for ac in ls:
            actoreq[ac]=i
        i+=1
    Nw = i
    Nd = maxminute+1

    #print actoreq
    #print Nd,Nw

    Nwd = [np.zeros([Nw,Nd]) for i in range(Nep)]
    for i in range(Nep):
        intext = inpath.split('*')[0]+"{:02}".format(i+1)+inpath.split('*')[1]
        lines = open(intext).readlines()
        for line in lines:
            if line.split(':')[0]=='Dialogue' and len(line.split()[1].split(','))>=5 \
            and line.split()[1].split(',')[4] in actorid:
                actor = line.split()[1].split(',')[4]
                try:    aid = actoreq[actor]
                except: continue

                wdlen = len(line.split()[1:])
                mints = int(line.split()[1].split(',')[1].split(':')[1])
                Nwd[i][aid][mints]=wdlen
    return Nwd,Nw,Nd,[eq[0] for eq in Equ]
'''
inpath='subinfo/nagi_*.srt'
Nep = 26
Equ = parseEQU.nagi
Nud,Nu,Nd, actor_name= parseNud(inpath,Nep,Equ)
print Nu,Nd
print actor_name
print np.shape(Nud[0]),np.shape(Nud[-1])
'''


import os

RSFROOT=os.getenv('RSFROOT')
RSFROOT_LIB=os.path.join(RSFROOT, 'lib')
RSFROOT_INC=os.path.join(RSFROOT, 'include')

env = Environment(CXX='/usr/local/opt/llvm/bin/clang++',
                  CXXFLAGS=['-O3', '-fopenmp'],
                  CPPPATH=[RSFROOT_INC],
                  LIBS=['rsf++','rsf', 'm'],
                  LIBPATH=[RSFROOT_LIB, '/usr/local/opt/llvm/lib'],
                  LINKFLAGS=['-fopenmp'])

BuiltTarget = env.Program(target = 'main',
                          source = Glob('*.cpp'))
#   modify @rpath
env.AddPostAction(BuiltTarget,'install_name_tool -change @rpath/libiomp5.dylib /opt/intel/compilers_and_libraries_2017.0.102/mac/compiler/lib/libiomp5.dylib main')


import socket
import sys

# Creating server socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Taking the server IP address and port number as command line arguments
server_ip = sys.argv[1]
server_port = int(sys.argv[2])

# Binding the server socket to listen to the given IP address and port number
server_socket.bind((server_ip, server_port))
server_socket.listen(0)

# The server will always keep running (as it realistically should), unless force quit using Ctrl+C
while True:

    print(f"\nListening on {server_ip} port {server_port}. Waiting for a connection...")

    # Waiting to accept a connection from a client. This line blocks the code until a client connection is made
    # After a client connects, a new socket is assigned to this connection (client_conn)
    # The server socket is always reserved to listen for incoming connections
    client_conn, client_addr = server_socket.accept()

    print(f"\nConnected to client {client_addr}\n")

    while True:

        # Receiving message from the client
        msg_bytes = client_conn.recv(1024)

        # If the client closes the connection using conn.close(), the message received has 0 bytes
        if msg_bytes == b'':
            print("Closing the connection\n")
            client_conn.close()
            break

        # The message received is in the form of bytes. Decoding it to a string
        msg = msg_bytes.decode()
        print (f"Recived expression {msg} from client")

        # Calculating the value of the received expression using eval(). Error is it is an invalid expression
        try:
            ans = eval(msg)
        except:
            ans = "ERROR: Invalid expression"
        ans = str(ans)
        print(f"Sending answer {ans} to the client\n")

        # Sending the reply to the client, and storing the length of the message sent
        lenth = client_conn.sendall(bytes(ans, "utf-8"))

server_socket.close()


import sys

n = sys.stdin.readline()
n = int(n)

dataTemp = sys.stdin.readline()
dataTemp = dataTemp.split(' ')
data = [int(i) for i in dataTemp]

minVal = data[0]
maxVal = data[0]

for val in data:
    if val < minVal:
        minVal = val
    if val > maxVal:
        maxVal = val

print('{} {}'.format(maxVal, minVal))


# Nick Weisberg
# 7shifts programming question
# January 27 2020

def Add(numbers):
    """
    Add:    adds up all the numbers in a string
    param:  String numbers - a string of delimitted numbers
            Assumes: start of string formatted as: "//DELIMITER\n"
    return: int value equal to sum of numbers in input string
    """
    # get index of first new line char to tell where end of delimitter ends
    newLine_index = numbers.index("\n")
    # delimitted is equal to the string after "//" and before the new line char
    delim = numbers[2:newLine_index]
    # the remaining section of the string is our numbers to be summed
    numbers = numbers[newLine_index:]
    # check if multiple delimiters
    if "," in delim and len(delim) > 1:
        delimiters = delim.split(",")
        # replace all instances of unique delimiters with a comma
        for delimiter in delimiters:
            numbers = numbers.replace(delimiter, ",")
        # set the delimiter to a comma
        delim = ","
    # case of empty string
    if numbers == "\n": return 0
    # converting our remaining numbers to an array
    number_array = numbers.split(delim)
    # removing any new line chars and converting numbers of array to integers
    number_array = [int(number.strip()) for number in number_array if int(number) <= 1000]
    # raising a value error if any number in array is negative
    for number in number_array:
        if number < 0:
            raise ValueError("Negatives not allowed: {}".format(number))
    # returning sum of array elements
    return sum(number_array)

##################################################################################
# TEST CASES FOR FUNCTION ADD

tests = {

# simple
"//,\n1,3,4" : 8,
"//,\n17,56,33,1" : 107,
"//,\n10,21,2,45,19,34,67" : 198,

# edges
"//,\n0,3,4" : 7,
"//,\n1000,3,4" : 1007,
"//,\n0" : 0,
"//,\n0,0,0,0,0,0" : 0,
"//,\n1000,0,1000,0,7, 1000" : 3007,

# special cases
"//,\n" : 0,
"//,\n1001" : 0,
"//,\n3,1001,21" : 24,
"//,\n29765, 2349, 4459, 2394" : 0,

# delimiters
"//;\n1;3;4" : 8,
"//$\n1$2$3" : 6,
"//@\n2@3@8" : 13,
"//***\n1***2***3" : 6,
"//$,@\n1$2@3" : 6

}

for test in tests:
    assert Add(test) == tests[test], "Test case: {} Result: {} Answer: {}".format(test,Add(test),tests[test])


# A simple class that represents a dog
# This can apply to any dog

# All dogs have a name and an age
# Dog's can sit and roll over

# This class will tell Python how to make an object representing a dog, after this is written
# this will be used to make individual instances, each of which represents one specific dog

class Dog(): # The class name starts with an upper case letter
    '''A class to create a simple model of a dog'''
    def __init__(self, name, age):
        # This __init__(self): is a default method in Python and runs whenever a new instance
        # is created based on the dog class
        # Whenever a new instance of Dog class is created then the values for name and age must be passed

        '''Initialize the name and age attributes'''
        # Define the varaiables name and age
        # These have a prefix of self. are available in every method in the class
        # self.name = name, takes the value stored in the parameter name and stores it
        # in the variable called name which is then attached to the instance being created
        self.name = name
        self.age = age

    # Create the sit and roll_over Methods
    # As these methods don't need any additional information like name and age they are defined
    # with one parameter called self

    def sit(self):
        ''' Simulate a dog sitting in response to a command'''
        print(self.name.title() + " is now sitting.")

    def roll_over(self):
        ''' Simulate a dog rolling over in response to a command'''
        print(self.name.title() + " rolled over")

# Create an instance of a dog using the Dog class
# Store the instance of the dog creation in a variable called my_dog
# Creating an instance of a class lower case letters are used
my_dog = Dog('washington', 12)

# Print some text and also call the variable along with the attribute name
# title is used to make the first letter uppercase
print("My dog's name was " + my_dog.name.title() + ".")

# Print some text and also call the variable along with the attribute
# age converted to a string as it's a number
print("My dog was " + str(my_dog.age) + " years old")

# Calling methods
# methods can be called by using dot notation
# example my_dog.sit()
# my_dog.roll_over()

# When Python reads my_dog.sit() it looks for the sit() method in the
# class Dog and runs that code

my_dog.sit()
my_dog.roll_over()

# Creating multiple Instances from a single class

my_dog = Dog('washington', 12)
your_dog = Dog('susie', 15)

print("\nYour dog's name is " + your_dog.name.title() + ".")
print("Your dog is " + str(your_dog.age) + " years old")
your_dog.sit()
your_dog.roll_over()

Python Crash Course/Chapter 9 Classes/dog_Class.py


from . import query
from .inventory import get_inventory_value
from .roles import has_role
from .. import faces
from ..engineobject import EngineObject
from ..helpers import FrameContext
import sbs

def science_start_scan(origin_id, selected_id, tab):
    #
    # Check if this was initiated by a "Follow route"
    #
    so = query.to_object(origin_id)
    so_sel = query.to_object(selected_id)
    percent = 0.0

    if so.side == so_sel.side:
        percent = 0.90
    if so:
        so.update_engine_data({
            "cur_scan_ID": selected_id,
            "cur_scan_type": tab,
            "cur_scan_percent": percent
        })

def science_set_scan_data(player_id_or_obj, scan_target_id_or_obj, tab, message):
        player_id = query.to_id(player_id_or_obj)
        scan_target_id = query.to_id(scan_target_id_or_obj)
        player_obj = query.to_object(player_id)
        target_blob = query.to_blob(scan_target_id)

        if player_obj is None: return
        if target_blob is None: return
        target_blob.set(f"{player_obj.side}{tab}", message, 0)


'''
number = 600851475143

while divisor > 1:
    if number % divisor == 0:
        print(divisor)
    else:
        divisor -= 1

def large(number):
    for x in range(number//2,0,-2):
        for x in range(number):
            if x**2 < number:
                print(x)
            if number % x == 0:
                return x
'''

def large(number):
    count = 2
    while count ** 2 < number:
        while number % count == 0:
            number = number / count
        count += 1
    return number

def main():
    print(large(600851475143))

main()


import os

from typing import Any, Dict, List, Optional

from tfx import types
from tfx.dsl.components.base import base_component
from tfx.dsl.components.base import base_executor
from tfx.dsl.components.base import executor_spec
from tfx.orchestration import pipeline
from tfx.proto.orchestration import pipeline_pb2
from tfx.types import component_spec
from tfx.types import standard_artifacts
from tfx.types.artifact import Artifact
from tfx.types.artifact import Property
from tfx.types.artifact import PropertyType
from google.protobuf import duration_pb2
from google.protobuf import timestamp_pb2

class StatsMetadata(Artifact):
  TYPE_NAME = 'StatsMetadata'
  PROPERTIES = {
      'timestamp': Property(type=PropertyType.PROTO
                           ),  # Expected proto type: google.protobuf.Timestamp
      'ttl': Property(type=PropertyType.PROTO
                     ),  # Expected proto type: google.protobuf.Duration
  }

class CustomProducerSpec(types.ComponentSpec):
  """ComponentSpec for Custom Producer Component."""

  PARAMETERS = {}
  INPUTS = {}
  OUTPUTS = {
      'stats':
          component_spec.ChannelParameter(
              type=standard_artifacts.ExampleStatistics),
      'stats_metadata':
          component_spec.ChannelParameter(type=StatsMetadata),
  }

class CustomConsumerSpec(types.ComponentSpec):
  """ComponentSpec for Custom Comsumer Component."""

  PARAMETERS = {}
  INPUTS = {
      'data':
          component_spec.ChannelParameter(
              type=standard_artifacts.ExampleStatistics),
  }
  OUTPUTS = {}

class DummyExecutor(base_executor.BaseExecutor):

  def Do(self, input_dict: Dict[str, List[types.Artifact]],
         output_dict: Dict[str, List[types.Artifact]],
         exec_properties: Dict[str, Any]) -> None:
    pass

class CustomProducer(base_component.BaseComponent):
  """Custom Producer Component."""

  SPEC_CLASS = CustomProducerSpec
  EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(DummyExecutor)

  def __init__(self,
               stats: Optional[types.Channel] = None,
               stats_metadata: Optional[types.Channel] = None):
    stats = stats or types.Channel(type=standard_artifacts.ExampleStatistics)
    stats.additional_properties['span'] = 42
    stats.additional_properties['split_names'] = '[\'train\', \'eval\']'
    stats.additional_custom_properties['bar'] = 'foo'
    stats.additional_custom_properties['baz'] = 0.5

    stats_metadata = stats_metadata or types.Channel(type=StatsMetadata)
    timestamp_value = pipeline_pb2.Value()
    timestamp_value.field_value.proto_value.Pack(
        timestamp_pb2.Timestamp(seconds=999999))
    stats_metadata.additional_properties['timestamp'] = timestamp_value
    ttl_value = pipeline_pb2.Value()
    ttl_value.field_value.proto_value.Pack(duration_pb2.Duration(seconds=600))

    stats_metadata.additional_properties['ttl'] = ttl_value
    spec = CustomProducerSpec(stats=stats, stats_metadata=stats_metadata)
    super().__init__(spec=spec)

class CustomConsumer(base_component.BaseComponent):
  """Custom Consumer Component."""

  SPEC_CLASS = CustomConsumerSpec
  EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(DummyExecutor)

  def __init__(self, data: types.Channel):
    spec = CustomConsumerSpec(data=data)
    super().__init__(spec=spec)

def create_test_pipeline():
  """Builds an example asynchronous pipeline using custom components."""
  pipeline_name = 'custom1'
  tfx_root = 'tfx_root'
  pipeline_root = os.path.join(tfx_root, 'pipelines', pipeline_name)

  custom_producer = CustomProducer()

  custom_consumer = CustomConsumer(data=custom_producer.outputs['stats'])

  return pipeline.Pipeline(
      pipeline_name=pipeline_name,
      pipeline_root=pipeline_root,
      components=[
          custom_producer,
          custom_consumer,
      ],
      execution_mode=pipeline.ExecutionMode.ASYNC)


class Solution:
    def reformatDate(self, date: str) -> str:
        months=["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        date=date.split()
        year=date[2]
        month=months.index(date[1])+1
        if month<10:
            month='0'+str(month)
        else:
            month=str(month)
        if len(date[0])==3:
            day='0'+date[0][0]
        else:
            day=date[0][0:2]
        return year+'-'+month+'-'+day

if __name__ == '__main__':
            s = Solution()
            print(s.reformatDate(date = "20th Oct 2052"))


'''
Created on Oct 20, 2019

@author: camila
'''
import bisect
import sys

import psycopg2
from psycopg2.sql import Identifier, SQL

from ..database.PostGISConnection import PostGISConnection
from ..database.PostgisDataManager import PostgisDataManager
from ..network.MultimodalNetwork import MultimodalNetwork
from ..travel_time_function.ConstantFunction import ConstantFunction
from ..travel_time_function.TimeTable import TimeTable

class CreateTransportationNetwork:

    def __init__(self, region):
        self.region = region
        self.graph = MultimodalNetwork()
        dataManager = PostgisDataManager()
        self.mbr = dataManager.getNetworkMBR(region)
        self.current_node_id = dataManager.getNumNodes(region) + 1

        self.calendar = {}
        self.parent_stops={}
        self.stops = {}
        self.routes_id = []
        self.links = {}

        self.route_transfers = {}
        self.stop_transfers = {}

        self.edges_timetable = {}

        self.conn = PostGISConnection()

    def run(self):
        self.conn.connect()
        self.load()
        self.createTables()
        self.populateTables()
        self.conn.close()

    def createTables(self):
        self.createTableNodes()
        self.createTableEdges()
        self.createTableTimetables()

    def populateTables(self):
        self.populateTableNodes()
        self.populateTableEdgesAndTimetables()

    def createTableNodes(self):
        #node_id, lat, lon, node_type, stop_id=None, route_id=None
        sql = """
        CREATE TABLE IF NOT EXISTS {0} (
            node_id bigint NOT NULL,
            lat double precision NOT NULL,
            long double precision NOT NULL,
            type integer NOT NULL,
            stop_id varchar NULL,
            route_id varchar NULL,
            CONSTRAINT {1} PRIMARY KEY (node_id)
        );
        """
        sql = SQL(sql).format(Identifier("transportation_nodes_"+str(self.region)),
                              Identifier("transportation_nodes_"+str(self.region)+"_pkey"))
        self.conn.executeCommand(sql)

    def populateTableNodes(self):
        print("Creating table nodes...")
        sql = """INSERT INTO {0}(node_id, lat, long, type, stop_id, route_id)
                 VALUES (%s, %s, %s, %s, %s, %s);
            """
        sql = SQL(sql).format(Identifier("transportation_nodes_"+str(self.region)))
        try:
            cursor = self.conn.getCursor()
            for node_id in self.graph.getNodesIds():
                #print(node_id)
                node = self.graph.getNode(node_id)
                if 'type' not in node:
                    continue
                #print(self.region, node_id, node['lat'], node['lon'], node['type'], stop_id, route_id)
                cursor.execute(sql, (node_id, node['lat'], node['lon'], node['type'], node.get('stop_id'), node.get('route_id')))
            self.conn.commit()

        except IOError as e:
            print("I/O error({0}): {1}".format(e.errno, e.strerror))
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
        except:
            print("Unexpected error:", sys.exc_info()[0])

    def createTableEdges(self):
        #node_from, node_to, edge_type, modes, travel_time_functions, original_edge_id=None, edge_position=None
        sql = """
        CREATE TABLE IF NOT EXISTS {0} (
            source bigint NOT NULL,
            target bigint NOT NULL,
            type integer NOT NULL,
            modes integer[] NOT NULL,
            cost integer NULL,
            timetable_id bigint NULL,
            original_edge_id bigint NULL,
            edge_position integer NULL,
            CONSTRAINT {1} PRIMARY KEY (source, target)
        );
        """
        sql = SQL(sql).format(Identifier("transportation_edges_"+str(self.region)),
                              Identifier("transportation_edges_"+str(self.region) + "_pkey"))
        self.conn.executeCommand(sql)

    def createTableTimetables(self):
        sql = """
        CREATE TABLE IF NOT EXISTS {0} (
            id bigint NOT NULL,
            monday time[] NULL,
            tuesday time[] NULL,
            wednesday time[] NULL,
            thursday time[] NULL,
            friday time[] NULL,
            saturday time[] NULL,
            sunday time[] NULL,
            CONSTRAINT {1} PRIMARY KEY (id)
        );
        """
        sql = SQL(sql).format(Identifier("transportation_timetables_"+str(self.region)),
                              Identifier("transportation_timetables_"+str(self.region) + "_pkey"))
        self.conn.executeCommand(sql)

    def populateTableEdgesAndTimetables(self):
        print("Creating table edges...")
        sql = """INSERT INTO {0}(source, target, type, modes, cost, timetable_id, original_edge_id, edge_position)
                 VALUES (%s, %s, %s, %s, %s, %s, %s, %s);
            """
        sql = SQL(sql).format(Identifier("transportation_edges_"+str(self.region)))

        sql_timetable = """INSERT INTO {}(id, monday, tuesday, wednesday, thursday, friday, saturday, sunday)
                 VALUES (%s, %s, %s, %s, %s, %s, %s, %s);
            """
        sql_timetable = SQL(sql_timetable).format(Identifier("transportation_timetables_"+str(self.region)))
        curr_timetable_id = 0;
        try:
            count = 0
            records = []
            cursor = self.conn.getCursor()
            for edge_id in self.graph.getEdges():
                edge = self.graph.getEdge(edge_id[0], edge_id[1])

                travel_time_functions = edge['travel_time_functions']
                cost = None
                timetable_id = None
                for mode in travel_time_functions:
                    if mode == self.graph.PUBLIC:
                        timetable_id = curr_timetable_id
                        timetable = travel_time_functions[mode].getTable()
                        cursor.execute(sql_timetable, (timetable_id, timetable.get(0), timetable.get(1),
                                                       timetable.get(2), timetable.get(3), timetable.get(4), timetable.get(5), timetable.get(6)))

                        curr_timetable_id += 1
                    else:
                        cost = travel_time_functions[mode].getTravelCost()

                records.append((edge_id[0], edge_id[1], edge['type'], list(edge['modes']), cost, timetable_id,
                                       edge.get('original_edge_id'), edge.get('edge_position')))
                count += 1
                if count % 1000 == 0:
                    #print("Commiting changes...")
                    cursor.executemany(sql, records)
                    self.conn.commit()
                    records = []

            cursor.executemany(sql, records)
            self.conn.commit()
            cursor.close()

        except IOError as e:
            print("I/O error({0}): {1}".format(e.errno, e.strerror))
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
        except:
            print("Unexpected error:", sys.exc_info()[0])

    def load(self):
        print("Loading GTFS data...")
        self.loadCalendar()
        self.loadStops()
        self.loadRoutes()
        self.loadTrips()
        del self.calendar
        del self.routes_id
        del self.edges_timetable

        #creating links within stations and to the road network
        self.loadLinks()
        self.loadTransferTimes()
        self.addTransfers()

        del self.stops
        del self.parent_stops
        del self.links
        del self.route_transfers
        del self.stop_transfers

    def loadCalendar(self):
        print("Loading calendar...")
        sql = """SELECT service_id, monday, tuesday, wednesday, thursday, friday, saturday, sunday
        FROM {};
        """
        sql = SQL(sql).format(Identifier("calendar_"+str(self.region)))
        try:
            cursor = self.conn.getCursor()
            cursor.execute(sql)

            row = cursor.fetchone()

            while row is not None:
                (service_id, monday, tuesday, wednesday, thursday, friday, saturday, sunday) = row
                self.calendar[service_id] = {0: monday, 1:tuesday, 2:wednesday, 3: thursday,
                                        4:friday, 5:saturday, 6:sunday}
                row = cursor.fetchone()
            cursor.close()
        except IOError as e:
            print("I/O error({0}): {1}".format(e.errno, e.strerror))
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
        except:
            print("Unexpected error:", sys.exc_info()[0])

    def loadStops(self):
        print("Loading stops...")
        sql = """SELECT stop_id, stop_lat, stop_lon, stop_type, stop_parent
        FROM {};
        """
        sql = SQL(sql).format(Identifier("stops_"+str(self.region)))

        min_lat = float(self.mbr[1])
        min_long = float(self.mbr[0])
        max_lat = float(self.mbr[3])
        max_long = float(self.mbr[2])

        try:
            cursor = self.conn.getCursor()
            cursor.execute(sql)

            row = cursor.fetchone()

            while row is not None:
                (stop_id, stop_lat, stop_lon, stop_type, stop_parent) = row
                if stop_lat >= min_lat and stop_lat <= max_lat and stop_lon >= min_long and stop_lon <= max_long:
                    self.stops[stop_id] = {'lat':stop_lat, 'lon':stop_lon, 'type':stop_type, 'parent':stop_parent}

                row = cursor.fetchone()
            cursor.close()
        except IOError as e:
            print("I/O error({0}): {1}".format(e.errno, e.strerror))
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
        except:
            print("Unexpected error:", sys.exc_info()[0])

    def loadLinks(self):
        print("Loading links...")
        sql = """SELECT link_id, edge_id, stop_id, source, target, edge_dist, source_ratio, edge_length, ST_X(point_location), ST_Y(point_location)
        FROM {0};
        """
        sql = SQL(sql).format(Identifier("links_"+str(self.region)))

        try:
            cursor = self.conn.getCursor()
            cursor.execute(sql)

            row = cursor.fetchone()

            #parents = self.parent_stops.keys()
            while row is not None:
                (link_id, edge_id, stop_id, source, target, edge_dist, source_ratio, edge_length, lon, lat) = row
                #if stop_id in parents:
                self.links[stop_id] = {'link_id': link_id, 'edge_id': edge_id, 'source':source, 'target':target, 'edge_dist':edge_dist,
                                        'source_ratio':source_ratio, 'edge_length':edge_length, 'lat':lat, 'lon':lon}
                row = cursor.fetchone()
            cursor.close()
        except IOError as e:
            print("I/O error({0}): {1}".format(e.errno, e.strerror))
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
        except:
            print("Unexpected error:", sys.exc_info()[0])

    def loadTransferTimes(self):
        if self.parent_stops:

            sql_exists = """SELECT EXISTS (
                               SELECT 1
                               FROM   information_schema.tables
                               WHERE  table_name = %s
                           );
            """
            #sql_exists = SQL(sql_exists).format(Identifier("transfers_"+str(self.region)))

            try:
                cursor = self.conn.getCursor()

                cursor.execute(sql_exists, ('transfers_'+str(self.region), ))
                (exists,) = cursor.fetchone()
                if not exists:
                    print("Table does not exist!")
                    return

                print("Loading transfer times...")
                sql = """SELECT from_stop_id, to_stop_id, transfer_type, min_transfer_time, from_route_id, to_route_id, from_trip_id
                FROM {};
                """
                sql = SQL(sql).format(Identifier("transfers_"+str(self.region)))
                cursor.execute(sql)

                row = cursor.fetchone()

                while row is not None:
                    (from_stop_id, to_stop_id, transfer_type, min_transfer_time, from_route_id, to_route_id, from_trip_id) = row
                    if not min_transfer_time:
                        min_transfer_time = MultimodalNetwork.MIN_TRANSFER_TIME
                    if from_stop_id != to_stop_id and not from_trip_id:
                        if not from_route_id:
                            if from_stop_id in self.stop_transfers:
                                self.stop_transfers[from_stop_id][to_stop_id] = min_transfer_time
                            else:
                                self.stop_transfers[from_stop_id] = {to_stop_id : min_transfer_time}
                        else:
                            if from_route_id in self.route_transfers:
                                if to_route_id in self.route_transfers[from_route_id]:
                                    if from_stop_id in self.route_transfers[from_route_id][to_route_id]:
                                        self.route_transfers[from_route_id][to_route_id][from_stop_id][to_stop_id] = min_transfer_time
                                    else:
                                        self.route_transfers[from_route_id][to_route_id][from_stop_id] = {to_stop_id:min_transfer_time}
                                else:
                                    self.route_transfers[from_route_id][to_route_id] = {from_stop_id: {to_stop_id:min_transfer_time}}
                            else:
                                self.route_transfers[from_route_id] = {to_route_id : {from_stop_id: {to_stop_id:min_transfer_time}}}
                    row = cursor.fetchone()

                cursor.close()
            except IOError as e:
                print("I/O error({0}): {1}".format(e.errno, e.strerror))
            except (Exception, psycopg2.DatabaseError) as error:
                print(error)
            except:
                print("Unexpected error:", sys.exc_info()[0])

    def loadRoutes(self):
        print("Loading routes...")
        sql = """SELECT route_id FROM {};
        """
        sql = SQL(sql).format(Identifier("routes_"+str(self.region)))

        try:
            cursor = self.conn.getCursor()
            cursor.execute(sql)

            row = cursor.fetchone()

            while row is not None:
                (route_id,) = row
                self.routes_id.append(route_id)
                row = cursor.fetchone()

            cursor.close()
        except IOError as e:
            print("I/O error({0}): {1}".format(e.errno, e.strerror))
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
        except:
            print("Unexpected error:", sys.exc_info()[0])

    def loadTrips(self):
        print("Loading trips...")
        sql = """SELECT s.*, t.service_id FROM {0} as s, {1} as t
                WHERE s.trip_id in
                (select trip_id from {1} where route_id=%s) and
                t.trip_id = s.trip_id
                order by trip_id, stop_sequence
                ;
        """
        sql = SQL(sql).format(Identifier("stop_times_"+str(self.region)), Identifier("trips_"+str(self.region)))

        try:
            cursor = self.conn.getCursor()

            for route in self.routes_id:
                #print(route)
                self.edges_timetable = {}
                node_mapping = {}

                cursor.execute(sql, (route, ))

                row = cursor.fetchone()

                previous_trip_id = -1
                previous_node = -1
                previous_departure_time = None
                while row is not None:
                    (trip_id, arrival_time, departure_time, stop_id, stop_sequence, service_id) = row
                    #print(trip_id)

                    if trip_id != previous_trip_id:
                        previous_node = -1

                    if stop_id in node_mapping:
                        node_id = node_mapping[stop_id]

                    else:
                        if stop_id not in self.stops:
                            previous_node = -1
                            row = cursor.fetchone()
                            continue

                        node_id = self.current_node_id
                        node_mapping[stop_id] = node_id

                        stop = self.stops[stop_id]
                        if self.graph.getNode(node_id):
                            print("duplicate node!!", node_id)
                        self.graph.addNode(node_id, stop['lat'], stop['lon'], MultimodalNetwork.TRANSPORTATION, stop_id, route)

                        #print(node_id)
                        if self.stops[stop_id]['parent']:
                            parent = self.stops[stop_id]['parent']
                            if parent in self.parent_stops:
                                self.parent_stops[parent].append(node_id)
                            else:
                                self.parent_stops[parent] = [node_id]
                        elif self.stops[stop_id]['type'] == 0 and not self.stops[stop_id]['parent']:
                            self.parent_stops[stop_id] = [node_id]
                            #print(stop_id, node_id)

                        self.current_node_id += 1
                    row = cursor.fetchone()

                    if previous_node != -1:
                        #create edge from previous_node to node_id
                        self.createTransportationEdge(previous_node, node_id, previous_departure_time, arrival_time, service_id)

                    previous_node = node_id
                    previous_trip_id = trip_id
                    previous_departure_time = departure_time

                self.addTransportationEdges()

            cursor.close()
        except IOError as e:
            print("I/O error({0}): {1}".format(e.errno, e.strerror))
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
        except:
            print("Unexpected error:", sys.exc_info()[0])

    def addTransportationEdges(self):
        for node_from in self.edges_timetable:
            for node_to in self.edges_timetable[node_from]:
                timetable = self.edges_timetable[node_from][node_to]
                self.graph.addEdge(node_from, node_to, MultimodalNetwork.TRANSPORTATION, {MultimodalNetwork.PUBLIC}, {MultimodalNetwork.PUBLIC:TimeTable(timetable)})
                #print(self.graph.getEdge(node_from, node_to))

    def createTransportationEdge(self, from_node, to_node, departure_time, arrival_time, service_id):
        #print(str(from_node) + "," + str(to_node))
        service = self.calendar[service_id]
        if from_node in self.edges_timetable:
            if to_node in self.edges_timetable[from_node]:
                timetable = self.edges_timetable[from_node][to_node]
                for day in service:
                    if service[day]:
                        self.addNewDeparture(timetable[day], departure_time, arrival_time)
            else:
                timetable = {}
                for i in range(7):
                    timetable[i] = []

                for day in service:
                    if service[day]:
                        self.addNewDeparture(timetable[day], departure_time, arrival_time)

                self.edges_timetable[from_node][to_node] = timetable
        else:
            self.edges_timetable[from_node] = {}
            timetable = {}
            for i in range(7):
                timetable[i] = []

            for day in service:
                if service[day]:
                    self.addNewDeparture(timetable[day], departure_time, arrival_time)
            self.edges_timetable[from_node][to_node] = timetable

    def addNewDeparture(self, list_departures, departure_time, arrival_time):
        if not list_departures:
            bisect.insort(list_departures, [departure_time, arrival_time])
        else:
            pos = bisect.bisect_left(list_departures, [departure_time, arrival_time])
            if pos == len(list_departures) or list_departures[pos] != [departure_time, arrival_time]:
                bisect.insort(list_departures, [departure_time, arrival_time])
        '''
        i = 0
        while i < len(list_departures):
            if list_departures[i][0] == departure_time:
                break
            elif list_departures[i][0] > departure_time:
                list_departures.insert(i, [departure_time, arrival_time])
                break
            else:
                i+=1
        if i == len(list_departures):
            list_departures.append([departure_time, arrival_time])

        '''
    def addTransfers(self):
        print("Adding transfers...")
        for stop in self.links:
            #print(stop)
            #connect the super node to the road network
            stop_id = self.addLinkSuperNodeToRoadNetwork(stop)

            if stop in self.parent_stops:
                list_nodes = self.parent_stops[stop]
                #print(stop, list_nodes)
                for node_from in list_nodes:
                    self.addLinkToSuperNode(node_from, stop_id)
                    for node_to in list_nodes:
                        if node_from != node_to:
                            transfer_time = self.getTransferTime(node_from, node_to)
                            #transfer_time = 0
                            self.graph.addEdge(node_from, node_to, MultimodalNetwork.TRANSFER, {MultimodalNetwork.PEDESTRIAN},
                                           {MultimodalNetwork.PEDESTRIAN:ConstantFunction(transfer_time)})

    def getTransferTime(self, node_from_id, node_to_id):
        node_from = self.graph.getNode(node_from_id)
        node_to = self.graph.getNode(node_to_id)

        stop_from = node_from['stop_id']
        stop_to = node_to['stop_id']
        route_from = node_from['route_id']
        route_to = node_to['route_id']

        transfer_time_stop = MultimodalNetwork.MIN_TRANSFER_TIME
        if stop_from in self.stop_transfers and stop_to in self.stop_transfers[stop_from]:
            transfer_time_stop = self.stop_transfers[stop_from][stop_to]

        if stop_from == stop_to:
            return MultimodalNetwork.MIN_TRANSFER_TIME
        if route_from in self.route_transfers:
            if route_to in self.route_transfers[route_from]:
                if stop_from in self.route_transfers[route_from][route_to] and stop_to in self.route_transfers[route_from][route_to][stop_from]:
                    return self.route_transfers[route_from][route_to][stop_from][stop_to]
                else:
                    return transfer_time_stop

            else:
                return transfer_time_stop
        else:
            return transfer_time_stop

    def addLinkSuperNodeToRoadNetwork(self, super_stop):
        #create super stop node
        if super_stop not in self.stops:
            return
        stop_id = self.current_node_id
        self.current_node_id += 1
        stop = self.stops[super_stop]
        if self.graph.getNode(stop_id):
            print("2 duplicate node!!", stop_id)

        self.graph.addNode(stop_id, stop['lat'], stop['lon'], MultimodalNetwork.SUPER_NODE)
        #print("Adding node:" + str(stop_id))

        link = self.links[super_stop]
        edge_id = link['edge_id']
        source = link['source']
        target = link['target']
        edge_dist = link['edge_dist']
        edge_time = round((edge_dist/MultimodalNetwork.PEDESTRIAN_SPEED)*3600)
        source_ratio = link['source_ratio']

        if source_ratio == 0.0:
            #transfer node is equal to the source
            self.graph.addEdge(stop_id, source, MultimodalNetwork.TRANSFER, {MultimodalNetwork.PEDESTRIAN},
                    {MultimodalNetwork.PEDESTRIAN:ConstantFunction(edge_time)})
            self.graph.addEdge(source, stop_id, MultimodalNetwork.TRANSFER, {MultimodalNetwork.PEDESTRIAN},
                    {MultimodalNetwork.PEDESTRIAN:ConstantFunction(edge_time)})

        elif source_ratio == 1.0:
            #transfer node is equal to the target
            self.graph.addEdge(stop_id, target, MultimodalNetwork.TRANSFER, {MultimodalNetwork.PEDESTRIAN},
                    {MultimodalNetwork.PEDESTRIAN:ConstantFunction(edge_time)})
            self.graph.addEdge(target, stop_id, MultimodalNetwork.TRANSFER, {MultimodalNetwork.PEDESTRIAN},
                    {MultimodalNetwork.PEDESTRIAN:ConstantFunction(edge_time)})

        else:
            node_id = self.current_node_id
            self.current_node_id += 1

            if self.graph.getNode(node_id):
                print("3 duplicate node!!", node_id)

            self.graph.addNode(node_id, link['lat'], link['lon'], MultimodalNetwork.TRANSFER)

            #splitting edge
            length = link['edge_length']
            time_source = round(((source_ratio*length)/MultimodalNetwork.PEDESTRIAN_SPEED)*3600)
            time_target = round((((1-source_ratio)*length)/MultimodalNetwork.PEDESTRIAN_SPEED)*3600)

            self.graph.addEdge(source, node_id, MultimodalNetwork.TRANSFER, {MultimodalNetwork.PEDESTRIAN},
                    {MultimodalNetwork.PEDESTRIAN:ConstantFunction(time_source)}, edge_id, 1)
            self.graph.addEdge(node_id, source, MultimodalNetwork.TRANSFER, {MultimodalNetwork.PEDESTRIAN},
                    {MultimodalNetwork.PEDESTRIAN:ConstantFunction(time_source)}, edge_id, 1)
            self.graph.addEdge(target, node_id, MultimodalNetwork.TRANSFER, {MultimodalNetwork.PEDESTRIAN},
                    {MultimodalNetwork.PEDESTRIAN:ConstantFunction(time_target)},edge_id, 2)
            self.graph.addEdge(node_id, target, MultimodalNetwork.TRANSFER, {MultimodalNetwork.PEDESTRIAN},
                    {MultimodalNetwork.PEDESTRIAN:ConstantFunction(time_target)}, edge_id, 2)

            #connecting new node to super node
            self.graph.addEdge(stop_id, node_id, MultimodalNetwork.TRANSFER, {MultimodalNetwork.PEDESTRIAN},
                    {MultimodalNetwork.PEDESTRIAN:ConstantFunction(edge_time)})
            self.graph.addEdge(node_id, stop_id, MultimodalNetwork.TRANSFER, {MultimodalNetwork.PEDESTRIAN},
                    {MultimodalNetwork.PEDESTRIAN:ConstantFunction(edge_time)})

        return stop_id

    def addLinkToSuperNode(self, node_id, parent_node_id):
        self.graph.addEdge(parent_node_id, node_id, MultimodalNetwork.TRANSFER, {MultimodalNetwork.PEDESTRIAN},
                    {MultimodalNetwork.PEDESTRIAN:ConstantFunction(0)})
        self.graph.addEdge(node_id, parent_node_id, MultimodalNetwork.TRANSFER, {MultimodalNetwork.PEDESTRIAN},
                    {MultimodalNetwork.PEDESTRIAN:ConstantFunction(0)})

    '''
    def addLinkToRoadNetworkSourceTarget(self, node_id, parent):
        link = self.links[parent]
        source = self.osm_mapping[link['source']]
        target = self.osm_mapping[link['target']]
        #print(source, node_id, target)
        source_dist = link['source_dist']
        source_time = round((source_dist/self.graph.PEDESTRIAN_SPEED)*3600)
        target_dist = link['source_dist']
        target_time = round((target_dist/self.graph.PEDESTRIAN_SPEED)*3600)

        #each node is connected to the source and target nodes in the road network

        self.graph.addEdge(source, node_id, self.graph.TRANSFER, {self.graph.PEDESTRIAN},
                                       {self.graph.PEDESTRIAN:ConstantFunction(source_time)})
        self.graph.addEdge(node_id, source, self.graph.TRANSFER, {self.graph.PEDESTRIAN},
                                       {self.graph.PEDESTRIAN:ConstantFunction(source_time)})
        self.graph.addEdge(node_id, target, self.graph.TRANSFER, {self.graph.PEDESTRIAN},
                                       {self.graph.PEDESTRIAN:ConstantFunction(target_time)})
        self.graph.addEdge(target, node_id, self.graph.TRANSFER, {self.graph.PEDESTRIAN},
                                       {self.graph.PEDESTRIAN:ConstantFunction(target_time)})

    '''


from fastapi import APIRouter, FastAPI, HTTPException
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel, ValidationError

from hand import Hand

app = FastAPI()
api_router = APIRouter()

class HandBody(BaseModel):
    hand: str

@api_router.post("/rank", response_class=PlainTextResponse)
def rank(body: HandBody) -> str:
    hand_str = body.hand
    try:
        return Hand.from_string(hand_str).rank()
    except (ValueError, ValidationError) as exp:
        raise HTTPException(500, str(exp)) from exp

app.include_router(api_router)

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8001, log_level="debug")


from django.shortcuts import render
from .models import *
from django.http import HttpResponse
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
import json
# Create your views here.

def index(request, group_name):
    group = GroupMaster.objects.filter(name = group_name).first()
    chats= []
    if group:
        chats = ChatMaster.objects.filter(group=group)
    else:
        GroupMaster.objects.create(name=group_name)
    return render(request, 'index.html',  {'group_name':group_name, 'chats':chats})

 #  This is static group add dynamic group name with logic
def send_dynamic_msg_to_group(request):
    channal_layer = get_channel_layer()
    async_to_sync(channal_layer.group_send)(
        	'love',
        {
            'type':'chat.message',
            'message':  "Alert Message for this group ! Warning !!"
        }
    )
    return HttpResponse("Warning message sent")

def msg_to_group(request):
    return HttpResponse("Warning message sent")


import boto3
import time
from ipdw_connect import IPDW_TEST02

def get_job_failures():
    view_sql = "SELECT * FROM vIPD_Alexa_Job_Failures"

    data_connection = IPDW_TEST02()

    data = data_connection.dataframe(view_sql)

    data.to_csv("latest_failed.csv", index=None)
    # Pull in data from view
    # If there is anything returned, store as a csv
    # Create message
    # "The following jobs have failed." + job (create loop with concat)

    failed_jobs = data["Job_Name"]
    start_message = "The following jobs have failed. "
    job_index = 0
    message = ""
    for job in data["Job_Name"]:
        job_index += 1
        if job_index == 1:
            message = start_message + job
        elif job_index != len(failed_jobs):
            message = message + ", " + job
        elif job_index == len(failed_jobs) & len(failed_jobs) == 2:
            message = message + ", and " + job + "."
    return message


#  Remove Covered Intervals
class Solution:
    def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
        n = len(intervals)
        intervals = sorted(intervals, key = lambda x : -x[0])
        count = n
        for i in range(n):
            start, end = intervals[i]
            for j in range(i+1,n):
                t_start, t_end = intervals[j]
                if  end <= t_end:
                    count -= 1
                    break
        ㅇ
        return count

# sorting start 는 작은거부터 !, end 는 큰거부터
# x[0]<=right and x[1]>=right right 만 갱신 - 어차피 x[0] 은 항상 크거나 같기때문
# x[0]>right 이면 right, left 둘다 갱신
class Solution:
    def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
        count = 0
        intervals.sort(key=lambda x: (x[0], -x[1]))
        left = intervals[0][0]
        right = intervals[0][1]
        for i in range(1, len(intervals)):
            x = intervals[i]
            if x[0]>=left and x[1]<=right:
                count+=1
            elif x[0]<=right and x[1]>=right:
                right = x[1]
            elif x[0]>right:
                left = x[0]
                right = x[1]

        return len(intervals)-count