"""
    Funny Strings Problem on HackerRank
    Problem Link: https://www.hackerrank.com/challenges/funny-string/problem

    Author: Shyam Kumar (@svshyam91)

"""

def funnyString(s):

    # Make the list of ascii of characters of string
    ascii_str=[ord(c) for c in s]
    ascii_str_rev=ascii_str[::-1]       # Reverse the ascii list
    for i in range(1,len(ascii_str)):
        if abs(ascii_str[i]-ascii_str[i-1]) != abs(ascii_str_rev[i]-ascii_str_rev[i-1]):
            return "Not Funny"
    return "Funny"

if __name__ == '__main__':
    q = int(input())

    for q_itr in range(q):
        s = input()

        result = funnyString(s)
        print(result)


import numpy as np
import matplotlib
import matplotlib.pyplot as plt

# random data
A = [2,5,7,9,11,16,19,23,22,29,29,35,37,40,46]
b = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

# Visualize data
plt.plot(A,b,'ro')

# array to [[   ]]
# change row vector to column vector
A = np.array([A]).T
b = np.array([b]).T

# Create vector 1
ones = np.ones_like(A, dtype = np.int8)
A = np.concatenate((A,ones),axis = 1)

# Use formula
x = np.linalg.inv(A.transpose().dot(A)).dot(A.transpose()).dot(b)

x0 = np.array([1,46]).T
y0 = x[0][0]*x0 + x[1][0]
# ko co phep toan matrix cong mot so
# nhung trong numpy cong mot so voi tat ca cac phan tu cua matrix

# Test predict data
x_test = 12
y_test = x[0][0]*x_test + x[1][0]
print(y_test)

# Visualize x0,y0
plt.plot(x0,y0)
plt.show()


from flask import Flask, request, render_template, redirect, flash, session
from flask_debugtoolbar import DebugToolbarExtension
from surveys import surveys, satisfaction_survey, personality_quiz

app = Flask(__name__)

app.config['SECRET_KEY'] = "secret_code_here"
# app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
# debug = DebugToolbarExtension(app)

@app.route('/')
def choose_the_servey():
    """ start-page that allows a user to choose a survey from a survey list """
    return render_template('choose_survey.html', surveys=surveys.items())

@app.route('/start-page', methods=['POST'])
def start_survey():
    """render a page for the chosen survey that shows the user the title of the survey, the instructions, and a button to start the survey;
    setup session variables """
    current_survey=surveys[request.form.get('choice')] #current survey object
    session['title'] = current_survey.title
    session['num_of_questions'] = len(current_survey.questions)
    session['survey'] = request.form['choice'] # key of current survey in surveys list
    session['comments'] = []
    return render_template('start.html', instructions = current_survey.instructions)

@app.route('/start', methods=['POST'])
def handling_start():
    """ Set a current session responses-list to an empty list and redirect to the start of the survey """
    session['responses'] = []
    return redirect('/questions/0')

@app.route('/questions/<question_number>')
def question_page(question_number):
    """ Page shows a form asking the current question, and listing the choices as radio buttons, also comments if are allowed """
    answers = session['responses']
    if len(answers) == session['num_of_questions']:
        return render_template('thanks.html')
    if len(answers) == int(question_number):
        number = int(question_number)
    else:
        flash('Could you please answer this question, you tried to access an invalid question','error')
        number = len(answers)
    current_survey = surveys[session['survey']]
    current_question = current_survey.questions[number]
    return render_template('question.html', number = number, choices = current_question.choices, question = current_question.question, title = current_survey.title, allow_text = current_question.allow_text)

@app.route('/answer', methods=['POST'])
def handling_answer():
    """ function appends the answer to responses list, adds comments if necessary and then redirect user to the next question; if no more questions in the survey - render thanks page ."""
    comment = request.form.get('comment')
    current_answer = request.form.get('choice')
    answers = session['responses']
    if current_answer:
        answers.append(current_answer)
        session['responses'] = answers
        if comment:
            comments = session['comments']
            comments.append((len(answers),comment))
            session['comments'] = comments
    else:
        flash('We are still waiting for your response!','error')
    if len(answers) < session['num_of_questions']:
        next_question = f"/questions/{len(answers)}"
        return redirect(next_question)
    else:
        return render_template('thanks.html')


class Solution(object):
    res = []
    def postorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        self.res = []
        self.postorder_find(root)
        return self.res

    def postorder_find(self, root):
        if root == None:
            return

        for child in root.children:
            self.postorder_find(child)

        self.res.append(root.val)


#LIBRERIAS A UTILIZAR
import pandas as pd
from sklearn.impute import SimpleImputer
import numpy as np
from sklearn.preprocessing import LabelEncoder
import matplotlib.pyplot as plt
import seaborn as seabornInstance
from sklearn.model_selection import train_test_split #libreria para poder separar los datos entre entrenamiento y test
from sklearn.linear_model import LinearRegression #libreria para poder generar la regresion lineal
from sklearn import metrics
#ANALISIS PREVIO
"""
En el analisis previo con solo mirar el archivo, puedo deducir que es un archivo que contiene
edad de una persona, sexo de la persona solicitante del seguro,bmi(segun lo que googlie es un reembolso que se le puede dar),
cuantos hijos tiene, si es fumador o no, y el precio del seguro a abonar.
De esto puedo inferir que mi prediccion va a ser con una regresion lineal multiple ya que la variable dependiete es el cargo del seguro, y es afectada
por todas las demas columnas, es decir, un seguro aumentara por todas las condiciones anteriores(edad, bmi, hijos, si es fumador o no y de que zona es la persona solicitante)
"""

#-------------GUARDO MI ARCHIVO A USAR -------------------------------
ruta =r'Unsam.Clase.12.4.6.2021\Unsam.Clase.12.4.6.2021\cvs_para_el_TP\seguro.csv'
dataSet = pd.read_csv(ruta) #archivo a utilizar

#-----------------ANALISIS DE MIS DATOS ---------------------
print(dataSet)
#print("CANTIDAD DE FILAS Y COLUMNAS")
#print(dataSet.shape)
#no hace falta hacer el shape ya que al imprimir el dataSet, me dice cuantas filas y columnas tengo
print(dataSet.describe())

#compruebo si hay valores nan en mi codigo
print("Valores null o nan en el dataSet: ")
print(dataSet.isna().values.any())
print(dataSet.isnull().values.any())
#devuelve falso por ende no tengo valores NaN o null

#-------------SEPARO LAS VARIABLES QUE VOY A USAR------------
X = dataSet[['age','sex','bmi','children','smoker','region' ]].values
Y = dataSet['charges'].values

print("X:\n")
print(X) #matriz     /variables independientes
print("Y:\n")
print(Y) #vector    /variables dependientes

#----------------COMIENZO A PREPARAR LOS DATOS-------------
"""
La edad y el bmi, son valores numericos ya manipulables , por ende , los dejo como estan para poder realizar mi analisis
"""

#MODIFICO LA COLUMNA DEL SEXO PARA MANEJARME CON 1 Y 0
labelencoder_X=LabelEncoder()
X[:,1]=labelencoder_X.fit_transform(X[:,1])

#MODIFICO LA COMLUNMA DE SI ES FUMADOR CON 1 Y 0
labelencoder_X=LabelEncoder()
X[:,4]=labelencoder_X.fit_transform(X[:,4])

#MODIFICO LA COLUMNNA DE SUR Y NORTE (CON ORIENTACION ESTE Y OESTE)
labelencoder_X=LabelEncoder()
X[:,-1]=labelencoder_X.fit_transform(X[:,-1])
print("Matriz X luego de preparacion de datos : \n")
print(X)

#PREGUNTAR SI HAY QUE ESCALAR LA EDAD?

#-------------GRAFICO MI VARIABLE DEPENDIENTE PARA SACAR ALGUNA CONCLUSION -----------

plt.figure(figsize=(10,5))
plt.tight_layout()
plt.title('Densidad de mi variable Dependiente')
seabornInstance.distplot(dataSet['charges'], color = 'lightblue')
plt.show()
"""
De este Grafico podemos concluir que mi variable dependiente 'charges' que seria el precio a pagar del seguro,
varia entre 0 y 70000 , y la mayor densidad(mayor cantidad de match) las hace desde el 0 hasta el 10000 aproximadamente.
"""

#------------------DIVIDIR LOS DATOS EN ENTRENAMIENTO Y TEST -----------------
#80 porciento de mis datos en entrenamiento y 20 en test
X_train , X_test, Y_train, Y_test = train_test_split(X , Y , test_size = 0.2, random_state=0)
#comienzo a entrenar mi modelo
regressor = LinearRegression()
regressor.fit(X_train, Y_train)

#------------------ELIMINO MI COLUMNA QUE ES LA DE CARGOS(VARIABLE DEPENDIENTE)-----------
dataFrame= dataSet.drop(['charges'], axis = 1) #dropeo(elimino) mi variale dependiente de mi data frame
dataFrame = dataFrame.T #transpongo filas por columnas PODRIA SER TRANSPOSE()
dataFrame = dataFrame.index #me guardo en mi dataframe solo las etiquetas
print(dataFrame) #imprimo las etiquetas para verificar que estan bien guardadas

#-----------------ENCONTRAR LOS COEFICIENTES MAS OPTIMOS PARA MIS ATRIBUTOS----------------

coeficiente_dataFrame = pd.DataFrame(regressor.coef_, dataFrame, columns= ['Coeficiente'])
print(coeficiente_dataFrame)
 #luego de imprimir concluyo que transpuso filas por columnas y tiene sus coeficentes correspondientes

#---------------PREDICCION--------------------

y_prediccion = regressor.predict(X_test)
#agarro mi dataFrame donde estan mis indices
dataFrame = pd.DataFrame({'Actual': Y_test, 'Prediccion': y_prediccion})
dataFrame_prediccion = dataFrame.head(30)
print(dataFrame_prediccion)

#-------------------GRAFICO MI PREDICCION -----------------

dataFrame_prediccion.plot(kind='bar',figsize=(10,8)) #LE DIGO QUE ES UN GRAFICO DE BARRAS Y EL TAMAÑO
plt.title('Actual vs Prediccion')
plt.grid(which='major', linestyle='-', linewidth='0.5', color='black')
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plt.show()

#----------------ME FIJO EL RENDIMIENTO DE MI ALGORITMO ---------------

print('Promedio de Error Absoluto:', metrics.mean_absolute_error(Y_test, y_prediccion))
print('Promedio de Error de Raiz:', metrics.mean_squared_error(Y_test, y_prediccion))
print('Error cuadratico medio de la raiz:', np.sqrt(metrics.mean_squared_error(Y_test, y_prediccion)))

#CONCLUSION FINAL
"""
Por el analisis hecho, podemos deducir que la prediccion no es nada buena, ya que los promedios de error
superan ampliamente el 10 porciento, es aproximadamente, un 15 porciento (siendo generoso), no es un analisis muy exacto, pero para nuestro caso
es aceptable(porque use regresion lineal multiple, entonces entre mas datos afecten a mi variable dependiente , menos me voy a acercar a una prediccion acertada),
ya que las columnas en las que supera ese porcentaje son la 14 , la 20 y la 23, que siendo generoso tendrian aproximadamente un 25 porciento extra.
"""

"""
PD: Perdon por mi manera de hablar o escribir pero la verdad que en las conclusiones tarde mas que en el codigo jajaja.
    Si hay algo que deba cambiar o mejorar porfavor diganmelo
Muchas gracias por TODO
Atte : Alex Sosa :)
"""


#!/usr/bin/env python3

class Tile:
    def __init__(self, x: int, y: int):
        self._x = x
        self._y = y
        self._c = 'W'
        self._nc = None

    def nw(self):
        return self._x - 1, self._y - 1

    def ne(self):
        return self._x + 1, self._y - 1

    def sw(self):
        return self._x - 1, self._y + 1

    def se(self):
        return self._x + 1, self._y + 1

    def w(self):
        return self._x - 2, self._y

    def e(self):
        return self._x + 2, self._y

    def flip(self):
        self._c = 'B' if self._c == 'W' else 'W'

    def flip_later(self):
        assert self._nc is None
        self._nc = 'B' if self._c == 'W' else 'W'
        # print('flipping later', self._x, self._y, 'to', self._nc)

    def commit(self):
        if self._nc is not None:
            self._c = self._nc
        self._nc = None

    @property
    def color(self):
        return self._c

class Floor:
    def __init__(self):
        self._f = {}

    def get(self, x, y):
        if not (x, y) in self._f:
            self._f[(x, y)] = Tile(x, y)
        return self._f[(x, y)]

    def count(self, c: str):
        count = 0
        for tile in self._f.values():
            if tile.color == c:
                count += 1
        return count

    def x_lim(self):
        max, min = None, None
        for coord in self._f:
            if max is None or coord[0] > max:
                max = coord[0]
            if min is None or coord[0] < min:
                min = coord[0]

        return min, max

    def y_lim(self):
        max, min = None, None
        for coord in self._f:
            if max is None or coord[1] > max:
                max = coord[1]
            if min is None or coord[1] < min:
                min = coord[1]

        return min, max

    def count_adj(self, tile: Tile, c: str):
        count = 0
        count += int(self.get(*tile.ne()).color == c)
        count += int(self.get(*tile.nw()).color == c)
        count += int(self.get(*tile.e()).color == c)
        count += int(self.get(*tile.w()).color == c)
        count += int(self.get(*tile.se()).color == c)
        count += int(self.get(*tile.sw()).color == c)
        return count

    def flip(self):
        # for coord, tile in dict(self._f).items():

        x_min, x_max = self.x_lim()
        y_min, y_max = self.x_lim()
        for x in range(x_min - 1, x_max + 2):
            for y in range(y_min - 1, y_max + 2):
                tile = self.get(x,y)

                if tile.color == 'B' and self.count_adj(tile, 'B') in [0, 3, 4, 5, 6]:
                    tile.flip_later()

                if tile.color == 'W' and self.count_adj(tile, 'B') == 2:
                    tile.flip_later()

        for _, tile in self._f.items():
            tile.commit()

floor = Floor()

for seq in open('24.input').readlines():
    tile = floor.get(0, 0)

    c_iter = iter(seq)
    while True:
        c = next(c_iter)
        if c == 'n':
            c = next(c_iter)
            if c == 'e':
                x, y = tile.ne()
            elif c == 'w':
                x, y = tile.nw()
            else:
                raise ValueError('unknown north')
        elif c == 's':
            c = next(c_iter)
            if c == 'e':
                x, y = tile.se()
            elif c == 'w':
                x, y = tile.sw()
            else:
                raise ValueError('unknown south')
        elif c == 'e':
            x, y = tile.e()
        elif c == 'w':
            x, y = tile.w()
        elif c == '\n':
            break
        else:
            raise ValueError('unknown direction', c)

        tile = floor.get(x, y)

    tile.flip()

black = floor.count('B')
print('initial black tiles', black)

for day in range(1, 101):
    floor.flip()
    print(day, floor.count('B'))


#!/usr/bin/env python

# This is more of a work in progress, but this script will
# test the code for creating vespagrams with our curved wavefront correction.

import obspy
import numpy as np
import time
import matplotlib.pyplot as plt

import circ_array as c
from circ_beam import Vespagram_Lin, Vespagram_PWS, Baz_vespagram_PWS, Baz_vespagram_Lin
from array_plotting import plotting

# parameters
# phase of interest
phase = 'SKS'
phases = ['SKS','SKKS','ScS','Sdiff','sSKS','sSKKS','PS','SKKKS','pSKS']

# frequency band
fmin = 0.13
fmax = 0.26

st = obspy.read('./data/19970525/*SAC')

# get array metadata
event_time = c.get_eventtime(st)
geometry = c.get_geometry(st)
distances = c.get_distances(st,type='deg')
mean_dist = np.mean(distances)
stations = c.get_stations(st)

# get travel time information and define a window
Target_phase_times, time_header_times = c.get_predicted_times(st,phase)

avg_target_time = np.mean(Target_phase_times)
min_target = int(np.nanmin(Target_phase_times, axis=0))
max_target = int(np.nanmax(Target_phase_times, axis=0)) + 100

stime = event_time + min_target
etime = event_time + max_target

# trim the stream
# Normalise and cut seismogram around defined window
st = st.copy().trim(starttime=stime, endtime=etime)
st = st.normalize()

# get predicted slownesses and backazimuths
predictions = c.pred_baz_slow(
    stream=st, phases=phases, one_eighty=True)

# find the line with the predictions for the phase of interest
row = np.where((predictions == phase))[0]
P, S, BAZ, PRED_BAZ_X, PRED_BAZ_Y, PRED_AZ_X, PRED_AZ_Y, DIST, TIME = predictions[row, :][0]

# make the box around the prediction to search over
smin=float(S)-2
smax=float(S)+6
s_step=0.1

# filter
st = st.filter('bandpass', freqmin=fmin, freqmax=fmax,
                  corners=4, zerophase=True)

# get the traces and phase traces
Traces = c.get_traces(st)
Phase_traces = c.get_phase_traces(st)

# get sampleing rate
sampling_rate=st[0].stats.sampling_rate

# slowness vespagrams
vesp_lin = Vespagram_Lin(traces=Traces, sampling_rate=sampling_rate, geometry=geometry,
                         distance=mean_dist, baz=float(BAZ), smin=smin, smax=smax, s_space=s_step)

fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(211)
p = plotting(ax = ax)

p.plot_vespagram(vespagram=vesp_lin, ymin=smin, ymax=smax, y_space=s_step, tmin=min_target, tmax=max_target,
                 sampling_rate=sampling_rate, title="Slow - Lin", predictions=predictions, type='slow',
                 envelope=True)

vesp_pws = Vespagram_PWS(traces=Traces, phase_traces=Phase_traces, sampling_rate=sampling_rate, geometry=geometry,
                         distance=mean_dist, baz=float(BAZ), smin=smin, smax=smax, s_space=s_step, degree=2)

ax = fig.add_subplot(212)
p = plotting(ax = ax)
p.plot_vespagram(vespagram=vesp_pws, ymin=smin, ymax=smax, y_space=s_step, tmin=min_target, tmax=max_target,
                 sampling_rate=sampling_rate, title="Slow - PWS", predictions=predictions, type='slow',
                 envelope=True)
plt.tight_layout()

plt.show()
# backazimuth vespagrams

bmin=float(BAZ)-30
bmax=float(BAZ)+30
b_step=0.05

vesp_lin = Baz_vespagram_Lin(traces=Traces, sampling_rate=sampling_rate, geometry=geometry,
                         distance=mean_dist, slow=float(S), bmin=bmin, bmax=bmax, b_space=b_step)

fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(211)
p = plotting(ax = ax)

p.plot_vespagram(vespagram=vesp_lin, ymin=bmin, ymax=bmax, y_space=b_step, tmin=min_target, tmax=max_target,
                 sampling_rate=sampling_rate, title="Baz - Lin", predictions=predictions, type='baz',
                 envelope=True)

vesp_pws = Baz_vespagram_PWS(traces=Traces, phase_traces=Phase_traces, sampling_rate=sampling_rate, geometry=geometry,
                         distance=mean_dist, slow=float(S), bmin=bmin, bmax=bmax, b_space=b_step, degree=2)

ax = fig.add_subplot(212)
p = plotting(ax = ax)
p.plot_vespagram(vespagram=vesp_pws, ymin=bmin, ymax=bmax, y_space=b_step, tmin=min_target, tmax=max_target,
                 sampling_rate=sampling_rate, title="Baz - PWS", predictions=predictions, npeaks=5, type='baz',
                 envelope=True)
plt.tight_layout()
plt.show()


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

import datasets
import utils

FLAGS = tf.flags.FLAGS

def get_lr(global_step, base_lr, steps_per_epoch,  # pylint: disable=missing-docstring
           decay_epochs, lr_decay_factor, warmup_epochs):

  warmup_lr = 0.0
  if warmup_epochs > 0:
    warmup_lr = (tf.cast(global_step, tf.float32) *
                 (base_lr / (warmup_epochs * steps_per_epoch)))

  normal_lr = tf.train.piecewise_constant(
      global_step,
      [e * steps_per_epoch for e in decay_epochs],
      [base_lr * (lr_decay_factor ** i) for i in range(len(decay_epochs) + 1)]
  )

  lr = tf.cond(tf.less(global_step, warmup_epochs * steps_per_epoch),
               lambda: warmup_lr,
               lambda: normal_lr)

  return lr

# TODO(akolesnikov): add more logging
class Trainer(object):
  """Base trainer class."""

  def __init__(self,
               update_batchnorm_params=True):
    self.update_batchnorm_params = update_batchnorm_params

    split = FLAGS.get_flag_value('train_split', 'train')
    num_samples = datasets.get_count(split)
    steps_per_epoch = num_samples // FLAGS.batch_size

    global_step = tf.train.get_or_create_global_step()
    self.global_step_inc = tf.assign_add(global_step, 1)

    # lr_scale_batch_size defines a canonical batch size that is coupled with
    # the initial learning rate. If actual batch size is not the same as
    # canonical than learning rate is linearly scaled. This is very convinient
    # as this allows to vary batch size without recomputing learning rate.
    lr_factor = 1.0
    if FLAGS.get_flag_value('lr_scale_batch_size', 0):
      lr_factor = FLAGS.batch_size / float(FLAGS.lr_scale_batch_size)

    deps = FLAGS.get_flag_value('decay_epochs', None)
    decay_epochs = utils.str2intlist(deps) if deps else [FLAGS.epochs]

    self.lr = get_lr(
        global_step,
        base_lr=FLAGS.lr * lr_factor,
        steps_per_epoch=steps_per_epoch,
        decay_epochs=decay_epochs,
        lr_decay_factor=FLAGS.get_flag_value('lr_decay_factor', 0.1),
        warmup_epochs=FLAGS.get_flag_value('warmup_epochs', 0))

    # TODO(marvinritter): Re-enable summaries with support for TPU training.
    # tf.summary.scalar('learning_rate', self.lr)

  def get_train_op(self, loss,  # pylint: disable=missing-docstring
                   var_list=None,
                   add_reg_loss=True,
                   use_tpu=False):

    if add_reg_loss:
      l2_loss = tf.reduce_sum(tf.losses.get_regularization_losses())
      loss += l2_loss

    optimizer = FLAGS.get_flag_value('optimizer', 'sgd')
    if optimizer == 'sgd':
      optimizer = tf.train.MomentumOptimizer(learning_rate=self.lr,
                                             momentum=0.9)
    elif optimizer == 'adam':
      optimizer = tf.train.AdamOptimizer(learning_rate=self.lr)
    else:
      raise ValueError('Unknown optimizer: %s' % optimizer)

    if use_tpu:
      # Wrap optimizer in CrossShardOptimizer which takes care of
      # synchronizing the weight updates between TPU cores.
      optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer)

    opt_step = optimizer.minimize(loss, var_list=var_list,
                                  colocate_gradients_with_ops=True)

    if self.update_batchnorm_params:
      opt_step = tf.group([opt_step] +
                          tf.get_collection(tf.GraphKeys.UPDATE_OPS))

    opt_step = tf.group([opt_step, self.global_step_inc])

    return opt_step

def make_estimator(mode, loss=None, eval_metrics=None, predictions=None):
  """Returns an EstimatorSpec (maybe TPU) for all modes."""

  # Always use TPUEstimator, even when not using TPU, then it's (almost) no-op.
  spec_type = tf.contrib.tpu.TPUEstimatorSpec

  if mode == tf.estimator.ModeKeys.PREDICT:
    assert predictions is not None, 'Need to pass `predict` arg.'
    return spec_type(mode=mode, predictions=predictions)

  if mode == tf.estimator.ModeKeys.EVAL:
    return spec_type(mode=mode, loss=loss, eval_metrics=eval_metrics)

  if mode == tf.estimator.ModeKeys.TRAIN:
    assert loss is not None, 'Need to pass `loss` arg.'
    trainer = Trainer(update_batchnorm_params=True)
    train_op = trainer.get_train_op(loss, use_tpu=FLAGS.use_tpu)
    return spec_type(mode=mode, loss=loss, train_op=train_op)

  raise ValueError('Unsupported mode %s' % mode)


from itertools import combinations
from collections import Counter

def solution(orders, course):
  answer = []
  for c in course:
    temp = []
    for order in orders:
      combi = combinations(sorted(order), c)
      temp += combi
    counter = Counter(temp)
    if len(counter) != 0 and max(counter.values()) != 1:
      for cnt in counter:
        if counter[cnt] == max(counter.values()):
          answer.append("".join(cnt))
  return sorted(answer)


import backtrader as bt
import backtrader.analyzers as btanalyzers
import matplotlib
import matplotlib.dates as mdates
from matplotlib import pyplot as plt
from datetime import datetime
import pandas as pd
import datetime as dt

# Create a subclass of Strategy to define the indicators and logic
class SMA_CrossStrategy(bt.Strategy):

    def __init__(self):
        ma_fast = bt.ind.SMA(period = 9)
        ma_slow = bt.ind.SMA(period = 21)

        self.crossover = bt.ind.CrossOver(ma_fast, ma_slow)

    def next(self):
        if not self.position:
            if self.crossover > 0:
                self.buy()
        elif self.crossover < 0:
            self.close()

    # def next(self):
    #     if not self.position:
    #         if self.crossover > 0:
    #             self.buy()
    #         elif self.crossover < 0:
    #             self.sell()
    #     elif self.crossover < 0:
    #         self.close()

def main():
    cerebro = bt.Cerebro()

    tickers_list = ['AAPL']
    df_tic = pd.read_hdf("datasets/df_SnP_500_ohlcv.h5", "df", mode = 'r')
    df_tic = df_tic[df_tic['tic'].isin(tickers_list)]
    df_tic = df_tic.set_index('date')
    # df_tic['date'] = pd.to_datetime(df_tic['date'])
    print(df_tic.head(5))
    data = bt.feeds.PandasData(dataname = df_tic,
                                            # datetime=None,
                                            open =1,
                                            high=2,
                                            low=3,
                                            close=4,
                                            volume=6,
                                            openinterest=-1,
                                            timeframe = bt.TimeFrame.Days,
                                            fromdate=dt.datetime(2023, 1, 1),  # Specify the start date
                                            todate=dt.datetime(2023, 8, 24),   # Specify the end date
                                        )

    # data = bt.feeds.YahooFinanceData(dataname = 'AAPL', fromdate = datetime(2010, 1, 1), todate = datetime(2020, 1, 1))
    cerebro.adddata(data)

    cerebro.addstrategy(SMA_CrossStrategy)

    cerebro.broker.setcash(10000.0)

    cerebro.addsizer(bt.sizers.PercentSizer, percents = 100)

    cerebro.addanalyzer(btanalyzers.SharpeRatio, _name = "sharpe")
    cerebro.addanalyzer(btanalyzers.Transactions, _name = "trans")
    cerebro.addanalyzer(btanalyzers.TradeAnalyzer, _name = "trades")

    back = cerebro.run()

    cerebro.broker.getvalue()

    back[0].analyzers.sharpe.get_analysis()

    back[0].analyzers.trans.get_analysis()

    back[0].analyzers.trades.get_analysis()

    cerebro.plot(style='candlestick', barup='green', bardown='red')
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    plt.gcf().autofmt_xdate()  # Rotates the date labels for better visibility

if __name__=="__main__":
    main()


import argparse
import logging
from typing import List

import torch
import torch.nn as nn

from .probe_base import ProbeBase

logger = logging.getLogger(__name__)

class OneWordNNProbe(ProbeBase):
    """
    Computes all squared L2 norm of n words as depths after an MLP projection.
    Can be used for probing the depth of words in a tree
    """

    def __init__(
        self, model_hidden_dim: int, probe_hidden_layers: int, intermediate_dim: int
    ):
        logging.info("Constructing OneWordNNDepthProbe")
        super(OneWordNNProbe, self).__init__()
        initial_linear = nn.Linear(model_hidden_dim, intermediate_dim)
        intermediate_layers: List[nn.Module] = []
        for i in range(probe_hidden_layers):
            intermediate_layers.append(nn.Linear(intermediate_dim, intermediate_dim))
            if i != probe_hidden_layers - 1:
                intermediate_layers.append(nn.ReLU())
        self.nn_probe = nn.Sequential(initial_linear, nn.ReLU(), *intermediate_layers)

    def forward(self, batch):
        """
        Computes all squared L2 norm of n words as depths after an MLP projection
         for each sentence in a batch. predicts the depth through an MLP
        Args:
            batch: a batch of word representations of the shape
                   (batch_size, max_seq_len, representation_dim)
        Returns: A tensor of depths of shape (batch_size, max_seq_len)
        """
        batch = self.nn_probe(batch)
        batchlen, seqlen, rank = batch.size()
        norms = torch.bmm(
            batch.view(batchlen * seqlen, 1, rank),
            batch.view(batchlen * seqlen, rank, 1),
        )
        norms = norms.view(batchlen, seqlen)
        return norms

    @staticmethod
    def add_probe_specific_args(
        parent_parser: argparse.ArgumentParser,
    ) -> argparse.ArgumentParser:
        parser = parent_parser.add_argument_group("ProbeArgs")
        parser.add_argument(
            "--probe_hidden_layers",
            type=int,
            default=2,
            help="Number of laers in probe.",
        )
        parser.add_argument(
            "--intermediate_dim",
            type=int,
            default=300,
            help="Dimension the probe maps embeddings to.",
        )
        return parent_parser


#7.7.1.py
# This program calculate sthe hourly rate and number of hours worked per week

def main():
    print("This program gives wages earned in a week period.")
    rate = float(input("What is the hourly rate? "))
    numberHours = float(input("How many hours were worked? "))

    # determines if overtime pay is included
    if numberHours > 40:
        pay = (numberHours-40) * (rate * 1.5) + 40 * rate
        print(f"The total wages are {pay} dollars")
    elif numberHours <= 40:
        pay = numberHours * rate
        print(f"The total wages are {pay} dollars")
    else:
        print("Something went wrong")

if __name__ == '__main__':
    main()


import argparse

from experiment.monitor import monitor
from apps.qe import qe

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    monitor.setup_run_args(parser)
    qe.setup_run_args(parser)

    args, extra_args = parser.parse_known_args()
    app_conf = qe.QuantumEspressoAppConf(args.node_count, args.benchmark_name)
    monitor.launch(app_conf=app_conf, args=args,
                   experiment_cli_args=extra_args)


# coding: utf-8

"""
    Refinery Calc API Documentation

    Integrate the powerful Refinery Calc Engine into your process using this API.  # noqa: E501

    OpenAPI spec version: 1.0
    Contact: support@refinerycalc.com.com
    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

import pprint
import re  # noqa: F401

import six

class OutputTypes(object):
    """NOTE: This class is auto generated by the swagger code generator program.

    Do not edit the class manually.
    """
    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {
        'balance': 'list[OutputDetails]',
        'complexity': 'list[OutputDetails]',
        'constraints': 'list[OutputDetails]',
        'crude_names': 'list[OutputDetails]',
        'crude_percent': 'list[OutputDetails]',
        'crude_pricing': 'list[OutputDetails]',
        'crude_quality': 'list[OutputDetails]',
        'crudes_and_feeds': 'list[OutputDetails]',
        'delete_category': 'list[OutputDetails]',
        'economics': 'list[OutputDetails]',
        'end_points_f': 'list[OutputDetails]',
        'expense_factors': 'list[OutputDetails]',
        'fcc_hydrk_conv': 'list[OutputDetails]',
        'feeds_pricing': 'list[OutputDetails]',
        'gasoline_blending': 'list[OutputDetails]',
        'general': 'list[OutputDetails]',
        'hydrogen': 'list[OutputDetails]',
        'product_pricing': 'list[OutputDetails]',
        'products': 'list[OutputDetails]',
        'refinery_layout_svg': 'list[OutputDetails]',
        'sustainability': 'list[OutputDetails]',
        'unit_balance': 'list[OutputDetails]'
    }

    attribute_map = {
        'balance': 'balance',
        'complexity': 'complexity',
        'constraints': 'constraints',
        'crude_names': 'crudeNames',
        'crude_percent': 'crudePercent',
        'crude_pricing': 'crudePricing',
        'crude_quality': 'crudeQuality',
        'crudes_and_feeds': 'crudesAndFeeds',
        'delete_category': 'deleteCategory',
        'economics': 'economics',
        'end_points_f': 'endPointsF',
        'expense_factors': 'expenseFactors',
        'fcc_hydrk_conv': 'fccHydrkConv',
        'feeds_pricing': 'feedsPricing',
        'gasoline_blending': 'gasolineBlending',
        'general': 'general',
        'hydrogen': 'hydrogen',
        'product_pricing': 'productPricing',
        'products': 'products',
        'refinery_layout_svg': 'refineryLayoutSVG',
        'sustainability': 'sustainability',
        'unit_balance': 'unitBalance'
    }

    def __init__(self, balance=None, complexity=None, constraints=None, crude_names=None, crude_percent=None, crude_pricing=None, crude_quality=None, crudes_and_feeds=None, delete_category=None, economics=None, end_points_f=None, expense_factors=None, fcc_hydrk_conv=None, feeds_pricing=None, gasoline_blending=None, general=None, hydrogen=None, product_pricing=None, products=None, refinery_layout_svg=None, sustainability=None, unit_balance=None):  # noqa: E501
        """OutputTypes - a model defined in Swagger"""  # noqa: E501
        self._balance = None
        self._complexity = None
        self._constraints = None
        self._crude_names = None
        self._crude_percent = None
        self._crude_pricing = None
        self._crude_quality = None
        self._crudes_and_feeds = None
        self._delete_category = None
        self._economics = None
        self._end_points_f = None
        self._expense_factors = None
        self._fcc_hydrk_conv = None
        self._feeds_pricing = None
        self._gasoline_blending = None
        self._general = None
        self._hydrogen = None
        self._product_pricing = None
        self._products = None
        self._refinery_layout_svg = None
        self._sustainability = None
        self._unit_balance = None
        self.discriminator = None
        if balance is not None:
            self.balance = balance
        if complexity is not None:
            self.complexity = complexity
        if constraints is not None:
            self.constraints = constraints
        if crude_names is not None:
            self.crude_names = crude_names
        if crude_percent is not None:
            self.crude_percent = crude_percent
        if crude_pricing is not None:
            self.crude_pricing = crude_pricing
        if crude_quality is not None:
            self.crude_quality = crude_quality
        if crudes_and_feeds is not None:
            self.crudes_and_feeds = crudes_and_feeds
        if delete_category is not None:
            self.delete_category = delete_category
        if economics is not None:
            self.economics = economics
        if end_points_f is not None:
            self.end_points_f = end_points_f
        if expense_factors is not None:
            self.expense_factors = expense_factors
        if fcc_hydrk_conv is not None:
            self.fcc_hydrk_conv = fcc_hydrk_conv
        if feeds_pricing is not None:
            self.feeds_pricing = feeds_pricing
        if gasoline_blending is not None:
            self.gasoline_blending = gasoline_blending
        if general is not None:
            self.general = general
        if hydrogen is not None:
            self.hydrogen = hydrogen
        if product_pricing is not None:
            self.product_pricing = product_pricing
        if products is not None:
            self.products = products
        if refinery_layout_svg is not None:
            self.refinery_layout_svg = refinery_layout_svg
        if sustainability is not None:
            self.sustainability = sustainability
        if unit_balance is not None:
            self.unit_balance = unit_balance

    @property
    def balance(self):
        """Gets the balance of this OutputTypes.  # noqa: E501

        :return: The balance of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._balance

    @balance.setter
    def balance(self, balance):
        """Sets the balance of this OutputTypes.

        :param balance: The balance of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._balance = balance

    @property
    def complexity(self):
        """Gets the complexity of this OutputTypes.  # noqa: E501

        :return: The complexity of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._complexity

    @complexity.setter
    def complexity(self, complexity):
        """Sets the complexity of this OutputTypes.

        :param complexity: The complexity of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._complexity = complexity

    @property
    def constraints(self):
        """Gets the constraints of this OutputTypes.  # noqa: E501

        :return: The constraints of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._constraints

    @constraints.setter
    def constraints(self, constraints):
        """Sets the constraints of this OutputTypes.

        :param constraints: The constraints of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._constraints = constraints

    @property
    def crude_names(self):
        """Gets the crude_names of this OutputTypes.  # noqa: E501

        :return: The crude_names of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._crude_names

    @crude_names.setter
    def crude_names(self, crude_names):
        """Sets the crude_names of this OutputTypes.

        :param crude_names: The crude_names of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._crude_names = crude_names

    @property
    def crude_percent(self):
        """Gets the crude_percent of this OutputTypes.  # noqa: E501

        :return: The crude_percent of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._crude_percent

    @crude_percent.setter
    def crude_percent(self, crude_percent):
        """Sets the crude_percent of this OutputTypes.

        :param crude_percent: The crude_percent of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._crude_percent = crude_percent

    @property
    def crude_pricing(self):
        """Gets the crude_pricing of this OutputTypes.  # noqa: E501

        :return: The crude_pricing of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._crude_pricing

    @crude_pricing.setter
    def crude_pricing(self, crude_pricing):
        """Sets the crude_pricing of this OutputTypes.

        :param crude_pricing: The crude_pricing of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._crude_pricing = crude_pricing

    @property
    def crude_quality(self):
        """Gets the crude_quality of this OutputTypes.  # noqa: E501

        :return: The crude_quality of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._crude_quality

    @crude_quality.setter
    def crude_quality(self, crude_quality):
        """Sets the crude_quality of this OutputTypes.

        :param crude_quality: The crude_quality of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._crude_quality = crude_quality

    @property
    def crudes_and_feeds(self):
        """Gets the crudes_and_feeds of this OutputTypes.  # noqa: E501

        :return: The crudes_and_feeds of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._crudes_and_feeds

    @crudes_and_feeds.setter
    def crudes_and_feeds(self, crudes_and_feeds):
        """Sets the crudes_and_feeds of this OutputTypes.

        :param crudes_and_feeds: The crudes_and_feeds of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._crudes_and_feeds = crudes_and_feeds

    @property
    def delete_category(self):
        """Gets the delete_category of this OutputTypes.  # noqa: E501

        :return: The delete_category of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._delete_category

    @delete_category.setter
    def delete_category(self, delete_category):
        """Sets the delete_category of this OutputTypes.

        :param delete_category: The delete_category of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._delete_category = delete_category

    @property
    def economics(self):
        """Gets the economics of this OutputTypes.  # noqa: E501

        :return: The economics of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._economics

    @economics.setter
    def economics(self, economics):
        """Sets the economics of this OutputTypes.

        :param economics: The economics of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._economics = economics

    @property
    def end_points_f(self):
        """Gets the end_points_f of this OutputTypes.  # noqa: E501

        :return: The end_points_f of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._end_points_f

    @end_points_f.setter
    def end_points_f(self, end_points_f):
        """Sets the end_points_f of this OutputTypes.

        :param end_points_f: The end_points_f of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._end_points_f = end_points_f

    @property
    def expense_factors(self):
        """Gets the expense_factors of this OutputTypes.  # noqa: E501

        :return: The expense_factors of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._expense_factors

    @expense_factors.setter
    def expense_factors(self, expense_factors):
        """Sets the expense_factors of this OutputTypes.

        :param expense_factors: The expense_factors of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._expense_factors = expense_factors

    @property
    def fcc_hydrk_conv(self):
        """Gets the fcc_hydrk_conv of this OutputTypes.  # noqa: E501

        :return: The fcc_hydrk_conv of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._fcc_hydrk_conv

    @fcc_hydrk_conv.setter
    def fcc_hydrk_conv(self, fcc_hydrk_conv):
        """Sets the fcc_hydrk_conv of this OutputTypes.

        :param fcc_hydrk_conv: The fcc_hydrk_conv of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._fcc_hydrk_conv = fcc_hydrk_conv

    @property
    def feeds_pricing(self):
        """Gets the feeds_pricing of this OutputTypes.  # noqa: E501

        :return: The feeds_pricing of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._feeds_pricing

    @feeds_pricing.setter
    def feeds_pricing(self, feeds_pricing):
        """Sets the feeds_pricing of this OutputTypes.

        :param feeds_pricing: The feeds_pricing of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._feeds_pricing = feeds_pricing

    @property
    def gasoline_blending(self):
        """Gets the gasoline_blending of this OutputTypes.  # noqa: E501

        :return: The gasoline_blending of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._gasoline_blending

    @gasoline_blending.setter
    def gasoline_blending(self, gasoline_blending):
        """Sets the gasoline_blending of this OutputTypes.

        :param gasoline_blending: The gasoline_blending of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._gasoline_blending = gasoline_blending

    @property
    def general(self):
        """Gets the general of this OutputTypes.  # noqa: E501

        :return: The general of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._general

    @general.setter
    def general(self, general):
        """Sets the general of this OutputTypes.

        :param general: The general of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._general = general

    @property
    def hydrogen(self):
        """Gets the hydrogen of this OutputTypes.  # noqa: E501

        :return: The hydrogen of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._hydrogen

    @hydrogen.setter
    def hydrogen(self, hydrogen):
        """Sets the hydrogen of this OutputTypes.

        :param hydrogen: The hydrogen of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._hydrogen = hydrogen

    @property
    def product_pricing(self):
        """Gets the product_pricing of this OutputTypes.  # noqa: E501

        :return: The product_pricing of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._product_pricing

    @product_pricing.setter
    def product_pricing(self, product_pricing):
        """Sets the product_pricing of this OutputTypes.

        :param product_pricing: The product_pricing of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._product_pricing = product_pricing

    @property
    def products(self):
        """Gets the products of this OutputTypes.  # noqa: E501

        :return: The products of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._products

    @products.setter
    def products(self, products):
        """Sets the products of this OutputTypes.

        :param products: The products of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._products = products

    @property
    def refinery_layout_svg(self):
        """Gets the refinery_layout_svg of this OutputTypes.  # noqa: E501

        :return: The refinery_layout_svg of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._refinery_layout_svg

    @refinery_layout_svg.setter
    def refinery_layout_svg(self, refinery_layout_svg):
        """Sets the refinery_layout_svg of this OutputTypes.

        :param refinery_layout_svg: The refinery_layout_svg of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._refinery_layout_svg = refinery_layout_svg

    @property
    def sustainability(self):
        """Gets the sustainability of this OutputTypes.  # noqa: E501

        :return: The sustainability of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._sustainability

    @sustainability.setter
    def sustainability(self, sustainability):
        """Sets the sustainability of this OutputTypes.

        :param sustainability: The sustainability of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._sustainability = sustainability

    @property
    def unit_balance(self):
        """Gets the unit_balance of this OutputTypes.  # noqa: E501

        :return: The unit_balance of this OutputTypes.  # noqa: E501
        :rtype: list[OutputDetails]
        """
        return self._unit_balance

    @unit_balance.setter
    def unit_balance(self, unit_balance):
        """Sets the unit_balance of this OutputTypes.

        :param unit_balance: The unit_balance of this OutputTypes.  # noqa: E501
        :type: list[OutputDetails]
        """

        self._unit_balance = unit_balance

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value
        if issubclass(OutputTypes, dict):
            for key, value in self.items():
                result[key] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, OutputTypes):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        return not self == other


import csv
import sqlite3
import numpy as np
import pandas as pd
from nltk.stem.porter import *
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import string
from PIL import Image
from os import path
import matplotlib.pyplot as plt
import matplotlib as mpl
import pickle

from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import TfidfVectorizer

from wordcloud import WordCloud, STOPWORDS
from collections import Counter

from nltk.stem import SnowballStemmer
from nltk.stem import WordNetLemmatizer
stemmer = SnowballStemmer('english')
wordnet_lemmatizer = WordNetLemmatizer()

#############################In/out############################
def open_file(csvfile):
    reader = pd.read_csv(csvfile)
    return reader

def output_file(df,string):
    df.to_csv(string, index = False)

#############################Word Cloud & Feature Extraction############################

def text_process(data):
    '''
    Takes in a df in format of [text,stars] performs the following:
    1. Lower capital letters
    2. Remove all punctuation
    3. Remove all stopwords
    4. Reduce words to their word stem
    5. Return a list of words

    '''
    for i in range(len(data)):
        line = data[i]
        line = line.lower()  # lower case
        translation = str.maketrans("", "", string.punctuation);
        line = line.translate(translation)
        split = word_tokenize(line)
        # filter out any tokens not containing letters (e.g., numeric tokens, raw punctuation)
        filtered = []
        for token in split:
            if re.search('[a-zA-Z]', token):
                filtered.append(token)
        word = [i for i in filtered if i not in stopwords.words('english')]

        d = [stemmer.stem(word) for word in word]
        d = [wordnet_lemmatizer.lemmatize(word) for word in d]
        data[i] = d
    return data

def top_words(business_id,review_ml ):
    train = review_ml[review_ml['business_id'] == business_id][review_ml['True(1)/Deceptive(0)'] == 'True']
    text = list(train['Review'])  # text
    text = text_process(text)
    text = sum(text, [])

    counts = Counter(text)
    wordcloud = WordCloud(
        background_color='white',
        max_words=100,
        max_font_size=50,
        min_font_size=10,
        random_state=40,

    ).fit_words(counts)
    fig = plt.figure(1)
    plt.imshow(wordcloud)
    plt.axis('off')  # remove axis
    plt.show()

def change_label(x):
    for i in range(len(x)):
        if x[i] >= 3.0:  # good review: stars >=3.0
            x[i] = 1
        else:  # bad review: stars 3.0
            x[i] = 0
    return x

def bigram(business_id, review_ml):
    # only use true review

    train0 = review_ml[review_ml['business_id'] == business_id]
    train = train0[train0['True(1)/Deceptive(0)'] == 'True']
    #print(train.head())
    #train_data = list(train['Review'])  # text
    label = list(train['Stars'])  # ratings
    #print(label)
    train_label = change_label(label)
    #print(train_label)

    # TfidfVectorizer Transform
    transformer = TfidfVectorizer(stop_words='english',
                                  ngram_range=(2, 2))  # "ignore terms that appear in less than 1% of the documents".
    #print(transformer)

    cvectorizer = transformer.fit(train['Review'])
    #print(cvectorizer)
    transformed = cvectorizer.transform(train['Review'])
    #print(transformed)

    # SVM regression
    clf = LinearSVC()
    clf.fit(transformed, train_label)
    coefficients = clf.coef_.ravel()
    #print(coefficients)
    pos_coefficients = np.argsort(coefficients)[-10:]
    neg_coefficients = np.argsort(coefficients)[:10]
    combine = np.hstack([neg_coefficients, pos_coefficients])
    #print("combine:, ",combine)
    #print("coefficients[combine]: ", coefficients[combine])

    plt.figure(figsize=(7, 4))
    #print("fisnish 1")

    colors = ['red' if i < 0 else 'blue' for i in coefficients[combine]]
    #print("finish 2")

    plt.bar(np.arange(len(coefficients[combine])), coefficients[combine], color=colors)
    #print("finish 3")

    feature_names = np.array(cvectorizer.get_feature_names())
    #print("finish 4")
    plt.title('why the restaurant is rated as bad or good ', fontsize=15)
    #print("finish 5")

    plt.xticks(np.arange(0, 2 * 10), feature_names[combine], rotation=40, ha='right')
    #print("finish 6")

    plt.show()
    #print("finish 7")

#############################helper function#############################
def load_database_data(c, zipcode, business_name_input):
    c.execute('''
            SELECT b_id,r.review, r.r_stars
            FROM business, review_fact_table r
            WHERE postal_code = ? AND name = ? AND r.business_id = b_id''', (zipcode, business_name_input,))
    dataframe = pd.DataFrame(data=c.fetchall(), columns=['business_id', 'review', 'rating'])
    return dataframe
def select_data(c, zipcode, business_name):
    c.execute('''
                SELECT DISTINCT(b_id)
                FROM business, review_fact_table r
                WHERE postal_code = ? AND name = ? AND r.business_id = b_id''', (zipcode, business_name,))
    single_df = pd.DataFrame(data=c.fetchall(), columns=['business_id'])
    return single_df['business_id'][0]

def fake_ratio(predict, single):
    # Load fake results
    predicted_fake = predict
    # reviews that has only that business id
    reviews = predicted_fake[predicted_fake['business_id'] == single]
    n = reviews.shape[0]
    # print(n)
    fake = reviews.groupby('True(1)/Deceptive(0)').count()['Review'][0]
    # print(fake)
    fake_percentage = fake / n
    # print(fake_percentage)
    return fake_percentage

##############################main######################################
def main():
    #open states and income raw data
    zipcode = input("zipcode:")
    business_name = input("restaurant name:")
    print(zipcode,business_name)

    conn = sqlite3.connect('yelp.db')
    c = conn.cursor()
    predicted_fake = open_file('data/predicted_review.csv')
    # find the business id
    single = select_data(c, zipcode, business_name)
    # print(single)
    fake_review_ratio = fake_ratio(predicted_fake,single)
    print(fake_review_ratio)
    #top_words(single, predicted_fake)
    bigram(single, predicted_fake)

#if __name__=="__main__":
    #main()
main()


nums = []
user_input = input('Enter numbers: ')
while (user_input != 'exit'):

    nums.append(user_input)
    user_input = input('Enter numbers: ')
#tokens = user_input.split() # converts numbers to string

# # Convert strings to integers
# nums = []
# for token in tokens:
#      nums.append(token)
print(nums)
#
# # Print each position and number
print()
for pos, val in enumerate(nums):
    print('{}: {}'.format(pos, val))
#
# # Change negative values to 0
for pos in range(len(nums)):
   if int(nums[pos]) < 0:
         nums[pos] = 0

# Print new numbers
print('New numbers: ')
for num in nums:
    print(num, end=' | ')
print()

nums1 = [50, 10, -5, -4, 6]

for i in range(len(nums1)):
    if nums1[i] < 0:
        nums1[i] = 0
print("nums1:", nums1)


import ast
import logging

from util import cname, slice_range, node_is_int, valid_int_slice
from errors import TypeUnspecifiedError
from ptype import PType
from settings import DEBUG_INFER

# Need to use this form to resolve circular import.
import check

int_t = PType.int()
float_t = PType.float()
bool_t = PType.bool()
str_t = PType.string()
unicode_t = PType.unicode()
unit_t = PType.unit()

log = None

def i_debug(s, cond=True):
    log.debug(s, DEBUG_INFER and cond)

def call_function(fun_name, *args, **kwargs):
    return globals()[fun_name](*args, **kwargs)

def env_get(env, var_id):
    """
    Look up the PType stored for identifier `var_id` in type environment
    `env`. Returns a PType. Raises `TypeUnspecifiedError` if `env` does not
    contain `var_id`.

    - `env`: dictionary mapping strings to PTypes.
    - `var_id`: string representing identifier.
    """

    # make sure the variable is in the environment
    if var_id not in env:
        i_debug("Type of %s not found in %s" % (var_id, env))
        raise TypeUnspecifiedError(var=var_id,env=env)

    # return the type stored in the environment
    return env[var_id]

def infer_expr(e, env):
    """
    Use limited type inference to determine the type of AST expression `e` under
    type environment `env`.
    """

    assert isinstance(e, ast.expr), \
           "Should be inferring type of an expr node, not a " + cname(e)

    n = get_infer_expr_func_name(e.__class__.__name__)

    # If we get a KeyError, then we're trying to infer the type of an AST node
    # that is not in the very limited subset of the language that we're trying
    # to perform type inference on.

    return call_function(n, e, env)

def get_infer_expr_func_name(expr_type):
    return "infer_%s_expr" % expr_type

def infer_Num_expr(num, env):
    """
    Determine the type of AST `Num` expression under type environment `env`.

    `ast.Num`
      - `n`: the numeric literal (as a Python object)
    """

    assert num.__class__ is ast.Num

    n = num.n

    if type(n) is int:

        # (int) assignment rule.
        return int_t

    elif type(n) is float:

        # (flt) assignment rule.
        return float_t

    else:

        # No type assignment rule found.
        return None

def infer_Str_expr(s, env):
    """
    Determine the type of AST `Str` expression under type environment `env`.

    `ast.Str`
      - `s`: the string literal (as a Python object)
    """

    assert s.__class__ is ast.Str

    the_string = s.s

    if type(the_string) is str:

        # (str) assignment rule.
        return str_t

    elif type(the_string) is unicode:

        # (ustr) assignment rule.
        return unicode_t

    else:

        # No type assignment rule found..
        return None

def infer_Name_expr(name, env):
    """
    Determine the type of AST `Name` expression under type environment `env`.

    `ast.Name`
      - `id`: the identifier (as a Python `str`)
      - `ctx`: the context (e.g., load, store) in which the expr is used

    The AST treats `True` and `False` as Name nodes with id of `"True"` or
    `"False"`, strangely enough.
    """

    assert name.__class__ is ast.Name

    id_str = name.id

    if id_str == 'True' or id_str == 'False':

        # (bool) assignment rule.
        return bool_t

    elif id_str == 'None':

        # (none) assignment rule.
        return unit_t

    else:

        # (idn) assignment rule.
        return env_get(env, id_str)

def infer_List_expr(lst, env):
    """
    Determine the type of AST `List` expression under type environment `env`.

    `ast.List`
      - `elts`: Python list of contained expr nodes
      - `ctx': context of the expr (e.g., load, store)
    """

    assert lst.__class__ is ast.List

    elts_list = lst.elts

    first_type = infer_expr(elts_list[0], env)

    if all(check.check_expr(e, first_type, env) for e in elts_list[1:]):

        # (lst) assignment rule.
        return PType.list(first_type)

    else:

        # No assignment rule found.
        return None

def infer_Tuple_expr(tup, env):
    """
    Determine the type of AST `Tuple` expression under type environment `env`.

    `ast.Tuple`
      - `elts`: Python list of contained expr nodes
      - `ctx`: context of the expr (e.g., load, store)
    """

    assert tup.__class__ is ast.Tuple

    elts_list = tup.elts

    if all(infer_expr(e, env) != None for e in elts_list):

        # (tup) assignment rule.
        return PType.tuple([infer_expr(e, env) for e in elts_list])

    else:

        # No assignment rule found.
        return None

def infer_Subscript_expr(subs, env):
    """
    Determine the type of AST `Subscript` expression under type environment
    `env`.

    `ast.Subscript`
      - `value`: the collection being subscripted
      - `slice`: `ast.Index` or `ast.Slice`
        + `value`: expr used as index (if `ast.Index`)
        + `lower`: expr used as lower bound (if `ast.Slice`)
        + `upper`: expr used as upper bound (if `ast.Slice`)
        + `step`: expr used as step (if `ast.Slice`)

    We can only subscript tuples with numeric literals because the inference
    algorithm needs to actually know the values of the subscript parameters.
    """

    assert subs.__class__ is ast.Subscript

    col = subs.value
    col_t = infer_expr(col, env)

    is_index = subs.slice.__class__ is ast.Index
    is_slice = subs.slice.__class__ is ast.Slice
    assert is_index or is_slice

    # Store the attributes of the slice.
    if is_index:
        i = subs.slice.value
    else: # is_slice
        l = subs.slice.lower
        u = subs.slice.upper
        s = subs.slice.step

    if col_t is None:

        # If we can't assign a type to the collection, then we can't assign a
        # type to its subscript.
        return None

    # String subscripting
    elif col_t == str_t or col_t == unicode_t:

        if is_index and infer_expr(i, env) == int_t:

            # (sidx) assignment rule.
            return col_t

        elif is_slice and valid_int_slice(l, u, s, env):

            # (sslc) assignment rule.
            return col_t

        else:

            # No assignment rule found.
            return None

    # List subscripting
    elif col_t.is_list():

        if is_index and check.check_expr(i, int_t, env):

            # (lidx) assignment rule.
            return col_t.elt

        elif is_slice and valid_int_slice(l, u, s, env):

            # (lslc) assignment rule.
            return col_t

        else:

            # No assignment rule found.
            return None

    # Tuple subscripting
    elif col_t.is_tuple():

        col_ts = col_t.elts
        n = len(col_ts)

        if is_index and node_is_int(i) and -n <= i.n < n:

            # (tidx) assignment rule.
            return col_ts[i.n]

        elif is_slice:

            rng = slice_range(l, u, s, len(col_ts))

            if rng is not None:

                # (tslc) assignment rule.
                return PType.tuple([col_ts[i] for i in rng])

            else:

                # No assignment rule found.
                return None

        else:

            # No assignment rule found.
            return None

    else:

        # No assignment rule found.
        return None


import asyncpg

from app.main import create_app
from app.settings import Settings
from tests.test_currencies import test_currencies_success

settings = Settings()

async def test_rate_success(aiohttp_client, loop):
    currencies = await test_currencies_success(aiohttp_client, loop)
    currency = currencies['results']['currencies'][0]['id']
    client = await aiohttp_client(create_app)

    conn = await asyncpg.connect(settings.dsn)
    try:
        resp = await client.get(f'/rate/{currency}/')
        assert resp.status == 200
        result = await resp.json()
        assert 'current_rate' in result
        assert 'avg_volume' in result

        resp = await client.get(f'/rate/?id={currency}')
        assert resp.status == 200
        result = await resp.json()
        assert 'current_rate' in result
        assert 'avg_volume' in result
    finally:
        await conn.close()

async def test_rate_not_found(aiohttp_client, loop):
    curency_name = 'BCH'
    client = await aiohttp_client(create_app)
    conn = await asyncpg.connect(settings.dsn)
    try:
        currency = await conn.fetchval('select id from currency where name=$1', curency_name)
        await conn.execute('delete from currency where name=$1', curency_name)
        resp = await client.get(f'/rate/{currency}/')
        assert resp.status == 404
        result = await resp.json()
        assert 'error' in result
        assert 'detail' in result
        assert 'not found transaction' == result['detail']

    finally:
        await conn.close()

async def test_rate_error(aiohttp_client, loop):
    curency_name = 'BCH'
    client = await aiohttp_client(create_app)
    resp = await client.get(f'/rate/{curency_name}/')
    assert resp.status == 400


# function programe 1

def funadd(e,f):
    a=10
    b=10
    print("e:",e,"f:",f)
    print(a+b)
    return a+b,e+f

def funsub():
    a=20
    b=10
    print(a-b)

c,d=funadd(4,8)
ff,dd=funadd(14,18)
print("c value:",c)
print("d value:",d)
funsub()


entered_string = input('Please enter the string: ')

def string_operations(text):
    third_symbol = text[2]
    print('Third symbol of this string: {}'.format(third_symbol))
    penultimate = text[-2]
    print('Penultimate character of this string: {}'.format(penultimate))
    first_five = text[:5]
    print('First five characters of this string: {}'.format(first_five))
    without_last_two = text[:-2]
    print('The entire string except the last two characters: {}'.format(without_last_two))
    even_indices = text[::2]
    print('All characters with even indices (assuming that indexing starts at 0,'
          ' so characters are output starting from the first one).: {}'.format(even_indices))
    odd_indices = text[1::2]
    print('All characters with odd indices, that is,'
          ' starting from the second character of the string.: {}'.format(odd_indices))
    reverse_order = text[::-1]
    print('All characters in reverse order.: {}'.format(reverse_order))
    reverse_from_last_one = text[-1::-2]
    print('All the characters of the string one by one in reverse order,'
          ' starting with the last one.: {}'.format(reverse_from_last_one))
    length_of_the_string = len(text)
    print('The length of this string.: {}'.format(length_of_the_string))

string_operations(entered_string)


'''
2 ways:
1. consider all substrings, and use memoization to not reconsider substrings
leetcode
   ^

                              abcd
          a bcd                ab cd       abc d       abcd .
      /     |      \
   b cd   bc d    bcd .

n = s.length
helper(mid = 1)
function helper(mid)
    if mid == n:
        return True
    #s = orig-s[mid:]
    for idx in [mid ... n]
        if s.substring(0..idx) and helper(idx)
            return True
    return False

2. iteratively get the answer of whether s[i] can be segmented until i = n - 1
    tabulation
    table[i] = substring[i]
    abcde
    00 = t
    01 =  t/f
    02 = 01? and 2 = F
    03 = 02F
    0n

    f[0] = true
    for cvc = 1 .. n
        for k = 0 .. cvc
            f[cvc] = f[cvc] or ( s.substring(0, cvc) and f[k])
    return f[n]

'''
class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        n = len(s)
        f = [False] * (n + 1)
        words = set(wordDict)
        f[0] = True
        for cvc in range(1, n + 1): # 3 [_ _ _]
            for k in range(cvc+1): # 0 .. 3 --> 0, 1
                f[cvc] = f[cvc] or (s[k:cvc] in words and f[k])
        return f[n]


from sys import stderr
from tourney import *

ENGINE = './erastus -i 10000 -w 4'
SCORE_THRESHOLD = .2

START = '0000000000000000000000000xxxxxxxx1'

def puzzle_search():
    engine = Engine(ENGINE)

    state = START
    while 1:
        action, log = engine.run(state)
        stderr.write('.')
        stderr.flush()

        top_score = None
        for line in log.split('\n'):
            if not line.startswith('alt'):
                continue

            _, score, _ = line.split()
            score = float(score)

            if top_score == None:
                top_score = score
                if top_score != 1:
                    break
            else:
                diff = top_score - score
                if diff >= SCORE_THRESHOLD:
                    print(f'https://erastus.schneiderbox.net/#{state}\t({diff})')
                break

        state = move_state(state, action)
        if action_count(state) == 0:
            stderr.write('\n')
            state = START

if __name__ == '__main__':
    puzzle_search()


"""Test the concurrency module."""

from typing import Any

import pytest

from rtasr.concurrency import ConcurrencyHandler, ConcurrencyToken

class TestConcurrencyToken:
    """Test the ConcurrencyToken class."""

    @pytest.mark.parametrize("value", [None, "string", True, False, [], {}])
    def test_concurrency_token_invalid(self, value: Any) -> None:
        """Test the concurrency token with invalid values."""
        with pytest.raises(TypeError):
            ConcurrencyToken(value)

    @pytest.mark.parametrize("value", [0, 1, 2, 1.0, 2.0])
    def test_concurrency_token_valid(self, value: int) -> None:
        """Test the concurrency token."""
        token = ConcurrencyToken(value=value)

        assert token.value == value

class TestConcurrencyHandler:
    """Test the ConcurrencyHandler class."""

    @pytest.mark.asyncio
    async def test_concurrency_handler_with_limit(self) -> None:
        """Test the concurrency handler with a limit."""
        limit = 5
        concurrency_handler = ConcurrencyHandler(limit)

        assert hasattr(concurrency_handler, "limit")
        assert hasattr(concurrency_handler, "queue")
        assert concurrency_handler.limit == limit
        assert concurrency_handler.queue.maxsize == limit

        tokens = []
        for _ in range(limit):
            token = await concurrency_handler.get()
            assert isinstance(token, ConcurrencyToken)
            tokens.append(token)

        # Queue should be empty now
        assert concurrency_handler.queue.empty()

        for token in tokens:
            concurrency_handler.put(token)

        # Queue should be refilled
        for _ in range(limit):
            token = await concurrency_handler.get()
            assert isinstance(token, ConcurrencyToken)

    @pytest.mark.asyncio
    async def test_concurrency_handler_without_limit(self) -> None:
        """Test the concurrency handler without a limit."""
        concurrency_handler = ConcurrencyHandler(limit=None)

        token = await concurrency_handler.get()
        assert token is None


import numpy as np
import time
import os
import sys
from scipy.stats import poisson, binom
from scipy.special import erf as erf
from admin import make_glob_array
import multiprocessing
# from Sim_show import Sim_fit
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import matplotlib.colors as mcolors
from make_3D import make_3D

pmts=np.array([0,1,4,6,7,3,10,13,15,17,18,5,11,12,14])

path='/home/gerak/Desktop/DireXeno/011220/'
data=np.load(path+'h.npz')
Angs=data['Angs']
Angs10=data['Angs10']
Angsbins=data['Angsbins']
H=data['H']
G=data['G']
Spectrum=data['spectrum']
Sbins=data['Sbins']
Spectra=np.transpose(data['spectra'], (2,0,1))
sbins=data['sbins']
FSbins=data['FSbins']
FullSpectrum=data['Fullspectrum']
w=data['W']
Wbins=data['Wbins']
Wbands=data['Wbands']
Sbands=data['Sbands']
W20_40=data['W20_40']
W20_40bins=data['W20_40bins']

data=np.loadtxt(path+'NRel.txt')
NDep=[]
NSpec=[]
for i in range(len(data)):
    NDep.append(data[i][0])
    NSpec.append(data[i][1])
NSpec=NSpec/np.sum(NSpec)

N=10
data=np.load('Q.npz')
ls=data['ls']
Sspectrum=data['Ravel_Spectrum'].reshape((N, 1, np.shape(Spectrum)[0]))[:,0]
Sspectra=data['Ravel_Spectra'].reshape((N, 1, np.shape(Spectra)[0], np.shape(Spectra)[1], np.shape(Spectra)[2]))[:,0]
SG=data['Ravel_G'].reshape((N, 1, np.shape(G)[0], np.shape(G)[1], np.shape(G)[2]))[:,0]
SH=data['Ravel_H'].reshape((N, 1, np.shape(H)[0], np.shape(H)[1], np.shape(H)[2], np.shape(H)[3]))[:,0]
SAngs=data['Ravel_Angs'].reshape((N, 1, np.shape(Angs)[0], np.shape(Angs)[1]))[:,0]
SFullspectrum=data['Ravel_Fullspectrum'].reshape((N, 1, np.shape(FullSpectrum)[1]))[:,0]
SW=data['Ravel_W'].reshape((N, 1, np.shape(w)[0]))[:,0]
keVbins=data['keVbins']
PEbins=data['PEbins']
keVPE=data['Ravel_KeVPE'].reshape((N, len(keVbins)-1, len(PEbins)-1))
y=np.arange(0, 600)
y1=data['adn']*y+data['bdn']
y2=data['aup']*y+data['bup']

plt.figure()
plt.title('Energy spectrum')
plt.step(NDep, NSpec, where='mid')
# plt.yscale('log')

plt.figure(figsize=(20,10))
X, Y= np.meshgrid(0.5*(keVbins[1:]+keVbins[:-1]), 0.5*(PEbins[1:]+PEbins[:-1]))
plt.pcolor(Y, X, np.mean(keVPE, axis=0), norm=mcolors.PowerNorm(0.3))
plt.plot(y, y1, 'k--', label='{}x+{}'.format(np.round(data['adn'],decimals=2), np.round(data['bdn'],decimals=2)), linewidth=5)
plt.plot(y, y2, 'k--', label='{}x+{}'.format(np.round(data['aup'],decimals=2), np.round(data['bup'],decimals=2)), linewidth=5)
plt.xlabel('PEs', fontsize=25)
plt.ylabel('keV', fontsize=25)
plt.tick_params(axis='both', which='major', labelsize=20)
cbar=plt.colorbar()
cbar.ax.tick_params(labelsize=25)
plt.legend(fontsize=35, loc='upper right')
plt.xlim(0, np.amax(PEbins))
plt.ylim(0, np.amax(keVbins))

plt.figure()
plt.title('W')
plt.bar(0.5*(Wbins[1:]+Wbins[:-1]), w, width=Wbins[1:]-Wbins[:-1], color='r', alpha=0.5)
plt.errorbar(0.5*(Wbins[1:]+Wbins[:-1]), np.mean(SW, axis=0), np.std(SW, axis=0), fmt='.')
for i in range(len(Wbands)):
    plt.axvline(Wbands[i], 0, 1)
plt.yscale('log')
#
plt.figure()
plt.title('Full Spectrum')
plt.step(0.5*(FSbins[1:]+FSbins[:-1]), np.sum(FullSpectrum, axis=0), where='mid')
for i in range(len(Wbands)-1):
    plt.bar(0.5*(FSbins[1:]+FSbins[:-1]), FullSpectrum[i], width=FSbins[1:]-FSbins[:-1], label='spectrum', alpha=0.5)
plt.errorbar(0.5*(FSbins[1:]+FSbins[:-1]), np.mean(SFullspectrum, axis=0), np.std(SFullspectrum, axis=0), fmt='.', label='A')
plt.yscale('log')
plt.legend()

plt.figure()
plt.title('Global Spectrum')
plt.bar(0.5*(Sbins[1:]+Sbins[:-1]), Spectrum, width=Sbins[1:]-Sbins[:-1], label='spectrum', color='r', alpha=0.5)
plt.errorbar(0.5*(Sbins[1:]+Sbins[:-1]), np.mean(Sspectrum, axis=0), np.std(Sspectrum, axis=0), fmt='.', label='A')
plt.legend()
plt.yscale('log')

t=np.arange(100)
fig, ax=plt.subplots(2,3)
for k in range(len(Sbands)-1):
    #plt.title('The temporal structure in different energy ranges (NRs) {}-{}'.format(Sbands[k], Sbands[k+1]), fontsize=35)
    data=np.ravel(G[k])
    model=np.ravel(np.mean(SG[:,k], axis=0))
    N=np.sum(np.sum(G[k].T*np.arange(np.shape(G)[1]), axis=1)/np.sum(G[k], axis=0))
    np.ravel(ax)[k].step(t, (np.sum(G[k].T*np.arange(np.shape(G)[1]), axis=1)/np.sum(G[k], axis=0))/N, where='mid', label='PEs: {}-{}'.format(Sbands[k], Sbands[k+1]), linewidth=3)
    np.ravel(ax)[k].errorbar(t, np.mean(np.sum(np.transpose(SG[:,k], (0,2,1))*np.arange(np.shape(G)[1]), axis=-1)/np.sum(SG[:,k], axis=1), axis=0)/N,
                np.std(np.sum(np.transpose(SG[:,k], (0,2,1))*np.arange(np.shape(G)[1]), axis=-1)/np.sum(SG[:,k], axis=1), axis=0)/N, fmt='.', label='{}'.format(-np.sum(data*np.log((model+1e-10)/(data+1e-10))+data-model)))
    np.ravel(ax)[k].legend(fontsize=10)
    np.ravel(ax)[k].set_yscale('log')
    # plt.xlabel('Time [ns]', fontsize=35)
    # plt.ylabel('The probability to resolve a PE /\naveage number of PEs at\n the energy range', fontsize=35)
    # plt.ylabel('The average number of\nPEs resolved (normalized)', fontsize=35)
    # plt.tick_params(axis='both', which='major', labelsize=20)
# plt.show()

# for k in range(len(Sbands)-1):
#     fig, ax=plt.subplots(4,4)
#     fig.suptitle('PMT spectra ({}-{})'.format(Sbands[k], Sbands[k+1]))
#     for i in range(15):
#         np.ravel(ax)[i].step(0.5*(sbins[1:]+sbins[:-1]), Spectra[k,:,i], where='mid', label='A')
#         np.ravel(ax)[i].errorbar(0.5*(sbins[1:]+sbins[:-1]), np.mean(Sspectra[:,k,:,i], axis=0), np.std(Sspectra[:,k,:,i], axis=0), fmt='.', label='A')
#         np.ravel(ax)[i].legend()
#         np.ravel(ax)[i].set_yscale('log')

# for k in range(len(Sbands)-1):
for k in range(1):
    fig, ax=plt.subplots(4,4)
    fig.suptitle('PMT temporal ({}-{})'.format(Sbands[k], Sbands[k+1]))
    for i in range(15):
        np.ravel(ax)[i].step(t, np.sum(H[k, :,:,i].T*np.arange(np.shape(H)[1]), axis=1)/np.sum(H[k, :,:,i], axis=0), where='mid', label='PMT{}'.format(pmts[i]))
        # np.ravel(ax)[i].errorbar(t, np.mean(np.sum(np.transpose(SH[k,:,:,:,i], (0,2,1))*np.arange(np.shape(H)[1]), axis=-1)/np.sum(SH[k,:,:,:,i], axis=1), axis=0),
        #             np.std(np.sum(np.transpose(SH[k,:,:,:,i], (0,2,1))*np.arange(np.shape(H)[1]), axis=-1)/np.sum(SH[k,:,:,:,i], axis=1), axis=0), fmt='.')
        np.ravel(ax)[i].set_yscale('log')
        np.ravel(ax)[i].legend()
plt.show()


import cv2
import matplotlib.pyplot as plt
import numpy as np
import selectivesearch
from predictors import resnet152
from utils import selectors, nms
import xml.etree.ElementTree as ET
import random

boxes = {}

def getImgReady(img, show=False):
    if img is None:
         return None
    if show:
         plt.imshow(img)
         plt.axis('off')
    # convert into format (batch, RGB, width, height)
    img = cv2.resize(img, (224, 224))
    img = np.swapaxes(img, 0, 2)
    img = np.swapaxes(img, 1, 2)
    img = img[np.newaxis, :]
    return img

def addBox(x, y, w, h, prob, label):
    x1 = x
    x2 = x + w
    y1 = y
    y2 = y + h
    if not boxes.has_key(label):
        boxes[label] = [[x1, y1, x2, y2, prob]]
    else:
        boxes[label].append([x1, y1, x2, y2, prob])

def drawGroundTruth(imgName, img):
    xmlTree = ET.parse(annotationsDir + '{}.xml'.format(imgName.split('.')[0]))  # reads corresponding XML file
    for object in xmlTree.findall('object'):
        name = object.find('name').text
        name = nameDict[name]

        bndbox = object.find('bndbox')
        xmin = int(float(bndbox.find('xmin').text))     #reads coordinates
        ymin = int(float(bndbox.find('ymin').text))
        xmax = int(float(bndbox.find('xmax').text))
        ymax = int(float(bndbox.find('ymax').text))

        rect = plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin,
                             fill=False, edgecolor=(0, 1, 0), linewidth=3.5)
        plt.gca().add_patch(rect)
        plt.gca().text(xmin, ymin - 2, 'Ground Truth:{:s}'.format(name),
                       bbox=dict(facecolor=(0, 1, 0), alpha=0.5), fontsize=12, color='white')

def getNameDict(filename):
    dic = {}
    with open(filename, 'r') as f:
        lines = f.readlines()
        for line in lines:
            line = line.strip('\n')
            key = line.split(' ')[0]
            val = line.split(' ')[1]
            dic[key] = val
    return dic

annotationsDir = '../Data/ImageNet/ILSVRC2012/val-Annotations/'
imgsDir = '../Data/ImageNet/ILSVRC2012/img_val/'

nameDict = getNameDict('../synset.txt')

imgName = selectors.selectImg(imgsDir)
imgPath = imgsDir + imgName
img = cv2.cvtColor(cv2.imread(imgPath), cv2.COLOR_BGR2RGB)

plt.figure(imgName.split('.')[0])
plt.imshow(img)
plt.axis('off')

img_label, regions = selectivesearch.selective_search(img, scale = 500, sigma = 0.9, min_size = 500)
for i, region in enumerate(regions):    #rect:x y w h
    x = region['rect'][0]
    y = region['rect'][1]
    w = region['rect'][2]
    h = region['rect'][3]

    croppedImg = img[y:y + h,x:x + w]
    croppedImg = getImgReady(croppedImg)
    prob, label = resnet152.predict(croppedImg)

    if prob < 0.2:  #ignore low probability boxes
        continue

    addBox(x, y, w, h, prob, label)

for label in boxes:
    color = (random.random(), random.random(), random.random())
    indexes = nms.nms(np.array(boxes[label]), 0.3)
    for i in indexes:
        x1 = boxes[label][i][0]
        y1 = boxes[label][i][1]
        x2 = boxes[label][i][2]
        y2 = boxes[label][i][3]
        prob = boxes[label][i][4]

        rect = plt.Rectangle((x1, y1), x2 - x1, y2 - y1,
                             fill=False, edgecolor=color, linewidth=3.5)
        plt.gca().add_patch(rect)
        plt.gca().text(x1, y1 - 2, '{:s} {:.3f}'.format(label, prob),
                       bbox=dict(facecolor=color, alpha=0.5), fontsize=12, color='white')

drawGroundTruth(imgName, img)

plt.show()


# -*- coding:utf-8 -*-
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        if len(tinput) < k or k <= 0: #他妈的还有这个条件 k不能为0！！！
            return []
        length = len(tinput)
        start = 0
        end = length - 1
        index = self.partition(tinput, length, start, end)
        while index != (k-1):
            if index > k-1:#前index位比K多，从start到K重新排序
                end = index - 1
                index = self.partition(tinput, length, start, end)
            else:#前start已经排序，但是start到k还没排好
                start = index + 1
                index = self.partition(tinput, length, start, end)
        return sorted(tinput[:k])

    def partition(self, data, length, start, end):
        temp = data[start]
        while start < end:
            while start < end and data[end] >= temp:
                end -= 1
            data[start] = data[end]
            while start < end and data[start] <= temp:
                start += 1
            data[end] = data[start] #交换后面那个比temp大的到end

        data[start] = temp
        return start


import math
vineyard_sq_m = int(input())
grapes_kg_per_sq_m = float(input())
wine_litres_needed = int(input())
number_workers = int(input())
difference = 0
litres_wine = 0
litres_per_worker = 0
total_grapes = vineyard_sq_m * grapes_kg_per_sq_m
percent_for_wine = 0.4
grapes_for_wine = total_grapes * 0.4
litres_wine = grapes_for_wine / 2.5
difference = abs(litres_wine - wine_litres_needed)
if litres_wine < wine_litres_needed:
    print(f"It will be a tough winter! More {math.floor(difference)} liters wine needed.")
elif litres_wine >= wine_litres_needed:
    litres_per_worker = difference / number_workers
    print(f"Good harvest this year! Total wine: {math.floor(litres_wine)} liters.")
    print(f"{math.ceil(difference)} liters left -> {math.ceil(litres_per_worker)} liters per person.")


#!/usr/bin/env python3

# Get sequences from NCBI.
# To be called from Snakefile.
# Usage: python windows.py <infile> <outfile> <email> <window_size>

import os
import sys

from Bio import Entrez
from Bio import SeqIO
import pandas as pd

def main():
    snpfile = sys.argv[1]
    outfile = sys.argv[2]
    email = sys.argv[3]
    window_size = sys.argv[4]

    interest = pd.read_csv(
        snpfile,
        header=0,
        dtype={"chrom": str, "center": np.int64},
    )
    interest.columns = interest.columns.str.lower().str.replace(" ", "_")
    interest[["chrom", "center"]] = (
        interest.iloc[:, 0]
        .str.replace("_[A-Z]{3}?", "")
        .str.replace(" ", "")
        .str.split("_", expand=True)
    )
    interest.assign(
        start=lambda center: center.to_numeric() - window_size,
        end=lambda center: center.to_numeric() + window_size
    )
    interest.index.rename("Index", inplace=True)
    summary = pd.read_csv("Data/dmelSummary.csv")
    summary.index.rename("Index", inplace=True)
    summary.columns = summary.columns.str.lower().str.replace(" ", "_")

    seqs = []
    Entrez.email = email
    for index, row in interest.iterrows():
        with Entrez.efetch(
            db="nucleotide",
            id=summary.loc[summary["name"] == row["chrom"], "refseq"].iat[0],
            rettype="fasta",
            strand=1,
            seq_start=row["start"],
            seq_stop=row["end"],
        ) as handle:
            seqs.append(SeqIO.read(handle, "fasta"))
    SeqIO.write(seqs, outfile, "fasta")

if __name__ == "__main__":
    main()


import pygame
from math import *
import time
pygame.init()
pygame.display.set_caption("sprite sheet")  # sets the window title
screen = pygame.display.set_mode((1000, 800))  # creates game screen
screen.fill((0,0,0))
clock = pygame.time.Clock() #set up clock

#Variables and stuff (Start)-------------------------------------------------------------------
red_pawn = pygame.image.load('RedPawn.png') #load your spritesheet
white_pawn = pygame.image.load('WhitePawn.png') #load your spritesheet
background = pygame.image.load('Chess board.png')#loads background
white_rook = pygame.image.load('WhiteRook.png')
red_rook = pygame.image.load('RedRook.png')
white_queen = pygame.image.load('WhiteQueen.png')
red_queen = pygame.image.load('RedQueen.png')
white_king = pygame.image.load('WhiteKing.png')
red_king = pygame.image.load('RedKing.png')
white_bishop = pygame.image.load('WhiteBishop.png')
red_bishop = pygame.image.load('RedBishop.png')
red_knight = pygame.image.load('RedKnight.png')
white_knight = pygame.image.load('WhiteKnight.png')

White=(255,255,255)
PIECEWIDTH = 100
checkmate = False #variable to run our game loop
whiteturn = True
hasPicked = False
clicked = False
TurnNum=0
ticks = 1
tickss = 1

t = 600
t2 = 600
pygame.display.set_caption('Show Text')
font = pygame.font.Font('freesansbold.ttf', 32)
#Variables and stuff (End)--------------------------------------------------------------------
#text to screen setup

#text input------------------------------------------
n1 = input('Enter your name player 1:')
n2 = input('Enter your name player 2')
#End of text input----------------------------------

#Pieces start-----------------------------------------------
class pieces:
    def __init__(self,xpos,ypos,type):
        self.xpos = xpos
        self.ypos = ypos
        self.lifted = False
        self.type = type
        self.alive = True
        self.row=0
        self.column=0

    def updatePos(self):
        self.row = int(self.xpos/100)
        self.column = int(self.ypos/100)
        print("my row and column is ", self.row, self.column)
        self.xpos = self.row*100
        self.ypos = self.column*100

    def isClicked(self,x,y):
            global hasPicked
            global TurnNum
            print("checking distance")
            if self.alive == True:
                if hasPicked == False and self.lifted == False:
                    if (sqrt(((self.xpos+50)-x)**2 + ((self.ypos+50)-y)**2)) <= 50:#check if the distance b/t (x, y) and (self.xpos, self.ypos) is LESS than 50
                        self.lifted = True #if true, set lifted to true
                        hasPicked = True
                        TurnNum+=1
                        print("lifted!")
                    else:
                        print("no collision")

    def move(self, x, y):
            if self.lifted == True:#if islifed is true, set self.xpos to x, and self.ypos to y
                self.xpos = x-50
                self.ypos = y-50

    def draw(self):
        if self.alive == True:
            #pawns
            if self.type == "WhitePawn":
                screen.blit(white_pawn, (self.xpos, self.ypos), (0, 0, 100, 100))
            if self.type == "RedPawn":
                screen.blit(red_pawn, (self.xpos, self.ypos), (0, 0, 100, 100))
            #knights
            if self.type == "WhiteKnight":
                screen.blit(white_knight, (self.xpos, self.ypos), (0, 0, 100, 100))
            if self.type == "RedKnight":
                screen.blit(red_knight, (self.xpos, self.ypos), (0, 0, 100, 100))
            #bishop
            if self.type == "WhiteBishop":
                screen.blit(white_bishop, (self.xpos, self.ypos), (0, 0, 100, 100))
            if self.type == "RedBishop":
                screen.blit(red_bishop, (self.xpos, self.ypos), (0, 0, 100, 100))
            #rook
            if self.type == "WhiteRook":
                screen.blit(white_rook, (self.xpos, self.ypos), (0, 0, 100, 100))
            if self.type == "RedRook":
                screen.blit(red_rook, (self.xpos, self.ypos), (0, 0, 100, 100))
            #king
            if self.type == "WhiteKing":
                screen.blit(white_king, (self.xpos, self.ypos), (0, 0, 100, 100))
            if self.type == "RedKing":
                screen.blit(red_king, (self.xpos, self.ypos), (0, 0, 100, 100))
            #queen
            if self.type == "WhiteQueen":
                screen.blit(white_queen, (self.xpos, self.ypos), (0, 0, 100, 100))
            if self.type == "RedQueen":
                screen.blit(red_queen, (self.xpos, self.ypos), (0, 0, 100, 100))

#Pieces End-----------------------------------------------------------

#python list (like a vector)
whitelist = []
redlist = []

#White Pawns
WhitePawn1 = pieces(0, 100, "WhitePawn")
whitelist.append(WhitePawn1)
WhitePawn2 = pieces(100, 100, "WhitePawn")
whitelist.append(WhitePawn2)
WhitePawn3 = pieces(200, 100, "WhitePawn")
whitelist.append(WhitePawn3)
WhitePawn4 = pieces(300, 100, "WhitePawn")
whitelist.append(WhitePawn4)
WhitePawn5 = pieces(400, 100, "WhitePawn")
whitelist.append(WhitePawn5)
WhitePawn6 = pieces(500, 100, "WhitePawn")
whitelist.append(WhitePawn6)
WhitePawn7 = pieces(600, 100, "WhitePawn")
whitelist.append(WhitePawn7)
WhitePawn8 = pieces(700, 100, "WhitePawn")
whitelist.append(WhitePawn8)
#Red Pawns
RedPawn1 = pieces(0, 600, "RedPawn")
redlist.append(RedPawn1)
RedPawn2 = pieces(100, 600, "RedPawn")
redlist.append(RedPawn2)
RedPawn3 = pieces(200, 600, "RedPawn")
redlist.append(RedPawn3)
RedPawn4 = pieces(300, 600, "RedPawn")
redlist.append(RedPawn4)
RedPawn5 = pieces(400, 600, "RedPawn")
redlist.append(RedPawn5)
RedPawn6 = pieces(500, 600, "RedPawn")
redlist.append(RedPawn6)
RedPawn7 = pieces(600, 600, "RedPawn")
redlist.append(RedPawn7)
RedPawn8 = pieces(700, 600, "RedPawn")
redlist.append(RedPawn8)
#White Rooks
WhiteRook1 = pieces(0, 0, "WhiteRook")
whitelist.append(WhiteRook1)
WhiteRook2 = pieces(700, 0, "WhiteRook")
whitelist.append(WhiteRook2)
#Red Rooks
RedRook1 = pieces(0, 700, "RedRook")
redlist.append(RedRook1)
RedRook2 = pieces(700, 700, "RedRook")
redlist.append(RedRook2)
#White Knights
WhiteKnight1 = pieces(100, 0, "WhiteKnight")
whitelist.append(WhiteKnight1)
WhiteKnight2 = pieces(600, 0, "WhiteKnight")
whitelist.append(WhiteKnight2)
#Red Knights
RedKnight1 = pieces(100, 700, "RedKnight")
redlist.append(RedKnight1)
RedKnight2 = pieces(600, 700, "RedKnight")
redlist.append(RedKnight2)
#White Bishops
WhiteBishop1 = pieces(200, 0, "WhiteBishop")
whitelist.append(WhiteBishop1)
WhiteBishop2 = pieces(500, 0, "WhiteBishop")
whitelist.append(WhiteBishop2)
#Red Bishop
RedBishop1 = pieces(200, 700, "RedBishop")
redlist.append(RedBishop1)
RedBishop2 = pieces(500, 700, "RedBishop")
redlist.append(RedBishop2)
#White and Red King
WhiteKing = pieces(300, 0, "WhiteKing")
whitelist.append(WhiteKing)
RedKing = pieces(300, 700, "RedKing")
redlist.append(RedKing)
#White and Red Queen
WhiteQueen = pieces(400, 0, "WhiteQueen")
whitelist.append(WhiteQueen)
RedQueen = pieces(400, 700, "RedQueen")
redlist.append(RedQueen)

#MAP:
map = [[3, 4, 5, 6, 7, 5, 4, 3],

       [2, 2, 2, 2, 2, 2, 2, 2],

       [0, 0, 0, 0, 0, 0, 0, 0],

       [0, 0, 0, 0, 0, 0, 0, 0],

       [0, 0, 0, 0, 0, 0, 0, 0],

       [0, 0, 0, 0, 0, 0, 0, 0],

       [1, 1, 1, 1, 1, 1, 1, 1],

       [8, 9, 10, 11, 12, 10, 9, 8]]

while not checkmate:

    clock.tick(60)
    #print("clicked is ", clicked)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            checkmate = True

        if event.type == pygame.MOUSEBUTTONDOWN:
            if pygame.MOUSEBUTTONDOWN:
                print("click")
                if clicked == False:
                    clicked = True
                elif clicked == True:
                    clicked = False

        if event.type == pygame.MOUSEBUTTONUP:
            print("unclick")
            clicked = False

        if event.type == pygame.MOUSEMOTION: #check if mouse moved
            mousePos = event.pos #refreshes mouse position
          #  print("mouse position: (",mousePos[0]," , ",mousePos[1], ")")

    #COLLISION

    #White updatepos
    for i in range(len(whitelist)):
        whitelist[i].updatePos()
    #red updatepos
    for i in range(len(redlist)):
        redlist[i].updatePos()

    if clicked ==True:

        if whiteturn is True:# if whiteturn is true white pieces go
            #white clicked function
            for i in range(len(whitelist)):
                whitelist[i].isClicked(mousePos[0],mousePos[1])

        if whiteturn is False: # if whiteturn is false red goes
            #red clicked function
            for i in range(len(redlist)):
                redlist[i].isClicked(mousePos[0],mousePos[1])
    if clicked == False:
        hasPicked = False
        #white pieces lifted set down
        for i in range(len(whitelist)):
            whitelist[i].lifted = False
        #red piece lifted set down
        for i in range(len(redlist)):
            redlist[i].lifted = False
    #White pieces move
    for i in range(len(whitelist)):
        whitelist[i].move(mousePos[0],mousePos[1])
    #Red pieces move
    for i in range(len(redlist)):
        redlist[i].move(mousePos[0],mousePos[1])

    #print to screen

    if whiteturn == True:
        ticks +=1
        if ticks%60==0:   #add a ticker variable here, add 1 to it, when it hits 60, decrement t and reset time
            t-=1
            if t == 0:
                gameover = True

    if whiteturn == False:
        tickss +=1
        if tickss%60==0:
            t2-=1
            if t2 == 0:
                gameover = True

    text = font.render(str(t), True, (0,255,0))
    textRect = text.get_rect()
    textRect.center = (900, 0)

    text2 = font.render(str(t2), True, (0,255,0))
    textRect2 = text2.get_rect()
    textRect2.center = (900, 800)

    Name = font.render(str(n1), True, (255,255,255))
    name = Name.get_rect()
    name.center = (900, 100)

    Name2 = font.render(str(n2), True, (255,255,255))
    name2 = Name2.get_rect()
    name2.center = (900, 700)

    for i in range(len(whitelist)):
       for j in range(len(redlist)):
            if whiteturn == False:
                if whitelist[i].row/100 == redlist[j].row/100 and whitelist[i].column/100 == redlist[j].column/100:
                    redlist[j].alive = False
                    print(redlist[j].type, "got killed")
            if whiteturn == True:
                if redlist[j].row/100 == whitelist[i].row/100 and redlist[j].column/100 == whitelist[i].column/100:
                    whitelist[i].alive = False
                    print(whitelist[i].type, "got killed")

    if WhiteKing.alive == False:
        checkmate = True
    if RedKing.alive == False:
        checkmate = True
    # RENDER--------------------------------------------------------------------------------
    screen.fill((0,0,0)) #wipe screen so it doesn't smear
    screen.blit(background, (0,0))

    if TurnNum % 2==0:
        whiteturn=True
        print("white's turn")
    else:
        print("red's turn")
        whiteturn = False
    print("Turn Num:", TurnNum)

    #draws white pieces
    for i in range(len(whitelist)):
            whitelist[i].draw()
    #draws red pieces
    for i in range(len(redlist)):
            redlist[i].draw()

    screen.blit(Name, (900,50))
    screen.blit(Name2, (900,700))
    screen.blit(text, (900, 100))
    screen.blit(text2, (900, 750))
    pygame.display.flip()#this actually puts the pixel on the screen

#end game loop------------------------------------------------------------------------------
pygame.quit()