from fastapi import APIRouter
from app.core.presenter import level as level_pres
from app.core.model import level as level_mod

router = APIRouter()

@router.get('/level')
async def list_level():
    list_levels = {
    "administrator":[{"kode_level":1}],
    "admin_pusat":[{"kode_level":2}],
    "admin_provinsi":[{"kode_level":3}],
    "admin_kabupaten":[{"kode_level":4}],
    "caleg":[{"kode_level":5}],
    "saksi":[{"kode_level":6}],
    "anggota":[{"kode_level":7}],
    }

    return list_levels

@router.post('/level/upgrade')
async def upgrade_level(upgrade: level_mod.UpgradeLevel):
    return await level_pres.handle(upgrade.user_id, upgrade.user_id_target, upgrade.target_level, mode='upgrade')

@router.post('/level/downgrade',)
async def downgrade_level(user_id: int, user_id_target: int, target_level: level_mod.Level, mode = 'downgrade') -> level_mod.Result:
    return await level_pres.handle(user_id, user_id_target, target_level, mode)


"""
******************
IAMB STRUCTURE
LEARNING ALGORITHM
******************

The IAMB algorithm - Incremental Association Markov Blanket - proceeds
similar to the Grow-Shrink algorithm, where the growing phase adds
random variables to a given node's markov blanket, and the shrinking
phase performs a second pass of conditional independence tests to
eliminate any variables from the markov blanket for which the given
node is conditionally independent given any other node in the markov
blanket (hence doesn't belong in the markov blanket).

It significantly reduces the complexity compared to PC/GS, and is
normally used in conjuction with the mutual information test for
independence (I do so here) [2].

Lastly, it can also be used as a feature selection algorithm for
classification or general dimensionality reduction - simply return
the markov blanket of a given node, which has been shown by Daphne
Koller to be theoretically optimal for prediction [3].

IAMB for Feature Selection (from [1]):
	Because the Markov blanket of a target attribute T renders
	it statistically independent from all the remaining attributes
	(see the Markov blanket definition below), all information
	that may influence its value is stored in the values
	of the attributes of its Markov blanket. Any attribute
	from the feature set outside its Markov blanket can be effectively
	ignored from the feature set without adversely affecting
	the performance of any classifier that predicts the
	value of T

References
----------
[1] Yaramakala and Maragritis, "Speculative Markov Blanket
Discovery for Optimal Feature Selection"

[2] Tsarmardinos, et al. "Algorithms for Large Scale
Markov Blanket Discovery"

[3] Koller "Toward Optimal Feature Selection."
"""

__author__ = """Nicholas Cullen <ncullen.th@dartmouth.edu>"""

import numpy as np
from pyBN.utils.independence_tests import are_independent, mi_test
from pyBN.utils.orient_edges import orient_edges_MB, orient_edges_gs2
from pyBN.utils.markov_blanket import resolve_markov_blanket
from pyBN.classes.bayesnet import BayesNet
from copy import copy

def iamb(data, alpha=0.05, feature_selection=None, debug=False):
	"""
	IAMB Algorithm for learning the structure of a
	Discrete Bayesian Network from data.

	Arguments
	---------
	*data* : a nested numpy array

	*alpha* : a float
		The type II error rate.

	*feature_selection* : None or a string
		Whether to use IAMB as a structure learning
		or feature selection algorithm.

	Returns
	-------
	*bn* : a BayesNet object or
	*mb* : the markov blanket of a node

	Effects
	-------
	None

	Notes
	-----
	- Works but there are definitely some bugs.

	Speed Test:
		*** 5 vars, 624 obs ***
			- 196 ms
	"""
	n_rv = data.shape[1]
	Mb = dict([(rv,[]) for rv in range(n_rv)])

	if feature_selection is None:
		_T = range(n_rv)
	else:
		assert (not isinstance(feature_selection, list)), 'feature_selection must be only one value'
		_T = [feature_selection]

	# LEARN MARKOV BLANKET
	for T in _T:

		V = set(range(n_rv)) - {T}
		Mb_change=True

		# GROWING PHASE
		while Mb_change:
			Mb_change = False
			# find X_max in V-Mb(T)-{T} that maximizes
			# mutual information of X,T|Mb(T)
			# i.e. max of mi_test(data[:,(X,T,Mb(T))])
			max_val = -1
			max_x = None
			for X in V - set(Mb[T]) - {T}:
				cols = (X,T)+tuple(Mb[T])
				mi_val = mi_test(data[:,cols],test=False)
				if mi_val > max_val:
					max_val = mi_val
					max_x = X
			# if Xmax is dependent on T given Mb(T)
			cols = (max_x,T) + tuple(Mb[T])
			if max_x is not None and are_independent(data[:,cols]):
				Mb[T].append(X)
				Mb_change = True
				if debug:
					print('Adding %s to MB of %s' % (str(X), str(T)))

		# SHRINKING PHASE
		for X in Mb[T]:
			# if x is independent of t given Mb(T) - {x}
			cols = (X,T) + tuple(set(Mb[T]) - {X})
			if are_independent(data[:,cols],alpha):
				Mb[T].remove(X)
				if debug:
					print('Removing %s from MB of %s' % (str(X), str(T)))

	if feature_selection is None:
		# RESOLVE GRAPH STRUCTURE
		edge_dict = resolve_markov_blanket(Mb, data)
		if debug:
			print('Unoriented edge dict:\n %s' % str(edge_dict))
			print('MB: %s' % str(Mb))
		# ORIENT EDGES
		oriented_edge_dict = orient_edges_gs2(edge_dict,Mb,data,alpha)
		if debug:
			print('Oriented edge dict:\n %s' % str(oriented_edge_dict))

		# CREATE BAYESNET OBJECT
		value_dict = dict(zip(range(data.shape[1]),
			[list(np.unique(col)) for col in data.T]))
		bn=BayesNet(oriented_edge_dict,value_dict)

		return bn
	else:
		return Mb[_T]


"""
PYTORCH DATASET CLASS
"""
import torch
from torch.utils.data import Dataset, DataLoader
import pytorch_lightning as pl

from COGS_Benchmark import train_src_lines, train_100_src_lines, train_100_tgt_lines, token2id, train_tgt_lines, \
    valid_src_lines, gen_src_lines, valid_tgt_lines, gen_tgt_lines, test_src_lines, test_tgt_lines

class COGSDataset(Dataset):
    def __init__(self, src_lines, tgt_lines, token2id):
        super().__init__()

        self.PAD_IDX = 0
        self.BOS_IDX = 1
        self.EOS_IDX = 2

        # tokenize data
        self.PAD_IDX = 0
        self.src_lines_tokenized = self.tokenize(src_lines, token2id)
        self.tgt_lines_tokenized = self.tokenize(tgt_lines, token2id)

    def tokenize(self, lines, token2id):
        # tokenize lines
        tokenized_lines = []
        for line in lines:
            tokenized_line = (
                [self.BOS_IDX]
                + [token2id[item] for item in line.split()]
                + [self.EOS_IDX]
            )
            tokenized_lines.append(tokenized_line)
        return tokenized_lines

    def __len__(self):
        return len(self.src_lines_tokenized)

    def __getitem__(self, idx):
        if torch.is_tensor(idx):
            idx = idx.tolist()
        input_seq = torch.tensor(self.src_lines_tokenized[idx])
        output_seq = torch.tensor(self.tgt_lines_tokenized[idx])
        return input_seq, output_seq

    def pad_tensor(self, tensor, max_length):
        tensor = torch.cat(
            [tensor, torch.zeros(max_length - tensor.shape[0], dtype=torch.int32)],
            dim=0,
        )
        return tensor

    def collate_fn(self, batch):
        # find longest sequences
        max_len_input = max([sample[0].shape[0] for sample in batch])
        max_len_output = max([sample[1].shape[0] for sample in batch])

        # pad according to max_length
        input_seq = [self.pad_tensor(sample[0], max_len_input) for sample in batch]
        output_seq = [self.pad_tensor(sample[1], max_len_output) for sample in batch]

        # stack all
        input_seq = torch.stack(input_seq, dim=0)
        output_seq = torch.stack(output_seq, dim=0)
        return input_seq, output_seq

"""
LIGHTNING DATAMODULE FOR COGS BENCHMARK
"""

class COGSDataModule(pl.LightningDataModule):
    def __init__(self, batch_size=32, num_workers=2, use_100=True, use_Gen=True):
        super().__init__()
        self.batch_size = batch_size
        self.num_workers = num_workers
        self.use_100 = use_100
        self.use_Gen = use_Gen

    def setup(self, stage=None):
        if stage == "fit" or stage is None:
            if self.use_100:
                self.train_dataset = COGSDataset(
                    train_100_src_lines, train_100_tgt_lines, token2id
                )
            else:
                self.train_dataset = COGSDataset(
                    train_src_lines, train_tgt_lines, token2id
                )
            self.valid_dataset = COGSDataset(valid_src_lines, valid_tgt_lines, token2id)
        if stage == "test" or stage is None:
            if self.use_Gen:
                self.test_dataset = COGSDataset(gen_src_lines, gen_tgt_lines, token2id)
            else:
                self.test_dataset = COGSDataset(test_src_lines, test_tgt_lines, token2id)

    def train_dataloader(self):
        return DataLoader(
            self.train_dataset,
            batch_size=self.batch_size,
            num_workers=self.num_workers,
            shuffle=True,
            drop_last=True,
            collate_fn=self.train_dataset.collate_fn,
        )

    def val_dataloader(self):
        return DataLoader(
            self.valid_dataset,
            batch_size=self.batch_size,
            num_workers=self.num_workers,
            shuffle=False,
            collate_fn=self.valid_dataset.collate_fn,
            drop_last=True,
        )

    def test_dataloader(self):
        return DataLoader(
            self.test_dataset,
            batch_size=4,
            num_workers=self.num_workers,
            shuffle=False,
            collate_fn=self.test_dataset.collate_fn,
            drop_last=True,
        )


#!/bin/env python

from modules.columns_number import columns_number_func
from termcolor import colored
from os import system
from modules.menu import menu
from modules.admin_db import read_settings, edit_settings
from modules.auto_start import *
from modules.strings_fitting import phrase_fitting, centered_phrase_fitting
from screens.update import update
from modules.create_db import create_db

def bold_blanco_centrado(n_cols, txt):
    return colored(centered_phrase_fitting(n_cols, txt), 'white', attrs=['bold'])

#Primer número indica si está marcado o no
#[[1,"1s", ": Sí"], [0, "1n", ": No"]]
def opcion(linea_azul_, linea_roja, numcols, descripcion, opciones):

    print(bold_blanco_centrado(numcols, descripcion))
    print(linea_azul_)

    for opcion in opciones:
        #Marcada
        if opcion[0] == 1:
            print(colored(opcion[1], 'green', 'on_white', attrs=['bold', 'dark']) + \
                    colored(opcion[2], 'grey', 'on_white', attrs=['bold', 'dark']))
        #No marcada
        else:
            print(colored(opcion[1], 'green', attrs=['bold', 'dark']) + opcion[2])
    print(linea_roja)

def settings():
    if read_settings("menu") != 'settings':
        edit_settings("previous_menu", str(read_settings("menu")))
    edit_settings("menu","settings")
    numcols = columns_number_func()

    #Líneas
    linea_azul = colored(numcols*"=", 'blue', attrs=['bold', 'dark'])
    linea_roja = colored(numcols*"=", 'red', attrs=['bold', 'dark'])
    linea_azul_ = colored(numcols*"-", 'blue', attrs=['bold', 'dark'])
    linea_roja_ = colored(numcols*"-", 'red', attrs=['bold', 'dark'])

    titulo = "CONFIGURACIÓN"
    print(linea_azul)
    print(((numcols - len(titulo))//2) * " " + titulo)
    print(linea_azul)
    print(linea_roja)

    #Actualizar ahora
    texto = centered_phrase_fitting(numcols, "Buscar actUalizaciones ahora")
    ind = texto.index("act")
    texto_1 = colored(texto[:ind + 3], 'white', attrs=['bold'])
    letra_u = colored("U", 'green', attrs=['bold', 'dark'])
    texto_2 = colored(texto[ind+4:], 'white', attrs=['bold'])

    print(texto_1 + letra_u + texto_2)
    print(linea_roja)

    #Verificar actualizaciones al iniciar
    updt = read_settings("auto_update")
    opcion(linea_azul_, linea_roja, numcols, \
            "Buscar actualizaciones al iniciar el programa", \
            [[updt, "1s", ": Sí"],[int("10"[updt]), "1n", ": No"]]
        )

    #Inicio automático
    inicio = read_settings("auto_start")
    opcion(linea_azul_, linea_roja, numcols, "Inicio automático al abrir Termux", \
            [[inicio, "2s", ": Sí"],[int("10"[inicio]), "2n", ": No"]]
        )

    #Ver una película y una carpeta por renglón
    oneline = read_settings("one_line")
    opcion(linea_azul_, linea_roja, numcols, "Un renglón para cada película/carpeta", \
            [[oneline, "3s", ": Sí"],[int("10"[oneline]), "3n", ": No"]])

    #Extensiones de video admitidas
    ext = read_settings("extensions")
    opcion(linea_azul_, linea_roja, numcols, "Extensiones de video admitidas", \
            [[ext.count("avi"), "4a", ": avi"],
            [ext.count("mkv"), "4k", ": mkv"],
            [ext.count("mp4"), "4m", ": mp4"]]
        )

    #Recodificar a UTF-8
    recode = read_settings("recode")
    opcion(linea_azul_, linea_roja, numcols, "Recodificar subtítulos a UTF-8", \
            [[recode, "5s", ": Sí"],[int("10"[recode]), "5n", ": No"]])

    #Fuentes de búsqueda
    scrapers = read_settings("sub_getters")
    opcion(linea_azul_, linea_roja, numcols, "Fuentes de búsqueda", [\
            [scrapers.count("subdivx"), "6s", ": subdivx"],
            [scrapers.count("opensubtitles"), "6o", ": opensubtitles"]
        ])

    #IDs descargables
    ids = read_settings("downloadable_ids")
    opcion(linea_azul_, linea_roja, numcols, "IDs descargables", [\
            [ids.count("page"), "7p", ": Página actual"],
            [ids.count("filtered"), "7f", ": Filtrados"],
            [ids.count("avaliables"), "7d", ": Disponibles"]
        ])

    #Reiniciar configuración
    texto = centered_phrase_fitting(numcols, "ReIniciar configuración")
    ind = texto.index("Re")
    texto_1 = colored(texto[:ind + 2], 'white', attrs=['bold'])
    letra_i = colored("I", 'green', attrs=['bold', 'dark'])
    texto_2 = colored(texto[ind+3:], 'white', attrs=['bold'])

    print(texto_1 + letra_i + texto_2)
    print(linea_roja)

    #Resultados por página
    rpp = str(read_settings("results_per_page"))
    texto = centered_phrase_fitting(numcols, "Resultados por página (#): " + rpp)
    ind = texto.index(":") - 2
    texto_1 = colored(texto[:ind], 'white', attrs=['bold'])
    numero = colored("#", 'green', attrs=['bold', 'dark'])
    texto_2 = colored(texto[ind + 1: ind + 4], 'white', attrs=['bold'])
    texto_3 = colored(rpp, 'grey', 'on_white', attrs=['bold'])
    print(texto_1 + numero + texto_2 + texto_3)
    print(linea_roja)

    i = menu(numcols, "Cambia una configuración")

    #Auxiliares para valores booleanos
    bool_1 = ["1n", "1s"]
    bool_2 = ["2n", "2s"]
    bool_3 = ["3n", "3s"]
    bool_5 = ["5n", "5s"]

    #Si la accion ingresada corresponde al menú, abre la respectiva pantalla
    if i[0] == "menu":
        return i[1]

    #Acciones:
    elif i[1] == "":
        return read_settings("previous_menu")

    #Actualizaciones ahora
    elif i[1].lower() == "u":
        if update() == 'exit_srq':
            return 'exit_srq'

    #Actualizaciones al iniciar
    elif i[1].lower() in bool_1:
        edit_settings("auto_update", str(bool_1.index(i[1])))

    #Inicio automático al abrir termux
    elif i[1].lower() in bool_2:
        edit_settings("auto_start", str(bool_2.index(i[1])))
        inicio_aut()

    #Un renglón por película/carpeta
    elif i[1].lower() in bool_3:
        edit_settings("one_line", str(bool_3.index(i[1])))

    #Recodificar a UTF-8
    elif i[1].lower() in bool_5:
        edit_settings("recode", str(bool_5.index(i[1])))

    #Extensiones de video admitidas
    elif i[1].lower() in ["4a", "4k", "4m"]:
        seleccion = i[1].lower()
        ext = read_settings("extensions").split(",")
        ext.sort()
        ext_editada = [x for x in ext]

        #Opcion extension
        op_ext = {"4a": "avi", "4k": "mkv", "4m": "mp4"}

        if op_ext[seleccion] not in ext_editada:
            ext_editada.append(op_ext[seleccion])
        elif len(ext_editada) > 1:
            ext_editada.remove(op_ext[seleccion])
        ext_editada.sort()

        if ext_editada != ext:
            edit_settings("extensions", ",".join(ext_editada))

    #Fuentes de búsqueda
    elif i[1].lower() in ["6s", "6o"]:
        seleccion = i[1].lower()
        fuentes = read_settings("sub_getters").split(",")
        fuentes.sort()
        fuentes_editada = [x for x in fuentes]

        #Opcion extension
        op_fuentes = {"6s": "subdivx", "6o": "opensubtitles"}

        if op_fuentes[seleccion] not in fuentes_editada:
            fuentes_editada.append(op_fuentes[seleccion])
        elif len(fuentes_editada) > 1:
            fuentes_editada.remove(op_fuentes[seleccion])
        fuentes_editada.sort()

        if fuentes_editada != fuentes:
            edit_settings("sub_getters", ",".join(fuentes_editada))

    #IDs descargables
    elif i[1].lower() in ["7p","7d","7f"]:
        seleccion = i[1].lower()

        op_selec = {
                "7p": "page",
                "7d": "avaliables",
                "7f": "filtered"
                }
        edit_settings("downloadable_ids", op_selec[seleccion])

    #Reiniciar configuración
    elif i[1].lower() == "i":
        system("rm '/data/data/com.termux/files/usr/share/srq-orquesta/srq-orquesta/data.db'")
        system("rm '/data/data/com.termux/files/usr/share/srq-orquesta/pip_freeze.txt'")
        system("rm '/data/data/com.termux/files/usr/share/srq-orquesta/pip_list.txt'")
        creadb()
        edit_settings("active_instance", "1")

    #Resultados por página
    elif i[1].isdigit():
        edit_settings("results_per_page", i[1])

    return 'settings'


import datetime as dt
import numpy as np
import pandas as pd
from datetime import datetime

import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func

from flask import Flask, jsonify

# Database Setup
engine = create_engine('sqlite:///hawaii.sqlite')

# reflect an existing database into a new model
Base = automap_base()
# reflect the tables
Base.prepare(engine, reflect=True)
# map measurement class
Measurement = Base.classes.measurement
# map station class
Station = Base.classes.station

# create our session (link) from Python to the DB
session = Session(engine)

# Flask Setup
app = Flask(__name__)

# Flask routes
@app.route("/")
def climate():
    '''List all available api routes.'''
    return(
        f'Available Routes:
'
        f'/api/v1.0/precipitation
'
        f'/api/v1.0/stations
'
        f'/api/v1.0/tobs
'
        f'/api/v1.0/start
'
        f'/api/v1.0/start/end
'
    )

@app.route('/api/v1.0/precipitation')
def precipitation():
    '''Query for the dates and prcp from the last year'''
    prev = dt.date.today() - dt.timedelta(days=365)
    query = session.query(Measurement.date,func.sum(Measurement.prcp)).filter(Measurement.date >= prev).group_by(Measurement.date).order_by(Measurement.date).all()

    '''convert the query results to a Dictionary using date as the key and prcp as the value'''
    results_list = []
    for measurement in query:
        results_dict = {}
        results_dict['date'] = measurement[0]
        results_dict['prcp'] = measurement[1]
        results_list.append(results_dict)
    '''return the json representation of your dictionary'''
    return jsonify(results_list)

@app.route('/api/v1.0/stations')
def stations():
    '''Return a json list of stations from the dataset'''
    stations = session.query(Station.station).all()
    return jsonify(stations)

@app.route('/api/v1.0/tobs')
def tobs():
    '''Return a json list of Temperature Observations (tobs) for the previous year'''
    prev = dt.date.today() - dt.timedelta(days=365)
    query_tobs = session.query(Measurement.date,Measurement.tobs).filter(Measurement.date >= prev).group_by(Measurement.date).order_by(Measurement.date).all()
    tobs_list = []
    for temp in query_tobs:
        tobs_dict = {}
        tobs_dict['date'] = temp[0]
        tobs_dict['tobs'] = temp[1]
        tobs_list.append(tobs_dict)
    return jsonify(tobs_list)

@app.route("/api/v1.0/temp/<start>")
@app.route("/api/v1.0/temp/<start>/<end>")
def stats(start=None, end=None):
    """Return TMIN, TAVG, TMAX."""

    # Select statement
    sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]

    if not end:
        # calculate TMIN, TAVG, TMAX for dates greater than start
        results = session.query(*sel).\
            filter(Measurement.date >= start).all()
        # Unravel results into a 1D array and convert to a list
        temps = list(np.ravel(results))
        return jsonify(temps)

    # calculate TMIN, TAVG, TMAX with start and stop
    results = session.query(*sel).\
        filter(Measurement.date >= start).\
        filter(Measurement.date <= end).all()
    # Unravel results into a 1D array and convert to a list
    temps = list(np.ravel(results))
    return jsonify(temps)

if __name__ == '__main__':
    app.run(debug=True)


# -*- coding: utf-8 -*-

"""
@author: Dariusz Koncewicz
@ email: d.koncewicz@sdacademy.pl
@site: www.dariuszkoncewicz.pl
"""

name = 'Python'

# %%
# print(name[0])
print(name[-2])
print(name[::-1])

# %%
# name[start:stop]
# name[:stop]
# name[start:]
# name[start:stop:step]
name[1:4]
name[:4]
name[2:]

name[:]

# %%
name[-3:]
name[-3:-1]

# %%
full = 'Python Programming'
print(full[7:])
print(full[::2])

# %%
sample = '#stop#this#flow'
print(sample[::5])

# %%
numbers = '8,9,7,4'
print(numbers[::2])

# %%
print(numbers[::-1])

# %%
name = 'kajak'
print(name[::-2])
# %%

name = 'Python'

'Py' in name
'java' in name


""" Specify imagenet model.

"""
import logging

import matplotlib.pyplot as plt
import numpy as np
import rawpy
import imageio
import tensorflow as tf
from tensorflow.python.framework import ops
import tensorflow.contrib.slim as slim

#from train_Sony import network

logger = logging.getLogger(__name__)

def create_placeholders(n_H, n_W, n_C):
    """
    Creates the placeholders for the tensorflow session.

    Note that the placeholders will most likely vary by input dataset.

    Arguments:
    n_H -- scalar, height of an input image
    n_W -- scalar, width of an input image
    n_C -- scalar, number of channels of the input

    Returns:
    X -- placeholder for the data input, of shape [None, n_H, n_W, n_C] and dtype "int"
    Y -- placeholder for the input labels, of shape and dtype equal to X
    """

    X = tf.placeholder(tf.float32, shape=(None, n_H, n_W, n_C))
    Y = tf.placeholder(tf.float32, shape=(None, n_H, n_W, n_C))

    return X,Y

def initialize_parameters():
    """
    Initializes weight parameters to build a neural network with tensorflow.
    The shapes are:
        []

    Returns:
    parameters -- a dictionary of tensors containing W1,...,WN
    """
    tf.set_random_seed(1)

    # Block 1

    W1 = tf.get_variable("W1", [3,3,3,32],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))
    W2 = tf.get_variable("W2", [3,3,32,32],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))

    # Block 2

    W3 = tf.get_variable("W3", [3,3,32,64],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))
    W4 = tf.get_variable("W4", [3,3,64,64],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))

    # Block 3

    W5 = tf.get_variable("W5", [3,3,64,128],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))
    W6 = tf.get_variable("W6", [3,3,128,128],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))

    # Block 4

    W7 = tf.get_variable("W7", [3,3,128,256],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))
    W8 = tf.get_variable("W8", [3,3,256,256],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))

    # Block 5

    W9 = tf.get_variable("W9", [3,3,256, 512],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))
    W10 = tf.get_variable("W10", [32,32,512,512],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))

    # Block 6

    W11 = tf.get_variable("W11", [3,3,512, 256],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))
    W12 = tf.get_variable("W12", [3,3,256, 256],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))

    # Block 7

    W13 = tf.get_variable("W13", [3,3,256,128],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))
    W14 = tf.get_variable("W14", [3,3,128,128],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))

    # Block 8

    W15 = tf.get_variable("W15", [3,3,128,64],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))
    W16 = tf.get_variable("W16", [3,3,64,64],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))

    # Block 9

    W17 = tf.get_variable("W17", [3,3,64,32],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))
    W18 = tf.get_variable("W18", [3,3,32,32],
                         initializer=\
                         tf.contrib.layers.xavier_initializer(seed = 0))

    # Block 10

    W19 = tf.get_variable('W19', [1,1,32, 12],
                          initializer=\
                          tf.contrib.layers.xavier_initializer(seed = 0))

    parameters = {
        'W1': W1, 'W2': W2, 'W3': W3, 'W4': W4, 'W5': W5, 'W6': W6,
        'W7': W7, 'W8': W8, 'W9': W9, 'W10':W10, 'W11': W11, 'W12': W12,
        'W13': W13, 'W14': W14, 'W15': W15, 'W16': W16, 'W17': W17,
        'W18': W18, 'W19': W19,
    }

    return parameters

def pool_block(X, Wa, Wb):
    """ This is like a mini forward propagation module. """
    Za = tf.nn.conv2d(X, Wa, strides=(1,1,1,1), padding='SAME')
    Aa = tf.nn.leaky_relu(Za, alpha=0.2)
    Zb = tf.nn.conv2d(Aa, Wb, strides=(1,1,1,1), padding='SAME')
    Ab = tf.nn.leaky_relu(Zb, alpha=0.2)
    P = tf.nn.max_pool(Ab, ksize=[1,2,2,1],
                        strides=[1,1,1,1], padding='SAME')
    return P

def conv_block(X, Wa, Wb):
    Za = tf.nn.conv2d(X, Wa, strides=(1,1,1,1), padding='SAME')
    Aa = tf.nn.leaky_relu(Za, alpha=0.2)
    Zb = tf.nn.conv2d(Aa, Wb, strides=(1,1,1,1), padding='SAME')
    Ab = tf.nn.leaky_relu(Zb, alpha=0.2)
    return Ab

def upsample_and_concat(x1, x2, output_channels, in_channels):
    pool_size = 2
    deconv_filter = tf.Variable(
        tf.truncated_normal([pool_size, pool_size, output_channels,
                             in_channels], stddev=0.02)
    )
    deconv = tf.nn.conv2d_transpose(x1, deconv_filter, tf.shape(x2),
                                    strides=[1, pool_size, pool_size, 1])

    deconv_output = tf.concat([deconv, x2], 3)
    deconv_output.set_shape([None, None, None, output_channels * 2])

    return deconv_output

def upsample_block(B, Bp, output_channels, in_channels, Wa, Wb):

    U = upsample_and_concat(B, Bp, output_channels, in_channels)
    Za = tf.nn.conv2d(U, Wa, strides=(1,1,1,1), padding='SAME')
    Aa = tf.nn.leaky_relu(Za, alpha=0.2)
    Zb = tf.nn.conv2d(Aa, Wb, strides=(1,1,1,1), padding='SAME')
    Ab = tf.nn.leaky_relu(Zb, alpha=0.2)
    return Ab

def output_block(X, W):

    Z = tf.nn.conv2d(X, W, strides=(1,1,1,1), padding='SAME')
    logger.debug("output block shape Z: {}".format(Z.get_shape()))
    Out = tf.depth_to_space(Z, 2)
    logger.debug("output block transform: {}".format(Out.get_shape()))
    return Out

def forward_propagation(X, parameters):

    # Block 1
    W1, W2 = parameters['W1'], parameters['W2']
    B1 = pool_block(X, W1, W2)
    logger.debug('B1 shape: {}'.format(B1.get_shape()))

    # Block 2
    W3, W4 = parameters['W3'], parameters['W4']
    B2 = pool_block(B1, W3, W4)
    logger.debug('B2 shape: {}'.format(B2.get_shape()))

    # Block 3
    W5, W6 = parameters['W5'], parameters['W6']
    B3 = pool_block(B2, W5, W6)
    logger.debug('B3 shape: {}'.format(B3.get_shape()))

    # Block 4
    W7, W8 = parameters['W7'], parameters['W8']
    B4 = pool_block(B3, W7, W8)
    logger.debug('B4 shape: {}'.format(B4.get_shape()))

    # Block 5
    W9, W10 = parameters['W9'], parameters['W10']
    B5 = conv_block(B4, W9, W10)
    logger.debug('B5 shape: {}'.format(B5.get_shape()))

    # Block 6
    W11, W12 = parameters['W11'], parameters['W12']
    B6 = upsample_block(B5, B4, 256, 512, W11, W12)
    logger.debug('B6 shape: {}'.format(B6.get_shape()))

    # Block 7
    W13, W14 = parameters['W13'], parameters['W14']
    B7 = upsample_block(B6, B3, 128, 256, W13, W14)
    logger.debug('B7 shape: {}'.format(B7.get_shape()))

    # Block 8
    W15, W16 = parameters['W15'], parameters['W16']
    B8 = upsample_block(B7, B2, 64, 128, W15, W16)
    logger.debug('B8 shape: {}'.format(B8.get_shape()))

    # Block 9
    W17, W18 = parameters['W17'], parameters['W18']
    B9 = upsample_block(B8, B1, 32, 64, W17, W18)
    logger.debug('B9 shape: {}'.format(B9.get_shape()))

    # Block 10
    W19 = parameters['W19']
    Bout = output_block(B9, W19)
    logger.debug('Bout shape: {}'.format(Bout.get_shape()))

    return Bout

def lrelu(x):
    return tf.maximum(x * 0.2, x)

def sony_network(input):
    conv1 = slim.conv2d(input, 32, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv1_1')
    conv1 = slim.conv2d(conv1, 32, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv1_2')
    pool1 = slim.max_pool2d(conv1, [2, 2], padding='SAME')
    logger.debug("pool1: {}".format(pool1.get_shape()))

    conv2 = slim.conv2d(pool1, 64, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv2_1')
    conv2 = slim.conv2d(conv2, 64, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv2_2')
    pool2 = slim.max_pool2d(conv2, [2, 2], padding='SAME')
    logger.debug("pool2: {}".format(pool2.get_shape()))

    conv3 = slim.conv2d(pool2, 128, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv3_1')
    conv3 = slim.conv2d(conv3, 128, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv3_2')
    pool3 = slim.max_pool2d(conv3, [2, 2], padding='SAME')
    logger.debug("pool3: {}".format(pool3.get_shape()))

    conv4 = slim.conv2d(pool3, 256, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv4_1')
    conv4 = slim.conv2d(conv4, 256, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv4_2')
    pool4 = slim.max_pool2d(conv4, [2, 2], padding='SAME')
    logger.debug("pool4: {}".format(pool4.get_shape()))

    conv5 = slim.conv2d(pool4, 512, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv5_1')
    conv5 = slim.conv2d(conv5, 512, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv5_2')
    logger.debug('conv5: {}'.format(conv5.get_shape()))

    up6 = upsample_and_concat(conv5, conv4, 256, 512)
    conv6 = slim.conv2d(up6, 256, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv6_1')
    conv6 = slim.conv2d(conv6, 256, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv6_2')
    logger.debug('conv6: {}'.format(conv6.get_shape()))

    up7 = upsample_and_concat(conv6, conv3, 128, 256)
    conv7 = slim.conv2d(up7, 128, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv7_1')
    conv7 = slim.conv2d(conv7, 128, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv7_2')
    logger.debug('conv7: {}'.format(conv7.get_shape()))

    up8 = upsample_and_concat(conv7, conv2, 64, 128)
    conv8 = slim.conv2d(up8, 64, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv8_1')
    conv8 = slim.conv2d(conv8, 64, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv8_2')
    logger.debug('conv8: {}'.format(conv8.get_shape()))

    up9 = upsample_and_concat(conv8, conv1, 32, 64)
    conv9 = slim.conv2d(up9, 32, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv9_1')
    conv9 = slim.conv2d(conv9, 32, [3, 3], rate=1, activation_fn=lrelu, scope='g_conv9_2')
    logger.debug('conv9: {}'.format(conv9.get_shape()))

    conv10 = slim.conv2d(conv9, 12, [1, 1], rate=1, activation_fn=None, scope='g_conv10')
    out = tf.depth_to_space(conv10, 2)
    logger.debug('out shape: {}'.format(out.get_shape()))
    return out

def compute_cost(Z, Y):
    """
    Computes the cost

    Arguments:
    Z -- output of forward propagation
    Y -- "true" image as a label, same shape as Z

    Returns:
    cost - Tensor of the cost function
    """
    cost = tf.reduce_mean(tf.abs(Z - Y))
    return cost

def random_mini_batches(m, minibatch_size, seed):
    """ Generator yielding minibatches """
    ids = [i for i in range(m)]
    np.random.seed(seed)
    np.random.shuffle(ids)

    for id_val in ids:
        yield id_val

def process_minibatch(minibatch_X, minibatch_Y, ps=16):

    mb_X = np.expand_dims(minibatch_X, axis=0)
    mb_Y = np.expand_dims(minibatch_Y, axis=0)

    _, H, W, _ = mb_X.shape

    xx = np.random.randint(0, W - ps)
    yy = np.random.randint(0, H - ps)

    X_patch = mb_X[:,yy:yy + ps, xx:xx + ps, :]
    Y_patch = mb_Y

    return X_patch, Y_patch

def cifar_model(X_train, Y_train, X_test, Y_test, learning_rate=1e-4,
                num_epochs=1, minibatch_size=32, print_cost=True):
    """
    Implements Learn-to-See-in-the-Dark for CIFAR dataset

    Arguments:
    X_train -- training set, of shape (None, 32, 32, 3)
    Y_train -- test set, of shape (None, 32, 32, 3)
    X_test -- training set, of shape (None, 32, 32, 3)
    Y_test -- test set, of shape (None, 32, 32, 3)
    learning_rate -- learning rate of the optimization
    num_epochs -- number of epochs of the optimization loop
    minibatch_size -- size of a minibatch
    print_cost -- True to print cost every 100 epochs

    Returns:
    parameters -- parameters learnt by the model. They can be used to predict.
    costs -- list of costs generated by the model
    learning_rate -- scalar real number, learning rate used by model
    """
    ops.reset_default_graph() # be able to rerun the model
    tf.set_random_seed(42)
    seed = 42
    m = X_train.shape[0]
    assert X_train.shape == Y_train.shape
    costs = []

    #X,Y = create_placeholders(n_H, n_W, n_C)
    #parameters = initialize_parameters()
    #Z = forward_propagation(X, parameters)

    X = tf.placeholder(tf.float32, [None, None, None, 3])
    Y = tf.placeholder(tf.float32, [None, None, None, 3])

    Z = sony_network(X)

    cost = compute_cost(Z, Y)

    # Backpropagation

    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

    # Initialize all the variables globally
    init = tf.global_variables_initializer()

    # Start the session to compute the tensorflow graph
    with tf.Session() as sess:

        # Run the initialization
        sess.run(init)

        # Do the training loop

        minibatches = random_mini_batches(m, minibatch_size, seed)

        logger.info("Starting epochs")
        for epoch in range(num_epochs):

            minibatch_cost = 0
            num_minibatches = int(m / minibatch_size)
            logger.debug('num minibatches: {}'.format(num_minibatches))
            seed = seed + 1
            minibatches = random_mini_batches(m, minibatch_size, seed)

            for minibatch in minibatches:

                # Select a minibatch
                minibatch_X = X_train[minibatch,...]
                minibatch_Y = Y_train[minibatch,...]

                minibatch_X, minibatch_Y = process_minibatch(minibatch_X, minibatch_Y)

                _, temp_cost, output = sess.run([optimizer, cost, Z],
                                        feed_dict={X: minibatch_X,
                                                   Y: minibatch_Y})

                minibatch_cost += temp_cost / num_minibatches

            # Print the cost every epoch
            if print_cost == True and epoch % 5 == 0:
                logger.info("Cost after epoch %i: %f" % (epoch,
                                                         minibatch_cost))
            if print_cost == True and epoch % 1 == 0:
                costs.append(minibatch_cost)

    # Write out image
    output = np.minimum(np.maximum(output, 0), 1)
    logger.info("output shape: {}".format(output.shape))
    imageio.imwrite("sony_network.jpg", output[0,...])
    parameters = {}

    return (parameters, costs, learning_rate)

def plot_costs(costs, learning_rate, filepath):
    """ plot the cost from forward propagation """
    plt.plot(np.squeeze(costs))
    plt.ylabel('cost')
    plt.xlabel('iterations (per tens)')
    plt.title("Learning rate =" + str(learning_rate))
    plt.savefig(filepath)


#!/usr/bin/env python3
import time
import sys
import numpy as np

import rclpy
from rclpy.action import ActionServer
from rclpy.node import Node
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist

from ex_solution.action import ExerciseAction

class ExerciseActionServer(Node):

    def __init__(self):
        super().__init__('exercise_action_server')
        self._action_server = ActionServer(
            self,
            ExerciseAction,
            'my',
            self.execute_callback)

        self.get_logger().info('Action Server is running...')

    def execute_callback(self, goal_handle):
        self.get_logger().info('Executing goal...')

        self.goal_reached = False

        start = time.time()

        result = ExerciseAction.Result()
        result.total_time = time.time() - start
        return result

def main(args=None):
    rclpy.init(args=args)

    exercise_action_server = ExerciseActionServer()

    rclpy.spin(exercise_action_server)

if __name__ == '__main__':
    main()


# 다음 소스는 N번째 피보나치 수를 구하는 C++ 함수이다.

# int fibonacci(int n) {
#     if (n == 0) {
#         printf("0");
#         return 0;
#     } else if (n == 1) {
#         printf("1");
#         return 1;
#     } else {
#         return fibonacci(n‐1) + fibonacci(n‐2);
#     }
# }
# fibonacci(3)을 호출하면 다음과 같은 일이 일어난다.

# fibonacci(3)은 fibonacci(2)와 fibonacci(1) (첫 번째 호출)을 호출한다.
# fibonacci(2)는 fibonacci(1) (두 번째 호출)과 fibonacci(0)을 호출한다.
# 두 번째 호출한 fibonacci(1)은 1을 출력하고 1을 리턴한다.
# fibonacci(0)은 0을 출력하고, 0을 리턴한다.
# fibonacci(2)는 fibonacci(1)과 fibonacci(0)의 결과를 얻고, 1을 리턴한다.
# 첫 번째 호출한 fibonacci(1)은 1을 출력하고, 1을 리턴한다.
# fibonacci(3)은 fibonacci(2)와 fibonacci(1)의 결과를 얻고, 2를 리턴한다.
# 1은 2번 출력되고, 0은 1번 출력된다. N이 주어졌을 때, fibonacci(N)을 호출했을 때, 0과 1이 각각 몇 번 출력되는지 구하는 프로그램을 작성하시오.

# import sys

# input = sys.stdin.readline

# T = int(input())
# fibo = [0, 1, 1]
# for i in range(3, 41):
#     number = fibo[i - 1] + fibo[i - 2]
#     fibo.append(number)
# for _ in range(T):
#     N = int(input())
#     if N == 0:
#         print(1, 0)
#     elif N == 1:
#         print(0, 1)
#     else:
#         print(fibo[N - 1], fibo[N])

import sys

input = sys.stdin.readline

T = int(input())

fibo = [0, 1, 1]
for i in range(3, 41):
    fibo.append(fibo[i - 1] + fibo[i - 2])
for _ in range(T):
    N = int(input())
    if N == 0:
        print(1, 0)
    elif N == 1:
        print(0, 1)
    else:
        print(fibo[N - 1], fibo[N])


from django.shortcuts import redirect
from django.template.response import TemplateResponse

from ...account.forms import get_address_form
from ...account.models import Address
from ..forms import AnonymousUserShippingForm, ShippingAddressesForm

def anonymous_user_shipping_address_view(request, checkout):
    """Display the shipping step for a user who is not logged in."""
    address_form, preview = get_address_form(
        request.POST or None, country_code=request.country.code,
        autocomplete_type='shipping',
        initial={'country': request.country.code},
        instance=checkout.shipping_address)

    user_form = AnonymousUserShippingForm(
        not preview and request.POST or None, initial={'email': checkout.email}
        if not preview else request.POST.dict())
    if all([user_form.is_valid(), address_form.is_valid()]):
        checkout.shipping_address = address_form.instance
        checkout.email = user_form.cleaned_data['email']
        return redirect('checkout:shipping-method')
    return TemplateResponse(
        request, 'checkout/shipping_address.html', context={
            'address_form': address_form, 'user_form': user_form,
            'checkout': checkout})

def user_shipping_address_view(request, checkout):
    """Display the shipping step for a logged in user.

    In addition to entering a new address the user has an option of selecting
    one of the existing entries from their address book.
    """
    data = request.POST or None
    additional_addresses = request.user.addresses.all()
    checkout.email = request.user.email
    shipping_address = checkout.shipping_address

    if shipping_address is not None and shipping_address.id:
        address_form, preview = get_address_form(
            data, country_code=request.country.code,
            initial={'country': request.country})
        addresses_form = ShippingAddressesForm(
            data, additional_addresses=additional_addresses,
            initial={'address': shipping_address.id})
    elif shipping_address:
        address_form, preview = get_address_form(
            data, country_code=shipping_address.country.code,
            instance=shipping_address)
        addresses_form = ShippingAddressesForm(
            data, additional_addresses=additional_addresses)
    else:
        address_form, preview = get_address_form(
            data, initial={'country': request.country},
            country_code=request.country.code)
        addresses_form = ShippingAddressesForm(
            data, additional_addresses=additional_addresses)

    if addresses_form.is_valid() and not preview:
        if (addresses_form.cleaned_data['address'] !=
                ShippingAddressesForm.NEW_ADDRESS):
            address_id = addresses_form.cleaned_data['address']
            checkout.shipping_address = Address.objects.get(id=address_id)
            return redirect('checkout:shipping-method')
        elif address_form.is_valid():
            checkout.shipping_address = address_form.instance
            return redirect('checkout:shipping-method')
    return TemplateResponse(
        request, 'checkout/shipping_address.html', context={
            'address_form': address_form, 'user_form': addresses_form,
            'checkout': checkout,
            'additional_addresses': additional_addresses})


# Python program to print even length words in a string

# method-1:

str = "How can i help you"

new_str = ""

for i in range(len(str)):
    if(i % 2 == 0):  # condition to choose only even number of position in the array which is i.
        new_str = new_str + str[i]    # assigning character by character only of even position of a string and store it in new_str

print("String1 of only even indexes is: ", new_str) # displaying of a string of only even postion values

# method-2:

# Obtain same output using a function

def evenDisplay(str1):
    str2 = "" # creation of a null value string which is further stores the new string of even position elements

    # code condition same as above method displays here.
    for i in range(len(str1)):
        if(i % 2 == 0):
            str2 = str2 + str1[i]

    return str2 # return of a new string as output

str1 = "Sure You Can"

str2 = ""

print("String2 of only even indexes is: ", evenDisplay(str1))


#! /usr/bin/env python
import os
import sys
import json
import finsymbols as data

if __name__ == '__main__':
    #a =data.get_sp500_symbols()
    a = data.get_amex_symbols()
    b = data.get_nyse_symbols()
    c = data.get_nasdaq_symbols()
    a +=b+c
    print(type(a), len(a))
    with open('ticker.json', 'w+') as outfile:
        json.dump(a, outfile)
    with open('ticker.txt', 'w+') as f:
        for line in a:
            f.write(str(line)+'\n')


"""Transformers for link prediction models based on combined text and layout embeddings."""

from __future__ import annotations
from sentence_transformers import SentenceTransformer
from link_prediction.models.classification.layout.layout_encoder import LayoutEncoder
from .types import (
    TextAndLayoutEncoding,
)
from link_prediction.datasets.figma import FigmaDataPoint
from link_prediction.datasets.rico import RicoDataPoint
from link_prediction.models.classification.text.preprocessing import (
    DataPointTransformer as TextDataPointTransformer,
)
from link_prediction.models.classification.layout.preprocessing import (
    DataPointTransformer as LayoutDataPointTransformer,
)
from link_prediction.models.classification.base import (
    DataPointTransformer as BaseDataPointTransformer,
)

class DataPointTransformer(BaseDataPointTransformer):
    def __init__(
        self,
        language_model=SentenceTransformer("all-MiniLM-L6-v2"),
        layout_model=LayoutEncoder(),
        number_of_neighbors=1,
    ):
        """Transformer to process RicoDataPoint into required format
        for TextAndLayoutClassifier."""
        self.text_transformer = TextDataPointTransformer(
            language_model=language_model,
            number_of_neighbors=number_of_neighbors,
        )
        self.layout_transformer = LayoutDataPointTransformer(
            layout_model=layout_model,
        )
        self.language_model = language_model
        self.layout_model = layout_model
        self.number_of_neighbors = number_of_neighbors
        super().__init__()

    def _encode_data_point(
        self, data_point: RicoDataPoint | FigmaDataPoint, *args, **kwargs
    ) -> TextAndLayoutEncoding:
        """Returns a vector encoding of the given data point
        using the text and layout embedding model.

        Examples
        --------
        Embedding a data point.

        >>> rico_data_point: RicoDataPoint = RicoDataPoint(
        ...      source=RicoDataPoint.RawSourceData(
        ...          id=795, element_id="2e18ce7"
        ...      ),
        ...      target=RicoDataPoint.RicoScreen(
        ...         id=887,
        ...      ),
        ...      application_name="com.vzw.indycar",
        ...      trace_id=0,
        ...      data_type="link",
        ... )
        >>> transformer = DataPointTransformer()
        >>> transformer._encode_data_point(rico_data_point)
        [0.01, 0.1, 0.5, ...]
        """
        text_encoding = self._encode_data_point_text(data_point)
        layout_encoding = self._encode_data_point_layout(data_point)
        return text_encoding + layout_encoding

    def _encode_data_point_text(
        self, data_point: RicoDataPoint | FigmaDataPoint, *args, **kwargs
    ) -> list:
        """Returns a vector encoding of the given data point's
        source element and target screen text using the language model

        Examples
        --------
        Embedding a data point's text.

        >>> rico_data_point: RicoDataPoint = RicoDataPoint(
        ...      source=RicoDataPoint.RawSourceData(
        ...          id=795, element_id="2e18ce7"
        ...      ),
        ...      target=RicoDataPoint.RicoScreen(
        ...         id=887,
        ...      ),
        ...      application_name="com.vzw.indycar",
        ...      trace_id=0,
        ...      data_type="link",
        ... )
        >>> transformer = DataPointTransformer()
        >>> transformer._encode_data_point_text(rico_data_point)
        [0.01, 0.1, 0.5, ...]
        """
        text_encoding = self.text_transformer.transform([data_point])[0]
        return text_encoding

    def _encode_data_point_layout(
        self, data_point: RicoDataPoint | FigmaDataPoint, *args, **kwargs
    ) -> list:
        """Returns a vector encoding of the given data point's
        source screen and target screen layout using the layout model

        Examples
        --------
        Embedding a data point's layout.

        >>> rico_data_point: RicoDataPoint = RicoDataPoint(
        ...      source=RicoDataPoint.RawSourceData(
        ...          id=795, element_id="2e18ce7"
        ...      ),
        ...      target=RicoDataPoint.RicoScreen(
        ...         id=887,
        ...      ),
        ...      application_name="com.vzw.indycar",
        ...      trace_id=0,
        ...      data_type="link",
        ... )
        >>> transformer = DataPointTransformer()
        >>> transformer._encode_data_point_layout(rico_data_point)
        [0.01, 0.1, 0.5, ...]
        """
        layout_encoding = self.layout_transformer.transform([data_point])[0]
        return layout_encoding

def main() -> None:
    """Test transformers."""
    transformer = DataPointTransformer()
    rico_data_point: RicoDataPoint = RicoDataPoint(
        source=RicoDataPoint.RawSourceData(id=795, element_id="2e18ce7"),
        target=RicoDataPoint.RicoScreen(
            id=887,
        ),
        application_name="com.vzw.indycar",
        trace_id=0,
        data_type="link",
    )
    embedding = transformer.transform([rico_data_point])[0]
    assert isinstance(embedding, list)
    assert isinstance(embedding[0], float)

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('werapp', '0001_initial'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='event',
            name='is_paid',
        ),
        migrations.AddField(
            model_name='event',
            name='price_support',
            field=models.FloatField(default=0),
            preserve_default=True,
        ),
    ]


redtotal=0
red=[10,8,7,9,10,10,9,8,7,9]
for i in range(10):
  redtotal = redtotal + red[i]
# subtract max and min
print("red scores",redtotal)

bluetotal=0
blue=[17,9,6,8,7,4,10,8,7,9]
for i in range(10):
  bluetotal = bluetotal + blue[i]
bluetotal = bluetotal - max(blue) - min(blue)
print("blue scores",bluetotal)
if bluetotal > redtotal:
    print("blue wins!")
elif bluetotal == redtotal:
    print("draw!")
else:
    print("red wins!")

print(max(red))
print(min(red))


import sqlite3
import json

conn = sqlite3.connect('py4everyone/UsingDatabases/Week4/wk4_assignment.sqlite')
cur = conn.cursor()

cur.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Course;
DROP TABLE IF EXISTS Member;

CREATE TABLE User(
    id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    name TEXT UNIQUE
);

CREATE TABLE Course(
    id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    title TEXT UNIQUE
);

CREATE TABLE Member(
    user_id INTEGER,
    course_id INTEGER,
    role INTEGER,
    PRIMARY KEY (user_id, course_id)
);
''')

fname = input('Enter file name: ')
if (len(fname) < 1): fname = 'roster_data.json'
jsonFile = open("/Users/conanchan/Documents/Coursera/py4everyone/UsingDatabases/Week4/"+fname)
data = json.load(jsonFile)

for entry in data:
    name = entry[0]
    course = entry[1]
    role = entry[2]
    cur.execute('INSERT OR IGNORE INTO User (name) VALUES (?)', (name,))
    cur.execute('INSERT OR IGNORE INTO Course (title) VALUES (?)', (course,))
    # Run select statement to get ID of user and Course
    cur.execute('SELECT id FROM User WHERE name = ?', (name,))
    user_id = cur.fetchone()[0]
    cur.execute('SELECT id FROM Course WHERE title = ?',(course,))
    course_id = cur.fetchone()[0]
    cur.execute('INSERT OR IGNORE INTO Member (user_id, course_id, role) VALUES (?,?,?)', (user_id, course_id, role,))

    conn.commit()
conn.close()


def smart_dev(fun):
    def inner(x,y):
        print("Devition process : ", x , y )
        if  y == 0 :
            print("there is no devition like this ")
            return
        return fun(x,y)
    return inner

@smart_dev
def dev(x,b):
    return x/b
print(dev(6,2))
print(dev(0,5))
print(dev(6,10))
print(dev(6,112))


import socket
import requests
from mcstatus import JavaServer
from dankware import multithread, chdir, clr, cls, title, clr_banner, align, random_ip, magenta

'''

for the future of this script

Goals: masscan port scans

https://github.com/MyKings/python-masscan
https://github.com/Arryboom/MasscanForWindows
https://github.com/rezonmain/mc-server-scanner/blob/main/src/iprange.py
https://github.com/ObscenityIB/creeper/blob/main/creeper.sh
https://raw.githubusercontent.com/robertdavidgraham/masscan/master/data/exclude.conf
https://github.com/Footsiefat/Minecraft-Server-Scanner

'''

# checks if ip has a server running on port 25565

def check(ip):

    if socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect_ex((ip,25565)) == 0:
        try:
            server = JavaServer(ip, 25565)
            status = server.status()
            #try: query = server.query(); query_response = f"| {query.software}"
            #except: query_response = ""
            response = requests.get(f"http://ipwho.is/{ip}").json()
            to_print = f"{ip} | {status.version.name} | {status.players.online} online | {int(status.latency)}ms | {response['city']} | {response['connection']['org']} | {response['connection']['domain']} | {status.description}".replace('\n','|')
            for _ in ['§0', '§1', '§2', '§3', '§4', '§5', '§6', '§7', '§8', '§9', '§a', '§b', '§c', '§d', '§e', '§f', '§l', '§n', '§o', '§m', '§k', '§r']: to_print = to_print.replace(_,'')
            print(clr(f"  > {to_print}\n"))
            open('servers.txt','a').write(f"\n{to_print}")
        except Exception as exc:
            exc = str(exc)
            err_found = False

            for err in ["timed out", "unreachable", "refused", "not valid", "invalid", "closed", "did not", "aborted", "failed", "no route", "Broken pipe"]:
                if err in exc:
                    err_found = True; break

            if not err_found:
                open('servers.txt','a').write(f"\n{ip} | {exc}")
                print(f"{ip} | {exc}\n")

# generates random valid ip

def generate():

    while True:
        ip = random_ip()
        if ip in ips or ip in scanned: continue
        ips.append(ip); break

def main():

    global ips, scanned

    title("dank.minecraft-server-scanner"); banner = '\n\n     _             _                                                              \n    | |           | |                                                             \n  _ | | ____ ____ | |  _   ____   ____ ___ ___  ____ ____ ____  ____   ____  ____ \n / || |/ _  |  _ \\| | / ) |    \\ / ___|___)___)/ ___) _  |  _ \\|  _ \\ / _  )/ ___)\n( (_| ( ( | | | | | |< ( _| | | ( (___   |___ ( (__( ( | | | | | | | ( (/ /| |    \n \\____|\\_||_|_| |_|_| \\_|_)_|_|_|\\____)  (___/ \\____)_||_|_| |_|_| |_|\\____)_|    \n                                                                                \n'
    socket.setdefaulttimeout(1)

    exec_mode = "script"; exec(chdir(exec_mode))
    try: open('scanned.txt','x')
    except: pass
    try: open('servers.txt','x')
    except: pass
    scanned = sorted(list(set(open('scanned.txt','r').read().splitlines())))
    servers = sorted(list(set(open('servers.txt','r').read().splitlines())))
    open('servers.txt','w').write('\n'.join(servers))

    while True:
        cls(); print(align(clr_banner(banner)))
        threads = input(clr("\n  > The scanned.txt file stores the ips that have been scanned, and thus will not be scanned again.\n\n  > Delete this file to reset scanned ips.\n\n  > Start with [ 100 threads ] just to see the performance impact on your computer.\n\n  > Should be smooth upto 500, you might notice some performance impact after this point!\n\n  > Start with 50000 IPs, will take a few seconds to generate.\n\n  > The scanned.txt is only updated after the scan is complete.\n\n  > Threads: ") + magenta)
        if threads.isdigit(): threads = int(threads)
        else: continue
        ips_amt = input(clr("\n  > Amount of IPs to scan: ") + magenta)
        if ips_amt.isdigit(): ips_amt = int(ips_amt); break

    cls(); print(clr(f"\n  > Generating {ips_amt} ips...\n"))
    ips = []; temp_ips_amt = ips_amt
    while temp_ips_amt >= 500:
        multithread(generate, 500, progress_bar=False)
        temp_ips_amt -= 500
    if temp_ips_amt > 0: multithread(generate, temp_ips_amt, progress_bar=False)

    ips = list(set(ips))
    cls(); print(clr(f"\n  > Checking {ips_amt} ips...\n"))
    multithread(check, threads, ips)

    scanned = sorted(list(set(scanned + ips)))
    open('scanned.txt','w').write('\n'.join(scanned))
    #cls(); print(clr(f"\n > Scanning Complete! Sleeping 5s...")); time.sleep(5)

if __name__ == "__main__":
    main()


"""Event Container.

Motivation: After the events are read from the event packet,
it's difficult to use and less informative to return them
as single variables, therefore, I decide to introduce a
container that can manage all the returned Python variables.

Author: Yuhuang Hu
Email : duguyue100@gmail.com
"""

from typing import Optional

import numpy as np

class EventContainer(object):
    """Event container that packs everything.

    Args:
        pol_events: polarity events array.
        special_events: special events.
        frames: APS frame events.
        frames_ts: APS frame time stamp.
        imu_events: IMU events.
    """

    def __init__(
        self,
        pol_events: np.ndarray,
        special_events: Optional[np.ndarray] = None,
        frames: Optional[np.ndarray] = None,
        frames_ts: Optional[np.ndarray] = None,
        imu_events: Optional[np.ndarray] = None,
    ) -> None:
        self.pol_events = pol_events
        self.num_pol_events = 0 if pol_events is None else pol_events.shape[0]
        self.compute_event_stats()

        self.special_events = special_events
        self.num_special_events = (
            None if special_events is None else special_events.shape[0]
        )

        self.frames = frames
        self.frames_ts = frames_ts

        self.imu_events = imu_events
        self.num_imu_events = None if imu_events is None else imu_events.shape[0]

    def compute_event_stats(self) -> None:
        """Calculate event stats."""
        self.pol_event_duration = None
        self.pol_event_rate = None

        self.num_valid_pol_events = None
        self.num_invalid_pol_events = None
        self.valid_pol_events_rate = None
        self.invalid_pol_events_rate = None

        if self.num_pol_events > 1:
            # in seconds
            self.pol_event_duration = (
                self.pol_events[-1, 0] - self.pol_events[0, 0]
            ) / 1e6

            self.pol_event_rate = self.num_pol_events / self.pol_event_duration

            # additional stats if has background filter
            if self.pol_events.shape[1] == 5:
                self.num_valid_pol_events = self.pol_events[:, -1].sum()
                self.num_invalid_pol_events = (
                    self.num_pol_events - self.num_valid_pol_events
                )

                self.valid_pol_events_rate = (
                    self.num_valid_pol_events / self.pol_event_duration
                )
                self.invalid_pol_events_rate = (
                    self.num_invalid_pol_events / self.pol_event_duration
                )


# app/main/routes.py
from datetime import datetime
from twilio.rest import Client
# HTML template module
from flask import flash, redirect, render_template, request, url_for
from flask import g, jsonify
from flask_babel import _, lazy_gettext as _l
from flask_login import current_user, login_required
from app import current_app, db
from app.main import bp
from app.main.forms import EditProfileForm, EmptyForm, MessageForm
from app.main.forms import PrivateMessageForm, SearchForm
# Commmunicate logins with the db
from app.models import User, Message, PrivateMessage, Notification

@bp.before_request
def before_request():
    if current_user.is_authenticated:
        current_user.last_seen = datetime.utcnow()
        db.session.commit()
        g.search_form = SearchForm()
#    g.locale = str(get_locale())

@bp.route("/", methods=['GET', 'POST'])
@bp.route("/index", methods=['GET', 'POST'])
@login_required
def home():
    #    if current_user.is_authenticated:
    #        flash("You are logged in as {}".format(current_user.username))
    print(current_app.config)

    messages = []
    form = MessageForm()

    if form.validate_on_submit():
        msg = Message(body=form.message.data, sender=current_user)
        db.session.add(msg)
        db.session.commit()
        flash("You sent a message!")
        return redirect(url_for('main.home'))

    page = request.args.get('page', 1, type=int)
    messages = current_user.followed_messages().paginate( page, current_app.config['MESSAGES_PER_PAGE'], False)
    next_url = url_for('main.home', page=messages.next_num) if messages.has_next else None
    prev_url = url_for('main.home', page=messages.prev_num) if messages.has_prev else None

    # messages = current_user.followed_messages().all()

    return render_template("index.html", title=current_app.config['TITLE'] + " - Send",
             form=form,
             messages=messages.items,
             next_url=next_url,  prev_url=prev_url
             )

@bp.route('/sms')
@login_required
def send_message():
    #  and set the environment variables. See http://twil.io/secure
    # account_sid = os.environ['TWILIO_ACCOUNT_SID']
    # auth_token = os.environ['TWILIO_AUTH_TOKEN']
    form = MessageForm()
    if form.validate_on_submit():
        msg = Message(body=form.message.data, sender=current_user).filter()
        db.session.add(msg)
        db.session.commit()
        flash("You sent a message!")
        return redirect(url_for('main.home'))

    msg = {'body': "One long message",
           'from_': '+someNumber', 'to': '+1someNumber'}
    # client = Client(current_app.config['TWILIO_ACCOUNT_SID'],
    # current_app.config['TWILIO_AUTH_TOKEN'])
    print(current_app.config)
    message = None
    # message = client.messages.create(**msg)
    #    .create(
    #         body="One long message",
    #         from_='+someNumber',
    #         to='+1someNumber'
    #     )

    msg['sid'] = message.id if message else "Fred"
    # print(message.sid)
    return render_template("index.html", title=current_app.config['TITLE'] + " - Send", form=form, msg=msg)

@bp.route('/send_private_message/<recipient>', methods=['GET', 'POST'])
@login_required
def send_private_message(recipient):
    user = User.query.filter_by(username=recipient).first_or_404()
    form = PrivateMessageForm()
    if form.validate_on_submit():
        msg = PrivateMessage(sender=current_user, recipient=user,
                      body=form.message.data)
        db.session.add(msg)
        db.session.commit()
        flash(_('Your message has been sent.'))
        current_user.add_notification('unread_private_message_count', user.new_private_messages())
        db.session.commit()
        return redirect(url_for('main.user', username=recipient))
    return render_template('send_private_message.html', title=_('Send Message'),
                           form=form, recipient=recipient)

@bp.route('/private_messages')
@login_required
def private_messages():
    current_user.last_private_message_read_time = datetime.utcnow()
    db.session.commit()
    page = request.args.get('page', 1, type=int)
    messages = current_user.private_messages_received.order_by(
        PrivateMessage.timestamp.desc()).paginate(
            page, current_app.config['MESSAGES_PER_PAGE'], False)
    current_user.add_notification('unread_private_message_count', 0)
    db.session.commit()
    next_url = url_for('main.private_messages', page=messages.next_num) \
        if messages.has_next else None
    prev_url = url_for('main.private_messages', page=messages.prev_num) \
        if messages.has_prev else None
    return render_template('private_messages.html', messages=messages.items,
                           next_url=next_url, prev_url=prev_url)

# ------------------------------------------------------------------------------
#    User Profile
# ------------------------------------------------------------------------------

@bp.route('/user/<username>', methods=['GET', 'POST'])
@login_required
def user(username):
    user = User.query.filter_by(username=username).first_or_404()
    messages = current_user.followed_messages().all()

    # EmptyForm for FollowFollowers
    form = EmptyForm()
    return render_template('user.html', user=user, messages=messages, form=form)

@bp.route('/user/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfileForm(current_user.username)

    if form.validate_on_submit():
        current_user.username = form.username.data
        current_user.about_me = form.about_me.data
        db.session.commit()
        flash("Your profile has been changed")
        return redirect(url_for('main.edit_profile'))
    elif request.method == 'GET':
        form.username.data = current_user.username
        form.about_me.data = current_user.about_me

    return render_template('edit_profile.html', title='Edit Profile', form=form)

# ------------------------------------------------------------------------------
#    Follow and Unfollow
# ------------------------------------------------------------------------------

@bp.route('/follow/<username>', methods=['POST'])
@login_required
def follow(username):
    form = EmptyForm()

    if form.validate_on_submit():
        user = User.query.filter_by(username=username).first()
        if user is None:
            flash("User, {1} doesn't exist!".format(username))
            return redirect(url_for('main.home'))
        if user == current_user:
            flash("You cannot follow yourself!")
            return redirect(url_for('main.user', username=username))

        current_user.follow(user)
        db.session.commit()
        flash("You are now followng {}!".format(user.username))
        return redirect(url_for('main.user', username=username))
    else:
        return redirect(url_for('main.home'))

@bp.route('/unfollow/<username>', methods=['POST'])
@login_required
def unfollow(username):
    form = EmptyForm()

    if form.validate_on_submit():
        user = User.query.filter_by(username=username).first()
        if user is None:
            flash("User, {1} doesn't exist!".format(username))
            return redirect(url_for('main.home'))
        if user == current_user:
            flash("You cannot unfollow yourself!")
            return redirect(url_for('main.user', username=username))

        current_user.unfollow(user)
        db.session.commit()
        flash("You have stopped followng {}!".format(user.username))
        return redirect(url_for('main.user', username=username))
    else:
        return redirect(url_for('main.home'))

# ------------------------------------------------------------------------------
#    Navigation
# ------------------------------------------------------------------------------
@bp.route('/explore')
@login_required
def explore():

    page = request.args.get('page', 1, type=int)
    messages = Message.query.order_by(Message.timestamp.desc()).paginate(page, current_app.config['MESSAGES_PER_PAGE'], False)
    next_url = url_for('main.explore', page=messages.next_num) if messages.has_next else None
    prev_url = url_for('main.explore', page=messages.prev_num) if messages.has_prev else None
    return render_template('index.html', title='Explore', messages=messages.items, next_url=next_url,  prev_url=prev_url)

@bp.route('/search')
@login_required
def search():
    # Use this type of form validation for GET requests
    if not g.search_form.validate():
        return redirect(url_for('main.explore'))
    page = request.args.get('page', 1, type=int)
    messages, total = Message.search(
        g.search_form.q.data, page, current_app.config['MESSAGES_PER_PAGE'])
    next_url = url_for('main.search', q.search_form.q.data, page=page + 1) \
        if total > current_app.config['MESSAGES_PER_PAGE'] * page else None
    prev_url = url_for('main.search', q.search_form.q.data, page=page - 1) \
        if page > 1 else None
    return render_template('search.html', title=_('Search'), messages=messages.items,
                           next_url=next_url, prev_url=prev_url)

# ------------------------------------------------------------------------------
#    Services
# ------------------------------------------------------------------------------

@bp.route('/notifications')
@login_required
def notifications():
    since = request.args.get('since', 0.0, type=float)
    notifications = current_user.notifications.filter(
        Notification.timestamp > since).order_by(Notification.timestamp.asc())
    return jsonify([{
        'name': n.name,
        'data': n.get_data(),
        'timestamp': n.timestamp
    } for n in notifications])

@bp.route('/export_messages')
@login_required
def export_messages():
    if current_user.get_task_in_progress('export_messages'):
        flash(_('Theres an export task already in progress'))
    else:
        current_user.launch_task('export_messages', _('Exporting messages...'))
        db.session.commit()
    return redirect(url_for('main.user', username=current_user.username))


# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# Calculate flow accumulation
# Author: Timm Nawrocki
# Last Updated: 2023-10-19
# Usage: Execute in ArcGIS Pro Python 3.9+.
# Description: "Calculate flow accumulation" is a function that calculates flow accumulation from a float elevation raster.
# ---------------------------------------------------------------------------

# Define function to calculate flow accumulation
def calculate_flow(area_raster, elevation_float, flow_direction, flow_accumulation):
    """
    Description: calculates 32-bit float flow direction and accumulation rasters
    Inputs: 'area_raster' -- a raster of the study area to set snap raster and extract area
            'elevation_float' -- an input float elevation raster
            'flow_accumulation' -- a file path for an output float flow direction raster
    Returned Value: Returns a raster dataset on disk
    Preconditions: requires float input elevation raster
    """

    # Import packages
    import arcpy
    from arcpy.sa import DeriveContinuousFlow
    from arcpy.sa import Raster
    from arcpy.sa import FocalStatistics
    from arcpy.sa import NbrRectangle

    # Set overwrite option
    arcpy.env.overwriteOutput = True

    # Specify core usage
    arcpy.env.parallelProcessingFactor = "75%"

    # Set snap raster and extent
    arcpy.env.snapRaster = area_raster
    arcpy.env.extent = Raster(area_raster).extent

    # Set cell size environment
    cell_size = arcpy.management.GetRasterProperties(area_raster, 'CELLSIZEX', '').getOutput(0)
    arcpy.env.cellSize = int(cell_size)

    # Smooth elevation
    print('\tSmoothing elevation...')
    neighborhood = NbrRectangle(7, 7, 'CELL')
    elevation_smoothed = FocalStatistics(Raster(elevation_float), neighborhood, 'MEAN', 'DATA')

    # Calculate flow direction
    print('\tCalculating flow accumulation...')
    accumulation_raster = DeriveContinuousFlow(elevation_smoothed,
                                               '',
                                               '',
                                               flow_direction,
                                               'MFD',
                                               'NORMAL')

    print('\tExporting flow accumulation raster as 32-bit float...')
    arcpy.management.CopyRaster(accumulation_raster,
                                flow_accumulation,
                                '',
                                '',
                                '-2147483648',
                                'NONE',
                                'NONE',
                                '32_BIT_FLOAT',
                                'NONE',
                                'NONE',
                                'TIFF',
                                'NONE',
                                'CURRENT_SLICE',
                                'NO_TRANSPOSE')


import os

# windows bug
os.system("")

class Cologger:
    def __init__(self):
        self.color = None
        self.bg_color = None
        self.fmt = None

    def set_fmt(self, fmt):
        if fmt == "bold":
            self.fmt = Formaters.BOLD
        elif fmt == "italic":
            self.fmt = Formaters.ITALIC
        elif fmt == "underline":
            self.fmt = Formaters.UNDERLINE
        elif fmt == "selected":
            self.fmt = Formaters.SELECTED
        elif fmt == "strikethrough":
            self.fmt = Formaters.STRIKETHORUGH
        else:
            raise Exception("Please pass a valid format.")

    def set_color(self, color, custom=""):
        if color == "black":
            self.color = Colors.BLACK
        elif color == "red":
            self.color = Colors.RED
        elif color == "green":
            self.color = Colors.GREEN
        elif color == "yellow":
            self.color = Colors.YELLOW
        elif color == "green":
            self.color = Colors.GREEN
        elif color == "blue":
            self.color = Colors.BLUE
        elif color == "violet":
            self.color = Colors.VIOLET
        elif color == "cyan":
            self.color = Colors.CYAN
        elif color == "white":
            self.color = Colors.WHITE
        elif color == "custom":
            self.color = "\033[38;2;{};{};{}m{}\033[0m".format(
                str(custom[0]), str(custom[1]), str(custom[2]), "X"
            )
        else:
            raise Exception("Please pass a valid color.")

    def set_bg(self, color, custom=""):
        if color == "black":
            self.bg_color = BackgroundColors.BLACK
        elif color == "red":
            self.bg_color = BackgroundColors.RED
        elif color == "green":
            self.bg_color = BackgroundColors.GREEN
        elif color == "yellow":
            self.bg_color = BackgroundColors.YELLOW
        elif color == "green":
            self.bg_color = BackgroundColors.GREEN
        elif color == "blue":
            self.bg_color = BackgroundColors.BLUE
        elif color == "violet":
            self.bg_color = BackgroundColors.VIOLET
        elif color == "cyan":
            self.bg_color = BackgroundColors.CYAN
        elif color == "white":
            self.bg_color = BackgroundColors.WHITE
        elif color == "custom":
            self.bg_color = "\033[48;2;{};{};{}m{}\033[0m".format(
                str(custom[0]), str(custom[1]), str(custom[2]), "X"
            )
        else:
            raise Exception("Please pass a valid color.")

    def colog(self, *args):
        # If statements:
        # 1. none
        # 2. color
        # 3. bg
        # 4. fmt
        # 5. color, bg
        # 6. color, fmt
        # 7. bg, fmt
        # 8. all

        if self.color != None:
            if "X" in self.color:
                index = self.color.index("X")

                string = ""
                for i in list(args):
                    string += str(i) + " "

                self.color = list(self.color)

                self.color[index] = string
                print("".join(self.color))
                return

        if self.bg_color != None:
            if "X" in self.bg_color:
                index = self.bg_color.index("X")

                string = ""
                for i in list(args):
                    string += str(i) + " "

                self.bg_color = list(self.bg_color)

                self.bg_color[index] = string
                print("".join(self.bg_color))
                return

        if self.color == None and self.bg_color == None and self.fmt == None:
            print(*args)
        elif self.color != None and self.bg_color == None and self.fmt == None:
            print(self.color + cologger_print(*args))
        elif self.color == None and self.bg_color != None and self.fmt == None:
            print(self.bg_color + cologger_print(*args))
        elif self.color == None and self.bg_color == None and self.fmt != None:
            print(self.fmt + cologger_print(*args))
        elif self.color != None and self.bg_color != None and self.fmt == None:
            print(self.color + self.bg_color + cologger_print(*args))
        elif self.color != None and self.bg_color == None and self.fmt != None:
            print(self.color + self.fmt + cologger_print(*args))
        elif self.color != None and self.bg_color == None and self.fmt != None:
            print(self.color + self.fmt + cologger_print(*args))
        elif self.color == None and self.bg_color != None and self.fmt != None:
            print(self.bg_color + self.fmt + cologger_print(*args))
        else:
            print(self.fmt + self.color + self.bg_color + cologger_print(*args))

    def error(self, text):
        return print(Colors.RED + cologger_print(text))

    def info(self, text):
        return print(Colors.WHITE + cologger_print(text))

    def debug_var(self, var):
        return print(f"""\n-----------------------\n{var}\n-----------------------""")

    def reset_color(self):
        self.color = None

    def reset_bg_color(self):
        self.bg_color = None

    def reset_fmt(self):
        self.fmt = None

class Formaters:
    END = "\33[0m"
    BOLD = "\33[1m"
    ITALIC = "\33[3m"
    UNDERLINE = "\33[4m"
    SELECTED = "\33[7m"
    STRIKETHORUGH = '\033[09m'

class Colors:
    BLACK = "\33[30m"
    RED = "\33[31m"
    GREEN = "\33[32m"
    YELLOW = "\33[33m"
    BLUE = "\33[34m"
    VIOLET = "\33[35m"
    CYAN = "\33[36m"
    WHITE = "\33[37m"

    BRIGHT_BLACK = "\033[90m"
    BRIGHT_RED = "\033[91m"
    BRIGHT_GREEN = "\033[92m"
    BRIGHT_YELLOW = "\033[93m"
    BRIGHT_BLUE = "\033[94m"
    BRIGHT_VIOLET = "\033[95m"
    BRIGHT_CYAN = "\033[96m"
    BRIGHT_WHITE = "\033[97m"

class BackgroundColors:
    BLACK = "\33[40m"
    RED = "\33[41m"
    GREEN = "\33[42m"
    YELLOW = "\33[43m"
    BLUE = "\33[44m"
    VIOLET = "\33[45m"
    CYAN = "\33[46m"
    WHITE = "\33[47m"

    BRIGHT_BLACK = "\033[100m"
    BRIGHT_RED = "\033[101m"
    BRIGHT_GREEN = "\033[102m"
    BRIGHT_YELLOW = "\033[103m"
    BRIGHT_BLUE = "\033[104m"
    BRIGHT_VIOLET = "\033[105m"
    BRIGHT_CYAN = "\033[106m"
    BRIGHT_WHITE = "\033[107m"

def cologger_print(*args):
    final_str = ""
    for i in list(args):
        final_str += str(i) + " "
    return final_str + Formaters.END

def main():
    cologger = Cologger()
    cologger.set_bg("custom", [255, 255, 255])  # white rgb code
    cologger.colog("Hello Cologger!")

main()


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

# In[93]:

import seaborn as sns
import matplotlib.pyplot as plt

# In[94]:

# Load the 'titanic' dataset from Seaborn
titanic = sns.load_dataset('titanic')

# In[96]:

# Convert 'fare' column to numeric
titanic['fare'] = pd.to_numeric(titanic['fare'], errors='coerce')

# In[97]:

# Plot a histogram of the ticket prices
sns.histplot(data=titanic, x="fare", kde=True)
plt.xlabel("Ticket Price")
plt.ylabel("Frequency")
plt.title("Distribution of Ticket Prices")
plt.show()

# In[ ]:


from flask import Flask, render_template, request

# questions = None# 7 done

with open ("questions.txt", "r") as myfile:
    data = myfile.read().splitlines()
    questions = data
index = 0
last_question = len(questions) - 1

app = Flask(__name__)

@app.route("/", methods=["POST", "GET"])
def hello_world():
    global index
    # if request.method == "POST":
        # if index == last_question:
        #     return "<p>You have completed the test. </p>"
        # index += 1
        # return render_template("index.html", question=questions[index])
    return render_template("index.html", questions=questions)

if __name__ == "__main__":
    app.run(debug=True)


import tweepy
import json
import os
import random
import time
import threading
from colorzero import Color
from datetime import datetime
from espeak import espeak
from sense_hat import SenseHat

# Set up background thread to flip image
def flip_image_horizontally():
    while 1:
        sense.flip_h()
        time.sleep(random.randint(1,5))

# Get device core temperature
def get_device_temp():
    temp = os.popen("vcgencmd measure_temp").readline()
    return (temp.replace("temp=","").replace('\'C\n',''))

# Convert celsius to fahrenheit
def get_fahrenheit(celsius):
    return round((celsius * 9/5) + 32,2)

# Use text to speech with sense hat LED animation
def speak(text_to_speech):
    sense.load_image("jaffar3.png")
    jaff_open_mouth = True
    espeak.synth(text_to_speech)
    while espeak.is_playing():
        time.sleep(0.3)
        jaff_open_mouth = not jaff_open_mouth
        sense.load_image("jaffar3.png" if jaff_open_mouth else "jaffar.png")
    sense.load_image("jaffar.png")

# configuration
enable_cheerlights = True

# print('Initiate Sense Hat')
sense = SenseHat()
sense.low_light = False
sense.load_image("jaffar.png")

# add a backgroudn thread to flip image horizonally
thread1 = threading.Thread(target = flip_image_horizontally)
thread1.start()

# print('Initiate TTS')
#espeak.set_voice("en-us+f5") # female's voice
espeak.set_voice("en-us+m3") # male's voice
speak("Initiate Jaffar's Pi Bot!")

# print('Set up tweepy')
with open('twitter_auth.json') as file:
    secrets = json.load(file)

# print('Authenticate the access token')
auth = tweepy.OAuthHandler(secrets['consumer_key'], secrets['consumer_secret'])
auth.set_access_token(secrets['access_token'], secrets['access_token_secret'])
twitter = tweepy.API(auth)

# Start the program loop
command = ''
while command != 'e':
    # print('Setting up greeters')
    status_greet_words = ['Hello','Hi','Hey', 'Heya']
    status_readers = ['friends','pals','earthlings','dawgs','homies']

    # Prompt menu option
    print('\n\n\n\n\n\n\n\n\n\n') # Throw a bunch of new line to move the menu down from previous texts
    print('[c] to set LED color and broadcast #cheerlights on twitter')
    print('[t] text to speech')
    print('[g] gyroscope (press ctrl + c to stop)')
    print('[cp] compass (press ctrl + c to stop)')
    print('[a] accelerometer (press ctrl + c to stop)')
    print('[o] orientation (press ctrl + c to stop)')
    print('[e] to exit')
    print('[other keys] to send a system tweet')
    command = input('Select the command: ')

    # Setting up date time
    status_date_time = 'It is ' + datetime.today().strftime('%a %b %d %Y %I:%M %p') + '. '

    # change LED color
    if command == 'c':
        speak("Please enter a color")
        color_input = ''
        while color_input != 'e':
            print('\n\n\n\n\n\n\n\n\n\n\n\n\n\n')
            color_input = input("Please enter a color or [e] to main menu: ")
            if color_input != 'e':
                try:
                    color = Color(color_input)
                    speak("Here is " + color_input)
                    sense.clear(color.rgb_bytes)
                    if enable_cheerlights == True:
                        status_greeting = random.choice(status_greet_words) + ', ' + random.choice(status_readers) + '! '
                        message = status_greeting + status_date_time + "Please set #cheerlights to " + color_input
                        print(message)
                        twitter.update_status(message)
                    else:
                        print("Cheerlights tweet is disabled")
                except:
                    error_message = color_input + ' is not a valid color. Try again!'
                    print(error_message)
                    speak(error_message)
            else:
                speak("Back to main menu")

    # text to speech
    elif command == 't':
        speak("Please enter what you want me to say")
        text_input = ''
        while text_input != 'e':
            print('\n\n\n\n\n\n\n\n\n\n\n\n\n\n')
            text_input = input("Please enter the texts or [e] to exit: ")
            if text_input != 'e':
                print(text_input)
                speak(text_input)
            else:
                speak("Back to main menu")
    elif command == 'g':
        speak("gyroscope")
        sense.clear()
        continue_gyro = True
        while continue_gyro:
            try:
                sense.set_imu_config(False, True, False)
                gyro_only = sense.get_gyroscope()
                print("p: {pitch}, r: {roll}, y: {yaw}".format(**gyro_only))
                time.sleep(0.05)
            except:
                speak("Back to main menu")
                continue_gyro = False
    elif command == 'cp':
        speak("compass")
        sense.clear()
        continue_compass = True
        while continue_compass:
            try:
                sense.set_imu_config(True, False, False)
                north = sense.get_compass()
                print("North: %s" % north)
                time.sleep(0.05)
            except:
                speak("Back to main menu")
                continue_compass = False
    elif command == 'a':
        speak("accelerometer")
        sense.clear()
        continue_acc = True
        while continue_acc:
            try:
                sense.set_imu_config(False, False, True)
                accel_only = sense.get_accelerometer()
                print("p: {pitch}, r: {roll}, y: {yaw}".format(**accel_only))
                time.sleep(0.05)
            except:
                speak("Back to main menu")
                continue_acc = False
    elif command == 'o':
        speak("orientation")
        sense.clear()
        continue_sensor = True
        while continue_sensor:
            try:
                sense.set_imu_config(True, True, True)
                orientation = sense.get_orientation()
                print("p: {pitch}, r: {roll}, y: {yaw}".format(**orientation))
                time.sleep(0.05)
            except:
                speak("Back to main menu")
                continue_sensor = False
    # Jaffar Pi Bot tweeting sensor data
    elif command != 'e':
        sense.load_image("jaffar2.png")
        espeak.synth("Constructing tweeter message")
        while espeak.is_playing():
            time.sleep(1)

        espeak.synth("Collecting data from the sensors")
        while espeak.is_playing():
            time.sleep(1)

        # print('Add dynamic temperature-based comment on Pi temp')
        cTemp = float(get_device_temp())
        fTemp = get_fahrenheit(cTemp)
        status_pi_temp = 'My core temp is ' + str(fTemp) +'\'F. '

        if cTemp < 60:
            status_pi_temp = status_pi_temp + 'I feel very comfortable right now. '
        elif cTemp > 60 and cTemp < 75:
            status_pi_temp = status_pi_temp + 'It\'s getting hot in here, but I\'m still doing OK. '
        elif cTemp >= 75:
            status_pi_temp = status_pi_temp + 'It\'s getting too hot in here, so I need to cool down a bit. '

        sense.set_imu_config(True, False, False)

        # Pull the data from sense sensors
        status_humidity = sense.humidity

        # Call twice to ensure that the pressure is being read correctly
        status_pressure = sense.get_pressure()
        status_pressure = sense.get_pressure()

        status_room_temp = get_fahrenheit(sense.get_temperature_from_humidity())
        status_room = '\n\nRoom Sensors\nHumidity: ' + str(round(status_humidity,2)) + ' %RH\nPressure: ' + str(round(status_pressure,2)) + ' Millibars'
        status_room += '\nTemperature: ' + str(status_room_temp) + '\'F'
        status_footer = '\n\nPowered by #jaffarspibot. '

        espeak.synth("Tweet the message")
        while espeak.is_playing():
            time.sleep(1)

        #message = status_greeting + status_date_time + status_pi_temp + status_room + status_orientation_rad + status_footer
        status_greeting = random.choice(status_greet_words) + ', ' + random.choice(status_readers) + '! '
        message = status_greeting + status_date_time + status_pi_temp + status_room + status_footer
        print(message)
        twitter.update_status(message)
        speak("Tasks completed!")

# Terminate the program loop
speak("Good bye!")
sense.clear()


#coding=utf8
import json
import requests
import pymongo
import time
import threading

class Get_comment():

    def __init__(self):
        self.client = pymongo.MongoClient(host='localhost',port=27017)
        self.db = self.client.mydb
        self.collenction_review = self.db.review
        self.collenction_hot = self.db.hot_article

        self.headers = {
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'
        }

    def get_articleid(self):
        sorts = self.collenction_hot.find().sort('impression_count',pymongo.DESCENDING)
        art_ids = list(sort['hot_id'] for sort in sorts )
        return art_ids

    def joint_url(self,art_ids):
        urls = []
        for art_id in art_ids:

            for i in range(0,201,10):
                url = 'http://is.snssdk.com/article/v4/tab_comments/?fold=1&offset=%s&group_id=%s&count=50&comment_request_from=1'%(i,art_id)
                urls.append(url)
        return urls

    def get_response(self,urls,art_ids):
        for url in urls:
            print(url)
            response = requests.get(url,headers=self.headers)
            text = response.text
            body = json.loads(text)
            for art_id in art_ids:
                for x in body['data']:
                    time_local = time.localtime(int(x['comment']['create_time']))
                    create_time = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
                    data = {
                        'review':x['comment']['text'],
                        'user_id':x['comment']['id'],
                        'article_id':art_id,
                        'create_time':create_time

                    }
                    result = self.collenction_review.find({'user_id': data['user_id']}).count()
                    counts = self.collenction_review.find().count()
                    if result:
                        print('数据已存在', result, counts)
                    else:

                        self.collenction_review.insert(data)

def main():
    com = Get_comment()
    art_id = com.get_articleid()
    urls = com.joint_url(art_id)
    com.get_response(urls, art_id)

if __name__ == '__main__':
    pass
    # for x in range(5):  # 建立多线程并启动
    #     t = threading.Thread(target=  main())
    #
    #     t.start()
    #     print(threading.current_thread())

        # main()