import os
import pandas as pd
from django.shortcuts import render
from django.http import HttpResponseRedirect

source_dates = pd.read_csv("us-covid-dates.csv")

titles = {
    "ct": {
        "title": "CASE RATE REPORTED BY STATE | TOTAL",
        "subtitle": "TOTAL NUMBER OF CASES | AS OF THE DATE INDICATED"
    },
    "ck": {
        "title": "CASE RATE REPORTED BY STATE WITH NATIONWIDE AVERAGE | PER 100K",
        "subtitle": "NUMBER OF CASES PER 100 000 POPULATION | AS OF THE DATE INDICATED"
    },
    "dt": {
        "title": "DEATH RATE REPORTED BY STATE | TOTAL",
        "subtitle": "TOTAL NUMBER OF DEATHS | AS OF THE DATE INDICATED"
    },
    "dk": {
        "title": "DEATH RATE REPORTED BY STATE WITH NATIONWIDE AVERAGE | PER 100K",
        "subtitle": "NUMBER OF DEATHS PER 100 000 POPULATION | AS OF THE DATE INDICATE"
    }
}

def index(request):

    if request.method == "POST":
        log = open("log.txt", "w")
        log.write(request.POST["day"])
        log.close()
        log_p = open("log_p.txt", "w")
        log_p.write(request.POST["page"])
        log_p.close()
        return HttpResponseRedirect("/")

    log = open("log.txt", "r")
    day = log.read()
    log.close()
    wb = db = nd = nw = "active"
    if int(day) < 8:
        wb = "inactive"
    if int(day) == 1:
        db = "inactive"
    if int(day) == 343:
        nd = "inactive"
    if int(day) > 336:
        nw = "inactive"

    log_p = open("log_p.txt", "r")
    page = log_p.read()
    log_p.close()
    ct = ck = dt = dk = "inactive"
    err = ""
    if page == "ct":
        ct = "active"
    if page == "ck":
        ck = "active"
        err = "NO STATES WITH AT LEAST 1 CASE PER 100 000 POPULATION"
    if page == "dt":
        dt = "active"
        err = "NO STATES WITH REPORTED DEATHS"
    if page == "dk":
        dk = "active"
        err = "NO STATES WITH AT LEAST 1 DEATH PER 100 000 POPULATION"

    code = "0" * (3 - len(str(day))) + str(day)
    date_line = list(source_dates[(source_dates.id == int(day))]["date_line"])[0]

    context = {
        "day": day,
        "date_line": date_line,
        "test": code,
        "chart": {"name": page, "code": code, "title": titles[page]["title"], "subtitle": titles[page]["subtitle"]},
        "buttons": {
            "days": {"back": {"day": db, "week": wb}, "next": {"day": nd, "week": nw}},
            "cases": {"total": ct, "100k": ck}, "deaths": {"total": dt, "100k": dk}
        },
        "file": os.path.exists("polls/static/polls/test/" + page + "_" + code + ".svg"),
        "error": err
    }

    return render(request, "polls/index.html", context)

def about(request):
    return render(request, "polls/about.html")


import base64
import xml.etree.ElementTree as ET

import gimme_aws_creds.common as commondef
from . import errors

class DefaultResolver(object):
    """
       The Aws Client Class performs post request on AWS sign-in page
       to fetch friendly names/alias for account and IAM roles
    """

    def __init__(self, verify_ssl_certs=True):
        return

    def _enumerate_saml_roles(self, assertion, saml_target_url):
        """ using the assertion to fetch aws sign-in page, parse it and return aws sts creds """
        role_pairs = []
        root = ET.fromstring(base64.b64decode(assertion))
        for saml2_attribute in root.iter('{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'):
            if saml2_attribute.get('Name') == 'https://aws.amazon.com/SAML/Attributes/Role':
                for saml2_attribute_value in saml2_attribute.iter('{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue'):
                    role_pairs.append(saml2_attribute_value.text)

        # Normalize pieces of string; order may vary per AWS sample
        result = []
        for role_pair in role_pairs:
            idp, role = None, None
            for field in role_pair.split(','):
                if 'saml-provider' in field:
                    idp = field
                elif 'role' in field:
                    role = field
            if not idp or not role:
                raise errors.GimmeAWSCredsError('Parsing error on {}'.format(role_pair))
            else:
                result.append(commondef.RoleSet(idp=idp, role=role, friendly_account_name="", friendly_role_name=""))

        return result

    def _display_role(self, roles):
        """ gets a list of available roles and
        asks the user to select the role they want to assume
        """
        # Gather the roles available to the user.
        role_strs = []
        for i, role in enumerate(roles):
            if not role:
                continue
            role_strs.append('[{}] {}'.format(i, role.role))

        return role_strs


def collatz(number):
    if number % 2 == 0:
        return number / 2
    elif number % 2 == 1:
        return number * 3 + 1
while True:
    try:
        n = int(input('请输入一个大于零的整数，按enter键确定'))
        if n <= 0:
            print('输入错误，请输入一个大于零的整数，按enter键确定，重新输入')
            continue
        break
    except:
        print('请输入整数')
x = collatz(n)
print(x)
while True:
    if x == 1:
        break
    x = collatz(x)
    print(x)


from src.infra.database.sqlite.views.user.user_view import *
from src.data.protocols.user.authenticate_user_repository import AuthenticateUserRepository as AuthenticateUserRepositoryInterface
from src.data.protocols.user.list_user_account_repository import ListUserAccountRepository as ListUserAccountRepositoryInterface

class ListUserAccountRepo(ListUserAccountRepositoryInterface):

  def get (self, id):
    if (id == 5000):
      user_result = listWithoutId()
    else:
      user_result = list(id)
    print('user_result', user_result)
    if (user_result == None):
      return None
    user_dict = []
    for user in user_result:
      user_dict.append(
        {
          "id": user[0],
          "username": user[1],
          "name": user[3]
        }
      )
    return user_dict


# -*- coding: utf-8 -*-
"""
Trains and tests a Rolling Bayesian Ridge Regression model on data

@author: Nick
"""

import warnings
import numpy as np
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.feature_selection import VarianceThreshold
from sklearn.preprocessing import MinMaxScaler
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score

# load dataset
Y = pd.read_csv('Y elect.csv').iloc[:,[0]]
X = pd.read_csv('X elect.csv')

# size the training and forecasting data sets
train_size = 16 # years
test_size = 1 # years

# define the initial train and test sets
train_idx = np.arange(train_size)
test_idx = np.arange(train_size, train_size + test_size)

# train the model on all the training data
pipeline = Pipeline([
    ('var', VarianceThreshold()),
    ('scale', MinMaxScaler()),
    ('model', GaussianNB()),
])
pipeline.fit(X.iloc[train_idx, :], Y.iloc[train_idx, :])

# produce a rolling forecast on all the testing data
predictions = pd.DataFrame()
actual = pd.DataFrame()
for i in range(X.shape[0] - train_size - test_size):
    # forecast
    pred = pd.DataFrame(pipeline.predict(X.iloc[test_idx, :])).T
    pred.columns = ["t" + str(i + 1) for i in range(pred.shape[1])]
    predictions = pd.concat([predictions, pred], axis=0).reset_index(drop=True)

    # actual
    true = Y.iloc[test_idx, :].copy().T
    true.columns = ["t" + str(i + 1) for i in range(true.shape[1])]
    actual = pd.concat([actual, true], axis=0).reset_index(drop=True)

    # roll forecast forward
    train_idx = train_idx + 1
    test_idx = test_idx + 1

    # train a new model
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        pipeline.fit(X.iloc[train_idx, :], Y.iloc[train_idx, :])

    # report forecast
    y_pred = pred["t1"]
    y_true = Y.iloc[train_idx[-1],:][0]
    print('predicted=%f, expected=%f' % (y_pred, y_true))

# compute r2 for the predictions
acc = []
for j in predictions.columns:
    acc.append(accuracy_score(actual[j], predictions[j]))
acc


from tests import unittest

from awscli.customizations.s3.utils import find_bucket_key, find_chunksize
from awscli.customizations.s3.constants import MAX_SINGLE_UPLOAD_SIZE

class FindBucketKey(unittest.TestCase):
    """
    This test ensures the find_bucket_key function works when
    unicode is used.
    """
    def test_unicode(self):
        s3_path = '\u1234' + u'/' + '\u5678'
        bucket, key = find_bucket_key(s3_path)
        self.assertEqual(bucket, '\u1234')
        self.assertEqual(key, '\u5678')

class FindChunksizeTest(unittest.TestCase):
    """
    This test ensures that the ``find_chunksize`` function works
    as expected.
    """
    def test_small_chunk(self):
        """
        This test ensures if the ``chunksize`` is appropriate to begin with,
        it does not change.
        """
        chunksize = 7 * (1024 ** 2)
        size = 8 * (1024 ** 2)
        self.assertEqual(find_chunksize(size, chunksize), chunksize)

    def test_large_chunk(self):
        """
        This test ensures if the ``chunksize`` adapts to an appropriate
        size because the original ``chunksize`` is too small.
        """
        chunksize = 7 * (1024 ** 2)
        size = 8 * (1024 ** 3)
        self.assertEqual(find_chunksize(size, chunksize), chunksize * 2)

    def test_super_chunk(self):
        """
        This tests to ensure that the ``chunksize can never be larger than
        the ``MAX_SINGLE_UPLOAD_SIZE``
        """
        chunksize = MAX_SINGLE_UPLOAD_SIZE + 1
        size = MAX_SINGLE_UPLOAD_SIZE * 2
        self.assertEqual(find_chunksize(size, chunksize),
                         MAX_SINGLE_UPLOAD_SIZE)

if __name__ == "__main__":
    unittest.main()


import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import QThread
import pyqtgraph as pg
import numpy as np

from MainWindow import Ui_MainWindow
#from GraphClass import MultiLine # Supposed to improve perforamnce, but with latest pyqtgraph updates maybe not needed anymore
from WorkerClass import AcquireData
from ParamsClass import SampleParams,DLTSParams,TempParams,LakeshoreParams,MFIAParams

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, *args, obj=None, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)
        self.first_plot = True
        self.curves = []

        ## CREATE PARAM STRUCTS
        self.sample = SampleParams()
        self.dlts = DLTSParams()
        self.temp = TempParams()
        self.lake = LakeshoreParams()
        self.mfia = MFIAParams()

        ## CREATE PRIMARY WORKER THREAD
        self.data = AcquireData()
        self.thread = QThread()
        self.data.moveToThread(self.thread)
        self.data.finished.connect(self.thread.quit)
        self.thread.started.connect(self.data.do_scan)

        ## MAIN SIGNAL->SLOTS
        # Machine States
        self.buttonInit.clicked.connect(self.initialize_hardware)
        self.buttonStart.clicked.connect(self.commence_scan)
        self.buttonStop.clicked.connect(self.stopping_scan)
        self.buttonIdle.clicked.connect(self.goto_idle)
        self.data.init_fail.connect(self.scan_complete)
        self.data.init_fail.connect(self.state_stopped)
        self.data.lakeshore.lakeshore_disconnect.connect(self.stopping_scan)
        self.data.lakeshore.lakeshore_disconnect.connect(self.state_stopwait)
        self.data.graph_update.connect(self.graph_data)
        self.data.finished.connect(self.scan_complete)
        self.data.finished.connect(self.state_stopped)

        # Worker LogObjects may print to log
        self.data.log_signal.connect(self.generate_log)
        self.data.lakeshore.log_signal.connect(self.generate_log)
        self.data.device.log_signal.connect(self.generate_log)
        self.data.file.log_signal.connect(self.generate_log)

    def initialize_hardware(self):
        ## POPULATE PARAMS STRUCTS FROM UI
        self.generate_log("All settings now locked in. You must re-initialize to make changes.")
        # Set sample info
        self.sample.user = self.sampleUser.text()
        self.sample.name = self.sampleName.text()
        self.sample.material = self.sampleMat.text()
        self.sample.area = self.sampleArea.value()
        self.sample.comment = self.sampleComment.text()

        # Set DLTS experiment parameters
        self.dlts.ss_bias = self.dltsBias.value()
        self.dlts.pulse_height = self.dltsPulse.value()
        self.dlts.trns_length = self.dltsTWidth.value()
        self.dlts.pulse_width = self.dltsPWidth.value()
        self.dlts.sample_time = self.dltsSample.value()

        # Set temperature parameters
        self.temp.temp_init = self.tempStart.value()
        self.temp.temp_step = self.tempStep.value()
        self.temp.temp_final = self.tempEnd.value()
        self.temp.temp_idle = self.tempIdle.value()
        self.temp.temp_stability = self.tempStable.value()
        self.temp.time_stability = self.timeStable.value()

        # Set Lakeshore parameters
        if self.radioSampleA.isChecked() == True:
            self.lake.sample = 'A'
        elif self.radioSampleB.isChecked() == True:
            self.lake.sample = 'B'
        if self.radioControlA.isChecked() == True:
            self.lake.control = 'A'
        elif self.radioControlB.isChecked() == True:
            self.lake.control = 'B'
        if self.radioHeaterLow.isChecked() == True:
            self.lake.heatpower = '1'
        elif self.radioHeaterMed.isChecked() == True:
            self.lake.heatpower = '2'
        elif self.radioHeaterHi.isChecked() == True:
            self.lake.heatpower = '3'

        # Set MFIA Parameters
        self.mfia.sample_rate = self.mfiaSample.value()
        self.mfia.ac_freq = self.mfiaFreq.value()
        self.mfia.ac_ampl = self.mfiaAmp.value()
        self.mfia.time_constant = self.mfiaTC.value()
        self.mfia.i_range = float(self.mfiaRange.currentText())*0.001 # conversion from mA to A
        self.mfia.sample_reject = self.mfiaReject.value()

        ## INITIALIZE WORKER
        self.data.reset(self.sample,self.dlts,self.temp,self.lake,self.mfia)

    def graph_data(self):
        #nPlots = 100
        nPlots = self.data.cap_data.shape[1]
        #nSamples = 16000
        nSamples = self.data.cap_data.shape[0]
        #y = np.random.normal(size=(120,20000), scale=0.2) + np.arange(120)[:,np.newaxis]
        #x = np.empty((120,20000))
        #x[:] = np.arange(20000)[np.newaxis,:]
        now = pg.ptime.time()
        if self.first_plot:
            #data = np.random.normal(size=(nPlots,nSamples))
            self.graphWidget.disableAutoRange()
            self.graphWidget.setYRange(np.nanmin(self.data.cap_data), np.nanmax(self.data.cap_data))
            self.graphWidget.setXRange(0, nSamples)

            for idx in range(nPlots):
                curve = pg.PlotCurveItem(pen=(170-idx,nPlots*4))  #7->17 out of 40
                self.graphWidget.addItem(curve)
                self.curves.append(curve)
                #lines = MultiLine(x,y)
                self.curves[idx].setData(self.data.cap_data[:,idx])
            curve = pg.PlotCurveItem(pen='r')
            self.graphWidget.addItem(curve)
            self.curves.append(curve)
            self.curves[nPlots].setData(self.data.file.transient)
            #lines = MultiLine(x,y)
            #self.graphWidget.addItem(lines)

            self.first_plot = False
        else:
            #data = np.random.normal(size=(nPlots,nSamples))
            print('hi')
            self.graphWidget.setYRange(np.nanmin(self.data.cap_data), np.nanmax(self.data.cap_data))
            self.graphWidget.setXRange(0, nSamples)
            for idx in range(nPlots):
                self.curves[idx].setData(self.data.cap_data[:,idx])
            self.curves[nPlots].setData(self.data.file.transient)
        print("Plot time: %0.2f sec" % (pg.ptime.time()-now))
        app.processEvents()

    def commence_scan(self):
        self.thread.start()

    def stopping_scan(self):
        self.generate_log("Stop signal sent. Please wait...","orange")
        self.data.lakeshore.stopped = True

    def scan_complete(self):
        self.first_plot = True
        self.curves = []
        self.generate_log("All done.","green")

    def goto_idle(self):
        self.generate_log("Setpoint set to idle temperature, {:3.2f} K.".format(self.tempIdle.value()),"blue")
        self.data.lakeshore.sampleSetPoint(self.tempIdle.value())

app = QtWidgets.QApplication(sys.argv)

window = MainWindow()
window.show()
app.exec()


# Time Complexity:O(n) for linear or sequential search as it traverse through all elements
def linear_search(list, item):
    for x in range(len(list)):
        if list[x] == item:
            return x
    return None

def main():
    my_array = [1, 2, 3, 4, 5, 6, 7, 10, 45, 869, 32, 44, 22, 55]
    print(linear_search(my_array, 45))
    print(linear_search(my_array, -1))

if __name__ == "__main__":
    main()


import math

from src.VAR import Var
from src.VAR_distance import Var_distance
from scipy.spatial import distance

class Grangercalculator_distance:

    def __init__(self, df, lag):
        self.df = df
        self.lag = lag

    def GC_calculator(self, bi_pairs, W, tau):
        distances = []
        tau_exp = math.exp(tau)
        for pair in bi_pairs:
            formula = []
            second_value = []
            for j in range(len(pair)):
                data = self.df[list(pair[j])].copy(deep=True)
                VAR = Var_distance(data, self.lag)

                params, l2norm = VAR.var_calculation(list(pair[j]))

                # Calculates the value of the past values of the second stock * it's coefficient value in the formula.
                second = data[data.columns[0]].to_numpy()
                second_converted = []
                for i in range(len(second)-1):
                    answer = params[1] * second[i]
                    second_converted.append(answer)

                second_value.append(second_converted)
                formula.append(l2norm)
                # Calculates the variance of the residuals univariate model of Z.
                if j == 0:
                    data_uni = self.df[pair[j][1]].copy(deep=True)
                    VAR_uni = Var(data_uni, self.lag)
                    variance_uni = VAR_uni.var_univariate()
            xy = distance.euclidean(second_value[1], second_value[2])
            lower_bound = (abs(abs(abs(xy - formula[1]) - formula[2])-formula[2]))
            Upperbound = (formula[1] + xy + 2*formula[2])
            # calculates the value for which formula[0]**2/W must be smaller so that GC holds
            GC_Threshold = (variance_uni/tau_exp)
            distances.append([[tau, W, lower_bound, formula[0], Upperbound,  formula[0]**2/W, GC_Threshold], pair])
        return distances


# services/tienda/project/api/tienda.py

from flask import Blueprint, jsonify, request, render_template

from project.api.models import Tienda
from project import db

from sqlalchemy import exc

tienda_blueprint = Blueprint('tienda', __name__, template_folder='./templates')

@tienda_blueprint.route('/tienda/ping', methods=['GET'])
def ping_pong():
    return jsonify({
        'estado': 'satisfactorio',
        'mensaje': 'Conectado exitosamente!'
    })

@tienda_blueprint.route('/tienda', methods=['POST'])
def add_tienda():
    post_data = request.get_json()
    response_object = {
        'estado': 'falló',
        'mensaje': 'Datos no validos.'
    }
    if not post_data:
        return jsonify(response_object), 400
    nombre = post_data.get('nombre')
    sucursal = post_data.get('sucursal')
    direccion = post_data.get('direccion')
    telefono = post_data.get('telefono')
    encargado = post_data.get('encargado')
    try:
        tienda = Tienda.query.filter_by(encargado=encargado).first()
        if not tienda:
            db.session.add(Tienda(nombre=nombre, sucursal=sucursal, direccion=direccion, telefono=telefono, encargado=encargado))
            db.session.commit()
            response_object['estado'] = 'satisfactorio'
            response_object['mensaje'] = f'{nombre} fue agregado!!!'
            return jsonify(response_object), 201
        else:
            response_object['mensaje'] = 'Lo siento, ese nombre ya existe.'
            return jsonify(response_object), 400
    except exc.IntegrityError as e:
        db.session.rollback()
        return jsonify(response_object), 400

@tienda_blueprint.route('/tienda/<tienda_id>', methods=['GET'])
def get_single_user(tienda_id):
    """Obteniendo detalles de un unico usuario"""
    response_object = {
        'estado': 'falló',
        'mensaje': 'La Tienda no existe'
    }

    try:
        tienda = Tienda.query.filter_by(id=int(tienda_id)).first()
        if not tienda:
            return jsonify(response_object), 404
        else:
            response_object = {
                'estado': 'satisfactorio',
                'data': {
                    'id': tienda.id,
                    'nombre': tienda.nombre,
                    'sucursal': tienda.sucursal,
                    'direccion': tienda.direccion,
                    'telefono': tienda.telefono,
                    'encargado': tienda.encargado,
                    'active': tienda.active
                }
            }
            return jsonify(response_object), 200
    except ValueError:
        return jsonify(response_object), 404

@tienda_blueprint.route('/tienda', methods=['GET'])
def get_all_tienda():
    """Get all tienda"""
    response_object = {
        'estado': 'satisfactorio',
        'data': {
            'tienda': [tienda.to_json() for tienda in Tienda.query.all()]
        }
    }
    return jsonify(response_object), 200

@tienda_blueprint.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        nombre = request.form['nombre']
        sucursal = request.form['sucursal']
        direccion = request.form['direccion']
        telefono = request.form['telefono']
        encargado = request.form['encargado']
        db.session.add(Tienda(nombre=nombre, sucursal=sucursal, direccion=direccion, telefono=telefono, encargado=encargado))
        db.session.commit()
    tienda = Tienda.query.all()
    return render_template('index.html', tienda=tienda)


def findPeakElement(nums):

    if nums[0]>nums[1]:
        return 0

    if nums[-1]>nums[-2]:
        return len(nums)-1

    left = 1
    right = len(nums)-2

    while left<=right:
        mid = (left+ right)//2

        if nums[mid]>nums[mid-1] and nums[mid]>nums[mid+1]:
            return mid

        elif nums[mid-1]>nums[mid]:
            right = mid - 1

        else:
            left =  mid + 1

if __name__ == "__main__":
    print(findPeakElement([1,2,1,3,5,6,4]))


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

# In[7]:

# Miles to kilometer
# 1mile = 1.6km

mls=float(input("Enter miles"))
km= 1.6*mls
print(mls ,"miles is" ,km,"km" )

# In[15]:

# checking leap year
# Number should be completely divided by 4, centuries should be completely divided by 4

year = int(input("Enter a year: "))
if year % 4 == 0:
    if year % 100 == 0:
        if (year % 400) == 0:
            print(year,"is a leap year")
        else:
            print(year,"is not a leap year")
    else:
        print(year,"is a leap year")
else:
    print(year,"is not a leap year")

# In[19]:

#Prime Number. Number should have only 1 factor

number = int(input("Enter a numberber: "))

if number > 1:
    for x in range(2,number):
        if (number % x) == 0:
            print(number,"is not a prime numberber")
            break
    else:
        print(number,"is a prime numberber")
else:
    print(number,"is not a prime numberber")


# 필요한 숫자들의 개수의 최댓값이 필요한 세트의 개수이다.
# 6과 9는 대체될 수 있으므로, 나올때마다 0.5씩 한 쪽에만 더해주면 된다.

from math import ceil

n = input()
cntOfNeededNums = {"0": 0, "1": 0, "2": 0, "3": 0, "4": 0, "5": 0, "6": 0, "7": 0, "8": 0}
pair = ("6", "9")
for num in n:
    if num in pair:
        cntOfNeededNums["6"] += 0.5
    else:
        cntOfNeededNums[num] += 1
print(ceil(max(cntOfNeededNums.values())))


from typing import Optional

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if not root:
            return TreeNode(val)
        node = root
        while node:
            if val > node.val:
                prev = node
                node = node.right
            elif val < node.val:
                prev = node
                node = node.left

        if val > prev.val:
            prev.right = TreeNode(val)
        if val < prev.val:
            prev.left = TreeNode(val)

        return root

class Solution:
    def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if not root:
            return TreeNode(val)

        if val > root.val:
            root.right = self.insertIntoBST(root.right, val)
        elif val < root.val:
            root.left = self.insertIntoBST(root.left, val)

        return root


import re

from graia.ariadne import Ariadne
from graia.ariadne.event.message import (
    GroupMessage,
    FriendMessage,
    MessageEvent,
)
from graia.ariadne.message.chain import MessageChain
from graia.ariadne.message.parser.twilight import (
    Twilight,
    UnionMatch,
    FullMatch,
    RegexResult,
    WildcardMatch,
)
from graia.saya import Saya, Channel
from graia.saya.builtins.broadcast.schema import ListenerSchema

from library.depend import Switch, FunctionCall

from graia.ariadne.message.parser.twilight import SpacePolicy
import binascii

channel = Channel.current()

@channel.use(
    ListenerSchema(
        [GroupMessage, FriendMessage],
        inline_dispatchers=[
            Twilight(
                [
                    FullMatch("转"),
                    UnionMatch("文本", "16").space(SpacePolicy.FORCE) @ "type",
                    WildcardMatch().flags(re.S) @ "data",
                ]
            )
        ],
        decorators=[Switch.check(channel.module), FunctionCall.record(channel.module)],
    )
)
async def Hex_text(
    app: Ariadne, event: MessageEvent, type: RegexResult, data: RegexResult
):
    if type.result.display == "文本":
        text = binascii.unhexlify(data.result.display).decode("gbk")
    else:
        text = binascii.b2a_hex(data.result.display.encode("gbk")).decode()
    await app.send_message(
        event.sender.group if isinstance(event, GroupMessage) else event.sender,
        MessageChain(f"{text}"),
    )


"""
15. 3Sum
Medium

4048

463

Favorite

Share
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
"""

"""
Runtime: 856 ms, faster than 72.46% of Python3 online submissions for 3Sum.
Memory Usage: 16.7 MB, less than 78.18% of Python3 online submissions for 3Sum.
"""

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        def twoSum(nums, target):
            left, right = 0, len(nums) - 1
            res = []
            while left < right:
                if nums[left] + nums[right] == target:
                    res.append([nums[left], nums[right]])
                    if left + 1 < right and nums[left + 1] == nums[left]:
                        while left + 1 < right and nums[left + 1] == nums[left]:
                            left += 1
                            res.append([nums[left], nums[right]])
                    right -= 1
                elif nums[left] + nums[right] > target:
                    right -= 1
                else:
                    left+= 1
            return res

        nums = sorted(nums)
        res = []
        for i in range(len(nums)):
            if nums[i] > 0:
                break
            if i > 0 and nums[i] == nums[i-1]:
                continue
            two_sum = twoSum(nums[i + 1 :], -nums[i])
            #print(two_sum)
            if len(two_sum) > 0:
                for t in two_sum:
                    res.append((nums[i],t[0],t[1]))
        #print(res)
        return [ele for ele in (set(res))]


#!/usr/bin/env python
# coding: utf-8
# import
import os
import numpy as np
import tensorflow as tf
from models import simple_CNN
from keras.callbacks import EarlyStopping, ModelCheckpoint, CSVLogger, TensorBoard
import matplotlib.pyplot as plt

init = tf.global_variables_initializer()

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.Session(config=config)
session.run(init)
model_save_path = 'trained_models/simpler_CNN.{epoch:02d}-{val_acc:.2f}.hdf5'
train_x = np.load('train_x.npy')
train_y = np.load('train_y.npy')

image_size = train_x.shape[1:]
print(image_size)
num_classes = 2
batch_size = 64
num_epochs = 10

model = simple_CNN(image_size, num_classes)
#model.load_weights('trained_models/simpler_CNN.22-0.67.hdf5')

# 编译模型，categorical_crossentropy多分类选用
model.compile(optimizer='Adam', loss='categorical_crossentropy', metrics=['accuracy'])

# 记录日志(Record Log)
csv_logger = CSVLogger('training.log')

# 保存检查点(Save checkpoint)
model_checkpoint = ModelCheckpoint(model_save_path,
                                   monitor='val_acc',
                                   verbose=1,
                                   save_best_only=True)

model_callbacks = [model_checkpoint, csv_logger]

# 训练模型(Training Model)
history = model.fit(train_x, train_y, batch_size, num_epochs,
                    verbose=1,
                    callbacks=model_callbacks,
                    validation_split=.2,
                    shuffle=True)

# 绘制训练的准确率值(Plotting the accuracy of training)
plt.figure(1)
plt.plot(history.history['acc'])#acc最新版keras已经无法使用
plt.title('Model accuracy')#图名
plt.ylabel('Accuracy')#纵坐标名
plt.xlabel('Epoch')#横坐标名
plt.legend(['Train'], loc='upper left')#角标及其位置

# 绘制训练的损失值(Plotting the loss value of training)
plt.figure(2)
plt.plot(history.history['loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train'], loc='upper left')
plt.show()


import random

def roll_dice():
    numbers = ''
    for i in range(1, 7):
        numbers += str(i)
    selected_num = (random.choice(numbers))
    print(f'Your dice is rolling! You got: {selected_num}')

roll_dice()


# Clean the experiment directory so you can start fresh.

import sys
sys.path.insert(0,'./')
import shutil
import os
import subprocess

from set_parameters import Options
from coupling_utils import copy_ua_restart

# Function to clean the given Ua executable directory
def clean_ua (directory):
    restart_name = None
    # Look at everything in the Ua executable directory
    for fname in os.listdir(directory):
        if fname.endswith('RestartFile.mat'):
            # Save the name of the restart file
            restart_name = fname
        # Don't care about mesh files
        elif fname in ['NewMeshFile.mat', 'AdaptMesh.mat']:
            pass
        # Don't delete the Ua executable, run script, options file, or other .mat files
        elif fname in ['Ua', 'Ua_MCR.sh', 'options_for_ua'] or fname.endswith('.mat'):
            continue
        # Delete everything else
        path = directory+fname
        if os.path.isfile(path):
            os.remove(path)
        elif os.path.isdir(path):
            shutil.rmtree(path)
    if restart_name is not None:
        # Copy in the original restart with the correct name
        copy_ua_restart(directory, restart_name)

# Main processing
if __name__ == "__main__":

    # Make sure the user didn't call this accidentally
    out = raw_input('This will delete all existing results if they are not backed up. Are you sure you want to proceed (yes/no)? ').strip()
    while True:
        if out == 'yes':
            break
        if out == 'no':
            sys.exit()
        out = raw_input('Please answer yes or no. ').strip()

    # Read simulation options so we have directories
    options = Options()

    # Remove everything in the output directory
    # Easiest just to delete the whole directory and then create it again
    shutil.rmtree(options.output_dir)
    os.mkdir(options.output_dir)

    # Clean Ua executable directory
    clean_ua(options.ua_exe_dir)

    # Now call the prepare_run.sh script to reset the MITgcm run directory
    # Pass the path to scripts/ as an argument, because prepare_run.sh is called from outside its own directory
    subprocess.check_output([options.mit_case_dir+'scripts/prepare_run.sh', options.mit_case_dir+'scripts/'])

    # Delete some log files if they exist
    for fname in os.listdir('./'):
        if fname in ['coupler_stdout', 'jobs.log'] or (fname.startswith('run_') and '.sh.o' in fname) or fname.startswith(options.expt_name+'o.o') or fname.startswith(options.expt_name+'i.o'):
            os.remove(fname)


import logging
import time

import dataset
import discord
from discord import Member
from discord.ext import commands

from cogs.commands import settings
from utils import database, embeds

# Enabling logs
log = logging.getLogger(__name__)

class MutesHandler(commands.Cog):
    """Handles actions such as mute evasion."""

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

    @commands.Cog.listener()
    async def on_member_remove(self, member: Member) -> None:
        # Open a connection to the database.
        db = dataset.connect(database.get_db())

        guild = member.guild
        mute_channel = discord.utils.get(guild.channels, name=f"mute-{member.id}")

        if mute_channel:
            mod_channel = guild.get_channel(settings.get_value("channel_moderation"))
            user = await self.bot.fetch_user(member.id)

            # Add an unmute entry in the database to prevent archive_mute_channel()'s unmuter throwing NoneType() exception.
            mute_entry = db["mod_logs"].find_one(user_id=member.id, type="mute")
            # Add an "unmute" entry into the database.
            if mute_entry:
                db["mod_logs"].insert(dict(
                    user_id=user.id,
                    mod_id=self.bot.user.id,
                    timestamp=int(time.time()),
                    reason="Mute evasion.",
                    type="unmute"
                ))

            # Update the mute entry in the timed_mod_actions database to prevent issues with task looping.
            tempmute_entry = db["timed_mod_actions"].find_one(user_id=member.id, is_done=False, action_type="mute")
            if tempmute_entry:
                db["timed_mod_actions"].update(dict(id=tempmute_entry["id"], is_done=True), ["id"])

            # Archive the mute channel
            mutes = self.bot.get_cog("MuteCog")
            await mutes.archive_mute_channel(
                ctx=None,
                user_id=user.id,
                reason="Mute channel archived after member banned due to mute evasion.",
                guild=guild,
            )

            # Add the ban to the mod_log database.
            db["mod_logs"].insert(dict(
                user_id=user.id,
                mod_id=self.bot.user.id,
                timestamp=int(time.time()),
                reason="Mute evasion.",
                type="ban"
            ))

            # Ban the user.
            await guild.ban(user, reason="Mute evasion.")

            # Creating the embed used to alert the moderators that the mute evading member was banned.
            embed = embeds.make_embed(
                ctx=None,
                title=f"Member {user.name}#{user.discriminator} banned",
                description=f"User {user.mention} was banned indefinitely because they evaded their timed mute by leaving.",
                thumbnail_url="https://i.imgur.com/l0jyxkz.png",
                color="soft_red"
            )
            await mod_channel.send(embed=embed)

        # Commit the changes to the database and close the connection.
        db.commit()
        db.close()

def setup(bot) -> None:
    """Load the cog."""
    bot.add_cog(MutesHandler(bot))
    log.info("Listener Loaded: mutes")


'''
通过解析xml文件，批量修改xml文件里的标签名称，比如把标签zero改成num
'''
import os.path
import glob
import xml.etree.ElementTree as ET

path = r'数据集\Annotations'    #存储标签的路径，修改为自己的Annotations标签路径
sum3 = 0
for xml_file in glob.glob(path + '/*.xml'):
    ####### 返回解析树
	tree = ET.parse(xml_file)
	##########获取根节点
	root = tree.getroot()
	#######对所有目标进行解析
	# *******************************这个用来批量改打标文件名称
	# for member in root.findall('object'):
	# 	objectname = member.find('name').text
	# 	if objectname == 'uncovered':      #原来的标签名字
	# 		print(objectname)
	# 		member.find('name').text = str('cover')    #替换的标签名字
	# 		tree.write(xml_file)
	# ****************************************************************
	# ********************************这个用来统计xml文件夹中某个标签的数量
	sum2 = 0
	for member in root.findall('object'):
		objectname = member.find('name').text
		sum = 0
		if objectname == 'playPhone':
			sum+=1
		sum2 = sum2+sum
	sum3 = sum2+sum3
print(objectname,'=',sum3)
# ****************************************************************************


"""
Created on Tue Oct 23 03:00:14 2018

@author: Rahul
"""

import numpy as np
import pandas as pd
import math
import random
import datetime
from logging import info
from .constant import STOCK_LIST

WILLIAM_K_UL = -80
WILLIAM_K_LL = -20
A = [
{'sector' : 'Mining', 'stock' : 'ABIRLANUVO'},
{'sector' : 'Computers', 'stock' : 'MTNL'},
{'sector' : 'Diversified', 'stock' : 'MCDOWELL-N'},
{'sector' : '', 'stock' : 'BANKNIFTY'},]

class StockScreener(object):

    def __init__(self):
        self.stocks = pd.DataFrame()

    def generate_results(self):
        i = 1
        result = list()
        for stock in STOCK_LIST:
            info('stock - {0}'.format(stock['stock']))
            print(str(i) + " - " + stock['stock'])
            i = i+1

            data = StockDetails(stock['stock']).getInfo()
            data['Sector'] = stock['sector']
            result.append(data)

        self.stocks = pd.DataFrame(result)
        return self.stocks

    def get_buyers(self):

        if self.stocks.empty: self.generate_results()
        return self.stocks[self.stocks['Buy'] == True]

    def get_sellers(self):

        if self.stocks.empty: self.generate_results()
        return self.stocks[self.stocks['Sell'] == True]

    def save_results(self, path = None):
        df = self.generate_results()
        if path is None:
            path = "F://Personal Work//Stock Data//Python Code Williams R//williamR_" + datetime.datetime.today().strftime("%Y%m%d") + "_" + str(random.randint(1,1000)) + ".csv"
        self.save_to_csv(df, path)

    def save_to_csv(self, df, path):
        df.to_csv(path)

class StockDetails(object):

    def __init__(self, stock_name, cob = None):
        self.stock_name         = stock_name
        self.historical_prices  = self.get_historical_prices(end_date = cob)
        self.stock_info         = dict()

    def getInfo(self):

        self.stock_info['Stock'] = self.stock_name

        # Volume Data
        self.stock_info.update(self.get_avg_vol())
        self.stock_info.update(self.get_last_cob_details())

        # William R Details
        self.stock_info.update(self.get_williams_ratio_details(self.stock_info['Average Volume']))

        # Moving Averages
        self.stock_info.update(self.calculate_moving_avgs())

        # 52W stats
        self.stock_info.update(self.get_52w_stat())

        # Add Buy/Sell Suggestion
        self.stock_info.update(self.buy_sell_suggestion())

        # Calculate MACD
        self.stock_info.update(self.calculate_macd())
        b = self.historical_prices

        return self.stock_info

    @property
    def stock_name(self):
        return self._stock_name

    @stock_name.setter
    def stock_name(self, stock_name):
        self._stock_name = stock_name

    def get_historical_prices(self, end_date = None):
        return getHistoricStockPrices(self.stock_name, end_date = end_date)

    def get_lookback_period(self, avg_vol, std_dev):
        return int(round(math.log(avg_vol, std_dev),0)*2)

    def get_avg_vol(self):
        try:
            avg_vol = round(np.mean(self.historical_prices['Volume']),2)
            avg_vol = 0 if np.isnan(avg_vol) else avg_vol
            return {'Average Volume' : avg_vol}
        except:
            return {'Average Volume' : 0}

    def get_last_cob_details( self ):
        try:
            last_row = self.historical_prices.tail(1)
            return {'Last Close' : round(last_row['Close'][0],2),
                    'Last COB' : last_row.reset_index()['Date'][0].strftime("%d%b%y")}
        except:
            return {'Last Close' : 0,
                    'Last COB' : datetime.datetime.today().strftime("%d%b%y")}

    def get_williams_ratio_details( self, avg_vol):

        smoothing_period = 5

        info = {'Standard Deviation': 0,
                    'Lookback Period'   : 14,
                    'Smoothing Period'  : smoothing_period,
                    '%R'                : 0,
                    '%D'                : 0,
                    'WILLIAM BUY/SELL'  : ''}

        try:
            std_dev                     = round(self.get_std_dev(),3)
            info['Standard Deviation']  = std_dev
            lookback_period             = max(self.get_lookback_period(avg_vol, std_dev),14)
            info['Lookback Period']     = lookback_period
            info['%R'], info['%D'], info['WILLIAM BUY/SELL']   = self.calculate_williams_ratio(lookback_period, smoothing_period)

        except:
            pass

        finally:
            return info

    def get_std_dev(self):
        df = self.historical_prices[['High', 'Low']]
        df['SD'] = df.apply(lambda row: (row['High'] - row['Low'])**2, axis = 1)
        return np.mean(df['SD'])**.5

    def calculate_williams_ratio(self, lookback_period, smoothing_period):

        # Append Highest High
        self.historical_prices['HH'] = self.historical_prices[['High']].rolling(window = lookback_period).max()

        # Append Lowest lows
        self.historical_prices['LL'] = self.historical_prices[['Low']].rolling(window = lookback_period).min()

        # Calculate %K
        self.historical_prices['%R'] = self.historical_prices.apply(lambda row: (row['Close'] - row['HH']) * 100 / (row['HH'] - row['LL']) if row['HH'] != 0 else 0, axis = 1)

        # Calculate %D
        self.historical_prices['%D'] = self.historical_prices['%R'].rolling(window = smoothing_period).mean()

        # Calculate Buy/Sell using Williams R
        self.historical_prices['WILLIAM BUY/SELL'] = self.historical_prices.apply(lambda row: 'BUY' if row['%D'] < WILLIAM_K_UL and row['%D'] < row['%R'] else 'SELL' if row['%D'] > WILLIAM_K_UL and row['%D'] > row['%R'] else '', axis = 1)

        last_row = self.historical_prices.tail(1)

        return round(last_row['%R'][0],2), round(last_row['%D'][0],2), last_row['WILLIAM BUY/SELL'][0]

    def calculate_moving_avgs(self):

        info = {'30D MA' : 0,
                '60D MA' : 0,
                '200D MA': 0}
        try:
            self.historical_prices['30D_MA'] = self.historical_prices['Close'].rolling(window=30).mean()
            info['30D MA'] = round(self.historical_prices.tail(1)['30D_MA'][0],2)

            self.historical_prices['60D_MA'] = self.historical_prices['Close'].rolling(window=60).mean()
            info['60D MA'] = round(self.historical_prices.tail(1)['60D_MA'][0],2)

            self.historical_prices['200D_MA'] = self.historical_prices['Close'].rolling(window=200).mean()
            info['200D MA'] = round(self.historical_prices.tail(1)['200D_MA'][0],2)

        except:
            pass
        finally:
            return info

    def calculate_macd( self ):
        ''' function to calculate MACD and Signal Line '''

        info = {'MACD'                                  : 0,
                'MACD Signal'                           : 0,
                'MACD To Signal Diff (Value)'           : 0,
                'MACD To Signal Diff (Days)'            : 0,
                'MACD Signal Diff Rolling Peak'         : 0,
                'MACD Signal Diff % to Rolling Peak'    : 0,
                'MACD BUY/SELL'                         : ''
                }
        try:
            self.historical_prices['26D_EMA'] = self.historical_prices[['Close']].apply(ema, args = (26,))
            self.historical_prices['12D_EMA'] = self.historical_prices[['Close']].apply(ema, args = (12,))

            self.historical_prices['MACD'] = self.historical_prices.apply(lambda row: row['12D_EMA'] - row['26D_EMA'], axis = 1)

            self.historical_prices['MACD Signal'] = self.historical_prices['MACD'].rolling(window=9).mean()
            self.historical_prices['MACD To Signal Diff (Value)'] = self.historical_prices.apply(lambda row: row['MACD'] - row['MACD Signal'], axis = 1)
            self.historical_prices['MACD Signal Diff Rolling Peak'] = self.historical_prices[['MACD To Signal Diff (Value)']].apply(abs)
            self.historical_prices['MACD Signal Diff Rolling Peak'] = self.historical_prices['MACD Signal Diff Rolling Peak'].rolling(window=9).max()
            self.historical_prices['MACD Signal Diff % to Rolling Peak'] = self.historical_prices.apply(lambda row: round(row['MACD To Signal Diff (Value)']*100/row['MACD Signal Diff Rolling Peak'], 2), axis = 1)

            self.historical_prices['MACD BUY/SELL'] = self.historical_prices['MACD Signal Diff % to Rolling Peak'].shift(1)
            self.historical_prices['MACD BUY/SELL'] = self.historical_prices[['MACD BUY/SELL', 'MACD Signal Diff % to Rolling Peak']].apply(lambda row: 'BUY' if row['MACD BUY/SELL'] == -100 and row['MACD Signal Diff % to Rolling Peak'] not in (100,-100) else 'SELL' if row['MACD BUY/SELL'] == 100 and row['MACD Signal Diff % to Rolling Peak'] not in (100,-100) else '', axis = 1)
            #self.historical_prices['MACD BUY/SELL'] = self.historical_prices[['MACD Signal Diff % to Rolling Peak']].apply(lambda col: 'BUY' if col.shift(1) == -100 and col not in (100,-100) else 'SELL' if col.shift(1) == 100 and col not in (100,-100) else '')

            self.historical_prices['MACD To Signal Diff (Days)'] = self.historical_prices.apply(lambda row: 1 if row['MACD To Signal Diff (Value)'] > 0 else -1 if row['MACD To Signal Diff (Value)'] < 0 else 0, axis = 1)
            self.historical_prices['MACD To Signal Diff (Days)'] = self.historical_prices[['MACD To Signal Diff (Days)']].apply(cum_pattern)

            last_row = self.historical_prices.tail(1)

            info['MACD']                                = round(last_row['MACD'][0],4)
            info['MACD Signal']                         = round(last_row['MACD Signal'][0],4)
            info['MACD To Signal Diff (Value)']         = round(last_row['MACD To Signal Diff (Value)'][0],4)
            info['MACD To Signal Diff (Days)']          = last_row['MACD To Signal Diff (Days)'][0]
            info['MACD Signal Diff Rolling Peak']       = round(last_row['MACD Signal Diff Rolling Peak'][0],4)
            info['MACD Signal Diff % to Rolling Peak']  = round(last_row['MACD Signal Diff % to Rolling Peak'][0],2)
            info['MACD BUY/SELL']                       = last_row['MACD BUY/SELL'][0]

        except:
            pass

        finally:
            return info

    def get_52w_stat(self, data = None):

        info = {'52W High'          : 0,
                '52W Low'           : 0,
                'Price% 52W'        : 0,
                'Price Band 52W'    : 0}

        if data is None: data = self.historical_prices

        try:
            _52W_High = data['High'].max()
            info['52W High'] = round(_52W_High,2)

            _52W_Low = data['Low'].min()
            info['52W Low'] = round(_52W_Low,2)

            last_close = data.tail(1)['Close'][0]
            info['Price% 52W'] = round((last_close - _52W_Low)*100/(_52W_High - _52W_Low),2)

            band = math.floor(info['Price% 52W']/10)
            info['Price Band 52W'] = str(band*10) + '% to ' + str((band + 1) * 10) + '%' if band < 10 else '100 %'

        except:
            pass

        finally:
            return info

    def buy_sell_suggestion( self ):

        info = {'Buy'   : 'False',
                'Sell'  : 'False'}
        D   = self.stock_info['%D']
        _R  = self.stock_info['%R']

        try:
            info['Buy']     = 'True' if D < WILLIAM_K_UL and D < _R else 'False'
            info['Sell']    = 'True' if D > WILLIAM_K_LL and D > _R else 'False'

        except:
            pass
        finally:
            return info

def getHistoricStockPrices(stock_name, end_date = None, days = 700):
    ''' wrapper to get historic stock prices
    :param stock_name: Name of the stock
    :param start_date: Start Date. Defaulted to today.
    :param days: No of past days. Defaulted to 365 days
    :return: Pandas datframe with high, close, AdjClose, volume for each historical date.
    '''

    try:
        if end_date is None: end_date = datetime.datetime.today()
        start_date = end_date + datetime.timedelta( days = -1* days )

        hist_prices = getHistoricStockPricesFromYahoo(stock_name + '.NS',start_date, end_date)
        if not hist_prices.empty: return hist_prices

        hist_prices = getHistoricStockPricesFromYahoo(stock_name,start_date, end_date)
        if not hist_prices.empty: return hist_prices

    except:
        pass
    return pd.DataFrame()

def getHistoricStockPricesFromYahoo( stock_name, start_date = None, end_date = None):
    '''
    :param stock_name: Name of the stock
    :param start_date: Start Date. Defaulted to today.
    :param days: No of past days. Defaulted to 365 days
    :return: Pandas datframe with high, close, AdjClose, volume for each historical date.
    '''

    import pandas_datareader as pdr

    try:
        if end_date is None: end_date = datetime.datetime.today()
        if start_date is None: start_date = end_date + datetime.timedelta( days = -1* 365 )

        hist_prices = pdr.DataReader(stock_name, 'yahoo',start_date, end_date)
        return hist_prices

    except:
        return pd.DataFrame()

def cum_pattern( data ):

    prev = 0
    out = []
    for l in data:
        new = l + prev if l*prev > 0 else l
        out.append(new)
        prev = new
    return out

def ema( data, period = 10):

    result = [0]*len(data)

    for i, j in enumerate(data):
        if i < period-1:
            result[i] = 0
        elif i == period-1:
            result[i] = sum(data[:period])/period
        else:
            result[i] = (j * 2)/(period + 1) + result[i-1]*(1 - 2/(period + 1))
    return result

#if __name__ == '__main__':

    #import time
    #start = time.time()
    #a = StockScreener()
    #b = a.save_results()
    #print(time.time() - start)


money = 0

def add():
    for i in range(1000000):
        global money
        lock.acquire()
        money += 1
        lock.release()
def reduce():
    for i in range(1000000):
        global money
        lock.acquire()
        money -= 1
        lock.release()
if __name__ == '__main__':
          from threading import  Thread, Lock
          # 创建线程锁
          lock = Lock()
          t1 = Thread(target=add)
          t2 = Thread(target=reduce)
          t1.start()
          t2.start()
          t1.join()
          t2.join()
          print(money)


from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute.networks import flags as network_flags
from googlecloudsdk.command_lib.compute.networks.subnets import flags
import six

def _AddArgs(cls, parser, include_alpha=False):
  """Add subnetwork create arguments to parser."""
  cls.SUBNETWORK_ARG = flags.SubnetworkArgument()
  cls.NETWORK_ARG = network_flags.NetworkArgumentForOtherResource(
      'The network to which the subnetwork belongs.')
  cls.SUBNETWORK_ARG.AddArgument(parser, operation_type='create')
  cls.NETWORK_ARG.AddArgument(parser)

  parser.add_argument(
      '--description', help='An optional description of this subnetwork.')

  parser.add_argument(
      '--range',
      required=True,
      help='The IP space allocated to this subnetwork in CIDR format.')

  parser.add_argument(
      '--enable-private-ip-google-access',
      action='store_true',
      default=False,
      help=('Enable/disable access to Google Cloud APIs from this subnet for '
            'instances without a public ip address.'))

  parser.add_argument(
      '--secondary-range',
      type=arg_parsers.ArgDict(min_length=1),
      action='append',
      metavar='PROPERTY=VALUE',
      help="""\
      Adds a secondary IP range to the subnetwork for use in IP aliasing.

      For example, `--secondary-range range1=192.168.64.0/24` adds
      a secondary range 192.168.64.0/24 with name range1.

      * `RANGE_NAME` - Name of the secondary range.
      * `RANGE` - `IP range in CIDR format.`
      """)

  parser.add_argument(
      '--enable-flow-logs',
      action='store_true',
      default=None,
      help=('Enable/disable VPC flow logging for this subnet. More information '
            'for VPC flow logs can be found at '
            'https://cloud.google.com/vpc/docs/using-flow-logs.'))

  if include_alpha:
    parser.add_argument(
        '--purpose',
        choices={
            'PRIVATE':
                'Regular user created or automatically created subnet.',
            'INTERNAL_HTTPS_LOAD_BALANCER':
                'Reserved for Internal HTTP(S) Load Balancing.'
        },
        type=lambda x: x.replace('-', '_').upper(),
        help='The purpose of this subnetwork.')

    parser.add_argument(
        '--role',
        choices={
            'ACTIVE': 'The ACTIVE subnet that is currently used.',
            'BACKUP': 'The BACKUP subnet that could be promoted to ACTIVE.'
        },
        type=lambda x: x.replace('-', '_').upper(),
        help=('The role of subnetwork. This field is only used when'
              'purpose=INTERNAL_HTTPS_LOAD_BALANCER. The value can be set to '
              'ACTIVE or BACKUP. An ACTIVE subnetwork is one that is currently '
              'being used for Internal HTTP(S) Load Balancing. A BACKUP '
              'subnetwork is one that is ready to be promoted to ACTIVE or is '
              'currently draining.'))

    aggregation_interval_argument = base.ChoiceArgument(
        '--aggregation-interval',
        choices=[
            'interval-5-sec', 'interval-30-sec', 'interval-1-min',
            'interval-5-min', 'interval-10-min', 'interval-15-min'
        ],
        help_str="""\
        Can only be specified if VPC flow logging for this subnetwork is
        enabled. Toggles the aggregation interval for collecting flow logs.
        Increasing the interval time will reduce the amount of generated flow
        logs for long lasting connections. Default is an interval of 5 seconds
        per connection.
        """)
    aggregation_interval_argument.AddToParser(parser)

    parser.add_argument(
        '--flow-sampling',
        type=arg_parsers.BoundedFloat(lower_bound=0.0, upper_bound=1.0),
        help="""\
        Can only be specified if VPC flow logging for this subnetwork is
        enabled. The value of the field must be in [0, 1]. Set the sampling rate
        of VPC flow logs within the subnetwork where 1.0 means all collected
        logs are reported and 0.0 means no logs are reported. Default is 0.5
        which means half of all collected logs are reported.
        """)

    metadata_argument = base.ChoiceArgument(
        '--metadata',
        choices=['include-all-metadata', 'exclude-all-metadata'],
        help_str="""\
        Can only be specified if VPC flow logging for this subnetwork is
        enabled. Configures whether metadata fields should be added to the
        reported VPC flow logs. Default is to include all metadata.
        """)
    metadata_argument.AddToParser(parser)

    parser.add_argument(
        '--enable-private-ipv6-access',
        action='store_true',
        default=None,
        help=('Enable/disable private IPv6 access for the subnet.'))

@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class Create(base.CreateCommand):
  """Define a subnet for a network in custom subnet mode.

  Define a subnet for a network in custom subnet mode. Subnets must be uniquely
  named per region.
  """

  NETWORK_ARG = None
  SUBNETWORK_ARG = None

  @classmethod
  def Args(cls, parser):
    parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
    _AddArgs(cls, parser)
    parser.display_info.AddCacheUpdater(network_flags.NetworksCompleter)

  def _CreateSubnetwork(self, messages, subnet_ref, network_ref, args):
    subnetwork = messages.Subnetwork(
        name=subnet_ref.Name(),
        description=args.description,
        network=network_ref.SelfLink(),
        ipCidrRange=args.range,
        privateIpGoogleAccess=args.enable_private_ip_google_access,
        enableFlowLogs=args.enable_flow_logs)

    if self.ReleaseTrack() == base.ReleaseTrack.ALPHA:
      if args.purpose:
        subnetwork.purpose = messages.Subnetwork.PurposeValueValuesEnum(
            args.purpose)
      if (subnetwork.purpose == messages.Subnetwork.PurposeValueValuesEnum.
          INTERNAL_HTTPS_LOAD_BALANCER):
        # Clear unsupported fields in the subnet resource
        subnetwork.privateIpGoogleAccess = None
        subnetwork.enableFlowLogs = None

      if getattr(args, 'role', None):
        subnetwork.role = messages.Subnetwork.RoleValueValuesEnum(args.role)

      convert_to_enum = lambda x: x.replace('-', '_').upper()
      if args.aggregation_interval:
        subnetwork.aggregationInterval = (
            messages.Subnetwork.AggregationIntervalValueValuesEnum(
                convert_to_enum(args.aggregation_interval)))
      if args.flow_sampling is not None:
        subnetwork.flowSampling = args.flow_sampling
      if args.metadata:
        subnetwork.metadata = messages.Subnetwork.MetadataValueValuesEnum(
            convert_to_enum(args.metadata))
      if args.enable_private_ipv6_access is not None:
        subnetwork.enablePrivateV6Access = args.enable_private_ipv6_access

    return subnetwork

  def Run(self, args):
    """Issues a list of requests necessary for adding a subnetwork."""
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client

    network_ref = self.NETWORK_ARG.ResolveAsResource(args, holder.resources)
    subnet_ref = self.SUBNETWORK_ARG.ResolveAsResource(
        args,
        holder.resources,
        scope_lister=compute_flags.GetDefaultScopeLister(client))

    request = client.messages.ComputeSubnetworksInsertRequest(
        subnetwork=self._CreateSubnetwork(client.messages, subnet_ref,
                                          network_ref, args),
        region=subnet_ref.region,
        project=subnet_ref.project)

    secondary_ranges = []
    if args.secondary_range:
      for secondary_range in args.secondary_range:
        for range_name, ip_cidr_range in sorted(six.iteritems(secondary_range)):
          secondary_ranges.append(
              client.messages.SubnetworkSecondaryRange(
                  rangeName=range_name, ipCidrRange=ip_cidr_range))

    request.subnetwork.secondaryIpRanges = secondary_ranges
    return client.MakeRequests([(client.apitools_client.subnetworks, 'Insert',
                                 request)])

@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(Create):
  """Define a subnet for a network in custom subnet mode.

  Define a subnet for a network in custom subnet mode. Subnets must be uniquely
  named per region.
  """

  @classmethod
  def Args(cls, parser):
    parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
    _AddArgs(cls, parser, include_alpha=True)
    parser.display_info.AddCacheUpdater(network_flags.NetworksCompleter)


from django.urls import path
from . import views

app_name = 'blog'

urlpatterns = [
    path('', views.blog_list, name='blog-list'),
    path('article/<int:id>/', views.blog_detail, name='blog-detail'),
    path('add-article/', views.add_article, name='add-article'),
    path('confirm-add-article/', views.confirm_add_article, name='confirm-add-article'),
    path('edit-article/<int:pk>/', views.edit_article, name='edit-article'),
    path('confirm-edit-article/<int:pk>/', views.confirm_edit_article, name='confirm-edit-article'),
    path('confirm-delete-article/<int:pk>/', views.confirm_delete_article, name='confirm-delete-article'),
    path('review/<int:pk>/<int:star_count>/', views.review, name='review'),
]


# Print "Type "play" to play the game, "exit" to quit:" when game starts
# - Start game if user types "play"
# - Do nothing if user types "exit"
# - Print message again if user types anything else
# Print "Type "play" to play the game, "exit" to quit:" when game end

import random as r

def play_game():

    list_of_options = ['python', 'java', 'kotlin', 'javascript']

    previous_guesses = []

    selected_word = r.choice(list_of_options)

    masked_text = len(selected_word) * '-'

    # print(selected_word)
    print("H A N G M A N")
    print("")
    remaining_lives = 8
    while remaining_lives > 0:
        print(masked_text)
        guessed_letter = input("Input a letter:")

        islower = guessed_letter.islower()
        isenglishalpha = guessed_letter.isalpha() and guessed_letter.isascii()

        if len(guessed_letter) != 1:
            print("Please input a single letter")
            if remaining_lives != 0:
                print("")
            continue

        elif not(islower and isenglishalpha):
            print("Please enter a lowercase English letter")
            if remaining_lives != 0:
                print("")
            continue

        elif guessed_letter in previous_guesses:
            print("You've already guessed this letter")

            if remaining_lives != 0:
                print("")
            continue

        elif guessed_letter not in selected_word:
            print("That letter doesn't appear in the word")
            remaining_lives -= 1

            if remaining_lives != 0:
                previous_guesses.append(guessed_letter)
                print("")
            continue

        else:
            char_list = list(masked_text)
            for index, value in enumerate(masked_text):
                if guessed_letter == selected_word[index]:
                    char_list[index] = guessed_letter
            masked_text = "".join(char_list)
            if '-' not in masked_text:
                break

            if remaining_lives != 0:
                previous_guesses.append(guessed_letter)
                print("")

    if '-' not in masked_text:
        print(f"You guessed the word {masked_text}!")
        print("You survived!")

    if '-' in masked_text:
        print("You lost!")

user_input = ""

while True:
    user_input = input('Type "play" to play the game, "exit" to quit:')
    if user_input == "play":
        play_game()
        print("")
    elif user_input == "exit":
        break
    else:
        pass


__author__ = 'Marcelo Ferreira da Costa Gomes'

import sys
import logging
import pandas as pd
import numpy as np
import random
from .episem import lastepiweek, epiweek2date

module_logger = logging.getLogger('update_system.delay_table')

def extract_quantile(dforig=pd.DataFrame, filtertype='srag'):
    if filtertype not in ['srag', 'sragnofever', 'hospdeath']:
        exit('Invalid filter type: %s' % filtertype)

    suff = ''
    if filtertype != 'srag':
        suff = '_%s' % filtertype

    dfquant = pd.DataFrame(columns=['UF', 'dado', 'epiyearweek', 'epiyear', 'epiweek'])
    df = dforig[(dforig.delayweeks <= 26) & (dforig.epiyear >= 2013)].copy()
    tgt_cols = ['UF', 'Regional', 'Regiao', 'Pais']
    uflist={col: dforig[col].unique().tolist() for col in tgt_cols}
    for year in range(2014, df.epiyear.max()+1):
        if year == df.epiyear.max():
            weekmax = int(max(df.DT_DIGITA_epiweek[df.DT_DIGITA_epiyear == year]) + 1)
        else:
            weekmax = int(lastepiweek(year)) + 1
        for week in range(1, weekmax):
            f_epiweek = '%sW%02d' % (year-1, week)
            l_epiweek = '%sW%02d' % (year, week)
            dftmp = df.loc[(df.epiyearweek >= f_epiweek) & (df.DT_DIGITA_epiyearweek <= l_epiweek),
                           tgt_cols + ['dado', 'delayweeks']]
            for tgt_col in tgt_cols:
                out_cols = [tgt_col, 'dado', 'delayweeks']
                dfqtmp = pd.DataFrame([{tgt_col: uf, 'dado': dado, 'epiyearweek': '%sW%02d' % (year, week), 'epiyear':
                    year, 'epiweek': week} for uf in uflist[tgt_col] for dado in ['srag', 'sragflu', 'obitoflu',
                                                                                'sragcovid', 'obitocovid', 'obito']])

                dfqtmp = dfqtmp.merge((np.ceil(dftmp[out_cols].groupby(out_cols[0:2]).quantile(.9))).reset_index()[
                    out_cols], on=[tgt_col, 'dado'], how='left').fillna(0)
                dfquant = dfquant.append(dfqtmp.rename(columns={tgt_col: 'UF'}), ignore_index=True, sort=False)

    dfquant.sort_values(by=['dado', 'UF', 'epiyearweek'], inplace=True)
    dfquant.to_csv('../clean_data/sinpri2digita_quantiles%s.csv' % suff, index=False)

    return

def readtable(fname):
    """Read notification table.

    :param fname: path to file
    :return: pandas.DataFrame
    """
    df = pd.read_csv(fname, low_memory=False)[
        ['UF', 'Regional', 'Regiao', 'Pais', 'dado', 'DT_SIN_PRI_epiyearweek', 'DT_SIN_PRI_epiyear',
         'DT_SIN_PRI_epiweek', 'SinPri2Digita_DelayWeeks', 'DT_DIGITA_epiyearweek', 'DT_DIGITA_epiyear',
         'DT_DIGITA_epiweek']
    ].rename(columns={'DT_SIN_PRI_epiyearweek': 'epiyearweek', 'DT_SIN_PRI_epiyear': 'epiyear',
                      'DT_SIN_PRI_epiweek': 'epiweek', 'SinPri2Digita_DelayWeeks': 'delayweeks'})
    df.UF = df.UF.astype(int).astype(str)

    # dfmunreg = pd.read_csv('~/dropbox-personal/Dropbox/IBGE/rl_municip_regsaud.csv', sep=';', header=None,
    #                        names=['municipio', 'regionalsaude'])

    return df

def delayimputation(df=pd.DataFrame()):
    """
    Generate delay estimate for missing data, from locality and epiweek profile

    :param df: original data frame
    :return: df: original data with imputed data
    """

    # Count delay frequency by locality and 4-epiweek periods since 2013:
    dfgrp = df[df.epiyear >= 2013].copy()
    dfgrp['4weeks'] = dfgrp.epiweek.map(lambda x: 1 + min(12, int((x-1)/4)))
    dfgrp = dfgrp.groupby(['UF', '4weeks', 'delayweeks']).size().reset_index()
    dfgrp.rename(columns={0: 'counts'}, inplace=True)
    dfgrp.delayweeks = dfgrp.delayweeks.astype(int)
    dfgrp_uf = dfgrp[['UF', 'delayweeks', 'counts']].groupby(['UF', 'delayweeks'], as_index=False).agg(sum)
    today_year = int(df.DT_DIGITA_epiyear.max())
    today_week = int(df.DT_DIGITA_epiweek[df.DT_DIGITA_epiyear == today_year].max())

    df['dlimit'] = today_week - df.epiweek.astype(int) + (today_year - df.epiyear) * \
                   (df.epiyear.apply(lastepiweek)).astype(int)

    def sampler(col):
        dfgrp_slice = dfgrp.loc[(dfgrp['UF'] == col['UF']) &
                                (dfgrp['4weeks'] == col['4weeks']) &
                                (dfgrp['delayweeks'] <= col['dlimit']),
                                ['delayweeks', 'counts']]
        if len(dfgrp_slice) == 0:
            dfgrp_slice = dfgrp_uf.loc[(dfgrp_uf['UF'] == col['UF']) & (dfgrp_uf['delayweeks'] <= col['dlimit']),
                                       ['delayweeks', 'counts']]

        d = random.choices(population=dfgrp_slice['delayweeks'].values, weights=dfgrp_slice['counts'].values)[0]
        return d

    df['4weeks'] = df.epiweek.map(lambda x: 1 + min(12, int((x-1)/4)))
    df.loc[pd.isnull(df.delayweeks), 'delayweeks'] = df.loc[pd.isnull(df.delayweeks), ['UF', '4weeks', 'dlimit']].apply(
        sampler, axis=1)

    df.drop(columns=['4weeks', 'dlimit'], inplace=True)

    return df

def createtable(df_in = pd.DataFrame()):
    """Generate digitalization opportunity table by epidemiological week.

    From notification data, creates a table with total number of notified cases on column Notifications
    and number of cases introduced in the database by number of weeks since notification.

    The output is a pandas.DataFrame with columns:

    locality | epiyear | epiweek | Notifications | d0 | d1 | ... | d27 | Notifications_26w

    Where:

     * locality: has the Federation Unit code;
     * epiyear: epidemiological year;
     * epiweek: epidemiological week;
     * Notifications: total number of notified cases for that locality, epiyear, epiweek so far;
     * dn: corresponds to the number of cases digitalized n weeks *after* notification week.
     * Notifications_26w: total number of notified cases with up to 26 weeks of delay.

    :param df: pandas.DataFrame of notifications with columns ['locality', 'epiyear', 'epiweek']
    :return: pandas.DataFrame
    """

    # Fill with all epiweeks:
    yearlist = list(df_in.epiyear.unique())
    # Remove NaN:
    yearlist = sorted([y for y in yearlist if y == y])
    lastweek = int(df_in.DT_DIGITA_epiweek[df_in.DT_DIGITA_epiyear == max(yearlist)].max())
    df = df_in.drop(columns=['DT_DIGITA_epiyear', 'DT_DIGITA_epiweek'])
    cols = ['UF', 'dado', 'epiyearweek', 'epiyear', 'epiweek', 'Notifications']
    dcols = ['d%s' % d for d in range(0, 27)]
    cols.extend(dcols)
    cols.extend(['Notifications_within_26w'])
    tbl = pd.DataFrame(columns=cols)
    tmpdict = []
    for dataset in df.dado.unique():
        for year in yearlist[:-1]:
            for week in range(1, (int(lastepiweek(year)) + 1)):
                tmpdict.extend([{'dado': dataset, 'epiyearweek': '%04dW%02d' % (year, week), 'epiyear': year,
                                 'epiweek': week}])
        year = yearlist[-1]
        tmpdict.extend([{'dado': dataset, 'epiyearweek': '%04dW%02d' % (year, week), 'epiyear': year, 'epiweek': week}
                        for week in range(1, (lastweek + 1))])
    dfallweeks = pd.DataFrame(tmpdict)

    for locality in ['UF', 'Regional', 'Regiao', 'Pais']:
        localitylist = sorted(df[locality].unique().tolist())
        dftmp = dfallweeks.copy()
        dftmp[locality] = localitylist[0]

        if len(localitylist) > 1:
            for loc in localitylist[1:]:
                dftmp = dftmp.append(dfallweeks, ignore_index=True, sort=False).fillna(loc)
        dftmp.sort_values(by=['dado', locality, 'epiyear', 'epiweek'], inplace=True)

        grp_cols = [locality, 'epiyearweek', 'epiyear', 'epiweek', 'dado']
        delay_table = df[grp_cols].groupby(grp_cols, as_index=False).size().reset_index()
        delay_table.rename(columns={0: 'Notifications'}, inplace=True)

        for k in range(0, 27):
            aux = df.loc[df.delayweeks == k, ].groupby(grp_cols, as_index=False).size().reset_index()
            aux.rename(columns={0: 'd%s' % k}, inplace=True)
            delay_table = delay_table.merge(aux, how='left', on=grp_cols).fillna(0)

        delay_table = dftmp[grp_cols].merge(delay_table, how='left', on=grp_cols).fillna(0)
        delay_table['Notifications_within_26w'] = delay_table[dcols].sum(axis=1)
        tbl = tbl.append(delay_table.rename(columns={locality: 'UF'}), ignore_index=True, sort=False)

    tbl['date'] = tbl[['epiyear', 'epiweek']].apply(lambda x: epiweek2date(x[0], x[1]), axis=1)

    return(tbl)

def main(fname, locality='UF'):

    module_logger.info('Read table from %s' % fname)
    df = readtable(fname)
    extract_quantile(df)
    df = delayimputation(df)
    df = createtable(df)
    for dataset in df.dado.unique():
        fout = '../clean_data/%s_sinpri2digita_table_weekly.csv' % dataset
        module_logger.info('Write table %s' % fout)
        df[df.dado == dataset].to_csv(fout, index=False)

if __name__ == '__main__':

    if len(sys.argv) == 2:
        main(sys.argv[1])
    else:
        main(sys.argv[1], sys.argv[2])


import rospy, time

from sensor_msgs.msg import LaserScan

TOPIC_scan_nomap = '/scan_nomap'

class AugmentedResolutionScan(object):

    def __init__(self):
        self.scan_pub = rospy.Publisher("/scan_nomap_augmented", LaserScan, queue_size=1)
        self.max_scan_range = 10.0

    def ScanPub(self):
        rospy.init_node("scan_nomap_augmented_resolution", disable_signals=True)
        rospy.sleep(1)

        scan_sub = rospy.Subscriber("/scan_nomap", LaserScan, self.ScanCB)

        rospy.spin()

    def ScanCB(self, msg):
        laser_scan = LaserScan()
        laser_scan.header = msg.header
        laser_scan.angle_min = msg.angle_min
        laser_scan.angle_max = msg.angle_max
        laser_scan.angle_increment = msg.angle_increment / 2.0
        laser_scan.time_increment = msg.time_increment
        laser_scan.scan_time = msg.scan_time
        laser_scan.range_min = msg.range_min
        laser_scan.range_max = msg.range_max
        laser_scan.ranges = []
        for i in range(1, len(msg.ranges)):
            r0 = msg.ranges[i-1]
            r1 = msg.ranges[i]
            laser_scan.ranges.append(r0)
            if r1 <= self.max_scan_range and abs(r1-r0) < 0.4:
                new = (r0 + r1) / 2.0
            else:
                new = msg.range_max+1
            laser_scan.ranges.append(new)

        laser_scan.intensities = []
        for r in laser_scan.ranges:
            if r <= self.max_scan_range:
                laser_scan.intensities.append(1.0)
            else:
                laser_scan.intensities.append(0.0)

        self.scan_pub.publish(laser_scan)

# main
if __name__ == "__main__":

    print("Running...")
    scan = AugmentedResolutionScan()
    scan.ScanPub()


import random
import string

words = ['coffee', 'approach', 'advance', 'message', 'edition', 'attachment', 'receipt', 'mouth', 'degree', 'license',
         'retreat', 'concert', 'acquaintance', 'measure', 'kitchen', 'pool', 'chain', 'swell', 'call', 'crash', ]

word = random.choice(words)

guessed_word = ['_' for char in word]
print(' '.join(guessed_word), '\n')
final_word = ' '.join(word)

lst_word = list(word)
rounds = 6
# create an empty list to add guessed letter to if it's in the word
is_part_of = []

# a list of all the available letters to restrict user input to unused lowercase letters only
letters = string.ascii_lowercase
available_letters = []
for x in letters:
    available_letters.append(x)
print(','.join(available_letters))

while rounds:
    try:
        guess = input('\nGuess a letter: ')
        available_letters.remove(guess)

        # cehck to see if letter guessed is correct
        for i in range(len(lst_word)):
            if lst_word[i] == guess:
                is_part_of.append(True)
                guessed_word[i] = guess
            else:
                is_part_of.append(False)

        # if not correct, less rounds by 1
        if True not in is_part_of:
            rounds -= 1
        # clear the array to be used in the next round
        is_part_of.clear()

        print(' '.join(guessed_word))

        # only print the available letters in this condition
        if ' '.join(guessed_word) != final_word:
            print('\nAvailable Letters:\n', ','.join(available_letters))
            print(f'\n{rounds} Rounds left')
        else:
            pass

        if rounds > 0 and ' '.join(guessed_word) == final_word:
            print('\nYou Won!')
            break
        elif rounds == 0 and ' '.join(guessed_word) != final_word:
            print('You Lost!', '\nThe word is: ', final_word)

    except ValueError:
        print("Error! Only one letter from \"Available Letters\" allowed!")


t = int(input())
answer = list()
for i in range(1, t+1):
    alpha = list(input().rstrip())
    alpha.sort()
    idx = 0
    res = list()

    while idx < len(alpha):

        if idx < len(alpha) - 1 and alpha[idx] == alpha[idx+1]:
            idx += 2
            continue
        else:
            res.append(alpha[idx])
            idx += 1

    if not res:
        res = 'Good'
    answer.append('#{} {}'.format(i, ''.join(res)))

print('\n'.join(answer))


import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install speechRecognition
import datetime
import wikipedia #pip install wikipedia
import webbrowser
import os
import smtplib
import sys
import random
import urllib.request
import json

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
# print(voices[1].id)
engine.setProperty('voice', voices[0].id)

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning!")

    elif hour>=12 and hour<18:
        speak("Good Afternoon!")

    else:
        speak("Good Evening!")

    speak("I am Jarvis Sir. Please tell me how may I help you")

def takeCommand():
    #It takes microphone input from the user and returns string output

    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)

    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language='en-in')
        print(f"User said: {query}\n")

    except Exception as e:
        # print(e)
        print("Say that again please...")
        return "None"
    return query

def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('youremail@gmail.com', 'your-password')
    server.sendmail('youremail@gmail.com', to, content)
    server.close()

if __name__ == "__main__":
    wishMe()
    while True:
    # if 1:
        query = takeCommand().lower()

        # Logic for executing tasks based on query
        if 'wikipedia' in query:
            speak('Searching Wikipedia...')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=2)
            speak("According to Wikipedia")
            print(results)
            speak(results)

        elif 'open youtube' in query:
            webbrowser.open("youtube.com")

        elif 'open google' in query:
            webbrowser.open("google.com")

        elif 'open stackoverflow' in query:
            webbrowser.open("stackoverflow.com")

        elif 'play music' in query:
            music_dir = 'C:\\Users\\bisha\\Desktop\\Songs'
            songs = os.listdir(music_dir)
            rd=random.choice(songs)
            print(songs)
            os.startfile(os.path.join(music_dir,rd ))

        elif 'the time' in query:
            strTime = datetime.datetime.now().strftime("%H:%M:%S")
            speak(f"Sir, the time is {strTime}")

        elif 'open code' in query:
            codePath = "C:\\Users\\bisha\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
            os.startfile(codePath)

        elif 'email to Bishal' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                to = "PersonEmai@gmail.com"
                sendEmail(to, content)
                speak("Email has been sent!")
            except Exception as e:
                print(e)
                speak("Sorry my friend Bishal. I am not able to send this email")
        elif 'you can sleep' in query:
            speak('Thanks for using me sir')
            sys.exit()
        elif 'close notepad' in query:
            speak('Closing notepad sir')
            os.system('taskkill/f/im notepad.exe')

        elif 'switch the window' in query:
            pyautogui.keyDown('alt')
            pyautogui.press('tab')
            time.sleep(1)
            pyautogui.keyUp('alt')

        elif 'where i am' in query or 'where we are' in query:
            speak('wait sir, let me check')
            try:
                ipAdd=requests.get('https://api.ipify.org')
                print(ipAdd)
                url='http://ip-api.com/json/'
                get_requests= urllib.request.urlopen(url+ipAdd)
                #get_requests= requests.get(url+ipAdd)
                geo_data= geo_requests.json()
                city= geo_data['city']
                state= geo_data['state']
                country= geo_data['country']
                speak(f'sir,i am not sure but i think we are in {city} city of {state} state of {country} country')

            except Exception as e:
                speak('sorry sir because of network issue i am not able to find where we are')
                pass


import time
import os
import sys

model_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], '../../')
sys.path.append(model_dir)

from dianping.utils.mongodb_utils import get_db
from dianping.utils import load_cities, load_shops

if __name__ == "__main__":
    format = '%Y-%m-%d-%H-%M-%S'
    current = time.localtime(time.time())
    dt = time.strftime(format, current)
    statistics_path = './progress_info.txt'
    cities = load_cities()
    with open(statistics_path, 'a', encoding='utf-8') as f:
        f.writelines('{}, 目前进展如下:\n'.format(dt))
        print('{}, 目前进展如下:'.format(dt))
        f.writelines('商店总数:{}\n'.format(load_shops().count()))
        print('商店总数:{}'.format(load_shops().count()))
        for city in cities:
            city_name = city.get('name')
            query1 = {
                'city': city_name,
            }
            query2 = {
                'city': city_name,
                'version': {
                    '$exists': True,
                },
            }
            f.writelines('{}的商店总数:{}, \t请求详情进度:{}\n'.format(city_name, load_shops(query1).count(), load_shops(query2).count()))
            print('{}的商店总数:{}, \t请求详情进度:{}'.format(city_name, load_shops(query1).count(), load_shops(query2).count()))


import time

import telebot
from telebot import types

import base

bot = telebot.TeleBot('5194270771:AAF2zvg8MEBgCjOusmaIyX6u4yF7X_CtmCw')
#bot = telebot.TeleBot('5188999206:AAFDzoHQCE6_YTsAxTA8hlhJD4M2tPXyVh4') #dev
bd = base.Base("localhost")

@bot.message_handler(commands=['start'])
def start(message):
    print(message.chat.id)
    if bd.getuser(message.chat.id) is None:
        bd.regUser(message.chat.id)

    keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)
    keyboard.add(types.KeyboardButton(text="payment"))

    bot.send_message(message.chat.id, "Here you can receive a newsletter of important events for cryptocurrency",
                     reply_markup=keyboard)

@bot.message_handler(content_types=['text'])
def text(message):
    if message.text == "payment":
        keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)
        keyboard.add(types.KeyboardButton(text="I have a promo code"))
        keyboard.add(types.KeyboardButton(text="Pay for a subscription"))
        bot.send_message(message.chat.id, "Pay for a subscription",
                         reply_markup=keyboard)
    if message.text == "I have a promo code":
        bot.send_message(message.chat.id, "Enter a promo code")
        bot.register_next_step_handler(message,PayPromos)
    if message.text == "Pay for a subscription":
        bot.send_message(message.chat.id, "Enter a promo code")
        bot.register_next_step_handler(message,PayPromos)

def PayPromos(message):
    pr = bd.PayPromo(message.chat.id,message.text)
    print(pr)
    if pr == True:
        bot.send_message(message.chat.id, "The subscription is activated for 5 days for free!")
    elif pr == False:
        bot.send_message(message.chat.id, "Subscription not activated(")
    elif pr == "admin":
        bot.send_message(message.chat.id, "Режим бога богатства активирован!")

if __name__ == "__main__":
    while True:
        try:
            bot.polling(none_stop=True)
        except:
            pass


import time

import bot_core as lcmbotcore
from director import lcmUtils
from director import applogic
from director.visualization import updateText

from drake.tools.workspace.drake_visualizer.plugin import scoped_singleton_func

class TimeVisualizer(object):

    def __init__(self):
        self._name = "Time Visualizer"
        self._real_time = []
        self._msg_time = []
        self._subscriber = None
        # Number of messages used to average for real time factor.
        self._num_msg_for_average = 50

        self.set_enabled(True)

    def add_subscriber(self):
        if (self._subscriber is not None):
            return

        self._subscriber = lcmUtils.addSubscriber(
            'DRAKE_VIEWER_DRAW',
            messageClass=lcmbotcore.viewer_draw_t,
            callback=self.handle_message)

    def remove_subscriber(self):
        if (self._subscriber is None):
            return

        lcmUtils.removeSubscriber(self._subscriber)
        self._subscriber = None
        updateText('', 'text')

    def is_enabled(self):
        return self._subscriber is not None

    def set_enabled(self, enable):
        if enable:
            self.add_subscriber()
        else:
            self.remove_subscriber()

    def handle_message(self, msg):
        msg_time = msg.timestamp * 1e-3  # convert from milliseconds
        self._real_time.append(time.time())
        self._msg_time.append(msg_time)

        my_text = 'sim time: %.3f' % msg_time

        if (len(self._real_time) >= self._num_msg_for_average):
            self._real_time.pop(0)
            self._msg_time.pop(0)

            dt = self._msg_time[-1] - self._msg_time[0]
            dt_real_time = self._real_time[-1] - self._real_time[0]

            rt_ratio = dt / dt_real_time

            my_text = my_text + ', real time factor: %.2f' % rt_ratio

        updateText(my_text, 'text')

@scoped_singleton_func
def init_visualizer():
    time_viz = TimeVisualizer()
    # Adds to the "Tools" menu.
    applogic.MenuActionToggleHelper(
        'Tools', time_viz._name,
        time_viz.is_enabled, time_viz.set_enabled)
    return time_viz

# Activate the plugin if this script is run directly; store the results to keep
# the plugin objects in scope.
if __name__ == "__main__":
    time_viz = init_visualizer()


from bs4 import BeautifulSoup
import requests
import urllib.parse
import json
from discord.ext import commands

class CodInGame(commands.Cog):
    def __init__(self,config, bot: commands.Bot):
        self.bot = bot
        self.config = config

    @commands.command()
    async def gofish(self, ctx):
        url = self.CodInGame()
        await ctx.send(url)

    def CodInGame(self) -> str:
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0",
            "Cookie": f"rememberMe={self.config['codingame_cookie']}"

            }
        search_url = f"https://www.codingame.com/services/ClashOfCode/createPrivateClash"
        data = '[4187058,["Python3"],["FASTEST","SHORTEST","REVERSE"]]'
        req = requests.post(search_url, headers=headers, data=data)

        print(req.text)
        command_dict = json.loads(req.text.replace("false", '"False"'))
        handle = command_dict['publicHandle']
        #https://www.codingame.com/clashofcode/clash/
        return f"https://www.codingame.com/clashofcode/clash/{handle}"

if __name__ == "__main__":
    pass
    #print(CodInGame())


import pandas as pd
from scipy.sparse.construct import rand
from sklearn.linear_model import Ridge
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
#import matplotlib.pyplot as plt
from sklearn import metrics
import os
from sklearn import tree
from sklearn.externals import joblib

import argparse

class BaselineModel:
    '''
    class to create the logistic regression
    '''
    def __init__(self,final_data, vars_to_keep , pred_var = 'prep_time_seconds'):
        self.final_data = final_data
        self.vars_to_keep = vars_to_keep
        self.pred_var = pred_var
        self.X_train_scaled , self.X_test_scaled = self.normalize_data()
        self.model = self.create_model()

    def normalize_data(self):
        '''
        Transform and Normalize the inputs so that the feature importance are on the same scale
        '''
        print("normalize the data")
        df_train = pd.get_dummies(self.final_data.train[self.vars_to_keep] ,drop_first=True)
        print("train dummies shape",df_train.shape[1])
        df_test = pd.get_dummies(self.final_data.test[self.vars_to_keep] ,drop_first=True)
        print("test dummies shape",df_test.shape[1])
        ss = MinMaxScaler()
        # X_train_scaled = ss.fit_transform(df_train)
        # X_train_scaled = pd.DataFrame(X_train_scaled,columns=df_train.columns)
        # X_test_scaled = ss.transform(df_test)
        # X_test_scaled = pd.DataFrame(X_test_scaled,columns=df_test.columns)
        X_train_scaled = df_train.copy()
        X_test_scaled = df_test.copy()
        return X_train_scaled , X_test_scaled

    def create_model(self):
        print("create the linear model using ridge with alpha 2")

        model = Ridge(random_state=999 , alpha = 2)

        model.fit(self.X_train_scaled,self.final_data.train[self.pred_var])
        return model

    def print_evaluation_statistics(self,train = True):
        if train:
            pred = self.model.predict(self.X_train_scaled)
            print("Mean Absolute Error:", metrics.mean_absolute_error(self.final_data.train['prep_time_seconds'],pred))
            print("Mean Square Error :",metrics.mean_squared_error(self.final_data.train['prep_time_seconds'],pred))
        else:
            pred = self.model.predict(self.X_test_scaled)
            print("Mean Absolute Error :",metrics.mean_absolute_error(self.final_data.test['prep_time_seconds'],pred))
            print("Mean Square Error :",metrics.mean_squared_error(self.final_data.test['prep_time_seconds'],pred))

class create_train_test_val:
    '''
    Class to create the train test and val
    '''
    def __init__(self,
                 data):
        self.data = data
        self.train, self.test = self.create_test_train()

    def create_test_train(self):

        train, test = train_test_split(self.data, random_state = 999,test_size=0.2)

        print(len(train), 'train examples')
        print(len(test), 'test examples')

        return train,test

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    # Sagemaker specific arguments. Defaults are set in the environment variables.

    #Saves Checkpoints and graphs
    parser.add_argument('--output-data-dir', type=str, default=os.environ['SM_OUTPUT_DATA_DIR'])

    #Save model artifacts
    parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])

    #Train data
    parser.add_argument('--train', type=str, default=os.environ['SM_CHANNEL_TRAIN'])

    args = parser.parse_args()

    file = os.path.join(args.train, "combined_data.csv")
    final_data = pd.read_csv(file, engine="python")

    final_data = create_train_test_val(final_data)

    # Creating the dummy variables
    base_model = BaselineModel(final_data,vars_to_keep=['order_value_gbp',
                                              'number_of_items',
                                              'country',
                                              'city',
                                              'type_of_food',
                                              'value_per_item',
                                              'hour_order_acknowledged_at',
                                              'day_of_order'])
    clf = base_model.create_model()
    joblib.dump(clf, os.path.join(args.model_dir, "lr_model.joblib"))

def model_fn(model_dir):
    """Deserialized and return fitted model

    Note that this should have the same name as the serialized model in the main method
    """
    regressor = joblib.load(os.path.join(model_dir, "lr_model.joblib"))
    return regressor


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

class bandit:
    def __init__(self, arm_num):
        self.arms = []
        for _ in range(arm_num):
            arm = {'mean': random.gauss(0, 1), 'std': 1}
            self.arms.append(arm)

    def reset(self, random_walk_std):
        for i in range(len(self.arms)):
            self.arms[i]['mean'] += random.gauss(0, random_walk_std)

    def step(self, arm_idx):
        mean = self.arms[arm_idx]['mean']
        std = self.arms[arm_idx]['std']
        reward = random.gauss(mean, std)
        return reward

    def optim_idx(self):
        item = max(self.arms, key=lambda x: x['mean'])
        return self.arms.index(item)

class agent:
    def __init__(self, greedy, arm_num, alpha_type):
        self.greedy = greedy
        self.arm_num = arm_num
        self.memory = []
        for _ in range(arm_num):
            arm_info = {'Q': 0.0, 'visits': 0}
            self.memory.append(arm_info)
        self.alpha_type = alpha_type
        self.reward_list = []

    def update_memory(self, arm_idx, reward):
        Q = self.memory[arm_idx]['Q']
        visits = self.memory[arm_idx]['visits'] + 1
        alpha = 0.0
        if self.alpha_type == 'sample-average':
            alpha = 1.0 / visits
        elif self.alpha_type == 'constant':
            alpha = 0.1
        Q_new = Q + alpha * (reward - Q)
        self.memory[arm_idx]['Q'] = Q_new
        self.memory[arm_idx]['visits'] = visits
        self.reward_list.append(reward)

    def action(self, time_step):
        prob = random.uniform(0, 1)
        if prob < self.greedy:
            arm_idx = random.randrange(0, self.arm_num)
        else:
            item = max(self.memory, key=lambda x: x['Q'])
            arm_idx = self.memory.index(item)
        return arm_idx

class agent_UCB(agent):
    def __init__(self, c):
        self.c = c
        super(agent_UCB, self).__init__(greedy=None, arm_num=10, alpha_type='sample-average')

    def action(self, time_step):
        value = []
        for dict in self.memory:
            if dict['visits'] == 0:
                return self.memory.index(dict)
            confidence = self.c * np.sqrt(np.log(time_step) / dict['visits'])
            value.append(dict['Q'] + confidence)
        arm_idx = value.index(max(value))
        return arm_idx

def figure2_4(max_steps=1000, task_num=2000, random_walk_std=0.5):
    tasks = []
    for _ in range(task_num):
        task = bandit(10)
        agent0 = agent(0.1, 10, 'sample-average')
        agent1 = agent_UCB(c=2)
        tasks.append([task, agent0, agent1])
    graph1 = []
    graph2 = []
    for i in range(1, 3):
        optim_percent = []
        total_reward = np.zeros(max_steps)
        for step in range(1, max_steps + 1):
            optim_count = 0
            for single_task in tasks:
                player = single_task[i]
                env = single_task[0]
                arm_idx = player.action(step)
                reward = env.step(arm_idx)
                player.update_memory(arm_idx, reward)
                optim_idx = env.optim_idx()
                if arm_idx == optim_idx:
                    optim_count += 1
                    # env.reset(random_walk_std)
            optim_percent.append(optim_count / task_num)
        for single_task in tasks:
            player = single_task[i]
            total_reward += np.array(player.reward_list)
        average_reward = total_reward / task_num
        graph1.append(average_reward)
        graph2.append(optim_percent)
    plt.figure()
    # plt.subplot(2, 1, 1)
    plt.xlabel('Steps')
    plt.ylabel('Average reward')
    plt.plot(graph1[1], 'g', label=r'$UCB,c=2$')
    plt.plot(graph1[0], 'r', label=r'$\epsilon-greedy,\epsilon=0.1$')
    plt.legend()
    '''
	plt.subplot(2, 1, 2)
    plt.xlabel('Steps')
    plt.ylabel('Optimal action')
    plt.plot(graph2[0], 'r', label=r'$\alpha=\frac{1}{n}$')
    plt.plot(graph2[1], 'g', label=r'$\alpha=0.1$')
    plt.legend()
	'''
    plt.show()

if __name__ == '__main__':
    # random walk : q=q+e , e~N(0,std)
    figure2_4(max_steps=1000, task_num=2000, random_walk_std=0.5)


#!/bin/python3

"""
Basic code for learning Python
Problem 22 - Designer Door Mat
(https://www.hackerrank.com/challenges/designer-door-mat/)
"""

if __name__ == '__main__':
    l = input().split()
    m = int(l[0])
    n =  m * 3

    lines = []

    above_center_line = (m // 2)

    for i in range(1, above_center_line+1):
        qto = ((n // 2) - (3 * i)) + 2
        lines.append('-' * qto + '.|.' * ((2 * i) - 1) + '-' * qto)

    print(*lines, sep='\n')
    print( ((n - 7) // 2) * '-'  + 'WELCOME'  + ((n - 7) // 2) * '-')
    lines.reverse()
    print(*lines, sep='\n')