#Для отображение цены в той же единице, что и указано
from decimal import Decimal
from django.conf import settings
from topikstore.models import Products

class Cart(object):

    def __init__(self, request):

        '''Инициализация корзины'''

        self.session = request.session
        cart = self.session.get(settings.CART_SESSION_ID)
        if not cart:
            #сохранить ПУСТУЮ корзину в сессии
            cart = self.session[settings.CART_SESSION_ID] = {}
        self.cart = cart

    def add(self, product, quantity=1,update_quantity=False):

        '''Метод для добавления товара в корзину
        update_quantity=False - добавить к существующему'''

        product_pk = str(product.pk)
        if product_pk not in self.cart:
            self.cart[product_pk] = {'quantity': 0,
                                    'price': str(product.price),}
        #Обновление кол-ва товара
        if update_quantity:
            self.cart[product_pk]['quantity'] = quantity
        else:
            self.cart[product_pk]['quantity'] += quantity
        self.save()

    def save(self):
        self.session.modified = True

    def remove(self, product):

        '''Удаление товара из корзины'''

        product_pk = str(product.pk)
        if product_pk in self.cart:
            del self.cart[product_pk]
            self.save()

    def __iter__(self):

        '''Для перебора товаров в корзине и получения из БД'''

        product_ids = self.cart.keys()
        #получаем товары и добавляем их в корзину
        products = Products.objects.filter(id__in=product_ids, available=True)
        print(self.cart)
        #cart = copy.deepcopy(self.cart)
        cart = self.cart.copy()
        print(cart)
        for product in products:
            cart[str(product.id)]['product'] = product

        for item in cart.values():
            item['price'] = Decimal(item['price'])
            item['total_price'] = item['price'] * item['quantity']
            yield item

    def __len__(self):

        '''Подсчет товаров в корзине'''

        return sum(item['quantity'] for item in self.cart.values())

    def get_total_price(self):

        '''Подсчет общей суммы'''

        return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())

    def clear(self):

        '''Очищение корзины в сессии'''

        del self.session[settings.CART_SESSION_ID]
        self.save()


import json
import logging
import polars as pl
import boto3

logger = logging.Logger(__name__)
logger.setLevel(logging.INFO)
sh = logging.StreamHandler()
sh.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(sh)

def messages_to_df(messages: list) -> pl.DataFrame:
    """Converts list of messages to a dataframe

    Args:
        messages (list): messages

    Returns:
        pl.DataFrame: dataframe
    """

    measurements = []
    for message in messages:
        body = json.loads(message["Body"])
        measurement = json.loads(body["Message"])
        measurements.append(measurement)

    df = pl.from_dicts(measurements)

    return df

def receive_messages(
    queue_url: str,
    region_name: str,
    max_nr_messages: int = 100000,
    visibility_timeout: int = 1800,
    page_size_messages: int = 10
    ) -> list:
    """Queries for messages on aws sqs

    Args:
        queue_url (str): url of the queue
        region_name (str): region name of the queue
        max_nr_messages (int, optional): Maximum nr of messages to receive. Defaults to 100000.
        visibility_timeout (int, optional): Visibility timeout for received messages. Defaults to 1800.
        page_size_messages (int, optional): Amount of messages to receive per call. Defaults to 10.

    Returns:
        list: received messages
    """

    # define sqs client
    sqs = boto3.client("sqs", region_name=region_name)
    messages = []
    messages_received = 0
    # receive messages until no more messages visible or mx nar messages received
    while messages_received < max_nr_messages:
        logger.warning(f"{messages_received} messages received...")
        # query queue
        response = sqs.receive_message(
            QueueUrl=queue_url,
            MaxNumberOfMessages=page_size_messages,
            VisibilityTimeout=visibility_timeout
            )

        # add message to message list
        if "Messages" in response:
            current_messages = response["Messages"]
            messages_received += len(current_messages)
            messages.extend(current_messages)
        else:
            logger.warning(f"no messages received...")
            break

    return messages


from snovault import collection, load_schema

from .base import Item as SMAHTItem

@collection(
    name='submission-centers',
    unique_key='submission_center:identifier',  # For shorthand reference as linkTo
    properties={
        'title': 'Submission Centers',
        'description': 'Listing of Submission Centers',
    })
class SubmissionCenter(SMAHTItem):
    """ Submission Center class """
    item_type = 'submission_center'
    schema = load_schema('encoded:schemas/submission_center.json')
    embedded_list = []


from numpy import ones, power

from .utils import BandedContinuum, Continuum, dry_air_number_density, P0, radiation_term, \
                   Spectrum, subgrid_bounds, T0

class CarbonDioxideContinuum(BandedContinuum):
    def __init__(self):
        self.bands = [CarbonDioxideHartmannContinuum(self.path),]

class CarbonDioxideHartmannContinuum(Continuum):
    """Carbon dioxide continuum coefficients.

    Attributes:
        data: Spectrum object containing data read from an input dataset.
        t_correction: Array of temperature correction coefficients.
        xfac_co2: Array of chi-factors.
    """
    def __init__(self, path):
        self.data = Spectrum(path, "bfco2")

        x = Spectrum(path, "tdep_bandhead")
        lower, upper = subgrid_bounds(self.data.grid, x.grid)
        self.t_correction = ones(self.data.data.size)
        self.t_correction[lower:upper + 1] = x.data[:]

        x = Spectrum(path, "x_factor_co2")
        lower, upper = subgrid_bounds(self.data.grid, x.grid)
        self.xfac_co2 = ones(self.data.data.size)
        self.xfac_co2[lower:upper + 1] = x.data[:]

    def spectra(self, temperature, pressure, vmr):
        nco2 = dry_air_number_density(pressure, temperature, vmr)*vmr["CO2"]
        rad = radiation_term(self.grid()[:], temperature)
        return \
            nco2*1.e-20*(pressure/P0)*(T0/temperature)*rad[:] * \
            self.xfac_co2[:]*power(temperature/246., self.t_correction[:]) * \
            self.data.data[:]

    def grid(self):
        return self.data.wavenumbers()


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

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

#data = pkl.load(file("TME6_lettres.pkl","rb"))
with open('TME6_lettres.pkl', 'rb') as f:
    data = pkl.load(f, encoding='latin1')
X = np.array(data.get('letters')) # récupération des données sur les lettres
Y = np.array(data.get('labels')) # récupération des étiquettes associées

# affichage d'une lettre
def tracerLettre(let):
    a = -let*np.pi/180; # conversion en rad
    coord = np.array([[0, 0]]); # point initial
    for i in range(len(a)):
        x = np.array([[1, 0]]);
        rot = np.array([[np.cos(a[i]), -np.sin(a[i])],[ np.sin(a[i]),np.cos(a[i])]])
        xr = x.dot(rot) # application de la rotation
        coord = np.vstack((coord,xr+coord[-1,:]))
    plt.figure()
    plt.plot(coord[:,0],coord[:,1])
    plt.savefig("exlettre.png")
    return

def discretise(Xcont, d):
    intervalle = 360 / d;
    return np.array([np.floor(x/intervalle) for x in Xcont]);

def groupByLabel( y):
    index = []
    for i in np.unique(y): # pour toutes les classes
        ind, = np.where(y==i)
        index.append(ind)
    return index;

def learnMarkovModel(Xc, d):
    #A = np.zeros((d,d))
    #Pi = np.zeros(d)
    A = np.ones((d,d))
    Pi = np.ones(d)
    for element in Xc:
        last = np.int(element[0]);
        Pi[last] += 1;
        for i in range(1, element.size):
            current = np.int(element[i]);
            A[last][current] += 1.0;
            last = current;

    A_norm = A/np.maximum(A.sum(1).reshape(d,1),1) # normalisation
    Pi = Pi/Pi.sum()
    return(Pi, A_norm)

def probaSequence(s,Pi,A):
    last = np.int(s[0]);
    proba = np.log(Pi[last]);
    for i in range(1,len(s)):
        current = np.int(s[i]);
        proba += np.log(A[last][current]);
        last = current;
    return proba;

def calculProba(d, Xlocal1, Ylocal1, Xlocal2):
    Xd1 = discretise(Xlocal1,d)  # application de la discrétisation
    Xd2 = discretise(Xlocal2,d)
    index = groupByLabel(Ylocal1)  # groupement des signaux par classe
    models = []
    for cl in range(len(np.unique(Ylocal1))): # parcours de toutes les classes et optimisation des modèles
        models.append(learnMarkovModel(Xd1[index[cl]], d))

    proba = np.array([
        [probaSequence(Xd2[i], models[cl][0], models[cl][1]) for i in range(len(Xlocal2))]
        for cl in range(len(np.unique(Ylocal1)))
    ])
    return (proba,models)

### Evaluation des performances ###

# Char à numero
proba, models = calculProba(20, X, Y, X)
Ynum = np.zeros(Y.shape);
for num,char in enumerate(np.unique(Y)):
    Ynum[Y==char] = num;

pred = proba.argmax(0);
print("teste avec le méme donnée")
print(np.where(pred != Ynum, 0.,1.).mean())

### Evalution juste ###

# separation app/test, pc=ratio de points en apprentissage
def separeTrainTest(y, pc):
    indTrain = []
    indTest = []
    for i in np.unique(y): # pour toutes les classes
        ind, = np.where(y==i)
        n = len(ind)
        indTrain.append(ind[np.random.permutation(n)][:int(np.floor(pc*n))])
        indTest.append(np.setdiff1d(ind, indTrain[-1]))
    return indTrain, indTest
# exemple d'utilisation
itrain,itest = separeTrainTest(Y,0.8)

def iTrain():
    ia = []
    for i in itrain:
        ia += i.tolist()
    it = []
    for i in itest:
        it += i.tolist()
    return (ia, it)

ia,it=iTrain()

# Char à numero
Ynum = np.zeros(Y[it].shape);
for num,char in enumerate(np.unique(Y)):
    Ynum[Y[it]==char] = num;

# change dimension et regarde l'effet sur les resultats
predictions = []
for d in range(10,90,10):
    Xd_test = discretise(X[it], d)

    proba = calculProba(d, X[ia], Y[ia], X[it])[0]

    pred = proba.argmax(0);
    print("teste avec le separation à training et test, d =",d)
    print(np.where(pred != Ynum, 0.,1.).mean())
    predictions.append(pred);

def visualise_conf(verite, prediction, Ylocal):
    conf = np.zeros((26,26))
    for cl in range (len(Ynum)):
        v = int(verite[cl])
        p = prediction[cl]
        conf[v][p] += 1

    plt.figure()
    plt.imshow(conf, interpolation='nearest')
    plt.colorbar()
    plt.xticks(np.arange(26),np.unique(Ylocal))
    plt.yticks(np.arange(26),np.unique(Ylocal))
    plt.xlabel(u'Vérité terrain')
    plt.ylabel(u'Prédiction')
    plt.savefig("mat_conf_lettres.png")

def prochaineEtat(dist):
    r = np.random.uniform()
    cs = dist.cumsum()
    i = 0
    while(cs[i] < r):
        i += 1
    return i

def generate(pi, model, N):
    liste = []
    current = prochaineEtat(pi)
    for i in range(N):
        liste.append(current)
        dist = model[current]
        current = prochaineEtat(dist)
    return liste

#Evaluation qualitative
pred = predictions[2] # d = 20
visualise_conf(Ynum, pred, Y);
#Modèle génératif
models = calculProba(d, X, Y, X)[1]
newa = generate(models[0][0],models[0][1], 25) # generation d'une séquence d'états
intervalle = 360./d # pour passer des états => valeur d'angles
newa_continu = np.array([i*intervalle for i in newa]) # conv int => double
tracerLettre(newa_continu)


import pytest

from mock import patch

from payit import Transaction, TransactionError, GatewayNetworkError
from payit.gateways import ZarinpalGateway

from tests.mockup.zarinpal_gateway import get_side_effect

config = {
    "merchant": "534534534532225234234",
    "description": "",
    "callback_url": "http://localhost/callback",
    "proxies": "socks5://127.0.0.1:9050",
}

def domock(sideeffect):
    return patch("payit.gateways.zarinpal.Client", side_effect=sideeffect)

def test_gateway():
    with domock(get_side_effect()):
        gateway = ZarinpalGateway(config=config)
        transaction = gateway.request_transaction(
            Transaction(amount=1000, order_id=1)
        )
        gateway.get_redirection(transaction)

        # validation
        valid_transaction = gateway.validate_transaction(
            {"Authority": "RETURNED_TOKEN", "Status": "OK"}
        )
        assert valid_transaction.validate_status

        invalid_transaction = gateway.validate_transaction(
            {"Authority": "RETURNED_TOKEN", "Status": "NOK"}
        )
        assert not invalid_transaction.validate_status

    # success verification
    with domock(get_side_effect(returned_status=100)):
        gateway.verify_transaction(transaction, dict())

    # verification fails
    with domock(get_side_effect(returned_status=300)):
        with pytest.raises(TransactionError):
            gateway.verify_transaction(transaction, dict())

    # verification already done
    with domock(get_side_effect(returned_status=101)):
        with pytest.raises(TransactionError):
            gateway.verify_transaction(transaction, dict())

    # verification network error
    with domock(get_side_effect(raise_zeep_error=True)):
        with pytest.raises(GatewayNetworkError):
            gateway.verify_transaction(transaction, dict())

    # no token
    with domock(get_side_effect(returned_token=None)):
        with pytest.raises(TransactionError):
            gateway.request_transaction(Transaction(amount=1000, order_id=1))

    # transation error
    with domock(get_side_effect(raise_zeep_fault=True)):
        with pytest.raises(TransactionError):
            gateway.request_transaction(Transaction(amount=1000, order_id=1))

    # gateway error
    with domock(get_side_effect(raise_zeep_error=True)):
        with pytest.raises(GatewayNetworkError):
            gateway.request_transaction(Transaction(amount=1000, order_id=1))


import pandas as pd
import string
from nltk.corpus import stopwords

def count_punctuation(df):
    # Counts the number of punctuations in the text
    count = lambda l1, l2: sum([1 for x in l1 if x in l2])
    df['count_punct'] = df.motivation.apply(lambda s: count(s, string.punctuation))
    df.to_csv(r'..\data\processed\motivation_liwc_meta.csv', index=False)

def count_stopwords(df):
    # Counts the number of stopwords in the text
    stopword_list = set(stopwords.words('Dutch'))
    df['count_stopwords'] = df['motivation'].str.split().apply(lambda x: len(set(x) & stopword_list))
    df.to_csv(r'..\data\processed\motivation_liwc_meta.csv', index=False)

# Add extra columns to the dataset
if __name__ == "__main__":
    # df = pd.read_csv(r'..\data\processed\liwc_results.csv')
    # print(count_punctuation(df))

    df = pd.read_csv(r'..\data\processed\motivation_liwc_meta.csv')
    count_stopwords(df)


#!/usr/bin/env python3
""" An evaluation script for MNASNet. """

import os
import typing
import collections

import torch
import torchvision.models as models
import numpy
import tqdm

import imagenet
import metrics
import log

IMAGENET_DIR = os.path.expanduser("~/datasets/imagenet")

def eval(model_name: str) -> None:
    if model_name == "mnasnet0_5":
        model = models.mnasnet0_5(num_classes=1000, pretrained=True).cuda()
    elif model_name == "mnasnet0_75":
        model = models.mnasnet0_75(num_classes=1000).cuda()
    elif model_name == "mnasnet1_0":
        model = models.mnasnet1_0(num_classes=1000, pretrained=True).cuda()
    elif model_name == "mnasnet1_3":
        model = models.mnasnet1_3(num_classes=1000).cuda()
    else:
        raise ValueError("Don't know how to evaluate {}".format(model_name))

    loss = torch.nn.CrossEntropyLoss().cuda()
    val_dataset = imagenet.validation(IMAGENET_DIR)
    val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=512,
                                             shuffle=False, num_workers=8,
                                             pin_memory=True)
    all_metrics = metrics.default()

    model.eval()
    with torch.no_grad():
        val_losses = []
        metric_dict = collections.defaultdict(list)
        for batch_index, (inputs, truth) in enumerate(tqdm.tqdm(val_loader)):
            outputs = model(inputs.cuda()).cpu()
            val_losses.append(loss(outputs, truth).item())
            for name, metric_fn in all_metrics:
                metric_dict[name].append(metric_fn(outputs, truth))

        print(
            numpy.mean(val_losses),
            list([(name, numpy.mean(vals))
                  for name, vals in metric_dict.items()]))

if __name__ == "__main__":
    for m in ["mnasnet1_0", "mnasnet0_5"]:
        print("Evaluating pretrained", m)
        eval(m)


# Импортируем необходимые компоненты
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from settings import TG_TOKEN
from handlers import *
import logging

logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',
                    level=logging.INFO,
                    filename='bot.log')

# Создаем (объявляем) функцию main, которая соединяется с платформой Telegram
def main():
    my_bot = Updater(TG_TOKEN, use_context=True)
    logging.info('Start bot')
    my_bot.dispatcher.add_handler(CommandHandler('start', sms))    # обработчик команды \start

    my_bot.dispatcher.add_handler(MessageHandler(Filters.text, parrot))    # обработчик тектового сообщения

    my_bot.start_polling()  # проверяет о наличии сообщений с платформы Telegram
    my_bot.idle()   # бот будет работать по его не остановят

if __name__ == '__main__':
    main()


import json
import boto3
import os
import requests
import openai

BUCKET_NAME='minutes-prod-contents'

s3 = boto3.resource('s3')

def main(event, context):
    print('ðŸ”¥')
    print(event)
    fname = "/tmp/leothefootball"
    openai.api_key = get_parameter()
    event_object = event['Records'][0]['s3']['object']['key']
    bucket = s3.Bucket(BUCKET_NAME)
    bucket.download_file(event_object, '/tmp/hoge.m4a')
    audio_file = open('/tmp/hoge.m4a', "rb")
    transcript = openai.Audio.transcribe("whisper-1", audio_file)
    txt = "\n".join(transcript['text'].split())
    f = open(fname + ".txt", "w")
    f.write(txt)
    f.close()
    upload(fname + ".txt")

def get_parameter():
    end_point = 'http://localhost:2773'
    path = '/systemsmanager/parameters/get/'
    query_parameter = '?name=/minutes/prod/OPENAI_API_KEY&withDecryption=true'
    url = end_point + path + query_parameter
    headers = {
        'X-Aws-Parameters-Secrets-Token': os.environ['AWS_SESSION_TOKEN']
    }
    res = requests.get(url, headers=headers)
    return res.json()['Parameter']['Value']

def upload(file):
    response = s3.Object(BUCKET_NAME, f'documents/{os.path.basename(file)}').upload_file(file)
    return response

if __name__ == "__main__":
  event = { 'data': '', 'part': '0' }
  main(event, '')


import json
import os
import shlex
import shutil
from subprocess import list2cmdline

import click

from .github import Github

# default paths
objection_path = os.path.join(os.path.expanduser('~'), '.objection')
gadget_versions = os.path.join(objection_path, 'gadget_versions')

def list2posix_cmdline(seq):
    """
        Translate a sequence of arguments into a command line
        string.

        Implemented using shlex.quote because
        subprocess.list2cmdline doesn't work with POSIX
    """

    return ' '.join(map(shlex.quote, seq))

class BasePlatformGadget(object):
    """ Class with base methods for any platforms Gadget downloaded """

    def __init__(self, github: Github) -> None:
        """
            Build a new instance with an existing Github instance.

            :param github:
        """

        self.github = github

    @staticmethod
    def get_local_version(gadget_type: str) -> str:
        """
            Check and return the local version of the FridaGadget
            type we have.

            :return:
        """

        if not os.path.exists(gadget_versions):
            return '0'

        with open(gadget_versions, 'r') as f:
            versions = f.read()

        # load the json.
        try:

            versions = json.loads(versions)

        except json.decoder.JSONDecodeError:
            return '0'

        if gadget_type in versions:
            return versions[gadget_type]

        return '0'

    def set_local_version(self, gadget_type: str, version: str):
        """
            Writes the version number to file, recording it as
            the current local version.

            :param gadget_type:
            :param version:
            :return:
        """

        # read the current versions if it exists, else start
        # a new dictionary for it
        if os.path.exists(gadget_versions):

            # load the json from disk
            try:

                with open(gadget_versions, 'r') as f:
                    versions = json.loads(f.read())

            except json.decoder.JSONDecodeError:
                versions = {}

        else:
            versions = {}

        # add the new version
        versions[gadget_type] = version

        # and write it to file
        with open(gadget_versions, 'w') as f:
            f.write(json.dumps(versions))

        return self

class BasePlatformPatcher(object):
    """ Base class with methods used by any platform patcher. """

    # extended classes should fill this property
    required_commands = {}

    def __init__(self):

        # check dependencies
        self.have_all_commands = self._check_commands()
        self.command_run_timeout = 60 * 5

        if os.name == 'nt':
            self.list2cmdline = list2cmdline
        else:
            self.list2cmdline = list2posix_cmdline

    def _check_commands(self) -> bool:
        """
            Check if the shell commands in required_commands are
            available.

            :return:
        """

        for cmd, attributes in self.required_commands.items():

            location = shutil.which(cmd)

            if location is None:
                click.secho('Unable to find {0}. Install it with: {1} before continuing.'.format(
                    cmd, attributes['installation']), fg='red', bold=True)

                return False

            self.required_commands[cmd]['location'] = location

        return True

    def are_requirements_met(self):
        """
            Checks if the command requirements have all been met.

            :return:
        """

        return self.have_all_commands


#The problem I was presented as a kata from codewars.com:
#solved in python 2.7

#Complete the solution so that it strips all text that follows any of a set of comment markers passed in.
#Any whitespace at the end of the line should also be stripped out.
#
#Example:
#
#iven an input string of:
#
#apples, pears # and bananas
#grapes
#bananas !apples
#The output expected would be:
#
#apples, pears
#grapes
#bananas

def solution(string,markers):
	newString = ''
	flag = 0
	for i in string:
		if i in ''.join(markers):
			newString = newString.rstrip(" ")
			flag = 1
		elif i == '\n':
			newString = newString.rstrip(" ")
			flag = 0
		if flag == 0:
			newString += i
	return newString


import re
import numpy as np

with open('i05.txt') as file:
    data = [list(map(int, re.split(r'\D+', l.strip())))
            for l in file.readlines()]

s = np.zeros((1000, 1000), dtype=np.int32)
d = np.zeros((1000, 1000), dtype=np.int32)
for x1, y1, x2, y2 in data:
    xs, xl = sorted([x1, x2])
    ys, yl = sorted([y1, y2])
    if y1 == y2:
        s[y1, xs:xl + 1] += 1
    elif x1 == x2:
        s[ys:yl + 1, x1] += 1
    else:
        d[ys:yl + 1, xs:xl + 1] += np.rot90(np.identity(
            xl - xs + 1, dtype=np.int32), 1 if (x1 > x2) != (y1 > y2) else 0)

print('Part 1:', np.sum(s > 1))
print('Part 2:', np.sum(s + d > 1))


import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkcalendar import*
import sqlite3
import connectDB

#Window
r = tk.Tk()
r.title('Quản lý sân bóng mini')
r.geometry('800x500')
r.resizable(False,False)
frm=Frame(r)
frm.pack(side=tk.LEFT)

Label(frm,text='QUẢN LÝ SÂN BÓNG MINI',fg='green',font=('cambria',14),width=25).pack()

#TreeView
style = ttk.Style()
style.theme_use('clam')
tree=ttk.Treeview(frm,columns=(1,2,3,4,5,6,7,8),show='headings',height='7')
for i in range(1,9):
    tree.column(i,anchor='center',width=100)
tree.heading(1,text='Tên Khách hàng')
tree.heading(2,text='Số điện thoại')
tree.heading(3,text='Tên sân')
tree.heading(4,text='Start(h)')
tree.heading(5,text='Start(m)')
tree.heading(6,text='Stop(h)')
tree.heading(7,text='Stop(m)')
tree.heading(8,text='Ngày đặt sân')
#Load Table
rows = connectDB.show_data()

#Load DB
for i in rows:
    tree.insert('','end',iid=i[0],values=i)

tree.pack()

def delete():
    selected = tree.selection()[0]
    query = 'delete from khach_hang where id = ?'
    data = (selected,)
    q_del = connectDB.connection.cursor()
    q_del.execute(query,data)
    connectDB.connection.commit()
    tree.delete(selected)

#insert button
b1=tk.Button(frm,text='DELETE',bg='yellow',width=20,command=delete)
b1.pack(pady=5)
b2=tk.Button(frm,text='EXIT',bg='yellow',width=20,command=exit)
b2.pack(pady=5)

r.mainloop()


import random

def get_words():
    resultado = []
    with open('palavras.txt', 'rt', encoding='utf-8') as palavras:
        for palavra in palavras:
            resultado.append(palavra)
    return resultado

def get_termo():
    return random.choice(get_words())

def verificar(palavra, palpite):
    mensagens = [f'O palpite foi {palpite}']
    if palavra == palpite+'\n':
        mensagens.append('Venceu')
    else:
        for i in range(5):
            if palavra[i] == palpite[i]:
                mensagens.append(f'A letra {palpite[i]} está na posição correta')
            elif palpite[i] in palavra:
                mensagens.append(f'A letra {palpite[i]} está na palavra, mas na posição incorreta')
            else:
                mensagens.append(f'A letra {palpite[i]} não está na palavra')

    for mensagem in mensagens:
        print(mensagem)

def verificar_automatico(palavra, palpite, informacoes):
    print(f'O palpite é {palpite}')
    for i in range(5):
        if palavra[i] == palpite[i]:
            print(f'A letra {palpite[i]} está na posição correta')
            informacoes[palpite[i]] = {'esta': True, 'posicao': i}
        elif palpite[i] in palavra:
            print(f'A letra {palpite[i]} está na palavra, mas na posição incorreta')
            if palpite[i] in list(informacoes.keys()):
                if 'posicao' not in list(informacoes[palpite[i]].keys()):
                    informacoes[palpite[i]]['posicao_nao'].append(i)
            else:
                informacoes[palpite[i]] = {'esta': True, 'posicao_nao': [i]}
        else:
            print(f'A letra {palpite[i]} não está na palavra')
            informacoes[palpite[i]] = {'esta': False}

    if palavra == palpite:
        print('Venceu')

def get_word_by_info(palavra):
    result = True
    for letra in informacoes:
        value = informacoes[letra]
        chaves = value.keys()

        #verificar letras que estão
        if value['esta']:
            # se a letra deve estar na palavra, mas não está, então não pode ser
            if letra not in palavra:
                result = False
            # se a posição da letra atual é conhecida e a letra na mesma posição na palavra é diferente, então não pode ser
            elif 'posicao' in chaves and letra != palavra[value['posicao']]:
                result = False
            # se a posição da letra atual coincide com algum indice da lista posicao não, então não pode ser
            elif 'posicao_nao' in chaves:
                for indice in value['posicao_nao']:
                    if letra == palavra[indice]:
                        result = False
        #verifica letras que não estão
        elif letra in palavra:
            result = False

    return result

def get_palpite():
    palavras = get_words()
    validas = list(filter(get_word_by_info, palavras))
    return random.choice(validas)

def preenche_info():
    nova_informacao = int(input("Quantos novos dados você conseguiu? "))
    for i in range(nova_informacao):
        letra = input("Informe a letra: ")
        dados = {'posicao_nao': []}
        if letra in informacoes.keys():
            dados = informacoes[letra]
        esta = input("A letra está na palavra? s/n") == 's'
        dados['esta'] = esta
        if esta:
            if input("Acertou a posição? s/n") == 's':
                dados['posicao'] = int(input("Informe a posição da letra: "))-1
            else:
                dados['posicao_nao'].append(int(input("Informe a posição em que a letra não está: "))-1)
        informacoes[letra] = dados

palavras = get_words()

# MODO auxílio
# informacoes = {}
# for i in range(6):
#     print(get_palpite())
#     preenche_info()

# MODO máquina contra máquina
# informacoes = {}
# palavra = get_termo()
# for i in range(6):
#     verificar_automatico(palavra, get_palpite(), informacoes)

# MODO máquina contra humano
# informacoes = {}
# while True:
#     palavra = input("Escolha uma palavra válida de 5 letras")
#     if palavra+'\n' in palavras:
#         break
# for i in range(6):
#     verificar_automatico(palavra, get_palpite(), informacoes)

# MODO humano contra máquina
# palavra = get_termo()
# for i in range(6):
#     while True:
#         palpite = str(input("Informe o palpite: "))
#         if palpite+'\n' in palavras:
#             break
#     verificar(palavra, palpite)
# print(palavra)


from __future__ import print_function

import errno
import os
import platform
import subprocess
import sys
import unittest

import mock

import tox_pyenv

try:
    unicode
except NameError:
    unicode = str

def touni(s, enc='utf8', err='strict'):
    if isinstance(s, bytes):
        return s.decode(enc, err)
    else:
        return unicode(s or ("" if s is None else s))

class MockTestenvConfig(object):
    def __init__(self, basepython):
        self.basepython = basepython
        self.tox_pyenv_fallback = True

class TestToxPyenvNoPyenv(unittest.TestCase):

    def setUp(self):
        def _mock_popen_func(cmd, *args, **kw):
            if all(x in cmd for x in ['which', '*TEST*']):
                raise OSError(errno.ENOENT, 'No such file or directory')
            self.fail('Unexpected call to Popen')
            # return self.popen_patcher.temp_original(*args, **kw)
        self.popen_patcher = mock.patch.object(
            tox_pyenv.subprocess, 'Popen', autospec=True,
            side_effect=_mock_popen_func,
        )
        self.popen_patcher.start()
        self.warning_patcher = mock.patch.object(
            tox_pyenv.LOG, 'warning', autospec=True,
        )
        self.warning_patcher.start()

    def tearDown(self):
        self.popen_patcher.stop()
        self.warning_patcher.stop()

    def test_logs_if_no_pyenv_binary(self):
        mock_test_env_config = MockTestenvConfig('*TEST*')
        tox_pyenv.tox_get_python_executable(mock_test_env_config)
        expected_popen = [
            mock.call(
                [mock.ANY, 'which', '*TEST*'],
                stderr=-1, stdout=-1,
                universal_newlines=True
            )
        ]
        self.assertEqual(
            tox_pyenv.subprocess.Popen.call_args_list,
            expected_popen
        )
        expected_warn = [
            mock.call("pyenv doesn't seem to be installed, you "
                      "probably don't want this plugin installed either.")
        ]
        self.assertEqual(tox_pyenv.LOG.warning.call_args_list, expected_warn)

class TestThings(unittest.TestCase):

    def test_the_answer(self):

        self.assertEqual(42, 42)

    def test_is_precisely_correct_version(self):

        toxenvname = 'TOX_%s' % os.environ['TOX_ENV_NAME'].upper().strip()
        expected_string = os.environ[toxenvname].strip(' "\'')
        print('\n\nTOX ENV NAME: %s' % toxenvname)
        if platform.python_implementation() == 'PyPy':
            actual_list = [str(_).strip() for _ in sys.pypy_version_info[:3]]
            expected_string = expected_string.split('-')[1].strip(' "\'')
            print('\nExpected version for this tox env: PyPy %s'
                  % expected_string)
            print('Actual version for this tox env: PyPy %s'
                  % '.'.join(actual_list))
        else:
            print('\nExpected version for this tox env: Python %s'
                  % expected_string)
            print('Actual version for this tox env: Python %s'
                  % platform.python_version())
            actual_list = list(platform.python_version_tuple())
        expected_list = expected_string.split('.')

        print('\n\nPYTHON VERSION (verbose)')
        print('*************************')
        print(sys.version)
        print('\n')
        self.assertEqual(actual_list, expected_list)

    def test_what_python(self):

        print('\nwhich python')
        subprocess.call('which python', stderr=subprocess.STDOUT, shell=True)
        print('\ntype python')
        subprocess.call('type python', stderr=subprocess.STDOUT, shell=True)
        print('\nwhereis python')
        subprocess.call('whereis python', stderr=subprocess.STDOUT, shell=True)
        print('\n')

if __name__ == '__main__':

    unittest.main(verbosity=3)


import math
import time

def divisors_count(number):
    count = 0
    for i in range(1, math.isqrt(number) + 1):
        if number % i == 0:
            count += 1 if number // i == i else 2
    return count

def solve():
    triangle = 1
    step = 2
    while True:
        if divisors_count(triangle) > 500:
            return triangle
        triangle += step
        step += 1

srt = time.time()
answer = solve()
end = time.time()
print(answer)
print(f"Took {end - srt} seconds to execute...")


class Evaluator():
    @classmethod
    def zip_evaluate(cls, coefs, words):
        if len(coefs) != len(words):
            return -1
        ret = 0
        for word, weight in zip(words, coefs):
            ret = ret + (len(word) * weight)
        return ret

    @classmethod
    def enumerate_evaluate(cls, coefs, words):
        if len(coefs) != len(words):
            return -1
        ret = 0
        for i, word in enumerate(words):
            ret = ret + (len(word) * coefs[i])
        return ret

words = ["Le", "Lorem", "Ipsum", "est", "simple"]
coefs = [1.0, 2.0, 1.0, 4.0, 0.5]
print(Evaluator.zip_evaluate(coefs, words))
print(Evaluator.enumerate_evaluate(coefs, words))
words.append("n")
print(Evaluator.zip_evaluate(coefs, words))
print(Evaluator.enumerate_evaluate(coefs, words))


#!/user/bin/env python
# encoding: utf-8
"""
@author: zwnong
@project: HogwartsSDE17
@file: base_page.py
@time: 2021/3/9 21:52
"""
import os
from time import sleep

import yaml
from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.wait import WebDriverWait
from decorator.handle_black_list import handle_black
from utils.get_file import GetFile
from utils.logger import log

class BasePage:
    def __init__(self, driver: WebDriver = None):
        self.driver = driver

    @handle_black
    def find(self, locator, element):
        """
        重构查找元素
        :param locator: 定位方式
        :param element: 元素信息
        :return:
        """
        # appium_log.debug('find' + element)
        return WebDriverWait(self.driver, 10, 0.1).until(lambda x: x.find_element(locator, element))
        # return self.driver.find_element(locator, element)
        # black_list = ['//android.widget.TextView[@resource-id="com.xueqiu.android:id/tv_agree" and @text="同意"]',
        #               '//android.widget.TextView[@resource-id="com.xueqiu.android:id/tv_left" and @text="取消"]']
        # try:
        #     return self.driver.find_element(locator, element)
        # except Exception:
        #         for i in black_list:
        #             ele_path = self.finds(locator, i)
        #             if len(ele_path) > 0:
        #                 ele_path[0].click()
        #         return self.find(locator, element)
        # black_list = ['//android.widget.TextView[@resource-id="com.xueqiu.android:id/tv_agree" and @text="同意"]',
        #               '//android.widget.TextView[@resource-id="com.xueqiu.android:id/tv_left" and @text="取消"]']
        # try:
        #     return self.driver.find_element(locator, element)
        # except Exception:
        #     for i in black_list:
        #         ele_path = self.finds(locator, i)
        #         if len(ele_path) > 0:
        #             ele_path[0].click()
        #             return self.find(locator, element)

    def find_and_click(self, locator, element):
        """
        重构查找元素并点击
        :param locator: 定位方式
        :param element: 元素信息
        :return:
        """
        self.find(locator, element).click()

    def find_and_sendkeys(self, locator, element, value):
        return self.find(locator, element).send_keys(value)

    def finds(self, locator, value):
        return self.driver.find_elements(locator, value)

    def web_driver_wait(self, locator, value):
        return WebDriverWait(self.driver, 10, 0.1).until(lambda x: x.find_element(locator, value))

    # def get_yaml_data(self, file_path=None, value=None):
    #     if file_path is None:
    #         self.file_path = r'../config\data.yaml'
    #     else:
    #         self.file_path = file_path
    #     data = yaml.safe_load(open(str(self.file_path), 'r', encoding='utf-8'))
    #     try:
    #         value = data.get()
    #     except EOFError:
    #         value = None
    #     return value

    def lunch_driver(self):
        self.driver.launch_app()

    # 获取屏幕的宽高
    def get_size(self):
        size = self.driver.get_window_size()
        width = size['width']
        height = size['height']
        return width, height

    # 向左边滑动
    def swipe_left(self):
        # [100,200]
        x1 = self.get_size()[0] / 10 * 9
        y1 = self.get_size()[1] / 2
        x = self.get_size()[0] / 10
        self.driver.swipe(x1, y1, x, y1, 2000)

    # 向右边滑动
    def swipe_right(self):
        # [100,200]
        x1 = self.get_size()[0] / 10
        y1 = self.get_size()[1] / 2
        x = self.get_size()[0] / 10 * 9
        self.driver.swipe(x1, y1, x, y1, 2000)

    # 向上滑动
    def swipe_up(self):
        # [100,200]direction
        x1 = self.get_size()[0] / 2
        y1 = self.get_size()[1] / 10 * 9
        y = self.get_size()[1] / 10
        self.driver.swipe(x1, y1, x1, y, 2000)

    # 向下滑动
    def swipe_down(self):
        x1 = self.get_size()[0] / 2
        y1 = self.get_size()[1] / 10
        y = self.get_size()[1] / 10 * 9
        self.driver.swipe(x1, y1, x1, y, 2000)

    def swipe_on(self, direction=None):
        if direction == 'up':
            self.swipe_up()
        elif direction == 'down':
            self.swipe_down()
        elif direction == 'left':
            self.swipe_left()
        else:
            self.swipe_right()

    @handle_black
    def swipe_find(self, function_name, num=10, file_path=None):
        """
        # 上下滑动查找元素
        :param file_path:
        :param function_name:
        :param num:
        :return:
        """
        if file_path is None:
            file_path = fr'{self.father_path()}\yaml\main_page.yml'
        else:
            file_path = file_path
        get_file = GetFile(file_path)
        elements = get_file.get_value(function_name)
        for element in elements:
            for i in range(num):
                if i == num - 1:
                    self.driver.implicitly_wait(5)
                    raise NoSuchElementException(f'滑动{num}次，没找到元素')

                self.driver.implicitly_wait(1)
                try:
                    # 查找元素并点击
                    # return self.find_and_click(MobileBy.XPATH,element.get('element'))
                    return self.driver.find_element(MobileBy.XPATH, element.get('element')).click()

                    # 仅返元素是否为真
                    # element = self.driver.find_element(MobileBy.XPATH, element.get('element'))
                    # self.driver.implicitly_wait(5)
                    # return element
                except Exception:
                    self.swipe_up()

    def parse(self, yaml_path, fun_name):
        """
        # 解析关键字 解析yaml文件并调用相应的方法 实现相应功能
        :param yaml_path: yaml文件路径
        :param fun_name: yaml文件定义的方法名
        :return:
        """
        with open(yaml_path, 'r', encoding='utf-8') as f:
            functance = yaml.load(f)
        steps = functance.get(fun_name)
        for step in steps:
            if step.get('action') == 'find_and_click':
                self.find_and_click(step.get('locator'), step.get('element'))
            elif step.get('action') == 'find_and_sendkeys':
                self.find_and_sendkeys(step.get('locator'), step.get('element'), step.get('contents'))

    def screenshot(self):
        return self.driver.get_screenshot_as_png()

    def get_web_view(shelf, driver):
        webview = driver.contexts
        for viw in webview:
            if 'WEBVIEW_cn.com.open.mooc' in viw:
                driver.switch_to.context(viw)
                break
        driver.find_element_by_link_text('C').click()
        try:
            driver.find_element_by_id('cn.com.open.mooc:id/left_icon').click()
        except Exception as e:
            driver.switch_to.context(webview[0])
            driver.find_element_by_id('cn.com.open.mooc:id/left_icon').click()
            raise e

    def pwd_path(self):
        return os.getcwd()

    def father_path(self):
        father_path = os.path.abspath(os.path.dirname(self.pwd_path()) + os.path.sep + ".")
        return father_path

    def grader_father_path(self):
        grader_father_path = os.path.abspath(os.path.dirname(self.pwd_path()) + os.path.sep + "..")
        return grader_father_path

    def get_yml_value(self, file_path, *args):
        return GetFile(file_path=file_path).get_value(args)

    def isElement(self, locator, ele):
        """
        Determine whether elements exist
        Usage:
        isElement(By.XPATH,"//a")
        """
        sleep(1)
        flag = None
        try:
            if locator == "id":
                # self.driver.implicitly_wait(60)
                self.driver.find_element_by_id(ele)
            elif locator == "xpath":
                # self.driver.implicitly_wait(60)
                self.driver.find_element_by_xpath(ele)
            elif locator == "class":
                self.driver.find_element_by_class_name(ele)
            elif locator == "link text":
                self.driver.find_element_by_link_text(ele)
            elif locator == "partial link text":
                self.driver.find_element_by_partial_link_text(ele)
            elif locator == "name":
                self.driver.find_element_by_name(ele)
            elif locator == "tag name":
                self.driver.find_element_by_tag_name(ele)
            elif locator == "css selector":
                self.driver.find_element_by_css_selector(ele)
            flag = True
        except NoSuchElementException as e:
            flag = False
        finally:
            return flag


from django.shortcuts import render
#getting the Http Responce on template
from django.http import HttpResponse

from .forms import  StudnetRegisterForm,UserForm
from django.views import  generic
from .models import  StudentRegister
from django.urls import reverse_lazy
#filtering Student Objects
from .filters import Searchfilter

#StudentForm Details and User Deatils
class StudentReg(generic.TemplateView):
    template_name='register.html'
    def get(self,request):
        context = {
            'student': StudnetRegisterForm,
            'user': UserForm
          }
        return render(request,self.template_name,context)

    def post(self,request):
        user_form = UserForm(data=request.POST)
        profile_form = StudnetRegisterForm(data=request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            return   HttpResponse("sucess")

#get the all the StudentDetails

class StudentDetails(generic.ListView):
    model=StudentRegister

    def get_context_data(self,**kwargs):
        context=super().get_context_data(**kwargs)
        context['filter'] = Searchfilter(self.request.GET, queryset=self.get_queryset())
        return  context

#update the all the StudentDetails

class StudentUpdate(generic.UpdateView):
    model =StudentRegister
    fields = '__all__'
    success_url = reverse_lazy('stu_list')

#delete the all the StudentDetails

class StudentDelete(generic.DeleteView):
    model =StudentRegister
    success_url = reverse_lazy('stu_list')


#!/usr/bin/env python3

from argparse import ArgumentParser
import os

import pandas as pd
import seaborn as sns

def plot_empirical_cdf(df, field):
    df = df.copy()
    df["cancer"] = df["cancer"].map(lambda x: "Case" if x else "Control")
    df = df.rename(columns={"cancer": "group"})
    g = sns.FacetGrid(df, hue="group")
    g.map(sns.distplot, field)
    g.add_legend()
    return g

def compute_code_counts(df):
    # only care about unique counts since features are binary
    cts = df.groupby(["UID", "cancer"])["diag_cd"].agg(lambda x: len(set(x)))
    cts = cts.to_frame(name="ct")
    cts = cts.reset_index()
    return cts

def compute_time_intervals(df):
    time = df.groupby(["UID", "cancer"])["date"].agg(lambda x: max(x) - min(x))
    time = time.to_frame(name="time_interval")
    time = time.reset_index()
    return time

def get_args():
    parser = ArgumentParser(
        description=
        "Plot distribution of unique codes counts and time interval (i.e. history length)"
    )
    parser.add_argument("--input", type=str, help="Input feather dataframe")
    parser.add_argument(
        "--output_dir",
        type=str,
        help="Path to output directory",
    )
    return parser.parse_args()

def main():
    args = get_args()
    df = pd.read_feather(args.input)

    if not os.path.exists(args.output_dir):
        os.makedirs(args.output_dir)

    df_codes = compute_code_counts(df)
    ax_codes = plot_empirical_cdf(df_codes, "ct")
    ax_codes.set_xlabels("# Diagnosis Codes")
    ax_codes.set_ylabels("Empirical CDF (patients)")
    codes_plot_path = os.path.join(args.output_dir, "code_ct_distribution.pdf")
    ax_codes.savefig(codes_plot_path)

    df_time = compute_time_intervals(df)
    ax_time = plot_empirical_cdf(df_time, "time_interval")
    ax_time.set_xlabels("Time interval of medical history (days)")
    ax_time.set_ylabels("Empirical CDF (patients)")
    time_plot_path = os.path.join(args.output_dir,
                                  "time_interval_distribution.pdf")
    ax_time.savefig(time_plot_path)

if __name__ == "__main__":
    try:
        main()
    except Exception as err:
        import pdb
        pdb.post_mortem()


import datetime
import numbers
import time

class UnboundField(object):
    """
        Uninitialized version of all field objects, which records in what order
        it was initialized.  This is primarily used to ensure each time a new
        Model instance is initialized a new field object is created, rather
        than having to worry about invoking Field.__copy__() and worrying about
        any changes that might have happened to the original instance attached
        to the Model class.
    """
    idx = 0

    def __init__(self, cls, **kwargs):
        self.field_type = cls
        self.kwargs = kwargs
        UnboundField.idx += 1
        self.idx = UnboundField.idx

    def bind(self, name, trans_name, owner):
        kwargs = dict(self.kwargs)
        kwargs.update({'_name': name, '_trans_name': trans_name,
                       '_owner': owner})
        instance = self.field_type(**kwargs)
        instance.idx = self.idx
        instance.unbound_field = self
        setattr(owner.c, name, instance)

class MetaField(type):
    """
        Returns an unbound field if we don't know all the information about
        the field yet.
    """
    def __call__(cls, **kwargs):
        if len({'_trans_name', '_owner', '_name'} & set(kwargs.keys())) == 3:
            instance = cls.__new__(cls)
            instance.__init__(**kwargs)
            return instance
        else:
            return UnboundField(cls, **kwargs)

class Field(object):
    """
        Basic Field object, to be attached to models
    """
    __metaclass__ = MetaField

    @property
    def value(self):
        if self._idx != self.owner.current_idx:
            self._value = self.owner._records[self.owner.current_idx]
            self._value = self.to_python(self._value)
            self._idx = self.owner.current_idx

        return self._value

    @value.setter
    def value(self, val):
        if self._value != val:
            self._changed = True
            self._value = val

    def __init__(self, default=None, null=False, **kwargs):
        self.default = default
        self.null = null
        self._idx = None
        self._changed = False
        self._value = None

    def to_python(self, val):
        return value

    def to_db(self, val):
        return value

class Integer(Field):
    def __init__(self, length=None, unsigned=False, autoincrement=False, **kwargs):
        super(Integer, self).__init__(**kwargs)
        self.length = length
        self.unsigned = unsigned
        self.autoincrement = autoincrement

class TinyInt(Integer):
    pass

class SmallInt(Integer):
    pass

class MediumInt(Integer):
    pass

class BigInt(Integer):
    pass

class UnixTimestamp(Integer):
    def to_python(self, val):
        """
            Attempts to return a datetime object when returning data from
            the database, should throw a TypeError if the conversion fails.
        """
        return datetime.datetime.fromtimestamp(val)

    def to_db(self, val):
        """
            Attempts to convert the object to an int() if possible, except
            when the object happens to be an expression/column/model from
            the ORM, in which case the original value is returned, as that
            indicates it is an expression that the db will need to evaluate
            when the query is actually executed.
        """
        if isinstance(val, numbers.Integral) or hasattr(val, 'token_type'):
            return val
        elif hasattr(val, 'timetuple'):
            return int(time.mktime(val.timetuple()))
        else:
            return int(val)

class Decimal(Field):
    def __init__(self, precision=None, scale=None, unsigned=False, **kwargs):
        super(Field, self).__init__(self, **kwargs)
        self.precision = precision
        self.scale = scale
        self.unsigned = unsigned

class Char(Field):
    def __init__(self, length=None, **kwargs):
        super(Field, self).__init__(self, **kwargs)
        self.length = length

class Timestamp(Field):
    def __init__(self, on_update=None, **kwargs):
        super(Field, self).__init__(self, **kwargs)
        self.on_update = on_update


import spidev, time
spi = spidev.SpiDev()
spi.open(0, 0)
def analog_read(channel):
    r = spi.xfer2([1, (8 + channel) << 4, 0])
    adc_out = ((r[1]&3) << 8) + r[2]
    return adc_out
while True:
    adc_arus = analog_read(0)
    adc_tegangan = analog_read(1)
    adc_resistansi = analog_read(2)

    #Pengukuran arus
    Vadc_arus = adc_arus * 3.3 / 1024
    R_arus = 10 # Resistor sensor arus
    I_ukur = Vadc_arus/R_arus # Rumus arus dalam ampere
    I_mili = I_ukur*1000 #ARumus arus dalam miliampere

    #Pengukuran tegangan
    Vadc_tegangan = adc_tegangan * 3.3 / 1024
    R1 = 100000 # Resistor R1=100kohm
    R2 = 1000 # Resistor R2=1kohm
    V_ukur = Vadc_tegangan*(R1+R2)/R2 # Rumus tegangan dalam volt

    #Pengukuran resistansi
    Vadc_resistansi = adc_resistansi * 3.3 / 1024
    Vcc = 3.3
    R_sensor = 1000 # Resistor Sensor R_sensor=1kohm
    R_ukur = R_sensor/((Vcc/Vadc_resistansi)-1) # Rumus Resistansi dalam ohm

    print("Arus(mA)=%f\tTegangan(Volt)=%f\tResistansi(Ohm)=%f" % (I_mili, V_ukur, R_ukur))
    time.sleep(1)


from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
print(views)
urlpatterns = [
# ex: /polls/
	url(r'^$', views.indexView.as_view(), name = 'index'),
    #url(r'^polls/$', views.index, name='index'),
    # ex: /polls/5/
    url(r'^polls/(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
    # ex: /polls/5/results/
    url(r'^polls/(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
    # ex: /polls/5/vote/
    url(r'^polls/(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]


import torch
import torchvision
import torchvision.transforms as transforms
import numpy as np

batch_size = 128

# transforms
transforms = transforms.Compose([
    transforms.RandAugment(),
    transforms.ToTensor(),
    transforms.Normalize((0.5,), (0.5,)),

])

train_dataset = torchvision.datasets.MNIST(root='./data', train=True, transform=transforms, download=False)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)

def add_noise(image, noise_factor=0.5) :
    # noise_factor -> 잡음의 정도를 결정 하는 인자
    noisy_images = image + noise_factor * torch.rand_like(image)
    noisy_images = torch.clamp(noisy_images, -1, 1)

    return noisy_images

for images, _ in train_loader :
    print(images.shape)

    noisy_images = add_noise(images)
    break

import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(np.transpose(torchvision.utils.make_grid(images[:8], padding=2, normalize=True), (1,2,0)))
axes[0].set_title('Original Images')
axes[0].axis('off')

axes[1].imshow(np.transpose(torchvision.utils.make_grid(noisy_images[:8], padding=2, normalize=True), (1,2,0)))
"""
RGB 이미지의 경우는 일반적으로 높이 너비 채널 순가지고요
그레이 높이 너비 즉 높이, 너비, 채널 형식의 이미지를 시각화할때 (1, 2, 0),오르 np.transpose 사용하여 차원을 재배열 합니다.
"""
axes[1].set_title('Noisy Images')
axes[1].axis('off')

plt.show()


import os
import cv2
import random
import argparse
import numpy as np
import pandas as pd
import tensorflow as tf
from keras.models import load_model

IMAGESIZE = 80
DATADIR = './datasets/test'
MODELDIR = './models'
# Path to 'Train' folder containing folders of pics for each letter (A, B, C, D, etc.)
CATEGORIES = [
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
    'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
    'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    'NOTHING', 'SPACE', 'DEL'
]

parser = argparse.ArgumentParser()
parser.add_argument('-d', '--data', help='path to testing dataset', action='store', default=DATADIR)
parser.add_argument('-m', '--model', help='path to model directory', action='store', default=MODELDIR)
parser.add_argument('-s', '--size', help='specify training image size', type=int, default=IMAGESIZE)
parser.add_argument('-p', '--predict', help='output redictions', action='store_true')
args = parser.parse_args()

class InvalidPathError(Exception):
    """Raised when path to training dataset is invalid"""
    pass

def get_data(test_dir):
    if os.path.isfile(test_dir):
        data_path = test_dir
    elif os.path.isdir(test_dir):
        # get last modified file in directory
        data_path = max([os.path.join(test_dir, file) for file in os.listdir(test_dir)], key=os.path.getctime)
        if not os.path.isfile(data_path):
            raise InvalidPathError
    else:
        raise InvalidPathError

    print(f"Reading {data_path} (May take a while)...")
    data = pd.read_csv(data_path, delimiter=',').values[1:]
    X_test = [[i[1:]] for i in data]
    y_test = [i[:1] for i in data]

    print("Shaping and shuffling data...")
    data = list(zip(X_test, y_test))
    random.shuffle(data)

    X_test, y_test = zip(*data)
    X_test = np.asarray(X_test).reshape(-1, args.size, args.size, 1)
    y_test = np.asarray(y_test).reshape(-1)

    return X_test, y_test

def get_model(model_dir):
    if os.path.isfile(model_dir):
        model_path = model_dir
    elif os.path.isdir(model_dir):
        model_path = max([os.path.join(model_dir, file) for file in os.listdir(model_dir)], key=os.path.getctime)
        if not os.path.isfile(model_path):
            raise InvalidPathError
    else:
        raise InvalidPathError

    return tf.keras.models.load_model(model_path)

X_test, y_test = get_data(args.data)
model = get_model(args.model)

if args.predict:
    predictions = model.predict([X_test])
    for i in range(len(X_test)):
        correct = int(y_test[i]) == np.argmax(predictions[i])
        print(f"{'✓' if correct else 'X'} {i}\tValue: {CATEGORIES[int(y_test[i])]}\tPrediction: {CATEGORIES[np.argmax(predictions[i])]}")

val_loss, val_accuracy = model.evaluate(X_test, y_test)
print(f'val_loss: {val_loss}\tval_accuracy: {val_accuracy}')


from log import *
import searchcont as sarch
import delitcont as delit
import newcont as newс
import redactcont as redact

filename = 'myphonebook.txt'
myfile = open(filename, 'a+')
myfile.close

def main_menu():
    logger.debug('function call - main_menu')
    print('\nГлавное меню\n')
    print('1. Показать список контактов')
    print('2. Поиск существующего контакта')
    print('3. Добавить новый контакт')
    print('4. Изменить контакт')
    print('5. Удалить контакт')
    print('6. Выход')

    choice = input('Введите свой выбор: ')
    logger.info(f"user's choice: {choice}")
    if choice == '1':
        myfile = open(filename, 'r+')
        filecontents = myfile.read()
        if len(filecontents) == 0:
            print('!! В телефонной книге нет контакта !!')
            logger.info('no data detected')
        else:
            print(filecontents)
            logger.debug('list output')
        myfile.close
        enter = input('Нажмите Enter, чтобы продолжить ...')
        main_menu()
    elif choice == '2':
        sarch.searchcontact()
        enter = input('Нажмите Enter, чтобы продолжить ...')
        main_menu()
    elif choice == '3':
        newс.newcontact()
        enter = input('Нажмите Enter, чтобы продолжить ...')
        main_menu()
    elif choice == '4':
        redact.redactcontact()
        enter = input('Нажмите Enter, чтобы продолжить ...')
        main_menu()
    elif choice == '5':
        delit.delitcontact()
        enter = input('Нажмите Enter, чтобы продолжить ...')
        main_menu()
    elif choice == '6':
        print('Благодарим вас за использование телефонной книги!')
    else:
        print('!! Пожалуйста, предоставьте действительные входные данные !!\n')
        logger.warning('incorrect data entered')
        enter = input('Нажмите Enter, чтобы продолжить ...')
        main_menu()


import RPi.GPIO as GPIO
import time

class LEDCONTROLLER:
    def __init__(self,data_pin, latch_pin, clock_pin):
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        GPIO.setup(data_pin, GPIO.OUT)
        GPIO.setup(latch_pin, GPIO.OUT)
        GPIO.setup(clock_pin, GPIO.OUT)
        self.data = data_pin
        self.latch = latch_pin
        self.clock = clock_pin

    def led_array(self, dist):
        ones = 0
        for i in range(dist):           #This starts at 0
            ones = ones + (pow(10, i))
        zeros = pow(10, (16 - dist))
        end_value = ones * zeros
        ledpattern = str(end_value)
        reverse_pattern = ledpattern[::-1]
        print(reverse_pattern)  # led Status zur Überprüfung
        GPIO.output(self.latch, 0)
        for x in range(16):
            GPIO.output(self.data, int(reverse_pattern[x]))
            # print(int(ledpattern[x]))
            GPIO.output(self.clock, 1)
            GPIO.output(self.clock, 0)
        GPIO.output(self.latch, 1)

#------------------------------------
# Beispiel: Angenommen die Distanze (dist) würde 4 Einheiten betragen:
'''
dist= 4
led_controller = LEDCONTROLLER(PIN_DATA, PIN_LATCH, PIN_CLOCK)
led_controller.led_array(dist)
'''
# this is a test edit


# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

import itertools
import nltk.corpus
import nltk
from nltk import trigrams
from nltk.text import Text
import random
import os

def ngrams_wrapper(sent):
    return list(nltk.ngrams(sent, 2, pad_right=True, pad_left=True, left_pad_symbol="$$", right_pad_symbol="$$"))

def ngrams_wrapper_3(sent):
    return list(nltk.ngrams(sent, 3,pad_right=True, pad_left= True, left_pad_symbol="$$", right_pad_symbol="$$"))

# first three letters are: ï»¿
# f = open("books/planet_named_joe.txt", "r")
# book = f.readline()
# book = book[3:-1]
book = ""

list_of_books = os.listdir("books/")

avoid_Gutenberg_Notes = True
license_start = "*** END OF "

cut_start_or = True
authors_credits_end = "*** START OF"

print(len(book))

"""
cut_start_or => if true then it will read the book after he finds the words '*** START OF'
each book in Gutenberg has first authors info etc.

avoid_Gutenberg_Notes => in end of the book there is the info about license etc.

"""
for i in list_of_books:
    read_path = "books/" + i
    print("Opening:  ", read_path)
    f = open(read_path, "r")
    cut_start = cut_start_or

    for j in f:
        if license_start in j and avoid_Gutenberg_Notes:
            break
        if cut_start:
            if authors_credits_end in j:
                cut_start = False
                print("    >>> parsing ", end="")
                continue
            else:
                continue

        j = j.replace("--", "")
        j = j.replace("_", "")
        book = book + j
    print(len(book))
    print()

print(len(book))
print()

#region unigramms

words = nltk.word_tokenize(book)
unigram = nltk.ngrams(words, 1)

freq_dist_un = nltk.FreqDist(unigram)
prob_dist_un = nltk.MLEProbDist(freq_dist_un)
# number_of_unigrams = prob_dist_un.N()

if False:
    for i in freq_dist_un:
        print(i," ", freq_dist_un[i], " ", prob_dist_un.prob(i))

#endregion

#region bigramms

sentences = nltk.sent_tokenize(book)
tokenized = map(nltk.tokenize.word_tokenize, sentences)

bigrams = map(ngrams_wrapper, tokenized)
bigram = list(itertools.chain.from_iterable(bigrams))

freq_dist_bi = nltk.FreqDist(bigram)

prob_dist_bi = nltk.MLEProbDist(freq_dist_bi)
number_of_bigrams = freq_dist_bi.N()

if False:
    for i in freq_dist:
        print(i," ", freq_dist_bi[i], " ", prob_dist_bi.prob(i))

#endregion

#region trigramms

sentences = nltk.sent_tokenize(book)
tokenized = map(nltk.tokenize.word_tokenize, sentences)

trigams = map(ngrams_wrapper_3, tokenized)
trigram = list(itertools.chain.from_iterable(trigams))

freq_dist_tri = nltk.FreqDist(trigram)
prob_dist_tri = nltk.MLEProbDist(freq_dist_tri)
number_of_trigramms = freq_dist_tri.N()

if False:
    for i in freq_dist_tri:
        print(i," ", freq_dist_tri[i], " ", prob_dist_tri.prob(i))

#endregion

# to check and find words propablities

# t = ["$$", "Our"]
#
# for i in trigram:
#     if i[0] == t[-2] and i[1] == t[-1]:
#         print(i," ", freq_dist_tri[i], " ", prob_dist_tri.prob(i))
#

"""
checks so first letter of bigramm is upper case and if exist the second is lower case.
    -> Avoiding sentences with all capitals

also remove sentences with "." in them

choose one at random and it is the initialization of the sentence
"""
def initial_sentence_2(bi):
    my_sentence = ""

    initial_bi = []
    for i in bi:
        if i[0] == "$$":
            initial_bi.append(i)

    x = random.randrange(len(initial_bi))
    my_sentence += initial_bi[x][0]
    my_sentence += " "
    my_sentence += initial_bi[x][1]
    return my_sentence

"""
generated_method [0,1]

0: sentences will be first generated through trigrams and if there is no matching trigram will bigram used

1: sentences will be generated through both trigram and bigram with the 'list_of_candidates' =>
in list there are all candidates of how the sentence can proceed. In the list are inserted  nltk.FreqDist[ngram] times each
possible candidate.

'bi_tri_balance' is how many times to input each trigram in the list. If 'bi_tri_balance = 1' then each trigram is inserted 1 time and has the same
weight as a bigram 'bi_tri_balance = 2' each trigram has double the weight and so on

"""
def find_possible_subSentences(sen, bi, tri,generate_method = 0, bi_tri_balance = 2):
    bi_sub_gen = []
    tri_sub_gen = []
    splited_sen = sen.split(" ")

    list_of_candidates = []

    for i in bi:
        if i[0] == splited_sen[-1]:
            bi_sub_gen.append(i)
            list_of_candidates.append(i[-1])

    for i in tri:
        if i[0] == splited_sen[-2] and i[1] == splited_sen[-1]:
            tri_sub_gen.append(i)
            for j in range(bi_tri_balance):
                list_of_candidates.append(i[-1])

    if False:
        for i in sorted(bi_sub_gen):
            print(i)
        print("==================\n\n")
        for i in tri_sub_gen:
            print(i)

    if generate_method == 0:
        if len(tri_sub_gen) <= 0:
            if len(list_of_candidates) > 0:
                x = random.randrange(len(list_of_candidates))
                to_add = list_of_candidates[x]
            else:
                to_add = "..."
        else:
            x = random.randrange(len(tri_sub_gen))
            to_add = tri_sub_gen[x][2]
    elif generate_method == 1:
        if len(list_of_candidates) > 0:
            x = random.randrange(len(list_of_candidates))
            to_add = list_of_candidates[x]
        else:
            to_add = "..."

    to_add = " " + str(to_add)
    return to_add

def generate_a_sentence_2(bi, tri, max_sentence_length = 120, ge_meth = 0, bi_tri_bal = 2):
    gen_sen = initial_sentence_2(bi)
    # print(gen_sen)
    # print("\n")

    while gen_sen.split()[-1] != "$$" and len(gen_sen) < max_sentence_length:
        gen_sen = gen_sen + find_possible_subSentences(gen_sen, bi, tri, ge_meth, bi_tri_bal)

        if len(gen_sen) >= max_sentence_length and gen_sen[-1] != "$$":
            gen_sen = gen_sen + "[.....]"
    # print(gen_sen)
    return gen_sen

for i in range(10):
    print(i, end=": ")
    my_sen = generate_a_sentence_2(bigram, trigram, 140, 1, 1)
    my_sen = my_sen.replace("$$", "")
    print(my_sen)
    print()


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

hadoop_path = '/usr/local/hadoop/bin/hadoop'
local_input = '/usr/zyy/zyy1/news_pages'
input_dir = '/'
output_dir = '/output'
subprocess.call(['python3', 'crawl.py'])
subprocess.call([hadoop_path, 'fs', '-rm','-r', output_dir])
subprocess.call(['rm','-r','/usr/zyy/zyy1/index-tf_idf.csv'])
subprocess.call([hadoop_path, 'fs', '-put', local_input, input_dir])

subprocess.call([hadoop_path, 'jar', '/usr/local/hadoop/share/hadoop/tools/lib/hadoop-streaming-2.7.1.jar',
                 '-input', '/news_pages', '-output', output_dir,
                 '-mapper', 'python3 /usr/zyy/zyy1/mapreduce/mapper.py', '-reducer', 'python3 /usr/zyy/zyy1/mapreduce/reducer.py',
                 '-file', '/usr/zyy/zyy1/mapreduce/mapper.py', '-file', '/usr/zyy/zyy1/mapreduce/reducer.py','-file', '/usr/zyy/zyy1/mapreduce/new_stopwords.txt'])
subprocess.call([hadoop_path, 'fs', '-get', '/output/part-00000','/usr/zyy/zyy1/index-tf_idf.csv'])

subprocess.call(['python3', 'pre.py'])


import altair as alt
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

from shared import app, data_raw

state_choice = data_raw.state.unique()
state_choice.sort()

company_size_choice = data_raw.no_employees.unique()
company_size_choice.sort()

tab_company_support_content = dbc.Card(
    dbc.CardBody([
        dbc.Row([
            dbc.Col(dbc.FormGroup([
                dbc.Label('State'),
                dcc.Dropdown(
                    id='company-support-state-dropdown',
                    value=[],
                    multi=True,
                    options=[{'label': col, 'value': col} for col in state_choice]),
                dbc.FormText('The state or territory where the respondents live in'),
                html.Br(),
                dbc.Label('Company Size'),
                dcc.Dropdown(
                    id='company-support-company-size-dropdown',
                    value=[],
                    multi=True,
                    options=[{'label': col, 'value': col} for col in company_size_choice]),
                dbc.FormText('Size of the companies the respondents working for: "Small" (0 - 100 employees), "Medium" (100 - 1000 employees), and "Large" (more than 1000 employees)'),
                html.Br(),
                dbc.Label('Tech Company'),
                dbc.RadioItems(
                    id='company-support-tech-company-radioitems',
                    options=[
                        {'label': 'All', 'value': 'All'},
                        {'label': 'Yes', 'value': 'Yes'},
                        {'label': 'No', 'value': 'No'}
                    ],
                    inline=True,
                    value='All'
                ),
                dbc.FormText('Are the respondents\' companies primarily tech companies or organizations?'),
                html.Br(),
                dbc.Label('Remote Work'),
                dbc.RadioItems(
                    id='company-support-remote-work-radioitems',
                    options=[
                        {'label': 'All', 'value': 'All'},
                        {'label': 'Yes', 'value': 'Yes'},
                        {'label': 'No', 'value': 'No'}
                    ],
                    inline=True,
                    value='All'
                ),
                dbc.FormText('Are the respondents\' work remotely (outside of an office) at least 50% of the time?')
            ]), md=2, align='baseline'),
            dbc.Col(dcc.Loading(
                id='company-support-loading',
                type='default',
                children=dbc.Col([
                    html.Iframe(id='iframe-company-support',
                                style={'border-width': '0', 'width': '100%', 'height': '90vh'}),
                    dbc.Col([
                        html.Hr(),
                        dbc.Card([
                        dbc.CardHeader('Full description of question labels:'),
                        dbc.CardBody(
                            dbc.Table([
                                html.Thead(html.Tr([html.Th('Label'), html.Th('Full Description')])),
                                html.Tr([html.Td('Anonymity'), html.Td('Is your anonymity protected if you choose to take '
                                                                    'advantage of mental health or substance abuse '
                                                                    'treatment resources?')]),
                                html.Tr(
                                    [html.Td('Benefits'), html.Td('Does your employer provide mental health benefits?')]),
                                html.Tr([html.Td('Mental vs physical'), html.Td('Do you feel that your employer takes '
                                                                                'mental health as seriously as physical '
                                                                                'health?')]),
                                html.Tr([html.Td('Resources'), html.Td(
                                    'Does your employer provide resources to learn more about mental health issues and how '
                                    'to seek help?')]),
                                html.Tr([html.Td('Wellness program'), html.Td(
                                    'Has your employer ever discussed mental health as part of an employee wellness '
                                    'program?')]),
                                html.Tr([html.Td('Coworkers'), html.Td('Would you be willing to discuss a mental health '
                                                                    'issue with your coworkers?')]),
                                html.Tr([html.Td('Supervisors'), html.Td('Would you be willing to discuss a mental health '
                                                                        'issue with your direct supervisor(s)?')])
                            ], bordered=False, dark=False, responsive=True, striped=True, size='sm'),
                            style={'width':'100%'}
                        )])],
                        md=12, align='center'),
                ], md=12, align='center')
            ), align='center')
        ])
    ]),
    className='mt-3')

# Set up callbacks/backend
@app.callback(
    Output('iframe-company-support', 'srcDoc'),
    Input('company-support-state-dropdown', 'value'),
    Input('company-support-company-size-dropdown', 'value'),
    Input('company-support-tech-company-radioitems', 'value'),
    Input('company-support-remote-work-radioitems', 'value'))
def plot_general_overview(state, company_size, is_tech, is_remote_work):
    """
    Callback function to be responsible for refreshing the dashboard. This function will read in the latest parameters,
    apply appropriate filters and generate plots

    :param state: States in the US that should be included in the result
    :param company_size: Company size that should be included in the result
    :param is_tech: Are the companies traditional tech companies?
    :param is_remote_work: Are the companies allow remote work?
    :return: The rendered html of the dashboard
    """
    data = data_raw

    if len(state) != 0:
        data = data.query('state == @state')

    if len(company_size) != 0:
        data = data.query('no_employees == @company_size')

    if is_tech.lower() != 'all':
        data = data.query('tech_company == @is_tech')

    if is_remote_work.lower() != 'all':
        data = data.query('remote_work == @is_remote_work')

    # melt dataframe for questions plot
    df_melted = data[['benefits', 'wellness_program', 'seek_help', 'anonymity', 'mental_vs_physical']] \
        .melt(var_name='Question',
              value_name='Answer')

    # replace question names
    df_melted = df_melted.replace({'benefits': 'Benefits', 'anonymity': 'Anonymity',
                                   'seek_help': 'Resources', 'wellness_program': 'Wellness program',
                                   'mental_vs_physical': 'Mental vs physical'})

    # question plot
    plot_question = alt.Chart(df_melted, title='Survey Questions (refer to detailed questions below)').mark_bar().encode(
        x=alt.X('count()', stack='normalize', axis=alt.Axis(format='%')),
        y=alt.Y('Question'),
        color=alt.Color('Answer', scale=alt.Scale(scheme='blues')),
        tooltip=[alt.Tooltip('count()', title='Respondent count')]
    ).properties(height=250, width=425,
                title={
                "text": ["Survey Questions"],
                "subtitle": ["(refer to detailed questions below)"],
                "color": "Black",
                "subtitleColor": "Grey"}
                )

    # boxplot
    plot_box = alt.Chart(data).mark_boxplot(size=50).encode(
        alt.X('mental_health_consequence', title=' '),
        alt.Y('Age'),
        alt.Color('Gender', scale=alt.Scale(scheme='tableau10'), legend=None)
    ).properties(
        height=300,
        width=305
    ).facet(facet='Gender',
            title='Do employees feel that there might be consequences discussing mental health conditions?')

    # heatmap plot
    plot_heat = alt.Chart(data, title=['Discussing with', 'Coworkers & Supervisors']).mark_rect().encode(
        x=alt.X('supervisor', title='Supervisors'),
        y=alt.Y('coworkers', sort='-y', title='Coworkers'),
        color=alt.Color('count()', legend=alt.Legend(title='Count'), scale=alt.Scale(scheme='greenblue')),
        tooltip=[alt.Tooltip('count()', title='Respondent count')]
    ).properties(height=250, width=220)

    return (plot_box & (plot_question|plot_heat)) \
        .resolve_scale(color ='independent') \
        .configure_axisX(labelAngle=360) \
        .configure_legend(titleFontSize=15,labelFontSize=13, gradientLength=100, gradientThickness=20)\
        .configure_title(fontSize=18, anchor='middle') \
        .configure_axis(labelFontSize=13,titleFontSize=13) \
        .to_html()


#WAP to print return the given argument
def func(arg_1):
    res=arg_1
    return res
    # Write your code here

n = int(input())
result = func(n)
print(result)
#WAP to print welcome message
def say_wishes(arg_1):
    msg="Welcome "+arg_1
    print(msg)
    return msg
    # Write your code here

name = input()
say_wishes(name)
#WAP to print multiply with 3
def multiply_with_three(arg_1):
    mul=arg_1*3
    print(mul)
    return mul
    # Write your code here

n = int(input())
multiply_with_three(n)
#WAP to print divisible by 7
def divisible_by_seven(arg_1):
    msg=arg_1
    if msg%7==0:
        print("True")
    else:
        print("False")
    # Write your code here

n = int(input())
divisible_by_seven(n)
#WAP to print perimeter of square
def perimeter_of_square(arg_1):
    per=arg_1*4
    return per
    # Write your code here

side = int(input())
result = perimeter_of_square(side)
print(result)
#WAP to print add two numbers
def add(arg_1, arg_2):
    addition=arg_1+arg_2
    print(addition)
    return addition
    # Complete this function

a = int(input())
b = int(input())
# Call the add function
add_1=add(a,b)
#WAP to print second character in a word
def second_character(arg_1):
    msg=arg_1
    sec_char=msg[1]
    print(sec_char)
    return sec_char
    # Complete this function

word = input()
# Call the second_character function
char=second_character(word)
#WAP to print indexing 2
def indexing(arg_1, arg_2):
    msg=arg_1
    indx=msg[index]
    print(indx)
    return indx
    # Complete this function

word = input()
index = int(input())
# Call the indexing function
calli=indexing(arg_1=word,arg_2=index)
#WAP to print printing message
def message(arg_1, arg_2):
    msg=arg_1+" is "+str(arg_2)+" years old."
    print(msg)
    return msg
    # Complete this function

name = input()
age = int(input())
# Call the message function
greet=message(arg_1=name,arg_2=age)
#WAP to print no of lower case and upper case letters
def count_of_lowercase_and_uppercase_letters(arg_1):
    count_of_uppercase=0
    count_of_lowercase=0
    for i in arg_1:

        if i==i.upper():
            count_of_uppercase=count_of_uppercase+1
        elif i==i.lower():
            count_of_lowercase=count_of_lowercase+1

    # Complete this function

    print(count_of_uppercase)
    print(count_of_lowercase)

word = input()
# Call the count_of_lowercase_and_uppercase_letters function
calli=count_of_lowercase_and_uppercase_letters(word)
#WAP to print squares in a list
def get_list(string_a):
    list_a = string_a.split(',')
    len_list_a = len(list_a)
    for i in range(len_list_a):
        list_a[i] = int(list_a[i])**2
    return list_a

string_a = input()
numbers_list = get_list(string_a)
print(numbers_list)
#WAP to print team points
def calculate_league_points(wins, draws, losses):
    wi_nn=wins*4
    dra_w=draws*2
    los_s=losses*(-1)
    tot_point=wi_nn+dra_w+los_s
    print(tot_point)
    return tot_point
    # Complete this function

statistics = input().split(",")
wins = int(statistics[0])
draws = int(statistics[1])
losses = int(statistics[2])
# Call the calculate_league_points function
calli=calculate_league_points(wins,draws,losses)
#WAP to print speed meter
def get_speed_status(speed):
    spe_d=speed
    if spe_d<60:
        print("Normal")
    elif (spe_d>=60) and (spe_d<80):
        print("Warning")
    elif spe_d>=80:
        print("Over Speed")
    # Complete this function

speed = int(input())
# Call the get_speed_status function
calli=get_speed_status(speed)
#WAP to print weather reporter
def get_weather_report(temperature):
    tem_p=temperature
    if tem_p<22:
        print("Cold")
    elif (tem_p>=22) and (tem_p<35):
        print("Warm")
    elif tem_p>=35:
        print("Hot")
    # Complete this function

temperature = int(input())
# Call the get_weather_report function
calli=get_weather_report(temperature)
#WAP to print discount
def get_discount(amount):
    dis_c=amount
    if dis_c<500:
        print("5%")
    elif (dis_c>=500) and (dis_c<2500):
        print("10%")
    elif dis_c>=2500:
        print("20%")
    # Complete this function

amount = int(input())
# Call the get_discount function
calli=get_discount(amount)
#WAP to print calculate bill
def calculate_bill(amount):
    bill=amount
    if bill<500:
        disc_ount=bill*(0.05)
        total=(bill)-(disc_ount)
        print(round(total,3))
    elif (bill>=500) and (bill<2500):
        disc_ount=bill*(0.1)
        total=(bill)-(disc_ount)
        print(round(total,3))
    elif bill>=2500:
        disc_ount=bill*(0.2)
        total=(bill)-(disc_ount)
        print(round(total,3))
        # Complete this function

amount = int(input())
# Call the calculate_bill function
calli=calculate_bill(amount)
#WAP to print fizz buzz
def fizz_buzz(number):
    buzz=number
    if (buzz%3==0) and (buzz%5==0):
        print("FizzBuzz")
    elif (buzz%3==0):
        print("Fizz")
    elif (buzz%5==0):
        print("Buzz")
    else:
        print(buzz)
    # Complete this function

number = int(input())
calli=fizz_buzz(number)
# Call the fizz_buzz function
#WAP to print squares from m to n
def sum_of_squares_m_to_n(m, n):
    arg_1=m
    arg_2=n
    add=0
    for i in range(arg_1,(arg_2+1)):
        add=add+(i)**2
    print(add)
    # Complete this function

m = int(input())
n = int(input())
# Call the sum_of_squares_m_to_n function
calli=sum_of_squares_m_to_n(m,n)
#WAP to print sum of cubes from m to n
def sum_of_cubes_m_to_n(m, n):
    arg_1=m
    arg_2=n
    add=0
    for i in range(arg_1,(arg_2+1)):
        add=add+(i)**3
    print(add)
    # Complete this function

m = int(input())
n = int(input())
calli=sum_of_cubes_m_to_n(m,n)
# Call the sum_of_cubes_m_to_n function
#WAP to print labelling numbers
def show_numbers(number):
    arg_1=number
    for i in range(arg_1+1):
        if i%2==0:
            print(str(i)+" EVEN")
        else:
            print(str(i)+" ODD")
    # Complete this Function

number = int(input())
# Call the show_numbers function
calli=show_numbers(number)
#WAP to print upper case and lower case letters
def get_lower_and_upper_case_letters(word):
    arg_1=word
    upp=""
    low=""
    for i in arg_1:
        if i==i.upper():
            upp=upp+i
        elif i==i.lower():
            low=low+i
    print(upp)
    print(low)
    # Complete this function

word = input()
# Call the get_lower_and_upper_case_letters function
calli=get_lower_and_upper_case_letters(word)
#WAP to print count vowels
def count_the_vowels(word):
    arg_1=word
    vowels="aeiou"
    count=0
    for i in arg_1:
        for j in vowels:
            if i==j:
                count=count+1
    print(count)
    # Complete this function

word = input()
# Call the count_the_vowels function
calli=count_the_vowels(word)
#WAP to print four passengers and driver
def number_of_cars_needed(no_of_people):
    arg_1=no_of_people
    count=0
    arg_2=arg_1%5
    j=(arg_2==1) or (arg_2==2)
    k=(arg_2==3) or (arg_2==4)
    for i in range(1,(arg_1+1)):
        if i%5==0:
            count=count+1
    if j or k:
        count=count+1
    print(count)
    # Complete this function

no_of_people = int(input())
# Call the number_of_cars_needed function
calli=number_of_cars_needed(no_of_people)
#WAP to print ATM pin code validation
def validate_atm_pin_code(pin):
    arg_1=pin
    arg_2=arg_1.isdigit()
    if arg_2==True:
        if (len(arg_1)==4) or (len(arg_1)==6):
            print("Valid PIN Code")
        else:
            print("Invalid PIN Code")
    else:
        print("Invalid PIN Code")

    # Complete this function

pin = input()
# Call the validate_atm_pin_code function
calli=validate_atm_pin_code(pin)


import os
import json
import pytest
import gzip
import numpy as np
from panqec.error_models import PauliErrorModel
from panqec.codes import Toric2DCode
from panqec.decoders import BeliefPropagationOSDDecoder
from panqec.simulation import (
    read_input_json, run_once, DirectSimulation, expand_input_ranges, run_file,
    BatchSimulation
)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR, 'data')

@pytest.fixture
def required_fields():
    return [
        'effective_error', 'success'
    ]

@pytest.mark.parametrize(
    'file_name, expected_runs',
    [
        ('single_input.json', 1),
        ('range_input.json', 27),
        ('single_input.json.gz', 1),
        ('range_input.json.gz', 27),
    ]
)
def test_read_json_input(file_name, expected_runs):
    input_json = os.path.join(DATA_DIR, file_name)
    output_json = os.path.join(DATA_DIR, 'results.json')
    batch_simulation = read_input_json(input_json, output_json)
    assert batch_simulation is not None
    assert len(batch_simulation._simulations) == expected_runs
    parameters = [
        {
            'code': list(s.code.size),
            'error_model': s.error_model.direction,
            'error_rate': s.error_rate
        }
        for s in batch_simulation._simulations
    ]
    for i in range(len(parameters)):
        for j in range(len(parameters)):
            if i != j:
                assert parameters[i] != parameters[j]

class TestRunOnce:
    @pytest.fixture
    def code(self):
        return Toric2DCode(3, 3)

    @pytest.fixture
    def error_model(self):
        return PauliErrorModel(1/3, 1/3, 1/3)

    def test_run_once(self, required_fields, code, error_model):
        error_rate = 0.5
        decoder = BeliefPropagationOSDDecoder(code, error_model, error_rate)
        results = run_once(
            code, error_model, decoder, error_rate=error_rate
        )
        assert set(required_fields).issubset(results.keys())
        assert results['error'].shape == (2*code.n,)
        assert results['syndrome'].shape == (code.stabilizer_matrix.shape[0],)
        assert isinstance(results['success'], bool)
        assert results['effective_error'].shape == (
            2*code.logicals_x.shape[0],
        )
        assert isinstance(results['codespace'], bool)

    def test_run_once_invalid_probability(self, code, error_model):
        error_rate = -1
        decoder = BeliefPropagationOSDDecoder(
            code, error_model, error_rate=error_rate
        )
        with pytest.raises(ValueError):
            run_once(code, error_model, decoder, error_rate=error_rate)

class TestSimulationToric2DCode():

    error_rate = 0.5

    @pytest.fixture
    def code(self):
        return Toric2DCode(3, 3)

    @pytest.fixture
    def decoder(self, code, error_model):
        return BeliefPropagationOSDDecoder(code, error_model, self.error_rate)

    @pytest.fixture
    def error_model(self):
        direction = np.ones(3)/3
        return PauliErrorModel(*direction)

    def test_run(self, code, error_model, decoder, required_fields):
        error_rate = 0.5
        simulation = DirectSimulation(code, error_model, decoder, error_rate)
        simulation.run(10)
        assert len(simulation._results['success']) == 10
        assert set(required_fields).issubset(simulation._results.keys())

class TestBatchSimulationOneFile():

    n_trials: int = 5

    @pytest.fixture
    def output_file(self, tmpdir):
        out_file = os.path.join(tmpdir, 'results.json.gz')

        batch_sim = BatchSimulation(
            label='mylabel',
            save_frequency=1,
            output_file=out_file,
        )

        for size, error_rate in [(3, 0.1), (4, 0.5)]:
            code = Toric2DCode(size, size)
            error_model = PauliErrorModel(1/3, 1/3, 1/3)
            decoder = BeliefPropagationOSDDecoder(
                code, error_model, error_rate
            )
            simulation = DirectSimulation(
                code, error_model, decoder, error_rate
            )
            batch_sim.append(simulation)

        assert len(batch_sim) == 2

        batch_sim.run(self.n_trials)
        batch_sim.save_results()

        return out_file

    def test_output_to_one_file(self, output_file):
        assert os.path.isfile(output_file)

        with gzip.open(output_file, 'rb') as gz:
            results = json.loads(gz.read().decode('utf-8'))

        # Check integrity of results.
        assert len(results) == 2
        expected_input_keys = [
            'code', 'error_model', 'decoder',
            'error_rate', 'method'
        ]
        expected_results_keys = [
            'effective_error', 'success', 'codespace', 'wall_time',
        ]
        for key in expected_input_keys:
            assert key in results[0]['inputs']
            assert key in results[1]['inputs']

        for key in expected_results_keys:
            assert key in results[0]['results']
            assert key in results[1]['results']

        # Numerical tests on the results.
        assert len(results[0]['results']['effective_error']) == self.n_trials
        assert len(results[0]['results']['success']) == self.n_trials
        assert len(results[0]['results']['codespace']) == self.n_trials

@pytest.fixture
def example_ranges():
    input_json = os.path.join(DATA_DIR, 'range_input.json')
    with open(input_json) as f:
        data = json.load(f)
    return data['ranges']

def test_expand_inputs_ranges(example_ranges):
    ranges = example_ranges
    expanded_inputs = expand_input_ranges(ranges)
    assert len(expanded_inputs) == 27

def test_run_file_range_input(tmpdir):
    input_json = os.path.join(DATA_DIR, 'range_input.json')
    output_json = os.path.join(tmpdir, 'results', 'results.json')
    n_trials = 2
    run_file(input_json, output_json, n_trials)

    assert os.path.isfile(output_json)

class TestReadInputJson:

    def test_multiple_ranges(self):
        input_json = os.path.join(DATA_DIR, 'toric_input.json')
        output_json = os.path.join(DATA_DIR, 'toric_output.json')

        batch_sim = read_input_json(input_json, output_json)
        assert len(batch_sim) == 126


from awesomeengine.behavior import verify_attrs
from awesomeengine.behavior import Behavior
from awesomeengine import engine

class ChangeMode(Behavior):

    def __init__(self):
        self.required_attrs = []
        self.event_handlers = {'input': self.handle_input}

    def handle_input(self, entity, action, value):
        if action == 'welcome' and value == 1:
            engine.get().change_mode('welcome')
        elif action == 'main' and value == 1:
            engine.get().change_mode('main')
        elif action == 'button' and value == 1:
            engine.get().change_mode('button')


import requests
import dateutil.parser
import time

from bs4 import BeautifulSoup
from datetime import datetime
from urllib.request import urlopen, Request
from urllib.parse import urlparse

####################################
######## NEWS SCRAPER UTILS ########
####################################

MONTH_DICT = {'Januari': 'January',
            'Februari': 'February',
            'Maret': 'March',
            'April': 'April',
            'Mei': 'May',
            'Juni': 'June',
            'Juli': 'July',
            'Agustus': 'August',
            'September': 'September',
            'Oktober': 'October',
            'November': 'November',
            'Desember': 'December'
            }

MONTH_ACR_DICT = {'Jan': 'Jan',
                'Feb': 'Feb',
                'Mar': 'Mar',
                'Apr': 'Apr',
                'Mei': 'May',
                'Jun': 'Jun',
                'Jul': 'Jul',
                'Agu': 'Aug',
                'Sep': 'Sep',
                'Okt': 'Oct',
                'Nov': 'Nov',
                'Des': 'Dec'
                }

USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5)\
     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"

MAX_RETRIES = 20

def retrieve_date_year(url, html_tag, attribute, attribute_value):
    """
        Retrieve year from dates of content
    """

    assert isinstance(url, str), f"Argument required str, but a {type(url)} was given."

    headers = {
        'User-Agent': USER_AGENT
    }

    session = requests.Session()
    adapter = requests.adapters.HTTPAdapter(max_retries=MAX_RETRIES)

    session.mount('https://', adapter)
    session.mount('http://', adapter)

    # Get content from source
    content_request = session.get(url, headers=headers)

    soup = BeautifulSoup(content_request.content)

    date_text = soup.find(
        html_tag,
        {attribute: attribute_value}
    ).text

    # Parsed date if month is not acronym
    for month in MONTH_DICT.keys():
        if month in date_text:
            date_text = date_text.replace(month, MONTH_DICT[month])
        else:
            pass
    # Parsed date if month is an acronym
    for month in MONTH_ACR_DICT.keys():

        if month in date_text:
            date_text = date_text.replace(month, MONTH_ACR_DICT[month])
        else:
            pass

    date_year = dateutil.parser.parse(date_text, fuzzy=True).year

    return date_year

####################################
######## PDF SCRAPER UTILS ########
####################################

def datetime_to_str(date):
    if isinstance(date, datetime):
        return date.strftime("%m-%d")
    else:
        return date

def get_range(range_str):
    """
        Get page range from the 'Page' column
    """
    if isinstance(range_str, datetime):
        range_str = datetime_to_str(range_str)
    if "-" in range_str:
        nums = range_str.split("-")
        return (int(nums[0]), int(nums[1]))
    else:
        nums = range_str.split("to")
        return (int(nums[0]), int(nums[1]))

####################################
###### YOUTUBE SCRAPER UTILS ######
####################################

def youtube_links(links):
    links = links.split(",")

    if len(links) == 1:
        return ""
    else:
        return links[1]


import string
import sys

res = 0

for line in sys.stdin.read().rstrip().split("\n"):
    half = len(line) // 2
    h1, h2 = set(line[:half]), set(line[half:])
    (ch,) = h1.intersection(h2)
    res += (string.ascii_lowercase + string.ascii_uppercase).index(ch) + 1

print(res)


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

import random
import time

VERSION = '3.1'

def get_jst_time(t = None):
	if t == None:
		t = int(time.time())
	return time.localtime(t + (9 * 3600))

def get_random_query_string():
	random.seed(int(time.time()))
	random_query_string = "q=" + str(random.random())
	return "?q=" + str(random.random())

def parse_time(t):
	return t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, t.tm_wday

def qsort(sites):
        if len(sites) <= 1:
                return sites
        pivot = sites.pop(0)
        greater_eq = qsort([i for i in sites if i.time >= pivot.time])
        lesser = qsort([i for i in sites if i.time < pivot.time])
        return greater_eq + [pivot] + lesser

def output_html_header(out):
        out.write('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n')
        out.write('\n')
        out.write('\n')
        out.write('\n')
        out.write('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\n')
        out.write('<title>更新リスト ' + VERSION + '</title>\n')
        out.write('\n')
        out.write('\n')

def output_html_footer(out):
        out.write('\n')